hash
stringlengths
64
64
content
stringlengths
0
1.51M
f9206dd4b04ddac948b089af4dec1e78e6efc777488ac23a2ad0f3ae95fd2efa
"""Tests for Gosper's algorithm for hypergeometric summation. """ from sympy.core.numbers import (Rational, pi) from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.functions.combinatorial.factorials import (binomial, factorial) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.special.gamma_functions import gamma from sympy.polys.polytools import Poly from sympy.simplify.simplify import simplify from sympy.abc import a, b, j, k, m, n, r, x from sympy.concrete.gosper import gosper_normal, gosper_sum, gosper_term def test_gosper_normal(): eq = 4*n + 5, 2*(4*n + 1)*(2*n + 3), n assert gosper_normal(*eq) == \ (Poly(Rational(1, 4), n), Poly(n + Rational(3, 2)), Poly(n + Rational(1, 4))) assert gosper_normal(*eq, polys=False) == \ (Rational(1, 4), n + Rational(3, 2), n + Rational(1, 4)) def test_gosper_term(): assert gosper_term((4*k + 1)*factorial( k)/factorial(2*k + 1), k) == (-k - S.Half)/(k + Rational(1, 4)) def test_gosper_sum(): assert gosper_sum(1, (k, 0, n)) == 1 + n assert gosper_sum(k, (k, 0, n)) == n*(1 + n)/2 assert gosper_sum(k**2, (k, 0, n)) == n*(1 + n)*(1 + 2*n)/6 assert gosper_sum(k**3, (k, 0, n)) == n**2*(1 + n)**2/4 assert gosper_sum(2**k, (k, 0, n)) == 2*2**n - 1 assert gosper_sum(factorial(k), (k, 0, n)) is None assert gosper_sum(binomial(n, k), (k, 0, n)) is None assert gosper_sum(factorial(k)/k**2, (k, 0, n)) is None assert gosper_sum((k - 3)*factorial(k), (k, 0, n)) is None assert gosper_sum(k*factorial(k), k) == factorial(k) assert gosper_sum( k*factorial(k), (k, 0, n)) == n*factorial(n) + factorial(n) - 1 assert gosper_sum((-1)**k*binomial(n, k), (k, 0, n)) == 0 assert gosper_sum(( -1)**k*binomial(n, k), (k, 0, m)) == -(-1)**m*(m - n)*binomial(n, m)/n assert gosper_sum((4*k + 1)*factorial(k)/factorial(2*k + 1), (k, 0, n)) == \ (2*factorial(2*n + 1) - factorial(n))/factorial(2*n + 1) # issue 6033: assert gosper_sum( n*(n + a + b)*a**n*b**n/(factorial(n + a)*factorial(n + b)), \ (n, 0, m)).simplify() == -(a*b)**m*gamma(a + 1) \ *gamma(b + 1)/(gamma(a)*gamma(b)*gamma(a + m + 1)*gamma(b + m + 1)) \ + 1/(gamma(a)*gamma(b)) def test_gosper_sum_indefinite(): assert gosper_sum(k, k) == k*(k - 1)/2 assert gosper_sum(k**2, k) == k*(k - 1)*(2*k - 1)/6 assert gosper_sum(1/(k*(k + 1)), k) == -1/k assert gosper_sum(-(27*k**4 + 158*k**3 + 430*k**2 + 678*k + 445)*gamma(2*k + 4)/(3*(3*k + 7)*gamma(3*k + 6)), k) == \ (3*k + 5)*(k**2 + 2*k + 5)*gamma(2*k + 4)/gamma(3*k + 6) def test_gosper_sum_parametric(): assert gosper_sum(binomial(S.Half, m - j + 1)*binomial(S.Half, m + j), (j, 1, n)) == \ n*(1 + m - n)*(-1 + 2*m + 2*n)*binomial(S.Half, 1 + m - n)* \ binomial(S.Half, m + n)/(m*(1 + 2*m)) def test_gosper_sum_algebraic(): assert gosper_sum( n**2 + sqrt(2), (n, 0, m)) == (m + 1)*(2*m**2 + m + 6*sqrt(2))/6 def test_gosper_sum_iterated(): f1 = binomial(2*k, k)/4**k f2 = (1 + 2*n)*binomial(2*n, n)/4**n f3 = (1 + 2*n)*(3 + 2*n)*binomial(2*n, n)/(3*4**n) f4 = (1 + 2*n)*(3 + 2*n)*(5 + 2*n)*binomial(2*n, n)/(15*4**n) f5 = (1 + 2*n)*(3 + 2*n)*(5 + 2*n)*(7 + 2*n)*binomial(2*n, n)/(105*4**n) assert gosper_sum(f1, (k, 0, n)) == f2 assert gosper_sum(f2, (n, 0, n)) == f3 assert gosper_sum(f3, (n, 0, n)) == f4 assert gosper_sum(f4, (n, 0, n)) == f5 # the AeqB tests test expressions given in # www.math.upenn.edu/~wilf/AeqB.pdf def test_gosper_sum_AeqB_part1(): f1a = n**4 f1b = n**3*2**n f1c = 1/(n**2 + sqrt(5)*n - 1) f1d = n**4*4**n/binomial(2*n, n) f1e = factorial(3*n)/(factorial(n)*factorial(n + 1)*factorial(n + 2)*27**n) f1f = binomial(2*n, n)**2/((n + 1)*4**(2*n)) f1g = (4*n - 1)*binomial(2*n, n)**2/((2*n - 1)**2*4**(2*n)) f1h = n*factorial(n - S.Half)**2/factorial(n + 1)**2 g1a = m*(m + 1)*(2*m + 1)*(3*m**2 + 3*m - 1)/30 g1b = 26 + 2**(m + 1)*(m**3 - 3*m**2 + 9*m - 13) g1c = (m + 1)*(m*(m**2 - 7*m + 3)*sqrt(5) - ( 3*m**3 - 7*m**2 + 19*m - 6))/(2*m**3*sqrt(5) + m**4 + 5*m**2 - 1)/6 g1d = Rational(-2, 231) + 2*4**m*(m + 1)*(63*m**4 + 112*m**3 + 18*m**2 - 22*m + 3)/(693*binomial(2*m, m)) g1e = Rational(-9, 2) + (81*m**2 + 261*m + 200)*factorial( 3*m + 2)/(40*27**m*factorial(m)*factorial(m + 1)*factorial(m + 2)) g1f = (2*m + 1)**2*binomial(2*m, m)**2/(4**(2*m)*(m + 1)) g1g = -binomial(2*m, m)**2/4**(2*m) g1h = 4*pi -(2*m + 1)**2*(3*m + 4)*factorial(m - S.Half)**2/factorial(m + 1)**2 g = gosper_sum(f1a, (n, 0, m)) assert g is not None and simplify(g - g1a) == 0 g = gosper_sum(f1b, (n, 0, m)) assert g is not None and simplify(g - g1b) == 0 g = gosper_sum(f1c, (n, 0, m)) assert g is not None and simplify(g - g1c) == 0 g = gosper_sum(f1d, (n, 0, m)) assert g is not None and simplify(g - g1d) == 0 g = gosper_sum(f1e, (n, 0, m)) assert g is not None and simplify(g - g1e) == 0 g = gosper_sum(f1f, (n, 0, m)) assert g is not None and simplify(g - g1f) == 0 g = gosper_sum(f1g, (n, 0, m)) assert g is not None and simplify(g - g1g) == 0 g = gosper_sum(f1h, (n, 0, m)) # need to call rewrite(gamma) here because we have terms involving # factorial(1/2) assert g is not None and simplify(g - g1h).rewrite(gamma) == 0 def test_gosper_sum_AeqB_part2(): f2a = n**2*a**n f2b = (n - r/2)*binomial(r, n) f2c = factorial(n - 1)**2/(factorial(n - x)*factorial(n + x)) g2a = -a*(a + 1)/(a - 1)**3 + a**( m + 1)*(a**2*m**2 - 2*a*m**2 + m**2 - 2*a*m + 2*m + a + 1)/(a - 1)**3 g2b = (m - r)*binomial(r, m)/2 ff = factorial(1 - x)*factorial(1 + x) g2c = 1/ff*( 1 - 1/x**2) + factorial(m)**2/(x**2*factorial(m - x)*factorial(m + x)) g = gosper_sum(f2a, (n, 0, m)) assert g is not None and simplify(g - g2a) == 0 g = gosper_sum(f2b, (n, 0, m)) assert g is not None and simplify(g - g2b) == 0 g = gosper_sum(f2c, (n, 1, m)) assert g is not None and simplify(g - g2c) == 0 def test_gosper_nan(): a = Symbol('a', positive=True) b = Symbol('b', positive=True) n = Symbol('n', integer=True) m = Symbol('m', integer=True) f2d = n*(n + a + b)*a**n*b**n/(factorial(n + a)*factorial(n + b)) g2d = 1/(factorial(a - 1)*factorial( b - 1)) - a**(m + 1)*b**(m + 1)/(factorial(a + m)*factorial(b + m)) g = gosper_sum(f2d, (n, 0, m)) assert simplify(g - g2d) == 0 def test_gosper_sum_AeqB_part3(): f3a = 1/n**4 f3b = (6*n + 3)/(4*n**4 + 8*n**3 + 8*n**2 + 4*n + 3) f3c = 2**n*(n**2 - 2*n - 1)/(n**2*(n + 1)**2) f3d = n**2*4**n/((n + 1)*(n + 2)) f3e = 2**n/(n + 1) f3f = 4*(n - 1)*(n**2 - 2*n - 1)/(n**2*(n + 1)**2*(n - 2)**2*(n - 3)**2) f3g = (n**4 - 14*n**2 - 24*n - 9)*2**n/(n**2*(n + 1)**2*(n + 2)**2* (n + 3)**2) # g3a -> no closed form g3b = m*(m + 2)/(2*m**2 + 4*m + 3) g3c = 2**m/m**2 - 2 g3d = Rational(2, 3) + 4**(m + 1)*(m - 1)/(m + 2)/3 # g3e -> no closed form g3f = -(Rational(-1, 16) + 1/((m - 2)**2*(m + 1)**2)) # the AeqB key is wrong g3g = Rational(-2, 9) + 2**(m + 1)/((m + 1)**2*(m + 3)**2) g = gosper_sum(f3a, (n, 1, m)) assert g is None g = gosper_sum(f3b, (n, 1, m)) assert g is not None and simplify(g - g3b) == 0 g = gosper_sum(f3c, (n, 1, m - 1)) assert g is not None and simplify(g - g3c) == 0 g = gosper_sum(f3d, (n, 1, m)) assert g is not None and simplify(g - g3d) == 0 g = gosper_sum(f3e, (n, 0, m - 1)) assert g is None g = gosper_sum(f3f, (n, 4, m)) assert g is not None and simplify(g - g3f) == 0 g = gosper_sum(f3g, (n, 1, m)) assert g is not None and simplify(g - g3g) == 0
9e380b8f6689b9e5c203b74d621e3529fe31748f6dbea888f5ed78115e148fc1
from sympy.concrete.products import (Product, product) from sympy.concrete.summations import (Sum, summation) from sympy.core.function import (Derivative, Function) from sympy.core.mul import prod from sympy.core import (Catalan, EulerGamma) from sympy.core.numbers import (E, I, Rational, nan, oo, pi) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, symbols) from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import (rf, binomial, factorial) from sympy.functions.combinatorial.numbers import harmonic from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.hyperbolic import (sinh, tanh) from sympy.functions.elementary.integers import floor from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.gamma_functions import (gamma, lowergamma) from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.functions.special.zeta_functions import zeta from sympy.integrals.integrals import Integral from sympy.logic.boolalg import And, Or from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.expressions.special import Identity from sympy.sets.fancysets import Range from sympy.sets.sets import Interval from sympy.simplify.combsimp import combsimp from sympy.simplify.simplify import simplify from sympy.tensor.indexed import (Idx, Indexed, IndexedBase) from sympy.abc import a, b, c, d, k, m, x, y, z from sympy.concrete.summations import ( telescopic, _dummy_with_inherited_properties_concrete, eval_sum_residue) from sympy.concrete.expr_with_intlimits import ReorderError from sympy.core.facts import InconsistentAssumptions from sympy.testing.pytest import XFAIL, raises, slow from sympy.matrices import (Matrix, SparseMatrix, ImmutableDenseMatrix, ImmutableSparseMatrix) from sympy.core.mod import Mod n = Symbol('n', integer=True) f, g = symbols('f g', cls=Function) def test_karr_convention(): # Test the Karr summation convention that we want to hold. # See his paper "Summation in Finite Terms" for a detailed # reasoning why we really want exactly this definition. # The convention is described on page 309 and essentially # in section 1.4, definition 3: # # \sum_{m <= i < n} f(i) 'has the obvious meaning' for m < n # \sum_{m <= i < n} f(i) = 0 for m = n # \sum_{m <= i < n} f(i) = - \sum_{n <= i < m} f(i) for m > n # # It is important to note that he defines all sums with # the upper limit being *exclusive*. # In contrast, SymPy and the usual mathematical notation has: # # sum_{i = a}^b f(i) = f(a) + f(a+1) + ... + f(b-1) + f(b) # # with the upper limit *inclusive*. So translating between # the two we find that: # # \sum_{m <= i < n} f(i) = \sum_{i = m}^{n-1} f(i) # # where we intentionally used two different ways to typeset the # sum and its limits. i = Symbol("i", integer=True) k = Symbol("k", integer=True) j = Symbol("j", integer=True) # A simple example with a concrete summand and symbolic limits. # The normal sum: m = k and n = k + j and therefore m < n: m = k n = k + j a = m b = n - 1 S1 = Sum(i**2, (i, a, b)).doit() # The reversed sum: m = k + j and n = k and therefore m > n: m = k + j n = k a = m b = n - 1 S2 = Sum(i**2, (i, a, b)).doit() assert simplify(S1 + S2) == 0 # Test the empty sum: m = k and n = k and therefore m = n: m = k n = k a = m b = n - 1 Sz = Sum(i**2, (i, a, b)).doit() assert Sz == 0 # Another example this time with an unspecified summand and # numeric limits. (We can not do both tests in the same example.) # The normal sum with m < n: m = 2 n = 11 a = m b = n - 1 S1 = Sum(f(i), (i, a, b)).doit() # The reversed sum with m > n: m = 11 n = 2 a = m b = n - 1 S2 = Sum(f(i), (i, a, b)).doit() assert simplify(S1 + S2) == 0 # Test the empty sum with m = n: m = 5 n = 5 a = m b = n - 1 Sz = Sum(f(i), (i, a, b)).doit() assert Sz == 0 e = Piecewise((exp(-i), Mod(i, 2) > 0), (0, True)) s = Sum(e, (i, 0, 11)) assert s.n(3) == s.doit().n(3) def test_karr_proposition_2a(): # Test Karr, page 309, proposition 2, part a i = Symbol("i", integer=True) u = Symbol("u", integer=True) v = Symbol("v", integer=True) def test_the_sum(m, n): # g g = i**3 + 2*i**2 - 3*i # f = Delta g f = simplify(g.subs(i, i+1) - g) # The sum a = m b = n - 1 S = Sum(f, (i, a, b)).doit() # Test if Sum_{m <= i < n} f(i) = g(n) - g(m) assert simplify(S - (g.subs(i, n) - g.subs(i, m))) == 0 # m < n test_the_sum(u, u+v) # m = n test_the_sum(u, u ) # m > n test_the_sum(u+v, u ) def test_karr_proposition_2b(): # Test Karr, page 309, proposition 2, part b i = Symbol("i", integer=True) u = Symbol("u", integer=True) v = Symbol("v", integer=True) w = Symbol("w", integer=True) def test_the_sum(l, n, m): # Summand s = i**3 # First sum a = l b = n - 1 S1 = Sum(s, (i, a, b)).doit() # Second sum a = l b = m - 1 S2 = Sum(s, (i, a, b)).doit() # Third sum a = m b = n - 1 S3 = Sum(s, (i, a, b)).doit() # Test if S1 = S2 + S3 as required assert S1 - (S2 + S3) == 0 # l < m < n test_the_sum(u, u+v, u+v+w) # l < m = n test_the_sum(u, u+v, u+v ) # l < m > n test_the_sum(u, u+v+w, v ) # l = m < n test_the_sum(u, u, u+v ) # l = m = n test_the_sum(u, u, u ) # l = m > n test_the_sum(u+v, u+v, u ) # l > m < n test_the_sum(u+v, u, u+w ) # l > m = n test_the_sum(u+v, u, u ) # l > m > n test_the_sum(u+v+w, u+v, u ) def test_arithmetic_sums(): assert summation(1, (n, a, b)) == b - a + 1 assert Sum(S.NaN, (n, a, b)) is S.NaN assert Sum(x, (n, a, a)).doit() == x assert Sum(x, (x, a, a)).doit() == a assert Sum(x, (n, 1, a)).doit() == a*x assert Sum(x, (x, Range(1, 11))).doit() == 55 assert Sum(x, (x, Range(1, 11, 2))).doit() == 25 assert Sum(x, (x, Range(1, 10, 2))) == Sum(x, (x, Range(9, 0, -2))) lo, hi = 1, 2 s1 = Sum(n, (n, lo, hi)) s2 = Sum(n, (n, hi, lo)) assert s1 != s2 assert s1.doit() == 3 and s2.doit() == 0 lo, hi = x, x + 1 s1 = Sum(n, (n, lo, hi)) s2 = Sum(n, (n, hi, lo)) assert s1 != s2 assert s1.doit() == 2*x + 1 and s2.doit() == 0 assert Sum(Integral(x, (x, 1, y)) + x, (x, 1, 2)).doit() == \ y**2 + 2 assert summation(1, (n, 1, 10)) == 10 assert summation(2*n, (n, 0, 10**10)) == 100000000010000000000 assert summation(4*n*m, (n, a, 1), (m, 1, d)).expand() == \ 2*d + 2*d**2 + a*d + a*d**2 - d*a**2 - a**2*d**2 assert summation(cos(n), (n, -2, 1)) == cos(-2) + cos(-1) + cos(0) + cos(1) assert summation(cos(n), (n, x, x + 2)) == cos(x) + cos(x + 1) + cos(x + 2) assert isinstance(summation(cos(n), (n, x, x + S.Half)), Sum) assert summation(k, (k, 0, oo)) is oo assert summation(k, (k, Range(1, 11))) == 55 def test_polynomial_sums(): assert summation(n**2, (n, 3, 8)) == 199 assert summation(n, (n, a, b)) == \ ((a + b)*(b - a + 1)/2).expand() assert summation(n**2, (n, 1, b)) == \ ((2*b**3 + 3*b**2 + b)/6).expand() assert summation(n**3, (n, 1, b)) == \ ((b**4 + 2*b**3 + b**2)/4).expand() assert summation(n**6, (n, 1, b)) == \ ((6*b**7 + 21*b**6 + 21*b**5 - 7*b**3 + b)/42).expand() def test_geometric_sums(): assert summation(pi**n, (n, 0, b)) == (1 - pi**(b + 1)) / (1 - pi) assert summation(2 * 3**n, (n, 0, b)) == 3**(b + 1) - 1 assert summation(S.Half**n, (n, 1, oo)) == 1 assert summation(2**n, (n, 0, b)) == 2**(b + 1) - 1 assert summation(2**n, (n, 1, oo)) is oo assert summation(2**(-n), (n, 1, oo)) == 1 assert summation(3**(-n), (n, 4, oo)) == Rational(1, 54) assert summation(2**(-4*n + 3), (n, 1, oo)) == Rational(8, 15) assert summation(2**(n + 1), (n, 1, b)).expand() == 4*(2**b - 1) # issue 6664: assert summation(x**n, (n, 0, oo)) == \ Piecewise((1/(-x + 1), Abs(x) < 1), (Sum(x**n, (n, 0, oo)), True)) assert summation(-2**n, (n, 0, oo)) is -oo assert summation(I**n, (n, 0, oo)) == Sum(I**n, (n, 0, oo)) # issue 6802: assert summation((-1)**(2*x + 2), (x, 0, n)) == n + 1 assert summation((-2)**(2*x + 2), (x, 0, n)) == 4*4**(n + 1)/S(3) - Rational(4, 3) assert summation((-1)**x, (x, 0, n)) == -(-1)**(n + 1)/S(2) + S.Half assert summation(y**x, (x, a, b)) == \ Piecewise((-a + b + 1, Eq(y, 1)), ((y**a - y**(b + 1))/(-y + 1), True)) assert summation((-2)**(y*x + 2), (x, 0, n)) == \ 4*Piecewise((n + 1, Eq((-2)**y, 1)), ((-(-2)**(y*(n + 1)) + 1)/(-(-2)**y + 1), True)) # issue 8251: assert summation((1/(n + 1)**2)*n**2, (n, 0, oo)) is oo #issue 9908: assert Sum(1/(n**3 - 1), (n, -oo, -2)).doit() == summation(1/(n**3 - 1), (n, -oo, -2)) #issue 11642: result = Sum(0.5**n, (n, 1, oo)).doit() assert result == 1 assert result.is_Float result = Sum(0.25**n, (n, 1, oo)).doit() assert result == 1/3. assert result.is_Float result = Sum(0.99999**n, (n, 1, oo)).doit() assert result == 99999 assert result.is_Float result = Sum(S.Half**n, (n, 1, oo)).doit() assert result == 1 assert not result.is_Float result = Sum(Rational(3, 5)**n, (n, 1, oo)).doit() assert result == Rational(3, 2) assert not result.is_Float assert Sum(1.0**n, (n, 1, oo)).doit() is oo assert Sum(2.43**n, (n, 1, oo)).doit() is oo # Issue 13979 i, k, q = symbols('i k q', integer=True) result = summation( exp(-2*I*pi*k*i/n) * exp(2*I*pi*q*i/n) / n, (i, 0, n - 1) ) assert result.simplify() == Piecewise( (1, Eq(exp(-2*I*pi*(k - q)/n), 1)), (0, True) ) def test_harmonic_sums(): assert summation(1/k, (k, 0, n)) == Sum(1/k, (k, 0, n)) assert summation(1/k, (k, 1, n)) == harmonic(n) assert summation(n/k, (k, 1, n)) == n*harmonic(n) assert summation(1/k, (k, 5, n)) == harmonic(n) - harmonic(4) def test_composite_sums(): f = S.Half*(7 - 6*n + Rational(1, 7)*n**3) s = summation(f, (n, a, b)) assert not isinstance(s, Sum) A = 0 for i in range(-3, 5): A += f.subs(n, i) B = s.subs(a, -3).subs(b, 4) assert A == B def test_hypergeometric_sums(): assert summation( binomial(2*k, k)/4**k, (k, 0, n)) == (1 + 2*n)*binomial(2*n, n)/4**n assert summation(binomial(2*k, k)/5**k, (k, -oo, oo)) == sqrt(5) def test_other_sums(): f = m**2 + m*exp(m) g = 3*exp(Rational(3, 2))/2 + exp(S.Half)/2 - exp(Rational(-1, 2))/2 - 3*exp(Rational(-3, 2))/2 + 5 assert summation(f, (m, Rational(-3, 2), Rational(3, 2))) == g assert summation(f, (m, -1.5, 1.5)).evalf().epsilon_eq(g.evalf(), 1e-10) fac = factorial def NS(e, n=15, **options): return str(sympify(e).evalf(n, **options)) def test_evalf_fast_series(): # Euler transformed series for sqrt(1+x) assert NS(Sum( fac(2*n + 1)/fac(n)**2/2**(3*n + 1), (n, 0, oo)), 100) == NS(sqrt(2), 100) # Some series for exp(1) estr = NS(E, 100) assert NS(Sum(1/fac(n), (n, 0, oo)), 100) == estr assert NS(1/Sum((1 - 2*n)/fac(2*n), (n, 0, oo)), 100) == estr assert NS(Sum((2*n + 1)/fac(2*n), (n, 0, oo)), 100) == estr assert NS(Sum((4*n + 3)/2**(2*n + 1)/fac(2*n + 1), (n, 0, oo))**2, 100) == estr pistr = NS(pi, 100) # Ramanujan series for pi assert NS(9801/sqrt(8)/Sum(fac( 4*n)*(1103 + 26390*n)/fac(n)**4/396**(4*n), (n, 0, oo)), 100) == pistr assert NS(1/Sum( binomial(2*n, n)**3 * (42*n + 5)/2**(12*n + 4), (n, 0, oo)), 100) == pistr # Machin's formula for pi assert NS(16*Sum((-1)**n/(2*n + 1)/5**(2*n + 1), (n, 0, oo)) - 4*Sum((-1)**n/(2*n + 1)/239**(2*n + 1), (n, 0, oo)), 100) == pistr # Apery's constant astr = NS(zeta(3), 100) P = 126392*n**5 + 412708*n**4 + 531578*n**3 + 336367*n**2 + 104000* \ n + 12463 assert NS(Sum((-1)**n * P / 24 * (fac(2*n + 1)*fac(2*n)*fac( n))**3 / fac(3*n + 2) / fac(4*n + 3)**3, (n, 0, oo)), 100) == astr assert NS(Sum((-1)**n * (205*n**2 + 250*n + 77)/64 * fac(n)**10 / fac(2*n + 1)**5, (n, 0, oo)), 100) == astr def test_evalf_fast_series_issue_4021(): # Catalan's constant assert NS(Sum((-1)**(n - 1)*2**(8*n)*(40*n**2 - 24*n + 3)*fac(2*n)**3* fac(n)**2/n**3/(2*n - 1)/fac(4*n)**2, (n, 1, oo))/64, 100) == \ NS(Catalan, 100) astr = NS(zeta(3), 100) assert NS(5*Sum( (-1)**(n - 1)*fac(n)**2 / n**3 / fac(2*n), (n, 1, oo))/2, 100) == astr assert NS(Sum((-1)**(n - 1)*(56*n**2 - 32*n + 5) / (2*n - 1)**2 * fac(n - 1) **3 / fac(3*n), (n, 1, oo))/4, 100) == astr def test_evalf_slow_series(): assert NS(Sum((-1)**n / n, (n, 1, oo)), 15) == NS(-log(2), 15) assert NS(Sum((-1)**n / n, (n, 1, oo)), 50) == NS(-log(2), 50) assert NS(Sum(1/n**2, (n, 1, oo)), 15) == NS(pi**2/6, 15) assert NS(Sum(1/n**2, (n, 1, oo)), 100) == NS(pi**2/6, 100) assert NS(Sum(1/n**2, (n, 1, oo)), 500) == NS(pi**2/6, 500) assert NS(Sum((-1)**n / (2*n + 1)**3, (n, 0, oo)), 15) == NS(pi**3/32, 15) assert NS(Sum((-1)**n / (2*n + 1)**3, (n, 0, oo)), 50) == NS(pi**3/32, 50) def test_evalf_oo_to_oo(): # There used to be an error in certain cases # Does not evaluate, but at least do not throw an error # Evaluates symbolically to 0, which is not correct assert Sum(1/(n**2+1), (n, -oo, oo)).evalf() == Sum(1/(n**2+1), (n, -oo, oo)) # This evaluates if from 1 to oo and symbolically assert Sum(1/(factorial(abs(n))), (n, -oo, -1)).evalf() == Sum(1/(factorial(abs(n))), (n, -oo, -1)) def test_euler_maclaurin(): # Exact polynomial sums with E-M def check_exact(f, a, b, m, n): A = Sum(f, (k, a, b)) s, e = A.euler_maclaurin(m, n) assert (e == 0) and (s.expand() == A.doit()) check_exact(k**4, a, b, 0, 2) check_exact(k**4 + 2*k, a, b, 1, 2) check_exact(k**4 + k**2, a, b, 1, 5) check_exact(k**5, 2, 6, 1, 2) check_exact(k**5, 2, 6, 1, 3) assert Sum(x-1, (x, 0, 2)).euler_maclaurin(m=30, n=30, eps=2**-15) == (0, 0) # Not exact assert Sum(k**6, (k, a, b)).euler_maclaurin(0, 2)[1] != 0 # Numerical test for mi, ni in [(2, 4), (2, 20), (10, 20), (18, 20)]: A = Sum(1/k**3, (k, 1, oo)) s, e = A.euler_maclaurin(mi, ni) assert abs((s - zeta(3)).evalf()) < e.evalf() raises(ValueError, lambda: Sum(1, (x, 0, 1), (k, 0, 1)).euler_maclaurin()) @slow def test_evalf_euler_maclaurin(): assert NS(Sum(1/k**k, (k, 1, oo)), 15) == '1.29128599706266' assert NS(Sum(1/k**k, (k, 1, oo)), 50) == '1.2912859970626635404072825905956005414986193682745' assert NS(Sum(1/k - log(1 + 1/k), (k, 1, oo)), 15) == NS(EulerGamma, 15) assert NS(Sum(1/k - log(1 + 1/k), (k, 1, oo)), 50) == NS(EulerGamma, 50) assert NS(Sum(log(k)/k**2, (k, 1, oo)), 15) == '0.937548254315844' assert NS(Sum(log(k)/k**2, (k, 1, oo)), 50) == '0.93754825431584375370257409456786497789786028861483' assert NS(Sum(1/k, (k, 1000000, 2000000)), 15) == '0.693147930560008' assert NS(Sum(1/k, (k, 1000000, 2000000)), 50) == '0.69314793056000780941723211364567656807940638436025' def test_evalf_symbolic(): # issue 6328 expr = Sum(f(x), (x, 1, 3)) + Sum(g(x), (x, 1, 3)) assert expr.evalf() == expr def test_evalf_issue_3273(): assert Sum(0, (k, 1, oo)).evalf() == 0 def test_simple_products(): assert Product(S.NaN, (x, 1, 3)) is S.NaN assert product(S.NaN, (x, 1, 3)) is S.NaN assert Product(x, (n, a, a)).doit() == x assert Product(x, (x, a, a)).doit() == a assert Product(x, (y, 1, a)).doit() == x**a lo, hi = 1, 2 s1 = Product(n, (n, lo, hi)) s2 = Product(n, (n, hi, lo)) assert s1 != s2 # This IS correct according to Karr product convention assert s1.doit() == 2 assert s2.doit() == 1 lo, hi = x, x + 1 s1 = Product(n, (n, lo, hi)) s2 = Product(n, (n, hi, lo)) s3 = 1 / Product(n, (n, hi + 1, lo - 1)) assert s1 != s2 # This IS correct according to Karr product convention assert s1.doit() == x*(x + 1) assert s2.doit() == 1 assert s3.doit() == x*(x + 1) assert Product(Integral(2*x, (x, 1, y)) + 2*x, (x, 1, 2)).doit() == \ (y**2 + 1)*(y**2 + 3) assert product(2, (n, a, b)) == 2**(b - a + 1) assert product(n, (n, 1, b)) == factorial(b) assert product(n**3, (n, 1, b)) == factorial(b)**3 assert product(3**(2 + n), (n, a, b)) \ == 3**(2*(1 - a + b) + b/2 + (b**2)/2 + a/2 - (a**2)/2) assert product(cos(n), (n, 3, 5)) == cos(3)*cos(4)*cos(5) assert product(cos(n), (n, x, x + 2)) == cos(x)*cos(x + 1)*cos(x + 2) assert isinstance(product(cos(n), (n, x, x + S.Half)), Product) # If Product managed to evaluate this one, it most likely got it wrong! assert isinstance(Product(n**n, (n, 1, b)), Product) def test_rational_products(): assert combsimp(product(1 + 1/n, (n, a, b))) == (1 + b)/a assert combsimp(product(n + 1, (n, a, b))) == gamma(2 + b)/gamma(1 + a) assert combsimp(product((n + 1)/(n - 1), (n, a, b))) == b*(1 + b)/(a*(a - 1)) assert combsimp(product(n/(n + 1)/(n + 2), (n, a, b))) == \ a*gamma(a + 2)/(b + 1)/gamma(b + 3) assert combsimp(product(n*(n + 1)/(n - 1)/(n - 2), (n, a, b))) == \ b**2*(b - 1)*(1 + b)/(a - 1)**2/(a*(a - 2)) def test_wallis_product(): # Wallis product, given in two different forms to ensure that Product # can factor simple rational expressions A = Product(4*n**2 / (4*n**2 - 1), (n, 1, b)) B = Product((2*n)*(2*n)/(2*n - 1)/(2*n + 1), (n, 1, b)) R = pi*gamma(b + 1)**2/(2*gamma(b + S.Half)*gamma(b + Rational(3, 2))) assert simplify(A.doit()) == R assert simplify(B.doit()) == R # This one should eventually also be doable (Euler's product formula for sin) # assert Product(1+x/n**2, (n, 1, b)) == ... def test_telescopic_sums(): #checks also input 2 of comment 1 issue 4127 assert Sum(1/k - 1/(k + 1), (k, 1, n)).doit() == 1 - 1/(1 + n) assert Sum( f(k) - f(k + 2), (k, m, n)).doit() == -f(1 + n) - f(2 + n) + f(m) + f(1 + m) assert Sum(cos(k) - cos(k + 3), (k, 1, n)).doit() == -cos(1 + n) - \ cos(2 + n) - cos(3 + n) + cos(1) + cos(2) + cos(3) # dummy variable shouldn't matter assert telescopic(1/m, -m/(1 + m), (m, n - 1, n)) == \ telescopic(1/k, -k/(1 + k), (k, n - 1, n)) assert Sum(1/x/(x - 1), (x, a, b)).doit() == -((a - b - 1)/(b*(a - 1))) def test_sum_reconstruct(): s = Sum(n**2, (n, -1, 1)) assert s == Sum(*s.args) raises(ValueError, lambda: Sum(x, x)) raises(ValueError, lambda: Sum(x, (x, 1))) def test_limit_subs(): for F in (Sum, Product, Integral): assert F(a*exp(a), (a, -2, 2)) == F(a*exp(a), (a, -b, b)).subs(b, 2) assert F(a, (a, F(b, (b, 1, 2)), 4)).subs(F(b, (b, 1, 2)), c) == \ F(a, (a, c, 4)) assert F(x, (x, 1, x + y)).subs(x, 1) == F(x, (x, 1, y + 1)) def test_function_subs(): S = Sum(x*f(y),(x,0,oo),(y,0,oo)) assert S.subs(f(y),y) == Sum(x*y,(x,0,oo),(y,0,oo)) assert S.subs(f(x),x) == S raises(ValueError, lambda: S.subs(f(y),x+y) ) S = Sum(x*log(y),(x,0,oo),(y,0,oo)) assert S.subs(log(y),y) == S S = Sum(x*f(y),(x,0,oo),(y,0,oo)) assert S.subs(f(y),y) == Sum(x*y,(x,0,oo),(y,0,oo)) def test_equality(): # if this fails remove special handling below raises(ValueError, lambda: Sum(x, x)) r = symbols('x', real=True) for F in (Sum, Product, Integral): try: assert F(x, x) != F(y, y) assert F(x, (x, 1, 2)) != F(x, x) assert F(x, (x, x)) != F(x, x) # or else they print the same assert F(1, x) != F(1, y) except ValueError: pass assert F(a, (x, 1, 2)) != F(a, (x, 1, 3)) # diff limit assert F(a, (x, 1, x)) != F(a, (y, 1, y)) assert F(a, (x, 1, 2)) != F(b, (x, 1, 2)) # diff expression assert F(x, (x, 1, 2)) != F(r, (r, 1, 2)) # diff assumptions assert F(1, (x, 1, x)) != F(1, (y, 1, x)) # only dummy is diff assert F(1, (x, 1, x)).dummy_eq(F(1, (y, 1, x))) # issue 5265 assert Sum(x, (x, 1, x)).subs(x, a) == Sum(x, (x, 1, a)) def test_Sum_doit(): assert Sum(n*Integral(a**2), (n, 0, 2)).doit() == a**3 assert Sum(n*Integral(a**2), (n, 0, 2)).doit(deep=False) == \ 3*Integral(a**2) assert summation(n*Integral(a**2), (n, 0, 2)) == 3*Integral(a**2) # test nested sum evaluation s = Sum( Sum( Sum(2,(z,1,n+1)), (y,x+1,n)), (x,1,n)) assert 0 == (s.doit() - n*(n+1)*(n-1)).factor() # Integer assumes finite assert Sum(KroneckerDelta(x, y), (x, -oo, oo)).doit() == Piecewise((1, And(-oo < y, y < oo)), (0, True)) assert Sum(KroneckerDelta(m, n), (m, -oo, oo)).doit() == 1 assert Sum(m*KroneckerDelta(x, y), (x, -oo, oo)).doit() == Piecewise((m, And(-oo < y, y < oo)), (0, True)) assert Sum(x*KroneckerDelta(m, n), (m, -oo, oo)).doit() == x assert Sum(Sum(KroneckerDelta(m, n), (m, 1, 3)), (n, 1, 3)).doit() == 3 assert Sum(Sum(KroneckerDelta(k, m), (m, 1, 3)), (n, 1, 3)).doit() == \ 3 * Piecewise((1, And(1 <= k, k <= 3)), (0, True)) assert Sum(f(n) * Sum(KroneckerDelta(m, n), (m, 0, oo)), (n, 1, 3)).doit() == \ f(1) + f(2) + f(3) assert Sum(f(n) * Sum(KroneckerDelta(m, n), (m, 0, oo)), (n, 1, oo)).doit() == \ Sum(f(n), (n, 1, oo)) # issue 2597 nmax = symbols('N', integer=True, positive=True) pw = Piecewise((1, And(1 <= n, n <= nmax)), (0, True)) assert Sum(pw, (n, 1, nmax)).doit() == Sum(Piecewise((1, nmax >= n), (0, True)), (n, 1, nmax)) q, s = symbols('q, s') assert summation(1/n**(2*s), (n, 1, oo)) == Piecewise((zeta(2*s), 2*s > 1), (Sum(n**(-2*s), (n, 1, oo)), True)) assert summation(1/(n+1)**s, (n, 0, oo)) == Piecewise((zeta(s), s > 1), (Sum((n + 1)**(-s), (n, 0, oo)), True)) assert summation(1/(n+q)**s, (n, 0, oo)) == Piecewise( (zeta(s, q), And(q > 0, s > 1)), (Sum((n + q)**(-s), (n, 0, oo)), True)) assert summation(1/(n+q)**s, (n, q, oo)) == Piecewise( (zeta(s, 2*q), And(2*q > 0, s > 1)), (Sum((n + q)**(-s), (n, q, oo)), True)) assert summation(1/n**2, (n, 1, oo)) == zeta(2) assert summation(1/n**s, (n, 0, oo)) == Sum(n**(-s), (n, 0, oo)) def test_Product_doit(): assert Product(n*Integral(a**2), (n, 1, 3)).doit() == 2 * a**9 / 9 assert Product(n*Integral(a**2), (n, 1, 3)).doit(deep=False) == \ 6*Integral(a**2)**3 assert product(n*Integral(a**2), (n, 1, 3)) == 6*Integral(a**2)**3 def test_Sum_interface(): assert isinstance(Sum(0, (n, 0, 2)), Sum) assert Sum(nan, (n, 0, 2)) is nan assert Sum(nan, (n, 0, oo)) is nan assert Sum(0, (n, 0, 2)).doit() == 0 assert isinstance(Sum(0, (n, 0, oo)), Sum) assert Sum(0, (n, 0, oo)).doit() == 0 raises(ValueError, lambda: Sum(1)) raises(ValueError, lambda: summation(1)) def test_diff(): assert Sum(x, (x, 1, 2)).diff(x) == 0 assert Sum(x*y, (x, 1, 2)).diff(x) == 0 assert Sum(x*y, (y, 1, 2)).diff(x) == Sum(y, (y, 1, 2)) e = Sum(x*y, (x, 1, a)) assert e.diff(a) == Derivative(e, a) assert Sum(x*y, (x, 1, 3), (a, 2, 5)).diff(y).doit() == \ Sum(x*y, (x, 1, 3), (a, 2, 5)).doit().diff(y) == 24 assert Sum(x, (x, 1, 2)).diff(y) == 0 def test_hypersum(): assert simplify(summation(x**n/fac(n), (n, 1, oo))) == -1 + exp(x) assert summation((-1)**n * x**(2*n) / fac(2*n), (n, 0, oo)) == cos(x) assert simplify(summation((-1)**n*x**(2*n + 1) / factorial(2*n + 1), (n, 3, oo))) == -x + sin(x) + x**3/6 - x**5/120 assert summation(1/(n + 2)**3, (n, 1, oo)) == Rational(-9, 8) + zeta(3) assert summation(1/n**4, (n, 1, oo)) == pi**4/90 s = summation(x**n*n, (n, -oo, 0)) assert s.is_Piecewise assert s.args[0].args[0] == -1/(x*(1 - 1/x)**2) assert s.args[0].args[1] == (abs(1/x) < 1) m = Symbol('n', integer=True, positive=True) assert summation(binomial(m, k), (k, 0, m)) == 2**m def test_issue_4170(): assert summation(1/factorial(k), (k, 0, oo)) == E def test_is_commutative(): from sympy.physics.secondquant import NO, F, Fd m = Symbol('m', commutative=False) for f in (Sum, Product, Integral): assert f(z, (z, 1, 1)).is_commutative is True assert f(z*y, (z, 1, 6)).is_commutative is True assert f(m*x, (x, 1, 2)).is_commutative is False assert f(NO(Fd(x)*F(y))*z, (z, 1, 2)).is_commutative is False def test_is_zero(): for func in [Sum, Product]: assert func(0, (x, 1, 1)).is_zero is True assert func(x, (x, 1, 1)).is_zero is None assert Sum(0, (x, 1, 0)).is_zero is True assert Product(0, (x, 1, 0)).is_zero is False def test_is_number(): # is number should not rely on evaluation or assumptions, # it should be equivalent to `not foo.free_symbols` assert Sum(1, (x, 1, 1)).is_number is True assert Sum(1, (x, 1, x)).is_number is False assert Sum(0, (x, y, z)).is_number is False assert Sum(x, (y, 1, 2)).is_number is False assert Sum(x, (y, 1, 1)).is_number is False assert Sum(x, (x, 1, 2)).is_number is True assert Sum(x*y, (x, 1, 2), (y, 1, 3)).is_number is True assert Product(2, (x, 1, 1)).is_number is True assert Product(2, (x, 1, y)).is_number is False assert Product(0, (x, y, z)).is_number is False assert Product(1, (x, y, z)).is_number is False assert Product(x, (y, 1, x)).is_number is False assert Product(x, (y, 1, 2)).is_number is False assert Product(x, (y, 1, 1)).is_number is False assert Product(x, (x, 1, 2)).is_number is True def test_free_symbols(): for func in [Sum, Product]: assert func(1, (x, 1, 2)).free_symbols == set() assert func(0, (x, 1, y)).free_symbols == {y} assert func(2, (x, 1, y)).free_symbols == {y} assert func(x, (x, 1, 2)).free_symbols == set() assert func(x, (x, 1, y)).free_symbols == {y} assert func(x, (y, 1, y)).free_symbols == {x, y} assert func(x, (y, 1, 2)).free_symbols == {x} assert func(x, (y, 1, 1)).free_symbols == {x} assert func(x, (y, 1, z)).free_symbols == {x, z} assert func(x, (x, 1, y), (y, 1, 2)).free_symbols == set() assert func(x, (x, 1, y), (y, 1, z)).free_symbols == {z} assert func(x, (x, 1, y), (y, 1, y)).free_symbols == {y} assert func(x, (y, 1, y), (y, 1, z)).free_symbols == {x, z} assert Sum(1, (x, 1, y)).free_symbols == {y} # free_symbols answers whether the object *as written* has free symbols, # not whether the evaluated expression has free symbols assert Product(1, (x, 1, y)).free_symbols == {y} # don't count free symbols that are not independent of integration # variable(s) assert func(f(x), (f(x), 1, 2)).free_symbols == set() assert func(f(x), (f(x), 1, x)).free_symbols == {x} assert func(f(x), (f(x), 1, y)).free_symbols == {y} assert func(f(x), (z, 1, y)).free_symbols == {x, y} def test_conjugate_transpose(): A, B = symbols("A B", commutative=False) p = Sum(A*B**n, (n, 1, 3)) assert p.adjoint().doit() == p.doit().adjoint() assert p.conjugate().doit() == p.doit().conjugate() assert p.transpose().doit() == p.doit().transpose() p = Sum(B**n*A, (n, 1, 3)) assert p.adjoint().doit() == p.doit().adjoint() assert p.conjugate().doit() == p.doit().conjugate() assert p.transpose().doit() == p.doit().transpose() def test_noncommutativity_honoured(): A, B = symbols("A B", commutative=False) M = symbols('M', integer=True, positive=True) p = Sum(A*B**n, (n, 1, M)) assert p.doit() == A*Piecewise((M, Eq(B, 1)), ((B - B**(M + 1))*(1 - B)**(-1), True)) p = Sum(B**n*A, (n, 1, M)) assert p.doit() == Piecewise((M, Eq(B, 1)), ((B - B**(M + 1))*(1 - B)**(-1), True))*A p = Sum(B**n*A*B**n, (n, 1, M)) assert p.doit() == p def test_issue_4171(): assert summation(factorial(2*k + 1)/factorial(2*k), (k, 0, oo)) is oo assert summation(2*k + 1, (k, 0, oo)) is oo def test_issue_6273(): assert Sum(x, (x, 1, n)).n(2, subs={n: 1}) == 1 def test_issue_6274(): assert Sum(x, (x, 1, 0)).doit() == 0 assert NS(Sum(x, (x, 1, 0))) == '0' assert Sum(n, (n, 10, 5)).doit() == -30 assert NS(Sum(n, (n, 10, 5))) == '-30.0000000000000' def test_simplify_sum(): y, t, v = symbols('y, t, v') _simplify = lambda e: simplify(e, doit=False) assert _simplify(Sum(x*y, (x, n, m), (y, a, k)) + \ Sum(y, (x, n, m), (y, a, k))) == Sum(y * (x + 1), (x, n, m), (y, a, k)) assert _simplify(Sum(x, (x, n, m)) + Sum(x, (x, m + 1, a))) == \ Sum(x, (x, n, a)) assert _simplify(Sum(x, (x, k + 1, a)) + Sum(x, (x, n, k))) == \ Sum(x, (x, n, a)) assert _simplify(Sum(x, (x, k + 1, a)) + Sum(x + 1, (x, n, k))) == \ Sum(x, (x, n, a)) + Sum(1, (x, n, k)) assert _simplify(Sum(x, (x, 0, 3)) * 3 + 3 * Sum(x, (x, 4, 6)) + \ 4 * Sum(z, (z, 0, 1))) == 4*Sum(z, (z, 0, 1)) + 3*Sum(x, (x, 0, 6)) assert _simplify(3*Sum(x**2, (x, a, b)) + Sum(x, (x, a, b))) == \ Sum(x*(3*x + 1), (x, a, b)) assert _simplify(Sum(x**3, (x, n, k)) * 3 + 3 * Sum(x, (x, n, k)) + \ 4 * y * Sum(z, (z, n, k))) + 1 == \ 4*y*Sum(z, (z, n, k)) + 3*Sum(x**3 + x, (x, n, k)) + 1 assert _simplify(Sum(x, (x, a, b)) + 1 + Sum(x, (x, b + 1, c))) == \ 1 + Sum(x, (x, a, c)) assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + \ Sum(x, (t, b+1, c))) == x * Sum(1, (t, a, c)) + y * Sum(1, (t, a, b)) assert _simplify(Sum(x, (t, a, b)) + Sum(x, (t, b+1, c)) + \ Sum(y, (t, a, b))) == x * Sum(1, (t, a, c)) + y * Sum(1, (t, a, b)) assert _simplify(Sum(x, (t, a, b)) + 2 * Sum(x, (t, b+1, c))) == \ _simplify(Sum(x, (t, a, b)) + Sum(x, (t, b+1, c)) + Sum(x, (t, b+1, c))) assert _simplify(Sum(x, (x, a, b))*Sum(x**2, (x, a, b))) == \ Sum(x, (x, a, b)) * Sum(x**2, (x, a, b)) assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + Sum(z, (t, a, b))) \ == (x + y + z) * Sum(1, (t, a, b)) # issue 8596 assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + Sum(z, (t, a, b)) + \ Sum(v, (t, a, b))) == (x + y + z + v) * Sum(1, (t, a, b)) # issue 8596 assert _simplify(Sum(x * y, (x, a, b)) / (3 * y)) == \ (Sum(x, (x, a, b)) / 3) assert _simplify(Sum(f(x) * y * z, (x, a, b)) / (y * z)) \ == Sum(f(x), (x, a, b)) assert _simplify(Sum(c * x, (x, a, b)) - c * Sum(x, (x, a, b))) == 0 assert _simplify(c * (Sum(x, (x, a, b)) + y)) == c * (y + Sum(x, (x, a, b))) assert _simplify(c * (Sum(x, (x, a, b)) + y * Sum(x, (x, a, b)))) == \ c * (y + 1) * Sum(x, (x, a, b)) assert _simplify(Sum(Sum(c * x, (x, a, b)), (y, a, b))) == \ c * Sum(x, (x, a, b), (y, a, b)) assert _simplify(Sum((3 + y) * Sum(c * x, (x, a, b)), (y, a, b))) == \ c * Sum((3 + y), (y, a, b)) * Sum(x, (x, a, b)) assert _simplify(Sum((3 + t) * Sum(c * t, (x, a, b)), (y, a, b))) == \ c*t*(t + 3)*Sum(1, (x, a, b))*Sum(1, (y, a, b)) assert _simplify(Sum(Sum(d * t, (x, a, b - 1)) + \ Sum(d * t, (x, b, c)), (t, a, b))) == \ d * Sum(1, (x, a, c)) * Sum(t, (t, a, b)) def test_change_index(): b, v, w = symbols('b, v, w', integer = True) assert Sum(x, (x, a, b)).change_index(x, x + 1, y) == \ Sum(y - 1, (y, a + 1, b + 1)) assert Sum(x**2, (x, a, b)).change_index( x, x - 1) == \ Sum((x+1)**2, (x, a - 1, b - 1)) assert Sum(x**2, (x, a, b)).change_index( x, -x, y) == \ Sum((-y)**2, (y, -b, -a)) assert Sum(x, (x, a, b)).change_index( x, -x - 1) == \ Sum(-x - 1, (x, -b - 1, -a - 1)) assert Sum(x*y, (x, a, b), (y, c, d)).change_index( x, x - 1, z) == \ Sum((z + 1)*y, (z, a - 1, b - 1), (y, c, d)) assert Sum(x, (x, a, b)).change_index( x, x + v) == \ Sum(-v + x, (x, a + v, b + v)) assert Sum(x, (x, a, b)).change_index( x, -x - v) == \ Sum(-v - x, (x, -b - v, -a - v)) assert Sum(x, (x, a, b)).change_index(x, w*x, v) == \ Sum(v/w, (v, b*w, a*w)) raises(ValueError, lambda: Sum(x, (x, a, b)).change_index(x, 2*x)) def test_reorder(): b, y, c, d, z = symbols('b, y, c, d, z', integer = True) assert Sum(x*y, (x, a, b), (y, c, d)).reorder((0, 1)) == \ Sum(x*y, (y, c, d), (x, a, b)) assert Sum(x, (x, a, b), (x, c, d)).reorder((0, 1)) == \ Sum(x, (x, c, d), (x, a, b)) assert Sum(x*y + z, (x, a, b), (z, m, n), (y, c, d)).reorder(\ (2, 0), (0, 1)) == Sum(x*y + z, (z, m, n), (y, c, d), (x, a, b)) assert Sum(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\ (0, 1), (1, 2), (0, 2)) == Sum(x*y*z, (x, a, b), (z, m, n), (y, c, d)) assert Sum(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\ (x, y), (y, z), (x, z)) == Sum(x*y*z, (x, a, b), (z, m, n), (y, c, d)) assert Sum(x*y, (x, a, b), (y, c, d)).reorder((x, 1)) == \ Sum(x*y, (y, c, d), (x, a, b)) assert Sum(x*y, (x, a, b), (y, c, d)).reorder((y, x)) == \ Sum(x*y, (y, c, d), (x, a, b)) def test_reverse_order(): assert Sum(x, (x, 0, 3)).reverse_order(0) == Sum(-x, (x, 4, -1)) assert Sum(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(0, 1) == \ Sum(x*y, (x, 6, 0), (y, 7, -1)) assert Sum(x, (x, 1, 2)).reverse_order(0) == Sum(-x, (x, 3, 0)) assert Sum(x, (x, 1, 3)).reverse_order(0) == Sum(-x, (x, 4, 0)) assert Sum(x, (x, 1, a)).reverse_order(0) == Sum(-x, (x, a + 1, 0)) assert Sum(x, (x, a, 5)).reverse_order(0) == Sum(-x, (x, 6, a - 1)) assert Sum(x, (x, a + 1, a + 5)).reverse_order(0) == \ Sum(-x, (x, a + 6, a)) assert Sum(x, (x, a + 1, a + 2)).reverse_order(0) == \ Sum(-x, (x, a + 3, a)) assert Sum(x, (x, a + 1, a + 1)).reverse_order(0) == \ Sum(-x, (x, a + 2, a)) assert Sum(x, (x, a, b)).reverse_order(0) == Sum(-x, (x, b + 1, a - 1)) assert Sum(x, (x, a, b)).reverse_order(x) == Sum(-x, (x, b + 1, a - 1)) assert Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1) == \ Sum(x*y, (x, b + 1, a - 1), (y, 6, 1)) assert Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x) == \ Sum(x*y, (x, b + 1, a - 1), (y, 6, 1)) def test_issue_7097(): assert sum(x**n/n for n in range(1, 401)) == summation(x**n/n, (n, 1, 400)) def test_factor_expand_subs(): # test factoring assert Sum(4 * x, (x, 1, y)).factor() == 4 * Sum(x, (x, 1, y)) assert Sum(x * a, (x, 1, y)).factor() == a * Sum(x, (x, 1, y)) assert Sum(4 * x * a, (x, 1, y)).factor() == 4 * a * Sum(x, (x, 1, y)) assert Sum(4 * x * y, (x, 1, y)).factor() == 4 * y * Sum(x, (x, 1, y)) # test expand assert Sum(x+1,(x,1,y)).expand() == Sum(x,(x,1,y)) + Sum(1,(x,1,y)) assert Sum(x+a*x**2,(x,1,y)).expand() == Sum(x,(x,1,y)) + Sum(a*x**2,(x,1,y)) assert Sum(x**(n + 1)*(n + 1), (n, -1, oo)).expand() \ == Sum(x*x**n, (n, -1, oo)) + Sum(n*x*x**n, (n, -1, oo)) assert Sum(x**(n + 1)*(n + 1), (n, -1, oo)).expand(power_exp=False) \ == Sum(n*x**(n+1), (n, -1, oo)) + Sum(x**(n+1), (n, -1, oo)) assert Sum(a*n+a*n**2,(n,0,4)).expand() \ == Sum(a*n,(n,0,4)) + Sum(a*n**2,(n,0,4)) assert Sum(x**a*x**n,(x,0,3)) \ == Sum(x**(a+n),(x,0,3)).expand(power_exp=True) assert Sum(x**(a+n),(x,0,3)) \ == Sum(x**(a+n),(x,0,3)).expand(power_exp=False) # test subs assert Sum(1/(1+a*x**2),(x,0,3)).subs([(a,3)]) == Sum(1/(1+3*x**2),(x,0,3)) assert Sum(x*y,(x,0,y),(y,0,x)).subs([(x,3)]) == Sum(x*y,(x,0,y),(y,0,3)) assert Sum(x,(x,1,10)).subs([(x,y-2)]) == Sum(x,(x,1,10)) assert Sum(1/x,(x,1,10)).subs([(x,(3+n)**3)]) == Sum(1/x,(x,1,10)) assert Sum(1/x,(x,1,10)).subs([(x,3*x-2)]) == Sum(1/x,(x,1,10)) def test_distribution_over_equality(): assert Product(Eq(x*2, f(x)), (x, 1, 3)).doit() == Eq(48, f(1)*f(2)*f(3)) assert Sum(Eq(f(x), x**2), (x, 0, y)) == \ Eq(Sum(f(x), (x, 0, y)), Sum(x**2, (x, 0, y))) def test_issue_2787(): n, k = symbols('n k', positive=True, integer=True) p = symbols('p', positive=True) binomial_dist = binomial(n, k)*p**k*(1 - p)**(n - k) s = Sum(binomial_dist*k, (k, 0, n)) res = s.doit().simplify() assert res == Piecewise( (n*p, p/Abs(p - 1) <= 1), ((-p + 1)**n*Sum(k*p**k*binomial(n, k)/(-p + 1)**(k), (k, 0, n)), True)) # Issue #17165: make sure that another simplify does not complicate # the result (but why didn't first simplify handle this?) assert res.simplify() == Piecewise((n*p, p <= S.Half), ((1 - p)**n*Sum(k*p**k*binomial(n, k)/(1 - p)**k, (k, 0, n)), True)) def test_issue_4668(): assert summation(1/n, (n, 2, oo)) is oo def test_matrix_sum(): A = Matrix([[0, 1], [n, 0]]) result = Sum(A, (n, 0, 3)).doit() assert result == Matrix([[0, 4], [6, 0]]) assert result.__class__ == ImmutableDenseMatrix A = SparseMatrix([[0, 1], [n, 0]]) result = Sum(A, (n, 0, 3)).doit() assert result.__class__ == ImmutableSparseMatrix def test_failing_matrix_sum(): n = Symbol('n') # TODO Implement matrix geometric series summation. A = Matrix([[0, 1, 0], [-1, 0, 0], [0, 0, 0]]) assert Sum(A ** n, (n, 1, 4)).doit() == \ Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) # issue sympy/sympy#16989 assert summation(A**n, (n, 1, 1)) == A def test_indexed_idx_sum(): i = symbols('i', cls=Idx) r = Indexed('r', i) assert Sum(r, (i, 0, 3)).doit() == sum([r.xreplace({i: j}) for j in range(4)]) assert Product(r, (i, 0, 3)).doit() == prod([r.xreplace({i: j}) for j in range(4)]) j = symbols('j', integer=True) assert Sum(r, (i, j, j+2)).doit() == sum([r.xreplace({i: j+k}) for k in range(3)]) assert Product(r, (i, j, j+2)).doit() == prod([r.xreplace({i: j+k}) for k in range(3)]) k = Idx('k', range=(1, 3)) A = IndexedBase('A') assert Sum(A[k], k).doit() == sum([A[Idx(j, (1, 3))] for j in range(1, 4)]) assert Product(A[k], k).doit() == prod([A[Idx(j, (1, 3))] for j in range(1, 4)]) raises(ValueError, lambda: Sum(A[k], (k, 1, 4))) raises(ValueError, lambda: Sum(A[k], (k, 0, 3))) raises(ValueError, lambda: Sum(A[k], (k, 2, oo))) raises(ValueError, lambda: Product(A[k], (k, 1, 4))) raises(ValueError, lambda: Product(A[k], (k, 0, 3))) raises(ValueError, lambda: Product(A[k], (k, 2, oo))) @slow def test_is_convergent(): # divergence tests -- assert Sum(n/(2*n + 1), (n, 1, oo)).is_convergent() is S.false assert Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent() is S.false assert Sum(3**(-2*n - 1)*n**n, (n, 1, oo)).is_convergent() is S.false assert Sum((-1)**n*n, (n, 3, oo)).is_convergent() is S.false assert Sum((-1)**n, (n, 1, oo)).is_convergent() is S.false assert Sum(log(1/n), (n, 2, oo)).is_convergent() is S.false # Raabe's test -- assert Sum(Product((3*m),(m,1,n))/Product((3*m+4),(m,1,n)),(n,1,oo)).is_convergent() is S.true # root test -- assert Sum((-12)**n/n, (n, 1, oo)).is_convergent() is S.false # integral test -- # p-series test -- assert Sum(1/(n**2 + 1), (n, 1, oo)).is_convergent() is S.true assert Sum(1/n**Rational(6, 5), (n, 1, oo)).is_convergent() is S.true assert Sum(2/(n*sqrt(n - 1)), (n, 2, oo)).is_convergent() is S.true assert Sum(1/(sqrt(n)*sqrt(n)), (n, 2, oo)).is_convergent() is S.false assert Sum(factorial(n) / factorial(n+2), (n, 1, oo)).is_convergent() is S.true assert Sum(rf(5,n)/rf(7,n),(n,1,oo)).is_convergent() is S.true assert Sum((rf(1, n)*rf(2, n))/(rf(3, n)*factorial(n)),(n,1,oo)).is_convergent() is S.false # comparison test -- assert Sum(1/(n + log(n)), (n, 1, oo)).is_convergent() is S.false assert Sum(1/(n**2*log(n)), (n, 2, oo)).is_convergent() is S.true assert Sum(1/(n*log(n)), (n, 2, oo)).is_convergent() is S.false assert Sum(2/(n*log(n)*log(log(n))**2), (n, 5, oo)).is_convergent() is S.true assert Sum(2/(n*log(n)**2), (n, 2, oo)).is_convergent() is S.true assert Sum((n - 1)/(n**2*log(n)**3), (n, 2, oo)).is_convergent() is S.true assert Sum(1/(n*log(n)*log(log(n))), (n, 5, oo)).is_convergent() is S.false assert Sum((n - 1)/(n*log(n)**3), (n, 3, oo)).is_convergent() is S.false assert Sum(2/(n**2*log(n)), (n, 2, oo)).is_convergent() is S.true assert Sum(1/(n*sqrt(log(n))*log(log(n))), (n, 100, oo)).is_convergent() is S.false assert Sum(log(log(n))/(n*log(n)**2), (n, 100, oo)).is_convergent() is S.true assert Sum(log(n)/n**2, (n, 5, oo)).is_convergent() is S.true # alternating series tests -- assert Sum((-1)**(n - 1)/(n**2 - 1), (n, 3, oo)).is_convergent() is S.true # with -negativeInfinite Limits assert Sum(1/(n**2 + 1), (n, -oo, 1)).is_convergent() is S.true assert Sum(1/(n - 1), (n, -oo, -1)).is_convergent() is S.false assert Sum(1/(n**2 - 1), (n, -oo, -5)).is_convergent() is S.true assert Sum(1/(n**2 - 1), (n, -oo, 2)).is_convergent() is S.true assert Sum(1/(n**2 - 1), (n, -oo, oo)).is_convergent() is S.true # piecewise functions f = Piecewise((n**(-2), n <= 1), (n**2, n > 1)) assert Sum(f, (n, 1, oo)).is_convergent() is S.false assert Sum(f, (n, -oo, oo)).is_convergent() is S.false assert Sum(f, (n, 1, 100)).is_convergent() is S.true #assert Sum(f, (n, -oo, 1)).is_convergent() is S.true # integral test assert Sum(log(n)/n**3, (n, 1, oo)).is_convergent() is S.true assert Sum(-log(n)/n**3, (n, 1, oo)).is_convergent() is S.true # the following function has maxima located at (x, y) = # (1.2, 0.43), (3.0, -0.25) and (6.8, 0.050) eq = (x - 2)*(x**2 - 6*x + 4)*exp(-x) assert Sum(eq, (x, 1, oo)).is_convergent() is S.true assert Sum(eq, (x, 1, 2)).is_convergent() is S.true assert Sum(1/(x**3), (x, 1, oo)).is_convergent() is S.true assert Sum(1/(x**S.Half), (x, 1, oo)).is_convergent() is S.false # issue 19545 assert Sum(1/n - 3/(3*n +2), (n, 1, oo)).is_convergent() is S.true # issue 19836 assert Sum(4/(n + 2) - 5/(n + 1) + 1/n,(n, 7, oo)).is_convergent() is S.true def test_is_absolutely_convergent(): assert Sum((-1)**n, (n, 1, oo)).is_absolutely_convergent() is S.false assert Sum((-1)**n/n**2, (n, 1, oo)).is_absolutely_convergent() is S.true @XFAIL def test_convergent_failing(): # dirichlet tests assert Sum(sin(n)/n, (n, 1, oo)).is_convergent() is S.true assert Sum(sin(2*n)/n, (n, 1, oo)).is_convergent() is S.true def test_issue_6966(): i, k, m = symbols('i k m', integer=True) z_i, q_i = symbols('z_i q_i') a_k = Sum(-q_i*z_i/k,(i,1,m)) b_k = a_k.diff(z_i) assert isinstance(b_k, Sum) assert b_k == Sum(-q_i/k,(i,1,m)) def test_issue_10156(): cx = Sum(2*y**2*x, (x, 1,3)) e = 2*y*Sum(2*cx*x**2, (x, 1, 9)) assert e.factor() == \ 8*y**3*Sum(x, (x, 1, 3))*Sum(x**2, (x, 1, 9)) def test_issue_10973(): assert Sum((-n + (n**3 + 1)**(S(1)/3))/log(n), (n, 1, oo)).is_convergent() is S.true def test_issue_14129(): assert Sum( k*x**k, (k, 0, n-1)).doit() == \ Piecewise((n**2/2 - n/2, Eq(x, 1)), ((n*x*x**n - n*x**n - x*x**n + x)/(x - 1)**2, True)) assert Sum( x**k, (k, 0, n-1)).doit() == \ Piecewise((n, Eq(x, 1)), ((-x**n + 1)/(-x + 1), True)) assert Sum( k*(x/y+x)**k, (k, 0, n-1)).doit() == \ Piecewise((n*(n - 1)/2, Eq(x, y/(y + 1))), (x*(y + 1)*(n*x*y*(x + x/y)**n/(x + x/y) + n*x*(x + x/y)**n/(x + x/y) - n*y*(x + x/y)**n/(x + x/y) - x*y*(x + x/y)**n/(x + x/y) - x*(x + x/y)**n/(x + x/y) + y)/(x*y + x - y)**2, True)) def test_issue_14112(): assert Sum((-1)**n/sqrt(n), (n, 1, oo)).is_absolutely_convergent() is S.false assert Sum((-1)**(2*n)/n, (n, 1, oo)).is_convergent() is S.false assert Sum((-2)**n + (-3)**n, (n, 1, oo)).is_convergent() is S.false def test_sin_times_absolutely_convergent(): assert Sum(sin(n) / n**3, (n, 1, oo)).is_convergent() is S.true assert Sum(sin(n) * log(n) / n**3, (n, 1, oo)).is_convergent() is S.true def test_issue_14111(): assert Sum(1/log(log(n)), (n, 22, oo)).is_convergent() is S.false def test_issue_14484(): assert Sum(sin(n)/log(log(n)), (n, 22, oo)).is_convergent() is S.false def test_issue_14640(): i, n = symbols("i n", integer=True) a, b, c = symbols("a b c") assert Sum(a**-i/(a - b), (i, 0, n)).doit() == Sum( 1/(a*a**i - a**i*b), (i, 0, n)).doit() == Piecewise( (n + 1, Eq(1/a, 1)), ((-a**(-n - 1) + 1)/(1 - 1/a), True))/(a - b) assert Sum((b*a**i - c*a**i)**-2, (i, 0, n)).doit() == Piecewise( (n + 1, Eq(a**(-2), 1)), ((-a**(-2*n - 2) + 1)/(1 - 1/a**2), True))/(b - c)**2 s = Sum(i*(a**(n - i) - b**(n - i))/(a - b), (i, 0, n)).doit() assert not s.has(Sum) assert s.subs({a: 2, b: 3, n: 5}) == 122 def test_issue_15943(): s = Sum(binomial(n, k)*factorial(n - k), (k, 0, n)).doit().rewrite(gamma) assert s == -E*(n + 1)*gamma(n + 1)*lowergamma(n + 1, 1)/gamma(n + 2 ) + E*gamma(n + 1) assert s.simplify() == E*(factorial(n) - lowergamma(n + 1, 1)) def test_Sum_dummy_eq(): assert not Sum(x, (x, a, b)).dummy_eq(1) assert not Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, b), (a, 1, 2))) assert not Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, c))) assert Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, b))) d = Dummy() assert Sum(x, (x, a, d)).dummy_eq(Sum(x, (x, a, c)), c) assert not Sum(x, (x, a, d)).dummy_eq(Sum(x, (x, a, c))) assert Sum(x, (x, a, c)).dummy_eq(Sum(y, (y, a, c))) assert Sum(x, (x, a, d)).dummy_eq(Sum(y, (y, a, c)), c) assert not Sum(x, (x, a, d)).dummy_eq(Sum(y, (y, a, c))) def test_issue_15852(): assert summation(x**y*y, (y, -oo, oo)).doit() == Sum(x**y*y, (y, -oo, oo)) def test_exceptions(): S = Sum(x, (x, a, b)) raises(ValueError, lambda: S.change_index(x, x**2, y)) S = Sum(x, (x, a, b), (x, 1, 4)) raises(ValueError, lambda: S.index(x)) S = Sum(x, (x, a, b), (y, 1, 4)) raises(ValueError, lambda: S.reorder([x])) S = Sum(x, (x, y, b), (y, 1, 4)) raises(ReorderError, lambda: S.reorder_limit(0, 1)) S = Sum(x*y, (x, a, b), (y, 1, 4)) raises(NotImplementedError, lambda: S.is_convergent()) def test_sumproducts_assumptions(): M = Symbol('M', integer=True, positive=True) m = Symbol('m', integer=True) for func in [Sum, Product]: assert func(m, (m, -M, M)).is_positive is None assert func(m, (m, -M, M)).is_nonpositive is None assert func(m, (m, -M, M)).is_negative is None assert func(m, (m, -M, M)).is_nonnegative is None assert func(m, (m, -M, M)).is_finite is True m = Symbol('m', integer=True, nonnegative=True) for func in [Sum, Product]: assert func(m, (m, 0, M)).is_positive is None assert func(m, (m, 0, M)).is_nonpositive is None assert func(m, (m, 0, M)).is_negative is False assert func(m, (m, 0, M)).is_nonnegative is True assert func(m, (m, 0, M)).is_finite is True m = Symbol('m', integer=True, positive=True) for func in [Sum, Product]: assert func(m, (m, 1, M)).is_positive is True assert func(m, (m, 1, M)).is_nonpositive is False assert func(m, (m, 1, M)).is_negative is False assert func(m, (m, 1, M)).is_nonnegative is True assert func(m, (m, 1, M)).is_finite is True m = Symbol('m', integer=True, negative=True) assert Sum(m, (m, -M, -1)).is_positive is False assert Sum(m, (m, -M, -1)).is_nonpositive is True assert Sum(m, (m, -M, -1)).is_negative is True assert Sum(m, (m, -M, -1)).is_nonnegative is False assert Sum(m, (m, -M, -1)).is_finite is True assert Product(m, (m, -M, -1)).is_positive is None assert Product(m, (m, -M, -1)).is_nonpositive is None assert Product(m, (m, -M, -1)).is_negative is None assert Product(m, (m, -M, -1)).is_nonnegative is None assert Product(m, (m, -M, -1)).is_finite is True m = Symbol('m', integer=True, nonpositive=True) assert Sum(m, (m, -M, 0)).is_positive is False assert Sum(m, (m, -M, 0)).is_nonpositive is True assert Sum(m, (m, -M, 0)).is_negative is None assert Sum(m, (m, -M, 0)).is_nonnegative is None assert Sum(m, (m, -M, 0)).is_finite is True assert Product(m, (m, -M, 0)).is_positive is None assert Product(m, (m, -M, 0)).is_nonpositive is None assert Product(m, (m, -M, 0)).is_negative is None assert Product(m, (m, -M, 0)).is_nonnegative is None assert Product(m, (m, -M, 0)).is_finite is True m = Symbol('m', integer=True) assert Sum(2, (m, 0, oo)).is_positive is None assert Sum(2, (m, 0, oo)).is_nonpositive is None assert Sum(2, (m, 0, oo)).is_negative is None assert Sum(2, (m, 0, oo)).is_nonnegative is None assert Sum(2, (m, 0, oo)).is_finite is None assert Product(2, (m, 0, oo)).is_positive is None assert Product(2, (m, 0, oo)).is_nonpositive is None assert Product(2, (m, 0, oo)).is_negative is False assert Product(2, (m, 0, oo)).is_nonnegative is None assert Product(2, (m, 0, oo)).is_finite is None assert Product(0, (x, M, M-1)).is_positive is True assert Product(0, (x, M, M-1)).is_finite is True def test_expand_with_assumptions(): M = Symbol('M', integer=True, positive=True) x = Symbol('x', positive=True) m = Symbol('m', nonnegative=True) assert log(Product(x**m, (m, 0, M))).expand() == Sum(m*log(x), (m, 0, M)) assert log(Product(exp(x**m), (m, 0, M))).expand() == Sum(x**m, (m, 0, M)) assert log(Product(x**m, (m, 0, M))).rewrite(Sum).expand() == Sum(m*log(x), (m, 0, M)) assert log(Product(exp(x**m), (m, 0, M))).rewrite(Sum).expand() == Sum(x**m, (m, 0, M)) n = Symbol('n', nonnegative=True) i, j = symbols('i,j', positive=True, integer=True) x, y = symbols('x,y', positive=True) assert log(Product(x**i*y**j, (i, 1, n), (j, 1, m))).expand() \ == Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m)) def test_has_finite_limits(): x = Symbol('x') assert Sum(1, (x, 1, 9)).has_finite_limits is True assert Sum(1, (x, 1, oo)).has_finite_limits is False M = Symbol('M') assert Sum(1, (x, 1, M)).has_finite_limits is None M = Symbol('M', positive=True) assert Sum(1, (x, 1, M)).has_finite_limits is True x = Symbol('x', positive=True) M = Symbol('M') assert Sum(1, (x, 1, M)).has_finite_limits is True assert Sum(1, (x, 1, M), (y, -oo, oo)).has_finite_limits is False def test_has_reversed_limits(): assert Sum(1, (x, 1, 1)).has_reversed_limits is False assert Sum(1, (x, 1, 9)).has_reversed_limits is False assert Sum(1, (x, 1, -9)).has_reversed_limits is True assert Sum(1, (x, 1, 0)).has_reversed_limits is True assert Sum(1, (x, 1, oo)).has_reversed_limits is False M = Symbol('M') assert Sum(1, (x, 1, M)).has_reversed_limits is None M = Symbol('M', positive=True, integer=True) assert Sum(1, (x, 1, M)).has_reversed_limits is False assert Sum(1, (x, 1, M), (y, -oo, oo)).has_reversed_limits is False M = Symbol('M', negative=True) assert Sum(1, (x, 1, M)).has_reversed_limits is True assert Sum(1, (x, 1, M), (y, -oo, oo)).has_reversed_limits is True assert Sum(1, (x, oo, oo)).has_reversed_limits is None def test_has_empty_sequence(): assert Sum(1, (x, 1, 1)).has_empty_sequence is False assert Sum(1, (x, 1, 9)).has_empty_sequence is False assert Sum(1, (x, 1, -9)).has_empty_sequence is False assert Sum(1, (x, 1, 0)).has_empty_sequence is True assert Sum(1, (x, y, y - 1)).has_empty_sequence is True assert Sum(1, (x, 3, 2), (y, -oo, oo)).has_empty_sequence is True assert Sum(1, (y, -oo, oo), (x, 3, 2)).has_empty_sequence is True assert Sum(1, (x, oo, oo)).has_empty_sequence is False def test_empty_sequence(): assert Product(x*y, (x, -oo, oo), (y, 1, 0)).doit() == 1 assert Product(x*y, (y, 1, 0), (x, -oo, oo)).doit() == 1 assert Sum(x, (x, -oo, oo), (y, 1, 0)).doit() == 0 assert Sum(x, (y, 1, 0), (x, -oo, oo)).doit() == 0 def test_issue_8016(): k = Symbol('k', integer=True) n, m = symbols('n, m', integer=True, positive=True) s = Sum(binomial(m, k)*binomial(m, n - k)*(-1)**k, (k, 0, n)) assert s.doit().simplify() == \ cos(pi*n/2)*gamma(m + 1)/gamma(n/2 + 1)/gamma(m - n/2 + 1) def test_issue_14313(): assert Sum(S.Half**floor(n/2), (n, 1, oo)).is_convergent() def test_issue_14563(): # The assertion was failing due to no assumptions methods in Sums and Product assert 1 % Sum(1, (x, 0, 1)) == 1 def test_issue_16735(): assert Sum(5**n/gamma(n+1), (n, 1, oo)).is_convergent() is S.true def test_issue_14871(): assert Sum((Rational(1, 10))**n*rf(0, n)/factorial(n), (n, 0, oo)).rewrite(factorial).doit() == 1 def test_issue_17165(): n = symbols("n", integer=True) x = symbols('x') s = (x*Sum(x**n, (n, -1, oo))) ssimp = s.doit().simplify() assert ssimp == Piecewise((-1/(x - 1), (x > -1) & (x < 1)), (x*Sum(x**n, (n, -1, oo)), True)), ssimp assert ssimp.simplify() == ssimp def test_issue_19379(): assert Sum(factorial(n)/factorial(n + 2), (n, 1, oo)).is_convergent() is S.true def test_issue_20777(): assert Sum(exp(x*sin(n/m)), (n, 1, m)).doit() == Sum(exp(x*sin(n/m)), (n, 1, m)) def test__dummy_with_inherited_properties_concrete(): x = Symbol('x') from sympy.core.containers import Tuple d = _dummy_with_inherited_properties_concrete(Tuple(x, 0, 5)) assert d.is_real assert d.is_integer assert d.is_nonnegative assert d.is_extended_nonnegative d = _dummy_with_inherited_properties_concrete(Tuple(x, 1, 9)) assert d.is_real assert d.is_integer assert d.is_positive assert d.is_odd is None d = _dummy_with_inherited_properties_concrete(Tuple(x, -5, 5)) assert d.is_real assert d.is_integer assert d.is_positive is None assert d.is_extended_nonnegative is None assert d.is_odd is None d = _dummy_with_inherited_properties_concrete(Tuple(x, -1.5, 1.5)) assert d.is_real assert d.is_integer is None assert d.is_positive is None assert d.is_extended_nonnegative is None N = Symbol('N', integer=True, positive=True) d = _dummy_with_inherited_properties_concrete(Tuple(x, 2, N)) assert d.is_real assert d.is_positive assert d.is_integer # Return None if no assumptions are added N = Symbol('N', integer=True, positive=True) d = _dummy_with_inherited_properties_concrete(Tuple(N, 2, 4)) assert d is None x = Symbol('x', negative=True) raises(InconsistentAssumptions, lambda: _dummy_with_inherited_properties_concrete(Tuple(x, 1, 5))) def test_matrixsymbol_summation_numerical_limits(): A = MatrixSymbol('A', 3, 3) n = Symbol('n', integer=True) assert Sum(A**n, (n, 0, 2)).doit() == Identity(3) + A + A**2 assert Sum(A, (n, 0, 2)).doit() == 3*A assert Sum(n*A, (n, 0, 2)).doit() == 3*A B = Matrix([[0, n, 0], [-1, 0, 0], [0, 0, 2]]) ans = Matrix([[0, 6, 0], [-4, 0, 0], [0, 0, 8]]) + 4*A assert Sum(A+B, (n, 0, 3)).doit() == ans ans = A*Matrix([[0, 6, 0], [-4, 0, 0], [0, 0, 8]]) assert Sum(A*B, (n, 0, 3)).doit() == ans ans = (A**2*Matrix([[-2, 0, 0], [0,-2, 0], [0, 0, 4]]) + A**3*Matrix([[0, -9, 0], [3, 0, 0], [0, 0, 8]]) + A*Matrix([[0, 1, 0], [-1, 0, 0], [0, 0, 2]])) assert Sum(A**n*B**n, (n, 1, 3)).doit() == ans def test_issue_21651(): i = Symbol('i') a = Sum(floor(2*2**(-i)), (i, S.One, 2)) assert a.doit() == S.One @XFAIL def test_matrixsymbol_summation_symbolic_limits(): N = Symbol('N', integer=True, positive=True) A = MatrixSymbol('A', 3, 3) n = Symbol('n', integer=True) assert Sum(A, (n, 0, N)).doit() == (N+1)*A assert Sum(n*A, (n, 0, N)).doit() == (N**2/2+N/2)*A def test_summation_by_residues(): x = Symbol('x') # Examples from Nakhle H. Asmar, Loukas Grafakos, # Complex Analysis with Applications assert eval_sum_residue(1 / (x**2 + 1), (x, -oo, oo)) == pi/tanh(pi) assert eval_sum_residue(1 / x**6, (x, S(1), oo)) == pi**6/945 assert eval_sum_residue(1 / (x**2 + 9), (x, -oo, oo)) == pi/(3*tanh(3*pi)) assert eval_sum_residue(1 / (x**2 + 1)**2, (x, -oo, oo)).cancel() == \ (-pi**2*tanh(pi)**2 + pi*tanh(pi) + pi**2)/(2*tanh(pi)**2) assert eval_sum_residue(x**2 / (x**2 + 1)**2, (x, -oo, oo)).cancel() == \ (-pi**2 + pi*tanh(pi) + pi**2*tanh(pi)**2)/(2*tanh(pi)**2) assert eval_sum_residue(1 / (4*x**2 - 1), (x, -oo, oo)) == 0 assert eval_sum_residue(x**2 / (x**2 - S(1)/4)**2, (x, -oo, oo)) == pi**2/2 assert eval_sum_residue(1 / (4*x**2 - 1)**2, (x, -oo, oo)) == pi**2/8 assert eval_sum_residue(1 / ((x - S(1)/2)**2 + 1), (x, -oo, oo)) == pi*tanh(pi) assert eval_sum_residue(1 / x**2, (x, S(1), oo)) == pi**2/6 assert eval_sum_residue(1 / x**4, (x, S(1), oo)) == pi**4/90 assert eval_sum_residue(1 / x**2 / (x**2 + 4), (x, S(1), oo)) == \ -pi*(-pi/12 - 1/(16*pi) + 1/(8*tanh(2*pi)))/2 # Some examples made from 1 / (x**2 + 1) assert eval_sum_residue(1 / (x**2 + 1), (x, S(0), oo)) == \ S(1)/2 + pi/(2*tanh(pi)) assert eval_sum_residue(1 / (x**2 + 1), (x, S(1), oo)) == \ -S(1)/2 + pi/(2*tanh(pi)) assert eval_sum_residue(1 / (x**2 + 1), (x, S(-1), oo)) == \ 1 + pi/(2*tanh(pi)) assert eval_sum_residue((-1)**x / (x**2 + 1), (x, -oo, oo)) == \ pi/sinh(pi) assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(0), oo)) == \ pi/(2*sinh(pi)) + S(1)/2 assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(1), oo)) == \ -S(1)/2 + pi/(2*sinh(pi)) assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(-1), oo)) == \ pi/(2*sinh(pi)) # Some examples made from shifting of 1 / (x**2 + 1) assert eval_sum_residue(1 / (x**2 + 2*x + 2), (x, S(-1), oo)) == S(1)/2 + pi/(2*tanh(pi)) assert eval_sum_residue(1 / (x**2 + 4*x + 5), (x, S(-2), oo)) == S(1)/2 + pi/(2*tanh(pi)) assert eval_sum_residue(1 / (x**2 - 2*x + 2), (x, S(1), oo)) == S(1)/2 + pi/(2*tanh(pi)) assert eval_sum_residue(1 / (x**2 - 4*x + 5), (x, S(2), oo)) == S(1)/2 + pi/(2*tanh(pi)) assert eval_sum_residue((-1)**x * -1 / (x**2 + 2*x + 2), (x, S(-1), oo)) == S(1)/2 + pi/(2*sinh(pi)) assert eval_sum_residue((-1)**x * -1 / (x**2 -2*x + 2), (x, S(1), oo)) == S(1)/2 + pi/(2*sinh(pi)) # Some examples made from 1 / x**2 assert eval_sum_residue(1 / x**2, (x, S(2), oo)) == -1 + pi**2/6 assert eval_sum_residue(1 / x**2, (x, S(3), oo)) == -S(5)/4 + pi**2/6 assert eval_sum_residue((-1)**x / x**2, (x, S(1), oo)) == -pi**2/12 assert eval_sum_residue((-1)**x / x**2, (x, S(2), oo)) == 1 - pi**2/12 @slow def test_summation_by_residues_failing(): x = Symbol('x') # Failing because of the bug in residue computation assert eval_sum_residue(x**2 / (x**4 + 1), (x, S(1), oo)) assert eval_sum_residue(1 / ((x - 1)*(x - 2) + 1), (x, -oo, oo)) != 0 def test_process_limits(): from sympy.concrete.expr_with_limits import _process_limits # these should be (x, Range(3)) not Range(3) raises(ValueError, lambda: _process_limits( Range(3), discrete=True)) raises(ValueError, lambda: _process_limits( Range(3), discrete=False)) # these should be (x, union) not union # (but then we would get a TypeError because we don't # handle non-contiguous sets: see below use of `union`) union = Or(x < 1, x > 3).as_set() raises(ValueError, lambda: _process_limits( union, discrete=True)) raises(ValueError, lambda: _process_limits( union, discrete=False)) # error not triggered if not needed assert _process_limits((x, 1, 2)) == ([(x, 1, 2)], 1) # this equivalence is used to detect Reals in _process_limits assert isinstance(S.Reals, Interval) C = Integral # continuous limits assert C(x, x >= 5) == C(x, (x, 5, oo)) assert C(x, x < 3) == C(x, (x, -oo, 3)) ans = C(x, (x, 0, 3)) assert C(x, And(x >= 0, x < 3)) == ans assert C(x, (x, Interval.Ropen(0, 3))) == ans raises(TypeError, lambda: C(x, (x, Range(3)))) # discrete limits for D in (Sum, Product): r, ans = Range(3, 10, 2), D(2*x + 3, (x, 0, 3)) assert D(x, (x, r)) == ans assert D(x, (x, r.reversed)) == ans r, ans = Range(3, oo, 2), D(2*x + 3, (x, 0, oo)) assert D(x, (x, r)) == ans assert D(x, (x, r.reversed)) == ans r, ans = Range(-oo, 5, 2), D(3 - 2*x, (x, 0, oo)) assert D(x, (x, r)) == ans assert D(x, (x, r.reversed)) == ans raises(TypeError, lambda: D(x, x > 0)) raises(ValueError, lambda: D(x, Interval(1, 3))) raises(NotImplementedError, lambda: D(x, (x, union)))
9c24c29605fb650513b7573433bdd02791b2ea55f7ba018b36fe3e2bbf449bb9
# This testfile tests SymPy <-> NumPy compatibility # Don't test any SymPy features here. Just pure interaction with NumPy. # Always write regular SymPy tests for anything, that can be tested in pure # Python (without numpy). Here we test everything, that a user may need when # using SymPy with NumPy from sympy.external.importtools import version_tuple from sympy.external import import_module numpy = import_module('numpy') if numpy: array, matrix, ndarray = numpy.array, numpy.matrix, numpy.ndarray else: #bin/test will not execute any tests now disabled = True from sympy.core.numbers import (Float, Integer, Rational) from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.trigonometric import sin from sympy.matrices.dense import (Matrix, list2numpy, matrix2numpy, symarray) from sympy.utilities.lambdify import lambdify import sympy import mpmath from sympy.abc import x, y, z from sympy.utilities.decorator import conserve_mpmath_dps from sympy.testing.pytest import raises # first, systematically check, that all operations are implemented and don't # raise an exception def test_systematic_basic(): def s(sympy_object, numpy_array): _ = [sympy_object + numpy_array, numpy_array + sympy_object, sympy_object - numpy_array, numpy_array - sympy_object, sympy_object * numpy_array, numpy_array * sympy_object, sympy_object / numpy_array, numpy_array / sympy_object, sympy_object ** numpy_array, numpy_array ** sympy_object] x = Symbol("x") y = Symbol("y") sympy_objs = [ Rational(2, 3), Float("1.3"), x, y, pow(x, y)*y, Integer(5), Float(5.5), ] numpy_objs = [ array([1]), array([3, 8, -1]), array([x, x**2, Rational(5)]), array([x/y*sin(y), 5, Rational(5)]), ] for x in sympy_objs: for y in numpy_objs: s(x, y) # now some random tests, that test particular problems and that also # check that the results of the operations are correct def test_basics(): one = Rational(1) zero = Rational(0) assert array(1) == array(one) assert array([one]) == array([one]) assert array([x]) == array([x]) assert array(x) == array(Symbol("x")) assert array(one + x) == array(1 + x) X = array([one, zero, zero]) assert (X == array([one, zero, zero])).all() assert (X == array([one, 0, 0])).all() def test_arrays(): one = Rational(1) zero = Rational(0) X = array([one, zero, zero]) Y = one*X X = array([Symbol("a") + Rational(1, 2)]) Y = X + X assert Y == array([1 + 2*Symbol("a")]) Y = Y + 1 assert Y == array([2 + 2*Symbol("a")]) Y = X - X assert Y == array([0]) def test_conversion1(): a = list2numpy([x**2, x]) #looks like an array? assert isinstance(a, ndarray) assert a[0] == x**2 assert a[1] == x assert len(a) == 2 #yes, it's the array def test_conversion2(): a = 2*list2numpy([x**2, x]) b = list2numpy([2*x**2, 2*x]) assert (a == b).all() one = Rational(1) zero = Rational(0) X = list2numpy([one, zero, zero]) Y = one*X X = list2numpy([Symbol("a") + Rational(1, 2)]) Y = X + X assert Y == array([1 + 2*Symbol("a")]) Y = Y + 1 assert Y == array([2 + 2*Symbol("a")]) Y = X - X assert Y == array([0]) def test_list2numpy(): assert (array([x**2, x]) == list2numpy([x**2, x])).all() def test_Matrix1(): m = Matrix([[x, x**2], [5, 2/x]]) assert (array(m.subs(x, 2)) == array([[2, 4], [5, 1]])).all() m = Matrix([[sin(x), x**2], [5, 2/x]]) assert (array(m.subs(x, 2)) == array([[sin(2), 4], [5, 1]])).all() def test_Matrix2(): m = Matrix([[x, x**2], [5, 2/x]]) assert (matrix(m.subs(x, 2)) == matrix([[2, 4], [5, 1]])).all() m = Matrix([[sin(x), x**2], [5, 2/x]]) assert (matrix(m.subs(x, 2)) == matrix([[sin(2), 4], [5, 1]])).all() def test_Matrix3(): a = array([[2, 4], [5, 1]]) assert Matrix(a) == Matrix([[2, 4], [5, 1]]) assert Matrix(a) != Matrix([[2, 4], [5, 2]]) a = array([[sin(2), 4], [5, 1]]) assert Matrix(a) == Matrix([[sin(2), 4], [5, 1]]) assert Matrix(a) != Matrix([[sin(0), 4], [5, 1]]) def test_Matrix4(): a = matrix([[2, 4], [5, 1]]) assert Matrix(a) == Matrix([[2, 4], [5, 1]]) assert Matrix(a) != Matrix([[2, 4], [5, 2]]) a = matrix([[sin(2), 4], [5, 1]]) assert Matrix(a) == Matrix([[sin(2), 4], [5, 1]]) assert Matrix(a) != Matrix([[sin(0), 4], [5, 1]]) def test_Matrix_sum(): M = Matrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]]) m = matrix([[2, 3, 4], [x, 5, 6], [x, y, z**2]]) assert M + m == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]]) assert m + M == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]]) assert M + m == M.add(m) def test_Matrix_mul(): M = Matrix([[1, 2, 3], [x, y, x]]) m = matrix([[2, 4], [x, 6], [x, z**2]]) assert M*m == Matrix([ [ 2 + 5*x, 16 + 3*z**2], [2*x + x*y + x**2, 4*x + 6*y + x*z**2], ]) assert m*M == Matrix([ [ 2 + 4*x, 4 + 4*y, 6 + 4*x], [ 7*x, 2*x + 6*y, 9*x], [x + x*z**2, 2*x + y*z**2, 3*x + x*z**2], ]) a = array([2]) assert a[0] * M == 2 * M assert M * a[0] == 2 * M def test_Matrix_array(): class matarray: def __array__(self): from numpy import array return array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) matarr = matarray() assert Matrix(matarr) == Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) def test_matrix2numpy(): a = matrix2numpy(Matrix([[1, x**2], [3*sin(x), 0]])) assert isinstance(a, ndarray) assert a.shape == (2, 2) assert a[0, 0] == 1 assert a[0, 1] == x**2 assert a[1, 0] == 3*sin(x) assert a[1, 1] == 0 def test_matrix2numpy_conversion(): a = Matrix([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]]) b = array([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]]) assert (matrix2numpy(a) == b).all() assert matrix2numpy(a).dtype == numpy.dtype('object') c = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='int8') d = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='float64') assert c.dtype == numpy.dtype('int8') assert d.dtype == numpy.dtype('float64') def test_issue_3728(): assert (Rational(1, 2)*array([2*x, 0]) == array([x, 0])).all() assert (Rational(1, 2) + array( [2*x, 0]) == array([2*x + Rational(1, 2), Rational(1, 2)])).all() assert (Float("0.5")*array([2*x, 0]) == array([Float("1.0")*x, 0])).all() assert (Float("0.5") + array( [2*x, 0]) == array([2*x + Float("0.5"), Float("0.5")])).all() @conserve_mpmath_dps def test_lambdify(): mpmath.mp.dps = 16 sin02 = mpmath.mpf("0.198669330795061215459412627") f = lambdify(x, sin(x), "numpy") prec = 1e-15 assert -prec < f(0.2) - sin02 < prec # if this succeeds, it can't be a numpy function if version_tuple(numpy.__version__) >= version_tuple('1.17'): with raises(TypeError): f(x) else: with raises(AttributeError): f(x) def test_lambdify_matrix(): f = lambdify(x, Matrix([[x, 2*x], [1, 2]]), [{'ImmutableMatrix': numpy.array}, "numpy"]) assert (f(1) == array([[1, 2], [1, 2]])).all() def test_lambdify_matrix_multi_input(): M = sympy.Matrix([[x**2, x*y, x*z], [y*x, y**2, y*z], [z*x, z*y, z**2]]) f = lambdify((x, y, z), M, [{'ImmutableMatrix': numpy.array}, "numpy"]) xh, yh, zh = 1.0, 2.0, 3.0 expected = array([[xh**2, xh*yh, xh*zh], [yh*xh, yh**2, yh*zh], [zh*xh, zh*yh, zh**2]]) actual = f(xh, yh, zh) assert numpy.allclose(actual, expected) def test_lambdify_matrix_vec_input(): X = sympy.DeferredVector('X') M = Matrix([ [X[0]**2, X[0]*X[1], X[0]*X[2]], [X[1]*X[0], X[1]**2, X[1]*X[2]], [X[2]*X[0], X[2]*X[1], X[2]**2]]) f = lambdify(X, M, [{'ImmutableMatrix': numpy.array}, "numpy"]) Xh = array([1.0, 2.0, 3.0]) expected = array([[Xh[0]**2, Xh[0]*Xh[1], Xh[0]*Xh[2]], [Xh[1]*Xh[0], Xh[1]**2, Xh[1]*Xh[2]], [Xh[2]*Xh[0], Xh[2]*Xh[1], Xh[2]**2]]) actual = f(Xh) assert numpy.allclose(actual, expected) def test_lambdify_transl(): from sympy.utilities.lambdify import NUMPY_TRANSLATIONS for sym, mat in NUMPY_TRANSLATIONS.items(): assert sym in sympy.__dict__ assert mat in numpy.__dict__ def test_symarray(): """Test creation of numpy arrays of SymPy symbols.""" import numpy as np import numpy.testing as npt syms = symbols('_0,_1,_2') s1 = symarray("", 3) s2 = symarray("", 3) npt.assert_array_equal(s1, np.array(syms, dtype=object)) assert s1[0] == s2[0] a = symarray('a', 3) b = symarray('b', 3) assert not(a[0] == b[0]) asyms = symbols('a_0,a_1,a_2') npt.assert_array_equal(a, np.array(asyms, dtype=object)) # Multidimensional checks a2d = symarray('a', (2, 3)) assert a2d.shape == (2, 3) a00, a12 = symbols('a_0_0,a_1_2') assert a2d[0, 0] == a00 assert a2d[1, 2] == a12 a3d = symarray('a', (2, 3, 2)) assert a3d.shape == (2, 3, 2) a000, a120, a121 = symbols('a_0_0_0,a_1_2_0,a_1_2_1') assert a3d[0, 0, 0] == a000 assert a3d[1, 2, 0] == a120 assert a3d[1, 2, 1] == a121 def test_vectorize(): assert (numpy.vectorize( sin)([1, 2, 3]) == numpy.array([sin(1), sin(2), sin(3)])).all()
1ecdebead30f0ce8615374aa5704ad431c0b13ca686d708d911c7c342731a739
from sympy.core.add import Add from sympy.core.symbol import Symbol from sympy.series.order import O x = Symbol('x') l = list(x**i for i in range(1000)) l.append(O(x**1001)) def timeit_order_1x(): Add(*l)
1a5c5b1a4d6e04f0ada4244a5c6996a91bf3e33c5e3a8e5ea09547b8fe06cb52
from sympy.concrete.summations import Sum from sympy.core.add import Add from sympy.core.numbers import (I, Rational, oo, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.combinatorial.factorials import (binomial, factorial, subfactorial) from sympy.functions.combinatorial.numbers import (fibonacci, harmonic) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.gamma_functions import gamma from sympy.series.limitseq import limit_seq from sympy.series.limitseq import difference_delta as dd from sympy.testing.pytest import raises, XFAIL from sympy.calculus.accumulationbounds import AccumulationBounds n, m, k = symbols('n m k', integer=True) def test_difference_delta(): e = n*(n + 1) e2 = e * k assert dd(e) == 2*n + 2 assert dd(e2, n, 2) == k*(4*n + 6) raises(ValueError, lambda: dd(e2)) raises(ValueError, lambda: dd(e2, n, oo)) def test_difference_delta__Sum(): e = Sum(1/k, (k, 1, n)) assert dd(e, n) == 1/(n + 1) assert dd(e, n, 5) == Add(*[1/(i + n + 1) for i in range(5)]) e = Sum(1/k, (k, 1, 3*n)) assert dd(e, n) == Add(*[1/(i + 3*n + 1) for i in range(3)]) e = n * Sum(1/k, (k, 1, n)) assert dd(e, n) == 1 + Sum(1/k, (k, 1, n)) e = Sum(1/k, (k, 1, n), (m, 1, n)) assert dd(e, n) == harmonic(n) def test_difference_delta__Add(): e = n + n*(n + 1) assert dd(e, n) == 2*n + 3 assert dd(e, n, 2) == 4*n + 8 e = n + Sum(1/k, (k, 1, n)) assert dd(e, n) == 1 + 1/(n + 1) assert dd(e, n, 5) == 5 + Add(*[1/(i + n + 1) for i in range(5)]) def test_difference_delta__Pow(): e = 4**n assert dd(e, n) == 3*4**n assert dd(e, n, 2) == 15*4**n e = 4**(2*n) assert dd(e, n) == 15*4**(2*n) assert dd(e, n, 2) == 255*4**(2*n) e = n**4 assert dd(e, n) == (n + 1)**4 - n**4 e = n**n assert dd(e, n) == (n + 1)**(n + 1) - n**n def test_limit_seq(): e = binomial(2*n, n) / Sum(binomial(2*k, k), (k, 1, n)) assert limit_seq(e) == S(3) / 4 assert limit_seq(e, m) == e e = (5*n**3 + 3*n**2 + 4) / (3*n**3 + 4*n - 5) assert limit_seq(e, n) == S(5) / 3 e = (harmonic(n) * Sum(harmonic(k), (k, 1, n))) / (n * harmonic(2*n)**2) assert limit_seq(e, n) == 1 e = Sum(k**2 * Sum(2**m/m, (m, 1, k)), (k, 1, n)) / (2**n*n) assert limit_seq(e, n) == 4 e = (Sum(binomial(3*k, k) * binomial(5*k, k), (k, 1, n)) / (binomial(3*n, n) * binomial(5*n, n))) assert limit_seq(e, n) == S(84375) / 83351 e = Sum(harmonic(k)**2/k, (k, 1, 2*n)) / harmonic(n)**3 assert limit_seq(e, n) == S.One / 3 raises(ValueError, lambda: limit_seq(e * m)) def test_alternating_sign(): assert limit_seq((-1)**n/n**2, n) == 0 assert limit_seq((-2)**(n+1)/(n + 3**n), n) == 0 assert limit_seq((2*n + (-1)**n)/(n + 1), n) == 2 assert limit_seq(sin(pi*n), n) == 0 assert limit_seq(cos(2*pi*n), n) == 1 assert limit_seq((S.NegativeOne/5)**n, n) == 0 assert limit_seq((Rational(-1, 5))**n, n) == 0 assert limit_seq((I/3)**n, n) == 0 assert limit_seq(sqrt(n)*(I/2)**n, n) == 0 assert limit_seq(n**7*(I/3)**n, n) == 0 assert limit_seq(n/(n + 1) + (I/2)**n, n) == 1 def test_accum_bounds(): assert limit_seq((-1)**n, n) == AccumulationBounds(-1, 1) assert limit_seq(cos(pi*n), n) == AccumulationBounds(-1, 1) assert limit_seq(sin(pi*n/2)**2, n) == AccumulationBounds(0, 1) assert limit_seq(2*(-3)**n/(n + 3**n), n) == AccumulationBounds(-2, 2) assert limit_seq(3*n/(n + 1) + 2*(-1)**n, n) == AccumulationBounds(1, 5) def test_limitseq_sum(): from sympy.abc import x, y, z assert limit_seq(Sum(1/x, (x, 1, y)) - log(y), y) == S.EulerGamma assert limit_seq(Sum(1/x, (x, 1, y)) - 1/y, y) is S.Infinity assert (limit_seq(binomial(2*x, x) / Sum(binomial(2*y, y), (y, 1, x)), x) == S(3) / 4) assert (limit_seq(Sum(y**2 * Sum(2**z/z, (z, 1, y)), (y, 1, x)) / (2**x*x), x) == 4) def test_issue_9308(): assert limit_seq(subfactorial(n)/factorial(n), n) == exp(-1) def test_issue_10382(): n = Symbol('n', integer=True) assert limit_seq(fibonacci(n+1)/fibonacci(n), n) == S.GoldenRatio def test_issue_11672(): assert limit_seq(Rational(-1, 2)**n, n) == 0 def test_issue_16735(): assert limit_seq(5**n/factorial(n), n) == 0 def test_issue_19868(): assert limit_seq(1/gamma(n + S.One/2), n) == 0 @XFAIL def test_limit_seq_fail(): # improve Summation algorithm or add ad-hoc criteria e = (harmonic(n)**3 * Sum(1/harmonic(k), (k, 1, n)) / (n * Sum(harmonic(k)/k, (k, 1, n)))) assert limit_seq(e, n) == 2 # No unique dominant term e = (Sum(2**k * binomial(2*k, k) / k**2, (k, 1, n)) / (Sum(2**k/k*2, (k, 1, n)) * Sum(binomial(2*k, k), (k, 1, n)))) assert limit_seq(e, n) == S(3) / 7 # Simplifications of summations needs to be improved. e = n**3*Sum(2**k/k**2, (k, 1, n))**2 / (2**n * Sum(2**k/k, (k, 1, n))) assert limit_seq(e, n) == 2 e = (harmonic(n) * Sum(2**k/k, (k, 1, n)) / (n * Sum(2**k*harmonic(k)/k**2, (k, 1, n)))) assert limit_seq(e, n) == 1 e = (Sum(2**k*factorial(k) / k**2, (k, 1, 2*n)) / (Sum(4**k/k**2, (k, 1, n)) * Sum(factorial(k), (k, 1, 2*n)))) assert limit_seq(e, n) == S(3) / 16
3b2ab7db24199c63500d2dae2776f2ddb67ecb81bd73d0457dd413715b96d913
from sympy.core.containers import Tuple from sympy.core.function import Function from sympy.core.numbers import oo, Rational from sympy.core.singleton import S from sympy.core.symbol import symbols, Symbol from sympy.functions.combinatorial.numbers import tribonacci, fibonacci from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import cos, sin from sympy.series import EmptySequence from sympy.series.sequences import (SeqMul, SeqAdd, SeqPer, SeqFormula, sequence) from sympy.sets.sets import Interval from sympy.tensor.indexed import Indexed, Idx from sympy.series.sequences import SeqExpr, SeqExprOp, RecursiveSeq from sympy.testing.pytest import raises, slow x, y, z = symbols('x y z') n, m = symbols('n m') def test_EmptySequence(): assert S.EmptySequence is EmptySequence assert S.EmptySequence.interval is S.EmptySet assert S.EmptySequence.length is S.Zero assert list(S.EmptySequence) == [] def test_SeqExpr(): #SeqExpr is a baseclass and does not take care of #ensuring all arguments are Basics hence the use of #Tuple(...) here. s = SeqExpr(Tuple(1, n, y), Tuple(x, 0, 10)) assert isinstance(s, SeqExpr) assert s.gen == (1, n, y) assert s.interval == Interval(0, 10) assert s.start == 0 assert s.stop == 10 assert s.length == 11 assert s.variables == (x,) assert SeqExpr(Tuple(1, 2, 3), Tuple(x, 0, oo)).length is oo def test_SeqPer(): s = SeqPer((1, n, 3), (x, 0, 5)) assert isinstance(s, SeqPer) assert s.periodical == Tuple(1, n, 3) assert s.period == 3 assert s.coeff(3) == 1 assert s.free_symbols == {n} assert list(s) == [1, n, 3, 1, n, 3] assert s[:] == [1, n, 3, 1, n, 3] assert SeqPer((1, n, 3), (x, -oo, 0))[0:6] == [1, n, 3, 1, n, 3] raises(ValueError, lambda: SeqPer((1, 2, 3), (0, 1, 2))) raises(ValueError, lambda: SeqPer((1, 2, 3), (x, -oo, oo))) raises(ValueError, lambda: SeqPer(n**2, (0, oo))) assert SeqPer((n, n**2, n**3), (m, 0, oo))[:6] == \ [n, n**2, n**3, n, n**2, n**3] assert SeqPer((n, n**2, n**3), (n, 0, oo))[:6] == [0, 1, 8, 3, 16, 125] assert SeqPer((n, m), (n, 0, oo))[:6] == [0, m, 2, m, 4, m] def test_SeqFormula(): s = SeqFormula(n**2, (n, 0, 5)) assert isinstance(s, SeqFormula) assert s.formula == n**2 assert s.coeff(3) == 9 assert list(s) == [i**2 for i in range(6)] assert s[:] == [i**2 for i in range(6)] assert SeqFormula(n**2, (n, -oo, 0))[0:6] == [i**2 for i in range(6)] assert SeqFormula(n**2, (0, oo)) == SeqFormula(n**2, (n, 0, oo)) assert SeqFormula(n**2, (0, m)).subs(m, x) == SeqFormula(n**2, (0, x)) assert SeqFormula(m*n**2, (n, 0, oo)).subs(m, x) == \ SeqFormula(x*n**2, (n, 0, oo)) raises(ValueError, lambda: SeqFormula(n**2, (0, 1, 2))) raises(ValueError, lambda: SeqFormula(n**2, (n, -oo, oo))) raises(ValueError, lambda: SeqFormula(m*n**2, (0, oo))) seq = SeqFormula(x*(y**2 + z), (z, 1, 100)) assert seq.expand() == SeqFormula(x*y**2 + x*z, (z, 1, 100)) seq = SeqFormula(sin(x*(y**2 + z)),(z, 1, 100)) assert seq.expand(trig=True) == SeqFormula(sin(x*y**2)*cos(x*z) + sin(x*z)*cos(x*y**2), (z, 1, 100)) assert seq.expand() == SeqFormula(sin(x*y**2 + x*z), (z, 1, 100)) assert seq.expand(trig=False) == SeqFormula(sin(x*y**2 + x*z), (z, 1, 100)) seq = SeqFormula(exp(x*(y**2 + z)), (z, 1, 100)) assert seq.expand() == SeqFormula(exp(x*y**2)*exp(x*z), (z, 1, 100)) assert seq.expand(power_exp=False) == SeqFormula(exp(x*y**2 + x*z), (z, 1, 100)) assert seq.expand(mul=False, power_exp=False) == SeqFormula(exp(x*(y**2 + z)), (z, 1, 100)) def test_sequence(): form = SeqFormula(n**2, (n, 0, 5)) per = SeqPer((1, 2, 3), (n, 0, 5)) inter = SeqFormula(n**2) assert sequence(n**2, (n, 0, 5)) == form assert sequence((1, 2, 3), (n, 0, 5)) == per assert sequence(n**2) == inter def test_SeqExprOp(): form = SeqFormula(n**2, (n, 0, 10)) per = SeqPer((1, 2, 3), (m, 5, 10)) s = SeqExprOp(form, per) assert s.gen == (n**2, (1, 2, 3)) assert s.interval == Interval(5, 10) assert s.start == 5 assert s.stop == 10 assert s.length == 6 assert s.variables == (n, m) def test_SeqAdd(): per = SeqPer((1, 2, 3), (n, 0, oo)) form = SeqFormula(n**2) per_bou = SeqPer((1, 2), (n, 1, 5)) form_bou = SeqFormula(n**2, (6, 10)) form_bou2 = SeqFormula(n**2, (1, 5)) assert SeqAdd() == S.EmptySequence assert SeqAdd(S.EmptySequence) == S.EmptySequence assert SeqAdd(per) == per assert SeqAdd(per, S.EmptySequence) == per assert SeqAdd(per_bou, form_bou) == S.EmptySequence s = SeqAdd(per_bou, form_bou2, evaluate=False) assert s.args == (form_bou2, per_bou) assert s[:] == [2, 6, 10, 18, 26] assert list(s) == [2, 6, 10, 18, 26] assert isinstance(SeqAdd(per, per_bou, evaluate=False), SeqAdd) s1 = SeqAdd(per, per_bou) assert isinstance(s1, SeqPer) assert s1 == SeqPer((2, 4, 4, 3, 3, 5), (n, 1, 5)) s2 = SeqAdd(form, form_bou) assert isinstance(s2, SeqFormula) assert s2 == SeqFormula(2*n**2, (6, 10)) assert SeqAdd(form, form_bou, per) == \ SeqAdd(per, SeqFormula(2*n**2, (6, 10))) assert SeqAdd(form, SeqAdd(form_bou, per)) == \ SeqAdd(per, SeqFormula(2*n**2, (6, 10))) assert SeqAdd(per, SeqAdd(form, form_bou), evaluate=False) == \ SeqAdd(per, SeqFormula(2*n**2, (6, 10))) assert SeqAdd(SeqPer((1, 2), (n, 0, oo)), SeqPer((1, 2), (m, 0, oo))) == \ SeqPer((2, 4), (n, 0, oo)) def test_SeqMul(): per = SeqPer((1, 2, 3), (n, 0, oo)) form = SeqFormula(n**2) per_bou = SeqPer((1, 2), (n, 1, 5)) form_bou = SeqFormula(n**2, (n, 6, 10)) form_bou2 = SeqFormula(n**2, (1, 5)) assert SeqMul() == S.EmptySequence assert SeqMul(S.EmptySequence) == S.EmptySequence assert SeqMul(per) == per assert SeqMul(per, S.EmptySequence) == S.EmptySequence assert SeqMul(per_bou, form_bou) == S.EmptySequence s = SeqMul(per_bou, form_bou2, evaluate=False) assert s.args == (form_bou2, per_bou) assert s[:] == [1, 8, 9, 32, 25] assert list(s) == [1, 8, 9, 32, 25] assert isinstance(SeqMul(per, per_bou, evaluate=False), SeqMul) s1 = SeqMul(per, per_bou) assert isinstance(s1, SeqPer) assert s1 == SeqPer((1, 4, 3, 2, 2, 6), (n, 1, 5)) s2 = SeqMul(form, form_bou) assert isinstance(s2, SeqFormula) assert s2 == SeqFormula(n**4, (6, 10)) assert SeqMul(form, form_bou, per) == \ SeqMul(per, SeqFormula(n**4, (6, 10))) assert SeqMul(form, SeqMul(form_bou, per)) == \ SeqMul(per, SeqFormula(n**4, (6, 10))) assert SeqMul(per, SeqMul(form, form_bou2, evaluate=False), evaluate=False) == \ SeqMul(form, per, form_bou2, evaluate=False) assert SeqMul(SeqPer((1, 2), (n, 0, oo)), SeqPer((1, 2), (n, 0, oo))) == \ SeqPer((1, 4), (n, 0, oo)) def test_add(): per = SeqPer((1, 2), (n, 0, oo)) form = SeqFormula(n**2) assert per + (SeqPer((2, 3))) == SeqPer((3, 5), (n, 0, oo)) assert form + SeqFormula(n**3) == SeqFormula(n**2 + n**3) assert per + form == SeqAdd(per, form) raises(TypeError, lambda: per + n) raises(TypeError, lambda: n + per) def test_sub(): per = SeqPer((1, 2), (n, 0, oo)) form = SeqFormula(n**2) assert per - (SeqPer((2, 3))) == SeqPer((-1, -1), (n, 0, oo)) assert form - (SeqFormula(n**3)) == SeqFormula(n**2 - n**3) assert per - form == SeqAdd(per, -form) raises(TypeError, lambda: per - n) raises(TypeError, lambda: n - per) def test_mul__coeff_mul(): assert SeqPer((1, 2), (n, 0, oo)).coeff_mul(2) == SeqPer((2, 4), (n, 0, oo)) assert SeqFormula(n**2).coeff_mul(2) == SeqFormula(2*n**2) assert S.EmptySequence.coeff_mul(100) == S.EmptySequence assert SeqPer((1, 2), (n, 0, oo)) * (SeqPer((2, 3))) == \ SeqPer((2, 6), (n, 0, oo)) assert SeqFormula(n**2) * SeqFormula(n**3) == SeqFormula(n**5) assert S.EmptySequence * SeqFormula(n**2) == S.EmptySequence assert SeqFormula(n**2) * S.EmptySequence == S.EmptySequence raises(TypeError, lambda: sequence(n**2) * n) raises(TypeError, lambda: n * sequence(n**2)) def test_neg(): assert -SeqPer((1, -2), (n, 0, oo)) == SeqPer((-1, 2), (n, 0, oo)) assert -SeqFormula(n**2) == SeqFormula(-n**2) def test_operations(): per = SeqPer((1, 2), (n, 0, oo)) per2 = SeqPer((2, 4), (n, 0, oo)) form = SeqFormula(n**2) form2 = SeqFormula(n**3) assert per + form + form2 == SeqAdd(per, form, form2) assert per + form - form2 == SeqAdd(per, form, -form2) assert per + form - S.EmptySequence == SeqAdd(per, form) assert per + per2 + form == SeqAdd(SeqPer((3, 6), (n, 0, oo)), form) assert S.EmptySequence - per == -per assert form + form == SeqFormula(2*n**2) assert per * form * form2 == SeqMul(per, form, form2) assert form * form == SeqFormula(n**4) assert form * -form == SeqFormula(-n**4) assert form * (per + form2) == SeqMul(form, SeqAdd(per, form2)) assert form * (per + per) == SeqMul(form, per2) assert form.coeff_mul(m) == SeqFormula(m*n**2, (n, 0, oo)) assert per.coeff_mul(m) == SeqPer((m, 2*m), (n, 0, oo)) def test_Idx_limits(): i = symbols('i', cls=Idx) r = Indexed('r', i) assert SeqFormula(r, (i, 0, 5))[:] == [r.subs(i, j) for j in range(6)] assert SeqPer((1, 2), (i, 0, 5))[:] == [1, 2, 1, 2, 1, 2] @slow def test_find_linear_recurrence(): assert sequence((0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55), \ (n, 0, 10)).find_linear_recurrence(11) == [1, 1] assert sequence((1, 2, 4, 7, 28, 128, 582, 2745, 13021, 61699, 292521, \ 1387138), (n, 0, 11)).find_linear_recurrence(12) == [5, -2, 6, -11] assert sequence(x*n**3+y*n, (n, 0, oo)).find_linear_recurrence(10) \ == [4, -6, 4, -1] assert sequence(x**n, (n,0,20)).find_linear_recurrence(21) == [x] assert sequence((1,2,3)).find_linear_recurrence(10, 5) == [0, 0, 1] assert sequence(((1 + sqrt(5))/2)**n + \ (-(1 + sqrt(5))/2)**(-n)).find_linear_recurrence(10) == [1, 1] assert sequence(x*((1 + sqrt(5))/2)**n + y*(-(1 + sqrt(5))/2)**(-n), \ (n,0,oo)).find_linear_recurrence(10) == [1, 1] assert sequence((1,2,3,4,6),(n, 0, 4)).find_linear_recurrence(5) == [] assert sequence((2,3,4,5,6,79),(n, 0, 5)).find_linear_recurrence(6,gfvar=x) \ == ([], None) assert sequence((2,3,4,5,8,30),(n, 0, 5)).find_linear_recurrence(6,gfvar=x) \ == ([Rational(19, 2), -20, Rational(27, 2)], (-31*x**2 + 32*x - 4)/(27*x**3 - 40*x**2 + 19*x -2)) assert sequence(fibonacci(n)).find_linear_recurrence(30,gfvar=x) \ == ([1, 1], -x/(x**2 + x - 1)) assert sequence(tribonacci(n)).find_linear_recurrence(30,gfvar=x) \ == ([1, 1, 1], -x/(x**3 + x**2 + x - 1)) def test_RecursiveSeq(): y = Function('y') n = Symbol('n') fib = RecursiveSeq(y(n - 1) + y(n - 2), y(n), n, [0, 1]) assert fib.coeff(3) == 2
9d9a948e7550f1de32923091c4fac6c58f6f0142e31c377563517864f9c17201
from sympy.core import EulerGamma from sympy.core.numbers import (E, I, Integer, Rational, oo, pi) from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acot, atan, cos, sin) from sympy.functions.special.error_functions import (Ei, erf) from sympy.functions.special.gamma_functions import (digamma, gamma, loggamma) from sympy.functions.special.zeta_functions import zeta from sympy.polys.polytools import cancel from sympy.functions.elementary.hyperbolic import cosh, coth, sinh, tanh from sympy.series.gruntz import compare, mrv, rewrite, mrv_leadterm, gruntz, \ sign from sympy.testing.pytest import XFAIL, skip, slow """ This test suite is testing the limit algorithm using the bottom up approach. See the documentation in limits2.py. The algorithm itself is highly recursive by nature, so "compare" is logically the lowest part of the algorithm, yet in some sense it's the most complex part, because it needs to calculate a limit to return the result. Nevertheless, the rest of the algorithm depends on compare working correctly. """ x = Symbol('x', real=True) m = Symbol('m', real=True) runslow = False def _sskip(): if not runslow: skip("slow") @slow def test_gruntz_evaluation(): # Gruntz' thesis pp. 122 to 123 # 8.1 assert gruntz(exp(x)*(exp(1/x - exp(-x)) - exp(1/x)), x, oo) == -1 # 8.2 assert gruntz(exp(x)*(exp(1/x + exp(-x) + exp(-x**2)) - exp(1/x - exp(-exp(x)))), x, oo) == 1 # 8.3 assert gruntz(exp(exp(x - exp(-x))/(1 - 1/x)) - exp(exp(x)), x, oo) is oo # 8.5 assert gruntz(exp(exp(exp(x + exp(-x)))) / exp(exp(exp(x))), x, oo) is oo # 8.6 assert gruntz(exp(exp(exp(x))) / exp(exp(exp(x - exp(-exp(x))))), x, oo) is oo # 8.7 assert gruntz(exp(exp(exp(x))) / exp(exp(exp(x - exp(-exp(exp(x)))))), x, oo) == 1 # 8.8 assert gruntz(exp(exp(x)) / exp(exp(x - exp(-exp(exp(x))))), x, oo) == 1 # 8.9 assert gruntz(log(x)**2 * exp(sqrt(log(x))*(log(log(x)))**2 * exp(sqrt(log(log(x))) * (log(log(log(x))))**3)) / sqrt(x), x, oo) == 0 # 8.10 assert gruntz((x*log(x)*(log(x*exp(x) - x**2))**2) / (log(log(x**2 + 2*exp(exp(3*x**3*log(x)))))), x, oo) == Rational(1, 3) # 8.11 assert gruntz((exp(x*exp(-x)/(exp(-x) + exp(-2*x**2/(x + 1)))) - exp(x))/x, x, oo) == -exp(2) # 8.12 assert gruntz((3**x + 5**x)**(1/x), x, oo) == 5 # 8.13 assert gruntz(x/log(x**(log(x**(log(2)/log(x))))), x, oo) is oo # 8.14 assert gruntz(exp(exp(2*log(x**5 + x)*log(log(x)))) / exp(exp(10*log(x)*log(log(x)))), x, oo) is oo # 8.15 assert gruntz(exp(exp(Rational(5, 2)*x**Rational(-5, 7) + Rational(21, 8)*x**Rational(6, 11) + 2*x**(-8) + Rational(54, 17)*x**Rational(49, 45)))**8 / log(log(-log(Rational(4, 3)*x**Rational(-5, 14))))**Rational(7, 6), x, oo) is oo # 8.16 assert gruntz((exp(4*x*exp(-x)/(1/exp(x) + 1/exp(2*x**2/(x + 1)))) - exp(x)) / exp(x)**4, x, oo) == 1 # 8.17 assert gruntz(exp(x*exp(-x)/(exp(-x) + exp(-2*x**2/(x + 1))))/exp(x), x, oo) \ == 1 # 8.19 assert gruntz(log(x)*(log(log(x) + log(log(x))) - log(log(x))) / (log(log(x) + log(log(log(x))))), x, oo) == 1 # 8.20 assert gruntz(exp((log(log(x + exp(log(x)*log(log(x)))))) / (log(log(log(exp(x) + x + log(x)))))), x, oo) == E # Another assert gruntz(exp(exp(exp(x + exp(-x)))) / exp(exp(x)), x, oo) is oo def test_gruntz_evaluation_slow(): _sskip() # 8.4 assert gruntz(exp(exp(exp(x)/(1 - 1/x))) - exp(exp(exp(x)/(1 - 1/x - log(x)**(-log(x))))), x, oo) is -oo # 8.18 assert gruntz((exp(exp(-x/(1 + exp(-x))))*exp(-x/(1 + exp(-x/(1 + exp(-x))))) *exp(exp(-x + exp(-x/(1 + exp(-x)))))) / (exp(-x/(1 + exp(-x))))**2 - exp(x) + x, x, oo) == 2 @slow def test_gruntz_eval_special(): # Gruntz, p. 126 assert gruntz(exp(x)*(sin(1/x + exp(-x)) - sin(1/x + exp(-x**2))), x, oo) == 1 assert gruntz((erf(x - exp(-exp(x))) - erf(x)) * exp(exp(x)) * exp(x**2), x, oo) == -2/sqrt(pi) assert gruntz(exp(exp(x)) * (exp(sin(1/x + exp(-exp(x)))) - exp(sin(1/x))), x, oo) == 1 assert gruntz(exp(x)*(gamma(x + exp(-x)) - gamma(x)), x, oo) is oo assert gruntz(exp(exp(digamma(digamma(x))))/x, x, oo) == exp(Rational(-1, 2)) assert gruntz(exp(exp(digamma(log(x))))/x, x, oo) == exp(Rational(-1, 2)) assert gruntz(digamma(digamma(digamma(x))), x, oo) is oo assert gruntz(loggamma(loggamma(x)), x, oo) is oo assert gruntz(((gamma(x + 1/gamma(x)) - gamma(x))/log(x) - cos(1/x)) * x*log(x), x, oo) == Rational(-1, 2) assert gruntz(x * (gamma(x - 1/gamma(x)) - gamma(x) + log(x)), x, oo) \ == S.Half assert gruntz((gamma(x + 1/gamma(x)) - gamma(x)) / log(x), x, oo) == 1 def test_gruntz_eval_special_slow(): _sskip() assert gruntz(gamma(x + 1)/sqrt(2*pi) - exp(-x)*(x**(x + S.Half) + x**(x - S.Half)/12), x, oo) is oo assert gruntz(exp(exp(exp(digamma(digamma(digamma(x))))))/x, x, oo) == 0 @XFAIL def test_grunts_eval_special_slow_sometimes_fail(): _sskip() # XXX This sometimes fails!!! assert gruntz(exp(gamma(x - exp(-x))*exp(1/x)) - exp(gamma(x)), x, oo) is oo def test_gruntz_Ei(): assert gruntz((Ei(x - exp(-exp(x))) - Ei(x)) *exp(-x)*exp(exp(x))*x, x, oo) == -1 @XFAIL def test_gruntz_eval_special_fail(): # TODO zeta function series assert gruntz( exp((log(2) + 1)*x) * (zeta(x + exp(-x)) - zeta(x)), x, oo) == -log(2) # TODO 8.35 - 8.37 (bessel, max-min) def test_gruntz_hyperbolic(): assert gruntz(cosh(x), x, oo) is oo assert gruntz(cosh(x), x, -oo) is oo assert gruntz(sinh(x), x, oo) is oo assert gruntz(sinh(x), x, -oo) is -oo assert gruntz(2*cosh(x)*exp(x), x, oo) is oo assert gruntz(2*cosh(x)*exp(x), x, -oo) == 1 assert gruntz(2*sinh(x)*exp(x), x, oo) is oo assert gruntz(2*sinh(x)*exp(x), x, -oo) == -1 assert gruntz(tanh(x), x, oo) == 1 assert gruntz(tanh(x), x, -oo) == -1 assert gruntz(coth(x), x, oo) == 1 assert gruntz(coth(x), x, -oo) == -1 def test_compare1(): assert compare(2, x, x) == "<" assert compare(x, exp(x), x) == "<" assert compare(exp(x), exp(x**2), x) == "<" assert compare(exp(x**2), exp(exp(x)), x) == "<" assert compare(1, exp(exp(x)), x) == "<" assert compare(x, 2, x) == ">" assert compare(exp(x), x, x) == ">" assert compare(exp(x**2), exp(x), x) == ">" assert compare(exp(exp(x)), exp(x**2), x) == ">" assert compare(exp(exp(x)), 1, x) == ">" assert compare(2, 3, x) == "=" assert compare(3, -5, x) == "=" assert compare(2, -5, x) == "=" assert compare(x, x**2, x) == "=" assert compare(x**2, x**3, x) == "=" assert compare(x**3, 1/x, x) == "=" assert compare(1/x, x**m, x) == "=" assert compare(x**m, -x, x) == "=" assert compare(exp(x), exp(-x), x) == "=" assert compare(exp(-x), exp(2*x), x) == "=" assert compare(exp(2*x), exp(x)**2, x) == "=" assert compare(exp(x)**2, exp(x + exp(-x)), x) == "=" assert compare(exp(x), exp(x + exp(-x)), x) == "=" assert compare(exp(x**2), 1/exp(x**2), x) == "=" def test_compare2(): assert compare(exp(x), x**5, x) == ">" assert compare(exp(x**2), exp(x)**2, x) == ">" assert compare(exp(x), exp(x + exp(-x)), x) == "=" assert compare(exp(x + exp(-x)), exp(x), x) == "=" assert compare(exp(x + exp(-x)), exp(-x), x) == "=" assert compare(exp(-x), x, x) == ">" assert compare(x, exp(-x), x) == "<" assert compare(exp(x + 1/x), x, x) == ">" assert compare(exp(-exp(x)), exp(x), x) == ">" assert compare(exp(exp(-exp(x)) + x), exp(-exp(x)), x) == "<" def test_compare3(): assert compare(exp(exp(x)), exp(x + exp(-exp(x))), x) == ">" def test_sign1(): assert sign(Rational(0), x) == 0 assert sign(Rational(3), x) == 1 assert sign(Rational(-5), x) == -1 assert sign(log(x), x) == 1 assert sign(exp(-x), x) == 1 assert sign(exp(x), x) == 1 assert sign(-exp(x), x) == -1 assert sign(3 - 1/x, x) == 1 assert sign(-3 - 1/x, x) == -1 assert sign(sin(1/x), x) == 1 assert sign((x**Integer(2)), x) == 1 assert sign(x**2, x) == 1 assert sign(x**5, x) == 1 def test_sign2(): assert sign(x, x) == 1 assert sign(-x, x) == -1 y = Symbol("y", positive=True) assert sign(y, x) == 1 assert sign(-y, x) == -1 assert sign(y*x, x) == 1 assert sign(-y*x, x) == -1 def mmrv(a, b): return set(mrv(a, b)[0].keys()) def test_mrv1(): assert mmrv(x, x) == {x} assert mmrv(x + 1/x, x) == {x} assert mmrv(x**2, x) == {x} assert mmrv(log(x), x) == {x} assert mmrv(exp(x), x) == {exp(x)} assert mmrv(exp(-x), x) == {exp(-x)} assert mmrv(exp(x**2), x) == {exp(x**2)} assert mmrv(-exp(1/x), x) == {x} assert mmrv(exp(x + 1/x), x) == {exp(x + 1/x)} def test_mrv2a(): assert mmrv(exp(x + exp(-exp(x))), x) == {exp(-exp(x))} assert mmrv(exp(x + exp(-x)), x) == {exp(x + exp(-x)), exp(-x)} assert mmrv(exp(1/x + exp(-x)), x) == {exp(-x)} #sometimes infinite recursion due to log(exp(x**2)) not simplifying def test_mrv2b(): assert mmrv(exp(x + exp(-x**2)), x) == {exp(-x**2)} #sometimes infinite recursion due to log(exp(x**2)) not simplifying def test_mrv2c(): assert mmrv( exp(-x + 1/x**2) - exp(x + 1/x), x) == {exp(x + 1/x), exp(1/x**2 - x)} #sometimes infinite recursion due to log(exp(x**2)) not simplifying def test_mrv3(): assert mmrv(exp(x**2) + x*exp(x) + log(x)**x/x, x) == {exp(x**2)} assert mmrv( exp(x)*(exp(1/x + exp(-x)) - exp(1/x)), x) == {exp(x), exp(-x)} assert mmrv(log( x**2 + 2*exp(exp(3*x**3*log(x)))), x) == {exp(exp(3*x**3*log(x)))} assert mmrv(log(x - log(x))/log(x), x) == {x} assert mmrv( (exp(1/x - exp(-x)) - exp(1/x))*exp(x), x) == {exp(x), exp(-x)} assert mmrv( 1/exp(-x + exp(-x)) - exp(x), x) == {exp(x), exp(-x), exp(x - exp(-x))} assert mmrv(log(log(x*exp(x*exp(x)) + 1)), x) == {exp(x*exp(x))} assert mmrv(exp(exp(log(log(x) + 1/x))), x) == {x} def test_mrv4(): ln = log assert mmrv((ln(ln(x) + ln(ln(x))) - ln(ln(x)))/ln(ln(x) + ln(ln(ln(x))))*ln(x), x) == {x} assert mmrv(log(log(x*exp(x*exp(x)) + 1)) - exp(exp(log(log(x) + 1/x))), x) == \ {exp(x*exp(x))} def mrewrite(a, b, c): return rewrite(a[1], a[0], b, c) def test_rewrite1(): e = exp(x) assert mrewrite(mrv(e, x), x, m) == (1/m, -x) e = exp(x**2) assert mrewrite(mrv(e, x), x, m) == (1/m, -x**2) e = exp(x + 1/x) assert mrewrite(mrv(e, x), x, m) == (1/m, -x - 1/x) e = 1/exp(-x + exp(-x)) - exp(x) assert mrewrite(mrv(e, x), x, m) == (1/(m*exp(m)) - 1/m, -x) def test_rewrite2(): e = exp(x)*log(log(exp(x))) assert mmrv(e, x) == {exp(x)} assert mrewrite(mrv(e, x), x, m) == (1/m*log(x), -x) #sometimes infinite recursion due to log(exp(x**2)) not simplifying def test_rewrite3(): e = exp(-x + 1/x**2) - exp(x + 1/x) #both of these are correct and should be equivalent: assert mrewrite(mrv(e, x), x, m) in [(-1/m + m*exp( 1/x + 1/x**2), -x - 1/x), (m - 1/m*exp(1/x + x**(-2)), x**(-2) - x)] def test_mrv_leadterm1(): assert mrv_leadterm(-exp(1/x), x) == (-1, 0) assert mrv_leadterm(1/exp(-x + exp(-x)) - exp(x), x) == (-1, 0) assert mrv_leadterm( (exp(1/x - exp(-x)) - exp(1/x))*exp(x), x) == (-exp(1/x), 0) def test_mrv_leadterm2(): #Gruntz: p51, 3.25 assert mrv_leadterm((log(exp(x) + x) - x)/log(exp(x) + log(x))*exp(x), x) == \ (1, 0) def test_mrv_leadterm3(): #Gruntz: p56, 3.27 assert mmrv(exp(-x + exp(-x)*exp(-x*log(x))), x) == {exp(-x - x*log(x))} assert mrv_leadterm(exp(-x + exp(-x)*exp(-x*log(x))), x) == (exp(-x), 0) def test_limit1(): assert gruntz(x, x, oo) is oo assert gruntz(x, x, -oo) is -oo assert gruntz(-x, x, oo) is -oo assert gruntz(x**2, x, -oo) is oo assert gruntz(-x**2, x, oo) is -oo assert gruntz(x*log(x), x, 0, dir="+") == 0 assert gruntz(1/x, x, oo) == 0 assert gruntz(exp(x), x, oo) is oo assert gruntz(-exp(x), x, oo) is -oo assert gruntz(exp(x)/x, x, oo) is oo assert gruntz(1/x - exp(-x), x, oo) == 0 assert gruntz(x + 1/x, x, oo) is oo def test_limit2(): assert gruntz(x**x, x, 0, dir="+") == 1 assert gruntz((exp(x) - 1)/x, x, 0) == 1 assert gruntz(1 + 1/x, x, oo) == 1 assert gruntz(-exp(1/x), x, oo) == -1 assert gruntz(x + exp(-x), x, oo) is oo assert gruntz(x + exp(-x**2), x, oo) is oo assert gruntz(x + exp(-exp(x)), x, oo) is oo assert gruntz(13 + 1/x - exp(-x), x, oo) == 13 def test_limit3(): a = Symbol('a') assert gruntz(x - log(1 + exp(x)), x, oo) == 0 assert gruntz(x - log(a + exp(x)), x, oo) == 0 assert gruntz(exp(x)/(1 + exp(x)), x, oo) == 1 assert gruntz(exp(x)/(a + exp(x)), x, oo) == 1 def test_limit4(): #issue 3463 assert gruntz((3**x + 5**x)**(1/x), x, oo) == 5 #issue 3463 assert gruntz((3**(1/x) + 5**(1/x))**x, x, 0) == 5 @XFAIL def test_MrvTestCase_page47_ex3_21(): h = exp(-x/(1 + exp(-x))) expr = exp(h)*exp(-x/(1 + h))*exp(exp(-x + h))/h**2 - exp(x) + x assert mmrv(expr, x) == {1/h, exp(-x), exp(x), exp(x - h), exp(x/(1 + h))} def test_gruntz_I(): y = Symbol("y") assert gruntz(I*x, x, oo) == I*oo assert gruntz(y*I*x, x, oo) == y*I*oo assert gruntz(y*3*I*x, x, oo) == y*I*oo assert gruntz(y*3*sin(I)*x, x, oo) == y*I*oo def test_issue_4814(): assert gruntz((x + 1)**(1/log(x + 1)), x, oo) == E def test_intractable(): assert gruntz(1/gamma(x), x, oo) == 0 assert gruntz(1/loggamma(x), x, oo) == 0 assert gruntz(gamma(x)/loggamma(x), x, oo) is oo assert gruntz(exp(gamma(x))/gamma(x), x, oo) is oo assert gruntz(gamma(x), x, 3) == 2 assert gruntz(gamma(Rational(1, 7) + 1/x), x, oo) == gamma(Rational(1, 7)) assert gruntz(log(x**x)/log(gamma(x)), x, oo) == 1 assert gruntz(log(gamma(gamma(x)))/exp(x), x, oo) is oo def test_aseries_trig(): assert cancel(gruntz(1/log(atan(x)), x, oo) - 1/(log(pi) + log(S.Half))) == 0 assert gruntz(1/acot(x), x, -oo) is -oo def test_exp_log_series(): assert gruntz(x/log(log(x*exp(x))), x, oo) is oo def test_issue_3644(): assert gruntz(((x**7 + x + 1)/(2**x + x**2))**(-1/x), x, oo) == 2 def test_issue_6843(): n = Symbol('n', integer=True, positive=True) r = (n + 1)*x**(n + 1)/(x**(n + 1) - 1) - x/(x - 1) assert gruntz(r, x, 1).simplify() == n/2 def test_issue_4190(): assert gruntz(x - gamma(1/x), x, oo) == S.EulerGamma @XFAIL def test_issue_5172(): n = Symbol('n') r = Symbol('r', positive=True) c = Symbol('c') p = Symbol('p', positive=True) m = Symbol('m', negative=True) expr = ((2*n*(n - r + 1)/(n + r*(n - r + 1)))**c + \ (r - 1)*(n*(n - r + 2)/(n + r*(n - r + 1)))**c - n)/(n**c - n) expr = expr.subs(c, c + 1) assert gruntz(expr.subs(c, m), n, oo) == 1 # fail: assert gruntz(expr.subs(c, p), n, oo).simplify() == \ (2**(p + 1) + r - 1)/(r + 1)**(p + 1) def test_issue_4109(): assert gruntz(1/gamma(x), x, 0) == 0 assert gruntz(x*gamma(x), x, 0) == 1 def test_issue_6682(): assert gruntz(exp(2*Ei(-x))/x**2, x, 0) == exp(2*EulerGamma) def test_issue_7096(): from sympy.functions import sign assert gruntz(x**-pi, x, 0, dir='-') == oo*sign((-1)**(-pi))
1394729b2bdaf00cb4a31be8c59f91f16902d6ec52294f3d7216f6fc4a26f400
from sympy.core.evalf import N from sympy.core.function import (Derivative, Function, PoleError, Subs) from sympy.core.numbers import (E, Rational, oo, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.exponential import (LambertW, exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (atan, cos, sin) from sympy.integrals.integrals import Integral from sympy.series.order import O from sympy.series.series import series from sympy.abc import x, y, n, k from sympy.testing.pytest import raises from sympy.series.gruntz import calculate_series def test_sin(): e1 = sin(x).series(x, 0) e2 = series(sin(x), x, 0) assert e1 == e2 def test_cos(): e1 = cos(x).series(x, 0) e2 = series(cos(x), x, 0) assert e1 == e2 def test_exp(): e1 = exp(x).series(x, 0) e2 = series(exp(x), x, 0) assert e1 == e2 def test_exp2(): e1 = exp(cos(x)).series(x, 0) e2 = series(exp(cos(x)), x, 0) assert e1 == e2 def test_issue_5223(): assert series(1, x) == 1 assert next(S.Zero.lseries(x)) == 0 assert cos(x).series() == cos(x).series(x) raises(ValueError, lambda: cos(x + y).series()) raises(ValueError, lambda: x.series(dir="")) assert (cos(x).series(x, 1) - cos(x + 1).series(x).subs(x, x - 1)).removeO() == 0 e = cos(x).series(x, 1, n=None) assert [next(e) for i in range(2)] == [cos(1), -((x - 1)*sin(1))] e = cos(x).series(x, 1, n=None, dir='-') assert [next(e) for i in range(2)] == [cos(1), (1 - x)*sin(1)] # the following test is exact so no need for x -> x - 1 replacement assert abs(x).series(x, 1, dir='-') == x assert exp(x).series(x, 1, dir='-', n=3).removeO() == \ E - E*(-x + 1) + E*(-x + 1)**2/2 D = Derivative assert D(x**2 + x**3*y**2, x, 2, y, 1).series(x).doit() == 12*x*y assert next(D(cos(x), x).lseries()) == D(1, x) assert D( exp(x), x).series(n=3) == D(1, x) + D(x, x) + D(x**2/2, x) + D(x**3/6, x) + O(x**3) assert Integral(x, (x, 1, 3), (y, 1, x)).series(x) == -4 + 4*x assert (1 + x + O(x**2)).getn() == 2 assert (1 + x).getn() is None raises(PoleError, lambda: ((1/sin(x))**oo).series()) logx = Symbol('logx') assert ((sin(x))**y).nseries(x, n=1, logx=logx) == \ exp(y*logx) + O(x*exp(y*logx), x) assert sin(1/x).series(x, oo, n=5) == 1/x - 1/(6*x**3) + O(x**(-5), (x, oo)) assert abs(x).series(x, oo, n=5, dir='+') == x assert abs(x).series(x, -oo, n=5, dir='-') == -x assert abs(-x).series(x, oo, n=5, dir='+') == x assert abs(-x).series(x, -oo, n=5, dir='-') == -x assert exp(x*log(x)).series(n=3) == \ 1 + x*log(x) + x**2*log(x)**2/2 + O(x**3*log(x)**3) # XXX is this right? If not, fix "ngot > n" handling in expr. p = Symbol('p', positive=True) assert exp(sqrt(p)**3*log(p)).series(n=3) == \ 1 + p**S('3/2')*log(p) + O(p**3*log(p)**3) assert exp(sin(x)*log(x)).series(n=2) == 1 + x*log(x) + O(x**2*log(x)**2) def test_issue_11313(): assert Integral(cos(x), x).series(x) == sin(x).series(x) assert Derivative(sin(x), x).series(x, n=3).doit() == cos(x).series(x, n=3) assert Derivative(x**3, x).as_leading_term(x) == 3*x**2 assert Derivative(x**3, y).as_leading_term(x) == 0 assert Derivative(sin(x), x).as_leading_term(x) == 1 assert Derivative(cos(x), x).as_leading_term(x) == -x # This result is equivalent to zero, zero is not return because # `Expr.series` doesn't currently detect an `x` in its `free_symbol`s. assert Derivative(1, x).as_leading_term(x) == Derivative(1, x) assert Derivative(exp(x), x).series(x).doit() == exp(x).series(x) assert 1 + Integral(exp(x), x).series(x) == exp(x).series(x) assert Derivative(log(x), x).series(x).doit() == (1/x).series(x) assert Integral(log(x), x).series(x) == Integral(log(x), x).doit().series(x).removeO() def test_series_of_Subs(): from sympy.abc import z subs1 = Subs(sin(x), x, y) subs2 = Subs(sin(x) * cos(z), x, y) subs3 = Subs(sin(x * z), (x, z), (y, x)) assert subs1.series(x) == subs1 subs1_series = (Subs(x, x, y) + Subs(-x**3/6, x, y) + Subs(x**5/120, x, y) + O(y**6)) assert subs1.series() == subs1_series assert subs1.series(y) == subs1_series assert subs1.series(z) == subs1 assert subs2.series(z) == (Subs(z**4*sin(x)/24, x, y) + Subs(-z**2*sin(x)/2, x, y) + Subs(sin(x), x, y) + O(z**6)) assert subs3.series(x).doit() == subs3.doit().series(x) assert subs3.series(z).doit() == sin(x*y) raises(ValueError, lambda: Subs(x + 2*y, y, z).series()) assert Subs(x + y, y, z).series(x).doit() == x + z def test_issue_3978(): f = Function('f') assert f(x).series(x, 0, 3, dir='-') == \ f(0) + x*Subs(Derivative(f(x), x), x, 0) + \ x**2*Subs(Derivative(f(x), x, x), x, 0)/2 + O(x**3) assert f(x).series(x, 0, 3) == \ f(0) + x*Subs(Derivative(f(x), x), x, 0) + \ x**2*Subs(Derivative(f(x), x, x), x, 0)/2 + O(x**3) assert f(x**2).series(x, 0, 3) == \ f(0) + x**2*Subs(Derivative(f(x), x), x, 0) + O(x**3) assert f(x**2+1).series(x, 0, 3) == \ f(1) + x**2*Subs(Derivative(f(x), x), x, 1) + O(x**3) class TestF(Function): pass assert TestF(x).series(x, 0, 3) == TestF(0) + \ x*Subs(Derivative(TestF(x), x), x, 0) + \ x**2*Subs(Derivative(TestF(x), x, x), x, 0)/2 + O(x**3) from sympy.series.acceleration import richardson, shanks from sympy.concrete.summations import Sum from sympy.core.numbers import Integer def test_acceleration(): e = (1 + 1/n)**n assert round(richardson(e, n, 10, 20).evalf(), 10) == round(E.evalf(), 10) A = Sum(Integer(-1)**(k + 1) / k, (k, 1, n)) assert round(shanks(A, n, 25).evalf(), 4) == round(log(2).evalf(), 4) assert round(shanks(A, n, 25, 5).evalf(), 10) == round(log(2).evalf(), 10) def test_issue_5852(): assert series(1/cos(x/log(x)), x, 0) == 1 + x**2/(2*log(x)**2) + \ 5*x**4/(24*log(x)**4) + O(x**6) def test_issue_4583(): assert cos(1 + x + x**2).series(x, 0, 5) == cos(1) - x*sin(1) + \ x**2*(-sin(1) - cos(1)/2) + x**3*(-cos(1) + sin(1)/6) + \ x**4*(-11*cos(1)/24 + sin(1)/2) + O(x**5) def test_issue_6318(): eq = (1/x)**Rational(2, 3) assert (eq + 1).as_leading_term(x) == eq def test_x_is_base_detection(): eq = (x**2)**Rational(2, 3) assert eq.series() == x**Rational(4, 3) def test_sin_power(): e = sin(x)**1.2 assert calculate_series(e, x) == x**1.2 def test_issue_7203(): assert series(cos(x), x, pi, 3) == \ -1 + (x - pi)**2/2 + O((x - pi)**3, (x, pi)) def test_exp_product_positive_factors(): a, b = symbols('a, b', positive=True) x = a * b assert series(exp(x), x, n=8) == 1 + a*b + a**2*b**2/2 + \ a**3*b**3/6 + a**4*b**4/24 + a**5*b**5/120 + a**6*b**6/720 + \ a**7*b**7/5040 + O(a**8*b**8, a, b) def test_issue_8805(): assert series(1, n=8) == 1 def test_issue_9549(): y = (x**2 + x + 1) / (x**3 + x**2) assert series(y, x, oo) == x**(-5) - 1/x**4 + x**(-3) + 1/x + O(x**(-6), (x, oo)) def test_issue_10761(): assert series(1/(x**-2 + x**-3), x, 0) == x**3 - x**4 + x**5 + O(x**6) def test_issue_12578(): y = (1 - 1/(x/2 - 1/(2*x))**4)**(S(1)/8) assert y.series(x, 0, n=17) == 1 - 2*x**4 - 8*x**6 - 34*x**8 - 152*x**10 - 714*x**12 - \ 3472*x**14 - 17318*x**16 + O(x**17) def test_issue_12791(): beta = symbols('beta', positive=True) theta, varphi = symbols('theta varphi', real=True) expr = (-beta**2*varphi*sin(theta) + beta**2*cos(theta) + \ beta*varphi*sin(theta) - beta*cos(theta) - beta + 1)/(beta*cos(theta) - 1)**2 sol = 0.5/(0.5*cos(theta) - 1.0)**2 - 0.25*cos(theta)/(0.5*cos(theta)\ - 1.0)**2 + (beta - 0.5)*(-0.25*varphi*sin(2*theta) - 1.5*cos(theta)\ + 0.25*cos(2*theta) + 1.25)/(0.5*cos(theta) - 1.0)**3\ + 0.25*varphi*sin(theta)/(0.5*cos(theta) - 1.0)**2 + O((beta - S.Half)**2, (beta, S.Half)) assert expr.series(beta, 0.5, 2).trigsimp() == sol def test_issue_14885(): assert series(x**Rational(-3, 2)*exp(x), x, 0) == (x**Rational(-3, 2) + 1/sqrt(x) + sqrt(x)/2 + x**Rational(3, 2)/6 + x**Rational(5, 2)/24 + x**Rational(7, 2)/120 + x**Rational(9, 2)/720 + x**Rational(11, 2)/5040 + O(x**6)) def test_issue_15539(): assert series(atan(x), x, -oo) == (-1/(5*x**5) + 1/(3*x**3) - 1/x - pi/2 + O(x**(-6), (x, -oo))) assert series(atan(x), x, oo) == (-1/(5*x**5) + 1/(3*x**3) - 1/x + pi/2 + O(x**(-6), (x, oo))) def test_issue_7259(): assert series(LambertW(x), x) == x - x**2 + 3*x**3/2 - 8*x**4/3 + 125*x**5/24 + O(x**6) assert series(LambertW(x**2), x, n=8) == x**2 - x**4 + 3*x**6/2 + O(x**8) assert series(LambertW(sin(x)), x, n=4) == x - x**2 + 4*x**3/3 + O(x**4) def test_issue_11884(): assert cos(x).series(x, 1, n=1) == cos(1) + O(x - 1, (x, 1)) def test_issue_18008(): y = x*(1 + x*(1 - x))/((1 + x*(1 - x)) - (1 - x)*(1 - x)) assert y.series(x, oo, n=4) == -9/(32*x**3) - 3/(16*x**2) - 1/(8*x) + S(1)/4 + x/2 + \ O(x**(-4), (x, oo)) def test_issue_18842(): f = log(x/(1 - x)) assert f.series(x, 0.491, n=1).removeO().nsimplify() == \ -S(180019443780011)/5000000000000000 def test_issue_19534(): dt = symbols('dt', real=True) expr = 16*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0)/45 + \ 49*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \ 0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \ 0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \ 0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.96296296296296296296*dt + 1.0) + 0.051640768506639183825*dt + \ dt*(1/2 - sqrt(21)/14) + 1.0)/180 + 49*dt*(-0.23637909581542530626*dt*(2.0*dt + 1.0) - \ 0.74817562366625959291*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.88085458023927036857*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \ 0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.96296296296296296296*dt + 1.0) + \ 2.1165151389911680013*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \ 0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \ 0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \ 0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.96296296296296296296*dt + 1.0) + 0.22431393315265061193*dt + 1.0) - \ 1.1854881643947648988*dt + dt*(sqrt(21)/14 + 1/2) + 1.0)/180 + \ dt*(0.66666666666666666667*dt*(2.0*dt + 1.0) + \ 6.0173399699313066769*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \ 4.1117044797036320069*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \ 0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.96296296296296296296*dt + 1.0) - \ 7.0189140975801991157*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \ 0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \ 0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \ 0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.96296296296296296296*dt + 1.0) + 0.22431393315265061193*dt + 1.0) + \ 0.94010945196161777522*dt*(-0.23637909581542530626*dt*(2.0*dt + 1.0) - \ 0.74817562366625959291*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.88085458023927036857*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \ 0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.96296296296296296296*dt + 1.0) + \ 2.1165151389911680013*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \ 0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \ 0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \ 0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.96296296296296296296*dt + 1.0) + 0.22431393315265061193*dt + 1.0) - \ 0.35816132904077632692*dt + 1.0) + 5.5065024887242400038*dt + 1.0)/20 + dt/20 + 1 assert N(expr.series(dt, 0, 8), 20) == -0.00092592592592592596126*dt**7 + 0.0027777777777777783175*dt**6 + \ 0.016666666666666656027*dt**5 + 0.083333333333333300952*dt**4 + 0.33333333333333337034*dt**3 + \ 1.0*dt**2 + 1.0*dt + 1.0 def test_issue_11407(): a, b, c, x = symbols('a b c x') assert series(sqrt(a + b + c*x), x, 0, 1) == sqrt(a + b) + O(x) assert series(sqrt(a + b + c + c*x), x, 0, 1) == sqrt(a + b + c) + O(x) def test_issue_14037(): assert (sin(x**50)/x**51).series(x, n=0) == 1/x + O(1, x) def test_issue_20551(): expr = (exp(x)/x).series(x, n=None) terms = [ next(expr) for i in range(3) ] assert terms == [1/x, 1, x/2] def test_issue_20697(): p_0, p_1, p_2, p_3, b_0, b_1, b_2 = symbols('p_0 p_1 p_2 p_3 b_0 b_1 b_2') Q = (p_0 + (p_1 + (p_2 + p_3/y)/y)/y)/(1 + ((p_3/(b_0*y) + (b_0*p_2\ - b_1*p_3)/b_0**2)/y + (b_0**2*p_1 - b_0*b_1*p_2 - p_3*(b_0*b_2\ - b_1**2))/b_0**3)/y) assert Q.series(y, n=3).ratsimp() == b_2*y**2 + b_1*y + b_0 + O(y**3) def test_issue_21245(): fi = (1 + sqrt(5))/2 assert (1/(1 - x - x**2)).series(x, 1/fi, 1).factor() == \ (-4812 - 2152*sqrt(5) + 1686*x + 754*sqrt(5)*x\ + O((x - 2/(1 + sqrt(5)))**2, (x, 2/(1 + sqrt(5)))))/((1 + sqrt(5))\ *(20 + 9*sqrt(5))**2*(x + sqrt(5)*x - 2)) def test_issue_21938(): expr = sin(1/x + exp(-x)) - sin(1/x) assert expr.series(x, oo) == (1/(24*x**4) - 1/(2*x**2) + 1 + O(x**(-6), (x, oo)))*exp(-x)
4ebf43de9fd2a5ab03743a12a5c1b2fd0c07f4fe4b8e0594ff2a08acd43774a1
from itertools import product from sympy.concrete.summations import Sum from sympy.core.function import (Function, diff) from sympy.core import EulerGamma from sympy.core.numbers import (E, I, Rational, oo, pi, zoo) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.combinatorial.factorials import (binomial, factorial, subfactorial) from sympy.functions.elementary.complexes import (Abs, re, sign) from sympy.functions.elementary.exponential import (LambertW, exp, log) from sympy.functions.elementary.hyperbolic import (acoth, atanh, sinh) from sympy.functions.elementary.integers import (ceiling, floor, frac) from sympy.functions.elementary.miscellaneous import (cbrt, real_root, sqrt) from sympy.functions.elementary.trigonometric import (acos, acot, acsc, asec, asin, atan, cos, cot, sec, sin, tan) from sympy.functions.special.bessel import (besselj, besselk) from sympy.functions.special.error_functions import (Ei, erf, erfc, erfi, fresnelc, fresnels) from sympy.functions.special.gamma_functions import (digamma, gamma, uppergamma) from sympy.integrals.integrals import (Integral, integrate) from sympy.series.limits import (Limit, limit) from sympy.simplify.simplify import simplify from sympy.calculus.accumulationbounds import AccumBounds from sympy.core.mul import Mul from sympy.series.limits import heuristics from sympy.series.order import Order from sympy.testing.pytest import XFAIL, raises from sympy.abc import x, y, z, k n = Symbol('n', integer=True, positive=True) def test_basic1(): assert limit(x, x, oo) is oo assert limit(x, x, -oo) is -oo assert limit(-x, x, oo) is -oo assert limit(x**2, x, -oo) is oo assert limit(-x**2, x, oo) is -oo assert limit(x*log(x), x, 0, dir="+") == 0 assert limit(1/x, x, oo) == 0 assert limit(exp(x), x, oo) is oo assert limit(-exp(x), x, oo) is -oo assert limit(exp(x)/x, x, oo) is oo assert limit(1/x - exp(-x), x, oo) == 0 assert limit(x + 1/x, x, oo) is oo assert limit(x - x**2, x, oo) is -oo assert limit((1 + x)**(1 + sqrt(2)), x, 0) == 1 assert limit((1 + x)**oo, x, 0) == Limit((x + 1)**oo, x, 0) assert limit((1 + x)**oo, x, 0, dir='-') == Limit((x + 1)**oo, x, 0, dir='-') assert limit((1 + x + y)**oo, x, 0, dir='-') == Limit((1 + x + y)**oo, x, 0, dir='-') assert limit(y/x/log(x), x, 0) == -oo*sign(y) assert limit(cos(x + y)/x, x, 0) == sign(cos(y))*oo assert limit(gamma(1/x + 3), x, oo) == 2 assert limit(S.NaN, x, -oo) is S.NaN assert limit(Order(2)*x, x, S.NaN) is S.NaN assert limit(1/(x - 1), x, 1, dir="+") is oo assert limit(1/(x - 1), x, 1, dir="-") is -oo assert limit(1/(5 - x)**3, x, 5, dir="+") is -oo assert limit(1/(5 - x)**3, x, 5, dir="-") is oo assert limit(1/sin(x), x, pi, dir="+") is -oo assert limit(1/sin(x), x, pi, dir="-") is oo assert limit(1/cos(x), x, pi/2, dir="+") is -oo assert limit(1/cos(x), x, pi/2, dir="-") is oo assert limit(1/tan(x**3), x, (2*pi)**Rational(1, 3), dir="+") is oo assert limit(1/tan(x**3), x, (2*pi)**Rational(1, 3), dir="-") is -oo assert limit(1/cot(x)**3, x, (pi*Rational(3, 2)), dir="+") is -oo assert limit(1/cot(x)**3, x, (pi*Rational(3, 2)), dir="-") is oo # test bi-directional limits assert limit(sin(x)/x, x, 0, dir="+-") == 1 assert limit(x**2, x, 0, dir="+-") == 0 assert limit(1/x**2, x, 0, dir="+-") is oo # test failing bi-directional limits assert limit(1/x, x, 0, dir="+-") is zoo # approaching 0 # from dir="+" assert limit(1 + 1/x, x, 0) is oo # from dir='-' # Add assert limit(1 + 1/x, x, 0, dir='-') is -oo # Pow assert limit(x**(-2), x, 0, dir='-') is oo assert limit(x**(-3), x, 0, dir='-') is -oo assert limit(1/sqrt(x), x, 0, dir='-') == (-oo)*I assert limit(x**2, x, 0, dir='-') == 0 assert limit(sqrt(x), x, 0, dir='-') == 0 assert limit(x**-pi, x, 0, dir='-') == oo/(-1)**pi assert limit((1 + cos(x))**oo, x, 0) == Limit((cos(x) + 1)**oo, x, 0) # test pull request 22491 assert limit(1/asin(x), x, 0, dir = '+') == oo assert limit(1/asin(x), x, 0, dir = '-') == -oo assert limit(1/sinh(x), x, 0, dir = '+') == oo assert limit(1/sinh(x), x, 0, dir = '-') == -oo assert limit(log(1/x) + 1/sin(x), x, 0, dir = '+') == oo assert limit(log(1/x) + 1/x, x, 0, dir = '+') == oo def test_basic2(): assert limit(x**x, x, 0, dir="+") == 1 assert limit((exp(x) - 1)/x, x, 0) == 1 assert limit(1 + 1/x, x, oo) == 1 assert limit(-exp(1/x), x, oo) == -1 assert limit(x + exp(-x), x, oo) is oo assert limit(x + exp(-x**2), x, oo) is oo assert limit(x + exp(-exp(x)), x, oo) is oo assert limit(13 + 1/x - exp(-x), x, oo) == 13 def test_basic3(): assert limit(1/x, x, 0, dir="+") is oo assert limit(1/x, x, 0, dir="-") is -oo def test_basic4(): assert limit(2*x + y*x, x, 0) == 0 assert limit(2*x + y*x, x, 1) == 2 + y assert limit(2*x**8 + y*x**(-3), x, -2) == 512 - y/8 assert limit(sqrt(x + 1) - sqrt(x), x, oo) == 0 assert integrate(1/(x**3 + 1), (x, 0, oo)) == 2*pi*sqrt(3)/9 def test_log(): # https://github.com/sympy/sympy/issues/21598 a, b, c = symbols('a b c', positive=True) A = log(a/b) - (log(a) - log(b)) assert A.limit(a, oo) == 0 assert (A * c).limit(a, oo) == 0 tau, x = symbols('tau x', positive=True) # The value of manualintegrate in the issue expr = tau**2*((tau - 1)*(tau + 1)*log(x + 1)/(tau**2 + 1)**2 + 1/((tau**2\ + 1)*(x + 1)) - (-2*tau*atan(x/tau) + (tau**2/2 - 1/2)*log(tau**2\ + x**2))/(tau**2 + 1)**2) assert limit(expr, x, oo) == pi*tau**3/(tau**2 + 1)**2 def test_piecewise(): # https://github.com/sympy/sympy/issues/18363 assert limit((real_root(x - 6, 3) + 2)/(x + 2), x, -2, '+') == Rational(1, 12) def test_basic5(): class my(Function): @classmethod def eval(cls, arg): if arg is S.Infinity: return S.NaN assert limit(my(x), x, oo) == Limit(my(x), x, oo) def test_issue_3885(): assert limit(x*y + x*z, z, 2) == x*y + 2*x def test_Limit(): assert Limit(sin(x)/x, x, 0) != 1 assert Limit(sin(x)/x, x, 0).doit() == 1 assert Limit(x, x, 0, dir='+-').args == (x, x, 0, Symbol('+-')) def test_floor(): assert limit(floor(x), x, -2, "+") == -2 assert limit(floor(x), x, -2, "-") == -3 assert limit(floor(x), x, -1, "+") == -1 assert limit(floor(x), x, -1, "-") == -2 assert limit(floor(x), x, 0, "+") == 0 assert limit(floor(x), x, 0, "-") == -1 assert limit(floor(x), x, 1, "+") == 1 assert limit(floor(x), x, 1, "-") == 0 assert limit(floor(x), x, 2, "+") == 2 assert limit(floor(x), x, 2, "-") == 1 assert limit(floor(x), x, 248, "+") == 248 assert limit(floor(x), x, 248, "-") == 247 # https://github.com/sympy/sympy/issues/14478 assert limit(x*floor(3/x)/2, x, 0, '+') == Rational(3, 2) assert limit(floor(x + 1/2) - floor(x), x, oo) == AccumBounds(-S.Half, S(3)/2) def test_floor_requires_robust_assumptions(): assert limit(floor(sin(x)), x, 0, "+") == 0 assert limit(floor(sin(x)), x, 0, "-") == -1 assert limit(floor(cos(x)), x, 0, "+") == 0 assert limit(floor(cos(x)), x, 0, "-") == 0 assert limit(floor(5 + sin(x)), x, 0, "+") == 5 assert limit(floor(5 + sin(x)), x, 0, "-") == 4 assert limit(floor(5 + cos(x)), x, 0, "+") == 5 assert limit(floor(5 + cos(x)), x, 0, "-") == 5 def test_ceiling(): assert limit(ceiling(x), x, -2, "+") == -1 assert limit(ceiling(x), x, -2, "-") == -2 assert limit(ceiling(x), x, -1, "+") == 0 assert limit(ceiling(x), x, -1, "-") == -1 assert limit(ceiling(x), x, 0, "+") == 1 assert limit(ceiling(x), x, 0, "-") == 0 assert limit(ceiling(x), x, 1, "+") == 2 assert limit(ceiling(x), x, 1, "-") == 1 assert limit(ceiling(x), x, 2, "+") == 3 assert limit(ceiling(x), x, 2, "-") == 2 assert limit(ceiling(x), x, 248, "+") == 249 assert limit(ceiling(x), x, 248, "-") == 248 # https://github.com/sympy/sympy/issues/14478 assert limit(x*ceiling(3/x)/2, x, 0, '+') == Rational(3, 2) assert limit(ceiling(x + 1/2) - ceiling(x), x, oo) == AccumBounds(-S.Half, S(3)/2) def test_ceiling_requires_robust_assumptions(): assert limit(ceiling(sin(x)), x, 0, "+") == 1 assert limit(ceiling(sin(x)), x, 0, "-") == 0 assert limit(ceiling(cos(x)), x, 0, "+") == 1 assert limit(ceiling(cos(x)), x, 0, "-") == 1 assert limit(ceiling(5 + sin(x)), x, 0, "+") == 6 assert limit(ceiling(5 + sin(x)), x, 0, "-") == 5 assert limit(ceiling(5 + cos(x)), x, 0, "+") == 6 assert limit(ceiling(5 + cos(x)), x, 0, "-") == 6 def test_atan(): x = Symbol("x", real=True) assert limit(atan(x)*sin(1/x), x, 0) == 0 assert limit(atan(x) + sqrt(x + 1) - sqrt(x), x, oo) == pi/2 def test_set_signs(): assert limit(abs(x), x, 0) == 0 assert limit(abs(sin(x)), x, 0) == 0 assert limit(abs(cos(x)), x, 0) == 1 assert limit(abs(sin(x + 1)), x, 0) == sin(1) # https://github.com/sympy/sympy/issues/9449 assert limit((Abs(x + y) - Abs(x - y))/(2*x), x, 0) == sign(y) # https://github.com/sympy/sympy/issues/12398 assert limit(Abs(log(x)/x**3), x, oo) == 0 assert limit(x*(Abs(log(x)/x**3)/Abs(log(x + 1)/(x + 1)**3) - 1), x, oo) == 3 # https://github.com/sympy/sympy/issues/18501 assert limit(Abs(log(x - 1)**3 - 1), x, 1, '+') == oo # https://github.com/sympy/sympy/issues/18997 assert limit(Abs(log(x)), x, 0) == oo assert limit(Abs(log(Abs(x))), x, 0) == oo # https://github.com/sympy/sympy/issues/19026 z = Symbol('z', positive=True) assert limit(Abs(log(z) + 1)/log(z), z, oo) == 1 # https://github.com/sympy/sympy/issues/20704 assert limit(z*(Abs(1/z + y) - Abs(y - 1/z))/2, z, 0) == 0 # https://github.com/sympy/sympy/issues/21606 assert limit(cos(z)/sign(z), z, pi, '-') == -1 def test_heuristic(): x = Symbol("x", real=True) assert heuristics(sin(1/x) + atan(x), x, 0, '+') == AccumBounds(-1, 1) assert limit(log(2 + sqrt(atan(x))*sqrt(sin(1/x))), x, 0) == log(2) def test_issue_3871(): z = Symbol("z", positive=True) f = -1/z*exp(-z*x) assert limit(f, x, oo) == 0 assert f.limit(x, oo) == 0 def test_exponential(): n = Symbol('n') x = Symbol('x', real=True) assert limit((1 + x/n)**n, n, oo) == exp(x) assert limit((1 + x/(2*n))**n, n, oo) == exp(x/2) assert limit((1 + x/(2*n + 1))**n, n, oo) == exp(x/2) assert limit(((x - 1)/(x + 1))**x, x, oo) == exp(-2) assert limit(1 + (1 + 1/x)**x, x, oo) == 1 + S.Exp1 assert limit((2 + 6*x)**x/(6*x)**x, x, oo) == exp(S('1/3')) def test_exponential2(): n = Symbol('n') assert limit((1 + x/(n + sin(n)))**n, n, oo) == exp(x) def test_doit(): f = Integral(2 * x, x) l = Limit(f, x, oo) assert l.doit() is oo def test_series_AccumBounds(): assert limit(sin(k) - sin(k + 1), k, oo) == AccumBounds(-2, 2) assert limit(cos(k) - cos(k + 1) + 1, k, oo) == AccumBounds(-1, 3) # not the exact bound assert limit(sin(k) - sin(k)*cos(k), k, oo) == AccumBounds(-2, 2) # test for issue #9934 lo = (-3 + cos(1))/2 hi = (1 + cos(1))/2 t1 = Mul(AccumBounds(lo, hi), 1/(-1 + cos(1)), evaluate=False) assert limit(simplify(Sum(cos(n).rewrite(exp), (n, 0, k)).doit().rewrite(sin)), k, oo) == t1 t2 = Mul(AccumBounds(-1 + sin(1)/2, sin(1)/2 + 1), 1/(1 - cos(1))) assert limit(simplify(Sum(sin(n).rewrite(exp), (n, 0, k)).doit().rewrite(sin)), k, oo) == t2 assert limit(frac(x)**x, x, oo) == AccumBounds(0, oo) # wolfram gives (0, 1) assert limit(((sin(x) + 1)/2)**x, x, oo) == AccumBounds(0, oo) # wolfram says 0 # https://github.com/sympy/sympy/issues/12312 e = 2**(-x)*(sin(x) + 1)**x assert limit(e, x, oo) == AccumBounds(0, oo) @XFAIL def test_doit2(): f = Integral(2 * x, x) l = Limit(f, x, oo) # limit() breaks on the contained Integral. assert l.doit(deep=False) == l def test_issue_2929(): assert limit((x * exp(x))/(exp(x) - 1), x, -oo) == 0 def test_issue_3792(): assert limit((1 - cos(x))/x**2, x, S.Half) == 4 - 4*cos(S.Half) assert limit(sin(sin(x + 1) + 1), x, 0) == sin(1 + sin(1)) assert limit(abs(sin(x + 1) + 1), x, 0) == 1 + sin(1) def test_issue_4090(): assert limit(1/(x + 3), x, 2) == Rational(1, 5) assert limit(1/(x + pi), x, 2) == S.One/(2 + pi) assert limit(log(x)/(x**2 + 3), x, 2) == log(2)/7 assert limit(log(x)/(x**2 + pi), x, 2) == log(2)/(4 + pi) def test_issue_4547(): assert limit(cot(x), x, 0, dir='+') is oo assert limit(cot(x), x, pi/2, dir='+') == 0 def test_issue_5164(): assert limit(x**0.5, x, oo) == oo**0.5 is oo assert limit(x**0.5, x, 16) == S(16)**0.5 assert limit(x**0.5, x, 0) == 0 assert limit(x**(-0.5), x, oo) == 0 assert limit(x**(-0.5), x, 4) == S(4)**(-0.5) def test_issue_5383(): func = (1.0 * 1 + 1.0 * x)**(1.0 * 1 / x) assert limit(func, x, 0) == E def test_issue_14793(): expr = ((x + S(1)/2) * log(x) - x + log(2*pi)/2 - \ log(factorial(x)) + S(1)/(12*x))*x**3 assert limit(expr, x, oo) == S(1)/360 def test_issue_5183(): # using list(...) so py.test can recalculate values tests = list(product([x, -x], [-1, 1], [2, 3, S.Half, Rational(2, 3)], ['-', '+'])) results = (oo, oo, -oo, oo, -oo*I, oo, -oo*(-1)**Rational(1, 3), oo, 0, 0, 0, 0, 0, 0, 0, 0, oo, oo, oo, -oo, oo, -oo*I, oo, -oo*(-1)**Rational(1, 3), 0, 0, 0, 0, 0, 0, 0, 0) assert len(tests) == len(results) for i, (args, res) in enumerate(zip(tests, results)): y, s, e, d = args eq = y**(s*e) try: assert limit(eq, x, 0, dir=d) == res except AssertionError: if 0: # change to 1 if you want to see the failing tests print() print(i, res, eq, d, limit(eq, x, 0, dir=d)) else: assert None def test_issue_5184(): assert limit(sin(x)/x, x, oo) == 0 assert limit(atan(x), x, oo) == pi/2 assert limit(gamma(x), x, oo) is oo assert limit(cos(x)/x, x, oo) == 0 assert limit(gamma(x), x, S.Half) == sqrt(pi) r = Symbol('r', real=True) assert limit(r*sin(1/r), r, 0) == 0 def test_issue_5229(): assert limit((1 + y)**(1/y) - S.Exp1, y, 0) == 0 def test_issue_4546(): # using list(...) so py.test can recalculate values tests = list(product([cot, tan], [-pi/2, 0, pi/2, pi, pi*Rational(3, 2)], ['-', '+'])) results = (0, 0, -oo, oo, 0, 0, -oo, oo, 0, 0, oo, -oo, 0, 0, oo, -oo, 0, 0, oo, -oo) assert len(tests) == len(results) for i, (args, res) in enumerate(zip(tests, results)): f, l, d = args eq = f(x) try: assert limit(eq, x, l, dir=d) == res except AssertionError: if 0: # change to 1 if you want to see the failing tests print() print(i, res, eq, l, d, limit(eq, x, l, dir=d)) else: assert None def test_issue_3934(): assert limit((1 + x**log(3))**(1/x), x, 0) == 1 assert limit((5**(1/x) + 3**(1/x))**x, x, 0) == 5 def test_calculate_series(): # needs gruntz calculate_series to go to n = 32 assert limit(x**Rational(77, 3)/(1 + x**Rational(77, 3)), x, oo) == 1 # needs gruntz calculate_series to go to n = 128 assert limit(x**101.1/(1 + x**101.1), x, oo) == 1 def test_issue_5955(): assert limit((x**16)/(1 + x**16), x, oo) == 1 assert limit((x**100)/(1 + x**100), x, oo) == 1 assert limit((x**1885)/(1 + x**1885), x, oo) == 1 assert limit((x**1000/((x + 1)**1000 + exp(-x))), x, oo) == 1 def test_newissue(): assert limit(exp(1/sin(x))/exp(cot(x)), x, 0) == 1 def test_extended_real_line(): assert limit(x - oo, x, oo) == Limit(x - oo, x, oo) assert limit(1/(x + sin(x)) - oo, x, 0) == Limit(1/(x + sin(x)) - oo, x, 0) assert limit(oo/x, x, oo) == Limit(oo/x, x, oo) assert limit(x - oo + 1/x, x, oo) == Limit(x - oo + 1/x, x, oo) @XFAIL def test_order_oo(): x = Symbol('x', positive=True) assert Order(x)*oo != Order(1, x) assert limit(oo/(x**2 - 4), x, oo) is oo def test_issue_5436(): raises(NotImplementedError, lambda: limit(exp(x*y), x, oo)) raises(NotImplementedError, lambda: limit(exp(-x*y), x, oo)) def test_Limit_dir(): raises(TypeError, lambda: Limit(x, x, 0, dir=0)) raises(ValueError, lambda: Limit(x, x, 0, dir='0')) def test_polynomial(): assert limit((x + 1)**1000/((x + 1)**1000 + 1), x, oo) == 1 assert limit((x + 1)**1000/((x + 1)**1000 + 1), x, -oo) == 1 def test_rational(): assert limit(1/y - (1/(y + x) + x/(y + x)/y)/z, x, oo) == (z - 1)/(y*z) assert limit(1/y - (1/(y + x) + x/(y + x)/y)/z, x, -oo) == (z - 1)/(y*z) def test_issue_5740(): assert limit(log(x)*z - log(2*x)*y, x, 0) == oo*sign(y - z) def test_issue_6366(): n = Symbol('n', integer=True, positive=True) r = (n + 1)*x**(n + 1)/(x**(n + 1) - 1) - x/(x - 1) assert limit(r, x, 1).cancel() == n/2 def test_factorial(): f = factorial(x) assert limit(f, x, oo) is oo assert limit(x/f, x, oo) == 0 # see Stirling's approximation: # https://en.wikipedia.org/wiki/Stirling's_approximation assert limit(f/(sqrt(2*pi*x)*(x/E)**x), x, oo) == 1 assert limit(f, x, -oo) == factorial(-oo) def test_issue_6560(): e = (5*x**3/4 - x*Rational(3, 4) + (y*(3*x**2/2 - S.Half) + 35*x**4/8 - 15*x**2/4 + Rational(3, 8))/(2*(y + 1))) assert limit(e, y, oo) == 5*x**3/4 + 3*x**2/4 - 3*x/4 - Rational(1, 4) @XFAIL def test_issue_5172(): n = Symbol('n') r = Symbol('r', positive=True) c = Symbol('c') p = Symbol('p', positive=True) m = Symbol('m', negative=True) expr = ((2*n*(n - r + 1)/(n + r*(n - r + 1)))**c + (r - 1)*(n*(n - r + 2)/(n + r*(n - r + 1)))**c - n)/(n**c - n) expr = expr.subs(c, c + 1) raises(NotImplementedError, lambda: limit(expr, n, oo)) assert limit(expr.subs(c, m), n, oo) == 1 assert limit(expr.subs(c, p), n, oo).simplify() == \ (2**(p + 1) + r - 1)/(r + 1)**(p + 1) def test_issue_7088(): a = Symbol('a') assert limit(sqrt(x/(x + a)), x, oo) == 1 def test_branch_cuts(): assert limit(asin(I*x + 2), x, 0) == pi - asin(2) assert limit(asin(I*x + 2), x, 0, '-') == asin(2) assert limit(asin(I*x - 2), x, 0) == -asin(2) assert limit(asin(I*x - 2), x, 0, '-') == -pi + asin(2) assert limit(acos(I*x + 2), x, 0) == -acos(2) assert limit(acos(I*x + 2), x, 0, '-') == acos(2) assert limit(acos(I*x - 2), x, 0) == acos(-2) assert limit(acos(I*x - 2), x, 0, '-') == 2*pi - acos(-2) assert limit(atan(x + 2*I), x, 0) == I*atanh(2) assert limit(atan(x + 2*I), x, 0, '-') == -pi + I*atanh(2) assert limit(atan(x - 2*I), x, 0) == pi - I*atanh(2) assert limit(atan(x - 2*I), x, 0, '-') == -I*atanh(2) assert limit(atan(1/x), x, 0) == pi/2 assert limit(atan(1/x), x, 0, '-') == -pi/2 assert limit(atan(x), x, oo) == pi/2 assert limit(atan(x), x, -oo) == -pi/2 assert limit(acot(x + S(1)/2*I), x, 0) == pi - I*acoth(S(1)/2) assert limit(acot(x + S(1)/2*I), x, 0, '-') == -I*acoth(S(1)/2) assert limit(acot(x - S(1)/2*I), x, 0) == I*acoth(S(1)/2) assert limit(acot(x - S(1)/2*I), x, 0, '-') == -pi + I*acoth(S(1)/2) assert limit(acot(x), x, 0) == pi/2 assert limit(acot(x), x, 0, '-') == -pi/2 assert limit(asec(I*x + S(1)/2), x, 0) == asec(S(1)/2) assert limit(asec(I*x + S(1)/2), x, 0, '-') == -asec(S(1)/2) assert limit(asec(I*x - S(1)/2), x, 0) == 2*pi - asec(-S(1)/2) assert limit(asec(I*x - S(1)/2), x, 0, '-') == asec(-S(1)/2) assert limit(acsc(I*x + S(1)/2), x, 0) == acsc(S(1)/2) assert limit(acsc(I*x + S(1)/2), x, 0, '-') == pi - acsc(S(1)/2) assert limit(acsc(I*x - S(1)/2), x, 0) == -pi + acsc(S(1)/2) assert limit(acsc(I*x - S(1)/2), x, 0, '-') == -acsc(S(1)/2) assert limit(log(I*x - 1), x, 0) == I*pi assert limit(log(I*x - 1), x, 0, '-') == -I*pi assert limit(log(-I*x - 1), x, 0) == -I*pi assert limit(log(-I*x - 1), x, 0, '-') == I*pi assert limit(sqrt(I*x - 1), x, 0) == I assert limit(sqrt(I*x - 1), x, 0, '-') == -I assert limit(sqrt(-I*x - 1), x, 0) == -I assert limit(sqrt(-I*x - 1), x, 0, '-') == I assert limit(cbrt(I*x - 1), x, 0) == (-1)**(S(1)/3) assert limit(cbrt(I*x - 1), x, 0, '-') == -(-1)**(S(2)/3) assert limit(cbrt(-I*x - 1), x, 0) == -(-1)**(S(2)/3) assert limit(cbrt(-I*x - 1), x, 0, '-') == (-1)**(S(1)/3) def test_issue_6364(): a = Symbol('a') e = z/(1 - sqrt(1 + z)*sin(a)**2 - sqrt(1 - z)*cos(a)**2) assert limit(e, z, 0) == 1/(cos(a)**2 - S.Half) def test_issue_4099(): a = Symbol('a') assert limit(a/x, x, 0) == oo*sign(a) assert limit(-a/x, x, 0) == -oo*sign(a) assert limit(-a*x, x, oo) == -oo*sign(a) assert limit(a*x, x, oo) == oo*sign(a) def test_issue_4503(): dx = Symbol('dx') assert limit((sqrt(1 + exp(x + dx)) - sqrt(1 + exp(x)))/dx, dx, 0) == \ exp(x)/(2*sqrt(exp(x) + 1)) def test_issue_8208(): assert limit(n**(Rational(1, 1e9) - 1), n, oo) == 0 def test_issue_8229(): assert limit((x**Rational(1, 4) - 2)/(sqrt(x) - 4)**Rational(2, 3), x, 16) == 0 def test_issue_8433(): d, t = symbols('d t', positive=True) assert limit(erf(1 - t/d), t, oo) == -1 def test_issue_8481(): k = Symbol('k', integer=True, nonnegative=True) lamda = Symbol('lamda', positive=True) assert limit(lamda**k * exp(-lamda) / factorial(k), k, oo) == 0 def test_issue_8635_18176(): x = Symbol('x', real=True) k = Symbol('k', positive=True) assert limit(x**n - x**(n - 0), x, oo) == 0 assert limit(x**n - x**(n - 5), x, oo) == oo assert limit(x**n - x**(n - 2.5), x, oo) == oo assert limit(x**n - x**(n - k - 1), x, oo) == oo x = Symbol('x', positive=True) assert limit(x**n - x**(n - 1), x, oo) == oo assert limit(x**n - x**(n + 2), x, oo) == -oo def test_issue_8730(): assert limit(subfactorial(x), x, oo) is oo def test_issue_9252(): n = Symbol('n', integer=True) c = Symbol('c', positive=True) assert limit((log(n))**(n/log(n)) / (1 + c)**n, n, oo) == 0 # limit should depend on the value of c raises(NotImplementedError, lambda: limit((log(n))**(n/log(n)) / c**n, n, oo)) def test_issue_9558(): assert limit(sin(x)**15, x, 0, '-') == 0 def test_issue_10801(): # make sure limits work with binomial assert limit(16**k / (k * binomial(2*k, k)**2), k, oo) == pi def test_issue_10976(): s, x = symbols('s x', real=True) assert limit(erf(s*x)/erf(s), s, 0) == x def test_issue_9041(): assert limit(factorial(n) / ((n/exp(1))**n * sqrt(2*pi*n)), n, oo) == 1 def test_issue_9205(): x, y, a = symbols('x, y, a') assert Limit(x, x, a).free_symbols == {a} assert Limit(x, x, a, '-').free_symbols == {a} assert Limit(x + y, x + y, a).free_symbols == {a} assert Limit(-x**2 + y, x**2, a).free_symbols == {y, a} def test_issue_9471(): assert limit(((27**(log(n,3)))/n**3),n,oo) == 1 assert limit(((27**(log(n,3)+1))/n**3),n,oo) == 27 def test_issue_11496(): assert limit(erfc(log(1/x)), x, oo) == 2 def test_issue_11879(): assert simplify(limit(((x+y)**n-x**n)/y, y, 0)) == n*x**(n-1) def test_limit_with_Float(): k = symbols("k") assert limit(1.0 ** k, k, oo) == 1 assert limit(0.3*1.0**k, k, oo) == Rational(3, 10) def test_issue_10610(): assert limit(3**x*3**(-x - 1)*(x + 1)**2/x**2, x, oo) == Rational(1, 3) def test_issue_6599(): assert limit((n + cos(n))/n, n, oo) == 1 def test_issue_12555(): assert limit((3**x + 2* x**10) / (x**10 + exp(x)), x, -oo) == 2 assert limit((3**x + 2* x**10) / (x**10 + exp(x)), x, oo) is oo def test_issue_12769(): r, z, x = symbols('r z x', real=True) a, b, s0, K, F0, s, T = symbols('a b s0 K F0 s T', positive=True, real=True) fx = (F0**b*K**b*r*s0 - sqrt((F0**2*K**(2*b)*a**2*(b - 1) + \ F0**(2*b)*K**2*a**2*(b - 1) + F0**(2*b)*K**(2*b)*s0**2*(b - 1)*(b**2 - 2*b + 1) - \ 2*F0**(2*b)*K**(b + 1)*a*r*s0*(b**2 - 2*b + 1) + \ 2*F0**(b + 1)*K**(2*b)*a*r*s0*(b**2 - 2*b + 1) - \ 2*F0**(b + 1)*K**(b + 1)*a**2*(b - 1))/((b - 1)*(b**2 - 2*b + 1))))*(b*r - b - r + 1) assert fx.subs(K, F0).factor(deep=True) == limit(fx, K, F0).factor(deep=True) def test_issue_13332(): assert limit(sqrt(30)*5**(-5*x - 1)*(46656*x)**x*(5*x + 2)**(5*x + 5*S.Half) * (6*x + 2)**(-6*x - 5*S.Half), x, oo) == Rational(25, 36) def test_issue_12564(): assert limit(x**2 + x*sin(x) + cos(x), x, -oo) is oo assert limit(x**2 + x*sin(x) + cos(x), x, oo) is oo assert limit(((x + cos(x))**2).expand(), x, oo) is oo assert limit(((x + sin(x))**2).expand(), x, oo) is oo assert limit(((x + cos(x))**2).expand(), x, -oo) is oo assert limit(((x + sin(x))**2).expand(), x, -oo) is oo def test_issue_14456(): raises(NotImplementedError, lambda: Limit(exp(x), x, zoo).doit()) raises(NotImplementedError, lambda: Limit(x**2/(x+1), x, zoo).doit()) def test_issue_14411(): assert limit(3*sec(4*pi*x - x/3), x, 3*pi/(24*pi - 2)) is -oo def test_issue_13382(): assert limit(x*(((x + 1)**2 + 1)/(x**2 + 1) - 1), x, oo) == 2 def test_issue_13403(): assert limit(x*(-1 + (x + log(x + 1) + 1)/(x + log(x))), x, oo) == 1 def test_issue_13416(): assert limit((-x**3*log(x)**3 + (x - 1)*(x + 1)**2*log(x + 1)**3)/(x**2*log(x)**3), x, oo) == 1 def test_issue_13462(): assert limit(n**2*(2*n*(-(1 - 1/(2*n))**x + 1) - x - (-x**2/4 + x/4)/n), n, oo) == x**3/24 - x**2/8 + x/12 def test_issue_13750(): a = Symbol('a') assert limit(erf(a - x), x, oo) == -1 assert limit(erf(sqrt(x) - x), x, oo) == -1 def test_issue_14514(): assert limit((1/(log(x)**log(x)))**(1/x), x, oo) == 1 def test_issue_14574(): assert limit(sqrt(x)*cos(x - x**2) / (x + 1), x, oo) == 0 def test_issue_10102(): assert limit(fresnels(x), x, oo) == S.Half assert limit(3 + fresnels(x), x, oo) == 3 + S.Half assert limit(5*fresnels(x), x, oo) == Rational(5, 2) assert limit(fresnelc(x), x, oo) == S.Half assert limit(fresnels(x), x, -oo) == Rational(-1, 2) assert limit(4*fresnelc(x), x, -oo) == -2 def test_issue_14377(): raises(NotImplementedError, lambda: limit(exp(I*x)*sin(pi*x), x, oo)) def test_issue_15146(): e = (x/2) * (-2*x**3 - 2*(x**3 - 1) * x**2 * digamma(x**3 + 1) + \ 2*(x**3 - 1) * x**2 * digamma(x**3 + x + 1) + x + 3) assert limit(e, x, oo) == S(1)/3 def test_issue_15202(): e = (2**x*(2 + 2**(-x)*(-2*2**x + x + 2))/(x + 1))**(x + 1) assert limit(e, x, oo) == exp(1) e = (log(x, 2)**7 + 10*x*factorial(x) + 5**x) / (factorial(x + 1) + 3*factorial(x) + 10**x) assert limit(e, x, oo) == 10 def test_issue_15282(): assert limit((x**2000 - (x + 1)**2000) / x**1999, x, oo) == -2000 def test_issue_15984(): assert limit((-x + log(exp(x) + 1))/x, x, oo, dir='-') == 0 def test_issue_13571(): assert limit(uppergamma(x, 1) / gamma(x), x, oo) == 1 def test_issue_13575(): assert limit(acos(erfi(x)), x, 1) == acos(erfi(S.One)) def test_issue_17325(): assert Limit(sin(x)/x, x, 0, dir="+-").doit() == 1 assert Limit(x**2, x, 0, dir="+-").doit() == 0 assert Limit(1/x**2, x, 0, dir="+-").doit() is oo assert Limit(1/x, x, 0, dir="+-").doit() is zoo def test_issue_10978(): assert LambertW(x).limit(x, 0) == 0 def test_issue_14313_comment(): assert limit(floor(n/2), n, oo) is oo @XFAIL def test_issue_15323(): d = ((1 - 1/x)**x).diff(x) assert limit(d, x, 1, dir='+') == 1 def test_issue_12571(): assert limit(-LambertW(-log(x))/log(x), x, 1) == 1 def test_issue_14590(): assert limit((x**3*((x + 1)/x)**x)/((x + 1)*(x + 2)*(x + 3)), x, oo) == exp(1) def test_issue_14393(): a, b = symbols('a b') assert limit((x**b - y**b)/(x**a - y**a), x, y) == b*y**(-a + b)/a def test_issue_14556(): assert limit(factorial(n + 1)**(1/(n + 1)) - factorial(n)**(1/n), n, oo) == exp(-1) def test_issue_14811(): assert limit(((1 + ((S(2)/3)**(x + 1)))**(2**x))/(2**((S(4)/3)**(x - 1))), x, oo) == oo def test_issue_14874(): assert limit(besselk(0, x), x, oo) == 0 def test_issue_16222(): assert limit(exp(x), x, 1000000000) == exp(1000000000) def test_issue_16714(): assert limit(((x**(x + 1) + (x + 1)**x) / x**(x + 1))**x, x, oo) == exp(exp(1)) def test_issue_16722(): z = symbols('z', positive=True) assert limit(binomial(n + z, n)*n**-z, n, oo) == 1/gamma(z + 1) z = symbols('z', positive=True, integer=True) assert limit(binomial(n + z, n)*n**-z, n, oo) == 1/gamma(z + 1) def test_issue_17431(): assert limit(((n + 1) + 1) / (((n + 1) + 2) * factorial(n + 1)) * (n + 2) * factorial(n) / (n + 1), n, oo) == 0 assert limit((n + 2)**2*factorial(n)/((n + 1)*(n + 3)*factorial(n + 1)) , n, oo) == 0 assert limit((n + 1) * factorial(n) / (n * factorial(n + 1)), n, oo) == 0 def test_issue_17671(): assert limit(Ei(-log(x)) - log(log(x))/x, x, 1) == EulerGamma def test_issue_17751(): a, b, c, x = symbols('a b c x', positive=True) assert limit((a + 1)*x - sqrt((a + 1)**2*x**2 + b*x + c), x, oo) == -b/(2*a + 2) def test_issue_17792(): assert limit(factorial(n)/sqrt(n)*(exp(1)/n)**n, n, oo) == sqrt(2)*sqrt(pi) def test_issue_18118(): assert limit(sign(sin(x)), x, 0, "-") == -1 assert limit(sign(sin(x)), x, 0, "+") == 1 def test_issue_18306(): assert limit(sin(sqrt(x))/sqrt(sin(x)), x, 0, '+') == 1 def test_issue_18378(): assert limit(log(exp(3*x) + x)/log(exp(x) + x**100), x, oo) == 3 def test_issue_18399(): assert limit((1 - S(1)/2*x)**(3*x), x, oo) is zoo assert limit((-x)**x, x, oo) is zoo def test_issue_18442(): assert limit(tan(x)**(2**(sqrt(pi))), x, oo, dir='-') == Limit(tan(x)**(2**(sqrt(pi))), x, oo, dir='-') def test_issue_18452(): assert limit(abs(log(x))**x, x, 0) == 1 assert limit(abs(log(x))**x, x, 0, "-") == 1 def test_issue_18482(): assert limit((2*exp(3*x)/(exp(2*x) + 1))**(1/x), x, oo) == exp(1) def test_issue_18508(): assert limit(sin(x)/sqrt(1-cos(x)), x, 0) == sqrt(2) assert limit(sin(x)/sqrt(1-cos(x)), x, 0, dir='+') == sqrt(2) assert limit(sin(x)/sqrt(1-cos(x)), x, 0, dir='-') == -sqrt(2) def test_issue_18521(): raises(NotImplementedError, lambda: limit(exp((2 - n) * x), x, oo)) def test_issue_18969(): a, b = symbols('a b', positive=True) assert limit(LambertW(a), a, b) == LambertW(b) assert limit(exp(LambertW(a)), a, b) == exp(LambertW(b)) def test_issue_18992(): assert limit(n/(factorial(n)**(1/n)), n, oo) == exp(1) def test_issue_19067(): x = Symbol('x') assert limit(gamma(x)/(gamma(x - 1)*gamma(x + 2)), x, 0) == -1 def test_issue_19586(): assert limit(x**(2**x*3**(-x)), x, oo) == 1 def test_issue_13715(): n = Symbol('n') p = Symbol('p', zero=True) assert limit(n + p, n, 0) == 0 def test_issue_15055(): assert limit(n**3*((-n - 1)*sin(1/n) + (n + 2)*sin(1/(n + 1)))/(-n + 1), n, oo) == 1 def test_issue_16708(): m, vi = symbols('m vi', positive=True) B, ti, d = symbols('B ti d') assert limit((B*ti*vi - sqrt(m)*sqrt(-2*B*d*vi + m*(vi)**2) + m*vi)/(B*vi), B, 0) == (d + ti*vi)/vi def test_issue_19453(): beta = Symbol("beta", positive=True) h = Symbol("h", positive=True) m = Symbol("m", positive=True) w = Symbol("omega", positive=True) g = Symbol("g", positive=True) e = exp(1) q = 3*h**2*beta*g*e**(0.5*h*beta*w) p = m**2*w**2 s = e**(h*beta*w) - 1 Z = -q/(4*p*s) - q/(2*p*s**2) - q*(e**(h*beta*w) + 1)/(2*p*s**3)\ + e**(0.5*h*beta*w)/s E = -diff(log(Z), beta) assert limit(E - 0.5*h*w, beta, oo) == 0 assert limit(E.simplify() - 0.5*h*w, beta, oo) == 0 def test_issue_19739(): assert limit((-S(1)/4)**x, x, oo) == 0 def test_issue_19766(): assert limit(2**(-x)*sqrt(4**(x + 1) + 1), x, oo) == 2 def test_issue_19770(): m = Symbol('m') # the result is not 0 for non-real m assert limit(cos(m*x)/x, x, oo) == Limit(cos(m*x)/x, x, oo, dir='-') m = Symbol('m', real=True) # can be improved to give the correct result 0 assert limit(cos(m*x)/x, x, oo) == Limit(cos(m*x)/x, x, oo, dir='-') m = Symbol('m', nonzero=True) assert limit(cos(m*x), x, oo) == AccumBounds(-1, 1) assert limit(cos(m*x)/x, x, oo) == 0 def test_issue_7535(): assert limit(tan(x)/sin(tan(x)), x, pi/2) == Limit(tan(x)/sin(tan(x)), x, pi/2, dir='+') assert limit(tan(x)/sin(tan(x)), x, pi/2, dir='-') == Limit(tan(x)/sin(tan(x)), x, pi/2, dir='-') assert limit(tan(x)/sin(tan(x)), x, pi/2, dir='+-') == Limit(tan(x)/sin(tan(x)), x, pi/2, dir='+-') assert limit(sin(tan(x)),x,pi/2) == AccumBounds(-1, 1) assert -oo*(1/sin(-oo)) == AccumBounds(-oo, oo) assert oo*(1/sin(oo)) == AccumBounds(-oo, oo) assert oo*(1/sin(-oo)) == AccumBounds(-oo, oo) assert -oo*(1/sin(oo)) == AccumBounds(-oo, oo) def test_issue_20365(): assert limit(((x + 1)**(1/x) - E)/x, x, 0) == -E/2 def test_issue_21031(): assert limit(((1 + x)**(1/x) - (1 + 2*x)**(1/(2*x)))/asin(x), x, 0) == E/2 def test_issue_21038(): assert limit(sin(pi*x)/(3*x - 12), x, 4) == pi/3 def test_issue_20578(): expr = abs(x) * sin(1/x) assert limit(expr,x,0,'+') == 0 assert limit(expr,x,0,'-') == 0 assert limit(expr,x,0,'+-') == 0 def test_issue_21415(): exp = (x-1)*cos(1/(x-1)) assert exp.limit(x,1) == 0 assert exp.expand().limit(x,1) == 0 def test_issue_21530(): assert limit(sinh(n + 1)/sinh(n), n, oo) == E def test_issue_21550(): r = (sqrt(5) - 1)/2 assert limit((x - r)/(x**2 + x - 1), x, r) == sqrt(5)/5 def test_issue_21661(): out = limit((x**(x + 1) * (log(x) + 1) + 1) / x, x, 11) assert out == S(3138428376722)/11 + 285311670611*log(11) def test_issue_21701(): assert limit((besselj(z, x)/x**z).subs(z, 7), x, 0) == S(1)/645120 def test_issue_21721(): a = Symbol('a', real=True) I = integrate(1/(pi*(1 + (x - a)**2)), x) assert I.limit(x, oo) == S.Half def test_issue_21756(): term = (1 - exp(-2*I*pi*z))/(1 - exp(-2*I*pi*z/5)) assert term.limit(z, 0) == 5 assert re(term).limit(z, 0) == 5 def test_issue_21785(): a = Symbol('a') assert sqrt((-a**2 + x**2)/(1 - x**2)).limit(a, 1, '-') == I def test_issue_22181(): assert limit((-1)**x * 2**(-x), x, oo) == 0
5eabfc3b207fcf71ab0d46bd61dc7263df2fabf5ebc2230acf0329a8ac7c5c54
from sympy.core.add import Add from sympy.core.mul import Mul from sympy.core.numbers import (I, Rational, pi) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, symbols) from sympy.functions.elementary.hyperbolic import (cosh, coth, csch, sech, sinh, tanh) from sympy.functions.elementary.miscellaneous import (root, sqrt) from sympy.functions.elementary.trigonometric import (cos, cot, csc, sec, sin, tan) from sympy.simplify.powsimp import powsimp from sympy.simplify.fu import ( L, TR1, TR10, TR10i, TR11, _TR11, TR12, TR12i, TR13, TR14, TR15, TR16, TR111, TR2, TR2i, TR3, TR5, TR6, TR7, TR8, TR9, TRmorrie, _TR56 as T, TRpower, hyper_as_trig, fu, process_common_addends, trig_split, as_f_sign_1) from sympy.core.random import verify_numerically from sympy.abc import a, b, c, x, y, z def test_TR1(): assert TR1(2*csc(x) + sec(x)) == 1/cos(x) + 2/sin(x) def test_TR2(): assert TR2(tan(x)) == sin(x)/cos(x) assert TR2(cot(x)) == cos(x)/sin(x) assert TR2(tan(tan(x) - sin(x)/cos(x))) == 0 def test_TR2i(): # just a reminder that ratios of powers only simplify if both # numerator and denominator satisfy the condition that each # has a positive base or an integer exponent; e.g. the following, # at y=-1, x=1/2 gives sqrt(2)*I != -sqrt(2)*I assert powsimp(2**x/y**x) != (2/y)**x assert TR2i(sin(x)/cos(x)) == tan(x) assert TR2i(sin(x)*sin(y)/cos(x)) == tan(x)*sin(y) assert TR2i(1/(sin(x)/cos(x))) == 1/tan(x) assert TR2i(1/(sin(x)*sin(y)/cos(x))) == 1/tan(x)/sin(y) assert TR2i(sin(x)/2/(cos(x) + 1)) == sin(x)/(cos(x) + 1)/2 assert TR2i(sin(x)/2/(cos(x) + 1), half=True) == tan(x/2)/2 assert TR2i(sin(1)/(cos(1) + 1), half=True) == tan(S.Half) assert TR2i(sin(2)/(cos(2) + 1), half=True) == tan(1) assert TR2i(sin(4)/(cos(4) + 1), half=True) == tan(2) assert TR2i(sin(5)/(cos(5) + 1), half=True) == tan(5*S.Half) assert TR2i((cos(1) + 1)/sin(1), half=True) == 1/tan(S.Half) assert TR2i((cos(2) + 1)/sin(2), half=True) == 1/tan(1) assert TR2i((cos(4) + 1)/sin(4), half=True) == 1/tan(2) assert TR2i((cos(5) + 1)/sin(5), half=True) == 1/tan(5*S.Half) assert TR2i((cos(1) + 1)**(-a)*sin(1)**a, half=True) == tan(S.Half)**a assert TR2i((cos(2) + 1)**(-a)*sin(2)**a, half=True) == tan(1)**a assert TR2i((cos(4) + 1)**(-a)*sin(4)**a, half=True) == (cos(4) + 1)**(-a)*sin(4)**a assert TR2i((cos(5) + 1)**(-a)*sin(5)**a, half=True) == (cos(5) + 1)**(-a)*sin(5)**a assert TR2i((cos(1) + 1)**a*sin(1)**(-a), half=True) == tan(S.Half)**(-a) assert TR2i((cos(2) + 1)**a*sin(2)**(-a), half=True) == tan(1)**(-a) assert TR2i((cos(4) + 1)**a*sin(4)**(-a), half=True) == (cos(4) + 1)**a*sin(4)**(-a) assert TR2i((cos(5) + 1)**a*sin(5)**(-a), half=True) == (cos(5) + 1)**a*sin(5)**(-a) i = symbols('i', integer=True) assert TR2i(((cos(5) + 1)**i*sin(5)**(-i)), half=True) == tan(5*S.Half)**(-i) assert TR2i(1/((cos(5) + 1)**i*sin(5)**(-i)), half=True) == tan(5*S.Half)**i def test_TR3(): assert TR3(cos(y - x*(y - x))) == cos(x*(x - y) + y) assert cos(pi/2 + x) == -sin(x) assert cos(30*pi/2 + x) == -cos(x) for f in (cos, sin, tan, cot, csc, sec): i = f(pi*Rational(3, 7)) j = TR3(i) assert verify_numerically(i, j) and i.func != j.func def test__TR56(): h = lambda x: 1 - x assert T(sin(x)**3, sin, cos, h, 4, False) == sin(x)*(-cos(x)**2 + 1) assert T(sin(x)**10, sin, cos, h, 4, False) == sin(x)**10 assert T(sin(x)**6, sin, cos, h, 6, False) == (-cos(x)**2 + 1)**3 assert T(sin(x)**6, sin, cos, h, 6, True) == sin(x)**6 assert T(sin(x)**8, sin, cos, h, 10, True) == (-cos(x)**2 + 1)**4 # issue 17137 assert T(sin(x)**I, sin, cos, h, 4, True) == sin(x)**I assert T(sin(x)**(2*I + 1), sin, cos, h, 4, True) == sin(x)**(2*I + 1) def test_TR5(): assert TR5(sin(x)**2) == -cos(x)**2 + 1 assert TR5(sin(x)**-2) == sin(x)**(-2) assert TR5(sin(x)**4) == (-cos(x)**2 + 1)**2 def test_TR6(): assert TR6(cos(x)**2) == -sin(x)**2 + 1 assert TR6(cos(x)**-2) == cos(x)**(-2) assert TR6(cos(x)**4) == (-sin(x)**2 + 1)**2 def test_TR7(): assert TR7(cos(x)**2) == cos(2*x)/2 + S.Half assert TR7(cos(x)**2 + 1) == cos(2*x)/2 + Rational(3, 2) def test_TR8(): assert TR8(cos(2)*cos(3)) == cos(5)/2 + cos(1)/2 assert TR8(cos(2)*sin(3)) == sin(5)/2 + sin(1)/2 assert TR8(sin(2)*sin(3)) == -cos(5)/2 + cos(1)/2 assert TR8(sin(1)*sin(2)*sin(3)) == sin(4)/4 - sin(6)/4 + sin(2)/4 assert TR8(cos(2)*cos(3)*cos(4)*cos(5)) == \ cos(4)/4 + cos(10)/8 + cos(2)/8 + cos(8)/8 + cos(14)/8 + \ cos(6)/8 + Rational(1, 8) assert TR8(cos(2)*cos(3)*cos(4)*cos(5)*cos(6)) == \ cos(10)/8 + cos(4)/8 + 3*cos(2)/16 + cos(16)/16 + cos(8)/8 + \ cos(14)/16 + cos(20)/16 + cos(12)/16 + Rational(1, 16) + cos(6)/8 assert TR8(sin(pi*Rational(3, 7))**2*cos(pi*Rational(3, 7))**2/(16*sin(pi/7)**2)) == Rational(1, 64) def test_TR9(): a = S.Half b = 3*a assert TR9(a) == a assert TR9(cos(1) + cos(2)) == 2*cos(a)*cos(b) assert TR9(cos(1) - cos(2)) == 2*sin(a)*sin(b) assert TR9(sin(1) - sin(2)) == -2*sin(a)*cos(b) assert TR9(sin(1) + sin(2)) == 2*sin(b)*cos(a) assert TR9(cos(1) + 2*sin(1) + 2*sin(2)) == cos(1) + 4*sin(b)*cos(a) assert TR9(cos(4) + cos(2) + 2*cos(1)*cos(3)) == 4*cos(1)*cos(3) assert TR9((cos(4) + cos(2))/cos(3)/2 + cos(3)) == 2*cos(1)*cos(2) assert TR9(cos(3) + cos(4) + cos(5) + cos(6)) == \ 4*cos(S.Half)*cos(1)*cos(Rational(9, 2)) assert TR9(cos(3) + cos(3)*cos(2)) == cos(3) + cos(2)*cos(3) assert TR9(-cos(y) + cos(x*y)) == -2*sin(x*y/2 - y/2)*sin(x*y/2 + y/2) assert TR9(-sin(y) + sin(x*y)) == 2*sin(x*y/2 - y/2)*cos(x*y/2 + y/2) c = cos(x) s = sin(x) for si in ((1, 1), (1, -1), (-1, 1), (-1, -1)): for a in ((c, s), (s, c), (cos(x), cos(x*y)), (sin(x), sin(x*y))): args = zip(si, a) ex = Add(*[Mul(*ai) for ai in args]) t = TR9(ex) assert not (a[0].func == a[1].func and ( not verify_numerically(ex, t.expand(trig=True)) or t.is_Add) or a[1].func != a[0].func and ex != t) def test_TR10(): assert TR10(cos(a + b)) == -sin(a)*sin(b) + cos(a)*cos(b) assert TR10(sin(a + b)) == sin(a)*cos(b) + sin(b)*cos(a) assert TR10(sin(a + b + c)) == \ (-sin(a)*sin(b) + cos(a)*cos(b))*sin(c) + \ (sin(a)*cos(b) + sin(b)*cos(a))*cos(c) assert TR10(cos(a + b + c)) == \ (-sin(a)*sin(b) + cos(a)*cos(b))*cos(c) - \ (sin(a)*cos(b) + sin(b)*cos(a))*sin(c) def test_TR10i(): assert TR10i(cos(1)*cos(3) + sin(1)*sin(3)) == cos(2) assert TR10i(cos(1)*cos(3) - sin(1)*sin(3)) == cos(4) assert TR10i(cos(1)*sin(3) - sin(1)*cos(3)) == sin(2) assert TR10i(cos(1)*sin(3) + sin(1)*cos(3)) == sin(4) assert TR10i(cos(1)*sin(3) + sin(1)*cos(3) + 7) == sin(4) + 7 assert TR10i(cos(1)*sin(3) + sin(1)*cos(3) + cos(3)) == cos(3) + sin(4) assert TR10i(2*cos(1)*sin(3) + 2*sin(1)*cos(3) + cos(3)) == \ 2*sin(4) + cos(3) assert TR10i(cos(2)*cos(3) + sin(2)*(cos(1)*sin(2) + cos(2)*sin(1))) == \ cos(1) eq = (cos(2)*cos(3) + sin(2)*( cos(1)*sin(2) + cos(2)*sin(1)))*cos(5) + sin(1)*sin(5) assert TR10i(eq) == TR10i(eq.expand()) == cos(4) assert TR10i(sqrt(2)*cos(x)*x + sqrt(6)*sin(x)*x) == \ 2*sqrt(2)*x*sin(x + pi/6) assert TR10i(cos(x)/sqrt(6) + sin(x)/sqrt(2) + cos(x)/sqrt(6)/3 + sin(x)/sqrt(2)/3) == 4*sqrt(6)*sin(x + pi/6)/9 assert TR10i(cos(x)/sqrt(6) + sin(x)/sqrt(2) + cos(y)/sqrt(6)/3 + sin(y)/sqrt(2)/3) == \ sqrt(6)*sin(x + pi/6)/3 + sqrt(6)*sin(y + pi/6)/9 assert TR10i(cos(x) + sqrt(3)*sin(x) + 2*sqrt(3)*cos(x + pi/6)) == 4*cos(x) assert TR10i(cos(x) + sqrt(3)*sin(x) + 2*sqrt(3)*cos(x + pi/6) + 4*sin(x)) == 4*sqrt(2)*sin(x + pi/4) assert TR10i(cos(2)*sin(3) + sin(2)*cos(4)) == \ sin(2)*cos(4) + sin(3)*cos(2) A = Symbol('A', commutative=False) assert TR10i(sqrt(2)*cos(x)*A + sqrt(6)*sin(x)*A) == \ 2*sqrt(2)*sin(x + pi/6)*A c = cos(x) s = sin(x) h = sin(y) r = cos(y) for si in ((1, 1), (1, -1), (-1, 1), (-1, -1)): for argsi in ((c*r, s*h), (c*h, s*r)): # explicit 2-args args = zip(si, argsi) ex = Add(*[Mul(*ai) for ai in args]) t = TR10i(ex) assert not (ex - t.expand(trig=True) or t.is_Add) c = cos(x) s = sin(x) h = sin(pi/6) r = cos(pi/6) for si in ((1, 1), (1, -1), (-1, 1), (-1, -1)): for argsi in ((c*r, s*h), (c*h, s*r)): # induced args = zip(si, argsi) ex = Add(*[Mul(*ai) for ai in args]) t = TR10i(ex) assert not (ex - t.expand(trig=True) or t.is_Add) def test_TR11(): assert TR11(sin(2*x)) == 2*sin(x)*cos(x) assert TR11(sin(4*x)) == 4*((-sin(x)**2 + cos(x)**2)*sin(x)*cos(x)) assert TR11(sin(x*Rational(4, 3))) == \ 4*((-sin(x/3)**2 + cos(x/3)**2)*sin(x/3)*cos(x/3)) assert TR11(cos(2*x)) == -sin(x)**2 + cos(x)**2 assert TR11(cos(4*x)) == \ (-sin(x)**2 + cos(x)**2)**2 - 4*sin(x)**2*cos(x)**2 assert TR11(cos(2)) == cos(2) assert TR11(cos(pi*Rational(3, 7)), pi*Rational(2, 7)) == -cos(pi*Rational(2, 7))**2 + sin(pi*Rational(2, 7))**2 assert TR11(cos(4), 2) == -sin(2)**2 + cos(2)**2 assert TR11(cos(6), 2) == cos(6) assert TR11(sin(x)/cos(x/2), x/2) == 2*sin(x/2) def test__TR11(): assert _TR11(sin(x/3)*sin(2*x)*sin(x/4)/(cos(x/6)*cos(x/8))) == \ 4*sin(x/8)*sin(x/6)*sin(2*x),_TR11(sin(x/3)*sin(2*x)*sin(x/4)/(cos(x/6)*cos(x/8))) assert _TR11(sin(x/3)/cos(x/6)) == 2*sin(x/6) assert _TR11(cos(x/6)/sin(x/3)) == 1/(2*sin(x/6)) assert _TR11(sin(2*x)*cos(x/8)/sin(x/4)) == sin(2*x)/(2*sin(x/8)), _TR11(sin(2*x)*cos(x/8)/sin(x/4)) assert _TR11(sin(x)/sin(x/2)) == 2*cos(x/2) def test_TR12(): assert TR12(tan(x + y)) == (tan(x) + tan(y))/(-tan(x)*tan(y) + 1) assert TR12(tan(x + y + z)) ==\ (tan(z) + (tan(x) + tan(y))/(-tan(x)*tan(y) + 1))/( 1 - (tan(x) + tan(y))*tan(z)/(-tan(x)*tan(y) + 1)) assert TR12(tan(x*y)) == tan(x*y) def test_TR13(): assert TR13(tan(3)*tan(2)) == -tan(2)/tan(5) - tan(3)/tan(5) + 1 assert TR13(cot(3)*cot(2)) == 1 + cot(3)*cot(5) + cot(2)*cot(5) assert TR13(tan(1)*tan(2)*tan(3)) == \ (-tan(2)/tan(5) - tan(3)/tan(5) + 1)*tan(1) assert TR13(tan(1)*tan(2)*cot(3)) == \ (-tan(2)/tan(3) + 1 - tan(1)/tan(3))*cot(3) def test_L(): assert L(cos(x) + sin(x)) == 2 def test_fu(): assert fu(sin(50)**2 + cos(50)**2 + sin(pi/6)) == Rational(3, 2) assert fu(sqrt(6)*cos(x) + sqrt(2)*sin(x)) == 2*sqrt(2)*sin(x + pi/3) eq = sin(x)**4 - cos(y)**2 + sin(y)**2 + 2*cos(x)**2 assert fu(eq) == cos(x)**4 - 2*cos(y)**2 + 2 assert fu(S.Half - cos(2*x)/2) == sin(x)**2 assert fu(sin(a)*(cos(b) - sin(b)) + cos(a)*(sin(b) + cos(b))) == \ sqrt(2)*sin(a + b + pi/4) assert fu(sqrt(3)*cos(x)/2 + sin(x)/2) == sin(x + pi/3) assert fu(1 - sin(2*x)**2/4 - sin(y)**2 - cos(x)**4) == \ -cos(x)**2 + cos(y)**2 assert fu(cos(pi*Rational(4, 9))) == sin(pi/18) assert fu(cos(pi/9)*cos(pi*Rational(2, 9))*cos(pi*Rational(3, 9))*cos(pi*Rational(4, 9))) == Rational(1, 16) assert fu( tan(pi*Rational(7, 18)) + tan(pi*Rational(5, 18)) - sqrt(3)*tan(pi*Rational(5, 18))*tan(pi*Rational(7, 18))) == \ -sqrt(3) assert fu(tan(1)*tan(2)) == tan(1)*tan(2) expr = Mul(*[cos(2**i) for i in range(10)]) assert fu(expr) == sin(1024)/(1024*sin(1)) # issue #18059: assert fu(cos(x) + sqrt(sin(x)**2)) == cos(x) + sqrt(sin(x)**2) assert fu((-14*sin(x)**3 + 35*sin(x) + 6*sqrt(3)*cos(x)**3 + 9*sqrt(3)*cos(x))/((cos(2*x) + 4))) == \ 7*sin(x) + 3*sqrt(3)*cos(x) def test_objective(): assert fu(sin(x)/cos(x), measure=lambda x: x.count_ops()) == \ tan(x) assert fu(sin(x)/cos(x), measure=lambda x: -x.count_ops()) == \ sin(x)/cos(x) def test_process_common_addends(): # this tests that the args are not evaluated as they are given to do # and that key2 works when key1 is False do = lambda x: Add(*[i**(i%2) for i in x.args]) assert process_common_addends(Add(*[1, 2, 3, 4], evaluate=False), do, key2=lambda x: x%2, key1=False) == 1**1 + 3**1 + 2**0 + 4**0 def test_trig_split(): assert trig_split(cos(x), cos(y)) == (1, 1, 1, x, y, True) assert trig_split(2*cos(x), -2*cos(y)) == (2, 1, -1, x, y, True) assert trig_split(cos(x)*sin(y), cos(y)*sin(y)) == \ (sin(y), 1, 1, x, y, True) assert trig_split(cos(x), -sqrt(3)*sin(x), two=True) == \ (2, 1, -1, x, pi/6, False) assert trig_split(cos(x), sin(x), two=True) == \ (sqrt(2), 1, 1, x, pi/4, False) assert trig_split(cos(x), -sin(x), two=True) == \ (sqrt(2), 1, -1, x, pi/4, False) assert trig_split(sqrt(2)*cos(x), -sqrt(6)*sin(x), two=True) == \ (2*sqrt(2), 1, -1, x, pi/6, False) assert trig_split(-sqrt(6)*cos(x), -sqrt(2)*sin(x), two=True) == \ (-2*sqrt(2), 1, 1, x, pi/3, False) assert trig_split(cos(x)/sqrt(6), sin(x)/sqrt(2), two=True) == \ (sqrt(6)/3, 1, 1, x, pi/6, False) assert trig_split(-sqrt(6)*cos(x)*sin(y), -sqrt(2)*sin(x)*sin(y), two=True) == \ (-2*sqrt(2)*sin(y), 1, 1, x, pi/3, False) assert trig_split(cos(x), sin(x)) is None assert trig_split(cos(x), sin(z)) is None assert trig_split(2*cos(x), -sin(x)) is None assert trig_split(cos(x), -sqrt(3)*sin(x)) is None assert trig_split(cos(x)*cos(y), sin(x)*sin(z)) is None assert trig_split(cos(x)*cos(y), sin(x)*sin(y)) is None assert trig_split(-sqrt(6)*cos(x), sqrt(2)*sin(x)*sin(y), two=True) is \ None assert trig_split(sqrt(3)*sqrt(x), cos(3), two=True) is None assert trig_split(sqrt(3)*root(x, 3), sin(3)*cos(2), two=True) is None assert trig_split(cos(5)*cos(6), cos(7)*sin(5), two=True) is None def test_TRmorrie(): assert TRmorrie(7*Mul(*[cos(i) for i in range(10)])) == \ 7*sin(12)*sin(16)*cos(5)*cos(7)*cos(9)/(64*sin(1)*sin(3)) assert TRmorrie(x) == x assert TRmorrie(2*x) == 2*x e = cos(pi/7)*cos(pi*Rational(2, 7))*cos(pi*Rational(4, 7)) assert TR8(TRmorrie(e)) == Rational(-1, 8) e = Mul(*[cos(2**i*pi/17) for i in range(1, 17)]) assert TR8(TR3(TRmorrie(e))) == Rational(1, 65536) # issue 17063 eq = cos(x)/cos(x/2) assert TRmorrie(eq) == eq # issue #20430 eq = cos(x/2)*sin(x/2)*cos(x)**3 assert TRmorrie(eq) == sin(2*x)*cos(x)**2/4 def test_TRpower(): assert TRpower(1/sin(x)**2) == 1/sin(x)**2 assert TRpower(cos(x)**3*sin(x/2)**4) == \ (3*cos(x)/4 + cos(3*x)/4)*(-cos(x)/2 + cos(2*x)/8 + Rational(3, 8)) for k in range(2, 8): assert verify_numerically(sin(x)**k, TRpower(sin(x)**k)) assert verify_numerically(cos(x)**k, TRpower(cos(x)**k)) def test_hyper_as_trig(): from sympy.simplify.fu import _osborne, _osbornei eq = sinh(x)**2 + cosh(x)**2 t, f = hyper_as_trig(eq) assert f(fu(t)) == cosh(2*x) e, f = hyper_as_trig(tanh(x + y)) assert f(TR12(e)) == (tanh(x) + tanh(y))/(tanh(x)*tanh(y) + 1) d = Dummy() assert _osborne(sinh(x), d) == I*sin(x*d) assert _osborne(tanh(x), d) == I*tan(x*d) assert _osborne(coth(x), d) == cot(x*d)/I assert _osborne(cosh(x), d) == cos(x*d) assert _osborne(sech(x), d) == sec(x*d) assert _osborne(csch(x), d) == csc(x*d)/I for func in (sinh, cosh, tanh, coth, sech, csch): h = func(pi) assert _osbornei(_osborne(h, d), d) == h # /!\ the _osborne functions are not meant to work # in the o(i(trig, d), d) direction so we just check # that they work as they are supposed to work assert _osbornei(cos(x*y + z), y) == cosh(x + z*I) assert _osbornei(sin(x*y + z), y) == sinh(x + z*I)/I assert _osbornei(tan(x*y + z), y) == tanh(x + z*I)/I assert _osbornei(cot(x*y + z), y) == coth(x + z*I)*I assert _osbornei(sec(x*y + z), y) == sech(x + z*I) assert _osbornei(csc(x*y + z), y) == csch(x + z*I)*I def test_TR12i(): ta, tb, tc = [tan(i) for i in (a, b, c)] assert TR12i((ta + tb)/(-ta*tb + 1)) == tan(a + b) assert TR12i((ta + tb)/(ta*tb - 1)) == -tan(a + b) assert TR12i((-ta - tb)/(ta*tb - 1)) == tan(a + b) eq = (ta + tb)/(-ta*tb + 1)**2*(-3*ta - 3*tc)/(2*(ta*tc - 1)) assert TR12i(eq.expand()) == \ -3*tan(a + b)*tan(a + c)/(tan(a) + tan(b) - 1)/2 assert TR12i(tan(x)/sin(x)) == tan(x)/sin(x) eq = (ta + cos(2))/(-ta*tb + 1) assert TR12i(eq) == eq eq = (ta + tb + 2)**2/(-ta*tb + 1) assert TR12i(eq) == eq eq = ta/(-ta*tb + 1) assert TR12i(eq) == eq eq = (((ta + tb)*(a + 1)).expand())**2/(ta*tb - 1) assert TR12i(eq) == -(a + 1)**2*tan(a + b) def test_TR14(): eq = (cos(x) - 1)*(cos(x) + 1) ans = -sin(x)**2 assert TR14(eq) == ans assert TR14(1/eq) == 1/ans assert TR14((cos(x) - 1)**2*(cos(x) + 1)**2) == ans**2 assert TR14((cos(x) - 1)**2*(cos(x) + 1)**3) == ans**2*(cos(x) + 1) assert TR14((cos(x) - 1)**3*(cos(x) + 1)**2) == ans**2*(cos(x) - 1) eq = (cos(x) - 1)**y*(cos(x) + 1)**y assert TR14(eq) == eq eq = (cos(x) - 2)**y*(cos(x) + 1) assert TR14(eq) == eq eq = (tan(x) - 2)**2*(cos(x) + 1) assert TR14(eq) == eq i = symbols('i', integer=True) assert TR14((cos(x) - 1)**i*(cos(x) + 1)**i) == ans**i assert TR14((sin(x) - 1)**i*(sin(x) + 1)**i) == (-cos(x)**2)**i # could use extraction in this case eq = (cos(x) - 1)**(i + 1)*(cos(x) + 1)**i assert TR14(eq) in [(cos(x) - 1)*ans**i, eq] assert TR14((sin(x) - 1)*(sin(x) + 1)) == -cos(x)**2 p1 = (cos(x) + 1)*(cos(x) - 1) p2 = (cos(y) - 1)*2*(cos(y) + 1) p3 = (3*(cos(y) - 1))*(3*(cos(y) + 1)) assert TR14(p1*p2*p3*(x - 1)) == -18*((x - 1)*sin(x)**2*sin(y)**4) def test_TR15_16_17(): assert TR15(1 - 1/sin(x)**2) == -cot(x)**2 assert TR16(1 - 1/cos(x)**2) == -tan(x)**2 assert TR111(1 - 1/tan(x)**2) == 1 - cot(x)**2 def test_as_f_sign_1(): assert as_f_sign_1(x + 1) == (1, x, 1) assert as_f_sign_1(x - 1) == (1, x, -1) assert as_f_sign_1(-x + 1) == (-1, x, -1) assert as_f_sign_1(-x - 1) == (-1, x, 1) assert as_f_sign_1(2*x + 2) == (2, x, 1) assert as_f_sign_1(x*y - y) == (y, x, -1) assert as_f_sign_1(-x*y + y) == (-y, x, -1)
2ffc5319f0554abc2bdda3269f2cbbfcb19110c9e5f94417ec2bf273976d89f9
from sympy.core.function import (Subs, count_ops, diff, expand) from sympy.core.numbers import (E, I, Rational, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.hyperbolic import (cosh, coth, sinh, tanh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (cos, cot, sin, tan) from sympy.integrals.integrals import integrate from sympy.matrices.dense import Matrix from sympy.simplify.simplify import simplify from sympy.simplify.trigsimp import (exptrigsimp, trigsimp) from sympy.testing.pytest import XFAIL from sympy.abc import x, y def test_trigsimp1(): x, y = symbols('x,y') assert trigsimp(1 - sin(x)**2) == cos(x)**2 assert trigsimp(1 - cos(x)**2) == sin(x)**2 assert trigsimp(sin(x)**2 + cos(x)**2) == 1 assert trigsimp(1 + tan(x)**2) == 1/cos(x)**2 assert trigsimp(1/cos(x)**2 - 1) == tan(x)**2 assert trigsimp(1/cos(x)**2 - tan(x)**2) == 1 assert trigsimp(1 + cot(x)**2) == 1/sin(x)**2 assert trigsimp(1/sin(x)**2 - 1) == 1/tan(x)**2 assert trigsimp(1/sin(x)**2 - cot(x)**2) == 1 assert trigsimp(5*cos(x)**2 + 5*sin(x)**2) == 5 assert trigsimp(5*cos(x/2)**2 + 2*sin(x/2)**2) == 3*cos(x)/2 + Rational(7, 2) assert trigsimp(sin(x)/cos(x)) == tan(x) assert trigsimp(2*tan(x)*cos(x)) == 2*sin(x) assert trigsimp(cot(x)**3*sin(x)**3) == cos(x)**3 assert trigsimp(y*tan(x)**2/sin(x)**2) == y/cos(x)**2 assert trigsimp(cot(x)/cos(x)) == 1/sin(x) assert trigsimp(sin(x + y) + sin(x - y)) == 2*sin(x)*cos(y) assert trigsimp(sin(x + y) - sin(x - y)) == 2*sin(y)*cos(x) assert trigsimp(cos(x + y) + cos(x - y)) == 2*cos(x)*cos(y) assert trigsimp(cos(x + y) - cos(x - y)) == -2*sin(x)*sin(y) assert trigsimp(tan(x + y) - tan(x)/(1 - tan(x)*tan(y))) == \ sin(y)/(-sin(y)*tan(x) + cos(y)) # -tan(y)/(tan(x)*tan(y) - 1) assert trigsimp(sinh(x + y) + sinh(x - y)) == 2*sinh(x)*cosh(y) assert trigsimp(sinh(x + y) - sinh(x - y)) == 2*sinh(y)*cosh(x) assert trigsimp(cosh(x + y) + cosh(x - y)) == 2*cosh(x)*cosh(y) assert trigsimp(cosh(x + y) - cosh(x - y)) == 2*sinh(x)*sinh(y) assert trigsimp(tanh(x + y) - tanh(x)/(1 + tanh(x)*tanh(y))) == \ sinh(y)/(sinh(y)*tanh(x) + cosh(y)) assert trigsimp(cos(0.12345)**2 + sin(0.12345)**2) == 1 e = 2*sin(x)**2 + 2*cos(x)**2 assert trigsimp(log(e)) == log(2) def test_trigsimp1a(): assert trigsimp(sin(2)**2*cos(3)*exp(2)/cos(2)**2) == tan(2)**2*cos(3)*exp(2) assert trigsimp(tan(2)**2*cos(3)*exp(2)*cos(2)**2) == sin(2)**2*cos(3)*exp(2) assert trigsimp(cot(2)*cos(3)*exp(2)*sin(2)) == cos(3)*exp(2)*cos(2) assert trigsimp(tan(2)*cos(3)*exp(2)/sin(2)) == cos(3)*exp(2)/cos(2) assert trigsimp(cot(2)*cos(3)*exp(2)/cos(2)) == cos(3)*exp(2)/sin(2) assert trigsimp(cot(2)*cos(3)*exp(2)*tan(2)) == cos(3)*exp(2) assert trigsimp(sinh(2)*cos(3)*exp(2)/cosh(2)) == tanh(2)*cos(3)*exp(2) assert trigsimp(tanh(2)*cos(3)*exp(2)*cosh(2)) == sinh(2)*cos(3)*exp(2) assert trigsimp(coth(2)*cos(3)*exp(2)*sinh(2)) == cosh(2)*cos(3)*exp(2) assert trigsimp(tanh(2)*cos(3)*exp(2)/sinh(2)) == cos(3)*exp(2)/cosh(2) assert trigsimp(coth(2)*cos(3)*exp(2)/cosh(2)) == cos(3)*exp(2)/sinh(2) assert trigsimp(coth(2)*cos(3)*exp(2)*tanh(2)) == cos(3)*exp(2) def test_trigsimp2(): x, y = symbols('x,y') assert trigsimp(cos(x)**2*sin(y)**2 + cos(x)**2*cos(y)**2 + sin(x)**2, recursive=True) == 1 assert trigsimp(sin(x)**2*sin(y)**2 + sin(x)**2*cos(y)**2 + cos(x)**2, recursive=True) == 1 assert trigsimp( Subs(x, x, sin(y)**2 + cos(y)**2)) == Subs(x, x, 1) def test_issue_4373(): x = Symbol("x") assert abs(trigsimp(2.0*sin(x)**2 + 2.0*cos(x)**2) - 2.0) < 1e-10 def test_trigsimp3(): x, y = symbols('x,y') assert trigsimp(sin(x)/cos(x)) == tan(x) assert trigsimp(sin(x)**2/cos(x)**2) == tan(x)**2 assert trigsimp(sin(x)**3/cos(x)**3) == tan(x)**3 assert trigsimp(sin(x)**10/cos(x)**10) == tan(x)**10 assert trigsimp(cos(x)/sin(x)) == 1/tan(x) assert trigsimp(cos(x)**2/sin(x)**2) == 1/tan(x)**2 assert trigsimp(cos(x)**10/sin(x)**10) == 1/tan(x)**10 assert trigsimp(tan(x)) == trigsimp(sin(x)/cos(x)) def test_issue_4661(): a, x, y = symbols('a x y') eq = -4*sin(x)**4 + 4*cos(x)**4 - 8*cos(x)**2 assert trigsimp(eq) == -4 n = sin(x)**6 + 4*sin(x)**4*cos(x)**2 + 5*sin(x)**2*cos(x)**4 + 2*cos(x)**6 d = -sin(x)**2 - 2*cos(x)**2 assert simplify(n/d) == -1 assert trigsimp(-2*cos(x)**2 + cos(x)**4 - sin(x)**4) == -1 eq = (- sin(x)**3/4)*cos(x) + (cos(x)**3/4)*sin(x) - sin(2*x)*cos(2*x)/8 assert trigsimp(eq) == 0 def test_issue_4494(): a, b = symbols('a b') eq = sin(a)**2*sin(b)**2 + cos(a)**2*cos(b)**2*tan(a)**2 + cos(a)**2 assert trigsimp(eq) == 1 def test_issue_5948(): a, x, y = symbols('a x y') assert trigsimp(diff(integrate(cos(x)/sin(x)**7, x), x)) == \ cos(x)/sin(x)**7 def test_issue_4775(): a, x, y = symbols('a x y') assert trigsimp(sin(x)*cos(y)+cos(x)*sin(y)) == sin(x + y) assert trigsimp(sin(x)*cos(y)+cos(x)*sin(y)+3) == sin(x + y) + 3 def test_issue_4280(): a, x, y = symbols('a x y') assert trigsimp(cos(x)**2 + cos(y)**2*sin(x)**2 + sin(y)**2*sin(x)**2) == 1 assert trigsimp(a**2*sin(x)**2 + a**2*cos(y)**2*cos(x)**2 + a**2*cos(x)**2*sin(y)**2) == a**2 assert trigsimp(a**2*cos(y)**2*sin(x)**2 + a**2*sin(y)**2*sin(x)**2) == a**2*sin(x)**2 def test_issue_3210(): eqs = (sin(2)*cos(3) + sin(3)*cos(2), -sin(2)*sin(3) + cos(2)*cos(3), sin(2)*cos(3) - sin(3)*cos(2), sin(2)*sin(3) + cos(2)*cos(3), sin(2)*sin(3) + cos(2)*cos(3) + cos(2), sinh(2)*cosh(3) + sinh(3)*cosh(2), sinh(2)*sinh(3) + cosh(2)*cosh(3), ) assert [trigsimp(e) for e in eqs] == [ sin(5), cos(5), -sin(1), cos(1), cos(1) + cos(2), sinh(5), cosh(5), ] def test_trigsimp_issues(): a, x, y = symbols('a x y') # issue 4625 - factor_terms works, too assert trigsimp(sin(x)**3 + cos(x)**2*sin(x)) == sin(x) # issue 5948 assert trigsimp(diff(integrate(cos(x)/sin(x)**3, x), x)) == \ cos(x)/sin(x)**3 assert trigsimp(diff(integrate(sin(x)/cos(x)**3, x), x)) == \ sin(x)/cos(x)**3 # check integer exponents e = sin(x)**y/cos(x)**y assert trigsimp(e) == e assert trigsimp(e.subs(y, 2)) == tan(x)**2 assert trigsimp(e.subs(x, 1)) == tan(1)**y # check for multiple patterns assert (cos(x)**2/sin(x)**2*cos(y)**2/sin(y)**2).trigsimp() == \ 1/tan(x)**2/tan(y)**2 assert trigsimp(cos(x)/sin(x)*cos(x+y)/sin(x+y)) == \ 1/(tan(x)*tan(x + y)) eq = cos(2)*(cos(3) + 1)**2/(cos(3) - 1)**2 assert trigsimp(eq) == eq.factor() # factor makes denom (-1 + cos(3))**2 assert trigsimp(cos(2)*(cos(3) + 1)**2*(cos(3) - 1)**2) == \ cos(2)*sin(3)**4 # issue 6789; this generates an expression that formerly caused # trigsimp to hang assert cot(x).equals(tan(x)) is False # nan or the unchanged expression is ok, but not sin(1) z = cos(x)**2 + sin(x)**2 - 1 z1 = tan(x)**2 - 1/cot(x)**2 n = (1 + z1/z) assert trigsimp(sin(n)) != sin(1) eq = x*(n - 1) - x*n assert trigsimp(eq) is S.NaN assert trigsimp(eq, recursive=True) is S.NaN assert trigsimp(1).is_Integer assert trigsimp(-sin(x)**4 - 2*sin(x)**2*cos(x)**2 - cos(x)**4) == -1 def test_trigsimp_issue_2515(): x = Symbol('x') assert trigsimp(x*cos(x)*tan(x)) == x*sin(x) assert trigsimp(-sin(x) + cos(x)*tan(x)) == 0 def test_trigsimp_issue_3826(): assert trigsimp(tan(2*x).expand(trig=True)) == tan(2*x) def test_trigsimp_issue_4032(): n = Symbol('n', integer=True, positive=True) assert trigsimp(2**(n/2)*cos(pi*n/4)/2 + 2**(n - 1)/2) == \ 2**(n/2)*cos(pi*n/4)/2 + 2**n/4 def test_trigsimp_issue_7761(): assert trigsimp(cosh(pi/4)) == cosh(pi/4) def test_trigsimp_noncommutative(): x, y = symbols('x,y') A, B = symbols('A,B', commutative=False) assert trigsimp(A - A*sin(x)**2) == A*cos(x)**2 assert trigsimp(A - A*cos(x)**2) == A*sin(x)**2 assert trigsimp(A*sin(x)**2 + A*cos(x)**2) == A assert trigsimp(A + A*tan(x)**2) == A/cos(x)**2 assert trigsimp(A/cos(x)**2 - A) == A*tan(x)**2 assert trigsimp(A/cos(x)**2 - A*tan(x)**2) == A assert trigsimp(A + A*cot(x)**2) == A/sin(x)**2 assert trigsimp(A/sin(x)**2 - A) == A/tan(x)**2 assert trigsimp(A/sin(x)**2 - A*cot(x)**2) == A assert trigsimp(y*A*cos(x)**2 + y*A*sin(x)**2) == y*A assert trigsimp(A*sin(x)/cos(x)) == A*tan(x) assert trigsimp(A*tan(x)*cos(x)) == A*sin(x) assert trigsimp(A*cot(x)**3*sin(x)**3) == A*cos(x)**3 assert trigsimp(y*A*tan(x)**2/sin(x)**2) == y*A/cos(x)**2 assert trigsimp(A*cot(x)/cos(x)) == A/sin(x) assert trigsimp(A*sin(x + y) + A*sin(x - y)) == 2*A*sin(x)*cos(y) assert trigsimp(A*sin(x + y) - A*sin(x - y)) == 2*A*sin(y)*cos(x) assert trigsimp(A*cos(x + y) + A*cos(x - y)) == 2*A*cos(x)*cos(y) assert trigsimp(A*cos(x + y) - A*cos(x - y)) == -2*A*sin(x)*sin(y) assert trigsimp(A*sinh(x + y) + A*sinh(x - y)) == 2*A*sinh(x)*cosh(y) assert trigsimp(A*sinh(x + y) - A*sinh(x - y)) == 2*A*sinh(y)*cosh(x) assert trigsimp(A*cosh(x + y) + A*cosh(x - y)) == 2*A*cosh(x)*cosh(y) assert trigsimp(A*cosh(x + y) - A*cosh(x - y)) == 2*A*sinh(x)*sinh(y) assert trigsimp(A*cos(0.12345)**2 + A*sin(0.12345)**2) == 1.0*A def test_hyperbolic_simp(): x, y = symbols('x,y') assert trigsimp(sinh(x)**2 + 1) == cosh(x)**2 assert trigsimp(cosh(x)**2 - 1) == sinh(x)**2 assert trigsimp(cosh(x)**2 - sinh(x)**2) == 1 assert trigsimp(1 - tanh(x)**2) == 1/cosh(x)**2 assert trigsimp(1 - 1/cosh(x)**2) == tanh(x)**2 assert trigsimp(tanh(x)**2 + 1/cosh(x)**2) == 1 assert trigsimp(coth(x)**2 - 1) == 1/sinh(x)**2 assert trigsimp(1/sinh(x)**2 + 1) == 1/tanh(x)**2 assert trigsimp(coth(x)**2 - 1/sinh(x)**2) == 1 assert trigsimp(5*cosh(x)**2 - 5*sinh(x)**2) == 5 assert trigsimp(5*cosh(x/2)**2 - 2*sinh(x/2)**2) == 3*cosh(x)/2 + Rational(7, 2) assert trigsimp(sinh(x)/cosh(x)) == tanh(x) assert trigsimp(tanh(x)) == trigsimp(sinh(x)/cosh(x)) assert trigsimp(cosh(x)/sinh(x)) == 1/tanh(x) assert trigsimp(2*tanh(x)*cosh(x)) == 2*sinh(x) assert trigsimp(coth(x)**3*sinh(x)**3) == cosh(x)**3 assert trigsimp(y*tanh(x)**2/sinh(x)**2) == y/cosh(x)**2 assert trigsimp(coth(x)/cosh(x)) == 1/sinh(x) for a in (pi/6*I, pi/4*I, pi/3*I): assert trigsimp(sinh(a)*cosh(x) + cosh(a)*sinh(x)) == sinh(x + a) assert trigsimp(-sinh(a)*cosh(x) + cosh(a)*sinh(x)) == sinh(x - a) e = 2*cosh(x)**2 - 2*sinh(x)**2 assert trigsimp(log(e)) == log(2) # issue 19535: assert trigsimp(sqrt(cosh(x)**2 - 1)) == sqrt(sinh(x)**2) assert trigsimp(cosh(x)**2*cosh(y)**2 - cosh(x)**2*sinh(y)**2 - sinh(x)**2, recursive=True) == 1 assert trigsimp(sinh(x)**2*sinh(y)**2 - sinh(x)**2*cosh(y)**2 + cosh(x)**2, recursive=True) == 1 assert abs(trigsimp(2.0*cosh(x)**2 - 2.0*sinh(x)**2) - 2.0) < 1e-10 assert trigsimp(sinh(x)**2/cosh(x)**2) == tanh(x)**2 assert trigsimp(sinh(x)**3/cosh(x)**3) == tanh(x)**3 assert trigsimp(sinh(x)**10/cosh(x)**10) == tanh(x)**10 assert trigsimp(cosh(x)**3/sinh(x)**3) == 1/tanh(x)**3 assert trigsimp(cosh(x)/sinh(x)) == 1/tanh(x) assert trigsimp(cosh(x)**2/sinh(x)**2) == 1/tanh(x)**2 assert trigsimp(cosh(x)**10/sinh(x)**10) == 1/tanh(x)**10 assert trigsimp(x*cosh(x)*tanh(x)) == x*sinh(x) assert trigsimp(-sinh(x) + cosh(x)*tanh(x)) == 0 assert tan(x) != 1/cot(x) # cot doesn't auto-simplify assert trigsimp(tan(x) - 1/cot(x)) == 0 assert trigsimp(3*tanh(x)**7 - 2/coth(x)**7) == tanh(x)**7 def test_trigsimp_groebner(): from sympy.simplify.trigsimp import trigsimp_groebner c = cos(x) s = sin(x) ex = (4*s*c + 12*s + 5*c**3 + 21*c**2 + 23*c + 15)/( -s*c**2 + 2*s*c + 15*s + 7*c**3 + 31*c**2 + 37*c + 21) resnum = (5*s - 5*c + 1) resdenom = (8*s - 6*c) results = [resnum/resdenom, (-resnum)/(-resdenom)] assert trigsimp_groebner(ex) in results assert trigsimp_groebner(s/c, hints=[tan]) == tan(x) assert trigsimp_groebner(c*s) == c*s assert trigsimp((-s + 1)/c + c/(-s + 1), method='groebner') == 2/c assert trigsimp((-s + 1)/c + c/(-s + 1), method='groebner', polynomial=True) == 2/c # Test quick=False works assert trigsimp_groebner(ex, hints=[2]) in results assert trigsimp_groebner(ex, hints=[int(2)]) in results # test "I" assert trigsimp_groebner(sin(I*x)/cos(I*x), hints=[tanh]) == I*tanh(x) # test hyperbolic / sums assert trigsimp_groebner((tanh(x)+tanh(y))/(1+tanh(x)*tanh(y)), hints=[(tanh, x, y)]) == tanh(x + y) def test_issue_2827_trigsimp_methods(): measure1 = lambda expr: len(str(expr)) measure2 = lambda expr: -count_ops(expr) # Return the most complicated result expr = (x + 1)/(x + sin(x)**2 + cos(x)**2) ans = Matrix([1]) M = Matrix([expr]) assert trigsimp(M, method='fu', measure=measure1) == ans assert trigsimp(M, method='fu', measure=measure2) != ans # all methods should work with Basic expressions even if they # aren't Expr M = Matrix.eye(1) assert all(trigsimp(M, method=m) == M for m in 'fu matching groebner old'.split()) # watch for E in exptrigsimp, not only exp() eq = 1/sqrt(E) + E assert exptrigsimp(eq) == eq def test_issue_15129_trigsimp_methods(): t1 = Matrix([sin(Rational(1, 50)), cos(Rational(1, 50)), 0]) t2 = Matrix([sin(Rational(1, 25)), cos(Rational(1, 25)), 0]) t3 = Matrix([cos(Rational(1, 25)), sin(Rational(1, 25)), 0]) r1 = t1.dot(t2) r2 = t1.dot(t3) assert trigsimp(r1) == cos(Rational(1, 50)) assert trigsimp(r2) == sin(Rational(3, 50)) def test_exptrigsimp(): def valid(a, b): from sympy.core.random import verify_numerically as tn if not (tn(a, b) and a == b): return False return True assert exptrigsimp(exp(x) + exp(-x)) == 2*cosh(x) assert exptrigsimp(exp(x) - exp(-x)) == 2*sinh(x) assert exptrigsimp((2*exp(x)-2*exp(-x))/(exp(x)+exp(-x))) == 2*tanh(x) assert exptrigsimp((2*exp(2*x)-2)/(exp(2*x)+1)) == 2*tanh(x) e = [cos(x) + I*sin(x), cos(x) - I*sin(x), cosh(x) - sinh(x), cosh(x) + sinh(x)] ok = [exp(I*x), exp(-I*x), exp(-x), exp(x)] assert all(valid(i, j) for i, j in zip( [exptrigsimp(ei) for ei in e], ok)) ue = [cos(x) + sin(x), cos(x) - sin(x), cosh(x) + I*sinh(x), cosh(x) - I*sinh(x)] assert [exptrigsimp(ei) == ei for ei in ue] res = [] ok = [y*tanh(1), 1/(y*tanh(1)), I*y*tan(1), -I/(y*tan(1)), y*tanh(x), 1/(y*tanh(x)), I*y*tan(x), -I/(y*tan(x)), y*tanh(1 + I), 1/(y*tanh(1 + I))] for a in (1, I, x, I*x, 1 + I): w = exp(a) eq = y*(w - 1/w)/(w + 1/w) res.append(simplify(eq)) res.append(simplify(1/eq)) assert all(valid(i, j) for i, j in zip(res, ok)) for a in range(1, 3): w = exp(a) e = w + 1/w s = simplify(e) assert s == exptrigsimp(e) assert valid(s, 2*cosh(a)) e = w - 1/w s = simplify(e) assert s == exptrigsimp(e) assert valid(s, 2*sinh(a)) def test_exptrigsimp_noncommutative(): a,b = symbols('a b', commutative=False) x = Symbol('x', commutative=True) assert exp(a + x) == exptrigsimp(exp(a)*exp(x)) p = exp(a)*exp(b) - exp(b)*exp(a) assert p == exptrigsimp(p) != 0 def test_powsimp_on_numbers(): assert 2**(Rational(1, 3) - 2) == 2**Rational(1, 3)/4 @XFAIL def test_issue_6811_fail(): # from doc/src/modules/physics/mechanics/examples.rst, the current `eq` # at Line 576 (in different variables) was formerly the equivalent and # shorter expression given below...it would be nice to get the short one # back again xp, y, x, z = symbols('xp, y, x, z') eq = 4*(-19*sin(x)*y + 5*sin(3*x)*y + 15*cos(2*x)*z - 21*z)*xp/(9*cos(x) - 5*cos(3*x)) assert trigsimp(eq) == -2*(2*cos(x)*tan(x)*y + 3*z)*xp/cos(x) def test_Piecewise(): e1 = x*(x + y) - y*(x + y) e2 = sin(x)**2 + cos(x)**2 e3 = expand((x + y)*y/x) # s1 = simplify(e1) s2 = simplify(e2) # s3 = simplify(e3) # trigsimp tries not to touch non-trig containing args assert trigsimp(Piecewise((e1, e3 < e2), (e3, True))) == \ Piecewise((e1, e3 < s2), (e3, True)) def test_issue_21594(): assert simplify(exp(Rational(1,2)) + exp(Rational(-1,2))) == cosh(S.Half)*2 def test_trigsimp_old(): x, y = symbols('x,y') assert trigsimp(1 - sin(x)**2, old=True) == cos(x)**2 assert trigsimp(1 - cos(x)**2, old=True) == sin(x)**2 assert trigsimp(sin(x)**2 + cos(x)**2, old=True) == 1 assert trigsimp(1 + tan(x)**2, old=True) == 1/cos(x)**2 assert trigsimp(1/cos(x)**2 - 1, old=True) == tan(x)**2 assert trigsimp(1/cos(x)**2 - tan(x)**2, old=True) == 1 assert trigsimp(1 + cot(x)**2, old=True) == 1/sin(x)**2 assert trigsimp(1/sin(x)**2 - cot(x)**2, old=True) == 1 assert trigsimp(5*cos(x)**2 + 5*sin(x)**2, old=True) == 5 assert trigsimp(sin(x)/cos(x), old=True) == tan(x) assert trigsimp(2*tan(x)*cos(x), old=True) == 2*sin(x) assert trigsimp(cot(x)**3*sin(x)**3, old=True) == cos(x)**3 assert trigsimp(y*tan(x)**2/sin(x)**2, old=True) == y/cos(x)**2 assert trigsimp(cot(x)/cos(x), old=True) == 1/sin(x) assert trigsimp(sin(x + y) + sin(x - y), old=True) == 2*sin(x)*cos(y) assert trigsimp(sin(x + y) - sin(x - y), old=True) == 2*sin(y)*cos(x) assert trigsimp(cos(x + y) + cos(x - y), old=True) == 2*cos(x)*cos(y) assert trigsimp(cos(x + y) - cos(x - y), old=True) == -2*sin(x)*sin(y) assert trigsimp(sinh(x + y) + sinh(x - y), old=True) == 2*sinh(x)*cosh(y) assert trigsimp(sinh(x + y) - sinh(x - y), old=True) == 2*sinh(y)*cosh(x) assert trigsimp(cosh(x + y) + cosh(x - y), old=True) == 2*cosh(x)*cosh(y) assert trigsimp(cosh(x + y) - cosh(x - y), old=True) == 2*sinh(x)*sinh(y) assert trigsimp(cos(0.12345)**2 + sin(0.12345)**2, old=True) == 1 assert trigsimp(sin(x)/cos(x), old=True, method='combined') == tan(x) assert trigsimp(sin(x)/cos(x), old=True, method='groebner') == sin(x)/cos(x) assert trigsimp(sin(x)/cos(x), old=True, method='groebner', hints=[tan]) == tan(x) assert trigsimp(1-sin(sin(x)**2+cos(x)**2)**2, old=True, deep=True) == cos(1)**2
086e47ff149bb7065a9232f32fe10483e4fd8f618e5329425396202ec6c79b60
from sympy.core.function import Function from sympy.core.mul import Mul from sympy.core.numbers import (E, I, Rational, oo, pi) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, symbols) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import (root, sqrt) from sympy.functions.elementary.trigonometric import sin from sympy.functions.special.gamma_functions import gamma from sympy.functions.special.hyper import hyper from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.simplify.powsimp import (powdenest, powsimp) from sympy.simplify.simplify import (signsimp, simplify) from sympy.core.symbol import Str from sympy.abc import x, y, z, a, b def test_powsimp(): x, y, z, n = symbols('x,y,z,n') f = Function('f') assert powsimp( 4**x * 2**(-x) * 2**(-x) ) == 1 assert powsimp( (-4)**x * (-2)**(-x) * 2**(-x) ) == 1 assert powsimp( f(4**x * 2**(-x) * 2**(-x)) ) == f(4**x * 2**(-x) * 2**(-x)) assert powsimp( f(4**x * 2**(-x) * 2**(-x)), deep=True ) == f(1) assert exp(x)*exp(y) == exp(x)*exp(y) assert powsimp(exp(x)*exp(y)) == exp(x + y) assert powsimp(exp(x)*exp(y)*2**x*2**y) == (2*E)**(x + y) assert powsimp(exp(x)*exp(y)*2**x*2**y, combine='exp') == \ exp(x + y)*2**(x + y) assert powsimp(exp(x)*exp(y)*exp(2)*sin(x) + sin(y) + 2**x*2**y) == \ exp(2 + x + y)*sin(x) + sin(y) + 2**(x + y) assert powsimp(sin(exp(x)*exp(y))) == sin(exp(x)*exp(y)) assert powsimp(sin(exp(x)*exp(y)), deep=True) == sin(exp(x + y)) assert powsimp(x**2*x**y) == x**(2 + y) # This should remain factored, because 'exp' with deep=True is supposed # to act like old automatic exponent combining. assert powsimp((1 + E*exp(E))*exp(-E), combine='exp', deep=True) == \ (1 + exp(1 + E))*exp(-E) assert powsimp((1 + E*exp(E))*exp(-E), deep=True) == \ (1 + exp(1 + E))*exp(-E) assert powsimp((1 + E*exp(E))*exp(-E)) == (1 + exp(1 + E))*exp(-E) assert powsimp((1 + E*exp(E))*exp(-E), combine='exp') == \ (1 + exp(1 + E))*exp(-E) assert powsimp((1 + E*exp(E))*exp(-E), combine='base') == \ (1 + E*exp(E))*exp(-E) x, y = symbols('x,y', nonnegative=True) n = Symbol('n', real=True) assert powsimp(y**n * (y/x)**(-n)) == x**n assert powsimp(x**(x**(x*y)*y**(x*y))*y**(x**(x*y)*y**(x*y)), deep=True) \ == (x*y)**(x*y)**(x*y) assert powsimp(2**(2**(2*x)*x), deep=False) == 2**(2**(2*x)*x) assert powsimp(2**(2**(2*x)*x), deep=True) == 2**(x*4**x) assert powsimp( exp(-x + exp(-x)*exp(-x*log(x))), deep=False, combine='exp') == \ exp(-x + exp(-x)*exp(-x*log(x))) assert powsimp( exp(-x + exp(-x)*exp(-x*log(x))), deep=False, combine='exp') == \ exp(-x + exp(-x)*exp(-x*log(x))) assert powsimp((x + y)/(3*z), deep=False, combine='exp') == (x + y)/(3*z) assert powsimp((x/3 + y/3)/z, deep=True, combine='exp') == (x/3 + y/3)/z assert powsimp(exp(x)/(1 + exp(x)*exp(y)), deep=True) == \ exp(x)/(1 + exp(x + y)) assert powsimp(x*y**(z**x*z**y), deep=True) == x*y**(z**(x + y)) assert powsimp((z**x*z**y)**x, deep=True) == (z**(x + y))**x assert powsimp(x*(z**x*z**y)**x, deep=True) == x*(z**(x + y))**x p = symbols('p', positive=True) assert powsimp((1/x)**log(2)/x) == (1/x)**(1 + log(2)) assert powsimp((1/p)**log(2)/p) == p**(-1 - log(2)) # coefficient of exponent can only be simplified for positive bases assert powsimp(2**(2*x)) == 4**x assert powsimp((-1)**(2*x)) == (-1)**(2*x) i = symbols('i', integer=True) assert powsimp((-1)**(2*i)) == 1 assert powsimp((-1)**(-x)) != (-1)**x # could be 1/((-1)**x), but is not # force=True overrides assumptions assert powsimp((-1)**(2*x), force=True) == 1 # rational exponents allow combining of negative terms w, n, m = symbols('w n m', negative=True) e = i/a # not a rational exponent if `a` is unknown ex = w**e*n**e*m**e assert powsimp(ex) == m**(i/a)*n**(i/a)*w**(i/a) e = i/3 ex = w**e*n**e*m**e assert powsimp(ex) == (-1)**i*(-m*n*w)**(i/3) e = (3 + i)/i ex = w**e*n**e*m**e assert powsimp(ex) == (-1)**(3*e)*(-m*n*w)**e eq = x**(a*Rational(2, 3)) # eq != (x**a)**(2/3) (try x = -1 and a = 3 to see) assert powsimp(eq).exp == eq.exp == a*Rational(2, 3) # powdenest goes the other direction assert powsimp(2**(2*x)) == 4**x assert powsimp(exp(p/2)) == exp(p/2) # issue 6368 eq = Mul(*[sqrt(Dummy(imaginary=True)) for i in range(3)]) assert powsimp(eq) == eq and eq.is_Mul assert all(powsimp(e) == e for e in (sqrt(x**a), sqrt(x**2))) # issue 8836 assert str( powsimp(exp(I*pi/3)*root(-1,3)) ) == '(-1)**(2/3)' # issue 9183 assert powsimp(-0.1**x) == -0.1**x # issue 10095 assert powsimp((1/(2*E))**oo) == (exp(-1)/2)**oo # PR 13131 eq = sin(2*x)**2*sin(2.0*x)**2 assert powsimp(eq) == eq # issue 14615 assert powsimp(x**2*y**3*(x*y**2)**Rational(3, 2) ) == x*y*(x*y**2)**Rational(5, 2) def test_powsimp_negated_base(): assert powsimp((-x + y)/sqrt(x - y)) == -sqrt(x - y) assert powsimp((-x + y)*(-z + y)/sqrt(x - y)/sqrt(z - y)) == sqrt(x - y)*sqrt(z - y) p = symbols('p', positive=True) reps = {p: 2, a: S.Half} assert powsimp((-p)**a/p**a).subs(reps) == ((-1)**a).subs(reps) assert powsimp((-p)**a*p**a).subs(reps) == ((-p**2)**a).subs(reps) n = symbols('n', negative=True) reps = {p: -2, a: S.Half} assert powsimp((-n)**a/n**a).subs(reps) == (-1)**(-a).subs(a, S.Half) assert powsimp((-n)**a*n**a).subs(reps) == ((-n**2)**a).subs(reps) # if x is 0 then the lhs is 0**a*oo**a which is not (-1)**a eq = (-x)**a/x**a assert powsimp(eq) == eq def test_powsimp_nc(): x, y, z = symbols('x,y,z') A, B, C = symbols('A B C', commutative=False) assert powsimp(A**x*A**y, combine='all') == A**(x + y) assert powsimp(A**x*A**y, combine='base') == A**x*A**y assert powsimp(A**x*A**y, combine='exp') == A**(x + y) assert powsimp(A**x*B**x, combine='all') == A**x*B**x assert powsimp(A**x*B**x, combine='base') == A**x*B**x assert powsimp(A**x*B**x, combine='exp') == A**x*B**x assert powsimp(B**x*A**x, combine='all') == B**x*A**x assert powsimp(B**x*A**x, combine='base') == B**x*A**x assert powsimp(B**x*A**x, combine='exp') == B**x*A**x assert powsimp(A**x*A**y*A**z, combine='all') == A**(x + y + z) assert powsimp(A**x*A**y*A**z, combine='base') == A**x*A**y*A**z assert powsimp(A**x*A**y*A**z, combine='exp') == A**(x + y + z) assert powsimp(A**x*B**x*C**x, combine='all') == A**x*B**x*C**x assert powsimp(A**x*B**x*C**x, combine='base') == A**x*B**x*C**x assert powsimp(A**x*B**x*C**x, combine='exp') == A**x*B**x*C**x assert powsimp(B**x*A**x*C**x, combine='all') == B**x*A**x*C**x assert powsimp(B**x*A**x*C**x, combine='base') == B**x*A**x*C**x assert powsimp(B**x*A**x*C**x, combine='exp') == B**x*A**x*C**x def test_issue_6440(): assert powsimp(16*2**a*8**b) == 2**(a + 3*b + 4) def test_powdenest(): x, y = symbols('x,y') p, q = symbols('p q', positive=True) i, j = symbols('i,j', integer=True) assert powdenest(x) == x assert powdenest(x + 2*(x**(a*Rational(2, 3)))**(3*x)) == (x + 2*(x**(a*Rational(2, 3)))**(3*x)) assert powdenest((exp(a*Rational(2, 3)))**(3*x)) # -X-> (exp(a/3))**(6*x) assert powdenest((x**(a*Rational(2, 3)))**(3*x)) == ((x**(a*Rational(2, 3)))**(3*x)) assert powdenest(exp(3*x*log(2))) == 2**(3*x) assert powdenest(sqrt(p**2)) == p eq = p**(2*i)*q**(4*i) assert powdenest(eq) == (p*q**2)**(2*i) # -X-> (x**x)**i*(x**x)**j == x**(x*(i + j)) assert powdenest((x**x)**(i + j)) assert powdenest(exp(3*y*log(x))) == x**(3*y) assert powdenest(exp(y*(log(a) + log(b)))) == (a*b)**y assert powdenest(exp(3*(log(a) + log(b)))) == a**3*b**3 assert powdenest(((x**(2*i))**(3*y))**x) == ((x**(2*i))**(3*y))**x assert powdenest(((x**(2*i))**(3*y))**x, force=True) == x**(6*i*x*y) assert powdenest(((x**(a*Rational(2, 3)))**(3*y/i))**x) == \ (((x**(a*Rational(2, 3)))**(3*y/i))**x) assert powdenest((x**(2*i)*y**(4*i))**z, force=True) == (x*y**2)**(2*i*z) assert powdenest((p**(2*i)*q**(4*i))**j) == (p*q**2)**(2*i*j) e = ((p**(2*a))**(3*y))**x assert powdenest(e) == e e = ((x**2*y**4)**a)**(x*y) assert powdenest(e) == e e = (((x**2*y**4)**a)**(x*y))**3 assert powdenest(e) == ((x**2*y**4)**a)**(3*x*y) assert powdenest((((x**2*y**4)**a)**(x*y)), force=True) == \ (x*y**2)**(2*a*x*y) assert powdenest((((x**2*y**4)**a)**(x*y))**3, force=True) == \ (x*y**2)**(6*a*x*y) assert powdenest((x**2*y**6)**i) != (x*y**3)**(2*i) x, y = symbols('x,y', positive=True) assert powdenest((x**2*y**6)**i) == (x*y**3)**(2*i) assert powdenest((x**(i*Rational(2, 3))*y**(i/2))**(2*i)) == (x**Rational(4, 3)*y)**(i**2) assert powdenest(sqrt(x**(2*i)*y**(6*i))) == (x*y**3)**i assert powdenest(4**x) == 2**(2*x) assert powdenest((4**x)**y) == 2**(2*x*y) assert powdenest(4**x*y) == 2**(2*x)*y def test_powdenest_polar(): x, y, z = symbols('x y z', polar=True) a, b, c = symbols('a b c') assert powdenest((x*y*z)**a) == x**a*y**a*z**a assert powdenest((x**a*y**b)**c) == x**(a*c)*y**(b*c) assert powdenest(((x**a)**b*y**c)**c) == x**(a*b*c)*y**(c**2) def test_issue_5805(): arg = ((gamma(x)*hyper((), (), x))*pi)**2 assert powdenest(arg) == (pi*gamma(x)*hyper((), (), x))**2 assert arg.is_positive is None def test_issue_9324_powsimp_on_matrix_symbol(): M = MatrixSymbol('M', 10, 10) expr = powsimp(M, deep=True) assert expr == M assert expr.args[0] == Str('M') def test_issue_6367(): z = -5*sqrt(2)/(2*sqrt(2*sqrt(29) + 29)) + sqrt(-sqrt(29)/29 + S.Half) assert Mul(*[powsimp(a) for a in Mul.make_args(z.normal())]) == 0 assert powsimp(z.normal()) == 0 assert simplify(z) == 0 assert powsimp(sqrt(2 + sqrt(3))*sqrt(2 - sqrt(3)) + 1) == 2 assert powsimp(z) != 0 def test_powsimp_polar(): from sympy.functions.elementary.complexes import polar_lift from sympy.functions.elementary.exponential import exp_polar x, y, z = symbols('x y z') p, q, r = symbols('p q r', polar=True) assert (polar_lift(-1))**(2*x) == exp_polar(2*pi*I*x) assert powsimp(p**x * q**x) == (p*q)**x assert p**x * (1/p)**x == 1 assert (1/p)**x == p**(-x) assert exp_polar(x)*exp_polar(y) == exp_polar(x)*exp_polar(y) assert powsimp(exp_polar(x)*exp_polar(y)) == exp_polar(x + y) assert powsimp(exp_polar(x)*exp_polar(y)*p**x*p**y) == \ (p*exp_polar(1))**(x + y) assert powsimp(exp_polar(x)*exp_polar(y)*p**x*p**y, combine='exp') == \ exp_polar(x + y)*p**(x + y) assert powsimp( exp_polar(x)*exp_polar(y)*exp_polar(2)*sin(x) + sin(y) + p**x*p**y) \ == p**(x + y) + sin(x)*exp_polar(2 + x + y) + sin(y) assert powsimp(sin(exp_polar(x)*exp_polar(y))) == \ sin(exp_polar(x)*exp_polar(y)) assert powsimp(sin(exp_polar(x)*exp_polar(y)), deep=True) == \ sin(exp_polar(x + y)) def test_issue_5728(): b = x*sqrt(y) a = sqrt(b) c = sqrt(sqrt(x)*y) assert powsimp(a*b) == sqrt(b)**3 assert powsimp(a*b**2*sqrt(y)) == sqrt(y)*a**5 assert powsimp(a*x**2*c**3*y) == c**3*a**5 assert powsimp(a*x*c**3*y**2) == c**7*a assert powsimp(x*c**3*y**2) == c**7 assert powsimp(x*c**3*y) == x*y*c**3 assert powsimp(sqrt(x)*c**3*y) == c**5 assert powsimp(sqrt(x)*a**3*sqrt(y)) == sqrt(x)*sqrt(y)*a**3 assert powsimp(Mul(sqrt(x)*c**3*sqrt(y), y, evaluate=False)) == \ sqrt(x)*sqrt(y)**3*c**3 assert powsimp(a**2*a*x**2*y) == a**7 # symbolic powers work, too b = x**y*y a = b*sqrt(b) assert a.is_Mul is True assert powsimp(a) == sqrt(b)**3 # as does exp a = x*exp(y*Rational(2, 3)) assert powsimp(a*sqrt(a)) == sqrt(a)**3 assert powsimp(a**2*sqrt(a)) == sqrt(a)**5 assert powsimp(a**2*sqrt(sqrt(a))) == sqrt(sqrt(a))**9 def test_issue_from_PR1599(): n1, n2, n3, n4 = symbols('n1 n2 n3 n4', negative=True) assert (powsimp(sqrt(n1)*sqrt(n2)*sqrt(n3)) == -I*sqrt(-n1)*sqrt(-n2)*sqrt(-n3)) assert (powsimp(root(n1, 3)*root(n2, 3)*root(n3, 3)*root(n4, 3)) == -(-1)**Rational(1, 3)* (-n1)**Rational(1, 3)*(-n2)**Rational(1, 3)*(-n3)**Rational(1, 3)*(-n4)**Rational(1, 3)) def test_issue_10195(): a = Symbol('a', integer=True) l = Symbol('l', even=True, nonzero=True) n = Symbol('n', odd=True) e_x = (-1)**(n/2 - S.Half) - (-1)**(n*Rational(3, 2) - S.Half) assert powsimp((-1)**(l/2)) == I**l assert powsimp((-1)**(n/2)) == I**n assert powsimp((-1)**(n*Rational(3, 2))) == -I**n assert powsimp(e_x) == (-1)**(n/2 - S.Half) + (-1)**(n*Rational(3, 2) + S.Half) assert powsimp((-1)**(a*Rational(3, 2))) == (-I)**a def test_issue_15709(): assert powsimp(3**x*Rational(2, 3)) == 2*3**(x-1) assert powsimp(2*3**x/3) == 2*3**(x-1) def test_issue_11981(): x, y = symbols('x y', commutative=False) assert powsimp((x*y)**2 * (y*x)**2) == (x*y)**2 * (y*x)**2 def test_issue_17524(): a = symbols("a", real=True) e = (-1 - a**2)*sqrt(1 + a**2) assert signsimp(powsimp(e)) == signsimp(e) == -(a**2 + 1)**(S(3)/2) def test_issue_19627(): # if you use force the user must verify assert powdenest(sqrt(sin(x)**2), force=True) == sin(x) assert powdenest((x**(S.Half/y))**(2*y), force=True) == x from sympy.core.function import expand_power_base e = 1 - a expr = (exp(z/e)*x**(b/e)*y**((1 - b)/e))**e assert powdenest(expand_power_base(expr, force=True), force=True ) == x**b*y**(1 - b)*exp(z) def test_issue_22546(): p1, p2 = symbols('p1, p2', positive=True) ref = powsimp(p1**z/p2**z) e = z + 1 ans = ref.subs(z, e) assert ans.is_Pow assert powsimp(p1**e/p2**e) == ans i = symbols('i', integer=True) ref = powsimp(x**i/y**i) e = i + 1 ans = ref.subs(i, e) assert ans.is_Pow assert powsimp(x**e/y**e) == ans
3f5392ea77c659a83d09cce0396cf573d72ee6753052ec851aaa7fa1c9311c41
from sympy.core.random import randrange from sympy.simplify.hyperexpand import (ShiftA, ShiftB, UnShiftA, UnShiftB, MeijerShiftA, MeijerShiftB, MeijerShiftC, MeijerShiftD, MeijerUnShiftA, MeijerUnShiftB, MeijerUnShiftC, MeijerUnShiftD, ReduceOrder, reduce_order, apply_operators, devise_plan, make_derivative_operator, Formula, hyperexpand, Hyper_Function, G_Function, reduce_order_meijer, build_hypergeometric_formula) from sympy.concrete.summations import Sum from sympy.core.containers import Tuple from sympy.core.expr import Expr from sympy.core.numbers import I from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.functions.combinatorial.factorials import binomial from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.special.hyper import (hyper, meijerg) from sympy.abc import z, a, b, c from sympy.testing.pytest import XFAIL, raises, slow, ON_TRAVIS, skip from sympy.core.random import verify_numerically as tn from sympy.core.numbers import (Rational, pi) from sympy.functions.elementary.exponential import (exp, exp_polar, log) from sympy.functions.elementary.hyperbolic import atanh from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (asin, cos, sin) from sympy.functions.special.bessel import besseli from sympy.functions.special.error_functions import erf from sympy.functions.special.gamma_functions import (gamma, lowergamma) def test_branch_bug(): assert hyperexpand(hyper((Rational(-1, 3), S.Half), (Rational(2, 3), Rational(3, 2)), -z)) == \ -z**S('1/3')*lowergamma(exp_polar(I*pi)/3, z)/5 \ + sqrt(pi)*erf(sqrt(z))/(5*sqrt(z)) assert hyperexpand(meijerg([Rational(7, 6), 1], [], [Rational(2, 3)], [Rational(1, 6), 0], z)) == \ 2*z**S('2/3')*(2*sqrt(pi)*erf(sqrt(z))/sqrt(z) - 2*lowergamma( Rational(2, 3), z)/z**S('2/3'))*gamma(Rational(2, 3))/gamma(Rational(5, 3)) def test_hyperexpand(): # Luke, Y. L. (1969), The Special Functions and Their Approximations, # Volume 1, section 6.2 assert hyperexpand(hyper([], [], z)) == exp(z) assert hyperexpand(hyper([1, 1], [2], -z)*z) == log(1 + z) assert hyperexpand(hyper([], [S.Half], -z**2/4)) == cos(z) assert hyperexpand(z*hyper([], [S('3/2')], -z**2/4)) == sin(z) assert hyperexpand(hyper([S('1/2'), S('1/2')], [S('3/2')], z**2)*z) \ == asin(z) assert isinstance(Sum(binomial(2, z)*z**2, (z, 0, a)).doit(), Expr) def can_do(ap, bq, numerical=True, div=1, lowerplane=False): r = hyperexpand(hyper(ap, bq, z)) if r.has(hyper): return False if not numerical: return True repl = {} randsyms = r.free_symbols - {z} while randsyms: # Only randomly generated parameters are checked. for n, ai in enumerate(randsyms): repl[ai] = randcplx(n)/div if not any(b.is_Integer and b <= 0 for b in Tuple(*bq).subs(repl)): break [a, b, c, d] = [2, -1, 3, 1] if lowerplane: [a, b, c, d] = [2, -2, 3, -1] return tn( hyper(ap, bq, z).subs(repl), r.replace(exp_polar, exp).subs(repl), z, a=a, b=b, c=c, d=d) def test_roach(): # Kelly B. Roach. Meijer G Function Representations. # Section "Gallery" assert can_do([S.Half], [Rational(9, 2)]) assert can_do([], [1, Rational(5, 2), 4]) assert can_do([Rational(-1, 2), 1, 2], [3, 4]) assert can_do([Rational(1, 3)], [Rational(-2, 3), Rational(-1, 2), S.Half, 1]) assert can_do([Rational(-3, 2), Rational(-1, 2)], [Rational(-5, 2), 1]) assert can_do([Rational(-3, 2), ], [Rational(-1, 2), S.Half]) # shine-integral assert can_do([Rational(-3, 2), Rational(-1, 2)], [2]) # elliptic integrals @XFAIL def test_roach_fail(): assert can_do([Rational(-1, 2), 1], [Rational(1, 4), S.Half, Rational(3, 4)]) # PFDD assert can_do([Rational(3, 2)], [Rational(5, 2), 5]) # struve function assert can_do([Rational(-1, 2), S.Half, 1], [Rational(3, 2), Rational(5, 2)]) # polylog, pfdd assert can_do([1, 2, 3], [S.Half, 4]) # XXX ? assert can_do([S.Half], [Rational(-1, 3), Rational(-1, 2), Rational(-2, 3)]) # PFDD ? # For the long table tests, see end of file def test_polynomial(): from sympy.core.numbers import oo assert hyperexpand(hyper([], [-1], z)) is oo assert hyperexpand(hyper([-2], [-1], z)) is oo assert hyperexpand(hyper([0, 0], [-1], z)) == 1 assert can_do([-5, -2, randcplx(), randcplx()], [-10, randcplx()]) assert hyperexpand(hyper((-1, 1), (-2,), z)) == 1 + z/2 def test_hyperexpand_bases(): assert hyperexpand(hyper([2], [a], z)) == \ a + z**(-a + 1)*(-a**2 + 3*a + z*(a - 1) - 2)*exp(z)* \ lowergamma(a - 1, z) - 1 # TODO [a+1, aRational(-1, 2)], [2*a] assert hyperexpand(hyper([1, 2], [3], z)) == -2/z - 2*log(-z + 1)/z**2 assert hyperexpand(hyper([S.Half, 2], [Rational(3, 2)], z)) == \ -1/(2*z - 2) + atanh(sqrt(z))/sqrt(z)/2 assert hyperexpand(hyper([S.Half, S.Half], [Rational(5, 2)], z)) == \ (-3*z + 3)/4/(z*sqrt(-z + 1)) \ + (6*z - 3)*asin(sqrt(z))/(4*z**Rational(3, 2)) assert hyperexpand(hyper([1, 2], [Rational(3, 2)], z)) == -1/(2*z - 2) \ - asin(sqrt(z))/(sqrt(z)*(2*z - 2)*sqrt(-z + 1)) assert hyperexpand(hyper([Rational(-1, 2) - 1, 1, 2], [S.Half, 3], z)) == \ sqrt(z)*(z*Rational(6, 7) - Rational(6, 5))*atanh(sqrt(z)) \ + (-30*z**2 + 32*z - 6)/35/z - 6*log(-z + 1)/(35*z**2) assert hyperexpand(hyper([1 + S.Half, 1, 1], [2, 2], z)) == \ -4*log(sqrt(-z + 1)/2 + S.Half)/z # TODO hyperexpand(hyper([a], [2*a + 1], z)) # TODO [S.Half, a], [Rational(3, 2), a+1] assert hyperexpand(hyper([2], [b, 1], z)) == \ z**(-b/2 + S.Half)*besseli(b - 1, 2*sqrt(z))*gamma(b) \ + z**(-b/2 + 1)*besseli(b, 2*sqrt(z))*gamma(b) # TODO [a], [a - S.Half, 2*a] def test_hyperexpand_parametric(): assert hyperexpand(hyper([a, S.Half + a], [S.Half], z)) \ == (1 + sqrt(z))**(-2*a)/2 + (1 - sqrt(z))**(-2*a)/2 assert hyperexpand(hyper([a, Rational(-1, 2) + a], [2*a], z)) \ == 2**(2*a - 1)*((-z + 1)**S.Half + 1)**(-2*a + 1) def test_shifted_sum(): from sympy.simplify.simplify import simplify assert simplify(hyperexpand(z**4*hyper([2], [3, S('3/2')], -z**2))) \ == z*sin(2*z) + (-z**2 + S.Half)*cos(2*z) - S.Half def _randrat(): """ Steer clear of integers. """ return S(randrange(25) + 10)/50 def randcplx(offset=-1): """ Polys is not good with real coefficients. """ return _randrat() + I*_randrat() + I*(1 + offset) @slow def test_formulae(): from sympy.simplify.hyperexpand import FormulaCollection formulae = FormulaCollection().formulae for formula in formulae: h = formula.func(formula.z) rep = {} for n, sym in enumerate(formula.symbols): rep[sym] = randcplx(n) # NOTE hyperexpand returns truly branched functions. We know we are # on the main sheet, but numerical evaluation can still go wrong # (e.g. if exp_polar cannot be evalf'd). # Just replace all exp_polar by exp, this usually works. # first test if the closed-form is actually correct h = h.subs(rep) closed_form = formula.closed_form.subs(rep).rewrite('nonrepsmall') z = formula.z assert tn(h, closed_form.replace(exp_polar, exp), z) # now test the computed matrix cl = (formula.C * formula.B)[0].subs(rep).rewrite('nonrepsmall') assert tn(closed_form.replace( exp_polar, exp), cl.replace(exp_polar, exp), z) deriv1 = z*formula.B.applyfunc(lambda t: t.rewrite( 'nonrepsmall')).diff(z) deriv2 = formula.M * formula.B for d1, d2 in zip(deriv1, deriv2): assert tn(d1.subs(rep).replace(exp_polar, exp), d2.subs(rep).rewrite('nonrepsmall').replace(exp_polar, exp), z) def test_meijerg_formulae(): from sympy.simplify.hyperexpand import MeijerFormulaCollection formulae = MeijerFormulaCollection().formulae for sig in formulae: for formula in formulae[sig]: g = meijerg(formula.func.an, formula.func.ap, formula.func.bm, formula.func.bq, formula.z) rep = {} for sym in formula.symbols: rep[sym] = randcplx() # first test if the closed-form is actually correct g = g.subs(rep) closed_form = formula.closed_form.subs(rep) z = formula.z assert tn(g, closed_form, z) # now test the computed matrix cl = (formula.C * formula.B)[0].subs(rep) assert tn(closed_form, cl, z) deriv1 = z*formula.B.diff(z) deriv2 = formula.M * formula.B for d1, d2 in zip(deriv1, deriv2): assert tn(d1.subs(rep), d2.subs(rep), z) def op(f): return z*f.diff(z) def test_plan(): assert devise_plan(Hyper_Function([0], ()), Hyper_Function([0], ()), z) == [] with raises(ValueError): devise_plan(Hyper_Function([1], ()), Hyper_Function((), ()), z) with raises(ValueError): devise_plan(Hyper_Function([2], [1]), Hyper_Function([2], [2]), z) with raises(ValueError): devise_plan(Hyper_Function([2], []), Hyper_Function([S("1/2")], []), z) # We cannot use pi/(10000 + n) because polys is insanely slow. a1, a2, b1 = (randcplx(n) for n in range(3)) b1 += 2*I h = hyper([a1, a2], [b1], z) h2 = hyper((a1 + 1, a2), [b1], z) assert tn(apply_operators(h, devise_plan(Hyper_Function((a1 + 1, a2), [b1]), Hyper_Function((a1, a2), [b1]), z), op), h2, z) h2 = hyper((a1 + 1, a2 - 1), [b1], z) assert tn(apply_operators(h, devise_plan(Hyper_Function((a1 + 1, a2 - 1), [b1]), Hyper_Function((a1, a2), [b1]), z), op), h2, z) def test_plan_derivatives(): a1, a2, a3 = 1, 2, S('1/2') b1, b2 = 3, S('5/2') h = Hyper_Function((a1, a2, a3), (b1, b2)) h2 = Hyper_Function((a1 + 1, a2 + 1, a3 + 2), (b1 + 1, b2 + 1)) ops = devise_plan(h2, h, z) f = Formula(h, z, h(z), []) deriv = make_derivative_operator(f.M, z) assert tn((apply_operators(f.C, ops, deriv)*f.B)[0], h2(z), z) h2 = Hyper_Function((a1, a2 - 1, a3 - 2), (b1 - 1, b2 - 1)) ops = devise_plan(h2, h, z) assert tn((apply_operators(f.C, ops, deriv)*f.B)[0], h2(z), z) def test_reduction_operators(): a1, a2, b1 = (randcplx(n) for n in range(3)) h = hyper([a1], [b1], z) assert ReduceOrder(2, 0) is None assert ReduceOrder(2, -1) is None assert ReduceOrder(1, S('1/2')) is None h2 = hyper((a1, a2), (b1, a2), z) assert tn(ReduceOrder(a2, a2).apply(h, op), h2, z) h2 = hyper((a1, a2 + 1), (b1, a2), z) assert tn(ReduceOrder(a2 + 1, a2).apply(h, op), h2, z) h2 = hyper((a2 + 4, a1), (b1, a2), z) assert tn(ReduceOrder(a2 + 4, a2).apply(h, op), h2, z) # test several step order reduction ap = (a2 + 4, a1, b1 + 1) bq = (a2, b1, b1) func, ops = reduce_order(Hyper_Function(ap, bq)) assert func.ap == (a1,) assert func.bq == (b1,) assert tn(apply_operators(h, ops, op), hyper(ap, bq, z), z) def test_shift_operators(): a1, a2, b1, b2, b3 = (randcplx(n) for n in range(5)) h = hyper((a1, a2), (b1, b2, b3), z) raises(ValueError, lambda: ShiftA(0)) raises(ValueError, lambda: ShiftB(1)) assert tn(ShiftA(a1).apply(h, op), hyper((a1 + 1, a2), (b1, b2, b3), z), z) assert tn(ShiftA(a2).apply(h, op), hyper((a1, a2 + 1), (b1, b2, b3), z), z) assert tn(ShiftB(b1).apply(h, op), hyper((a1, a2), (b1 - 1, b2, b3), z), z) assert tn(ShiftB(b2).apply(h, op), hyper((a1, a2), (b1, b2 - 1, b3), z), z) assert tn(ShiftB(b3).apply(h, op), hyper((a1, a2), (b1, b2, b3 - 1), z), z) def test_ushift_operators(): a1, a2, b1, b2, b3 = (randcplx(n) for n in range(5)) h = hyper((a1, a2), (b1, b2, b3), z) raises(ValueError, lambda: UnShiftA((1,), (), 0, z)) raises(ValueError, lambda: UnShiftB((), (-1,), 0, z)) raises(ValueError, lambda: UnShiftA((1,), (0, -1, 1), 0, z)) raises(ValueError, lambda: UnShiftB((0, 1), (1,), 0, z)) s = UnShiftA((a1, a2), (b1, b2, b3), 0, z) assert tn(s.apply(h, op), hyper((a1 - 1, a2), (b1, b2, b3), z), z) s = UnShiftA((a1, a2), (b1, b2, b3), 1, z) assert tn(s.apply(h, op), hyper((a1, a2 - 1), (b1, b2, b3), z), z) s = UnShiftB((a1, a2), (b1, b2, b3), 0, z) assert tn(s.apply(h, op), hyper((a1, a2), (b1 + 1, b2, b3), z), z) s = UnShiftB((a1, a2), (b1, b2, b3), 1, z) assert tn(s.apply(h, op), hyper((a1, a2), (b1, b2 + 1, b3), z), z) s = UnShiftB((a1, a2), (b1, b2, b3), 2, z) assert tn(s.apply(h, op), hyper((a1, a2), (b1, b2, b3 + 1), z), z) def can_do_meijer(a1, a2, b1, b2, numeric=True): """ This helper function tries to hyperexpand() the meijer g-function corresponding to the parameters a1, a2, b1, b2. It returns False if this expansion still contains g-functions. If numeric is True, it also tests the so-obtained formula numerically (at random values) and returns False if the test fails. Else it returns True. """ from sympy.core.function import expand from sympy.functions.elementary.complexes import unpolarify r = hyperexpand(meijerg(a1, a2, b1, b2, z)) if r.has(meijerg): return False # NOTE hyperexpand() returns a truly branched function, whereas numerical # evaluation only works on the main branch. Since we are evaluating on # the main branch, this should not be a problem, but expressions like # exp_polar(I*pi/2*x)**a are evaluated incorrectly. We thus have to get # rid of them. The expand heuristically does this... r = unpolarify(expand(r, force=True, power_base=True, power_exp=False, mul=False, log=False, multinomial=False, basic=False)) if not numeric: return True repl = {} for n, ai in enumerate(meijerg(a1, a2, b1, b2, z).free_symbols - {z}): repl[ai] = randcplx(n) return tn(meijerg(a1, a2, b1, b2, z).subs(repl), r.subs(repl), z) @slow def test_meijerg_expand(): from sympy.simplify.gammasimp import gammasimp from sympy.simplify.simplify import simplify # from mpmath docs assert hyperexpand(meijerg([[], []], [[0], []], -z)) == exp(z) assert hyperexpand(meijerg([[1, 1], []], [[1], [0]], z)) == \ log(z + 1) assert hyperexpand(meijerg([[1, 1], []], [[1], [1]], z)) == \ z/(z + 1) assert hyperexpand(meijerg([[], []], [[S.Half], [0]], (z/2)**2)) \ == sin(z)/sqrt(pi) assert hyperexpand(meijerg([[], []], [[0], [S.Half]], (z/2)**2)) \ == cos(z)/sqrt(pi) assert can_do_meijer([], [a], [a - 1, a - S.Half], []) assert can_do_meijer([], [], [a/2], [-a/2], False) # branches... assert can_do_meijer([a], [b], [a], [b, a - 1]) # wikipedia assert hyperexpand(meijerg([1], [], [], [0], z)) == \ Piecewise((0, abs(z) < 1), (1, abs(1/z) < 1), (meijerg([1], [], [], [0], z), True)) assert hyperexpand(meijerg([], [1], [0], [], z)) == \ Piecewise((1, abs(z) < 1), (0, abs(1/z) < 1), (meijerg([], [1], [0], [], z), True)) # The Special Functions and their Approximations assert can_do_meijer([], [], [a + b/2], [a, a - b/2, a + S.Half]) assert can_do_meijer( [], [], [a], [b], False) # branches only agree for small z assert can_do_meijer([], [S.Half], [a], [-a]) assert can_do_meijer([], [], [a, b], []) assert can_do_meijer([], [], [a, b], []) assert can_do_meijer([], [], [a, a + S.Half], [b, b + S.Half]) assert can_do_meijer([], [], [a, -a], [0, S.Half], False) # dito assert can_do_meijer([], [], [a, a + S.Half, b, b + S.Half], []) assert can_do_meijer([S.Half], [], [0], [a, -a]) assert can_do_meijer([S.Half], [], [a], [0, -a], False) # dito assert can_do_meijer([], [a - S.Half], [a, b], [a - S.Half], False) assert can_do_meijer([], [a + S.Half], [a + b, a - b, a], [], False) assert can_do_meijer([a + S.Half], [], [b, 2*a - b, a], [], False) # This for example is actually zero. assert can_do_meijer([], [], [], [a, b]) # Testing a bug: assert hyperexpand(meijerg([0, 2], [], [], [-1, 1], z)) == \ Piecewise((0, abs(z) < 1), (z*(1 - 1/z**2)/2, abs(1/z) < 1), (meijerg([0, 2], [], [], [-1, 1], z), True)) # Test that the simplest possible answer is returned: assert gammasimp(simplify(hyperexpand( meijerg([1], [1 - a], [-a/2, -a/2 + S.Half], [], 1/z)))) == \ -2*sqrt(pi)*(sqrt(z + 1) + 1)**a/a # Test that hyper is returned assert hyperexpand(meijerg([1], [], [a], [0, 0], z)) == hyper( (a,), (a + 1, a + 1), z*exp_polar(I*pi))*z**a*gamma(a)/gamma(a + 1)**2 # Test place option f = meijerg(((0, 1), ()), ((S.Half,), (0,)), z**2) assert hyperexpand(f) == sqrt(pi)/sqrt(1 + z**(-2)) assert hyperexpand(f, place=0) == sqrt(pi)*z/sqrt(z**2 + 1) def test_meijerg_lookup(): from sympy.functions.special.error_functions import (Ci, Si) from sympy.functions.special.gamma_functions import uppergamma assert hyperexpand(meijerg([a], [], [b, a], [], z)) == \ z**b*exp(z)*gamma(-a + b + 1)*uppergamma(a - b, z) assert hyperexpand(meijerg([0], [], [0, 0], [], z)) == \ exp(z)*uppergamma(0, z) assert can_do_meijer([a], [], [b, a + 1], []) assert can_do_meijer([a], [], [b + 2, a], []) assert can_do_meijer([a], [], [b - 2, a], []) assert hyperexpand(meijerg([a], [], [a, a, a - S.Half], [], z)) == \ -sqrt(pi)*z**(a - S.Half)*(2*cos(2*sqrt(z))*(Si(2*sqrt(z)) - pi/2) - 2*sin(2*sqrt(z))*Ci(2*sqrt(z))) == \ hyperexpand(meijerg([a], [], [a, a - S.Half, a], [], z)) == \ hyperexpand(meijerg([a], [], [a - S.Half, a, a], [], z)) assert can_do_meijer([a - 1], [], [a + 2, a - Rational(3, 2), a + 1], []) @XFAIL def test_meijerg_expand_fail(): # These basically test hyper([], [1/2 - a, 1/2 + 1, 1/2], z), # which is *very* messy. But since the meijer g actually yields a # sum of bessel functions, things can sometimes be simplified a lot and # are then put into tables... assert can_do_meijer([], [], [a + S.Half], [a, a - b/2, a + b/2]) assert can_do_meijer([], [], [0, S.Half], [a, -a]) assert can_do_meijer([], [], [3*a - S.Half, a, -a - S.Half], [a - S.Half]) assert can_do_meijer([], [], [0, a - S.Half, -a - S.Half], [S.Half]) assert can_do_meijer([], [], [a, b + S.Half, b], [2*b - a]) assert can_do_meijer([], [], [a, b + S.Half, b, 2*b - a]) assert can_do_meijer([S.Half], [], [-a, a], [0]) @slow def test_meijerg(): # carefully set up the parameters. # NOTE: this used to fail sometimes. I believe it is fixed, but if you # hit an inexplicable test failure here, please let me know the seed. a1, a2 = (randcplx(n) - 5*I - n*I for n in range(2)) b1, b2 = (randcplx(n) + 5*I + n*I for n in range(2)) b3, b4, b5, a3, a4, a5 = (randcplx() for n in range(6)) g = meijerg([a1], [a3, a4], [b1], [b3, b4], z) assert ReduceOrder.meijer_minus(3, 4) is None assert ReduceOrder.meijer_plus(4, 3) is None g2 = meijerg([a1, a2], [a3, a4], [b1], [b3, b4, a2], z) assert tn(ReduceOrder.meijer_plus(a2, a2).apply(g, op), g2, z) g2 = meijerg([a1, a2], [a3, a4], [b1], [b3, b4, a2 + 1], z) assert tn(ReduceOrder.meijer_plus(a2, a2 + 1).apply(g, op), g2, z) g2 = meijerg([a1, a2 - 1], [a3, a4], [b1], [b3, b4, a2 + 2], z) assert tn(ReduceOrder.meijer_plus(a2 - 1, a2 + 2).apply(g, op), g2, z) g2 = meijerg([a1], [a3, a4, b2 - 1], [b1, b2 + 2], [b3, b4], z) assert tn(ReduceOrder.meijer_minus( b2 + 2, b2 - 1).apply(g, op), g2, z, tol=1e-6) # test several-step reduction an = [a1, a2] bq = [b3, b4, a2 + 1] ap = [a3, a4, b2 - 1] bm = [b1, b2 + 1] niq, ops = reduce_order_meijer(G_Function(an, ap, bm, bq)) assert niq.an == (a1,) assert set(niq.ap) == {a3, a4} assert niq.bm == (b1,) assert set(niq.bq) == {b3, b4} assert tn(apply_operators(g, ops, op), meijerg(an, ap, bm, bq, z), z) def test_meijerg_shift_operators(): # carefully set up the parameters. XXX this still fails sometimes a1, a2, a3, a4, a5, b1, b2, b3, b4, b5 = (randcplx(n) for n in range(10)) g = meijerg([a1], [a3, a4], [b1], [b3, b4], z) assert tn(MeijerShiftA(b1).apply(g, op), meijerg([a1], [a3, a4], [b1 + 1], [b3, b4], z), z) assert tn(MeijerShiftB(a1).apply(g, op), meijerg([a1 - 1], [a3, a4], [b1], [b3, b4], z), z) assert tn(MeijerShiftC(b3).apply(g, op), meijerg([a1], [a3, a4], [b1], [b3 + 1, b4], z), z) assert tn(MeijerShiftD(a3).apply(g, op), meijerg([a1], [a3 - 1, a4], [b1], [b3, b4], z), z) s = MeijerUnShiftA([a1], [a3, a4], [b1], [b3, b4], 0, z) assert tn( s.apply(g, op), meijerg([a1], [a3, a4], [b1 - 1], [b3, b4], z), z) s = MeijerUnShiftC([a1], [a3, a4], [b1], [b3, b4], 0, z) assert tn( s.apply(g, op), meijerg([a1], [a3, a4], [b1], [b3 - 1, b4], z), z) s = MeijerUnShiftB([a1], [a3, a4], [b1], [b3, b4], 0, z) assert tn( s.apply(g, op), meijerg([a1 + 1], [a3, a4], [b1], [b3, b4], z), z) s = MeijerUnShiftD([a1], [a3, a4], [b1], [b3, b4], 0, z) assert tn( s.apply(g, op), meijerg([a1], [a3 + 1, a4], [b1], [b3, b4], z), z) @slow def test_meijerg_confluence(): def t(m, a, b): from sympy.core.sympify import sympify a, b = sympify([a, b]) m_ = m m = hyperexpand(m) if not m == Piecewise((a, abs(z) < 1), (b, abs(1/z) < 1), (m_, True)): return False if not (m.args[0].args[0] == a and m.args[1].args[0] == b): return False z0 = randcplx()/10 if abs(m.subs(z, z0).n() - a.subs(z, z0).n()).n() > 1e-10: return False if abs(m.subs(z, 1/z0).n() - b.subs(z, 1/z0).n()).n() > 1e-10: return False return True assert t(meijerg([], [1, 1], [0, 0], [], z), -log(z), 0) assert t(meijerg( [], [3, 1], [0, 0], [], z), -z**2/4 + z - log(z)/2 - Rational(3, 4), 0) assert t(meijerg([], [3, 1], [-1, 0], [], z), z**2/12 - z/2 + log(z)/2 + Rational(1, 4) + 1/(6*z), 0) assert t(meijerg([], [1, 1, 1, 1], [0, 0, 0, 0], [], z), -log(z)**3/6, 0) assert t(meijerg([1, 1], [], [], [0, 0], z), 0, -log(1/z)) assert t(meijerg([1, 1], [2, 2], [1, 1], [0, 0], z), -z*log(z) + 2*z, -log(1/z) + 2) assert t(meijerg([S.Half], [1, 1], [0, 0], [Rational(3, 2)], z), log(z)/2 - 1, 0) def u(an, ap, bm, bq): m = meijerg(an, ap, bm, bq, z) m2 = hyperexpand(m, allow_hyper=True) if m2.has(meijerg) and not (m2.is_Piecewise and len(m2.args) == 3): return False return tn(m, m2, z) assert u([], [1], [0, 0], []) assert u([1, 1], [], [], [0]) assert u([1, 1], [2, 2, 5], [1, 1, 6], [0, 0]) assert u([1, 1], [2, 2, 5], [1, 1, 6], [0]) def test_meijerg_with_Floats(): # see issue #10681 from sympy.polys.domains.realfield import RR f = meijerg(((3.0, 1), ()), ((Rational(3, 2),), (0,)), z) a = -2.3632718012073 g = a*z**Rational(3, 2)*hyper((-0.5, Rational(3, 2)), (Rational(5, 2),), z*exp_polar(I*pi)) assert RR.almosteq((hyperexpand(f)/g).n(), 1.0, 1e-12) def test_lerchphi(): from sympy.functions.special.zeta_functions import (lerchphi, polylog) from sympy.simplify.gammasimp import gammasimp assert hyperexpand(hyper([1, a], [a + 1], z)/a) == lerchphi(z, 1, a) assert hyperexpand( hyper([1, a, a], [a + 1, a + 1], z)/a**2) == lerchphi(z, 2, a) assert hyperexpand(hyper([1, a, a, a], [a + 1, a + 1, a + 1], z)/a**3) == \ lerchphi(z, 3, a) assert hyperexpand(hyper([1] + [a]*10, [a + 1]*10, z)/a**10) == \ lerchphi(z, 10, a) assert gammasimp(hyperexpand(meijerg([0, 1 - a], [], [0], [-a], exp_polar(-I*pi)*z))) == lerchphi(z, 1, a) assert gammasimp(hyperexpand(meijerg([0, 1 - a, 1 - a], [], [0], [-a, -a], exp_polar(-I*pi)*z))) == lerchphi(z, 2, a) assert gammasimp(hyperexpand(meijerg([0, 1 - a, 1 - a, 1 - a], [], [0], [-a, -a, -a], exp_polar(-I*pi)*z))) == lerchphi(z, 3, a) assert hyperexpand(z*hyper([1, 1], [2], z)) == -log(1 + -z) assert hyperexpand(z*hyper([1, 1, 1], [2, 2], z)) == polylog(2, z) assert hyperexpand(z*hyper([1, 1, 1, 1], [2, 2, 2], z)) == polylog(3, z) assert hyperexpand(hyper([1, a, 1 + S.Half], [a + 1, S.Half], z)) == \ -2*a/(z - 1) + (-2*a**2 + a)*lerchphi(z, 1, a) # Now numerical tests. These make sure reductions etc are carried out # correctly # a rational function (polylog at negative integer order) assert can_do([2, 2, 2], [1, 1]) # NOTE these contain log(1-x) etc ... better make sure we have |z| < 1 # reduction of order for polylog assert can_do([1, 1, 1, b + 5], [2, 2, b], div=10) # reduction of order for lerchphi # XXX lerchphi in mpmath is flaky assert can_do( [1, a, a, a, b + 5], [a + 1, a + 1, a + 1, b], numerical=False) # test a bug from sympy.functions.elementary.complexes import Abs assert hyperexpand(hyper([S.Half, S.Half, S.Half, 1], [Rational(3, 2), Rational(3, 2), Rational(3, 2)], Rational(1, 4))) == \ Abs(-polylog(3, exp_polar(I*pi)/2) + polylog(3, S.Half)) def test_partial_simp(): # First test that hypergeometric function formulae work. a, b, c, d, e = (randcplx() for _ in range(5)) for func in [Hyper_Function([a, b, c], [d, e]), Hyper_Function([], [a, b, c, d, e])]: f = build_hypergeometric_formula(func) z = f.z assert f.closed_form == func(z) deriv1 = f.B.diff(z)*z deriv2 = f.M*f.B for func1, func2 in zip(deriv1, deriv2): assert tn(func1, func2, z) # Now test that formulae are partially simplified. a, b, z = symbols('a b z') assert hyperexpand(hyper([3, a], [1, b], z)) == \ (-a*b/2 + a*z/2 + 2*a)*hyper([a + 1], [b], z) \ + (a*b/2 - 2*a + 1)*hyper([a], [b], z) assert tn( hyperexpand(hyper([3, d], [1, e], z)), hyper([3, d], [1, e], z), z) assert hyperexpand(hyper([3], [1, a, b], z)) == \ hyper((), (a, b), z) \ + z*hyper((), (a + 1, b), z)/(2*a) \ - z*(b - 4)*hyper((), (a + 1, b + 1), z)/(2*a*b) assert tn( hyperexpand(hyper([3], [1, d, e], z)), hyper([3], [1, d, e], z), z) def test_hyperexpand_special(): assert hyperexpand(hyper([a, b], [c], 1)) == \ gamma(c)*gamma(c - a - b)/gamma(c - a)/gamma(c - b) assert hyperexpand(hyper([a, b], [1 + a - b], -1)) == \ gamma(1 + a/2)*gamma(1 + a - b)/gamma(1 + a)/gamma(1 + a/2 - b) assert hyperexpand(hyper([a, b], [1 + b - a], -1)) == \ gamma(1 + b/2)*gamma(1 + b - a)/gamma(1 + b)/gamma(1 + b/2 - a) assert hyperexpand(meijerg([1 - z - a/2], [1 - z + a/2], [b/2], [-b/2], 1)) == \ gamma(1 - 2*z)*gamma(z + a/2 + b/2)/gamma(1 - z + a/2 - b/2) \ /gamma(1 - z - a/2 + b/2)/gamma(1 - z + a/2 + b/2) assert hyperexpand(hyper([a], [b], 0)) == 1 assert hyper([a], [b], 0) != 0 def test_Mod1_behavior(): from sympy.core.symbol import Symbol from sympy.simplify.simplify import simplify n = Symbol('n', integer=True) # Note: this should not hang. assert simplify(hyperexpand(meijerg([1], [], [n + 1], [0], z))) == \ lowergamma(n + 1, z) @slow def test_prudnikov_misc(): assert can_do([1, (3 + I)/2, (3 - I)/2], [Rational(3, 2), 2]) assert can_do([S.Half, a - 1], [Rational(3, 2), a + 1], lowerplane=True) assert can_do([], [b + 1]) assert can_do([a], [a - 1, b + 1]) assert can_do([a], [a - S.Half, 2*a]) assert can_do([a], [a - S.Half, 2*a + 1]) assert can_do([a], [a - S.Half, 2*a - 1]) assert can_do([a], [a + S.Half, 2*a]) assert can_do([a], [a + S.Half, 2*a + 1]) assert can_do([a], [a + S.Half, 2*a - 1]) assert can_do([S.Half], [b, 2 - b]) assert can_do([S.Half], [b, 3 - b]) assert can_do([1], [2, b]) assert can_do([a, a + S.Half], [2*a, b, 2*a - b + 1]) assert can_do([a, a + S.Half], [S.Half, 2*a, 2*a + S.Half]) assert can_do([a], [a + 1], lowerplane=True) # lowergamma def test_prudnikov_1(): # A. P. Prudnikov, Yu. A. Brychkov and O. I. Marichev (1990). # Integrals and Series: More Special Functions, Vol. 3,. # Gordon and Breach Science Publisher # 7.3.1 assert can_do([a, -a], [S.Half]) assert can_do([a, 1 - a], [S.Half]) assert can_do([a, 1 - a], [Rational(3, 2)]) assert can_do([a, 2 - a], [S.Half]) assert can_do([a, 2 - a], [Rational(3, 2)]) assert can_do([a, 2 - a], [Rational(3, 2)]) assert can_do([a, a + S.Half], [2*a - 1]) assert can_do([a, a + S.Half], [2*a]) assert can_do([a, a + S.Half], [2*a + 1]) assert can_do([a, a + S.Half], [S.Half]) assert can_do([a, a + S.Half], [Rational(3, 2)]) assert can_do([a, a/2 + 1], [a/2]) assert can_do([1, b], [2]) assert can_do([1, b], [b + 1], numerical=False) # Lerch Phi # NOTE: branches are complicated for |z| > 1 assert can_do([a], [2*a]) assert can_do([a], [2*a + 1]) assert can_do([a], [2*a - 1]) @slow def test_prudnikov_2(): h = S.Half assert can_do([-h, -h], [h]) assert can_do([-h, h], [3*h]) assert can_do([-h, h], [5*h]) assert can_do([-h, h], [7*h]) assert can_do([-h, 1], [h]) for p in [-h, h]: for n in [-h, h, 1, 3*h, 2, 5*h, 3, 7*h, 4]: for m in [-h, h, 3*h, 5*h, 7*h]: assert can_do([p, n], [m]) for n in [1, 2, 3, 4]: for m in [1, 2, 3, 4]: assert can_do([p, n], [m]) @slow def test_prudnikov_3(): if ON_TRAVIS: # See https://github.com/sympy/sympy/pull/12795 skip("Too slow for travis.") h = S.Half assert can_do([Rational(1, 4), Rational(3, 4)], [h]) assert can_do([Rational(1, 4), Rational(3, 4)], [3*h]) assert can_do([Rational(1, 3), Rational(2, 3)], [3*h]) assert can_do([Rational(3, 4), Rational(5, 4)], [h]) assert can_do([Rational(3, 4), Rational(5, 4)], [3*h]) for p in [1, 2, 3, 4]: for n in [-h, h, 1, 3*h, 2, 5*h, 3, 7*h, 4, 9*h]: for m in [1, 3*h, 2, 5*h, 3, 7*h, 4]: assert can_do([p, m], [n]) @slow def test_prudnikov_4(): h = S.Half for p in [3*h, 5*h, 7*h]: for n in [-h, h, 3*h, 5*h, 7*h]: for m in [3*h, 2, 5*h, 3, 7*h, 4]: assert can_do([p, m], [n]) for n in [1, 2, 3, 4]: for m in [2, 3, 4]: assert can_do([p, m], [n]) @slow def test_prudnikov_5(): h = S.Half for p in [1, 2, 3]: for q in range(p, 4): for r in [1, 2, 3]: for s in range(r, 4): assert can_do([-h, p, q], [r, s]) for p in [h, 1, 3*h, 2, 5*h, 3]: for q in [h, 3*h, 5*h]: for r in [h, 3*h, 5*h]: for s in [h, 3*h, 5*h]: if s <= q and s <= r: assert can_do([-h, p, q], [r, s]) for p in [h, 1, 3*h, 2, 5*h, 3]: for q in [1, 2, 3]: for r in [h, 3*h, 5*h]: for s in [1, 2, 3]: assert can_do([-h, p, q], [r, s]) @slow def test_prudnikov_6(): h = S.Half for m in [3*h, 5*h]: for n in [1, 2, 3]: for q in [h, 1, 2]: for p in [1, 2, 3]: assert can_do([h, q, p], [m, n]) for q in [1, 2, 3]: for p in [3*h, 5*h]: assert can_do([h, q, p], [m, n]) for q in [1, 2]: for p in [1, 2, 3]: for m in [1, 2, 3]: for n in [1, 2, 3]: assert can_do([h, q, p], [m, n]) assert can_do([h, h, 5*h], [3*h, 3*h]) assert can_do([h, 1, 5*h], [3*h, 3*h]) assert can_do([h, 2, 2], [1, 3]) # pages 435 to 457 contain more PFDD and stuff like this @slow def test_prudnikov_7(): assert can_do([3], [6]) h = S.Half for n in [h, 3*h, 5*h, 7*h]: assert can_do([-h], [n]) for m in [-h, h, 1, 3*h, 2, 5*h, 3, 7*h, 4]: # HERE for n in [-h, h, 3*h, 5*h, 7*h, 1, 2, 3, 4]: assert can_do([m], [n]) @slow def test_prudnikov_8(): h = S.Half # 7.12.2 for ai in [1, 2, 3]: for bi in [1, 2, 3]: for ci in range(1, ai + 1): for di in [h, 1, 3*h, 2, 5*h, 3]: assert can_do([ai, bi], [ci, di]) for bi in [3*h, 5*h]: for ci in [h, 1, 3*h, 2, 5*h, 3]: for di in [1, 2, 3]: assert can_do([ai, bi], [ci, di]) for ai in [-h, h, 3*h, 5*h]: for bi in [1, 2, 3]: for ci in [h, 1, 3*h, 2, 5*h, 3]: for di in [1, 2, 3]: assert can_do([ai, bi], [ci, di]) for bi in [h, 3*h, 5*h]: for ci in [h, 3*h, 5*h, 3]: for di in [h, 1, 3*h, 2, 5*h, 3]: if ci <= bi: assert can_do([ai, bi], [ci, di]) def test_prudnikov_9(): # 7.13.1 [we have a general formula ... so this is a bit pointless] for i in range(9): assert can_do([], [(S(i) + 1)/2]) for i in range(5): assert can_do([], [-(2*S(i) + 1)/2]) @slow def test_prudnikov_10(): # 7.14.2 h = S.Half for p in [-h, h, 1, 3*h, 2, 5*h, 3, 7*h, 4]: for m in [1, 2, 3, 4]: for n in range(m, 5): assert can_do([p], [m, n]) for p in [1, 2, 3, 4]: for n in [h, 3*h, 5*h, 7*h]: for m in [1, 2, 3, 4]: assert can_do([p], [n, m]) for p in [3*h, 5*h, 7*h]: for m in [h, 1, 2, 5*h, 3, 7*h, 4]: assert can_do([p], [h, m]) assert can_do([p], [3*h, m]) for m in [h, 1, 2, 5*h, 3, 7*h, 4]: assert can_do([7*h], [5*h, m]) assert can_do([Rational(-1, 2)], [S.Half, S.Half]) # shine-integral shi def test_prudnikov_11(): # 7.15 assert can_do([a, a + S.Half], [2*a, b, 2*a - b]) assert can_do([a, a + S.Half], [Rational(3, 2), 2*a, 2*a - S.Half]) assert can_do([Rational(1, 4), Rational(3, 4)], [S.Half, S.Half, 1]) assert can_do([Rational(5, 4), Rational(3, 4)], [Rational(3, 2), S.Half, 2]) assert can_do([Rational(5, 4), Rational(3, 4)], [Rational(3, 2), Rational(3, 2), 1]) assert can_do([Rational(5, 4), Rational(7, 4)], [Rational(3, 2), Rational(5, 2), 2]) assert can_do([1, 1], [Rational(3, 2), 2, 2]) # cosh-integral chi def test_prudnikov_12(): # 7.16 assert can_do( [], [a, a + S.Half, 2*a], False) # branches only agree for some z! assert can_do([], [a, a + S.Half, 2*a + 1], False) # dito assert can_do([], [S.Half, a, a + S.Half]) assert can_do([], [Rational(3, 2), a, a + S.Half]) assert can_do([], [Rational(1, 4), S.Half, Rational(3, 4)]) assert can_do([], [S.Half, S.Half, 1]) assert can_do([], [S.Half, Rational(3, 2), 1]) assert can_do([], [Rational(3, 4), Rational(3, 2), Rational(5, 4)]) assert can_do([], [1, 1, Rational(3, 2)]) assert can_do([], [1, 2, Rational(3, 2)]) assert can_do([], [1, Rational(3, 2), Rational(3, 2)]) assert can_do([], [Rational(5, 4), Rational(3, 2), Rational(7, 4)]) assert can_do([], [2, Rational(3, 2), Rational(3, 2)]) @slow def test_prudnikov_2F1(): h = S.Half # Elliptic integrals for p in [-h, h]: for m in [h, 3*h, 5*h, 7*h]: for n in [1, 2, 3, 4]: assert can_do([p, m], [n]) @XFAIL def test_prudnikov_fail_2F1(): assert can_do([a, b], [b + 1]) # incomplete beta function assert can_do([-1, b], [c]) # Poly. also -2, -3 etc # TODO polys # Legendre functions: assert can_do([a, b], [a + b + S.Half]) assert can_do([a, b], [a + b - S.Half]) assert can_do([a, b], [a + b + Rational(3, 2)]) assert can_do([a, b], [(a + b + 1)/2]) assert can_do([a, b], [(a + b)/2 + 1]) assert can_do([a, b], [a - b + 1]) assert can_do([a, b], [a - b + 2]) assert can_do([a, b], [2*b]) assert can_do([a, b], [S.Half]) assert can_do([a, b], [Rational(3, 2)]) assert can_do([a, 1 - a], [c]) assert can_do([a, 2 - a], [c]) assert can_do([a, 3 - a], [c]) assert can_do([a, a + S.Half], [c]) assert can_do([1, b], [c]) assert can_do([1, b], [Rational(3, 2)]) assert can_do([Rational(1, 4), Rational(3, 4)], [1]) # PFDD o = S.One assert can_do([o/8, 1], [o/8*9]) assert can_do([o/6, 1], [o/6*7]) assert can_do([o/6, 1], [o/6*13]) assert can_do([o/5, 1], [o/5*6]) assert can_do([o/5, 1], [o/5*11]) assert can_do([o/4, 1], [o/4*5]) assert can_do([o/4, 1], [o/4*9]) assert can_do([o/3, 1], [o/3*4]) assert can_do([o/3, 1], [o/3*7]) assert can_do([o/8*3, 1], [o/8*11]) assert can_do([o/5*2, 1], [o/5*7]) assert can_do([o/5*2, 1], [o/5*12]) assert can_do([o/5*3, 1], [o/5*8]) assert can_do([o/5*3, 1], [o/5*13]) assert can_do([o/8*5, 1], [o/8*13]) assert can_do([o/4*3, 1], [o/4*7]) assert can_do([o/4*3, 1], [o/4*11]) assert can_do([o/3*2, 1], [o/3*5]) assert can_do([o/3*2, 1], [o/3*8]) assert can_do([o/5*4, 1], [o/5*9]) assert can_do([o/5*4, 1], [o/5*14]) assert can_do([o/6*5, 1], [o/6*11]) assert can_do([o/6*5, 1], [o/6*17]) assert can_do([o/8*7, 1], [o/8*15]) @XFAIL def test_prudnikov_fail_3F2(): assert can_do([a, a + Rational(1, 3), a + Rational(2, 3)], [Rational(1, 3), Rational(2, 3)]) assert can_do([a, a + Rational(1, 3), a + Rational(2, 3)], [Rational(2, 3), Rational(4, 3)]) assert can_do([a, a + Rational(1, 3), a + Rational(2, 3)], [Rational(4, 3), Rational(5, 3)]) # page 421 assert can_do([a, a + Rational(1, 3), a + Rational(2, 3)], [a*Rational(3, 2), (3*a + 1)/2]) # pages 422 ... assert can_do([Rational(-1, 2), S.Half, S.Half], [1, 1]) # elliptic integrals assert can_do([Rational(-1, 2), S.Half, 1], [Rational(3, 2), Rational(3, 2)]) # TODO LOTS more # PFDD assert can_do([Rational(1, 8), Rational(3, 8), 1], [Rational(9, 8), Rational(11, 8)]) assert can_do([Rational(1, 8), Rational(5, 8), 1], [Rational(9, 8), Rational(13, 8)]) assert can_do([Rational(1, 8), Rational(7, 8), 1], [Rational(9, 8), Rational(15, 8)]) assert can_do([Rational(1, 6), Rational(1, 3), 1], [Rational(7, 6), Rational(4, 3)]) assert can_do([Rational(1, 6), Rational(2, 3), 1], [Rational(7, 6), Rational(5, 3)]) assert can_do([Rational(1, 6), Rational(2, 3), 1], [Rational(5, 3), Rational(13, 6)]) assert can_do([S.Half, 1, 1], [Rational(1, 4), Rational(3, 4)]) # LOTS more @XFAIL def test_prudnikov_fail_other(): # 7.11.2 # 7.12.1 assert can_do([1, a], [b, 1 - 2*a + b]) # ??? # 7.14.2 assert can_do([Rational(-1, 2)], [S.Half, 1]) # struve assert can_do([1], [S.Half, S.Half]) # struve assert can_do([Rational(1, 4)], [S.Half, Rational(5, 4)]) # PFDD assert can_do([Rational(3, 4)], [Rational(3, 2), Rational(7, 4)]) # PFDD assert can_do([1], [Rational(1, 4), Rational(3, 4)]) # PFDD assert can_do([1], [Rational(3, 4), Rational(5, 4)]) # PFDD assert can_do([1], [Rational(5, 4), Rational(7, 4)]) # PFDD # TODO LOTS more # 7.15.2 assert can_do([S.Half, 1], [Rational(3, 4), Rational(5, 4), Rational(3, 2)]) # PFDD assert can_do([S.Half, 1], [Rational(7, 4), Rational(5, 4), Rational(3, 2)]) # PFDD # 7.16.1 assert can_do([], [Rational(1, 3), S(2/3)]) # PFDD assert can_do([], [Rational(2, 3), S(4/3)]) # PFDD assert can_do([], [Rational(5, 3), S(4/3)]) # PFDD # XXX this does not *evaluate* right?? assert can_do([], [a, a + S.Half, 2*a - 1]) def test_bug(): h = hyper([-1, 1], [z], -1) assert hyperexpand(h) == (z + 1)/z def test_omgissue_203(): h = hyper((-5, -3, -4), (-6, -6), 1) assert hyperexpand(h) == Rational(1, 30) h = hyper((-6, -7, -5), (-6, -6), 1) assert hyperexpand(h) == Rational(-1, 6)
262f220886a98f020ca8ce19ed52bcb016e118bd838ab1180cb7d0618f526134
from sympy.concrete.summations import Sum from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.expr import unchanged from sympy.core.function import (count_ops, diff, expand, expand_multinomial, Function, Derivative) from sympy.core.mul import Mul, _keep_coeff from sympy.core import GoldenRatio from sympy.core.numbers import (E, Float, I, oo, pi, Rational, zoo) from sympy.core.relational import (Eq, Lt, Gt, Ge, Le) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import (binomial, factorial) from sympy.functions.elementary.complexes import (Abs, sign) from sympy.functions.elementary.exponential import (exp, exp_polar, log) from sympy.functions.elementary.hyperbolic import (cosh, csch, sinh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, sinc, tan) from sympy.functions.special.error_functions import erf from sympy.functions.special.gamma_functions import gamma from sympy.functions.special.hyper import hyper from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.geometry.polygon import rad from sympy.integrals.integrals import (Integral, integrate) from sympy.logic.boolalg import (And, Or) from sympy.matrices.dense import (Matrix, eye) from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.polys.polytools import (factor, Poly) from sympy.simplify.simplify import (besselsimp, hypersimp, inversecombine, logcombine, nsimplify, nthroot, posify, separatevars, signsimp, simplify) from sympy.solvers.solvers import solve from sympy.testing.pytest import XFAIL, slow, _both_exp_pow from sympy.abc import x, y, z, t, a, b, c, d, e, f, g, h, i, n def test_issue_7263(): assert abs((simplify(30.8**2 - 82.5**2 * sin(rad(11.6))**2)).evalf() - \ 673.447451402970) < 1e-12 def test_factorial_simplify(): # There are more tests in test_factorials.py. x = Symbol('x') assert simplify(factorial(x)/x) == gamma(x) assert simplify(factorial(factorial(x))) == factorial(factorial(x)) def test_simplify_expr(): x, y, z, k, n, m, w, s, A = symbols('x,y,z,k,n,m,w,s,A') f = Function('f') assert all(simplify(tmp) == tmp for tmp in [I, E, oo, x, -x, -oo, -E, -I]) e = 1/x + 1/y assert e != (x + y)/(x*y) assert simplify(e) == (x + y)/(x*y) e = A**2*s**4/(4*pi*k*m**3) assert simplify(e) == e e = (4 + 4*x - 2*(2 + 2*x))/(2 + 2*x) assert simplify(e) == 0 e = (-4*x*y**2 - 2*y**3 - 2*x**2*y)/(x + y)**2 assert simplify(e) == -2*y e = -x - y - (x + y)**(-1)*y**2 + (x + y)**(-1)*x**2 assert simplify(e) == -2*y e = (x + x*y)/x assert simplify(e) == 1 + y e = (f(x) + y*f(x))/f(x) assert simplify(e) == 1 + y e = (2 * (1/n - cos(n * pi)/n))/pi assert simplify(e) == (-cos(pi*n) + 1)/(pi*n)*2 e = integrate(1/(x**3 + 1), x).diff(x) assert simplify(e) == 1/(x**3 + 1) e = integrate(x/(x**2 + 3*x + 1), x).diff(x) assert simplify(e) == x/(x**2 + 3*x + 1) f = Symbol('f') A = Matrix([[2*k - m*w**2, -k], [-k, k - m*w**2]]).inv() assert simplify((A*Matrix([0, f]))[1] - (-f*(2*k - m*w**2)/(k**2 - (k - m*w**2)*(2*k - m*w**2)))) == 0 f = -x + y/(z + t) + z*x/(z + t) + z*a/(z + t) + t*x/(z + t) assert simplify(f) == (y + a*z)/(z + t) # issue 10347 expr = -x*(y**2 - 1)*(2*y**2*(x**2 - 1)/(a*(x**2 - y**2)**2) + (x**2 - 1) /(a*(x**2 - y**2)))/(a*(x**2 - y**2)) + x*(-2*x**2*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(a*(x**2 - y**2)**2) - x**2*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(a*(x**2 - 1)*(x**2 - y**2)) + (x**2*sqrt((-x**2 + 1)* (y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(x**2 - 1) + sqrt( (-x**2 + 1)*(y**2 - 1))*(x*(-x*y**2 + x)/sqrt(-x**2*y**2 + x**2 + y**2 - 1) + sqrt(-x**2*y**2 + x**2 + y**2 - 1))*sin(z))/(a*sqrt((-x**2 + 1)*( y**2 - 1))*(x**2 - y**2)))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(a* (x**2 - y**2)) + x*(-2*x**2*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(a* (x**2 - y**2)**2) - x**2*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(a* (x**2 - 1)*(x**2 - y**2)) + (x**2*sqrt((-x**2 + 1)*(y**2 - 1))*sqrt(-x**2 *y**2 + x**2 + y**2 - 1)*cos(z)/(x**2 - 1) + x*sqrt((-x**2 + 1)*(y**2 - 1))*(-x*y**2 + x)*cos(z)/sqrt(-x**2*y**2 + x**2 + y**2 - 1) + sqrt((-x**2 + 1)*(y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z))/(a*sqrt((-x**2 + 1)*(y**2 - 1))*(x**2 - y**2)))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos( z)/(a*(x**2 - y**2)) - y*sqrt((-x**2 + 1)*(y**2 - 1))*(-x*y*sqrt(-x**2* y**2 + x**2 + y**2 - 1)*sin(z)/(a*(x**2 - y**2)*(y**2 - 1)) + 2*x*y*sqrt( -x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(a*(x**2 - y**2)**2) + (x*y*sqrt(( -x**2 + 1)*(y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(y**2 - 1) + x*sqrt((-x**2 + 1)*(y**2 - 1))*(-x**2*y + y)*sin(z)/sqrt(-x**2*y**2 + x**2 + y**2 - 1))/(a*sqrt((-x**2 + 1)*(y**2 - 1))*(x**2 - y**2)))*sin( z)/(a*(x**2 - y**2)) + y*(x**2 - 1)*(-2*x*y*(x**2 - 1)/(a*(x**2 - y**2) **2) + 2*x*y/(a*(x**2 - y**2)))/(a*(x**2 - y**2)) + y*(x**2 - 1)*(y**2 - 1)*(-x*y*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(a*(x**2 - y**2)*(y**2 - 1)) + 2*x*y*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(a*(x**2 - y**2) **2) + (x*y*sqrt((-x**2 + 1)*(y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(y**2 - 1) + x*sqrt((-x**2 + 1)*(y**2 - 1))*(-x**2*y + y)*cos( z)/sqrt(-x**2*y**2 + x**2 + y**2 - 1))/(a*sqrt((-x**2 + 1)*(y**2 - 1) )*(x**2 - y**2)))*cos(z)/(a*sqrt((-x**2 + 1)*(y**2 - 1))*(x**2 - y**2) ) - x*sqrt((-x**2 + 1)*(y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin( z)**2/(a**2*(x**2 - 1)*(x**2 - y**2)*(y**2 - 1)) - x*sqrt((-x**2 + 1)*( y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)**2/(a**2*(x**2 - 1)*( x**2 - y**2)*(y**2 - 1)) assert simplify(expr) == 2*x/(a**2*(x**2 - y**2)) #issue 17631 assert simplify('((-1/2)*Boole(True)*Boole(False)-1)*Boole(True)') == \ Mul(sympify('(2 + Boole(True)*Boole(False))'), sympify('-Boole(True)/2')) A, B = symbols('A,B', commutative=False) assert simplify(A*B - B*A) == A*B - B*A assert simplify(A/(1 + y/x)) == x*A/(x + y) assert simplify(A*(1/x + 1/y)) == A/x + A/y #(x + y)*A/(x*y) assert simplify(log(2) + log(3)) == log(6) assert simplify(log(2*x) - log(2)) == log(x) assert simplify(hyper([], [], x)) == exp(x) def test_issue_3557(): f_1 = x*a + y*b + z*c - 1 f_2 = x*d + y*e + z*f - 1 f_3 = x*g + y*h + z*i - 1 solutions = solve([f_1, f_2, f_3], x, y, z, simplify=False) assert simplify(solutions[y]) == \ (a*i + c*d + f*g - a*f - c*g - d*i)/ \ (a*e*i + b*f*g + c*d*h - a*f*h - b*d*i - c*e*g) def test_simplify_other(): assert simplify(sin(x)**2 + cos(x)**2) == 1 assert simplify(gamma(x + 1)/gamma(x)) == x assert simplify(sin(x)**2 + cos(x)**2 + factorial(x)/gamma(x)) == 1 + x assert simplify( Eq(sin(x)**2 + cos(x)**2, factorial(x)/gamma(x))) == Eq(x, 1) nc = symbols('nc', commutative=False) assert simplify(x + x*nc) == x*(1 + nc) # issue 6123 # f = exp(-I*(k*sqrt(t) + x/(2*sqrt(t)))**2) # ans = integrate(f, (k, -oo, oo), conds='none') ans = I*(-pi*x*exp(I*pi*Rational(-3, 4) + I*x**2/(4*t))*erf(x*exp(I*pi*Rational(-3, 4))/ (2*sqrt(t)))/(2*sqrt(t)) + pi*x*exp(I*pi*Rational(-3, 4) + I*x**2/(4*t))/ (2*sqrt(t)))*exp(-I*x**2/(4*t))/(sqrt(pi)*x) - I*sqrt(pi) * \ (-erf(x*exp(I*pi/4)/(2*sqrt(t))) + 1)*exp(I*pi/4)/(2*sqrt(t)) assert simplify(ans) == -(-1)**Rational(3, 4)*sqrt(pi)/sqrt(t) # issue 6370 assert simplify(2**(2 + x)/4) == 2**x @_both_exp_pow def test_simplify_complex(): cosAsExp = cos(x)._eval_rewrite_as_exp(x) tanAsExp = tan(x)._eval_rewrite_as_exp(x) assert simplify(cosAsExp*tanAsExp) == sin(x) # issue 4341 # issue 10124 assert simplify(exp(Matrix([[0, -1], [1, 0]]))) == Matrix([[cos(1), -sin(1)], [sin(1), cos(1)]]) def test_simplify_ratio(): # roots of x**3-3*x+5 roots = ['(1/2 - sqrt(3)*I/2)*(sqrt(21)/2 + 5/2)**(1/3) + 1/((1/2 - ' 'sqrt(3)*I/2)*(sqrt(21)/2 + 5/2)**(1/3))', '1/((1/2 + sqrt(3)*I/2)*(sqrt(21)/2 + 5/2)**(1/3)) + ' '(1/2 + sqrt(3)*I/2)*(sqrt(21)/2 + 5/2)**(1/3)', '-(sqrt(21)/2 + 5/2)**(1/3) - 1/(sqrt(21)/2 + 5/2)**(1/3)'] for r in roots: r = S(r) assert count_ops(simplify(r, ratio=1)) <= count_ops(r) # If ratio=oo, simplify() is always applied: assert simplify(r, ratio=oo) is not r def test_simplify_measure(): measure1 = lambda expr: len(str(expr)) measure2 = lambda expr: -count_ops(expr) # Return the most complicated result expr = (x + 1)/(x + sin(x)**2 + cos(x)**2) assert measure1(simplify(expr, measure=measure1)) <= measure1(expr) assert measure2(simplify(expr, measure=measure2)) <= measure2(expr) expr2 = Eq(sin(x)**2 + cos(x)**2, 1) assert measure1(simplify(expr2, measure=measure1)) <= measure1(expr2) assert measure2(simplify(expr2, measure=measure2)) <= measure2(expr2) def test_simplify_rational(): expr = 2**x*2.**y assert simplify(expr, rational = True) == 2**(x+y) assert simplify(expr, rational = None) == 2.0**(x+y) assert simplify(expr, rational = False) == expr assert simplify('0.9 - 0.8 - 0.1', rational = True) == 0 def test_simplify_issue_1308(): assert simplify(exp(Rational(-1, 2)) + exp(Rational(-3, 2))) == \ (1 + E)*exp(Rational(-3, 2)) def test_issue_5652(): assert simplify(E + exp(-E)) == exp(-E) + E n = symbols('n', commutative=False) assert simplify(n + n**(-n)) == n + n**(-n) def test_simplify_fail1(): x = Symbol('x') y = Symbol('y') e = (x + y)**2/(-4*x*y**2 - 2*y**3 - 2*x**2*y) assert simplify(e) == 1 / (-2*y) def test_nthroot(): assert nthroot(90 + 34*sqrt(7), 3) == sqrt(7) + 3 q = 1 + sqrt(2) - 2*sqrt(3) + sqrt(6) + sqrt(7) assert nthroot(expand_multinomial(q**3), 3) == q assert nthroot(41 + 29*sqrt(2), 5) == 1 + sqrt(2) assert nthroot(-41 - 29*sqrt(2), 5) == -1 - sqrt(2) expr = 1320*sqrt(10) + 4216 + 2576*sqrt(6) + 1640*sqrt(15) assert nthroot(expr, 5) == 1 + sqrt(6) + sqrt(15) q = 1 + sqrt(2) + sqrt(3) + sqrt(5) assert expand_multinomial(nthroot(expand_multinomial(q**5), 5)) == q q = 1 + sqrt(2) + 7*sqrt(6) + 2*sqrt(10) assert nthroot(expand_multinomial(q**5), 5, 8) == q q = 1 + sqrt(2) - 2*sqrt(3) + 1171*sqrt(6) assert nthroot(expand_multinomial(q**3), 3) == q assert nthroot(expand_multinomial(q**6), 6) == q def test_nthroot1(): q = 1 + sqrt(2) + sqrt(3) + S.One/10**20 p = expand_multinomial(q**5) assert nthroot(p, 5) == q q = 1 + sqrt(2) + sqrt(3) + S.One/10**30 p = expand_multinomial(q**5) assert nthroot(p, 5) == q @_both_exp_pow def test_separatevars(): x, y, z, n = symbols('x,y,z,n') assert separatevars(2*n*x*z + 2*x*y*z) == 2*x*z*(n + y) assert separatevars(x*z + x*y*z) == x*z*(1 + y) assert separatevars(pi*x*z + pi*x*y*z) == pi*x*z*(1 + y) assert separatevars(x*y**2*sin(x) + x*sin(x)*sin(y)) == \ x*(sin(y) + y**2)*sin(x) assert separatevars(x*exp(x + y) + x*exp(x)) == x*(1 + exp(y))*exp(x) assert separatevars((x*(y + 1))**z).is_Pow # != x**z*(1 + y)**z assert separatevars(1 + x + y + x*y) == (x + 1)*(y + 1) assert separatevars(y/pi*exp(-(z - x)/cos(n))) == \ y*exp(x/cos(n))*exp(-z/cos(n))/pi assert separatevars((x + y)*(x - y) + y**2 + 2*x + 1) == (x + 1)**2 # issue 4858 p = Symbol('p', positive=True) assert separatevars(sqrt(p**2 + x*p**2)) == p*sqrt(1 + x) assert separatevars(sqrt(y*(p**2 + x*p**2))) == p*sqrt(y*(1 + x)) assert separatevars(sqrt(y*(p**2 + x*p**2)), force=True) == \ p*sqrt(y)*sqrt(1 + x) # issue 4865 assert separatevars(sqrt(x*y)).is_Pow assert separatevars(sqrt(x*y), force=True) == sqrt(x)*sqrt(y) # issue 4957 # any type sequence for symbols is fine assert separatevars(((2*x + 2)*y), dict=True, symbols=()) == \ {'coeff': 1, x: 2*x + 2, y: y} # separable assert separatevars(((2*x + 2)*y), dict=True, symbols=[x]) == \ {'coeff': y, x: 2*x + 2} assert separatevars(((2*x + 2)*y), dict=True, symbols=[]) == \ {'coeff': 1, x: 2*x + 2, y: y} assert separatevars(((2*x + 2)*y), dict=True) == \ {'coeff': 1, x: 2*x + 2, y: y} assert separatevars(((2*x + 2)*y), dict=True, symbols=None) == \ {'coeff': y*(2*x + 2)} # not separable assert separatevars(3, dict=True) is None assert separatevars(2*x + y, dict=True, symbols=()) is None assert separatevars(2*x + y, dict=True) is None assert separatevars(2*x + y, dict=True, symbols=None) == {'coeff': 2*x + y} # issue 4808 n, m = symbols('n,m', commutative=False) assert separatevars(m + n*m) == (1 + n)*m assert separatevars(x + x*n) == x*(1 + n) # issue 4910 f = Function('f') assert separatevars(f(x) + x*f(x)) == f(x) + x*f(x) # a noncommutable object present eq = x*(1 + hyper((), (), y*z)) assert separatevars(eq) == eq s = separatevars(abs(x*y)) assert s == abs(x)*abs(y) and s.is_Mul z = cos(1)**2 + sin(1)**2 - 1 a = abs(x*z) s = separatevars(a) assert not a.is_Mul and s.is_Mul and s == abs(x)*abs(z) s = separatevars(abs(x*y*z)) assert s == abs(x)*abs(y)*abs(z) # abs(x+y)/abs(z) would be better but we test this here to # see that it doesn't raise assert separatevars(abs((x+y)/z)) == abs((x+y)/z) def test_separatevars_advanced_factor(): x, y, z = symbols('x,y,z') assert separatevars(1 + log(x)*log(y) + log(x) + log(y)) == \ (log(x) + 1)*(log(y) + 1) assert separatevars(1 + x - log(z) - x*log(z) - exp(y)*log(z) - x*exp(y)*log(z) + x*exp(y) + exp(y)) == \ -((x + 1)*(log(z) - 1)*(exp(y) + 1)) x, y = symbols('x,y', positive=True) assert separatevars(1 + log(x**log(y)) + log(x*y)) == \ (log(x) + 1)*(log(y) + 1) def test_hypersimp(): n, k = symbols('n,k', integer=True) assert hypersimp(factorial(k), k) == k + 1 assert hypersimp(factorial(k**2), k) is None assert hypersimp(1/factorial(k), k) == 1/(k + 1) assert hypersimp(2**k/factorial(k)**2, k) == 2/(k + 1)**2 assert hypersimp(binomial(n, k), k) == (n - k)/(k + 1) assert hypersimp(binomial(n + 1, k), k) == (n - k + 1)/(k + 1) term = (4*k + 1)*factorial(k)/factorial(2*k + 1) assert hypersimp(term, k) == S.Half*((4*k + 5)/(3 + 14*k + 8*k**2)) term = 1/((2*k - 1)*factorial(2*k + 1)) assert hypersimp(term, k) == (k - S.Half)/((k + 1)*(2*k + 1)*(2*k + 3)) term = binomial(n, k)*(-1)**k/factorial(k) assert hypersimp(term, k) == (k - n)/(k + 1)**2 def test_nsimplify(): x = Symbol("x") assert nsimplify(0) == 0 assert nsimplify(-1) == -1 assert nsimplify(1) == 1 assert nsimplify(1 + x) == 1 + x assert nsimplify(2.7) == Rational(27, 10) assert nsimplify(1 - GoldenRatio) == (1 - sqrt(5))/2 assert nsimplify((1 + sqrt(5))/4, [GoldenRatio]) == GoldenRatio/2 assert nsimplify(2/GoldenRatio, [GoldenRatio]) == 2*GoldenRatio - 2 assert nsimplify(exp(pi*I*Rational(5, 3), evaluate=False)) == \ sympify('1/2 - sqrt(3)*I/2') assert nsimplify(sin(pi*Rational(3, 5), evaluate=False)) == \ sympify('sqrt(sqrt(5)/8 + 5/8)') assert nsimplify(sqrt(atan('1', evaluate=False))*(2 + I), [pi]) == \ sqrt(pi) + sqrt(pi)/2*I assert nsimplify(2 + exp(2*atan('1/4')*I)) == sympify('49/17 + 8*I/17') assert nsimplify(pi, tolerance=0.01) == Rational(22, 7) assert nsimplify(pi, tolerance=0.001) == Rational(355, 113) assert nsimplify(0.33333, tolerance=1e-4) == Rational(1, 3) assert nsimplify(2.0**(1/3.), tolerance=0.001) == Rational(635, 504) assert nsimplify(2.0**(1/3.), tolerance=0.001, full=True) == \ 2**Rational(1, 3) assert nsimplify(x + .5, rational=True) == S.Half + x assert nsimplify(1/.3 + x, rational=True) == Rational(10, 3) + x assert nsimplify(log(3).n(), rational=True) == \ sympify('109861228866811/100000000000000') assert nsimplify(Float(0.272198261287950), [pi, log(2)]) == pi*log(2)/8 assert nsimplify(Float(0.272198261287950).n(3), [pi, log(2)]) == \ -pi/4 - log(2) + Rational(7, 4) assert nsimplify(x/7.0) == x/7 assert nsimplify(pi/1e2) == pi/100 assert nsimplify(pi/1e2, rational=False) == pi/100.0 assert nsimplify(pi/1e-7) == 10000000*pi assert not nsimplify( factor(-3.0*z**2*(z**2)**(-2.5) + 3*(z**2)**(-1.5))).atoms(Float) e = x**0.0 assert e.is_Pow and nsimplify(x**0.0) == 1 assert nsimplify(3.333333, tolerance=0.1, rational=True) == Rational(10, 3) assert nsimplify(3.333333, tolerance=0.01, rational=True) == Rational(10, 3) assert nsimplify(3.666666, tolerance=0.1, rational=True) == Rational(11, 3) assert nsimplify(3.666666, tolerance=0.01, rational=True) == Rational(11, 3) assert nsimplify(33, tolerance=10, rational=True) == Rational(33) assert nsimplify(33.33, tolerance=10, rational=True) == Rational(30) assert nsimplify(37.76, tolerance=10, rational=True) == Rational(40) assert nsimplify(-203.1) == Rational(-2031, 10) assert nsimplify(.2, tolerance=0) == Rational(1, 5) assert nsimplify(-.2, tolerance=0) == Rational(-1, 5) assert nsimplify(.2222, tolerance=0) == Rational(1111, 5000) assert nsimplify(-.2222, tolerance=0) == Rational(-1111, 5000) # issue 7211, PR 4112 assert nsimplify(S(2e-8)) == Rational(1, 50000000) # issue 7322 direct test assert nsimplify(1e-42, rational=True) != 0 # issue 10336 inf = Float('inf') infs = (-oo, oo, inf, -inf) for zi in infs: ans = sign(zi)*oo assert nsimplify(zi) == ans assert nsimplify(zi + x) == x + ans assert nsimplify(0.33333333, rational=True, rational_conversion='exact') == Rational(0.33333333) # Make sure nsimplify on expressions uses full precision assert nsimplify(pi.evalf(100)*x, rational_conversion='exact').evalf(100) == pi.evalf(100)*x def test_issue_9448(): tmp = sympify("1/(1 - (-1)**(2/3) - (-1)**(1/3)) + 1/(1 + (-1)**(2/3) + (-1)**(1/3))") assert nsimplify(tmp) == S.Half def test_extract_minus_sign(): x = Symbol("x") y = Symbol("y") a = Symbol("a") b = Symbol("b") assert simplify(-x/-y) == x/y assert simplify(-x/y) == -x/y assert simplify(x/y) == x/y assert simplify(x/-y) == -x/y assert simplify(-x/0) == zoo*x assert simplify(Rational(-5, 0)) is zoo assert simplify(-a*x/(-y - b)) == a*x/(b + y) def test_diff(): x = Symbol("x") y = Symbol("y") f = Function("f") g = Function("g") assert simplify(g(x).diff(x)*f(x).diff(x) - f(x).diff(x)*g(x).diff(x)) == 0 assert simplify(2*f(x)*f(x).diff(x) - diff(f(x)**2, x)) == 0 assert simplify(diff(1/f(x), x) + f(x).diff(x)/f(x)**2) == 0 assert simplify(f(x).diff(x, y) - f(x).diff(y, x)) == 0 def test_logcombine_1(): x, y = symbols("x,y") a = Symbol("a") z, w = symbols("z,w", positive=True) b = Symbol("b", real=True) assert logcombine(log(x) + 2*log(y)) == log(x) + 2*log(y) assert logcombine(log(x) + 2*log(y), force=True) == log(x*y**2) assert logcombine(a*log(w) + log(z)) == a*log(w) + log(z) assert logcombine(b*log(z) + b*log(x)) == log(z**b) + b*log(x) assert logcombine(b*log(z) - log(w)) == log(z**b/w) assert logcombine(log(x)*log(z)) == log(x)*log(z) assert logcombine(log(w)*log(x)) == log(w)*log(x) assert logcombine(cos(-2*log(z) + b*log(w))) in [cos(log(w**b/z**2)), cos(log(z**2/w**b))] assert logcombine(log(log(x) - log(y)) - log(z), force=True) == \ log(log(x/y)/z) assert logcombine((2 + I)*log(x), force=True) == (2 + I)*log(x) assert logcombine((x**2 + log(x) - log(y))/(x*y), force=True) == \ (x**2 + log(x/y))/(x*y) # the following could also give log(z*x**log(y**2)), what we # are testing is that a canonical result is obtained assert logcombine(log(x)*2*log(y) + log(z), force=True) == \ log(z*y**log(x**2)) assert logcombine((x*y + sqrt(x**4 + y**4) + log(x) - log(y))/(pi*x**Rational(2, 3)* sqrt(y)**3), force=True) == ( x*y + sqrt(x**4 + y**4) + log(x/y))/(pi*x**Rational(2, 3)*y**Rational(3, 2)) assert logcombine(gamma(-log(x/y))*acos(-log(x/y)), force=True) == \ acos(-log(x/y))*gamma(-log(x/y)) assert logcombine(2*log(z)*log(w)*log(x) + log(z) + log(w)) == \ log(z**log(w**2))*log(x) + log(w*z) assert logcombine(3*log(w) + 3*log(z)) == log(w**3*z**3) assert logcombine(x*(y + 1) + log(2) + log(3)) == x*(y + 1) + log(6) assert logcombine((x + y)*log(w) + (-x - y)*log(3)) == (x + y)*log(w/3) # a single unknown can combine assert logcombine(log(x) + log(2)) == log(2*x) eq = log(abs(x)) + log(abs(y)) assert logcombine(eq) == eq reps = {x: 0, y: 0} assert log(abs(x)*abs(y)).subs(reps) != eq.subs(reps) def test_logcombine_complex_coeff(): i = Integral((sin(x**2) + cos(x**3))/x, x) assert logcombine(i, force=True) == i assert logcombine(i + 2*log(x), force=True) == \ i + log(x**2) def test_issue_5950(): x, y = symbols("x,y", positive=True) assert logcombine(log(3) - log(2)) == log(Rational(3,2), evaluate=False) assert logcombine(log(x) - log(y)) == log(x/y) assert logcombine(log(Rational(3,2), evaluate=False) - log(2)) == \ log(Rational(3,4), evaluate=False) def test_posify(): x = symbols('x') assert str(posify( x + Symbol('p', positive=True) + Symbol('n', negative=True))) == '(_x + n + p, {_x: x})' eq, rep = posify(1/x) assert log(eq).expand().subs(rep) == -log(x) assert str(posify([x, 1 + x])) == '([_x, _x + 1], {_x: x})' p = symbols('p', positive=True) n = symbols('n', negative=True) orig = [x, n, p] modified, reps = posify(orig) assert str(modified) == '[_x, n, p]' assert [w.subs(reps) for w in modified] == orig assert str(Integral(posify(1/x + y)[0], (y, 1, 3)).expand()) == \ 'Integral(1/_x, (y, 1, 3)) + Integral(_y, (y, 1, 3))' assert str(Sum(posify(1/x**n)[0], (n,1,3)).expand()) == \ 'Sum(_x**(-n), (n, 1, 3))' # issue 16438 k = Symbol('k', finite=True) eq, rep = posify(k) assert eq.assumptions0 == {'positive': True, 'zero': False, 'imaginary': False, 'nonpositive': False, 'commutative': True, 'hermitian': True, 'real': True, 'nonzero': True, 'nonnegative': True, 'negative': False, 'complex': True, 'finite': True, 'infinite': False, 'extended_real':True, 'extended_negative': False, 'extended_nonnegative': True, 'extended_nonpositive': False, 'extended_nonzero': True, 'extended_positive': True} def test_issue_4194(): # simplify should call cancel f = Function('f') assert simplify((4*x + 6*f(y))/(2*x + 3*f(y))) == 2 @XFAIL def test_simplify_float_vs_integer(): # Test for issue 4473: # https://github.com/sympy/sympy/issues/4473 assert simplify(x**2.0 - x**2) == 0 assert simplify(x**2 - x**2.0) == 0 def test_as_content_primitive(): assert (x/2 + y).as_content_primitive() == (S.Half, x + 2*y) assert (x/2 + y).as_content_primitive(clear=False) == (S.One, x/2 + y) assert (y*(x/2 + y)).as_content_primitive() == (S.Half, y*(x + 2*y)) assert (y*(x/2 + y)).as_content_primitive(clear=False) == (S.One, y*(x/2 + y)) # although the _as_content_primitive methods do not alter the underlying structure, # the as_content_primitive function will touch up the expression and join # bases that would otherwise have not been joined. assert (x*(2 + 2*x)*(3*x + 3)**2).as_content_primitive() == \ (18, x*(x + 1)**3) assert (2 + 2*x + 2*y*(3 + 3*y)).as_content_primitive() == \ (2, x + 3*y*(y + 1) + 1) assert ((2 + 6*x)**2).as_content_primitive() == \ (4, (3*x + 1)**2) assert ((2 + 6*x)**(2*y)).as_content_primitive() == \ (1, (_keep_coeff(S(2), (3*x + 1)))**(2*y)) assert (5 + 10*x + 2*y*(3 + 3*y)).as_content_primitive() == \ (1, 10*x + 6*y*(y + 1) + 5) assert (5*(x*(1 + y)) + 2*x*(3 + 3*y)).as_content_primitive() == \ (11, x*(y + 1)) assert ((5*(x*(1 + y)) + 2*x*(3 + 3*y))**2).as_content_primitive() == \ (121, x**2*(y + 1)**2) assert (y**2).as_content_primitive() == \ (1, y**2) assert (S.Infinity).as_content_primitive() == (1, oo) eq = x**(2 + y) assert (eq).as_content_primitive() == (1, eq) assert (S.Half**(2 + x)).as_content_primitive() == (Rational(1, 4), 2**-x) assert (Rational(-1, 2)**(2 + x)).as_content_primitive() == \ (Rational(1, 4), (Rational(-1, 2))**x) assert (Rational(-1, 2)**(2 + x)).as_content_primitive() == \ (Rational(1, 4), Rational(-1, 2)**x) assert (4**((1 + y)/2)).as_content_primitive() == (2, 4**(y/2)) assert (3**((1 + y)/2)).as_content_primitive() == \ (1, 3**(Mul(S.Half, 1 + y, evaluate=False))) assert (5**Rational(3, 4)).as_content_primitive() == (1, 5**Rational(3, 4)) assert (5**Rational(7, 4)).as_content_primitive() == (5, 5**Rational(3, 4)) assert Add(z*Rational(5, 7), 0.5*x, y*Rational(3, 2), evaluate=False).as_content_primitive() == \ (Rational(1, 14), 7.0*x + 21*y + 10*z) assert (2**Rational(3, 4) + 2**Rational(1, 4)*sqrt(3)).as_content_primitive(radical=True) == \ (1, 2**Rational(1, 4)*(sqrt(2) + sqrt(3))) def test_signsimp(): e = x*(-x + 1) + x*(x - 1) assert signsimp(Eq(e, 0)) is S.true assert Abs(x - 1) == Abs(1 - x) assert signsimp(y - x) == y - x assert signsimp(y - x, evaluate=False) == Mul(-1, x - y, evaluate=False) def test_besselsimp(): from sympy.functions.special.bessel import (besseli, besselj, bessely) from sympy.integrals.transforms import cosine_transform assert besselsimp(exp(-I*pi*y/2)*besseli(y, z*exp_polar(I*pi/2))) == \ besselj(y, z) assert besselsimp(exp(-I*pi*a/2)*besseli(a, 2*sqrt(x)*exp_polar(I*pi/2))) == \ besselj(a, 2*sqrt(x)) assert besselsimp(sqrt(2)*sqrt(pi)*x**Rational(1, 4)*exp(I*pi/4)*exp(-I*pi*a/2) * besseli(Rational(-1, 2), sqrt(x)*exp_polar(I*pi/2)) * besseli(a, sqrt(x)*exp_polar(I*pi/2))/2) == \ besselj(a, sqrt(x)) * cos(sqrt(x)) assert besselsimp(besseli(Rational(-1, 2), z)) == \ sqrt(2)*cosh(z)/(sqrt(pi)*sqrt(z)) assert besselsimp(besseli(a, z*exp_polar(-I*pi/2))) == \ exp(-I*pi*a/2)*besselj(a, z) assert cosine_transform(1/t*sin(a/t), t, y) == \ sqrt(2)*sqrt(pi)*besselj(0, 2*sqrt(a)*sqrt(y))/2 assert besselsimp(x**2*(a*(-2*besselj(5*I, x) + besselj(-2 + 5*I, x) + besselj(2 + 5*I, x)) + b*(-2*bessely(5*I, x) + bessely(-2 + 5*I, x) + bessely(2 + 5*I, x)))/4 + x*(a*(besselj(-1 + 5*I, x)/2 - besselj(1 + 5*I, x)/2) + b*(bessely(-1 + 5*I, x)/2 - bessely(1 + 5*I, x)/2)) + (x**2 + 25)*(a*besselj(5*I, x) + b*bessely(5*I, x))) == 0 assert besselsimp(81*x**2*(a*(besselj(Rational(-5, 3), 9*x) - 2*besselj(Rational(1, 3), 9*x) + besselj(Rational(7, 3), 9*x)) + b*(bessely(Rational(-5, 3), 9*x) - 2*bessely(Rational(1, 3), 9*x) + bessely(Rational(7, 3), 9*x)))/4 + x*(a*(9*besselj(Rational(-2, 3), 9*x)/2 - 9*besselj(Rational(4, 3), 9*x)/2) + b*(9*bessely(Rational(-2, 3), 9*x)/2 - 9*bessely(Rational(4, 3), 9*x)/2)) + (81*x**2 - Rational(1, 9))*(a*besselj(Rational(1, 3), 9*x) + b*bessely(Rational(1, 3), 9*x))) == 0 assert besselsimp(besselj(a-1,x) + besselj(a+1, x) - 2*a*besselj(a, x)/x) == 0 assert besselsimp(besselj(a-1,x) + besselj(a+1, x) + besselj(a, x)) == (2*a + x)*besselj(a, x)/x assert besselsimp(x**2* besselj(a,x) + x**3*besselj(a+1, x) + besselj(a+2, x)) == \ 2*a*x*besselj(a + 1, x) + x**3*besselj(a + 1, x) - x**2*besselj(a + 2, x) + 2*x*besselj(a + 1, x) + besselj(a + 2, x) def test_Piecewise(): e1 = x*(x + y) - y*(x + y) e2 = sin(x)**2 + cos(x)**2 e3 = expand((x + y)*y/x) s1 = simplify(e1) s2 = simplify(e2) s3 = simplify(e3) assert simplify(Piecewise((e1, x < e2), (e3, True))) == \ Piecewise((s1, x < s2), (s3, True)) def test_polymorphism(): class A(Basic): def _eval_simplify(x, **kwargs): return S.One a = A(S(5), S(2)) assert simplify(a) == 1 def test_issue_from_PR1599(): n1, n2, n3, n4 = symbols('n1 n2 n3 n4', negative=True) assert simplify(I*sqrt(n1)) == -sqrt(-n1) def test_issue_6811(): eq = (x + 2*y)*(2*x + 2) assert simplify(eq) == (x + 1)*(x + 2*y)*2 # reject the 2-arg Mul -- these are a headache for test writing assert simplify(eq.expand()) == \ 2*x**2 + 4*x*y + 2*x + 4*y def test_issue_6920(): e = [cos(x) + I*sin(x), cos(x) - I*sin(x), cosh(x) - sinh(x), cosh(x) + sinh(x)] ok = [exp(I*x), exp(-I*x), exp(-x), exp(x)] # wrap in f to show that the change happens wherever ei occurs f = Function('f') assert [simplify(f(ei)).args[0] for ei in e] == ok def test_issue_7001(): from sympy.abc import r, R assert simplify(-(r*Piecewise((pi*Rational(4, 3), r <= R), (-8*pi*R**3/(3*r**3), True)) + 2*Piecewise((pi*r*Rational(4, 3), r <= R), (4*pi*R**3/(3*r**2), True)))/(4*pi*r)) == \ Piecewise((-1, r <= R), (0, True)) def test_inequality_no_auto_simplify(): # no simplify on creation but can be simplified lhs = cos(x)**2 + sin(x)**2 rhs = 2 e = Lt(lhs, rhs, evaluate=False) assert e is not S.true assert simplify(e) def test_issue_9398(): from sympy.core.numbers import Number from sympy.polys.polytools import cancel assert cancel(1e-14) != 0 assert cancel(1e-14*I) != 0 assert simplify(1e-14) != 0 assert simplify(1e-14*I) != 0 assert (I*Number(1.)*Number(10)**Number(-14)).simplify() != 0 assert cancel(1e-20) != 0 assert cancel(1e-20*I) != 0 assert simplify(1e-20) != 0 assert simplify(1e-20*I) != 0 assert cancel(1e-100) != 0 assert cancel(1e-100*I) != 0 assert simplify(1e-100) != 0 assert simplify(1e-100*I) != 0 f = Float("1e-1000") assert cancel(f) != 0 assert cancel(f*I) != 0 assert simplify(f) != 0 assert simplify(f*I) != 0 def test_issue_9324_simplify(): M = MatrixSymbol('M', 10, 10) e = M[0, 0] + M[5, 4] + 1304 assert simplify(e) == e def test_issue_9817_simplify(): # simplify on trace of substituted explicit quadratic form of matrix # expressions (a scalar) should return without errors (AttributeError) # See issue #9817 and #9190 for the original bug more discussion on this from sympy.matrices.expressions import Identity, trace v = MatrixSymbol('v', 3, 1) A = MatrixSymbol('A', 3, 3) x = Matrix([i + 1 for i in range(3)]) X = Identity(3) quadratic = v.T * A * v assert simplify((trace(quadratic.as_explicit())).xreplace({v:x, A:X})) == 14 def test_issue_13474(): x = Symbol('x') assert simplify(x + csch(sinc(1))) == x + csch(sinc(1)) @_both_exp_pow def test_simplify_function_inverse(): # "inverse" attribute does not guarantee that f(g(x)) is x # so this simplification should not happen automatically. # See issue #12140 x, y = symbols('x, y') g = Function('g') class f(Function): def inverse(self, argindex=1): return g assert simplify(f(g(x))) == f(g(x)) assert inversecombine(f(g(x))) == x assert simplify(f(g(x)), inverse=True) == x assert simplify(f(g(sin(x)**2 + cos(x)**2)), inverse=True) == 1 assert simplify(f(g(x, y)), inverse=True) == f(g(x, y)) assert unchanged(asin, sin(x)) assert simplify(asin(sin(x))) == asin(sin(x)) assert simplify(2*asin(sin(3*x)), inverse=True) == 6*x assert simplify(log(exp(x))) == log(exp(x)) assert simplify(log(exp(x)), inverse=True) == x assert simplify(exp(log(x)), inverse=True) == x assert simplify(log(exp(x), 2), inverse=True) == x/log(2) assert simplify(log(exp(x), 2, evaluate=False), inverse=True) == x/log(2) def test_clear_coefficients(): from sympy.simplify.simplify import clear_coefficients assert clear_coefficients(4*y*(6*x + 3)) == (y*(2*x + 1), 0) assert clear_coefficients(4*y*(6*x + 3) - 2) == (y*(2*x + 1), Rational(1, 6)) assert clear_coefficients(4*y*(6*x + 3) - 2, x) == (y*(2*x + 1), x/12 + Rational(1, 6)) assert clear_coefficients(sqrt(2) - 2) == (sqrt(2), 2) assert clear_coefficients(4*sqrt(2) - 2) == (sqrt(2), S.Half) assert clear_coefficients(S(3), x) == (0, x - 3) assert clear_coefficients(S.Infinity, x) == (S.Infinity, x) assert clear_coefficients(-S.Pi, x) == (S.Pi, -x) assert clear_coefficients(2 - S.Pi/3, x) == (pi, -3*x + 6) def test_nc_simplify(): from sympy.simplify.simplify import nc_simplify from sympy.matrices.expressions import MatPow, Identity from sympy.core import Pow from functools import reduce a, b, c, d = symbols('a b c d', commutative = False) x = Symbol('x') A = MatrixSymbol("A", x, x) B = MatrixSymbol("B", x, x) C = MatrixSymbol("C", x, x) D = MatrixSymbol("D", x, x) subst = {a: A, b: B, c: C, d:D} funcs = {Add: lambda x,y: x+y, Mul: lambda x,y: x*y } def _to_matrix(expr): if expr in subst: return subst[expr] if isinstance(expr, Pow): return MatPow(_to_matrix(expr.args[0]), expr.args[1]) elif isinstance(expr, (Add, Mul)): return reduce(funcs[expr.func],[_to_matrix(a) for a in expr.args]) else: return expr*Identity(x) def _check(expr, simplified, deep=True, matrix=True): assert nc_simplify(expr, deep=deep) == simplified assert expand(expr) == expand(simplified) if matrix: m_simp = _to_matrix(simplified).doit(inv_expand=False) assert nc_simplify(_to_matrix(expr), deep=deep) == m_simp _check(a*b*a*b*a*b*c*(a*b)**3*c, ((a*b)**3*c)**2) _check(a*b*(a*b)**-2*a*b, 1) _check(a**2*b*a*b*a*b*(a*b)**-1, a*(a*b)**2, matrix=False) _check(b*a*b**2*a*b**2*a*b**2, b*(a*b**2)**3) _check(a*b*a**2*b*a**2*b*a**3, (a*b*a)**3*a**2) _check(a**2*b*a**4*b*a**4*b*a**2, (a**2*b*a**2)**3) _check(a**3*b*a**4*b*a**4*b*a, a**3*(b*a**4)**3*a**-3) _check(a*b*a*b + a*b*c*x*a*b*c, (a*b)**2 + x*(a*b*c)**2) _check(a*b*a*b*c*a*b*a*b*c, ((a*b)**2*c)**2) _check(b**-1*a**-1*(a*b)**2, a*b) _check(a**-1*b*c**-1, (c*b**-1*a)**-1) expr = a**3*b*a**4*b*a**4*b*a**2*b*a**2*(b*a**2)**2*b*a**2*b*a**2 for _ in range(10): expr *= a*b _check(expr, a**3*(b*a**4)**2*(b*a**2)**6*(a*b)**10) _check((a*b*a*b)**2, (a*b*a*b)**2, deep=False) _check(a*b*(c*d)**2, a*b*(c*d)**2) expr = b**-1*(a**-1*b**-1 - a**-1*c*b**-1)**-1*a**-1 assert nc_simplify(expr) == (1-c)**-1 # commutative expressions should be returned without an error assert nc_simplify(2*x**2) == 2*x**2 def test_issue_15965(): A = Sum(z*x**y, (x, 1, a)) anew = z*Sum(x**y, (x, 1, a)) B = Integral(x*y, x) bdo = x**2*y/2 assert simplify(A + B) == anew + bdo assert simplify(A) == anew assert simplify(B) == bdo assert simplify(B, doit=False) == y*Integral(x, x) def test_issue_17137(): assert simplify(cos(x)**I) == cos(x)**I assert simplify(cos(x)**(2 + 3*I)) == cos(x)**(2 + 3*I) def test_issue_21869(): x = Symbol('x', real=True) y = Symbol('y', real=True) expr = And(Eq(x**2, 4), Le(x, y)) assert expr.simplify() == expr expr = And(Eq(x**2, 4), Eq(x, 2)) assert expr.simplify() == Eq(x, 2) expr = And(Eq(x**3, x**2), Eq(x, 1)) assert expr.simplify() == Eq(x, 1) expr = And(Eq(sin(x), x**2), Eq(x, 0)) assert expr.simplify() == Eq(x, 0) expr = And(Eq(x**3, x**2), Eq(x, 2)) assert expr.simplify() == S.false expr = And(Eq(y, x**2), Eq(x, 1)) assert expr.simplify() == And(Eq(y,1), Eq(x, 1)) expr = And(Eq(y**2, 1), Eq(y, x**2), Eq(x, 1)) assert expr.simplify() == And(Eq(y,1), Eq(x, 1)) expr = And(Eq(y**2, 4), Eq(y, 2*x**2), Eq(x, 1)) assert expr.simplify() == And(Eq(y,2), Eq(x, 1)) expr = And(Eq(y**2, 4), Eq(y, x**2), Eq(x, 1)) assert expr.simplify() == S.false def test_issue_7971_21740(): z = Integral(x, (x, 1, 1)) assert z != 0 assert simplify(z) is S.Zero assert simplify(S.Zero) is S.Zero z = simplify(Float(0)) assert z is not S.Zero and z == 0 @slow def test_issue_17141_slow(): # Should not give RecursionError assert simplify((2**acos(I+1)**2).rewrite('log')) == 2**((pi + 2*I*log(-1 + sqrt(1 - 2*I) + I))**2/4) def test_issue_17141(): # Check that there is no RecursionError assert simplify(x**(1 / acos(I))) == x**(2/(pi - 2*I*log(1 + sqrt(2)))) assert simplify(acos(-I)**2*acos(I)**2) == \ log(1 + sqrt(2))**4 + pi**2*log(1 + sqrt(2))**2/2 + pi**4/16 assert simplify(2**acos(I)**2) == 2**((pi - 2*I*log(1 + sqrt(2)))**2/4) p = 2**acos(I+1)**2 assert simplify(p) == p def test_simplify_kroneckerdelta(): i, j = symbols("i j") K = KroneckerDelta assert simplify(K(i, j)) == K(i, j) assert simplify(K(0, j)) == K(0, j) assert simplify(K(i, 0)) == K(i, 0) assert simplify(K(0, j).rewrite(Piecewise) * K(1, j)) == 0 assert simplify(K(1, i) + Piecewise((1, Eq(j, 2)), (0, True))) == K(1, i) + K(2, j) # issue 17214 assert simplify(K(0, j) * K(1, j)) == 0 n = Symbol('n', integer=True) assert simplify(K(0, n) * K(1, n)) == 0 M = Matrix(4, 4, lambda i, j: K(j - i, n) if i <= j else 0) assert simplify(M**2) == Matrix([[K(0, n), 0, K(1, n), 0], [0, K(0, n), 0, K(1, n)], [0, 0, K(0, n), 0], [0, 0, 0, K(0, n)]]) assert simplify(eye(1) * KroneckerDelta(0, n) * KroneckerDelta(1, n)) == Matrix([[0]]) assert simplify(S.Infinity * KroneckerDelta(0, n) * KroneckerDelta(1, n)) is S.NaN def test_issue_17292(): assert simplify(abs(x)/abs(x**2)) == 1/abs(x) # this is bigger than the issue: check that deep processing works assert simplify(5*abs((x**2 - 1)/(x - 1))) == 5*Abs(x + 1) def test_issue_19822(): expr = And(Gt(n-2, 1), Gt(n, 1)) assert simplify(expr) == Gt(n, 3) def test_issue_18645(): expr = And(Ge(x, 3), Le(x, 3)) assert simplify(expr) == Eq(x, 3) expr = And(Eq(x, 3), Le(x, 3)) assert simplify(expr) == Eq(x, 3) @XFAIL def test_issue_18642(): i = Symbol("i", integer=True) n = Symbol("n", integer=True) expr = And(Eq(i, 2 * n), Le(i, 2*n -1)) assert simplify(expr) == S.false @XFAIL def test_issue_18389(): n = Symbol("n", integer=True) expr = Eq(n, 0) | (n >= 1) assert simplify(expr) == Ge(n, 0) def test_issue_8373(): x = Symbol('x', real=True) assert simplify(Or(x < 1, x >= 1)) == S.true def test_issue_7950(): expr = And(Eq(x, 1), Eq(x, 2)) assert simplify(expr) == S.false def test_issue_22020(): expr = I*pi/2 -oo assert simplify(expr) == expr # Used to throw an error def test_issue_19484(): assert simplify(sign(x) * Abs(x)) == x e = x + sign(x + x**3) assert simplify(Abs(x + x**3)*e) == x**3 + x*Abs(x**3 + x) + x e = x**2 + sign(x**3 + 1) assert simplify(Abs(x**3 + 1) * e) == x**3 + x**2*Abs(x**3 + 1) + 1 f = Function('f') e = x + sign(x + f(x)**3) assert simplify(Abs(x + f(x)**3) * e) == x*Abs(x + f(x)**3) + x + f(x)**3 def test_issue_19161(): polynomial = Poly('x**2').simplify() assert (polynomial-x**2).simplify() == 0 def test_issue_22210(): d = Symbol('d', integer=True) expr = 2*Derivative(sin(x), (x, d)) assert expr.simplify() == expr
560027089ef6b5fb760281fa67301364ac0b23490309b8fe692dcd59d109fb7f
from functools import reduce import itertools from operator import add from sympy.core.add import Add from sympy.core.containers import Tuple from sympy.core.function import Function from sympy.core.mul import Mul from sympy.core.power import Pow from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.core.sympify import sympify from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.matrices.dense import Matrix from sympy.polys.rootoftools import CRootOf from sympy.series.order import O from sympy.simplify.cse_main import cse from sympy.simplify.simplify import signsimp from sympy.tensor.indexed import (Idx, IndexedBase) from sympy.core.function import count_ops from sympy.simplify.cse_opts import sub_pre, sub_post from sympy.functions.special.hyper import meijerg from sympy.simplify import cse_main, cse_opts from sympy.utilities.iterables import subsets from sympy.testing.pytest import XFAIL, raises from sympy.matrices import (MutableDenseMatrix, MutableSparseMatrix, ImmutableDenseMatrix, ImmutableSparseMatrix) from sympy.matrices.expressions import MatrixSymbol w, x, y, z = symbols('w,x,y,z') x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12 = symbols('x:13') def test_numbered_symbols(): ns = cse_main.numbered_symbols(prefix='y') assert list(itertools.islice( ns, 0, 10)) == [Symbol('y%s' % i) for i in range(0, 10)] ns = cse_main.numbered_symbols(prefix='y') assert list(itertools.islice( ns, 10, 20)) == [Symbol('y%s' % i) for i in range(10, 20)] ns = cse_main.numbered_symbols() assert list(itertools.islice( ns, 0, 10)) == [Symbol('x%s' % i) for i in range(0, 10)] # Dummy "optimization" functions for testing. def opt1(expr): return expr + y def opt2(expr): return expr*z def test_preprocess_for_cse(): assert cse_main.preprocess_for_cse(x, [(opt1, None)]) == x + y assert cse_main.preprocess_for_cse(x, [(None, opt1)]) == x assert cse_main.preprocess_for_cse(x, [(None, None)]) == x assert cse_main.preprocess_for_cse(x, [(opt1, opt2)]) == x + y assert cse_main.preprocess_for_cse( x, [(opt1, None), (opt2, None)]) == (x + y)*z def test_postprocess_for_cse(): assert cse_main.postprocess_for_cse(x, [(opt1, None)]) == x assert cse_main.postprocess_for_cse(x, [(None, opt1)]) == x + y assert cse_main.postprocess_for_cse(x, [(None, None)]) == x assert cse_main.postprocess_for_cse(x, [(opt1, opt2)]) == x*z # Note the reverse order of application. assert cse_main.postprocess_for_cse( x, [(None, opt1), (None, opt2)]) == x*z + y def test_cse_single(): # Simple substitution. e = Add(Pow(x + y, 2), sqrt(x + y)) substs, reduced = cse([e]) assert substs == [(x0, x + y)] assert reduced == [sqrt(x0) + x0**2] subst42, (red42,) = cse([42]) # issue_15082 assert len(subst42) == 0 and red42 == 42 subst_half, (red_half,) = cse([0.5]) assert len(subst_half) == 0 and red_half == 0.5 def test_cse_single2(): # Simple substitution, test for being able to pass the expression directly e = Add(Pow(x + y, 2), sqrt(x + y)) substs, reduced = cse(e) assert substs == [(x0, x + y)] assert reduced == [sqrt(x0) + x0**2] substs, reduced = cse(Matrix([[1]])) assert isinstance(reduced[0], Matrix) subst42, (red42,) = cse(42) # issue 15082 assert len(subst42) == 0 and red42 == 42 subst_half, (red_half,) = cse(0.5) # issue 15082 assert len(subst_half) == 0 and red_half == 0.5 def test_cse_not_possible(): # No substitution possible. e = Add(x, y) substs, reduced = cse([e]) assert substs == [] assert reduced == [x + y] # issue 6329 eq = (meijerg((1, 2), (y, 4), (5,), [], x) + meijerg((1, 3), (y, 4), (5,), [], x)) assert cse(eq) == ([], [eq]) def test_nested_substitution(): # Substitution within a substitution. e = Add(Pow(w*x + y, 2), sqrt(w*x + y)) substs, reduced = cse([e]) assert substs == [(x0, w*x + y)] assert reduced == [sqrt(x0) + x0**2] def test_subtraction_opt(): # Make sure subtraction is optimized. e = (x - y)*(z - y) + exp((x - y)*(z - y)) substs, reduced = cse( [e], optimizations=[(cse_opts.sub_pre, cse_opts.sub_post)]) assert substs == [(x0, (x - y)*(y - z))] assert reduced == [-x0 + exp(-x0)] e = -(x - y)*(z - y) + exp(-(x - y)*(z - y)) substs, reduced = cse( [e], optimizations=[(cse_opts.sub_pre, cse_opts.sub_post)]) assert substs == [(x0, (x - y)*(y - z))] assert reduced == [x0 + exp(x0)] # issue 4077 n = -1 + 1/x e = n/x/(-n)**2 - 1/n/x assert cse(e, optimizations=[(cse_opts.sub_pre, cse_opts.sub_post)]) == \ ([], [0]) assert cse(((w + x + y + z)*(w - y - z))/(w + x)**3) == \ ([(x0, w + x), (x1, y + z)], [(w - x1)*(x0 + x1)/x0**3]) def test_multiple_expressions(): e1 = (x + y)*z e2 = (x + y)*w substs, reduced = cse([e1, e2]) assert substs == [(x0, x + y)] assert reduced == [x0*z, x0*w] l = [w*x*y + z, w*y] substs, reduced = cse(l) rsubsts, _ = cse(reversed(l)) assert substs == rsubsts assert reduced == [z + x*x0, x0] l = [w*x*y, w*x*y + z, w*y] substs, reduced = cse(l) rsubsts, _ = cse(reversed(l)) assert substs == rsubsts assert reduced == [x1, x1 + z, x0] l = [(x - z)*(y - z), x - z, y - z] substs, reduced = cse(l) rsubsts, _ = cse(reversed(l)) assert substs == [(x0, -z), (x1, x + x0), (x2, x0 + y)] assert rsubsts == [(x0, -z), (x1, x0 + y), (x2, x + x0)] assert reduced == [x1*x2, x1, x2] l = [w*y + w + x + y + z, w*x*y] assert cse(l) == ([(x0, w*y)], [w + x + x0 + y + z, x*x0]) assert cse([x + y, x + y + z]) == ([(x0, x + y)], [x0, z + x0]) assert cse([x + y, x + z]) == ([], [x + y, x + z]) assert cse([x*y, z + x*y, x*y*z + 3]) == \ ([(x0, x*y)], [x0, z + x0, 3 + x0*z]) @XFAIL # CSE of non-commutative Mul terms is disabled def test_non_commutative_cse(): A, B, C = symbols('A B C', commutative=False) l = [A*B*C, A*C] assert cse(l) == ([], l) l = [A*B*C, A*B] assert cse(l) == ([(x0, A*B)], [x0*C, x0]) # Test if CSE of non-commutative Mul terms is disabled def test_bypass_non_commutatives(): A, B, C = symbols('A B C', commutative=False) l = [A*B*C, A*C] assert cse(l) == ([], l) l = [A*B*C, A*B] assert cse(l) == ([], l) l = [B*C, A*B*C] assert cse(l) == ([], l) @XFAIL # CSE fails when replacing non-commutative sub-expressions def test_non_commutative_order(): A, B, C = symbols('A B C', commutative=False) x0 = symbols('x0', commutative=False) l = [B+C, A*(B+C)] assert cse(l) == ([(x0, B+C)], [x0, A*x0]) @XFAIL # Worked in gh-11232, but was reverted due to performance considerations def test_issue_10228(): assert cse([x*y**2 + x*y]) == ([(x0, x*y)], [x0*y + x0]) assert cse([x + y, 2*x + y]) == ([(x0, x + y)], [x0, x + x0]) assert cse((w + 2*x + y + z, w + x + 1)) == ( [(x0, w + x)], [x0 + x + y + z, x0 + 1]) assert cse(((w + x + y + z)*(w - x))/(w + x)) == ( [(x0, w + x)], [(x0 + y + z)*(w - x)/x0]) a, b, c, d, f, g, j, m = symbols('a, b, c, d, f, g, j, m') exprs = (d*g**2*j*m, 4*a*f*g*m, a*b*c*f**2) assert cse(exprs) == ( [(x0, g*m), (x1, a*f)], [d*g*j*x0, 4*x0*x1, b*c*f*x1] ) @XFAIL def test_powers(): assert cse(x*y**2 + x*y) == ([(x0, x*y)], [x0*y + x0]) def test_issue_4498(): assert cse(w/(x - y) + z/(y - x), optimizations='basic') == \ ([], [(w - z)/(x - y)]) def test_issue_4020(): assert cse(x**5 + x**4 + x**3 + x**2, optimizations='basic') \ == ([(x0, x**2)], [x0*(x**3 + x + x0 + 1)]) def test_issue_4203(): assert cse(sin(x**x)/x**x) == ([(x0, x**x)], [sin(x0)/x0]) def test_issue_6263(): e = Eq(x*(-x + 1) + x*(x - 1), 0) assert cse(e, optimizations='basic') == ([], [True]) def test_dont_cse_tuples(): from sympy.core.function import Subs f = Function("f") g = Function("g") name_val, (expr,) = cse( Subs(f(x, y), (x, y), (0, 1)) + Subs(g(x, y), (x, y), (0, 1))) assert name_val == [] assert expr == (Subs(f(x, y), (x, y), (0, 1)) + Subs(g(x, y), (x, y), (0, 1))) name_val, (expr,) = cse( Subs(f(x, y), (x, y), (0, x + y)) + Subs(g(x, y), (x, y), (0, x + y))) assert name_val == [(x0, x + y)] assert expr == Subs(f(x, y), (x, y), (0, x0)) + \ Subs(g(x, y), (x, y), (0, x0)) def test_pow_invpow(): assert cse(1/x**2 + x**2) == \ ([(x0, x**2)], [x0 + 1/x0]) assert cse(x**2 + (1 + 1/x**2)/x**2) == \ ([(x0, x**2), (x1, 1/x0)], [x0 + x1*(x1 + 1)]) assert cse(1/x**2 + (1 + 1/x**2)*x**2) == \ ([(x0, x**2), (x1, 1/x0)], [x0*(x1 + 1) + x1]) assert cse(cos(1/x**2) + sin(1/x**2)) == \ ([(x0, x**(-2))], [sin(x0) + cos(x0)]) assert cse(cos(x**2) + sin(x**2)) == \ ([(x0, x**2)], [sin(x0) + cos(x0)]) assert cse(y/(2 + x**2) + z/x**2/y) == \ ([(x0, x**2)], [y/(x0 + 2) + z/(x0*y)]) assert cse(exp(x**2) + x**2*cos(1/x**2)) == \ ([(x0, x**2)], [x0*cos(1/x0) + exp(x0)]) assert cse((1 + 1/x**2)/x**2) == \ ([(x0, x**(-2))], [x0*(x0 + 1)]) assert cse(x**(2*y) + x**(-2*y)) == \ ([(x0, x**(2*y))], [x0 + 1/x0]) def test_postprocess(): eq = (x + 1 + exp((x + 1)/(y + 1)) + cos(y + 1)) assert cse([eq, Eq(x, z + 1), z - 2, (z + 1)*(x + 1)], postprocess=cse_main.cse_separate) == \ [[(x0, y + 1), (x2, z + 1), (x, x2), (x1, x + 1)], [x1 + exp(x1/x0) + cos(x0), z - 2, x1*x2]] def test_issue_4499(): # previously, this gave 16 constants from sympy.abc import a, b B = Function('B') G = Function('G') t = Tuple(* (a, a + S.Half, 2*a, b, 2*a - b + 1, (sqrt(z)/2)**(-2*a + 1)*B(2*a - b, sqrt(z))*B(b - 1, sqrt(z))*G(b)*G(2*a - b + 1), sqrt(z)*(sqrt(z)/2)**(-2*a + 1)*B(b, sqrt(z))*B(2*a - b, sqrt(z))*G(b)*G(2*a - b + 1), sqrt(z)*(sqrt(z)/2)**(-2*a + 1)*B(b - 1, sqrt(z))*B(2*a - b + 1, sqrt(z))*G(b)*G(2*a - b + 1), (sqrt(z)/2)**(-2*a + 1)*B(b, sqrt(z))*B(2*a - b + 1, sqrt(z))*G(b)*G(2*a - b + 1), 1, 0, S.Half, z/2, -b + 1, -2*a + b, -2*a)) c = cse(t) ans = ( [(x0, 2*a), (x1, -b + x0), (x2, x1 + 1), (x3, b - 1), (x4, sqrt(z)), (x5, B(x3, x4)), (x6, (x4/2)**(1 - x0)*G(b)*G(x2)), (x7, x6*B(x1, x4)), (x8, B(b, x4)), (x9, x6*B(x2, x4))], [(a, a + S.Half, x0, b, x2, x5*x7, x4*x7*x8, x4*x5*x9, x8*x9, 1, 0, S.Half, z/2, -x3, -x1, -x0)]) assert ans == c def test_issue_6169(): r = CRootOf(x**6 - 4*x**5 - 2, 1) assert cse(r) == ([], [r]) # and a check that the right thing is done with the new # mechanism assert sub_post(sub_pre((-x - y)*z - x - y)) == -z*(x + y) - x - y def test_cse_Indexed(): len_y = 5 y = IndexedBase('y', shape=(len_y,)) x = IndexedBase('x', shape=(len_y,)) i = Idx('i', len_y-1) expr1 = (y[i+1]-y[i])/(x[i+1]-x[i]) expr2 = 1/(x[i+1]-x[i]) replacements, reduced_exprs = cse([expr1, expr2]) assert len(replacements) > 0 def test_cse_MatrixSymbol(): # MatrixSymbols have non-Basic args, so make sure that works A = MatrixSymbol("A", 3, 3) assert cse(A) == ([], [A]) n = symbols('n', integer=True) B = MatrixSymbol("B", n, n) assert cse(B) == ([], [B]) def test_cse_MatrixExpr(): A = MatrixSymbol('A', 3, 3) y = MatrixSymbol('y', 3, 1) expr1 = (A.T*A).I * A * y expr2 = (A.T*A) * A * y replacements, reduced_exprs = cse([expr1, expr2]) assert len(replacements) > 0 replacements, reduced_exprs = cse([expr1 + expr2, expr1]) assert replacements replacements, reduced_exprs = cse([A**2, A + A**2]) assert replacements def test_Piecewise(): f = Piecewise((-z + x*y, Eq(y, 0)), (-z - x*y, True)) ans = cse(f) actual_ans = ([(x0, x*y)], [Piecewise((x0 - z, Eq(y, 0)), (-z - x0, True))]) assert ans == actual_ans def test_ignore_order_terms(): eq = exp(x).series(x,0,3) + sin(y+x**3) - 1 assert cse(eq) == ([], [sin(x**3 + y) + x + x**2/2 + O(x**3)]) def test_name_conflict(): z1 = x0 + y z2 = x2 + x3 l = [cos(z1) + z1, cos(z2) + z2, x0 + x2] substs, reduced = cse(l) assert [e.subs(reversed(substs)) for e in reduced] == l def test_name_conflict_cust_symbols(): z1 = x0 + y z2 = x2 + x3 l = [cos(z1) + z1, cos(z2) + z2, x0 + x2] substs, reduced = cse(l, symbols("x:10")) assert [e.subs(reversed(substs)) for e in reduced] == l def test_symbols_exhausted_error(): l = cos(x+y)+x+y+cos(w+y)+sin(w+y) sym = [x, y, z] with raises(ValueError): cse(l, symbols=sym) def test_issue_7840(): # daveknippers' example C393 = sympify( \ 'Piecewise((C391 - 1.65, C390 < 0.5), (Piecewise((C391 - 1.65, \ C391 > 2.35), (C392, True)), True))' ) C391 = sympify( \ 'Piecewise((2.05*C390**(-1.03), C390 < 0.5), (2.5*C390**(-0.625), True))' ) C393 = C393.subs('C391',C391) # simple substitution sub = {} sub['C390'] = 0.703451854 sub['C392'] = 1.01417794 ss_answer = C393.subs(sub) # cse substitutions,new_eqn = cse(C393) for pair in substitutions: sub[pair[0].name] = pair[1].subs(sub) cse_answer = new_eqn[0].subs(sub) # both methods should be the same assert ss_answer == cse_answer # GitRay's example expr = sympify( "Piecewise((Symbol('ON'), Equality(Symbol('mode'), Symbol('ON'))), \ (Piecewise((Piecewise((Symbol('OFF'), StrictLessThan(Symbol('x'), \ Symbol('threshold'))), (Symbol('ON'), true)), Equality(Symbol('mode'), \ Symbol('AUTO'))), (Symbol('OFF'), true)), true))" ) substitutions, new_eqn = cse(expr) # this Piecewise should be exactly the same assert new_eqn[0] == expr # there should not be any replacements assert len(substitutions) < 1 def test_issue_8891(): for cls in (MutableDenseMatrix, MutableSparseMatrix, ImmutableDenseMatrix, ImmutableSparseMatrix): m = cls(2, 2, [x + y, 0, 0, 0]) res = cse([x + y, m]) ans = ([(x0, x + y)], [x0, cls([[x0, 0], [0, 0]])]) assert res == ans assert isinstance(res[1][-1], cls) def test_issue_11230(): # a specific test that always failed a, b, f, k, l, i = symbols('a b f k l i') p = [a*b*f*k*l, a*i*k**2*l, f*i*k**2*l] R, C = cse(p) assert not any(i.is_Mul for a in C for i in a.args) # random tests for the issue from sympy.core.random import choice from sympy.core.function import expand_mul s = symbols('a:m') # 35 Mul tests, none of which should ever fail ex = [Mul(*[choice(s) for i in range(5)]) for i in range(7)] for p in subsets(ex, 3): p = list(p) R, C = cse(p) assert not any(i.is_Mul for a in C for i in a.args) for ri in reversed(R): for i in range(len(C)): C[i] = C[i].subs(*ri) assert p == C # 35 Add tests, none of which should ever fail ex = [Add(*[choice(s[:7]) for i in range(5)]) for i in range(7)] for p in subsets(ex, 3): p = list(p) R, C = cse(p) assert not any(i.is_Add for a in C for i in a.args) for ri in reversed(R): for i in range(len(C)): C[i] = C[i].subs(*ri) # use expand_mul to handle cases like this: # p = [a + 2*b + 2*e, 2*b + c + 2*e, b + 2*c + 2*g] # x0 = 2*(b + e) is identified giving a rebuilt p that # is now `[a + 2*(b + e), c + 2*(b + e), b + 2*c + 2*g]` assert p == [expand_mul(i) for i in C] @XFAIL def test_issue_11577(): def check(eq): r, c = cse(eq) assert eq.count_ops() >= \ len(r) + sum([i[1].count_ops() for i in r]) + \ count_ops(c) eq = x**5*y**2 + x**5*y + x**5 assert cse(eq) == ( [(x0, x**4), (x1, x*y)], [x**5 + x0*x1*y + x0*x1]) # ([(x0, x**5*y)], [x0*y + x0 + x**5]) or # ([(x0, x**5)], [x0*y**2 + x0*y + x0]) check(eq) eq = x**2/(y + 1)**2 + x/(y + 1) assert cse(eq) == ( [(x0, y + 1)], [x**2/x0**2 + x/x0]) # ([(x0, x/(y + 1))], [x0**2 + x0]) check(eq) def test_hollow_rejection(): eq = [x + 3, x + 4] assert cse(eq) == ([], eq) def test_cse_ignore(): exprs = [exp(y)*(3*y + 3*sqrt(x+1)), exp(y)*(5*y + 5*sqrt(x+1))] subst1, red1 = cse(exprs) assert any(y in sub.free_symbols for _, sub in subst1), "cse failed to identify any term with y" subst2, red2 = cse(exprs, ignore=(y,)) # y is not allowed in substitutions assert not any(y in sub.free_symbols for _, sub in subst2), "Sub-expressions containing y must be ignored" assert any(sub - sqrt(x + 1) == 0 for _, sub in subst2), "cse failed to identify sqrt(x + 1) as sub-expression" def test_cse_ignore_issue_15002(): l = [ w*exp(x)*exp(-z), exp(y)*exp(x)*exp(-z) ] substs, reduced = cse(l, ignore=(x,)) rl = [e.subs(reversed(substs)) for e in reduced] assert rl == l def test_cse__performance(): nexprs, nterms = 3, 20 x = symbols('x:%d' % nterms) exprs = [ reduce(add, [x[j]*(-1)**(i+j) for j in range(nterms)]) for i in range(nexprs) ] assert (exprs[0] + exprs[1]).simplify() == 0 subst, red = cse(exprs) assert len(subst) > 0, "exprs[0] == -exprs[2], i.e. a CSE" for i, e in enumerate(red): assert (e.subs(reversed(subst)) - exprs[i]).simplify() == 0 def test_issue_12070(): exprs = [x + y, 2 + x + y, x + y + z, 3 + x + y + z] subst, red = cse(exprs) assert 6 >= (len(subst) + sum([v.count_ops() for k, v in subst]) + count_ops(red)) def test_issue_13000(): eq = x/(-4*x**2 + y**2) cse_eq = cse(eq)[1][0] assert cse_eq == eq def test_issue_18203(): eq = CRootOf(x**5 + 11*x - 2, 0) + CRootOf(x**5 + 11*x - 2, 1) assert cse(eq) == ([], [eq]) def test_unevaluated_mul(): eq = Mul(x + y, x + y, evaluate=False) assert cse(eq) == ([(x0, x + y)], [x0**2]) def test_cse_release_variables(): from sympy.simplify.cse_main import cse_release_variables _0, _1, _2, _3, _4 = symbols('_:5') eqs = [(x + y - 1)**2, x, x + y, (x + y)/(2*x + 1) + (x + y - 1)**2, (2*x + 1)**(x + y)] r, e = cse(eqs, postprocess=cse_release_variables) # this can change in keeping with the intention of the function assert r, e == ([ (x0, x + y), (x1, (x0 - 1)**2), (x2, 2*x + 1), (_3, x0/x2 + x1), (_4, x2**x0), (x2, None), (_0, x1), (x1, None), (_2, x0), (x0, None), (_1, x)], (_0, _1, _2, _3, _4)) r.reverse() assert eqs == [i.subs(r) for i in e] def test_cse_list(): _cse = lambda x: cse(x, list=False) assert _cse(x) == ([], x) assert _cse('x') == ([], 'x') it = [x] for c in (list, tuple, set): assert _cse(c(it)) == ([], c(it)) #Tuple works different from tuple: assert _cse(Tuple(*it)) == ([], Tuple(*it)) d = {x: 1} assert _cse(d) == ([], d) def test_issue_18991(): A = MatrixSymbol('A', 2, 2) assert signsimp(-A * A - A) == -A * A - A def test_unevaluated_Mul(): m = [Mul(1, 2, evaluate=False)] assert cse(m) == ([], m)
df670f466b46fbf333f60d369669a7f8f5830f727f2aeeacc4bc48514ed6ab11
from sympy.core.function import Function from sympy.core.numbers import (Rational, pi) from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.functions.combinatorial.factorials import (rf, binomial, factorial) from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.gamma_functions import gamma from sympy.simplify.gammasimp import gammasimp from sympy.simplify.powsimp import powsimp from sympy.simplify.simplify import simplify from sympy.abc import x, y, n, k def test_gammasimp(): R = Rational # was part of test_combsimp_gamma() in test_combsimp.py assert gammasimp(gamma(x)) == gamma(x) assert gammasimp(gamma(x + 1)/x) == gamma(x) assert gammasimp(gamma(x)/(x - 1)) == gamma(x - 1) assert gammasimp(x*gamma(x)) == gamma(x + 1) assert gammasimp((x + 1)*gamma(x + 1)) == gamma(x + 2) assert gammasimp(gamma(x + y)*(x + y)) == gamma(x + y + 1) assert gammasimp(x/gamma(x + 1)) == 1/gamma(x) assert gammasimp((x + 1)**2/gamma(x + 2)) == (x + 1)/gamma(x + 1) assert gammasimp(x*gamma(x) + gamma(x + 3)/(x + 2)) == \ (x + 2)*gamma(x + 1) assert gammasimp(gamma(2*x)*x) == gamma(2*x + 1)/2 assert gammasimp(gamma(2*x)/(x - S.Half)) == 2*gamma(2*x - 1) assert gammasimp(gamma(x)*gamma(1 - x)) == pi/sin(pi*x) assert gammasimp(gamma(x)*gamma(-x)) == -pi/(x*sin(pi*x)) assert gammasimp(1/gamma(x + 3)/gamma(1 - x)) == \ sin(pi*x)/(pi*x*(x + 1)*(x + 2)) assert gammasimp(factorial(n + 2)) == gamma(n + 3) assert gammasimp(binomial(n, k)) == \ gamma(n + 1)/(gamma(k + 1)*gamma(-k + n + 1)) assert powsimp(gammasimp( gamma(x)*gamma(x + S.Half)*gamma(y)/gamma(x + y))) == \ 2**(-2*x + 1)*sqrt(pi)*gamma(2*x)*gamma(y)/gamma(x + y) assert gammasimp(1/gamma(x)/gamma(x - Rational(1, 3))/gamma(x + Rational(1, 3))) == \ 3**(3*x - Rational(3, 2))/(2*pi*gamma(3*x - 1)) assert simplify( gamma(S.Half + x/2)*gamma(1 + x/2)/gamma(1 + x)/sqrt(pi)*2**x) == 1 assert gammasimp(gamma(Rational(-1, 4))*gamma(Rational(-3, 4))) == 16*sqrt(2)*pi/3 assert powsimp(gammasimp(gamma(2*x)/gamma(x))) == \ 2**(2*x - 1)*gamma(x + S.Half)/sqrt(pi) # issue 6792 e = (-gamma(k)*gamma(k + 2) + gamma(k + 1)**2)/gamma(k)**2 assert gammasimp(e) == -k assert gammasimp(1/e) == -1/k e = (gamma(x) + gamma(x + 1))/gamma(x) assert gammasimp(e) == x + 1 assert gammasimp(1/e) == 1/(x + 1) e = (gamma(x) + gamma(x + 2))*(gamma(x - 1) + gamma(x))/gamma(x) assert gammasimp(e) == (x**2 + x + 1)*gamma(x + 1)/(x - 1) e = (-gamma(k)*gamma(k + 2) + gamma(k + 1)**2)/gamma(k)**2 assert gammasimp(e**2) == k**2 assert gammasimp(e**2/gamma(k + 1)) == k/gamma(k) a = R(1, 2) + R(1, 3) b = a + R(1, 3) assert gammasimp(gamma(2*k)/gamma(k)*gamma(k + a)*gamma(k + b) ) == 3*2**(2*k + 1)*3**(-3*k - 2)*sqrt(pi)*gamma(3*k + R(3, 2))/2 # issue 9699 assert gammasimp((x + 1)*factorial(x)/gamma(y)) == gamma(x + 2)/gamma(y) assert gammasimp(rf(x + n, k)*binomial(n, k)).simplify() == Piecewise( (gamma(n + 1)*gamma(k + n + x)/(gamma(k + 1)*gamma(n + x)*gamma(-k + n + 1)), n > -x), ((-1)**k*gamma(n + 1)*gamma(-n - x + 1)/(gamma(k + 1)*gamma(-k + n + 1)*gamma(-k - n - x + 1)), True)) A, B = symbols('A B', commutative=False) assert gammasimp(e*B*A) == gammasimp(e)*B*A # check iteration assert gammasimp(gamma(2*k)/gamma(k)*gamma(-k - R(1, 2))) == ( -2**(2*k + 1)*sqrt(pi)/(2*((2*k + 1)*cos(pi*k)))) assert gammasimp( gamma(k)*gamma(k + R(1, 3))*gamma(k + R(2, 3))/gamma(k*R(3, 2))) == ( 3*2**(3*k + 1)*3**(-3*k - S.Half)*sqrt(pi)*gamma(k*R(3, 2) + S.Half)/2) # issue 6153 assert gammasimp(gamma(Rational(1, 4))/gamma(Rational(5, 4))) == 4 # was part of test_combsimp() in test_combsimp.py assert gammasimp(binomial(n + 2, k + S.Half)) == gamma(n + 3)/ \ (gamma(k + R(3, 2))*gamma(-k + n + R(5, 2))) assert gammasimp(binomial(n + 2, k + 2.0)) == \ gamma(n + 3)/(gamma(k + 3.0)*gamma(-k + n + 1)) # issue 11548 assert gammasimp(binomial(0, x)) == sin(pi*x)/(pi*x) e = gamma(n + Rational(1, 3))*gamma(n + R(2, 3)) assert gammasimp(e) == e assert gammasimp(gamma(4*n + S.Half)/gamma(2*n - R(3, 4))) == \ 2**(4*n - R(5, 2))*(8*n - 3)*gamma(2*n + R(3, 4))/sqrt(pi) i, m = symbols('i m', integer = True) e = gamma(exp(i)) assert gammasimp(e) == e e = gamma(m + 3) assert gammasimp(e) == e e = gamma(m + 1)/(gamma(i + 1)*gamma(-i + m + 1)) assert gammasimp(e) == e p = symbols("p", integer=True, positive=True) assert gammasimp(gamma(-p + 4)) == gamma(-p + 4) def test_issue_22606(): fx = Function('f')(x) eq = x + gamma(y) # seems like ans should be `eq`, not `(x*y + gamma(y + 1))/y` ans = gammasimp(eq) assert gammasimp(eq.subs(x, fx)).subs(fx, x) == ans assert gammasimp(eq.subs(x, cos(x))).subs(cos(x), x) == ans assert 1/gammasimp(1/eq) == ans assert gammasimp(fx.subs(x, eq)).args[0] == ans
0b1899dce0692db396f930cdd0179668b4dacf420f1839d8065ce419a82e0412
import math from sympy.core.containers import Tuple from sympy.core.numbers import nan, oo, Float, Integer from sympy.core.relational import Lt from sympy.core.symbol import symbols, Symbol from sympy.functions.elementary.trigonometric import sin from sympy.matrices.dense import Matrix from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.sets.fancysets import Range from sympy.tensor.indexed import Idx, IndexedBase from sympy.testing.pytest import raises from sympy.codegen.ast import ( Assignment, Attribute, aug_assign, CodeBlock, For, Type, Variable, Pointer, Declaration, AddAugmentedAssignment, SubAugmentedAssignment, MulAugmentedAssignment, DivAugmentedAssignment, ModAugmentedAssignment, value_const, pointer_const, integer, real, complex_, int8, uint8, float16 as f16, float32 as f32, float64 as f64, float80 as f80, float128 as f128, complex64 as c64, complex128 as c128, While, Scope, String, Print, QuotedString, FunctionPrototype, FunctionDefinition, Return, FunctionCall, untyped, IntBaseType, intc, Node, none, NoneToken, Token, Comment ) x, y, z, t, x0, x1, x2, a, b = symbols("x, y, z, t, x0, x1, x2, a, b") n = symbols("n", integer=True) A = MatrixSymbol('A', 3, 1) mat = Matrix([1, 2, 3]) B = IndexedBase('B') i = Idx("i", n) A22 = MatrixSymbol('A22',2,2) B22 = MatrixSymbol('B22',2,2) def test_Assignment(): # Here we just do things to show they don't error Assignment(x, y) Assignment(x, 0) Assignment(A, mat) Assignment(A[1,0], 0) Assignment(A[1,0], x) Assignment(B[i], x) Assignment(B[i], 0) a = Assignment(x, y) assert a.func(*a.args) == a assert a.op == ':=' # Here we test things to show that they error # Matrix to scalar raises(ValueError, lambda: Assignment(B[i], A)) raises(ValueError, lambda: Assignment(B[i], mat)) raises(ValueError, lambda: Assignment(x, mat)) raises(ValueError, lambda: Assignment(x, A)) raises(ValueError, lambda: Assignment(A[1,0], mat)) # Scalar to matrix raises(ValueError, lambda: Assignment(A, x)) raises(ValueError, lambda: Assignment(A, 0)) # Non-atomic lhs raises(TypeError, lambda: Assignment(mat, A)) raises(TypeError, lambda: Assignment(0, x)) raises(TypeError, lambda: Assignment(x*x, 1)) raises(TypeError, lambda: Assignment(A + A, mat)) raises(TypeError, lambda: Assignment(B, 0)) def test_AugAssign(): # Here we just do things to show they don't error aug_assign(x, '+', y) aug_assign(x, '+', 0) aug_assign(A, '+', mat) aug_assign(A[1, 0], '+', 0) aug_assign(A[1, 0], '+', x) aug_assign(B[i], '+', x) aug_assign(B[i], '+', 0) # Check creation via aug_assign vs constructor for binop, cls in [ ('+', AddAugmentedAssignment), ('-', SubAugmentedAssignment), ('*', MulAugmentedAssignment), ('/', DivAugmentedAssignment), ('%', ModAugmentedAssignment), ]: a = aug_assign(x, binop, y) b = cls(x, y) assert a.func(*a.args) == a == b assert a.binop == binop assert a.op == binop + '=' # Here we test things to show that they error # Matrix to scalar raises(ValueError, lambda: aug_assign(B[i], '+', A)) raises(ValueError, lambda: aug_assign(B[i], '+', mat)) raises(ValueError, lambda: aug_assign(x, '+', mat)) raises(ValueError, lambda: aug_assign(x, '+', A)) raises(ValueError, lambda: aug_assign(A[1, 0], '+', mat)) # Scalar to matrix raises(ValueError, lambda: aug_assign(A, '+', x)) raises(ValueError, lambda: aug_assign(A, '+', 0)) # Non-atomic lhs raises(TypeError, lambda: aug_assign(mat, '+', A)) raises(TypeError, lambda: aug_assign(0, '+', x)) raises(TypeError, lambda: aug_assign(x * x, '+', 1)) raises(TypeError, lambda: aug_assign(A + A, '+', mat)) raises(TypeError, lambda: aug_assign(B, '+', 0)) def test_Assignment_printing(): assignment_classes = [ Assignment, AddAugmentedAssignment, SubAugmentedAssignment, MulAugmentedAssignment, DivAugmentedAssignment, ModAugmentedAssignment, ] pairs = [ (x, 2 * y + 2), (B[i], x), (A22, B22), (A[0, 0], x), ] for cls in assignment_classes: for lhs, rhs in pairs: a = cls(lhs, rhs) assert repr(a) == '%s(%s, %s)' % (cls.__name__, repr(lhs), repr(rhs)) def test_CodeBlock(): c = CodeBlock(Assignment(x, 1), Assignment(y, x + 1)) assert c.func(*c.args) == c assert c.left_hand_sides == Tuple(x, y) assert c.right_hand_sides == Tuple(1, x + 1) def test_CodeBlock_topological_sort(): assignments = [ Assignment(x, y + z), Assignment(z, 1), Assignment(t, x), Assignment(y, 2), ] ordered_assignments = [ # Note that the unrelated z=1 and y=2 are kept in that order Assignment(z, 1), Assignment(y, 2), Assignment(x, y + z), Assignment(t, x), ] c1 = CodeBlock.topological_sort(assignments) assert c1 == CodeBlock(*ordered_assignments) # Cycle invalid_assignments = [ Assignment(x, y + z), Assignment(z, 1), Assignment(y, x), Assignment(y, 2), ] raises(ValueError, lambda: CodeBlock.topological_sort(invalid_assignments)) # Free symbols free_assignments = [ Assignment(x, y + z), Assignment(z, a * b), Assignment(t, x), Assignment(y, b + 3), ] free_assignments_ordered = [ Assignment(z, a * b), Assignment(y, b + 3), Assignment(x, y + z), Assignment(t, x), ] c2 = CodeBlock.topological_sort(free_assignments) assert c2 == CodeBlock(*free_assignments_ordered) def test_CodeBlock_free_symbols(): c1 = CodeBlock( Assignment(x, y + z), Assignment(z, 1), Assignment(t, x), Assignment(y, 2), ) assert c1.free_symbols == set() c2 = CodeBlock( Assignment(x, y + z), Assignment(z, a * b), Assignment(t, x), Assignment(y, b + 3), ) assert c2.free_symbols == {a, b} def test_CodeBlock_cse(): c1 = CodeBlock( Assignment(y, 1), Assignment(x, sin(y)), Assignment(z, sin(y)), Assignment(t, x*z), ) assert c1.cse() == CodeBlock( Assignment(y, 1), Assignment(x0, sin(y)), Assignment(x, x0), Assignment(z, x0), Assignment(t, x*z), ) # Multiple assignments to same symbol not supported raises(NotImplementedError, lambda: CodeBlock( Assignment(x, 1), Assignment(y, 1), Assignment(y, 2) ).cse()) # Check auto-generated symbols do not collide with existing ones c2 = CodeBlock( Assignment(x0, sin(y) + 1), Assignment(x1, 2 * sin(y)), Assignment(z, x * y), ) assert c2.cse() == CodeBlock( Assignment(x2, sin(y)), Assignment(x0, x2 + 1), Assignment(x1, 2 * x2), Assignment(z, x * y), ) def test_CodeBlock_cse__issue_14118(): # see https://github.com/sympy/sympy/issues/14118 c = CodeBlock( Assignment(A22, Matrix([[x, sin(y)],[3, 4]])), Assignment(B22, Matrix([[sin(y), 2*sin(y)], [sin(y)**2, 7]])) ) assert c.cse() == CodeBlock( Assignment(x0, sin(y)), Assignment(A22, Matrix([[x, x0],[3, 4]])), Assignment(B22, Matrix([[x0, 2*x0], [x0**2, 7]])) ) def test_For(): f = For(n, Range(0, 3), (Assignment(A[n, 0], x + n), aug_assign(x, '+', y))) f = For(n, (1, 2, 3, 4, 5), (Assignment(A[n, 0], x + n),)) assert f.func(*f.args) == f raises(TypeError, lambda: For(n, x, (x + y,))) def test_none(): assert none.is_Atom assert none == none class Foo(Token): pass foo = Foo() assert foo != none assert none == None assert none == NoneToken() assert none.func(*none.args) == none def test_String(): st = String('foobar') assert st.is_Atom assert st == String('foobar') assert st.text == 'foobar' assert st.func(**st.kwargs()) == st assert st.func(*st.args) == st class Signifier(String): pass si = Signifier('foobar') assert si != st assert si.text == st.text s = String('foo') assert str(s) == 'foo' assert repr(s) == "String('foo')" def test_Comment(): c = Comment('foobar') assert c.text == 'foobar' assert str(c) == 'foobar' def test_Node(): n = Node() assert n == Node() assert n.func(*n.args) == n def test_Type(): t = Type('MyType') assert len(t.args) == 1 assert t.name == String('MyType') assert str(t) == 'MyType' assert repr(t) == "Type(String('MyType'))" assert Type(t) == t assert t.func(*t.args) == t t1 = Type('t1') t2 = Type('t2') assert t1 != t2 assert t1 == t1 and t2 == t2 t1b = Type('t1') assert t1 == t1b assert t2 != t1b def test_Type__from_expr(): assert Type.from_expr(i) == integer u = symbols('u', real=True) assert Type.from_expr(u) == real assert Type.from_expr(n) == integer assert Type.from_expr(3) == integer assert Type.from_expr(3.0) == real assert Type.from_expr(3+1j) == complex_ raises(ValueError, lambda: Type.from_expr(sum)) def test_Type__cast_check__integers(): # Rounding raises(ValueError, lambda: integer.cast_check(3.5)) assert integer.cast_check('3') == 3 assert integer.cast_check(Float('3.0000000000000000000')) == 3 assert integer.cast_check(Float('3.0000000000000000001')) == 3 # unintuitive maybe? # Range assert int8.cast_check(127.0) == 127 raises(ValueError, lambda: int8.cast_check(128)) assert int8.cast_check(-128) == -128 raises(ValueError, lambda: int8.cast_check(-129)) assert uint8.cast_check(0) == 0 assert uint8.cast_check(128) == 128 raises(ValueError, lambda: uint8.cast_check(256.0)) raises(ValueError, lambda: uint8.cast_check(-1)) def test_Attribute(): noexcept = Attribute('noexcept') assert noexcept == Attribute('noexcept') alignas16 = Attribute('alignas', [16]) alignas32 = Attribute('alignas', [32]) assert alignas16 != alignas32 assert alignas16.func(*alignas16.args) == alignas16 def test_Variable(): v = Variable(x, type=real) assert v == Variable(v) assert v == Variable('x', type=real) assert v.symbol == x assert v.type == real assert value_const not in v.attrs assert v.func(*v.args) == v assert str(v) == 'Variable(x, type=real)' w = Variable(y, f32, attrs={value_const}) assert w.symbol == y assert w.type == f32 assert value_const in w.attrs assert w.func(*w.args) == w v_n = Variable(n, type=Type.from_expr(n)) assert v_n.type == integer assert v_n.func(*v_n.args) == v_n v_i = Variable(i, type=Type.from_expr(n)) assert v_i.type == integer assert v_i != v_n a_i = Variable.deduced(i) assert a_i.type == integer assert Variable.deduced(Symbol('x', real=True)).type == real assert a_i.func(*a_i.args) == a_i v_n2 = Variable.deduced(n, value=3.5, cast_check=False) assert v_n2.func(*v_n2.args) == v_n2 assert abs(v_n2.value - 3.5) < 1e-15 raises(ValueError, lambda: Variable.deduced(n, value=3.5, cast_check=True)) v_n3 = Variable.deduced(n) assert v_n3.type == integer assert str(v_n3) == 'Variable(n, type=integer)' assert Variable.deduced(z, value=3).type == integer assert Variable.deduced(z, value=3.0).type == real assert Variable.deduced(z, value=3.0+1j).type == complex_ def test_Pointer(): p = Pointer(x) assert p.symbol == x assert p.type == untyped assert value_const not in p.attrs assert pointer_const not in p.attrs assert p.func(*p.args) == p u = symbols('u', real=True) pu = Pointer(u, type=Type.from_expr(u), attrs={value_const, pointer_const}) assert pu.symbol is u assert pu.type == real assert value_const in pu.attrs assert pointer_const in pu.attrs assert pu.func(*pu.args) == pu i = symbols('i', integer=True) deref = pu[i] assert deref.indices == (i,) def test_Declaration(): u = symbols('u', real=True) vu = Variable(u, type=Type.from_expr(u)) assert Declaration(vu).variable.type == real vn = Variable(n, type=Type.from_expr(n)) assert Declaration(vn).variable.type == integer # PR 19107, does not allow comparison between expressions and Basic # lt = StrictLessThan(vu, vn) # assert isinstance(lt, StrictLessThan) vuc = Variable(u, Type.from_expr(u), value=3.0, attrs={value_const}) assert value_const in vuc.attrs assert pointer_const not in vuc.attrs decl = Declaration(vuc) assert decl.variable == vuc assert isinstance(decl.variable.value, Float) assert decl.variable.value == 3.0 assert decl.func(*decl.args) == decl assert vuc.as_Declaration() == decl assert vuc.as_Declaration(value=None, attrs=None) == Declaration(vu) vy = Variable(y, type=integer, value=3) decl2 = Declaration(vy) assert decl2.variable == vy assert decl2.variable.value == Integer(3) vi = Variable(i, type=Type.from_expr(i), value=3.0) decl3 = Declaration(vi) assert decl3.variable.type == integer assert decl3.variable.value == 3.0 raises(ValueError, lambda: Declaration(vi, 42)) def test_IntBaseType(): assert intc.name == String('intc') assert intc.args == (intc.name,) assert str(IntBaseType('a').name) == 'a' def test_FloatType(): assert f16.dig == 3 assert f32.dig == 6 assert f64.dig == 15 assert f80.dig == 18 assert f128.dig == 33 assert f16.decimal_dig == 5 assert f32.decimal_dig == 9 assert f64.decimal_dig == 17 assert f80.decimal_dig == 21 assert f128.decimal_dig == 36 assert f16.max_exponent == 16 assert f32.max_exponent == 128 assert f64.max_exponent == 1024 assert f80.max_exponent == 16384 assert f128.max_exponent == 16384 assert f16.min_exponent == -13 assert f32.min_exponent == -125 assert f64.min_exponent == -1021 assert f80.min_exponent == -16381 assert f128.min_exponent == -16381 assert abs(f16.eps / Float('0.00097656', precision=16) - 1) < 0.1*10**-f16.dig assert abs(f32.eps / Float('1.1920929e-07', precision=32) - 1) < 0.1*10**-f32.dig assert abs(f64.eps / Float('2.2204460492503131e-16', precision=64) - 1) < 0.1*10**-f64.dig assert abs(f80.eps / Float('1.08420217248550443401e-19', precision=80) - 1) < 0.1*10**-f80.dig assert abs(f128.eps / Float(' 1.92592994438723585305597794258492732e-34', precision=128) - 1) < 0.1*10**-f128.dig assert abs(f16.max / Float('65504', precision=16) - 1) < .1*10**-f16.dig assert abs(f32.max / Float('3.40282347e+38', precision=32) - 1) < 0.1*10**-f32.dig assert abs(f64.max / Float('1.79769313486231571e+308', precision=64) - 1) < 0.1*10**-f64.dig # cf. np.finfo(np.float64).max assert abs(f80.max / Float('1.18973149535723176502e+4932', precision=80) - 1) < 0.1*10**-f80.dig assert abs(f128.max / Float('1.18973149535723176508575932662800702e+4932', precision=128) - 1) < 0.1*10**-f128.dig # cf. np.finfo(np.float32).tiny assert abs(f16.tiny / Float('6.1035e-05', precision=16) - 1) < 0.1*10**-f16.dig assert abs(f32.tiny / Float('1.17549435e-38', precision=32) - 1) < 0.1*10**-f32.dig assert abs(f64.tiny / Float('2.22507385850720138e-308', precision=64) - 1) < 0.1*10**-f64.dig assert abs(f80.tiny / Float('3.36210314311209350626e-4932', precision=80) - 1) < 0.1*10**-f80.dig assert abs(f128.tiny / Float('3.3621031431120935062626778173217526e-4932', precision=128) - 1) < 0.1*10**-f128.dig assert f64.cast_check(0.5) == 0.5 assert abs(f64.cast_check(3.7) - 3.7) < 3e-17 assert isinstance(f64.cast_check(3), (Float, float)) assert f64.cast_nocheck(oo) == float('inf') assert f64.cast_nocheck(-oo) == float('-inf') assert f64.cast_nocheck(float(oo)) == float('inf') assert f64.cast_nocheck(float(-oo)) == float('-inf') assert math.isnan(f64.cast_nocheck(nan)) assert f32 != f64 assert f64 == f64.func(*f64.args) def test_Type__cast_check__floating_point(): raises(ValueError, lambda: f32.cast_check(123.45678949)) raises(ValueError, lambda: f32.cast_check(12.345678949)) raises(ValueError, lambda: f32.cast_check(1.2345678949)) raises(ValueError, lambda: f32.cast_check(.12345678949)) assert abs(123.456789049 - f32.cast_check(123.456789049) - 4.9e-8) < 1e-8 assert abs(0.12345678904 - f32.cast_check(0.12345678904) - 4e-11) < 1e-11 dcm21 = Float('0.123456789012345670499') # 21 decimals assert abs(dcm21 - f64.cast_check(dcm21) - 4.99e-19) < 1e-19 f80.cast_check(Float('0.12345678901234567890103', precision=88)) raises(ValueError, lambda: f80.cast_check(Float('0.12345678901234567890149', precision=88))) v10 = 12345.67894 raises(ValueError, lambda: f32.cast_check(v10)) assert abs(Float(str(v10), precision=64+8) - f64.cast_check(v10)) < v10*1e-16 assert abs(f32.cast_check(2147483647) - 2147483650) < 1 def test_Type__cast_check__complex_floating_point(): val9_11 = 123.456789049 + 0.123456789049j raises(ValueError, lambda: c64.cast_check(.12345678949 + .12345678949j)) assert abs(val9_11 - c64.cast_check(val9_11) - 4.9e-8) < 1e-8 dcm21 = Float('0.123456789012345670499') + 1e-20j # 21 decimals assert abs(dcm21 - c128.cast_check(dcm21) - 4.99e-19) < 1e-19 v19 = Float('0.1234567890123456749') + 1j*Float('0.1234567890123456749') raises(ValueError, lambda: c128.cast_check(v19)) def test_While(): xpp = AddAugmentedAssignment(x, 1) whl1 = While(x < 2, [xpp]) assert whl1.condition.args[0] == x assert whl1.condition.args[1] == 2 assert whl1.condition == Lt(x, 2, evaluate=False) assert whl1.body.args == (xpp,) assert whl1.func(*whl1.args) == whl1 cblk = CodeBlock(AddAugmentedAssignment(x, 1)) whl2 = While(x < 2, cblk) assert whl1 == whl2 assert whl1 != While(x < 3, [xpp]) def test_Scope(): assign = Assignment(x, y) incr = AddAugmentedAssignment(x, 1) scp = Scope([assign, incr]) cblk = CodeBlock(assign, incr) assert scp.body == cblk assert scp == Scope(cblk) assert scp != Scope([incr, assign]) assert scp.func(*scp.args) == scp def test_Print(): fmt = "%d %.3f" ps = Print([n, x], fmt) assert str(ps.format_string) == fmt assert ps.print_args == Tuple(n, x) assert ps.args == (Tuple(n, x), QuotedString(fmt), none) assert ps == Print((n, x), fmt) assert ps != Print([x, n], fmt) assert ps.func(*ps.args) == ps ps2 = Print([n, x]) assert ps2 == Print([n, x]) assert ps2 != ps assert ps2.format_string == None def test_FunctionPrototype_and_FunctionDefinition(): vx = Variable(x, type=real) vn = Variable(n, type=integer) fp1 = FunctionPrototype(real, 'power', [vx, vn]) assert fp1.return_type == real assert fp1.name == String('power') assert fp1.parameters == Tuple(vx, vn) assert fp1 == FunctionPrototype(real, 'power', [vx, vn]) assert fp1 != FunctionPrototype(real, 'power', [vn, vx]) assert fp1.func(*fp1.args) == fp1 body = [Assignment(x, x**n), Return(x)] fd1 = FunctionDefinition(real, 'power', [vx, vn], body) assert fd1.return_type == real assert str(fd1.name) == 'power' assert fd1.parameters == Tuple(vx, vn) assert fd1.body == CodeBlock(*body) assert fd1 == FunctionDefinition(real, 'power', [vx, vn], body) assert fd1 != FunctionDefinition(real, 'power', [vx, vn], body[::-1]) assert fd1.func(*fd1.args) == fd1 fp2 = FunctionPrototype.from_FunctionDefinition(fd1) assert fp2 == fp1 fd2 = FunctionDefinition.from_FunctionPrototype(fp1, body) assert fd2 == fd1 def test_Return(): rs = Return(x) assert rs.args == (x,) assert rs == Return(x) assert rs != Return(y) assert rs.func(*rs.args) == rs def test_FunctionCall(): fc = FunctionCall('power', (x, 3)) assert fc.function_args[0] == x assert fc.function_args[1] == 3 assert len(fc.function_args) == 2 assert isinstance(fc.function_args[1], Integer) assert fc == FunctionCall('power', (x, 3)) assert fc != FunctionCall('power', (3, x)) assert fc != FunctionCall('Power', (x, 3)) assert fc.func(*fc.args) == fc fc2 = FunctionCall('fma', [2, 3, 4]) assert len(fc2.function_args) == 3 assert fc2.function_args[0] == 2 assert fc2.function_args[1] == 3 assert fc2.function_args[2] == 4 assert str(fc2) in ( # not sure if QuotedString is a better default... 'FunctionCall(fma, function_args=(2, 3, 4))', 'FunctionCall("fma", function_args=(2, 3, 4))', ) def test_ast_replace(): x = Variable('x', real) y = Variable('y', real) n = Variable('n', integer) pwer = FunctionDefinition(real, 'pwer', [x, n], [pow(x.symbol, n.symbol)]) pname = pwer.name pcall = FunctionCall('pwer', [y, 3]) tree1 = CodeBlock(pwer, pcall) assert str(tree1.args[0].name) == 'pwer' assert str(tree1.args[1].name) == 'pwer' for a, b in zip(tree1, [pwer, pcall]): assert a == b tree2 = tree1.replace(pname, String('power')) assert str(tree1.args[0].name) == 'pwer' assert str(tree1.args[1].name) == 'pwer' assert str(tree2.args[0].name) == 'power' assert str(tree2.args[1].name) == 'power'
12e4708fd534d222dcdbefaab58d980fb4e92029dd434815b025d3607ac81614
from sympy.core.numbers import (Rational, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.exponential import (exp, log) from sympy.codegen.cfunctions import ( expm1, log1p, exp2, log2, fma, log10, Sqrt, Cbrt, hypot ) from sympy.core.function import expand_log def test_expm1(): # Eval assert expm1(0) == 0 x = Symbol('x', real=True) # Expand and rewrite assert expm1(x).expand(func=True) - exp(x) == -1 assert expm1(x).rewrite('tractable') - exp(x) == -1 assert expm1(x).rewrite('exp') - exp(x) == -1 # Precision assert not ((exp(1e-10).evalf() - 1) - 1e-10 - 5e-21) < 1e-22 # for comparison assert abs(expm1(1e-10).evalf() - 1e-10 - 5e-21) < 1e-22 # Properties assert expm1(x).is_real assert expm1(x).is_finite # Diff assert expm1(42*x).diff(x) - 42*exp(42*x) == 0 assert expm1(42*x).diff(x) - expm1(42*x).expand(func=True).diff(x) == 0 def test_log1p(): # Eval assert log1p(0) == 0 d = S(10) assert expand_log(log1p(d**-1000) - log(d**1000 + 1) + log(d**1000)) == 0 x = Symbol('x', real=True) # Expand and rewrite assert log1p(x).expand(func=True) - log(x + 1) == 0 assert log1p(x).rewrite('tractable') - log(x + 1) == 0 assert log1p(x).rewrite('log') - log(x + 1) == 0 # Precision assert not abs(log(1e-99 + 1).evalf() - 1e-99) < 1e-100 # for comparison assert abs(expand_log(log1p(1e-99)).evalf() - 1e-99) < 1e-100 # Properties assert log1p(-2**Rational(-1, 2)).is_real assert not log1p(-1).is_finite assert log1p(pi).is_finite assert not log1p(x).is_positive assert log1p(Symbol('y', positive=True)).is_positive assert not log1p(x).is_zero assert log1p(Symbol('z', zero=True)).is_zero assert not log1p(x).is_nonnegative assert log1p(Symbol('o', nonnegative=True)).is_nonnegative # Diff assert log1p(42*x).diff(x) - 42/(42*x + 1) == 0 assert log1p(42*x).diff(x) - log1p(42*x).expand(func=True).diff(x) == 0 def test_exp2(): # Eval assert exp2(2) == 4 x = Symbol('x', real=True) # Expand assert exp2(x).expand(func=True) - 2**x == 0 # Diff assert exp2(42*x).diff(x) - 42*exp2(42*x)*log(2) == 0 assert exp2(42*x).diff(x) - exp2(42*x).diff(x) == 0 def test_log2(): # Eval assert log2(8) == 3 assert log2(pi) != log(pi)/log(2) # log2 should *save* (CPU) instructions x = Symbol('x', real=True) assert log2(x) != log(x)/log(2) assert log2(2**x) == x # Expand assert log2(x).expand(func=True) - log(x)/log(2) == 0 # Diff assert log2(42*x).diff() - 1/(log(2)*x) == 0 assert log2(42*x).diff() - log2(42*x).expand(func=True).diff(x) == 0 def test_fma(): x, y, z = symbols('x y z') # Expand assert fma(x, y, z).expand(func=True) - x*y - z == 0 expr = fma(17*x, 42*y, 101*z) # Diff assert expr.diff(x) - expr.expand(func=True).diff(x) == 0 assert expr.diff(y) - expr.expand(func=True).diff(y) == 0 assert expr.diff(z) - expr.expand(func=True).diff(z) == 0 assert expr.diff(x) - 17*42*y == 0 assert expr.diff(y) - 17*42*x == 0 assert expr.diff(z) - 101 == 0 def test_log10(): x = Symbol('x') # Expand assert log10(x).expand(func=True) - log(x)/log(10) == 0 # Diff assert log10(42*x).diff(x) - 1/(log(10)*x) == 0 assert log10(42*x).diff(x) - log10(42*x).expand(func=True).diff(x) == 0 def test_Cbrt(): x = Symbol('x') # Expand assert Cbrt(x).expand(func=True) - x**Rational(1, 3) == 0 # Diff assert Cbrt(42*x).diff(x) - 42*(42*x)**(Rational(1, 3) - 1)/3 == 0 assert Cbrt(42*x).diff(x) - Cbrt(42*x).expand(func=True).diff(x) == 0 def test_Sqrt(): x = Symbol('x') # Expand assert Sqrt(x).expand(func=True) - x**S.Half == 0 # Diff assert Sqrt(42*x).diff(x) - 42*(42*x)**(S.Half - 1)/2 == 0 assert Sqrt(42*x).diff(x) - Sqrt(42*x).expand(func=True).diff(x) == 0 def test_hypot(): x, y = symbols('x y') # Expand assert hypot(x, y).expand(func=True) - (x**2 + y**2)**S.Half == 0 # Diff assert hypot(17*x, 42*y).diff(x).expand(func=True) - hypot(17*x, 42*y).expand(func=True).diff(x) == 0 assert hypot(17*x, 42*y).diff(y).expand(func=True) - hypot(17*x, 42*y).expand(func=True).diff(y) == 0 assert hypot(17*x, 42*y).diff(x).expand(func=True) - 2*17*17*x*((17*x)**2 + (42*y)**2)**Rational(-1, 2)/2 == 0 assert hypot(17*x, 42*y).diff(y).expand(func=True) - 2*42*42*y*((17*x)**2 + (42*y)**2)**Rational(-1, 2)/2 == 0
f862587b3a9cb90dca52afc8a821090166becd600f58592ed9674b8fb0289eb7
from sympy.core import symbols from sympy.crypto.crypto import (cycle_list, encipher_shift, encipher_affine, encipher_substitution, check_and_join, encipher_vigenere, decipher_vigenere, encipher_hill, decipher_hill, encipher_bifid5, encipher_bifid6, bifid5_square, bifid6_square, bifid5, bifid6, decipher_bifid5, decipher_bifid6, encipher_kid_rsa, decipher_kid_rsa, kid_rsa_private_key, kid_rsa_public_key, decipher_rsa, rsa_private_key, rsa_public_key, encipher_rsa, lfsr_connection_polynomial, lfsr_autocorrelation, lfsr_sequence, encode_morse, decode_morse, elgamal_private_key, elgamal_public_key, encipher_elgamal, decipher_elgamal, dh_private_key, dh_public_key, dh_shared_key, decipher_shift, decipher_affine, encipher_bifid, decipher_bifid, bifid_square, padded_key, uniq, decipher_gm, encipher_gm, gm_public_key, gm_private_key, encipher_bg, decipher_bg, bg_private_key, bg_public_key, encipher_rot13, decipher_rot13, encipher_atbash, decipher_atbash, NonInvertibleCipherWarning, encipher_railfence, decipher_railfence) from sympy.matrices import Matrix from sympy.ntheory import isprime, is_primitive_root from sympy.polys.domains import FF from sympy.testing.pytest import raises, warns from sympy.core.random import randrange def test_encipher_railfence(): assert encipher_railfence("hello world",2) == "hlowrdel ol" assert encipher_railfence("hello world",3) == "horel ollwd" assert encipher_railfence("hello world",4) == "hwe olordll" def test_decipher_railfence(): assert decipher_railfence("hlowrdel ol",2) == "hello world" assert decipher_railfence("horel ollwd",3) == "hello world" assert decipher_railfence("hwe olordll",4) == "hello world" def test_cycle_list(): assert cycle_list(3, 4) == [3, 0, 1, 2] assert cycle_list(-1, 4) == [3, 0, 1, 2] assert cycle_list(1, 4) == [1, 2, 3, 0] def test_encipher_shift(): assert encipher_shift("ABC", 0) == "ABC" assert encipher_shift("ABC", 1) == "BCD" assert encipher_shift("ABC", -1) == "ZAB" assert decipher_shift("ZAB", -1) == "ABC" def test_encipher_rot13(): assert encipher_rot13("ABC") == "NOP" assert encipher_rot13("NOP") == "ABC" assert decipher_rot13("ABC") == "NOP" assert decipher_rot13("NOP") == "ABC" def test_encipher_affine(): assert encipher_affine("ABC", (1, 0)) == "ABC" assert encipher_affine("ABC", (1, 1)) == "BCD" assert encipher_affine("ABC", (-1, 0)) == "AZY" assert encipher_affine("ABC", (-1, 1), symbols="ABCD") == "BAD" assert encipher_affine("123", (-1, 1), symbols="1234") == "214" assert encipher_affine("ABC", (3, 16)) == "QTW" assert decipher_affine("QTW", (3, 16)) == "ABC" def test_encipher_atbash(): assert encipher_atbash("ABC") == "ZYX" assert encipher_atbash("ZYX") == "ABC" assert decipher_atbash("ABC") == "ZYX" assert decipher_atbash("ZYX") == "ABC" def test_encipher_substitution(): assert encipher_substitution("ABC", "BAC", "ABC") == "BAC" assert encipher_substitution("123", "1243", "1234") == "124" def test_check_and_join(): assert check_and_join("abc") == "abc" assert check_and_join(uniq("aaabc")) == "abc" assert check_and_join("ab c".split()) == "abc" assert check_and_join("abc", "a", filter=True) == "a" raises(ValueError, lambda: check_and_join('ab', 'a')) def test_encipher_vigenere(): assert encipher_vigenere("ABC", "ABC") == "ACE" assert encipher_vigenere("ABC", "ABC", symbols="ABCD") == "ACA" assert encipher_vigenere("ABC", "AB", symbols="ABCD") == "ACC" assert encipher_vigenere("AB", "ABC", symbols="ABCD") == "AC" assert encipher_vigenere("A", "ABC", symbols="ABCD") == "A" def test_decipher_vigenere(): assert decipher_vigenere("ABC", "ABC") == "AAA" assert decipher_vigenere("ABC", "ABC", symbols="ABCD") == "AAA" assert decipher_vigenere("ABC", "AB", symbols="ABCD") == "AAC" assert decipher_vigenere("AB", "ABC", symbols="ABCD") == "AA" assert decipher_vigenere("A", "ABC", symbols="ABCD") == "A" def test_encipher_hill(): A = Matrix(2, 2, [1, 2, 3, 5]) assert encipher_hill("ABCD", A) == "CFIV" A = Matrix(2, 2, [1, 0, 0, 1]) assert encipher_hill("ABCD", A) == "ABCD" assert encipher_hill("ABCD", A, symbols="ABCD") == "ABCD" A = Matrix(2, 2, [1, 2, 3, 5]) assert encipher_hill("ABCD", A, symbols="ABCD") == "CBAB" assert encipher_hill("AB", A, symbols="ABCD") == "CB" # message length, n, does not need to be a multiple of k; # it is padded assert encipher_hill("ABA", A) == "CFGC" assert encipher_hill("ABA", A, pad="Z") == "CFYV" def test_decipher_hill(): A = Matrix(2, 2, [1, 2, 3, 5]) assert decipher_hill("CFIV", A) == "ABCD" A = Matrix(2, 2, [1, 0, 0, 1]) assert decipher_hill("ABCD", A) == "ABCD" assert decipher_hill("ABCD", A, symbols="ABCD") == "ABCD" A = Matrix(2, 2, [1, 2, 3, 5]) assert decipher_hill("CBAB", A, symbols="ABCD") == "ABCD" assert decipher_hill("CB", A, symbols="ABCD") == "AB" # n does not need to be a multiple of k assert decipher_hill("CFA", A) == "ABAA" def test_encipher_bifid5(): assert encipher_bifid5("AB", "AB") == "AB" assert encipher_bifid5("AB", "CD") == "CO" assert encipher_bifid5("ab", "c") == "CH" assert encipher_bifid5("a bc", "b") == "BAC" def test_bifid5_square(): A = bifid5 f = lambda i, j: symbols(A[5*i + j]) M = Matrix(5, 5, f) assert bifid5_square("") == M def test_decipher_bifid5(): assert decipher_bifid5("AB", "AB") == "AB" assert decipher_bifid5("CO", "CD") == "AB" assert decipher_bifid5("ch", "c") == "AB" assert decipher_bifid5("b ac", "b") == "ABC" def test_encipher_bifid6(): assert encipher_bifid6("AB", "AB") == "AB" assert encipher_bifid6("AB", "CD") == "CP" assert encipher_bifid6("ab", "c") == "CI" assert encipher_bifid6("a bc", "b") == "BAC" def test_decipher_bifid6(): assert decipher_bifid6("AB", "AB") == "AB" assert decipher_bifid6("CP", "CD") == "AB" assert decipher_bifid6("ci", "c") == "AB" assert decipher_bifid6("b ac", "b") == "ABC" def test_bifid6_square(): A = bifid6 f = lambda i, j: symbols(A[6*i + j]) M = Matrix(6, 6, f) assert bifid6_square("") == M def test_rsa_public_key(): assert rsa_public_key(2, 3, 1) == (6, 1) assert rsa_public_key(5, 3, 3) == (15, 3) with warns(NonInvertibleCipherWarning): assert rsa_public_key(2, 2, 1) == (4, 1) assert rsa_public_key(8, 8, 8) is False def test_rsa_private_key(): assert rsa_private_key(2, 3, 1) == (6, 1) assert rsa_private_key(5, 3, 3) == (15, 3) assert rsa_private_key(23,29,5) == (667,493) with warns(NonInvertibleCipherWarning): assert rsa_private_key(2, 2, 1) == (4, 1) assert rsa_private_key(8, 8, 8) is False def test_rsa_large_key(): # Sample from # http://www.herongyang.com/Cryptography/JCE-Public-Key-RSA-Private-Public-Key-Pair-Sample.html p = int('101565610013301240713207239558950144682174355406589305284428666'\ '903702505233009') q = int('894687191887545488935455605955948413812376003053143521429242133'\ '12069293984003') e = int('65537') d = int('893650581832704239530398858744759129594796235440844479456143566'\ '6999402846577625762582824202269399672579058991442587406384754958587'\ '400493169361356902030209') assert rsa_public_key(p, q, e) == (p*q, e) assert rsa_private_key(p, q, e) == (p*q, d) def test_encipher_rsa(): puk = rsa_public_key(2, 3, 1) assert encipher_rsa(2, puk) == 2 puk = rsa_public_key(5, 3, 3) assert encipher_rsa(2, puk) == 8 with warns(NonInvertibleCipherWarning): puk = rsa_public_key(2, 2, 1) assert encipher_rsa(2, puk) == 2 def test_decipher_rsa(): prk = rsa_private_key(2, 3, 1) assert decipher_rsa(2, prk) == 2 prk = rsa_private_key(5, 3, 3) assert decipher_rsa(8, prk) == 2 with warns(NonInvertibleCipherWarning): prk = rsa_private_key(2, 2, 1) assert decipher_rsa(2, prk) == 2 def test_mutltiprime_rsa_full_example(): # Test example from # https://iopscience.iop.org/article/10.1088/1742-6596/995/1/012030 puk = rsa_public_key(2, 3, 5, 7, 11, 13, 7) prk = rsa_private_key(2, 3, 5, 7, 11, 13, 7) assert puk == (30030, 7) assert prk == (30030, 823) msg = 10 encrypted = encipher_rsa(2 * msg - 15, puk) assert encrypted == 18065 decrypted = (decipher_rsa(encrypted, prk) + 15) / 2 assert decrypted == msg # Test example from # https://www.scirp.org/pdf/JCC_2018032215502008.pdf puk1 = rsa_public_key(53, 41, 43, 47, 41) prk1 = rsa_private_key(53, 41, 43, 47, 41) puk2 = rsa_public_key(53, 41, 43, 47, 97) prk2 = rsa_private_key(53, 41, 43, 47, 97) assert puk1 == (4391633, 41) assert prk1 == (4391633, 294041) assert puk2 == (4391633, 97) assert prk2 == (4391633, 455713) msg = 12321 encrypted = encipher_rsa(encipher_rsa(msg, puk1), puk2) assert encrypted == 1081588 decrypted = decipher_rsa(decipher_rsa(encrypted, prk2), prk1) assert decrypted == msg def test_rsa_crt_extreme(): p = int( '10177157607154245068023861503693082120906487143725062283406501' \ '54082258226204046999838297167140821364638180697194879500245557' \ '65445186962893346463841419427008800341257468600224049986260471' \ '92257248163014468841725476918639415726709736077813632961290911' \ '0256421232977833028677441206049309220354796014376698325101693') q = int( '28752342353095132872290181526607275886182793241660805077850801' \ '75689512797754286972952273553128181861830576836289738668745250' \ '34028199691128870676414118458442900035778874482624765513861643' \ '27966696316822188398336199002306588703902894100476186823849595' \ '103239410527279605442148285816149368667083114802852804976893') r = int( '17698229259868825776879500736350186838850961935956310134378261' \ '89771862186717463067541369694816245225291921138038800171125596' \ '07315449521981157084370187887650624061033066022458512942411841' \ '18747893789972315277160085086164119879536041875335384844820566' \ '0287479617671726408053319619892052000850883994343378882717849') s = int( '68925428438585431029269182233502611027091755064643742383515623' \ '64321310582896893395529367074942808353187138794422745718419645' \ '28291231865157212604266903677599180789896916456120289112752835' \ '98502265889669730331688206825220074713977607415178738015831030' \ '364290585369150502819743827343552098197095520550865360159439' ) t = int( '69035483433453632820551311892368908779778144568711455301541094' \ '31487047642322695357696860925747923189635033183069823820910521' \ '71172909106797748883261493224162414050106920442445896819806600' \ '15448444826108008217972129130625571421904893252804729877353352' \ '739420480574842850202181462656251626522910618936534699566291' ) e = 65537 puk = rsa_public_key(p, q, r, s, t, e) prk = rsa_private_key(p, q, r, s, t, e) plaintext = 1000 ciphertext_1 = encipher_rsa(plaintext, puk) ciphertext_2 = encipher_rsa(plaintext, puk, [p, q, r, s, t]) assert ciphertext_1 == ciphertext_2 assert decipher_rsa(ciphertext_1, prk) == \ decipher_rsa(ciphertext_1, prk, [p, q, r, s, t]) def test_rsa_exhaustive(): p, q = 61, 53 e = 17 puk = rsa_public_key(p, q, e, totient='Carmichael') prk = rsa_private_key(p, q, e, totient='Carmichael') for msg in range(puk[0]): encrypted = encipher_rsa(msg, puk) decrypted = decipher_rsa(encrypted, prk) try: assert decrypted == msg except AssertionError: raise AssertionError( "The RSA is not correctly decrypted " \ "(Original : {}, Encrypted : {}, Decrypted : {})" \ .format(msg, encrypted, decrypted) ) def test_rsa_multiprime_exhanstive(): primes = [3, 5, 7, 11] e = 7 args = primes + [e] puk = rsa_public_key(*args, totient='Carmichael') prk = rsa_private_key(*args, totient='Carmichael') n = puk[0] for msg in range(n): encrypted = encipher_rsa(msg, puk) decrypted = decipher_rsa(encrypted, prk) try: assert decrypted == msg except AssertionError: raise AssertionError( "The RSA is not correctly decrypted " \ "(Original : {}, Encrypted : {}, Decrypted : {})" \ .format(msg, encrypted, decrypted) ) def test_rsa_multipower_exhanstive(): from sympy.core.numbers import igcd primes = [5, 5, 7] e = 7 args = primes + [e] puk = rsa_public_key(*args, multipower=True) prk = rsa_private_key(*args, multipower=True) n = puk[0] for msg in range(n): if igcd(msg, n) != 1: continue encrypted = encipher_rsa(msg, puk) decrypted = decipher_rsa(encrypted, prk) try: assert decrypted == msg except AssertionError: raise AssertionError( "The RSA is not correctly decrypted " \ "(Original : {}, Encrypted : {}, Decrypted : {})" \ .format(msg, encrypted, decrypted) ) def test_kid_rsa_public_key(): assert kid_rsa_public_key(1, 2, 1, 1) == (5, 2) assert kid_rsa_public_key(1, 2, 2, 1) == (8, 3) assert kid_rsa_public_key(1, 2, 1, 2) == (7, 2) def test_kid_rsa_private_key(): assert kid_rsa_private_key(1, 2, 1, 1) == (5, 3) assert kid_rsa_private_key(1, 2, 2, 1) == (8, 3) assert kid_rsa_private_key(1, 2, 1, 2) == (7, 4) def test_encipher_kid_rsa(): assert encipher_kid_rsa(1, (5, 2)) == 2 assert encipher_kid_rsa(1, (8, 3)) == 3 assert encipher_kid_rsa(1, (7, 2)) == 2 def test_decipher_kid_rsa(): assert decipher_kid_rsa(2, (5, 3)) == 1 assert decipher_kid_rsa(3, (8, 3)) == 1 assert decipher_kid_rsa(2, (7, 4)) == 1 def test_encode_morse(): assert encode_morse('ABC') == '.-|-...|-.-.' assert encode_morse('SMS ') == '...|--|...||' assert encode_morse('SMS\n') == '...|--|...||' assert encode_morse('') == '' assert encode_morse(' ') == '||' assert encode_morse(' ', sep='`') == '``' assert encode_morse(' ', sep='``') == '````' assert encode_morse('!@#$%^&*()_+') == '-.-.--|.--.-.|...-..-|-.--.|-.--.-|..--.-|.-.-.' assert encode_morse('12345') == '.----|..---|...--|....-|.....' assert encode_morse('67890') == '-....|--...|---..|----.|-----' def test_decode_morse(): assert decode_morse('-.-|.|-.--') == 'KEY' assert decode_morse('.-.|..-|-.||') == 'RUN' raises(KeyError, lambda: decode_morse('.....----')) def test_lfsr_sequence(): raises(TypeError, lambda: lfsr_sequence(1, [1], 1)) raises(TypeError, lambda: lfsr_sequence([1], 1, 1)) F = FF(2) assert lfsr_sequence([F(1)], [F(1)], 2) == [F(1), F(1)] assert lfsr_sequence([F(0)], [F(1)], 2) == [F(1), F(0)] F = FF(3) assert lfsr_sequence([F(1)], [F(1)], 2) == [F(1), F(1)] assert lfsr_sequence([F(0)], [F(2)], 2) == [F(2), F(0)] assert lfsr_sequence([F(1)], [F(2)], 2) == [F(2), F(2)] def test_lfsr_autocorrelation(): raises(TypeError, lambda: lfsr_autocorrelation(1, 2, 3)) F = FF(2) s = lfsr_sequence([F(1), F(0)], [F(0), F(1)], 5) assert lfsr_autocorrelation(s, 2, 0) == 1 assert lfsr_autocorrelation(s, 2, 1) == -1 def test_lfsr_connection_polynomial(): F = FF(2) x = symbols("x") s = lfsr_sequence([F(1), F(0)], [F(0), F(1)], 5) assert lfsr_connection_polynomial(s) == x**2 + 1 s = lfsr_sequence([F(1), F(1)], [F(0), F(1)], 5) assert lfsr_connection_polynomial(s) == x**2 + x + 1 def test_elgamal_private_key(): a, b, _ = elgamal_private_key(digit=100) assert isprime(a) assert is_primitive_root(b, a) assert len(bin(a)) >= 102 def test_elgamal(): dk = elgamal_private_key(5) ek = elgamal_public_key(dk) P = ek[0] assert P - 1 == decipher_elgamal(encipher_elgamal(P - 1, ek), dk) raises(ValueError, lambda: encipher_elgamal(P, dk)) raises(ValueError, lambda: encipher_elgamal(-1, dk)) def test_dh_private_key(): p, g, _ = dh_private_key(digit = 100) assert isprime(p) assert is_primitive_root(g, p) assert len(bin(p)) >= 102 def test_dh_public_key(): p1, g1, a = dh_private_key(digit = 100) p2, g2, ga = dh_public_key((p1, g1, a)) assert p1 == p2 assert g1 == g2 assert ga == pow(g1, a, p1) def test_dh_shared_key(): prk = dh_private_key(digit = 100) p, _, ga = dh_public_key(prk) b = randrange(2, p) sk = dh_shared_key((p, _, ga), b) assert sk == pow(ga, b, p) raises(ValueError, lambda: dh_shared_key((1031, 14, 565), 2000)) def test_padded_key(): assert padded_key('b', 'ab') == 'ba' raises(ValueError, lambda: padded_key('ab', 'ace')) raises(ValueError, lambda: padded_key('ab', 'abba')) def test_bifid(): raises(ValueError, lambda: encipher_bifid('abc', 'b', 'abcde')) assert encipher_bifid('abc', 'b', 'abcd') == 'bdb' raises(ValueError, lambda: decipher_bifid('bdb', 'b', 'abcde')) assert encipher_bifid('bdb', 'b', 'abcd') == 'abc' raises(ValueError, lambda: bifid_square('abcde')) assert bifid5_square("B") == \ bifid5_square('BACDEFGHIKLMNOPQRSTUVWXYZ') assert bifid6_square('B0') == \ bifid6_square('B0ACDEFGHIJKLMNOPQRSTUVWXYZ123456789') def test_encipher_decipher_gm(): ps = [131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199] qs = [89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 47] messages = [ 0, 32855, 34303, 14805, 1280, 75859, 38368, 724, 60356, 51675, 76697, 61854, 18661, ] for p, q in zip(ps, qs): pri = gm_private_key(p, q) for msg in messages: pub = gm_public_key(p, q) enc = encipher_gm(msg, pub) dec = decipher_gm(enc, pri) assert dec == msg def test_gm_private_key(): raises(ValueError, lambda: gm_public_key(13, 15)) raises(ValueError, lambda: gm_public_key(0, 0)) raises(ValueError, lambda: gm_public_key(0, 5)) assert 17, 19 == gm_public_key(17, 19) def test_gm_public_key(): assert 323 == gm_public_key(17, 19)[1] assert 15 == gm_public_key(3, 5)[1] raises(ValueError, lambda: gm_public_key(15, 19)) def test_encipher_decipher_bg(): ps = [67, 7, 71, 103, 11, 43, 107, 47, 79, 19, 83, 23, 59, 127, 31] qs = qs = [7, 71, 103, 11, 43, 107, 47, 79, 19, 83, 23, 59, 127, 31, 67] messages = [ 0, 328, 343, 148, 1280, 758, 383, 724, 603, 516, 766, 618, 186, ] for p, q in zip(ps, qs): pri = bg_private_key(p, q) for msg in messages: pub = bg_public_key(p, q) enc = encipher_bg(msg, pub) dec = decipher_bg(enc, pri) assert dec == msg def test_bg_private_key(): raises(ValueError, lambda: bg_private_key(8, 16)) raises(ValueError, lambda: bg_private_key(8, 8)) raises(ValueError, lambda: bg_private_key(13, 17)) assert 23, 31 == bg_private_key(23, 31) def test_bg_public_key(): assert 5293 == bg_public_key(67, 79) assert 713 == bg_public_key(23, 31) raises(ValueError, lambda: bg_private_key(13, 17))
1185c1a7b921d8b66ae9523d03e7fe6cd5b14373deb03a7a68a531db6848eda2
""" General binary relations. """ from typing import Optional from sympy.core.singleton import S from sympy.assumptions import AppliedPredicate, ask, Predicate, Q # type: ignore from sympy.core.kind import BooleanKind from sympy.core.relational import Eq, Ne, Gt, Lt, Ge, Le from sympy.logic.boolalg import conjuncts, Not __all__ = ["BinaryRelation", "AppliedBinaryRelation"] class BinaryRelation(Predicate): """ Base class for all binary relational predicates. Explanation =========== Binary relation takes two arguments and returns ``AppliedBinaryRelation`` instance. To evaluate it to boolean value, use :obj:`~.ask()` or :obj:`~.refine()` function. You can add support for new types by registering the handler to dispatcher. See :obj:`~.Predicate()` for more information about predicate dispatching. Examples ======== Applying and evaluating to boolean value: >>> from sympy import Q, ask, sin, cos >>> from sympy.abc import x >>> Q.eq(sin(x)**2+cos(x)**2, 1) Q.eq(sin(x)**2 + cos(x)**2, 1) >>> ask(_) True You can define a new binary relation by subclassing and dispatching. Here, we define a relation $R$ such that $x R y$ returns true if $x = y + 1$. >>> from sympy import ask, Number, Q >>> from sympy.assumptions import BinaryRelation >>> class MyRel(BinaryRelation): ... name = "R" ... is_reflexive = False >>> Q.R = MyRel() >>> @Q.R.register(Number, Number) ... def _(n1, n2, assumptions): ... return ask(Q.zero(n1 - n2 - 1), assumptions) >>> Q.R(2, 1) Q.R(2, 1) Now, we can use ``ask()`` to evaluate it to boolean value. >>> ask(Q.R(2, 1)) True >>> ask(Q.R(1, 2)) False ``Q.R`` returns ``False`` with minimum cost if two arguments have same structure because it is antireflexive relation [1] by ``is_reflexive = False``. >>> ask(Q.R(x, x)) False References ========== .. [1] https://en.wikipedia.org/wiki/Reflexive_relation """ is_reflexive: Optional[bool] = None is_symmetric: Optional[bool] = None def __call__(self, *args): if not len(args) == 2: raise ValueError("Binary relation takes two arguments, but got %s." % len(args)) return AppliedBinaryRelation(self, *args) @property def reversed(self): if self.is_symmetric: return self return None @property def negated(self): return None def _compare_reflexive(self, lhs, rhs): # quick exit for structurally same arguments # do not check != here because it cannot catch the # equivalent arguements with different structures. # reflexivity does not hold to NaN if lhs is S.NaN or rhs is S.NaN: return None reflexive = self.is_reflexive if reflexive is None: pass elif reflexive and (lhs == rhs): return True elif not reflexive and (lhs == rhs): return False return None def eval(self, args, assumptions=True): # quick exit for structurally same arguments ret = self._compare_reflexive(*args) if ret is not None: return ret # don't perform simplify on args here. (done by AppliedBinaryRelation._eval_ask) # evaluate by multipledispatch lhs, rhs = args ret = self.handler(lhs, rhs, assumptions=assumptions) if ret is not None: return ret # check reversed order if the relation is reflexive if self.is_reflexive: types = (type(lhs), type(rhs)) if self.handler.dispatch(*types) is not self.handler.dispatch(*reversed(types)): ret = self.handler(rhs, lhs, assumptions=assumptions) return ret class AppliedBinaryRelation(AppliedPredicate): """ The class of expressions resulting from applying ``BinaryRelation`` to the arguments. """ @property def lhs(self): """The left-hand side of the relation.""" return self.arguments[0] @property def rhs(self): """The right-hand side of the relation.""" return self.arguments[1] @property def reversed(self): """ Try to return the relationship with sides reversed. """ revfunc = self.function.reversed if revfunc is None: return self return revfunc(self.rhs, self.lhs) @property def reversedsign(self): """ Try to return the relationship with signs reversed. """ revfunc = self.function.reversed if revfunc is None: return self if not any(side.kind is BooleanKind for side in self.arguments): return revfunc(-self.lhs, -self.rhs) return self @property def negated(self): neg_rel = self.function.negated if neg_rel is None: return Not(self, evaluate=False) return neg_rel(*self.arguments) def _eval_ask(self, assumptions): conj_assumps = set() binrelpreds = {Eq: Q.eq, Ne: Q.ne, Gt: Q.gt, Lt: Q.lt, Ge: Q.ge, Le: Q.le} for a in conjuncts(assumptions): if a.func in binrelpreds: conj_assumps.add(binrelpreds[type(a)](*a.args)) else: conj_assumps.add(a) # After CNF in assumptions module is modified to take polyadic # predicate, this will be removed if any(rel in conj_assumps for rel in (self, self.reversed)): return True neg_rels = (self.negated, self.reversed.negated, Not(self, evaluate=False), Not(self.reversed, evaluate=False)) if any(rel in conj_assumps for rel in neg_rels): return False # evaluation using multipledispatching ret = self.function.eval(self.arguments, assumptions) if ret is not None: return ret # simplify the args and try again args = tuple(a.simplify() for a in self.arguments) return self.function.eval(args, assumptions) def __bool__(self): ret = ask(self) if ret is None: raise TypeError("Cannot determine truth value of %s" % self) return ret
ce9072002a5afed1749d5341d09feb25e8675e41ed93185c867d43be45554beb
from sympy.assumptions import Predicate, AppliedPredicate, Q from sympy.core.relational import Eq, Ne, Gt, Lt, Ge, Le from sympy.multipledispatch import Dispatcher class CommutativePredicate(Predicate): """ Commutative predicate. Explanation =========== ``ask(Q.commutative(x))`` is true iff ``x`` commutes with any other object with respect to multiplication operation. """ # TODO: Add examples name = 'commutative' handler = Dispatcher("CommutativeHandler", doc="Handler for key 'commutative'.") binrelpreds = {Eq: Q.eq, Ne: Q.ne, Gt: Q.gt, Lt: Q.lt, Ge: Q.ge, Le: Q.le} class IsTruePredicate(Predicate): """ Generic predicate. Explanation =========== ``ask(Q.is_true(x))`` is true iff ``x`` is true. This only makes sense if ``x`` is a boolean object. Examples ======== >>> from sympy import ask, Q >>> from sympy.abc import x, y >>> ask(Q.is_true(True)) True Wrapping another applied predicate just returns the applied predicate. >>> Q.is_true(Q.even(x)) Q.even(x) Wrapping binary relation classes in SymPy core returns applied binary relational predicates. >>> from sympy import Eq, Gt >>> Q.is_true(Eq(x, y)) Q.eq(x, y) >>> Q.is_true(Gt(x, y)) Q.gt(x, y) Notes ===== This class is designed to wrap the boolean objects so that they can behave as if they are applied predicates. Consequently, wrapping another applied predicate is unnecessary and thus it just returns the argument. Also, binary relation classes in SymPy core have binary predicates to represent themselves and thus wrapping them with ``Q.is_true`` converts them to these applied predicates. """ name = 'is_true' handler = Dispatcher( "IsTrueHandler", doc="Wrapper allowing to query the truth value of a boolean expression." ) def __call__(self, arg): # No need to wrap another predicate if isinstance(arg, AppliedPredicate): return arg # Convert relational predicates instead of wrapping them if getattr(arg, "is_Relational", False): pred = binrelpreds[type(arg)] return pred(*arg.args) return super().__call__(arg)
52c66ee91165ca04d8c2a9f1dc48a26b0d42a2af5418c1df2c1cb219def05014
from sympy.abc import t, w, x, y, z, n, k, m, p, i from sympy.assumptions import (ask, AssumptionsContext, Q, register_handler, remove_handler) from sympy.assumptions.assume import assuming, global_assumptions, Predicate from sympy.assumptions.cnf import CNF, Literal from sympy.assumptions.facts import (single_fact_lookup, get_known_facts, generate_known_facts_dict, get_known_facts_keys) from sympy.assumptions.handlers import AskHandler from sympy.assumptions.ask_generated import (get_all_known_facts, get_known_facts_dict) from sympy.core.add import Add from sympy.core.numbers import (I, Integer, Rational, oo, zoo, pi) from sympy.core.singleton import S from sympy.core.power import Pow from sympy.core.symbol import Str, symbols, Symbol from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.complexes import (Abs, im, re, sign) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import ( acos, acot, asin, atan, cos, cot, sin, tan) from sympy.logic.boolalg import Equivalent, Implies, Xor, And, to_cnf from sympy.matrices import Matrix, SparseMatrix from sympy.testing.pytest import XFAIL, slow, raises, warns_deprecated_sympy, _both_exp_pow import math def test_int_1(): z = 1 assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is True assert ask(Q.rational(z)) is True assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is False assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is True assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False def test_int_11(): z = 11 assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is True assert ask(Q.rational(z)) is True assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is False assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is True assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is True assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False def test_int_12(): z = 12 assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is True assert ask(Q.rational(z)) is True assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is False assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is True assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is True assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False def test_float_1(): z = 1.0 assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is None assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is None assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False z = 7.2123 assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is None assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is None assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False # test for issue #12168 assert ask(Q.rational(math.pi)) is None def test_zero_0(): z = Integer(0) assert ask(Q.nonzero(z)) is False assert ask(Q.zero(z)) is True assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is True assert ask(Q.rational(z)) is True assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is False assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is True assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is True def test_negativeone(): z = Integer(-1) assert ask(Q.nonzero(z)) is True assert ask(Q.zero(z)) is False assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is True assert ask(Q.rational(z)) is True assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is False assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is False assert ask(Q.negative(z)) is True assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is True assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False def test_infinity(): assert ask(Q.commutative(oo)) is True assert ask(Q.integer(oo)) is False assert ask(Q.rational(oo)) is False assert ask(Q.algebraic(oo)) is False assert ask(Q.real(oo)) is False assert ask(Q.extended_real(oo)) is True assert ask(Q.complex(oo)) is False assert ask(Q.irrational(oo)) is False assert ask(Q.imaginary(oo)) is False assert ask(Q.positive(oo)) is False assert ask(Q.extended_positive(oo)) is True assert ask(Q.negative(oo)) is False assert ask(Q.even(oo)) is False assert ask(Q.odd(oo)) is False assert ask(Q.finite(oo)) is False assert ask(Q.infinite(oo)) is True assert ask(Q.prime(oo)) is False assert ask(Q.composite(oo)) is False assert ask(Q.hermitian(oo)) is False assert ask(Q.antihermitian(oo)) is False assert ask(Q.positive_infinite(oo)) is True assert ask(Q.negative_infinite(oo)) is False def test_neg_infinity(): mm = S.NegativeInfinity assert ask(Q.commutative(mm)) is True assert ask(Q.integer(mm)) is False assert ask(Q.rational(mm)) is False assert ask(Q.algebraic(mm)) is False assert ask(Q.real(mm)) is False assert ask(Q.extended_real(mm)) is True assert ask(Q.complex(mm)) is False assert ask(Q.irrational(mm)) is False assert ask(Q.imaginary(mm)) is False assert ask(Q.positive(mm)) is False assert ask(Q.negative(mm)) is False assert ask(Q.extended_negative(mm)) is True assert ask(Q.even(mm)) is False assert ask(Q.odd(mm)) is False assert ask(Q.finite(mm)) is False assert ask(Q.infinite(oo)) is True assert ask(Q.prime(mm)) is False assert ask(Q.composite(mm)) is False assert ask(Q.hermitian(mm)) is False assert ask(Q.antihermitian(mm)) is False assert ask(Q.positive_infinite(-oo)) is False assert ask(Q.negative_infinite(-oo)) is True def test_complex_infinity(): assert ask(Q.commutative(zoo)) is True assert ask(Q.integer(zoo)) is False assert ask(Q.rational(zoo)) is False assert ask(Q.algebraic(zoo)) is False assert ask(Q.real(zoo)) is False assert ask(Q.extended_real(zoo)) is False assert ask(Q.complex(zoo)) is False assert ask(Q.irrational(zoo)) is False assert ask(Q.imaginary(zoo)) is False assert ask(Q.positive(zoo)) is False assert ask(Q.negative(zoo)) is False assert ask(Q.zero(zoo)) is False assert ask(Q.nonzero(zoo)) is False assert ask(Q.even(zoo)) is False assert ask(Q.odd(zoo)) is False assert ask(Q.finite(zoo)) is False assert ask(Q.infinite(zoo)) is True assert ask(Q.prime(zoo)) is False assert ask(Q.composite(zoo)) is False assert ask(Q.hermitian(zoo)) is False assert ask(Q.antihermitian(zoo)) is False assert ask(Q.positive_infinite(zoo)) is False assert ask(Q.negative_infinite(zoo)) is False def test_nan(): nan = S.NaN assert ask(Q.commutative(nan)) is True assert ask(Q.integer(nan)) is None assert ask(Q.rational(nan)) is None assert ask(Q.algebraic(nan)) is None assert ask(Q.real(nan)) is None assert ask(Q.extended_real(nan)) is None assert ask(Q.complex(nan)) is None assert ask(Q.irrational(nan)) is None assert ask(Q.imaginary(nan)) is None assert ask(Q.positive(nan)) is None assert ask(Q.nonzero(nan)) is None assert ask(Q.zero(nan)) is None assert ask(Q.even(nan)) is None assert ask(Q.odd(nan)) is None assert ask(Q.finite(nan)) is None assert ask(Q.infinite(nan)) is None assert ask(Q.prime(nan)) is None assert ask(Q.composite(nan)) is None assert ask(Q.hermitian(nan)) is None assert ask(Q.antihermitian(nan)) is None def test_Rational_number(): r = Rational(3, 4) assert ask(Q.commutative(r)) is True assert ask(Q.integer(r)) is False assert ask(Q.rational(r)) is True assert ask(Q.real(r)) is True assert ask(Q.complex(r)) is True assert ask(Q.irrational(r)) is False assert ask(Q.imaginary(r)) is False assert ask(Q.positive(r)) is True assert ask(Q.negative(r)) is False assert ask(Q.even(r)) is False assert ask(Q.odd(r)) is False assert ask(Q.finite(r)) is True assert ask(Q.prime(r)) is False assert ask(Q.composite(r)) is False assert ask(Q.hermitian(r)) is True assert ask(Q.antihermitian(r)) is False r = Rational(1, 4) assert ask(Q.positive(r)) is True assert ask(Q.negative(r)) is False r = Rational(5, 4) assert ask(Q.negative(r)) is False assert ask(Q.positive(r)) is True r = Rational(5, 3) assert ask(Q.positive(r)) is True assert ask(Q.negative(r)) is False r = Rational(-3, 4) assert ask(Q.positive(r)) is False assert ask(Q.negative(r)) is True r = Rational(-1, 4) assert ask(Q.positive(r)) is False assert ask(Q.negative(r)) is True r = Rational(-5, 4) assert ask(Q.negative(r)) is True assert ask(Q.positive(r)) is False r = Rational(-5, 3) assert ask(Q.positive(r)) is False assert ask(Q.negative(r)) is True def test_sqrt_2(): z = sqrt(2) assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is True assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False def test_pi(): z = S.Pi assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.algebraic(z)) is False assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is True assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False z = S.Pi + 1 assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.algebraic(z)) is False assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is True assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False z = 2*S.Pi assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.algebraic(z)) is False assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is True assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False z = S.Pi ** 2 assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.algebraic(z)) is False assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is True assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False z = (1 + S.Pi) ** 2 assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.algebraic(z)) is False assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is True assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False def test_E(): z = S.Exp1 assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.algebraic(z)) is False assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is True assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False def test_GoldenRatio(): z = S.GoldenRatio assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.algebraic(z)) is True assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is True assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False def test_TribonacciConstant(): z = S.TribonacciConstant assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.algebraic(z)) is True assert ask(Q.real(z)) is True assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is True assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is True assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is True assert ask(Q.antihermitian(z)) is False def test_I(): z = I assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.algebraic(z)) is True assert ask(Q.real(z)) is False assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is False assert ask(Q.imaginary(z)) is True assert ask(Q.positive(z)) is False assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is False assert ask(Q.antihermitian(z)) is True z = 1 + I assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.algebraic(z)) is True assert ask(Q.real(z)) is False assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is False assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is False assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is False assert ask(Q.antihermitian(z)) is False z = I*(1 + I) assert ask(Q.commutative(z)) is True assert ask(Q.integer(z)) is False assert ask(Q.rational(z)) is False assert ask(Q.algebraic(z)) is True assert ask(Q.real(z)) is False assert ask(Q.complex(z)) is True assert ask(Q.irrational(z)) is False assert ask(Q.imaginary(z)) is False assert ask(Q.positive(z)) is False assert ask(Q.negative(z)) is False assert ask(Q.even(z)) is False assert ask(Q.odd(z)) is False assert ask(Q.finite(z)) is True assert ask(Q.prime(z)) is False assert ask(Q.composite(z)) is False assert ask(Q.hermitian(z)) is False assert ask(Q.antihermitian(z)) is False z = I**(I) assert ask(Q.imaginary(z)) is False assert ask(Q.real(z)) is True z = (-I)**(I) assert ask(Q.imaginary(z)) is False assert ask(Q.real(z)) is True z = (3*I)**(I) assert ask(Q.imaginary(z)) is False assert ask(Q.real(z)) is False z = (1)**(I) assert ask(Q.imaginary(z)) is False assert ask(Q.real(z)) is True z = (-1)**(I) assert ask(Q.imaginary(z)) is False assert ask(Q.real(z)) is True z = (1+I)**(I) assert ask(Q.imaginary(z)) is False assert ask(Q.real(z)) is False z = (I)**(I+3) assert ask(Q.imaginary(z)) is True assert ask(Q.real(z)) is False z = (I)**(I+2) assert ask(Q.imaginary(z)) is False assert ask(Q.real(z)) is True z = (I)**(2) assert ask(Q.imaginary(z)) is False assert ask(Q.real(z)) is True z = (I)**(3) assert ask(Q.imaginary(z)) is True assert ask(Q.real(z)) is False z = (3)**(I) assert ask(Q.imaginary(z)) is False assert ask(Q.real(z)) is False z = (I)**(0) assert ask(Q.imaginary(z)) is False assert ask(Q.real(z)) is True def test_bounded(): x, y, z = symbols('x,y,z') assert ask(Q.finite(x)) is None assert ask(Q.finite(x), Q.finite(x)) is True assert ask(Q.finite(x), Q.finite(y)) is None assert ask(Q.finite(x), Q.complex(x)) is True assert ask(Q.finite(x), Q.extended_real(x)) is None assert ask(Q.finite(x + 1)) is None assert ask(Q.finite(x + 1), Q.finite(x)) is True a = x + y x, y = a.args # B + B assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)) is True assert ask(Q.finite(a), Q.positive(x) & Q.finite(y)) is True assert ask(Q.finite(a), Q.finite(x) & Q.positive(y)) is True assert ask(Q.finite(a), Q.positive(x) & Q.positive(y)) is True assert ask(Q.finite(a), Q.positive(x) & Q.finite(y) & ~Q.positive(y)) is True assert ask(Q.finite(a), Q.finite(x) & ~Q.positive(x) & Q.positive(y)) is True assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) & ~Q.positive(x) & ~Q.positive(y)) is True # B + U assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)) is False assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y)) is False assert ask(Q.finite(a), Q.finite(x) & Q.positive_infinite(y)) is False assert ask(Q.finite(a), Q.positive(x) & Q.positive_infinite(y)) is False assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y) & ~Q.positive(y)) is False assert ask(Q.finite(a), Q.finite(x) & ~Q.positive(x) & Q.positive_infinite(y)) is False assert ask(Q.finite(a), Q.finite(x) & ~Q.positive(x) & ~Q.finite(y) & ~Q.positive(y)) is False # B + ? assert ask(Q.finite(a), Q.finite(x)) is None assert ask(Q.finite(a), Q.positive(x)) is None assert ask(Q.finite(a), Q.finite(x) & Q.extended_positive(y)) is None assert ask(Q.finite(a), Q.positive(x) & Q.extended_positive(y)) is None assert ask(Q.finite(a), Q.positive(x) & ~Q.positive(y)) is None assert ask(Q.finite(a), Q.finite(x) & ~Q.positive(x) & Q.extended_positive(y)) is None assert ask(Q.finite(a), Q.finite(x) & ~Q.positive(x) & ~Q.positive(y)) is None # U + U assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)) is None assert ask(Q.finite(a), Q.positive_infinite(x) & ~Q.finite(y)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.positive_infinite(y)) is None assert ask(Q.finite(a), Q.positive_infinite(x) & Q.positive_infinite(y)) is False assert ask(Q.finite(a), Q.positive_infinite(x) & ~Q.finite(y) & ~Q.extended_positive(y)) is None assert ask(Q.finite(a), ~Q.finite(x) & ~Q.extended_positive(x) & Q.positive_infinite(y)) is None assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & ~Q.extended_positive(x) & ~Q.extended_positive(y)) is False # U + ? assert ask(Q.finite(a), ~Q.finite(y)) is None assert ask(Q.finite(a), Q.extended_positive(x) & ~Q.finite(y)) is None assert ask(Q.finite(a), Q.positive_infinite(y)) is None assert ask(Q.finite(a), Q.extended_positive(x) & Q.positive_infinite(y)) is False assert ask(Q.finite(a), Q.extended_positive(x) & ~Q.finite(y) & ~Q.extended_positive(y)) is None assert ask(Q.finite(a), ~Q.extended_positive(x) & Q.positive_infinite(y)) is None assert ask(Q.finite(a), ~Q.extended_positive(x) & ~Q.finite(y) & ~Q.extended_positive(y)) is False # ? + ? assert ask(Q.finite(a)) is None assert ask(Q.finite(a), Q.extended_positive(x)) is None assert ask(Q.finite(a), Q.extended_positive(y)) is None assert ask(Q.finite(a), Q.extended_positive(x) & Q.extended_positive(y)) is None assert ask(Q.finite(a), Q.extended_positive(x) & ~Q.extended_positive(y)) is None assert ask(Q.finite(a), ~Q.extended_positive(x) & Q.extended_positive(y)) is None assert ask(Q.finite(a), ~Q.extended_positive(x) & ~Q.extended_positive(y)) is None x, y, z = symbols('x,y,z') a = x + y + z x, y, z = a.args assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) & Q.negative(z)) is True assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) & Q.finite(z)) is True assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) & Q.positive(z)) is True assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) & Q.negative_infinite(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) & ~Q.finite(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) & Q.positive_infinite(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.negative(y)) is None assert ask(Q.finite(a), Q.negative(x) & Q.negative(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.finite(y) & Q.finite(z)) is True assert ask(Q.finite(a), Q.negative(x) & Q.finite(y) & Q.positive(z)) is True assert ask(Q.finite(a), Q.negative(x) & Q.finite(y) & Q.negative_infinite(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.finite(y) & ~Q.finite(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.finite(y) & Q.positive_infinite(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.finite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.finite(y)) is None assert ask(Q.finite(a), Q.negative(x) & Q.finite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.positive(y) & Q.positive(z)) is True assert ask(Q.finite(a), Q.negative(x) & Q.positive(y) & Q.negative_infinite(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.positive(y) & ~Q.finite(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.positive(y) & Q.positive_infinite(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.positive(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.extended_positive(y) & Q.finite(y)) is None assert ask(Q.finite(a), Q.negative(x) & Q.positive(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.negative_infinite(y) & Q.negative_infinite(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.negative_infinite(y) & ~Q.finite(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.negative_infinite(y) & Q.positive_infinite(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.negative_infinite(y) & Q.extended_negative(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.negative_infinite(y)) is None assert ask(Q.finite(a), Q.negative(x) & Q.negative_infinite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(y) & ~Q.finite(z)) is None assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(y) & Q.positive_infinite(z)) is None assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(y)) is None assert ask(Q.finite(a), Q.negative(x) & ~Q.finite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.positive_infinite(y) & Q.positive_infinite(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.positive_infinite(y) & Q.negative_infinite(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.positive_infinite(y)) is None assert ask(Q.finite(a), Q.negative(x) & Q.positive_infinite(y) & Q.extended_positive(z)) is False assert ask(Q.finite(a), Q.negative(x) & Q.extended_negative(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.extended_negative(y)) is None assert ask(Q.finite(a), Q.negative(x) & Q.extended_negative(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative(x)) is None assert ask(Q.finite(a), Q.negative(x) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative(x) & Q.extended_positive(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) & Q.finite(z)) is True assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) & Q.positive(z)) is True assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) & Q.negative_infinite(z)) is False assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) & ~Q.finite(z)) is False assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) & Q.positive_infinite(z)) is False assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)) is None assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.finite(x) & Q.positive(y) & Q.positive(z)) is True assert ask(Q.finite(a), Q.finite(x) & Q.positive(y) & Q.negative_infinite(z)) is False assert ask(Q.finite(a), Q.finite(x) & Q.positive(y) & ~Q.finite(z)) is False assert ask(Q.finite(a), Q.finite(x) & Q.positive(y) & Q.positive_infinite(z)) is False assert ask(Q.finite(a), Q.finite(x) & Q.positive(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.finite(x) & Q.positive(y)) is None assert ask(Q.finite(a), Q.finite(x) & Q.positive(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.finite(x) & Q.negative_infinite(y) & Q.negative_infinite(z)) is False assert ask(Q.finite(a), Q.finite(x) & Q.negative_infinite(y) & ~Q.finite(z)) is None assert ask(Q.finite(a), Q.finite(x) & Q.negative_infinite(y) & Q.positive_infinite(z)) is None assert ask(Q.finite(a), Q.finite(x) & Q.negative_infinite(y) & Q.extended_negative(z)) is False assert ask(Q.finite(a), Q.finite(x) & Q.negative_infinite(y)) is None assert ask(Q.finite(a), Q.finite(x) & Q.negative_infinite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y) & ~Q.finite(z)) is None assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y) & Q.positive_infinite(z)) is None assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)) is None assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.finite(x) & Q.positive_infinite(y) & Q.positive_infinite(z)) is False assert ask(Q.finite(a), Q.finite(x) & Q.positive_infinite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.finite(x) & Q.positive_infinite(y)) is None assert ask(Q.finite(a), Q.finite(x) & Q.positive_infinite(y) & Q.extended_positive(z)) is False assert ask(Q.finite(a), Q.finite(x) & Q.extended_negative(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.finite(x) & Q.extended_negative(y)) is None assert ask(Q.finite(a), Q.finite(x) & Q.extended_negative(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.finite(x)) is None assert ask(Q.finite(a), Q.finite(x) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.finite(x) & Q.extended_positive(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.positive(x) & Q.positive(y) & Q.positive(z)) is True assert ask(Q.finite(a), Q.positive(x) & Q.positive(y) & Q.negative_infinite(z)) is False assert ask(Q.finite(a), Q.positive(x) & Q.positive(y) & ~Q.finite(z)) is False assert ask(Q.finite(a), Q.positive(x) & Q.positive(y) & Q.positive_infinite(z)) is False assert ask(Q.finite(a), Q.positive(x) & Q.positive(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.positive(x) & Q.positive(y)) is None assert ask(Q.finite(a), Q.positive(x) & Q.positive(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.positive(x) & Q.negative_infinite(y) & Q.negative_infinite(z)) is False assert ask(Q.finite(a), Q.positive(x) & Q.negative_infinite(y) & ~Q.finite(z)) is None assert ask(Q.finite(a), Q.positive(x) & Q.negative_infinite(y) & Q.positive_infinite(z)) is None assert ask(Q.finite(a), Q.positive(x) & Q.negative_infinite(y) & Q.extended_negative(z)) is False assert ask(Q.finite(a), Q.positive(x) & Q.negative_infinite(y)) is None assert ask(Q.finite(a), Q.positive(x) & Q.negative_infinite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y) & ~Q.finite(z)) is None assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y) & Q.positive_infinite(z)) is None assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y)) is None assert ask(Q.finite(a), Q.positive(x) & ~Q.finite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.positive(x) & Q.positive_infinite(y) & Q.positive_infinite(z)) is False assert ask(Q.finite(a), Q.positive(x) & Q.positive_infinite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.positive(x) & Q.positive_infinite(y)) is None assert ask(Q.finite(a), Q.positive(x) & Q.positive_infinite(y) & Q.extended_positive(z)) is False assert ask(Q.finite(a), Q.positive(x) & Q.extended_negative(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.positive(x) & Q.extended_negative(y)) is None assert ask(Q.finite(a), Q.positive(x) & Q.extended_negative(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.positive(x)) is None assert ask(Q.finite(a), Q.positive(x) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.positive(x) & Q.extended_positive(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.negative_infinite(y) & Q.negative_infinite(z)) is False assert ask(Q.finite(a), Q.negative_infinite(x) & Q.negative_infinite(y) & ~Q.finite(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.negative_infinite(y)& Q.positive_infinite(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.negative_infinite(y) & Q.extended_negative(z)) is False assert ask(Q.finite(a), Q.negative_infinite(x) & Q.negative_infinite(y)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.negative_infinite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & ~Q.finite(y) & ~Q.finite(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & ~Q.finite(y) & Q.positive_infinite(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & ~Q.finite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & ~Q.finite(y)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & ~Q.finite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.positive_infinite(y) & Q.positive_infinite(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.positive_infinite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.positive_infinite(y)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.positive_infinite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.extended_negative(y) & Q.extended_negative(z)) is False assert ask(Q.finite(a), Q.negative_infinite(x) & Q.extended_negative(y)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.extended_negative(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.negative_infinite(x) & Q.extended_positive(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & ~Q.finite(z)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.positive_infinite(z) & ~Q.finite(z)) is None assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)) is None assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.positive_infinite(y) & Q.positive_infinite(z)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.positive_infinite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.positive_infinite(y)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.positive_infinite(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.extended_negative(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.extended_negative(y)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.extended_negative(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), ~Q.finite(x)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.extended_positive(z)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.extended_positive(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.positive_infinite(x) & Q.positive_infinite(y) & Q.positive_infinite(z)) is False assert ask(Q.finite(a), Q.positive_infinite(x) & Q.positive_infinite(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.positive_infinite(x) & Q.positive_infinite(y)) is None assert ask(Q.finite(a), Q.positive_infinite(x) & Q.positive_infinite(y) & Q.extended_positive(z)) is False assert ask(Q.finite(a), Q.positive_infinite(x) & Q.extended_negative(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.positive_infinite(x) & Q.extended_negative(y)) is None assert ask(Q.finite(a), Q.positive_infinite(x) & Q.extended_negative(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.positive_infinite(x)) is None assert ask(Q.finite(a), Q.positive_infinite(x) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.positive_infinite(x) & Q.extended_positive(y) & Q.extended_positive(z)) is False assert ask(Q.finite(a), Q.extended_negative(x) & Q.extended_negative(y) & Q.extended_negative(z)) is None assert ask(Q.finite(a), Q.extended_negative(x) & Q.extended_negative(y)) is None assert ask(Q.finite(a), Q.extended_negative(x) & Q.extended_negative(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.extended_negative(x)) is None assert ask(Q.finite(a), Q.extended_negative(x) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.extended_negative(x) & Q.extended_positive(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a)) is None assert ask(Q.finite(a), Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.extended_positive(y) & Q.extended_positive(z)) is None assert ask(Q.finite(a), Q.extended_positive(x) & Q.extended_positive(y) & Q.extended_positive(z)) is None assert ask(Q.finite(2*x)) is None assert ask(Q.finite(2*x), Q.finite(x)) is True x, y, z = symbols('x,y,z') a = x*y x, y = a.args assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)) is True assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)) is False assert ask(Q.finite(a), Q.finite(x)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(y)) is False assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)) is False assert ask(Q.finite(a), ~Q.finite(x)) is None assert ask(Q.finite(a), Q.finite(y)) is None assert ask(Q.finite(a), ~Q.finite(y)) is None assert ask(Q.finite(a)) is None a = x*y*z x, y, z = a.args assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) & Q.finite(z)) is True assert ask(Q.finite(a), Q.finite(x) & Q.finite(y) & ~Q.finite(z)) is False assert ask(Q.finite(a), Q.finite(x) & Q.finite(y)) is None assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y) & Q.finite(z)) is False assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y) & ~Q.finite(z)) is False assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(y)) is None assert ask(Q.finite(a), Q.finite(x) & Q.finite(z)) is None assert ask(Q.finite(a), Q.finite(x) & ~Q.finite(z)) is None assert ask(Q.finite(a), Q.finite(x)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(y) & Q.finite(z)) is False assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(y) & ~Q.finite(z)) is False assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(y)) is None assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & Q.finite(z)) is False assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y) & ~Q.finite(z)) is False assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(y)) is None assert ask(Q.finite(a), ~Q.finite(x) & Q.finite(z)) is None assert ask(Q.finite(a), ~Q.finite(x) & ~Q.finite(z)) is None assert ask(Q.finite(a), ~Q.finite(x)) is None assert ask(Q.finite(a), Q.finite(y) & Q.finite(z)) is None assert ask(Q.finite(a), Q.finite(y) & ~Q.finite(z)) is None assert ask(Q.finite(a), Q.finite(y)) is None assert ask(Q.finite(a), ~Q.finite(y) & Q.finite(z)) is None assert ask(Q.finite(a), ~Q.finite(y) & ~Q.finite(z)) is None assert ask(Q.finite(a), ~Q.finite(y)) is None assert ask(Q.finite(a), Q.finite(z)) is None assert ask(Q.finite(a), ~Q.finite(z)) is None assert ask(Q.finite(a), ~Q.finite(z) & Q.extended_nonzero(x) & Q.extended_nonzero(y) & Q.extended_nonzero(z)) is None assert ask(Q.finite(a), Q.extended_nonzero(x) & ~Q.finite(y) & Q.extended_nonzero(y) & ~Q.finite(z) & Q.extended_nonzero(z)) is False x, y, z = symbols('x,y,z') assert ask(Q.finite(x**2)) is None assert ask(Q.finite(2**x)) is None assert ask(Q.finite(2**x), Q.finite(x)) is True assert ask(Q.finite(x**x)) is None assert ask(Q.finite(S.Half ** x)) is None assert ask(Q.finite(S.Half ** x), Q.extended_positive(x)) is True assert ask(Q.finite(S.Half ** x), Q.extended_negative(x)) is None assert ask(Q.finite(2**x), Q.extended_negative(x)) is True assert ask(Q.finite(sqrt(x))) is None assert ask(Q.finite(2**x), ~Q.finite(x)) is False assert ask(Q.finite(x**2), ~Q.finite(x)) is False # sign function assert ask(Q.finite(sign(x))) is True assert ask(Q.finite(sign(x)), ~Q.finite(x)) is True # exponential functions assert ask(Q.finite(log(x))) is None assert ask(Q.finite(log(x)), Q.finite(x)) is None assert ask(Q.finite(log(x)), ~Q.zero(x)) is True assert ask(Q.finite(log(x)), Q.infinite(x)) is False assert ask(Q.finite(log(x)), Q.zero(x)) is False assert ask(Q.finite(exp(x))) is None assert ask(Q.finite(exp(x)), Q.finite(x)) is True assert ask(Q.finite(exp(2))) is True # trigonometric functions assert ask(Q.finite(sin(x))) is True assert ask(Q.finite(sin(x)), ~Q.finite(x)) is True assert ask(Q.finite(cos(x))) is True assert ask(Q.finite(cos(x)), ~Q.finite(x)) is True assert ask(Q.finite(2*sin(x))) is True assert ask(Q.finite(sin(x)**2)) is True assert ask(Q.finite(cos(x)**2)) is True assert ask(Q.finite(cos(x) + sin(x))) is True @XFAIL def test_bounded_xfail(): """We need to support relations in ask for this to work""" assert ask(Q.finite(sin(x)**x)) is True assert ask(Q.finite(cos(x)**x)) is True def test_commutative(): """By default objects are Q.commutative that is why it returns True for both key=True and key=False""" assert ask(Q.commutative(x)) is True assert ask(Q.commutative(x), ~Q.commutative(x)) is False assert ask(Q.commutative(x), Q.complex(x)) is True assert ask(Q.commutative(x), Q.imaginary(x)) is True assert ask(Q.commutative(x), Q.real(x)) is True assert ask(Q.commutative(x), Q.positive(x)) is True assert ask(Q.commutative(x), ~Q.commutative(y)) is True assert ask(Q.commutative(2*x)) is True assert ask(Q.commutative(2*x), ~Q.commutative(x)) is False assert ask(Q.commutative(x + 1)) is True assert ask(Q.commutative(x + 1), ~Q.commutative(x)) is False assert ask(Q.commutative(x**2)) is True assert ask(Q.commutative(x**2), ~Q.commutative(x)) is False assert ask(Q.commutative(log(x))) is True @_both_exp_pow def test_complex(): assert ask(Q.complex(x)) is None assert ask(Q.complex(x), Q.complex(x)) is True assert ask(Q.complex(x), Q.complex(y)) is None assert ask(Q.complex(x), ~Q.complex(x)) is False assert ask(Q.complex(x), Q.real(x)) is True assert ask(Q.complex(x), ~Q.real(x)) is None assert ask(Q.complex(x), Q.rational(x)) is True assert ask(Q.complex(x), Q.irrational(x)) is True assert ask(Q.complex(x), Q.positive(x)) is True assert ask(Q.complex(x), Q.imaginary(x)) is True assert ask(Q.complex(x), Q.algebraic(x)) is True # a+b assert ask(Q.complex(x + 1), Q.complex(x)) is True assert ask(Q.complex(x + 1), Q.real(x)) is True assert ask(Q.complex(x + 1), Q.rational(x)) is True assert ask(Q.complex(x + 1), Q.irrational(x)) is True assert ask(Q.complex(x + 1), Q.imaginary(x)) is True assert ask(Q.complex(x + 1), Q.integer(x)) is True assert ask(Q.complex(x + 1), Q.even(x)) is True assert ask(Q.complex(x + 1), Q.odd(x)) is True assert ask(Q.complex(x + y), Q.complex(x) & Q.complex(y)) is True assert ask(Q.complex(x + y), Q.real(x) & Q.imaginary(y)) is True # a*x +b assert ask(Q.complex(2*x + 1), Q.complex(x)) is True assert ask(Q.complex(2*x + 1), Q.real(x)) is True assert ask(Q.complex(2*x + 1), Q.positive(x)) is True assert ask(Q.complex(2*x + 1), Q.rational(x)) is True assert ask(Q.complex(2*x + 1), Q.irrational(x)) is True assert ask(Q.complex(2*x + 1), Q.imaginary(x)) is True assert ask(Q.complex(2*x + 1), Q.integer(x)) is True assert ask(Q.complex(2*x + 1), Q.even(x)) is True assert ask(Q.complex(2*x + 1), Q.odd(x)) is True # x**2 assert ask(Q.complex(x**2), Q.complex(x)) is True assert ask(Q.complex(x**2), Q.real(x)) is True assert ask(Q.complex(x**2), Q.positive(x)) is True assert ask(Q.complex(x**2), Q.rational(x)) is True assert ask(Q.complex(x**2), Q.irrational(x)) is True assert ask(Q.complex(x**2), Q.imaginary(x)) is True assert ask(Q.complex(x**2), Q.integer(x)) is True assert ask(Q.complex(x**2), Q.even(x)) is True assert ask(Q.complex(x**2), Q.odd(x)) is True # 2**x assert ask(Q.complex(2**x), Q.complex(x)) is True assert ask(Q.complex(2**x), Q.real(x)) is True assert ask(Q.complex(2**x), Q.positive(x)) is True assert ask(Q.complex(2**x), Q.rational(x)) is True assert ask(Q.complex(2**x), Q.irrational(x)) is True assert ask(Q.complex(2**x), Q.imaginary(x)) is True assert ask(Q.complex(2**x), Q.integer(x)) is True assert ask(Q.complex(2**x), Q.even(x)) is True assert ask(Q.complex(2**x), Q.odd(x)) is True assert ask(Q.complex(x**y), Q.complex(x) & Q.complex(y)) is True # trigonometric expressions assert ask(Q.complex(sin(x))) is True assert ask(Q.complex(sin(2*x + 1))) is True assert ask(Q.complex(cos(x))) is True assert ask(Q.complex(cos(2*x + 1))) is True # exponential assert ask(Q.complex(exp(x))) is True assert ask(Q.complex(exp(x))) is True # Q.complexes assert ask(Q.complex(Abs(x))) is True assert ask(Q.complex(re(x))) is True assert ask(Q.complex(im(x))) is True def test_even_query(): assert ask(Q.even(x)) is None assert ask(Q.even(x), Q.integer(x)) is None assert ask(Q.even(x), ~Q.integer(x)) is False assert ask(Q.even(x), Q.rational(x)) is None assert ask(Q.even(x), Q.positive(x)) is None assert ask(Q.even(2*x)) is None assert ask(Q.even(2*x), Q.integer(x)) is True assert ask(Q.even(2*x), Q.even(x)) is True assert ask(Q.even(2*x), Q.irrational(x)) is False assert ask(Q.even(2*x), Q.odd(x)) is True assert ask(Q.even(2*x), ~Q.integer(x)) is None assert ask(Q.even(3*x), Q.integer(x)) is None assert ask(Q.even(3*x), Q.even(x)) is True assert ask(Q.even(3*x), Q.odd(x)) is False assert ask(Q.even(x + 1), Q.odd(x)) is True assert ask(Q.even(x + 1), Q.even(x)) is False assert ask(Q.even(x + 2), Q.odd(x)) is False assert ask(Q.even(x + 2), Q.even(x)) is True assert ask(Q.even(7 - x), Q.odd(x)) is True assert ask(Q.even(7 + x), Q.odd(x)) is True assert ask(Q.even(x + y), Q.odd(x) & Q.odd(y)) is True assert ask(Q.even(x + y), Q.odd(x) & Q.even(y)) is False assert ask(Q.even(x + y), Q.even(x) & Q.even(y)) is True assert ask(Q.even(2*x + 1), Q.integer(x)) is False assert ask(Q.even(2*x*y), Q.rational(x) & Q.rational(x)) is None assert ask(Q.even(2*x*y), Q.irrational(x) & Q.irrational(x)) is None assert ask(Q.even(x + y + z), Q.odd(x) & Q.odd(y) & Q.even(z)) is True assert ask(Q.even(x + y + z + t), Q.odd(x) & Q.odd(y) & Q.even(z) & Q.integer(t)) is None assert ask(Q.even(Abs(x)), Q.even(x)) is True assert ask(Q.even(Abs(x)), ~Q.even(x)) is None assert ask(Q.even(re(x)), Q.even(x)) is True assert ask(Q.even(re(x)), ~Q.even(x)) is None assert ask(Q.even(im(x)), Q.even(x)) is True assert ask(Q.even(im(x)), Q.real(x)) is True assert ask(Q.even((-1)**n), Q.integer(n)) is False assert ask(Q.even(k**2), Q.even(k)) is True assert ask(Q.even(n**2), Q.odd(n)) is False assert ask(Q.even(2**k), Q.even(k)) is None assert ask(Q.even(x**2)) is None assert ask(Q.even(k**m), Q.even(k) & Q.integer(m) & ~Q.negative(m)) is None assert ask(Q.even(n**m), Q.odd(n) & Q.integer(m) & ~Q.negative(m)) is False assert ask(Q.even(k**p), Q.even(k) & Q.integer(p) & Q.positive(p)) is True assert ask(Q.even(n**p), Q.odd(n) & Q.integer(p) & Q.positive(p)) is False assert ask(Q.even(m**k), Q.even(k) & Q.integer(m) & ~Q.negative(m)) is None assert ask(Q.even(p**k), Q.even(k) & Q.integer(p) & Q.positive(p)) is None assert ask(Q.even(m**n), Q.odd(n) & Q.integer(m) & ~Q.negative(m)) is None assert ask(Q.even(p**n), Q.odd(n) & Q.integer(p) & Q.positive(p)) is None assert ask(Q.even(k**x), Q.even(k)) is None assert ask(Q.even(n**x), Q.odd(n)) is None assert ask(Q.even(x*y), Q.integer(x) & Q.integer(y)) is None assert ask(Q.even(x*x), Q.integer(x)) is None assert ask(Q.even(x*(x + y)), Q.integer(x) & Q.odd(y)) is True assert ask(Q.even(x*(x + y)), Q.integer(x) & Q.even(y)) is None @XFAIL def test_evenness_in_ternary_integer_product_with_odd(): # Tests that oddness inference is independent of term ordering. # Term ordering at the point of testing depends on SymPy's symbol order, so # we try to force a different order by modifying symbol names. assert ask(Q.even(x*y*(y + z)), Q.integer(x) & Q.integer(y) & Q.odd(z)) is True assert ask(Q.even(y*x*(x + z)), Q.integer(x) & Q.integer(y) & Q.odd(z)) is True def test_evenness_in_ternary_integer_product_with_even(): assert ask(Q.even(x*y*(y + z)), Q.integer(x) & Q.integer(y) & Q.even(z)) is None def test_extended_real(): assert ask(Q.extended_real(x), Q.positive_infinite(x)) is True assert ask(Q.extended_real(x), Q.positive(x)) is True assert ask(Q.extended_real(x), Q.zero(x)) is True assert ask(Q.extended_real(x), Q.negative(x)) is True assert ask(Q.extended_real(x), Q.negative_infinite(x)) is True assert ask(Q.extended_real(-x), Q.positive(x)) is True assert ask(Q.extended_real(-x), Q.negative(x)) is True assert ask(Q.extended_real(x + S.Infinity), Q.real(x)) is True assert ask(Q.extended_real(x), Q.infinite(x)) is None @_both_exp_pow def test_rational(): assert ask(Q.rational(x), Q.integer(x)) is True assert ask(Q.rational(x), Q.irrational(x)) is False assert ask(Q.rational(x), Q.real(x)) is None assert ask(Q.rational(x), Q.positive(x)) is None assert ask(Q.rational(x), Q.negative(x)) is None assert ask(Q.rational(x), Q.nonzero(x)) is None assert ask(Q.rational(x), ~Q.algebraic(x)) is False assert ask(Q.rational(2*x), Q.rational(x)) is True assert ask(Q.rational(2*x), Q.integer(x)) is True assert ask(Q.rational(2*x), Q.even(x)) is True assert ask(Q.rational(2*x), Q.odd(x)) is True assert ask(Q.rational(2*x), Q.irrational(x)) is False assert ask(Q.rational(x/2), Q.rational(x)) is True assert ask(Q.rational(x/2), Q.integer(x)) is True assert ask(Q.rational(x/2), Q.even(x)) is True assert ask(Q.rational(x/2), Q.odd(x)) is True assert ask(Q.rational(x/2), Q.irrational(x)) is False assert ask(Q.rational(1/x), Q.rational(x)) is True assert ask(Q.rational(1/x), Q.integer(x)) is True assert ask(Q.rational(1/x), Q.even(x)) is True assert ask(Q.rational(1/x), Q.odd(x)) is True assert ask(Q.rational(1/x), Q.irrational(x)) is False assert ask(Q.rational(2/x), Q.rational(x)) is True assert ask(Q.rational(2/x), Q.integer(x)) is True assert ask(Q.rational(2/x), Q.even(x)) is True assert ask(Q.rational(2/x), Q.odd(x)) is True assert ask(Q.rational(2/x), Q.irrational(x)) is False assert ask(Q.rational(x), ~Q.algebraic(x)) is False # with multiple symbols assert ask(Q.rational(x*y), Q.irrational(x) & Q.irrational(y)) is None assert ask(Q.rational(y/x), Q.rational(x) & Q.rational(y)) is True assert ask(Q.rational(y/x), Q.integer(x) & Q.rational(y)) is True assert ask(Q.rational(y/x), Q.even(x) & Q.rational(y)) is True assert ask(Q.rational(y/x), Q.odd(x) & Q.rational(y)) is True assert ask(Q.rational(y/x), Q.irrational(x) & Q.rational(y)) is False for f in [exp, sin, tan, asin, atan, cos]: assert ask(Q.rational(f(7))) is False assert ask(Q.rational(f(7, evaluate=False))) is False assert ask(Q.rational(f(0, evaluate=False))) is True assert ask(Q.rational(f(x)), Q.rational(x)) is None assert ask(Q.rational(f(x)), Q.rational(x) & Q.nonzero(x)) is False for g in [log, acos]: assert ask(Q.rational(g(7))) is False assert ask(Q.rational(g(7, evaluate=False))) is False assert ask(Q.rational(g(1, evaluate=False))) is True assert ask(Q.rational(g(x)), Q.rational(x)) is None assert ask(Q.rational(g(x)), Q.rational(x) & Q.nonzero(x - 1)) is False for h in [cot, acot]: assert ask(Q.rational(h(7))) is False assert ask(Q.rational(h(7, evaluate=False))) is False assert ask(Q.rational(h(x)), Q.rational(x)) is False def test_hermitian(): assert ask(Q.hermitian(x)) is None assert ask(Q.hermitian(x), Q.antihermitian(x)) is None assert ask(Q.hermitian(x), Q.imaginary(x)) is False assert ask(Q.hermitian(x), Q.prime(x)) is True assert ask(Q.hermitian(x), Q.real(x)) is True assert ask(Q.hermitian(x), Q.zero(x)) is True assert ask(Q.hermitian(x + 1), Q.antihermitian(x)) is None assert ask(Q.hermitian(x + 1), Q.complex(x)) is None assert ask(Q.hermitian(x + 1), Q.hermitian(x)) is True assert ask(Q.hermitian(x + 1), Q.imaginary(x)) is False assert ask(Q.hermitian(x + 1), Q.real(x)) is True assert ask(Q.hermitian(x + I), Q.antihermitian(x)) is None assert ask(Q.hermitian(x + I), Q.complex(x)) is None assert ask(Q.hermitian(x + I), Q.hermitian(x)) is False assert ask(Q.hermitian(x + I), Q.imaginary(x)) is None assert ask(Q.hermitian(x + I), Q.real(x)) is False assert ask( Q.hermitian(x + y), Q.antihermitian(x) & Q.antihermitian(y)) is None assert ask(Q.hermitian(x + y), Q.antihermitian(x) & Q.complex(y)) is None assert ask( Q.hermitian(x + y), Q.antihermitian(x) & Q.hermitian(y)) is None assert ask(Q.hermitian(x + y), Q.antihermitian(x) & Q.imaginary(y)) is None assert ask(Q.hermitian(x + y), Q.antihermitian(x) & Q.real(y)) is None assert ask(Q.hermitian(x + y), Q.hermitian(x) & Q.complex(y)) is None assert ask(Q.hermitian(x + y), Q.hermitian(x) & Q.hermitian(y)) is True assert ask(Q.hermitian(x + y), Q.hermitian(x) & Q.imaginary(y)) is False assert ask(Q.hermitian(x + y), Q.hermitian(x) & Q.real(y)) is True assert ask(Q.hermitian(x + y), Q.imaginary(x) & Q.complex(y)) is None assert ask(Q.hermitian(x + y), Q.imaginary(x) & Q.imaginary(y)) is None assert ask(Q.hermitian(x + y), Q.imaginary(x) & Q.real(y)) is False assert ask(Q.hermitian(x + y), Q.real(x) & Q.complex(y)) is None assert ask(Q.hermitian(x + y), Q.real(x) & Q.real(y)) is True assert ask(Q.hermitian(I*x), Q.antihermitian(x)) is True assert ask(Q.hermitian(I*x), Q.complex(x)) is None assert ask(Q.hermitian(I*x), Q.hermitian(x)) is False assert ask(Q.hermitian(I*x), Q.imaginary(x)) is True assert ask(Q.hermitian(I*x), Q.real(x)) is False assert ask(Q.hermitian(x*y), Q.hermitian(x) & Q.real(y)) is True assert ask( Q.hermitian(x + y + z), Q.real(x) & Q.real(y) & Q.real(z)) is True assert ask(Q.hermitian(x + y + z), Q.real(x) & Q.real(y) & Q.imaginary(z)) is False assert ask(Q.hermitian(x + y + z), Q.real(x) & Q.imaginary(y) & Q.imaginary(z)) is None assert ask(Q.hermitian(x + y + z), Q.imaginary(x) & Q.imaginary(y) & Q.imaginary(z)) is None assert ask(Q.antihermitian(x)) is None assert ask(Q.antihermitian(x), Q.real(x)) is False assert ask(Q.antihermitian(x), Q.prime(x)) is False assert ask(Q.antihermitian(x + 1), Q.antihermitian(x)) is False assert ask(Q.antihermitian(x + 1), Q.complex(x)) is None assert ask(Q.antihermitian(x + 1), Q.hermitian(x)) is None assert ask(Q.antihermitian(x + 1), Q.imaginary(x)) is False assert ask(Q.antihermitian(x + 1), Q.real(x)) is None assert ask(Q.antihermitian(x + I), Q.antihermitian(x)) is True assert ask(Q.antihermitian(x + I), Q.complex(x)) is None assert ask(Q.antihermitian(x + I), Q.hermitian(x)) is None assert ask(Q.antihermitian(x + I), Q.imaginary(x)) is True assert ask(Q.antihermitian(x + I), Q.real(x)) is False assert ask(Q.antihermitian(x), Q.zero(x)) is True assert ask( Q.antihermitian(x + y), Q.antihermitian(x) & Q.antihermitian(y) ) is True assert ask( Q.antihermitian(x + y), Q.antihermitian(x) & Q.complex(y)) is None assert ask( Q.antihermitian(x + y), Q.antihermitian(x) & Q.hermitian(y)) is None assert ask( Q.antihermitian(x + y), Q.antihermitian(x) & Q.imaginary(y)) is True assert ask(Q.antihermitian(x + y), Q.antihermitian(x) & Q.real(y) ) is False assert ask(Q.antihermitian(x + y), Q.hermitian(x) & Q.complex(y)) is None assert ask(Q.antihermitian(x + y), Q.hermitian(x) & Q.hermitian(y) ) is None assert ask( Q.antihermitian(x + y), Q.hermitian(x) & Q.imaginary(y)) is None assert ask(Q.antihermitian(x + y), Q.hermitian(x) & Q.real(y)) is None assert ask(Q.antihermitian(x + y), Q.imaginary(x) & Q.complex(y)) is None assert ask(Q.antihermitian(x + y), Q.imaginary(x) & Q.imaginary(y)) is True assert ask(Q.antihermitian(x + y), Q.imaginary(x) & Q.real(y)) is False assert ask(Q.antihermitian(x + y), Q.real(x) & Q.complex(y)) is None assert ask(Q.antihermitian(x + y), Q.real(x) & Q.real(y)) is None assert ask(Q.antihermitian(I*x), Q.real(x)) is True assert ask(Q.antihermitian(I*x), Q.antihermitian(x)) is False assert ask(Q.antihermitian(I*x), Q.complex(x)) is None assert ask(Q.antihermitian(x*y), Q.antihermitian(x) & Q.real(y)) is True assert ask(Q.antihermitian(x + y + z), Q.real(x) & Q.real(y) & Q.real(z)) is None assert ask(Q.antihermitian(x + y + z), Q.real(x) & Q.real(y) & Q.imaginary(z)) is None assert ask(Q.antihermitian(x + y + z), Q.real(x) & Q.imaginary(y) & Q.imaginary(z)) is False assert ask(Q.antihermitian(x + y + z), Q.imaginary(x) & Q.imaginary(y) & Q.imaginary(z)) is True @_both_exp_pow def test_imaginary(): assert ask(Q.imaginary(x)) is None assert ask(Q.imaginary(x), Q.real(x)) is False assert ask(Q.imaginary(x), Q.prime(x)) is False assert ask(Q.imaginary(x + 1), Q.real(x)) is False assert ask(Q.imaginary(x + 1), Q.imaginary(x)) is False assert ask(Q.imaginary(x + I), Q.real(x)) is False assert ask(Q.imaginary(x + I), Q.imaginary(x)) is True assert ask(Q.imaginary(x + y), Q.imaginary(x) & Q.imaginary(y)) is True assert ask(Q.imaginary(x + y), Q.real(x) & Q.real(y)) is False assert ask(Q.imaginary(x + y), Q.imaginary(x) & Q.real(y)) is False assert ask(Q.imaginary(x + y), Q.complex(x) & Q.real(y)) is None assert ask( Q.imaginary(x + y + z), Q.real(x) & Q.real(y) & Q.real(z)) is False assert ask(Q.imaginary(x + y + z), Q.real(x) & Q.real(y) & Q.imaginary(z)) is None assert ask(Q.imaginary(x + y + z), Q.real(x) & Q.imaginary(y) & Q.imaginary(z)) is False assert ask(Q.imaginary(I*x), Q.real(x)) is True assert ask(Q.imaginary(I*x), Q.imaginary(x)) is False assert ask(Q.imaginary(I*x), Q.complex(x)) is None assert ask(Q.imaginary(x*y), Q.imaginary(x) & Q.real(y)) is True assert ask(Q.imaginary(x*y), Q.real(x) & Q.real(y)) is False assert ask(Q.imaginary(I**x), Q.negative(x)) is None assert ask(Q.imaginary(I**x), Q.positive(x)) is None assert ask(Q.imaginary(I**x), Q.even(x)) is False assert ask(Q.imaginary(I**x), Q.odd(x)) is True assert ask(Q.imaginary(I**x), Q.imaginary(x)) is False assert ask(Q.imaginary((2*I)**x), Q.imaginary(x)) is False assert ask(Q.imaginary(x**0), Q.imaginary(x)) is False assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.imaginary(y)) is None assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.real(y)) is None assert ask(Q.imaginary(x**y), Q.real(x) & Q.imaginary(y)) is None assert ask(Q.imaginary(x**y), Q.real(x) & Q.real(y)) is None assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.integer(y)) is None assert ask(Q.imaginary(x**y), Q.imaginary(y) & Q.integer(x)) is None assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.odd(y)) is True assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.rational(y)) is None assert ask(Q.imaginary(x**y), Q.imaginary(x) & Q.even(y)) is False assert ask(Q.imaginary(x**y), Q.real(x) & Q.integer(y)) is False assert ask(Q.imaginary(x**y), Q.positive(x) & Q.real(y)) is False assert ask(Q.imaginary(x**y), Q.negative(x) & Q.real(y)) is None assert ask(Q.imaginary(x**y), Q.negative(x) & Q.real(y) & ~Q.rational(y)) is False assert ask(Q.imaginary(x**y), Q.integer(x) & Q.imaginary(y)) is None assert ask(Q.imaginary(x**y), Q.negative(x) & Q.rational(y) & Q.integer(2*y)) is True assert ask(Q.imaginary(x**y), Q.negative(x) & Q.rational(y) & ~Q.integer(2*y)) is False assert ask(Q.imaginary(x**y), Q.negative(x) & Q.rational(y)) is None assert ask(Q.imaginary(x**y), Q.real(x) & Q.rational(y) & ~Q.integer(2*y)) is False assert ask(Q.imaginary(x**y), Q.real(x) & Q.rational(y) & Q.integer(2*y)) is None # logarithm assert ask(Q.imaginary(log(I))) is True assert ask(Q.imaginary(log(2*I))) is False assert ask(Q.imaginary(log(I + 1))) is False assert ask(Q.imaginary(log(x)), Q.complex(x)) is None assert ask(Q.imaginary(log(x)), Q.imaginary(x)) is None assert ask(Q.imaginary(log(x)), Q.positive(x)) is False assert ask(Q.imaginary(log(exp(x))), Q.complex(x)) is None assert ask(Q.imaginary(log(exp(x))), Q.imaginary(x)) is None # zoo/I/a+I*b assert ask(Q.imaginary(log(exp(I)))) is True # exponential assert ask(Q.imaginary(exp(x)**x), Q.imaginary(x)) is False eq = Pow(exp(pi*I*x, evaluate=False), x, evaluate=False) assert ask(Q.imaginary(eq), Q.even(x)) is False eq = Pow(exp(pi*I*x/2, evaluate=False), x, evaluate=False) assert ask(Q.imaginary(eq), Q.odd(x)) is True assert ask(Q.imaginary(exp(3*I*pi*x)**x), Q.integer(x)) is False assert ask(Q.imaginary(exp(2*pi*I, evaluate=False))) is False assert ask(Q.imaginary(exp(pi*I/2, evaluate=False))) is True # issue 7886 assert ask(Q.imaginary(Pow(x, Rational(1, 4))), Q.real(x) & Q.negative(x)) is False def test_integer(): assert ask(Q.integer(x)) is None assert ask(Q.integer(x), Q.integer(x)) is True assert ask(Q.integer(x), ~Q.integer(x)) is False assert ask(Q.integer(x), ~Q.real(x)) is False assert ask(Q.integer(x), ~Q.positive(x)) is None assert ask(Q.integer(x), Q.even(x) | Q.odd(x)) is True assert ask(Q.integer(2*x), Q.integer(x)) is True assert ask(Q.integer(2*x), Q.even(x)) is True assert ask(Q.integer(2*x), Q.prime(x)) is True assert ask(Q.integer(2*x), Q.rational(x)) is None assert ask(Q.integer(2*x), Q.real(x)) is None assert ask(Q.integer(sqrt(2)*x), Q.integer(x)) is False assert ask(Q.integer(sqrt(2)*x), Q.irrational(x)) is None assert ask(Q.integer(x/2), Q.odd(x)) is False assert ask(Q.integer(x/2), Q.even(x)) is True assert ask(Q.integer(x/3), Q.odd(x)) is None assert ask(Q.integer(x/3), Q.even(x)) is None def test_negative(): assert ask(Q.negative(x), Q.negative(x)) is True assert ask(Q.negative(x), Q.positive(x)) is False assert ask(Q.negative(x), ~Q.real(x)) is False assert ask(Q.negative(x), Q.prime(x)) is False assert ask(Q.negative(x), ~Q.prime(x)) is None assert ask(Q.negative(-x), Q.positive(x)) is True assert ask(Q.negative(-x), ~Q.positive(x)) is None assert ask(Q.negative(-x), Q.negative(x)) is False assert ask(Q.negative(-x), Q.positive(x)) is True assert ask(Q.negative(x - 1), Q.negative(x)) is True assert ask(Q.negative(x + y)) is None assert ask(Q.negative(x + y), Q.negative(x)) is None assert ask(Q.negative(x + y), Q.negative(x) & Q.negative(y)) is True assert ask(Q.negative(x + y), Q.negative(x) & Q.nonpositive(y)) is True assert ask(Q.negative(2 + I)) is False # although this could be False, it is representative of expressions # that don't evaluate to a zero with precision assert ask(Q.negative(cos(I)**2 + sin(I)**2 - 1)) is None assert ask(Q.negative(-I + I*(cos(2)**2 + sin(2)**2))) is None assert ask(Q.negative(x**2)) is None assert ask(Q.negative(x**2), Q.real(x)) is False assert ask(Q.negative(x**1.4), Q.real(x)) is None assert ask(Q.negative(x**I), Q.positive(x)) is None assert ask(Q.negative(x*y)) is None assert ask(Q.negative(x*y), Q.positive(x) & Q.positive(y)) is False assert ask(Q.negative(x*y), Q.positive(x) & Q.negative(y)) is True assert ask(Q.negative(x*y), Q.complex(x) & Q.complex(y)) is None assert ask(Q.negative(x**y)) is None assert ask(Q.negative(x**y), Q.negative(x) & Q.even(y)) is False assert ask(Q.negative(x**y), Q.negative(x) & Q.odd(y)) is True assert ask(Q.negative(x**y), Q.positive(x) & Q.integer(y)) is False assert ask(Q.negative(Abs(x))) is False def test_nonzero(): assert ask(Q.nonzero(x)) is None assert ask(Q.nonzero(x), Q.real(x)) is None assert ask(Q.nonzero(x), Q.positive(x)) is True assert ask(Q.nonzero(x), Q.negative(x)) is True assert ask(Q.nonzero(x), Q.negative(x) | Q.positive(x)) is True assert ask(Q.nonzero(x + y)) is None assert ask(Q.nonzero(x + y), Q.positive(x) & Q.positive(y)) is True assert ask(Q.nonzero(x + y), Q.positive(x) & Q.negative(y)) is None assert ask(Q.nonzero(x + y), Q.negative(x) & Q.negative(y)) is True assert ask(Q.nonzero(2*x)) is None assert ask(Q.nonzero(2*x), Q.positive(x)) is True assert ask(Q.nonzero(2*x), Q.negative(x)) is True assert ask(Q.nonzero(x*y), Q.nonzero(x)) is None assert ask(Q.nonzero(x*y), Q.nonzero(x) & Q.nonzero(y)) is True assert ask(Q.nonzero(x**y), Q.nonzero(x)) is True assert ask(Q.nonzero(Abs(x))) is None assert ask(Q.nonzero(Abs(x)), Q.nonzero(x)) is True assert ask(Q.nonzero(log(exp(2*I)))) is False # although this could be False, it is representative of expressions # that don't evaluate to a zero with precision assert ask(Q.nonzero(cos(1)**2 + sin(1)**2 - 1)) is None def test_zero(): assert ask(Q.zero(x)) is None assert ask(Q.zero(x), Q.real(x)) is None assert ask(Q.zero(x), Q.positive(x)) is False assert ask(Q.zero(x), Q.negative(x)) is False assert ask(Q.zero(x), Q.negative(x) | Q.positive(x)) is False assert ask(Q.zero(x), Q.nonnegative(x) & Q.nonpositive(x)) is True assert ask(Q.zero(x + y)) is None assert ask(Q.zero(x + y), Q.positive(x) & Q.positive(y)) is False assert ask(Q.zero(x + y), Q.positive(x) & Q.negative(y)) is None assert ask(Q.zero(x + y), Q.negative(x) & Q.negative(y)) is False assert ask(Q.zero(2*x)) is None assert ask(Q.zero(2*x), Q.positive(x)) is False assert ask(Q.zero(2*x), Q.negative(x)) is False assert ask(Q.zero(x*y), Q.nonzero(x)) is None assert ask(Q.zero(Abs(x))) is None assert ask(Q.zero(Abs(x)), Q.zero(x)) is True assert ask(Q.integer(x), Q.zero(x)) is True assert ask(Q.even(x), Q.zero(x)) is True assert ask(Q.odd(x), Q.zero(x)) is False assert ask(Q.zero(x), Q.even(x)) is None assert ask(Q.zero(x), Q.odd(x)) is False assert ask(Q.zero(x) | Q.zero(y), Q.zero(x*y)) is True def test_odd_query(): assert ask(Q.odd(x)) is None assert ask(Q.odd(x), Q.odd(x)) is True assert ask(Q.odd(x), Q.integer(x)) is None assert ask(Q.odd(x), ~Q.integer(x)) is False assert ask(Q.odd(x), Q.rational(x)) is None assert ask(Q.odd(x), Q.positive(x)) is None assert ask(Q.odd(-x), Q.odd(x)) is True assert ask(Q.odd(2*x)) is None assert ask(Q.odd(2*x), Q.integer(x)) is False assert ask(Q.odd(2*x), Q.odd(x)) is False assert ask(Q.odd(2*x), Q.irrational(x)) is False assert ask(Q.odd(2*x), ~Q.integer(x)) is None assert ask(Q.odd(3*x), Q.integer(x)) is None assert ask(Q.odd(x/3), Q.odd(x)) is None assert ask(Q.odd(x/3), Q.even(x)) is None assert ask(Q.odd(x + 1), Q.even(x)) is True assert ask(Q.odd(x + 2), Q.even(x)) is False assert ask(Q.odd(x + 2), Q.odd(x)) is True assert ask(Q.odd(3 - x), Q.odd(x)) is False assert ask(Q.odd(3 - x), Q.even(x)) is True assert ask(Q.odd(3 + x), Q.odd(x)) is False assert ask(Q.odd(3 + x), Q.even(x)) is True assert ask(Q.odd(x + y), Q.odd(x) & Q.odd(y)) is False assert ask(Q.odd(x + y), Q.odd(x) & Q.even(y)) is True assert ask(Q.odd(x - y), Q.even(x) & Q.odd(y)) is True assert ask(Q.odd(x - y), Q.odd(x) & Q.odd(y)) is False assert ask(Q.odd(x + y + z), Q.odd(x) & Q.odd(y) & Q.even(z)) is False assert ask(Q.odd(x + y + z + t), Q.odd(x) & Q.odd(y) & Q.even(z) & Q.integer(t)) is None assert ask(Q.odd(2*x + 1), Q.integer(x)) is True assert ask(Q.odd(2*x + y), Q.integer(x) & Q.odd(y)) is True assert ask(Q.odd(2*x + y), Q.integer(x) & Q.even(y)) is False assert ask(Q.odd(2*x + y), Q.integer(x) & Q.integer(y)) is None assert ask(Q.odd(x*y), Q.odd(x) & Q.even(y)) is False assert ask(Q.odd(x*y), Q.odd(x) & Q.odd(y)) is True assert ask(Q.odd(2*x*y), Q.rational(x) & Q.rational(x)) is None assert ask(Q.odd(2*x*y), Q.irrational(x) & Q.irrational(x)) is None assert ask(Q.odd(Abs(x)), Q.odd(x)) is True assert ask(Q.odd((-1)**n), Q.integer(n)) is True assert ask(Q.odd(k**2), Q.even(k)) is False assert ask(Q.odd(n**2), Q.odd(n)) is True assert ask(Q.odd(3**k), Q.even(k)) is None assert ask(Q.odd(k**m), Q.even(k) & Q.integer(m) & ~Q.negative(m)) is None assert ask(Q.odd(n**m), Q.odd(n) & Q.integer(m) & ~Q.negative(m)) is True assert ask(Q.odd(k**p), Q.even(k) & Q.integer(p) & Q.positive(p)) is False assert ask(Q.odd(n**p), Q.odd(n) & Q.integer(p) & Q.positive(p)) is True assert ask(Q.odd(m**k), Q.even(k) & Q.integer(m) & ~Q.negative(m)) is None assert ask(Q.odd(p**k), Q.even(k) & Q.integer(p) & Q.positive(p)) is None assert ask(Q.odd(m**n), Q.odd(n) & Q.integer(m) & ~Q.negative(m)) is None assert ask(Q.odd(p**n), Q.odd(n) & Q.integer(p) & Q.positive(p)) is None assert ask(Q.odd(k**x), Q.even(k)) is None assert ask(Q.odd(n**x), Q.odd(n)) is None assert ask(Q.odd(x*y), Q.integer(x) & Q.integer(y)) is None assert ask(Q.odd(x*x), Q.integer(x)) is None assert ask(Q.odd(x*(x + y)), Q.integer(x) & Q.odd(y)) is False assert ask(Q.odd(x*(x + y)), Q.integer(x) & Q.even(y)) is None @XFAIL def test_oddness_in_ternary_integer_product_with_odd(): # Tests that oddness inference is independent of term ordering. # Term ordering at the point of testing depends on SymPy's symbol order, so # we try to force a different order by modifying symbol names. assert ask(Q.odd(x*y*(y + z)), Q.integer(x) & Q.integer(y) & Q.odd(z)) is False assert ask(Q.odd(y*x*(x + z)), Q.integer(x) & Q.integer(y) & Q.odd(z)) is False def test_oddness_in_ternary_integer_product_with_even(): assert ask(Q.odd(x*y*(y + z)), Q.integer(x) & Q.integer(y) & Q.even(z)) is None def test_prime(): assert ask(Q.prime(x), Q.prime(x)) is True assert ask(Q.prime(x), ~Q.prime(x)) is False assert ask(Q.prime(x), Q.integer(x)) is None assert ask(Q.prime(x), ~Q.integer(x)) is False assert ask(Q.prime(2*x), Q.integer(x)) is None assert ask(Q.prime(x*y)) is None assert ask(Q.prime(x*y), Q.prime(x)) is None assert ask(Q.prime(x*y), Q.integer(x) & Q.integer(y)) is None assert ask(Q.prime(4*x), Q.integer(x)) is False assert ask(Q.prime(4*x)) is None assert ask(Q.prime(x**2), Q.integer(x)) is False assert ask(Q.prime(x**2), Q.prime(x)) is False assert ask(Q.prime(x**y), Q.integer(x) & Q.integer(y)) is False @_both_exp_pow def test_positive(): assert ask(Q.positive(x), Q.positive(x)) is True assert ask(Q.positive(x), Q.negative(x)) is False assert ask(Q.positive(x), Q.nonzero(x)) is None assert ask(Q.positive(-x), Q.positive(x)) is False assert ask(Q.positive(-x), Q.negative(x)) is True assert ask(Q.positive(x + y), Q.positive(x) & Q.positive(y)) is True assert ask(Q.positive(x + y), Q.positive(x) & Q.nonnegative(y)) is True assert ask(Q.positive(x + y), Q.positive(x) & Q.negative(y)) is None assert ask(Q.positive(x + y), Q.positive(x) & Q.imaginary(y)) is False assert ask(Q.positive(2*x), Q.positive(x)) is True assumptions = Q.positive(x) & Q.negative(y) & Q.negative(z) & Q.positive(w) assert ask(Q.positive(x*y*z)) is None assert ask(Q.positive(x*y*z), assumptions) is True assert ask(Q.positive(-x*y*z), assumptions) is False assert ask(Q.positive(x**I), Q.positive(x)) is None assert ask(Q.positive(x**2), Q.positive(x)) is True assert ask(Q.positive(x**2), Q.negative(x)) is True assert ask(Q.positive(x**3), Q.negative(x)) is False assert ask(Q.positive(1/(1 + x**2)), Q.real(x)) is True assert ask(Q.positive(2**I)) is False assert ask(Q.positive(2 + I)) is False # although this could be False, it is representative of expressions # that don't evaluate to a zero with precision assert ask(Q.positive(cos(I)**2 + sin(I)**2 - 1)) is None assert ask(Q.positive(-I + I*(cos(2)**2 + sin(2)**2))) is None #exponential assert ask(Q.positive(exp(x)), Q.real(x)) is True assert ask(~Q.negative(exp(x)), Q.real(x)) is True assert ask(Q.positive(x + exp(x)), Q.real(x)) is None assert ask(Q.positive(exp(x)), Q.imaginary(x)) is None assert ask(Q.positive(exp(2*pi*I, evaluate=False)), Q.imaginary(x)) is True assert ask(Q.negative(exp(pi*I, evaluate=False)), Q.imaginary(x)) is True assert ask(Q.positive(exp(x*pi*I)), Q.even(x)) is True assert ask(Q.positive(exp(x*pi*I)), Q.odd(x)) is False assert ask(Q.positive(exp(x*pi*I)), Q.real(x)) is None # logarithm assert ask(Q.positive(log(x)), Q.imaginary(x)) is False assert ask(Q.positive(log(x)), Q.negative(x)) is False assert ask(Q.positive(log(x)), Q.positive(x)) is None assert ask(Q.positive(log(x + 2)), Q.positive(x)) is True # factorial assert ask(Q.positive(factorial(x)), Q.integer(x) & Q.positive(x)) assert ask(Q.positive(factorial(x)), Q.integer(x)) is None #absolute value assert ask(Q.positive(Abs(x))) is None # Abs(0) = 0 assert ask(Q.positive(Abs(x)), Q.positive(x)) is True def test_nonpositive(): assert ask(Q.nonpositive(-1)) assert ask(Q.nonpositive(0)) assert ask(Q.nonpositive(1)) is False assert ask(~Q.positive(x), Q.nonpositive(x)) assert ask(Q.nonpositive(x), Q.positive(x)) is False assert ask(Q.nonpositive(sqrt(-1))) is False assert ask(Q.nonpositive(x), Q.imaginary(x)) is False def test_nonnegative(): assert ask(Q.nonnegative(-1)) is False assert ask(Q.nonnegative(0)) assert ask(Q.nonnegative(1)) assert ask(~Q.negative(x), Q.nonnegative(x)) assert ask(Q.nonnegative(x), Q.negative(x)) is False assert ask(Q.nonnegative(sqrt(-1))) is False assert ask(Q.nonnegative(x), Q.imaginary(x)) is False def test_real_basic(): assert ask(Q.real(x)) is None assert ask(Q.real(x), Q.real(x)) is True assert ask(Q.real(x), Q.nonzero(x)) is True assert ask(Q.real(x), Q.positive(x)) is True assert ask(Q.real(x), Q.negative(x)) is True assert ask(Q.real(x), Q.integer(x)) is True assert ask(Q.real(x), Q.even(x)) is True assert ask(Q.real(x), Q.prime(x)) is True assert ask(Q.real(x/sqrt(2)), Q.real(x)) is True assert ask(Q.real(x/sqrt(-2)), Q.real(x)) is False assert ask(Q.real(x + 1), Q.real(x)) is True assert ask(Q.real(x + I), Q.real(x)) is False assert ask(Q.real(x + I), Q.complex(x)) is None assert ask(Q.real(2*x), Q.real(x)) is True assert ask(Q.real(I*x), Q.real(x)) is False assert ask(Q.real(I*x), Q.imaginary(x)) is True assert ask(Q.real(I*x), Q.complex(x)) is None def test_real_pow(): assert ask(Q.real(x**2), Q.real(x)) is True assert ask(Q.real(sqrt(x)), Q.negative(x)) is False assert ask(Q.real(x**y), Q.real(x) & Q.integer(y)) is True assert ask(Q.real(x**y), Q.real(x) & Q.real(y)) is None assert ask(Q.real(x**y), Q.positive(x) & Q.real(y)) is True assert ask(Q.real(x**y), Q.imaginary(x) & Q.imaginary(y)) is None # I**I or (2*I)**I assert ask(Q.real(x**y), Q.imaginary(x) & Q.real(y)) is None # I**1 or I**0 assert ask(Q.real(x**y), Q.real(x) & Q.imaginary(y)) is None # could be exp(2*pi*I) or 2**I assert ask(Q.real(x**0), Q.imaginary(x)) is True assert ask(Q.real(x**y), Q.real(x) & Q.integer(y)) is True assert ask(Q.real(x**y), Q.positive(x) & Q.real(y)) is True assert ask(Q.real(x**y), Q.real(x) & Q.rational(y)) is None assert ask(Q.real(x**y), Q.imaginary(x) & Q.integer(y)) is None assert ask(Q.real(x**y), Q.imaginary(x) & Q.odd(y)) is False assert ask(Q.real(x**y), Q.imaginary(x) & Q.even(y)) is True assert ask(Q.real(x**(y/z)), Q.real(x) & Q.real(y/z) & Q.rational(y/z) & Q.even(z) & Q.positive(x)) is True assert ask(Q.real(x**(y/z)), Q.real(x) & Q.rational(y/z) & Q.even(z) & Q.negative(x)) is False assert ask(Q.real(x**(y/z)), Q.real(x) & Q.integer(y/z)) is True assert ask(Q.real(x**(y/z)), Q.real(x) & Q.real(y/z) & Q.positive(x)) is True assert ask(Q.real(x**(y/z)), Q.real(x) & Q.real(y/z) & Q.negative(x)) is False assert ask(Q.real((-I)**i), Q.imaginary(i)) is True assert ask(Q.real(I**i), Q.imaginary(i)) is True assert ask(Q.real(i**i), Q.imaginary(i)) is None # i might be 2*I assert ask(Q.real(x**i), Q.imaginary(i)) is None # x could be 0 assert ask(Q.real(x**(I*pi/log(x))), Q.real(x)) is True @_both_exp_pow def test_real_functions(): # trigonometric functions assert ask(Q.real(sin(x))) is None assert ask(Q.real(cos(x))) is None assert ask(Q.real(sin(x)), Q.real(x)) is True assert ask(Q.real(cos(x)), Q.real(x)) is True # exponential function assert ask(Q.real(exp(x))) is None assert ask(Q.real(exp(x)), Q.real(x)) is True assert ask(Q.real(x + exp(x)), Q.real(x)) is True assert ask(Q.real(exp(2*pi*I, evaluate=False))) is True assert ask(Q.real(exp(pi*I, evaluate=False))) is True assert ask(Q.real(exp(pi*I/2, evaluate=False))) is False # logarithm assert ask(Q.real(log(I))) is False assert ask(Q.real(log(2*I))) is False assert ask(Q.real(log(I + 1))) is False assert ask(Q.real(log(x)), Q.complex(x)) is None assert ask(Q.real(log(x)), Q.imaginary(x)) is False assert ask(Q.real(log(exp(x))), Q.imaginary(x)) is None # exp(2*pi*I) is 1, log(exp(pi*I)) is pi*I (disregarding periodicity) assert ask(Q.real(log(exp(x))), Q.complex(x)) is None eq = Pow(exp(2*pi*I*x, evaluate=False), x, evaluate=False) assert ask(Q.real(eq), Q.integer(x)) is True assert ask(Q.real(exp(x)**x), Q.imaginary(x)) is True assert ask(Q.real(exp(x)**x), Q.complex(x)) is None # Q.complexes assert ask(Q.real(re(x))) is True assert ask(Q.real(im(x))) is True def test_matrix(): # hermitian assert ask(Q.hermitian(Matrix([[2, 2 + I, 4], [2 - I, 3, I], [4, -I, 1]]))) == True assert ask(Q.hermitian(Matrix([[2, 2 + I, 4], [2 + I, 3, I], [4, -I, 1]]))) == False z = symbols('z', complex=True) assert ask(Q.hermitian(Matrix([[2, 2 + I, z], [2 - I, 3, I], [4, -I, 1]]))) == None assert ask(Q.hermitian(SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))))) == True assert ask(Q.hermitian(SparseMatrix(((25, 15, -5), (15, I, 0), (-5, 0, 11))))) == False assert ask(Q.hermitian(SparseMatrix(((25, 15, -5), (15, z, 0), (-5, 0, 11))))) == None # antihermitian A = Matrix([[0, -2 - I, 0], [2 - I, 0, -I], [0, -I, 0]]) B = Matrix([[-I, 2 + I, 0], [-2 + I, 0, 2 + I], [0, -2 + I, -I]]) assert ask(Q.antihermitian(A)) is True assert ask(Q.antihermitian(B)) is True assert ask(Q.antihermitian(A**2)) is False C = (B**3) C.simplify() assert ask(Q.antihermitian(C)) is True _A = Matrix([[0, -2 - I, 0], [z, 0, -I], [0, -I, 0]]) assert ask(Q.antihermitian(_A)) is None @_both_exp_pow def test_algebraic(): assert ask(Q.algebraic(x)) is None assert ask(Q.algebraic(I)) is True assert ask(Q.algebraic(2*I)) is True assert ask(Q.algebraic(I/3)) is True assert ask(Q.algebraic(sqrt(7))) is True assert ask(Q.algebraic(2*sqrt(7))) is True assert ask(Q.algebraic(sqrt(7)/3)) is True assert ask(Q.algebraic(I*sqrt(3))) is True assert ask(Q.algebraic(sqrt(1 + I*sqrt(3)))) is True assert ask(Q.algebraic(1 + I*sqrt(3)**Rational(17, 31))) is True assert ask(Q.algebraic(1 + I*sqrt(3)**(17/pi))) is False for f in [exp, sin, tan, asin, atan, cos]: assert ask(Q.algebraic(f(7))) is False assert ask(Q.algebraic(f(7, evaluate=False))) is False assert ask(Q.algebraic(f(0, evaluate=False))) is True assert ask(Q.algebraic(f(x)), Q.algebraic(x)) is None assert ask(Q.algebraic(f(x)), Q.algebraic(x) & Q.nonzero(x)) is False for g in [log, acos]: assert ask(Q.algebraic(g(7))) is False assert ask(Q.algebraic(g(7, evaluate=False))) is False assert ask(Q.algebraic(g(1, evaluate=False))) is True assert ask(Q.algebraic(g(x)), Q.algebraic(x)) is None assert ask(Q.algebraic(g(x)), Q.algebraic(x) & Q.nonzero(x - 1)) is False for h in [cot, acot]: assert ask(Q.algebraic(h(7))) is False assert ask(Q.algebraic(h(7, evaluate=False))) is False assert ask(Q.algebraic(h(x)), Q.algebraic(x)) is False assert ask(Q.algebraic(sqrt(sin(7)))) is False assert ask(Q.algebraic(sqrt(y + I*sqrt(7)))) is None assert ask(Q.algebraic(2.47)) is True assert ask(Q.algebraic(x), Q.transcendental(x)) is False assert ask(Q.transcendental(x), Q.algebraic(x)) is False def test_global(): """Test ask with global assumptions""" assert ask(Q.integer(x)) is None global_assumptions.add(Q.integer(x)) assert ask(Q.integer(x)) is True global_assumptions.clear() assert ask(Q.integer(x)) is None def test_custom_context(): """Test ask with custom assumptions context""" assert ask(Q.integer(x)) is None local_context = AssumptionsContext() local_context.add(Q.integer(x)) assert ask(Q.integer(x), context=local_context) is True assert ask(Q.integer(x)) is None def test_functions_in_assumptions(): assert ask(Q.negative(x), Q.real(x) >> Q.positive(x)) is False assert ask(Q.negative(x), Equivalent(Q.real(x), Q.positive(x))) is False assert ask(Q.negative(x), Xor(Q.real(x), Q.negative(x))) is False def test_composite_ask(): assert ask(Q.negative(x) & Q.integer(x), assumptions=Q.real(x) >> Q.positive(x)) is False def test_composite_proposition(): assert ask(True) is True assert ask(False) is False assert ask(~Q.negative(x), Q.positive(x)) is True assert ask(~Q.real(x), Q.commutative(x)) is None assert ask(Q.negative(x) & Q.integer(x), Q.positive(x)) is False assert ask(Q.negative(x) & Q.integer(x)) is None assert ask(Q.real(x) | Q.integer(x), Q.positive(x)) is True assert ask(Q.real(x) | Q.integer(x)) is None assert ask(Q.real(x) >> Q.positive(x), Q.negative(x)) is False assert ask(Implies( Q.real(x), Q.positive(x), evaluate=False), Q.negative(x)) is False assert ask(Implies(Q.real(x), Q.positive(x), evaluate=False)) is None assert ask(Equivalent(Q.integer(x), Q.even(x)), Q.even(x)) is True assert ask(Equivalent(Q.integer(x), Q.even(x))) is None assert ask(Equivalent(Q.positive(x), Q.integer(x)), Q.integer(x)) is None assert ask(Q.real(x) | Q.integer(x), Q.real(x) | Q.integer(x)) is True def test_tautology(): assert ask(Q.real(x) | ~Q.real(x)) is True assert ask(Q.real(x) & ~Q.real(x)) is False def test_composite_assumptions(): assert ask(Q.real(x), Q.real(x) & Q.real(y)) is True assert ask(Q.positive(x), Q.positive(x) | Q.positive(y)) is None assert ask(Q.positive(x), Q.real(x) >> Q.positive(y)) is None assert ask(Q.real(x), ~(Q.real(x) >> Q.real(y))) is True def test_key_extensibility(): """test that you can add keys to the ask system at runtime""" # make sure the key is not defined raises(AttributeError, lambda: ask(Q.my_key(x))) # Old handler system class MyAskHandler(AskHandler): @staticmethod def Symbol(expr, assumptions): return True try: with warns_deprecated_sympy(): register_handler('my_key', MyAskHandler) with warns_deprecated_sympy(): assert ask(Q.my_key(x)) is True with warns_deprecated_sympy(): assert ask(Q.my_key(x + 1)) is None finally: with warns_deprecated_sympy(): remove_handler('my_key', MyAskHandler) del Q.my_key raises(AttributeError, lambda: ask(Q.my_key(x))) # New handler system class MyPredicate(Predicate): pass try: Q.my_key = MyPredicate() @Q.my_key.register(Symbol) def _(expr, assumptions): return True assert ask(Q.my_key(x)) is True assert ask(Q.my_key(x+1)) is None finally: del Q.my_key raises(AttributeError, lambda: ask(Q.my_key(x))) def test_type_extensibility(): """test that new types can be added to the ask system at runtime """ from sympy.core import Basic class MyType(Basic): pass @Q.prime.register(MyType) def _(expr, assumptions): return True assert ask(Q.prime(MyType())) is True def test_single_fact_lookup(): known_facts = And(Implies(Q.integer, Q.rational), Implies(Q.rational, Q.real), Implies(Q.real, Q.complex)) known_facts_keys = {Q.integer, Q.rational, Q.real, Q.complex} known_facts_cnf = to_cnf(known_facts) mapping = single_fact_lookup(known_facts_keys, known_facts_cnf) assert mapping[Q.rational] == {Q.real, Q.rational, Q.complex} def test_generate_known_facts_dict(): known_facts = And(Implies(Q.integer(x), Q.rational(x)), Implies(Q.rational(x), Q.real(x)), Implies(Q.real(x), Q.complex(x))) known_facts_keys = {Q.integer(x), Q.rational(x), Q.real(x), Q.complex(x)} assert generate_known_facts_dict(known_facts_keys, known_facts) == \ {Q.complex: ({Q.complex}, set()), Q.integer: ({Q.complex, Q.integer, Q.rational, Q.real}, set()), Q.rational: ({Q.complex, Q.rational, Q.real}, set()), Q.real: ({Q.complex, Q.real}, set())} @slow def test_known_facts_consistent(): """"Test that ask_generated.py is up-to-date""" x = Symbol('x') fact = get_known_facts(x) # test cnf clauses of fact between unary predicates cnf = CNF.to_CNF(fact) clauses = set() for cl in cnf.clauses: clauses.add(frozenset(Literal(lit.arg.function, lit.is_Not) for lit in sorted(cl, key=str))) assert get_all_known_facts() == clauses # test dictionary of fact between unary predicates keys = [pred(x) for pred in get_known_facts_keys()] mapping = generate_known_facts_dict(keys, fact) assert get_known_facts_dict() == mapping def test_Add_queries(): assert ask(Q.prime(12345678901234567890 + (cos(1)**2 + sin(1)**2))) is True assert ask(Q.even(Add(S(2), S(2), evaluate=0))) is True assert ask(Q.prime(Add(S(2), S(2), evaluate=0))) is False assert ask(Q.integer(Add(S(2), S(2), evaluate=0))) is True def test_positive_assuming(): with assuming(Q.positive(x + 1)): assert not ask(Q.positive(x)) def test_issue_5421(): raises(TypeError, lambda: ask(pi/log(x), Q.real)) def test_issue_3906(): raises(TypeError, lambda: ask(Q.positive)) def test_issue_5833(): assert ask(Q.positive(log(x)**2), Q.positive(x)) is None assert ask(~Q.negative(log(x)**2), Q.positive(x)) is True def test_issue_6732(): raises(ValueError, lambda: ask(Q.positive(x), Q.positive(x) & Q.negative(x))) raises(ValueError, lambda: ask(Q.negative(x), Q.positive(x) & Q.negative(x))) def test_issue_7246(): assert ask(Q.positive(atan(p)), Q.positive(p)) is True assert ask(Q.positive(atan(p)), Q.negative(p)) is False assert ask(Q.positive(atan(p)), Q.zero(p)) is False assert ask(Q.positive(atan(x))) is None assert ask(Q.positive(asin(p)), Q.positive(p)) is None assert ask(Q.positive(asin(p)), Q.zero(p)) is None assert ask(Q.positive(asin(Rational(1, 7)))) is True assert ask(Q.positive(asin(x)), Q.positive(x) & Q.nonpositive(x - 1)) is True assert ask(Q.positive(asin(x)), Q.negative(x) & Q.nonnegative(x + 1)) is False assert ask(Q.positive(acos(p)), Q.positive(p)) is None assert ask(Q.positive(acos(Rational(1, 7)))) is True assert ask(Q.positive(acos(x)), Q.nonnegative(x + 1) & Q.nonpositive(x - 1)) is True assert ask(Q.positive(acos(x)), Q.nonnegative(x - 1)) is None assert ask(Q.positive(acot(x)), Q.positive(x)) is True assert ask(Q.positive(acot(x)), Q.real(x)) is True assert ask(Q.positive(acot(x)), Q.imaginary(x)) is False assert ask(Q.positive(acot(x))) is None @XFAIL def test_issue_7246_failing(): #Move this test to test_issue_7246 once #the new assumptions module is improved. assert ask(Q.positive(acos(x)), Q.zero(x)) is True def test_check_old_assumption(): x = symbols('x', real=True) assert ask(Q.real(x)) is True assert ask(Q.imaginary(x)) is False assert ask(Q.complex(x)) is True x = symbols('x', imaginary=True) assert ask(Q.real(x)) is False assert ask(Q.imaginary(x)) is True assert ask(Q.complex(x)) is True x = symbols('x', complex=True) assert ask(Q.real(x)) is None assert ask(Q.complex(x)) is True x = symbols('x', positive=True) assert ask(Q.positive(x)) is True assert ask(Q.negative(x)) is False assert ask(Q.real(x)) is True x = symbols('x', commutative=False) assert ask(Q.commutative(x)) is False x = symbols('x', negative=True) assert ask(Q.positive(x)) is False assert ask(Q.negative(x)) is True x = symbols('x', nonnegative=True) assert ask(Q.negative(x)) is False assert ask(Q.positive(x)) is None assert ask(Q.zero(x)) is None x = symbols('x', finite=True) assert ask(Q.finite(x)) is True x = symbols('x', prime=True) assert ask(Q.prime(x)) is True assert ask(Q.composite(x)) is False x = symbols('x', composite=True) assert ask(Q.prime(x)) is False assert ask(Q.composite(x)) is True x = symbols('x', even=True) assert ask(Q.even(x)) is True assert ask(Q.odd(x)) is False x = symbols('x', odd=True) assert ask(Q.even(x)) is False assert ask(Q.odd(x)) is True x = symbols('x', nonzero=True) assert ask(Q.nonzero(x)) is True assert ask(Q.zero(x)) is False x = symbols('x', zero=True) assert ask(Q.zero(x)) is True x = symbols('x', integer=True) assert ask(Q.integer(x)) is True x = symbols('x', rational=True) assert ask(Q.rational(x)) is True assert ask(Q.irrational(x)) is False x = symbols('x', irrational=True) assert ask(Q.irrational(x)) is True assert ask(Q.rational(x)) is False def test_issue_9636(): assert ask(Q.integer(1.0)) is False assert ask(Q.prime(3.0)) is False assert ask(Q.composite(4.0)) is False assert ask(Q.even(2.0)) is False assert ask(Q.odd(3.0)) is False def test_autosimp_used_to_fail(): # See issue #9807 assert ask(Q.imaginary(0**I)) is None assert ask(Q.imaginary(0**(-I))) is None assert ask(Q.real(0**I)) is None assert ask(Q.real(0**(-I))) is None def test_custom_AskHandler(): from sympy.logic.boolalg import conjuncts # Old handler system class MersenneHandler(AskHandler): @staticmethod def Integer(expr, assumptions): if ask(Q.integer(log(expr + 1, 2))): return True @staticmethod def Symbol(expr, assumptions): if expr in conjuncts(assumptions): return True try: with warns_deprecated_sympy(): register_handler('mersenne', MersenneHandler) n = Symbol('n', integer=True) with warns_deprecated_sympy(): assert ask(Q.mersenne(7)) with warns_deprecated_sympy(): assert ask(Q.mersenne(n), Q.mersenne(n)) finally: del Q.mersenne # New handler system class MersennePredicate(Predicate): pass try: Q.mersenne = MersennePredicate() @Q.mersenne.register(Integer) def _(expr, assumptions): if ask(Q.integer(log(expr + 1, 2))): return True @Q.mersenne.register(Symbol) def _(expr, assumptions): if expr in conjuncts(assumptions): return True assert ask(Q.mersenne(7)) assert ask(Q.mersenne(n), Q.mersenne(n)) finally: del Q.mersenne def test_polyadic_predicate(): class SexyPredicate(Predicate): pass try: Q.sexyprime = SexyPredicate() @Q.sexyprime.register(Integer, Integer) def _(int1, int2, assumptions): args = sorted([int1, int2]) if not all(ask(Q.prime(a), assumptions) for a in args): return False return args[1] - args[0] == 6 @Q.sexyprime.register(Integer, Integer, Integer) def _(int1, int2, int3, assumptions): args = sorted([int1, int2, int3]) if not all(ask(Q.prime(a), assumptions) for a in args): return False return args[2] - args[1] == 6 and args[1] - args[0] == 6 assert ask(Q.sexyprime(5, 11)) assert ask(Q.sexyprime(7, 13, 19)) finally: del Q.sexyprime def test_Predicate_handler_is_unique(): # Undefined predicate does not have a handler assert Predicate('mypredicate').handler is None # Handler of defined predicate is unique to the class class MyPredicate(Predicate): pass mp1 = MyPredicate(Str('mp1')) mp2 = MyPredicate(Str('mp2')) assert mp1.handler is mp2.handler def test_relational(): assert ask(Q.eq(x, 0), Q.zero(x)) assert not ask(Q.eq(x, 0), Q.nonzero(x)) assert not ask(Q.ne(x, 0), Q.zero(x)) assert ask(Q.ne(x, 0), Q.nonzero(x))
c4b10d027b5b6ee84f17bbc7dda0d140f63da6228c1fee521afc35ca30dc71ca
""" This module implements some special functions that commonly appear in combinatorial contexts (e.g. in power series); in particular, sequences of rational numbers such as Bernoulli and Fibonacci numbers. Factorials, binomial coefficients and related functions are located in the separate 'factorials' module. """ from typing import Callable, Dict as tDict, Tuple as tTuple from sympy.core import S, Symbol, Add, Dummy from sympy.core.cache import cacheit from sympy.core.evalf import pure_complex from sympy.core.expr import Expr from sympy.core.function import Function, expand_mul from sympy.core.logic import fuzzy_not from sympy.core.mul import Mul, prod from sympy.core.numbers import E, pi, oo, Rational, Integer from sympy.core.relational import is_le, is_gt from sympy.external.gmpy import SYMPY_INTS from sympy.functions.combinatorial.factorials import (binomial, factorial, subfactorial) from sympy.functions.elementary.exponential import log from sympy.functions.elementary.integers import floor from sympy.functions.elementary.miscellaneous import sqrt, cbrt from sympy.functions.elementary.trigonometric import sin, cos, cot from sympy.ntheory import isprime from sympy.ntheory.primetest import is_square from sympy.utilities.enumerative import MultisetPartitionTraverser from sympy.utilities.iterables import multiset, multiset_derangements, iterable from sympy.utilities.memoization import recurrence_memo from sympy.utilities.misc import as_int from mpmath import bernfrac, workprec from mpmath.libmp import ifib as _ifib def _product(a, b): p = 1 for k in range(a, b + 1): p *= k return p # Dummy symbol used for computing polynomial sequences _sym = Symbol('x') #----------------------------------------------------------------------------# # # # Carmichael numbers # # # #----------------------------------------------------------------------------# class carmichael(Function): """ Carmichael Numbers: Certain cryptographic algorithms make use of big prime numbers. However, checking whether a big number is prime is not so easy. Randomized prime number checking tests exist that offer a high degree of confidence of accurate determination at low cost, such as the Fermat test. Let 'a' be a random number between 2 and n - 1, where n is the number whose primality we are testing. Then, n is probably prime if it satisfies the modular arithmetic congruence relation : a^(n-1) = 1(mod n). (where mod refers to the modulo operation) If a number passes the Fermat test several times, then it is prime with a high probability. Unfortunately, certain composite numbers (non-primes) still pass the Fermat test with every number smaller than themselves. These numbers are called Carmichael numbers. A Carmichael number will pass a Fermat primality test to every base b relatively prime to the number, even though it is not actually prime. This makes tests based on Fermat's Little Theorem less effective than strong probable prime tests such as the Baillie-PSW primality test and the Miller-Rabin primality test. mr functions given in sympy/sympy/ntheory/primetest.py will produce wrong results for each and every carmichael number. Examples ======== >>> from sympy import carmichael >>> carmichael.find_first_n_carmichaels(5) [561, 1105, 1729, 2465, 2821] >>> carmichael.is_prime(2465) False >>> carmichael.is_prime(1729) False >>> carmichael.find_carmichael_numbers_in_range(0, 562) [561] >>> carmichael.find_carmichael_numbers_in_range(0,1000) [561] >>> carmichael.find_carmichael_numbers_in_range(0,2000) [561, 1105, 1729] References ========== .. [1] https://en.wikipedia.org/wiki/Carmichael_number .. [2] https://en.wikipedia.org/wiki/Fermat_primality_test .. [3] https://www.jstor.org/stable/23248683?seq=1#metadata_info_tab_contents """ @staticmethod def is_perfect_square(n): return is_square(n) @staticmethod def divides(p, n): return n % p == 0 @staticmethod def is_prime(n): return isprime(n) @staticmethod def is_carmichael(n): if n >= 0: if (n == 1) or (carmichael.is_prime(n)) or (n % 2 == 0): return False divisors = list([1, n]) # get divisors for i in range(3, n // 2 + 1, 2): if n % i == 0: divisors.append(i) for i in divisors: if carmichael.is_perfect_square(i) and i != 1: return False if carmichael.is_prime(i): if not carmichael.divides(i - 1, n - 1): return False return True else: raise ValueError('The provided number must be greater than or equal to 0') @staticmethod def find_carmichael_numbers_in_range(x, y): if 0 <= x <= y: if x % 2 == 0: return list([i for i in range(x + 1, y, 2) if carmichael.is_carmichael(i)]) else: return list([i for i in range(x, y, 2) if carmichael.is_carmichael(i)]) else: raise ValueError('The provided range is not valid. x and y must be non-negative integers and x <= y') @staticmethod def find_first_n_carmichaels(n): i = 1 carmichaels = list() while len(carmichaels) < n: if carmichael.is_carmichael(i): carmichaels.append(i) i += 2 return carmichaels #----------------------------------------------------------------------------# # # # Fibonacci numbers # # # #----------------------------------------------------------------------------# class fibonacci(Function): r""" Fibonacci numbers / Fibonacci polynomials The Fibonacci numbers are the integer sequence defined by the initial terms `F_0 = 0`, `F_1 = 1` and the two-term recurrence relation `F_n = F_{n-1} + F_{n-2}`. This definition extended to arbitrary real and complex arguments using the formula .. math :: F_z = \frac{\phi^z - \cos(\pi z) \phi^{-z}}{\sqrt 5} The Fibonacci polynomials are defined by `F_1(x) = 1`, `F_2(x) = x`, and `F_n(x) = x*F_{n-1}(x) + F_{n-2}(x)` for `n > 2`. For all positive integers `n`, `F_n(1) = F_n`. * ``fibonacci(n)`` gives the `n^{th}` Fibonacci number, `F_n` * ``fibonacci(n, x)`` gives the `n^{th}` Fibonacci polynomial in `x`, `F_n(x)` Examples ======== >>> from sympy import fibonacci, Symbol >>> [fibonacci(x) for x in range(11)] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> fibonacci(5, Symbol('t')) t**4 + 3*t**2 + 1 See Also ======== bell, bernoulli, catalan, euler, harmonic, lucas, genocchi, partition, tribonacci References ========== .. [1] https://en.wikipedia.org/wiki/Fibonacci_number .. [2] http://mathworld.wolfram.com/FibonacciNumber.html """ @staticmethod def _fib(n): return _ifib(n) @staticmethod @recurrence_memo([None, S.One, _sym]) def _fibpoly(n, prev): return (prev[-2] + _sym*prev[-1]).expand() @classmethod def eval(cls, n, sym=None): if n is S.Infinity: return S.Infinity if n.is_Integer: if sym is None: n = int(n) if n < 0: return S.NegativeOne**(n + 1) * fibonacci(-n) else: return Integer(cls._fib(n)) else: if n < 1: raise ValueError("Fibonacci polynomials are defined " "only for positive integer indices.") return cls._fibpoly(n).subs(_sym, sym) def _eval_rewrite_as_sqrt(self, n, **kwargs): return 2**(-n)*sqrt(5)*((1 + sqrt(5))**n - (-sqrt(5) + 1)**n) / 5 def _eval_rewrite_as_GoldenRatio(self,n, **kwargs): return (S.GoldenRatio**n - 1/(-S.GoldenRatio)**n)/(2*S.GoldenRatio-1) #----------------------------------------------------------------------------# # # # Lucas numbers # # # #----------------------------------------------------------------------------# class lucas(Function): """ Lucas numbers Lucas numbers satisfy a recurrence relation similar to that of the Fibonacci sequence, in which each term is the sum of the preceding two. They are generated by choosing the initial values `L_0 = 2` and `L_1 = 1`. * ``lucas(n)`` gives the `n^{th}` Lucas number Examples ======== >>> from sympy import lucas >>> [lucas(x) for x in range(11)] [2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123] See Also ======== bell, bernoulli, catalan, euler, fibonacci, harmonic, genocchi, partition, tribonacci References ========== .. [1] https://en.wikipedia.org/wiki/Lucas_number .. [2] http://mathworld.wolfram.com/LucasNumber.html """ @classmethod def eval(cls, n): if n is S.Infinity: return S.Infinity if n.is_Integer: return fibonacci(n + 1) + fibonacci(n - 1) def _eval_rewrite_as_sqrt(self, n, **kwargs): return 2**(-n)*((1 + sqrt(5))**n + (-sqrt(5) + 1)**n) #----------------------------------------------------------------------------# # # # Tribonacci numbers # # # #----------------------------------------------------------------------------# class tribonacci(Function): r""" Tribonacci numbers / Tribonacci polynomials The Tribonacci numbers are the integer sequence defined by the initial terms `T_0 = 0`, `T_1 = 1`, `T_2 = 1` and the three-term recurrence relation `T_n = T_{n-1} + T_{n-2} + T_{n-3}`. The Tribonacci polynomials are defined by `T_0(x) = 0`, `T_1(x) = 1`, `T_2(x) = x^2`, and `T_n(x) = x^2 T_{n-1}(x) + x T_{n-2}(x) + T_{n-3}(x)` for `n > 2`. For all positive integers `n`, `T_n(1) = T_n`. * ``tribonacci(n)`` gives the `n^{th}` Tribonacci number, `T_n` * ``tribonacci(n, x)`` gives the `n^{th}` Tribonacci polynomial in `x`, `T_n(x)` Examples ======== >>> from sympy import tribonacci, Symbol >>> [tribonacci(x) for x in range(11)] [0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149] >>> tribonacci(5, Symbol('t')) t**8 + 3*t**5 + 3*t**2 See Also ======== bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition References ========== .. [1] https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers#Tribonacci_numbers .. [2] http://mathworld.wolfram.com/TribonacciNumber.html .. [3] https://oeis.org/A000073 """ @staticmethod @recurrence_memo([S.Zero, S.One, S.One]) def _trib(n, prev): return (prev[-3] + prev[-2] + prev[-1]) @staticmethod @recurrence_memo([S.Zero, S.One, _sym**2]) def _tribpoly(n, prev): return (prev[-3] + _sym*prev[-2] + _sym**2*prev[-1]).expand() @classmethod def eval(cls, n, sym=None): if n is S.Infinity: return S.Infinity if n.is_Integer: n = int(n) if n < 0: raise ValueError("Tribonacci polynomials are defined " "only for non-negative integer indices.") if sym is None: return Integer(cls._trib(n)) else: return cls._tribpoly(n).subs(_sym, sym) def _eval_rewrite_as_sqrt(self, n, **kwargs): w = (-1 + S.ImaginaryUnit * sqrt(3)) / 2 a = (1 + cbrt(19 + 3*sqrt(33)) + cbrt(19 - 3*sqrt(33))) / 3 b = (1 + w*cbrt(19 + 3*sqrt(33)) + w**2*cbrt(19 - 3*sqrt(33))) / 3 c = (1 + w**2*cbrt(19 + 3*sqrt(33)) + w*cbrt(19 - 3*sqrt(33))) / 3 Tn = (a**(n + 1)/((a - b)*(a - c)) + b**(n + 1)/((b - a)*(b - c)) + c**(n + 1)/((c - a)*(c - b))) return Tn def _eval_rewrite_as_TribonacciConstant(self, n, **kwargs): b = cbrt(586 + 102*sqrt(33)) Tn = 3 * b * S.TribonacciConstant**n / (b**2 - 2*b + 4) return floor(Tn + S.Half) #----------------------------------------------------------------------------# # # # Bernoulli numbers # # # #----------------------------------------------------------------------------# class bernoulli(Function): r""" Bernoulli numbers / Bernoulli polynomials The Bernoulli numbers are a sequence of rational numbers defined by `B_0 = 1` and the recursive relation (`n > 0`): .. math :: 0 = \sum_{k=0}^n \binom{n+1}{k} B_k They are also commonly defined by their exponential generating function, which is `\frac{x}{e^x - 1}`. For odd indices > 1, the Bernoulli numbers are zero. The Bernoulli polynomials satisfy the analogous formula: .. math :: B_n(x) = \sum_{k=0}^n \binom{n}{k} B_k x^{n-k} Bernoulli numbers and Bernoulli polynomials are related as `B_n(0) = B_n`. We compute Bernoulli numbers using Ramanujan's formula: .. math :: B_n = \frac{A(n) - S(n)}{\binom{n+3}{n}} where: .. math :: A(n) = \begin{cases} \frac{n+3}{3} & n \equiv 0\ \text{or}\ 2 \pmod{6} \\ -\frac{n+3}{6} & n \equiv 4 \pmod{6} \end{cases} and: .. math :: S(n) = \sum_{k=1}^{[n/6]} \binom{n+3}{n-6k} B_{n-6k} This formula is similar to the sum given in the definition, but cuts 2/3 of the terms. For Bernoulli polynomials, we use the formula in the definition. * ``bernoulli(n)`` gives the nth Bernoulli number, `B_n` * ``bernoulli(n, x)`` gives the nth Bernoulli polynomial in `x`, `B_n(x)` Examples ======== >>> from sympy import bernoulli >>> [bernoulli(n) for n in range(11)] [1, -1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0, 5/66] >>> bernoulli(1000001) 0 See Also ======== bell, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition, tribonacci References ========== .. [1] https://en.wikipedia.org/wiki/Bernoulli_number .. [2] https://en.wikipedia.org/wiki/Bernoulli_polynomial .. [3] http://mathworld.wolfram.com/BernoulliNumber.html .. [4] http://mathworld.wolfram.com/BernoulliPolynomial.html """ args: tTuple[Integer] # Calculates B_n for positive even n @staticmethod def _calc_bernoulli(n): s = 0 a = int(binomial(n + 3, n - 6)) for j in range(1, n//6 + 1): s += a * bernoulli(n - 6*j) # Avoid computing each binomial coefficient from scratch a *= _product(n - 6 - 6*j + 1, n - 6*j) a //= _product(6*j + 4, 6*j + 9) if n % 6 == 4: s = -Rational(n + 3, 6) - s else: s = Rational(n + 3, 3) - s return s / binomial(n + 3, n) # We implement a specialized memoization scheme to handle each # case modulo 6 separately _cache = {0: S.One, 2: Rational(1, 6), 4: Rational(-1, 30)} _highest = {0: 0, 2: 2, 4: 4} @classmethod def eval(cls, n, sym=None): if n.is_Number: if n.is_Integer and n.is_nonnegative: if n.is_zero: return S.One elif n is S.One: if sym is None: return Rational(-1, 2) else: return sym - S.Half # Bernoulli numbers elif sym is None: if n.is_odd: return S.Zero n = int(n) # Use mpmath for enormous Bernoulli numbers if n > 500: p, q = bernfrac(n) return Rational(int(p), int(q)) case = n % 6 highest_cached = cls._highest[case] if n <= highest_cached: return cls._cache[n] # To avoid excessive recursion when, say, bernoulli(1000) is # requested, calculate and cache the entire sequence ... B_988, # B_994, B_1000 in increasing order for i in range(highest_cached + 6, n + 6, 6): b = cls._calc_bernoulli(i) cls._cache[i] = b cls._highest[case] = i return b # Bernoulli polynomials else: n, result = int(n), [] for k in range(n + 1): result.append(binomial(n, k)*cls(k)*sym**(n - k)) return Add(*result) else: raise ValueError("Bernoulli numbers are defined only" " for nonnegative integer indices.") if sym is None: if n.is_odd and (n - 1).is_positive: return S.Zero #----------------------------------------------------------------------------# # # # Bell numbers # # # #----------------------------------------------------------------------------# class bell(Function): r""" Bell numbers / Bell polynomials The Bell numbers satisfy `B_0 = 1` and .. math:: B_n = \sum_{k=0}^{n-1} \binom{n-1}{k} B_k. They are also given by: .. math:: B_n = \frac{1}{e} \sum_{k=0}^{\infty} \frac{k^n}{k!}. The Bell polynomials are given by `B_0(x) = 1` and .. math:: B_n(x) = x \sum_{k=1}^{n-1} \binom{n-1}{k-1} B_{k-1}(x). The second kind of Bell polynomials (are sometimes called "partial" Bell polynomials or incomplete Bell polynomials) are defined as .. math:: B_{n,k}(x_1, x_2,\dotsc x_{n-k+1}) = \sum_{j_1+j_2+j_2+\dotsb=k \atop j_1+2j_2+3j_2+\dotsb=n} \frac{n!}{j_1!j_2!\dotsb j_{n-k+1}!} \left(\frac{x_1}{1!} \right)^{j_1} \left(\frac{x_2}{2!} \right)^{j_2} \dotsb \left(\frac{x_{n-k+1}}{(n-k+1)!} \right) ^{j_{n-k+1}}. * ``bell(n)`` gives the `n^{th}` Bell number, `B_n`. * ``bell(n, x)`` gives the `n^{th}` Bell polynomial, `B_n(x)`. * ``bell(n, k, (x1, x2, ...))`` gives Bell polynomials of the second kind, `B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})`. Notes ===== Not to be confused with Bernoulli numbers and Bernoulli polynomials, which use the same notation. Examples ======== >>> from sympy import bell, Symbol, symbols >>> [bell(n) for n in range(11)] [1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147, 115975] >>> bell(30) 846749014511809332450147 >>> bell(4, Symbol('t')) t**4 + 6*t**3 + 7*t**2 + t >>> bell(6, 2, symbols('x:6')[1:]) 6*x1*x5 + 15*x2*x4 + 10*x3**2 See Also ======== bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition, tribonacci References ========== .. [1] https://en.wikipedia.org/wiki/Bell_number .. [2] http://mathworld.wolfram.com/BellNumber.html .. [3] http://mathworld.wolfram.com/BellPolynomial.html """ @staticmethod @recurrence_memo([1, 1]) def _bell(n, prev): s = 1 a = 1 for k in range(1, n): a = a * (n - k) // k s += a * prev[k] return s @staticmethod @recurrence_memo([S.One, _sym]) def _bell_poly(n, prev): s = 1 a = 1 for k in range(2, n + 1): a = a * (n - k + 1) // (k - 1) s += a * prev[k - 1] return expand_mul(_sym * s) @staticmethod def _bell_incomplete_poly(n, k, symbols): r""" The second kind of Bell polynomials (incomplete Bell polynomials). Calculated by recurrence formula: .. math:: B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1}) = \sum_{m=1}^{n-k+1} \x_m \binom{n-1}{m-1} B_{n-m,k-1}(x_1, x_2, \dotsc, x_{n-m-k}) where `B_{0,0} = 1;` `B_{n,0} = 0; for n \ge 1` `B_{0,k} = 0; for k \ge 1` """ if (n == 0) and (k == 0): return S.One elif (n == 0) or (k == 0): return S.Zero s = S.Zero a = S.One for m in range(1, n - k + 2): s += a * bell._bell_incomplete_poly( n - m, k - 1, symbols) * symbols[m - 1] a = a * (n - m) / m return expand_mul(s) @classmethod def eval(cls, n, k_sym=None, symbols=None): if n is S.Infinity: if k_sym is None: return S.Infinity else: raise ValueError("Bell polynomial is not defined") if n.is_negative or n.is_integer is False: raise ValueError("a non-negative integer expected") if n.is_Integer and n.is_nonnegative: if k_sym is None: return Integer(cls._bell(int(n))) elif symbols is None: return cls._bell_poly(int(n)).subs(_sym, k_sym) else: r = cls._bell_incomplete_poly(int(n), int(k_sym), symbols) return r def _eval_rewrite_as_Sum(self, n, k_sym=None, symbols=None, **kwargs): from sympy.concrete.summations import Sum if (k_sym is not None) or (symbols is not None): return self # Dobinski's formula if not n.is_nonnegative: return self k = Dummy('k', integer=True, nonnegative=True) return 1 / E * Sum(k**n / factorial(k), (k, 0, S.Infinity)) #----------------------------------------------------------------------------# # # # Harmonic numbers # # # #----------------------------------------------------------------------------# class harmonic(Function): r""" Harmonic numbers The nth harmonic number is given by `\operatorname{H}_{n} = 1 + \frac{1}{2} + \frac{1}{3} + \ldots + \frac{1}{n}`. More generally: .. math:: \operatorname{H}_{n,m} = \sum_{k=1}^{n} \frac{1}{k^m} As `n \rightarrow \infty`, `\operatorname{H}_{n,m} \rightarrow \zeta(m)`, the Riemann zeta function. * ``harmonic(n)`` gives the nth harmonic number, `\operatorname{H}_n` * ``harmonic(n, m)`` gives the nth generalized harmonic number of order `m`, `\operatorname{H}_{n,m}`, where ``harmonic(n) == harmonic(n, 1)`` Examples ======== >>> from sympy import harmonic, oo >>> [harmonic(n) for n in range(6)] [0, 1, 3/2, 11/6, 25/12, 137/60] >>> [harmonic(n, 2) for n in range(6)] [0, 1, 5/4, 49/36, 205/144, 5269/3600] >>> harmonic(oo, 2) pi**2/6 >>> from sympy import Symbol, Sum >>> n = Symbol("n") >>> harmonic(n).rewrite(Sum) Sum(1/_k, (_k, 1, n)) We can evaluate harmonic numbers for all integral and positive rational arguments: >>> from sympy import S, expand_func, simplify >>> harmonic(8) 761/280 >>> harmonic(11) 83711/27720 >>> H = harmonic(1/S(3)) >>> H harmonic(1/3) >>> He = expand_func(H) >>> He -log(6) - sqrt(3)*pi/6 + 2*Sum(log(sin(_k*pi/3))*cos(2*_k*pi/3), (_k, 1, 1)) + 3*Sum(1/(3*_k + 1), (_k, 0, 0)) >>> He.doit() -log(6) - sqrt(3)*pi/6 - log(sqrt(3)/2) + 3 >>> H = harmonic(25/S(7)) >>> He = simplify(expand_func(H).doit()) >>> He 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 >>> He.n(40) 1.983697455232980674869851942390639915940 >>> harmonic(25/S(7)).n(40) 1.983697455232980674869851942390639915940 We can rewrite harmonic numbers in terms of polygamma functions: >>> from sympy import digamma, polygamma >>> m = Symbol("m") >>> harmonic(n).rewrite(digamma) polygamma(0, n + 1) + EulerGamma >>> harmonic(n).rewrite(polygamma) polygamma(0, n + 1) + EulerGamma >>> harmonic(n,3).rewrite(polygamma) polygamma(2, n + 1)/2 - polygamma(2, 1)/2 >>> harmonic(n,m).rewrite(polygamma) (-1)**m*(polygamma(m - 1, 1) - polygamma(m - 1, n + 1))/factorial(m - 1) Integer offsets in the argument can be pulled out: >>> from sympy import expand_func >>> expand_func(harmonic(n+4)) harmonic(n) + 1/(n + 4) + 1/(n + 3) + 1/(n + 2) + 1/(n + 1) >>> expand_func(harmonic(n-4)) harmonic(n) - 1/(n - 1) - 1/(n - 2) - 1/(n - 3) - 1/n Some limits can be computed as well: >>> from sympy import limit, oo >>> limit(harmonic(n), n, oo) oo >>> limit(harmonic(n, 2), n, oo) pi**2/6 >>> limit(harmonic(n, 3), n, oo) -polygamma(2, 1)/2 However we cannot compute the general relation yet: >>> limit(harmonic(n, m), n, oo) harmonic(oo, m) which equals ``zeta(m)`` for ``m > 1``. See Also ======== bell, bernoulli, catalan, euler, fibonacci, lucas, genocchi, partition, tribonacci References ========== .. [1] https://en.wikipedia.org/wiki/Harmonic_number .. [2] http://functions.wolfram.com/GammaBetaErf/HarmonicNumber/ .. [3] http://functions.wolfram.com/GammaBetaErf/HarmonicNumber2/ """ # Generate one memoized Harmonic number-generating function for each # order and store it in a dictionary _functions = {} # type: tDict[Integer, Callable[[int], Rational]] @classmethod def eval(cls, n, m=None): from sympy.functions.special.zeta_functions import zeta if m is S.One: return cls(n) if m is None: m = S.One if m.is_zero: return n if n is S.Infinity: if m.is_negative: return S.NaN elif is_le(m, S.One): return S.Infinity elif is_gt(m, S.One): return zeta(m) else: return if n == 0: return S.Zero if n.is_Integer and n.is_nonnegative and m.is_Integer: if m not in cls._functions: @recurrence_memo([0]) def f(n, prev): return prev[-1] + S.One / n**m cls._functions[m] = f return cls._functions[m](int(n)) def _eval_rewrite_as_polygamma(self, n, m=1, **kwargs): from sympy.functions.special.gamma_functions import polygamma return S.NegativeOne**m/factorial(m - 1) * (polygamma(m - 1, 1) - polygamma(m - 1, n + 1)) def _eval_rewrite_as_digamma(self, n, m=1, **kwargs): from sympy.functions.special.gamma_functions import polygamma return self.rewrite(polygamma) def _eval_rewrite_as_trigamma(self, n, m=1, **kwargs): from sympy.functions.special.gamma_functions import polygamma return self.rewrite(polygamma) def _eval_rewrite_as_Sum(self, n, m=None, **kwargs): from sympy.concrete.summations import Sum k = Dummy("k", integer=True) if m is None: m = S.One return Sum(k**(-m), (k, 1, n)) def _eval_expand_func(self, **hints): from sympy.concrete.summations import Sum n = self.args[0] m = self.args[1] if len(self.args) == 2 else 1 if m == S.One: if n.is_Add: off = n.args[0] nnew = n - off if off.is_Integer and off.is_positive: result = [S.One/(nnew + i) for i in range(off, 0, -1)] + [harmonic(nnew)] return Add(*result) elif off.is_Integer and off.is_negative: result = [-S.One/(nnew + i) for i in range(0, off, -1)] + [harmonic(nnew)] return Add(*result) if n.is_Rational: # Expansions for harmonic numbers at general rational arguments (u + p/q) # Split n as u + p/q with p < q p, q = n.as_numer_denom() u = p // q p = p - u * q if u.is_nonnegative and p.is_positive and q.is_positive and p < q: k = Dummy("k") t1 = q * Sum(1 / (q * k + p), (k, 0, u)) t2 = 2 * Sum(cos((2 * pi * p * k) / S(q)) * log(sin((pi * k) / S(q))), (k, 1, floor((q - 1) / S(2)))) t3 = (pi / 2) * cot((pi * p) / q) + log(2 * q) return t1 + t2 - t3 return self def _eval_rewrite_as_tractable(self, n, m=1, limitvar=None, **kwargs): from sympy.functions.special.gamma_functions import polygamma return self.rewrite(polygamma).rewrite("tractable", deep=True) def _eval_evalf(self, prec): from sympy.functions.special.gamma_functions import polygamma if all(i.is_number for i in self.args): return self.rewrite(polygamma)._eval_evalf(prec) #----------------------------------------------------------------------------# # # # Euler numbers # # # #----------------------------------------------------------------------------# class euler(Function): r""" Euler numbers / Euler polynomials The Euler numbers are given by: .. math:: E_{2n} = I \sum_{k=1}^{2n+1} \sum_{j=0}^k \binom{k}{j} \frac{(-1)^j (k-2j)^{2n+1}}{2^k I^k k} .. math:: E_{2n+1} = 0 Euler numbers and Euler polynomials are related by .. math:: E_n = 2^n E_n\left(\frac{1}{2}\right). We compute symbolic Euler polynomials using [5]_ .. math:: E_n(x) = \sum_{k=0}^n \binom{n}{k} \frac{E_k}{2^k} \left(x - \frac{1}{2}\right)^{n-k}. However, numerical evaluation of the Euler polynomial is computed more efficiently (and more accurately) using the mpmath library. * ``euler(n)`` gives the `n^{th}` Euler number, `E_n`. * ``euler(n, x)`` gives the `n^{th}` Euler polynomial, `E_n(x)`. Examples ======== >>> from sympy import euler, Symbol, S >>> [euler(n) for n in range(10)] [1, 0, -1, 0, 5, 0, -61, 0, 1385, 0] >>> n = Symbol("n") >>> euler(n + 2*n) euler(3*n) >>> x = Symbol("x") >>> euler(n, x) euler(n, x) >>> euler(0, x) 1 >>> euler(1, x) x - 1/2 >>> euler(2, x) x**2 - x >>> euler(3, x) x**3 - 3*x**2/2 + 1/4 >>> euler(4, x) x**4 - 2*x**3 + x >>> euler(12, S.Half) 2702765/4096 >>> euler(12) 2702765 See Also ======== bell, bernoulli, catalan, fibonacci, harmonic, lucas, genocchi, partition, tribonacci References ========== .. [1] https://en.wikipedia.org/wiki/Euler_numbers .. [2] http://mathworld.wolfram.com/EulerNumber.html .. [3] https://en.wikipedia.org/wiki/Alternating_permutation .. [4] http://mathworld.wolfram.com/AlternatingPermutation.html .. [5] http://dlmf.nist.gov/24.2#ii """ @classmethod def eval(cls, m, sym=None): if m.is_Number: if m.is_Integer and m.is_nonnegative: # Euler numbers if sym is None: if m.is_odd: return S.Zero from mpmath import mp m = m._to_mpmath(mp.prec) res = mp.eulernum(m, exact=True) return Integer(res) # Euler polynomial else: reim = pure_complex(sym, or_real=True) # Evaluate polynomial numerically using mpmath if reim and all(a.is_Float or a.is_Integer for a in reim) \ and any(a.is_Float for a in reim): from mpmath import mp m = int(m) # XXX ComplexFloat (#12192) would be nice here, above prec = min([a._prec for a in reim if a.is_Float]) with workprec(prec): res = mp.eulerpoly(m, sym) return Expr._from_mpmath(res, prec) # Construct polynomial symbolically from definition m, result = int(m), [] for k in range(m + 1): result.append(binomial(m, k)*cls(k)/(2**k)*(sym - S.Half)**(m - k)) return Add(*result).expand() else: raise ValueError("Euler numbers are defined only" " for nonnegative integer indices.") if sym is None: if m.is_odd and m.is_positive: return S.Zero def _eval_rewrite_as_Sum(self, n, x=None, **kwargs): from sympy.concrete.summations import Sum if x is None and n.is_even: k = Dummy("k", integer=True) j = Dummy("j", integer=True) n = n / 2 Em = (S.ImaginaryUnit * Sum(Sum(binomial(k, j) * (S.NegativeOne**j * (k - 2*j)**(2*n + 1)) / (2**k*S.ImaginaryUnit**k * k), (j, 0, k)), (k, 1, 2*n + 1))) return Em if x: k = Dummy("k", integer=True) return Sum(binomial(n, k)*euler(k)/2**k*(x - S.Half)**(n - k), (k, 0, n)) def _eval_evalf(self, prec): m, x = (self.args[0], None) if len(self.args) == 1 else self.args if x is None and m.is_Integer and m.is_nonnegative: from mpmath import mp m = m._to_mpmath(prec) with workprec(prec): res = mp.eulernum(m) return Expr._from_mpmath(res, prec) if x and x.is_number and m.is_Integer and m.is_nonnegative: from mpmath import mp m = int(m) x = x._to_mpmath(prec) with workprec(prec): res = mp.eulerpoly(m, x) return Expr._from_mpmath(res, prec) #----------------------------------------------------------------------------# # # # Catalan numbers # # # #----------------------------------------------------------------------------# class catalan(Function): r""" Catalan numbers The `n^{th}` catalan number is given by: .. math :: C_n = \frac{1}{n+1} \binom{2n}{n} * ``catalan(n)`` gives the `n^{th}` Catalan number, `C_n` Examples ======== >>> from sympy import (Symbol, binomial, gamma, hyper, ... catalan, diff, combsimp, Rational, I) >>> [catalan(i) for i in range(1,10)] [1, 2, 5, 14, 42, 132, 429, 1430, 4862] >>> n = Symbol("n", integer=True) >>> catalan(n) catalan(n) Catalan numbers can be transformed into several other, identical expressions involving other mathematical functions >>> catalan(n).rewrite(binomial) binomial(2*n, n)/(n + 1) >>> catalan(n).rewrite(gamma) 4**n*gamma(n + 1/2)/(sqrt(pi)*gamma(n + 2)) >>> catalan(n).rewrite(hyper) hyper((1 - n, -n), (2,), 1) For some non-integer values of n we can get closed form expressions by rewriting in terms of gamma functions: >>> catalan(Rational(1, 2)).rewrite(gamma) 8/(3*pi) We can differentiate the Catalan numbers C(n) interpreted as a continuous real function in n: >>> diff(catalan(n), n) (polygamma(0, n + 1/2) - polygamma(0, n + 2) + log(4))*catalan(n) As a more advanced example consider the following ratio between consecutive numbers: >>> combsimp((catalan(n + 1)/catalan(n)).rewrite(binomial)) 2*(2*n + 1)/(n + 2) The Catalan numbers can be generalized to complex numbers: >>> catalan(I).rewrite(gamma) 4**I*gamma(1/2 + I)/(sqrt(pi)*gamma(2 + I)) and evaluated with arbitrary precision: >>> catalan(I).evalf(20) 0.39764993382373624267 - 0.020884341620842555705*I See Also ======== bell, bernoulli, euler, fibonacci, harmonic, lucas, genocchi, partition, tribonacci sympy.functions.combinatorial.factorials.binomial References ========== .. [1] https://en.wikipedia.org/wiki/Catalan_number .. [2] http://mathworld.wolfram.com/CatalanNumber.html .. [3] http://functions.wolfram.com/GammaBetaErf/CatalanNumber/ .. [4] http://geometer.org/mathcircles/catalan.pdf """ @classmethod def eval(cls, n): from sympy.functions.special.gamma_functions import gamma if (n.is_Integer and n.is_nonnegative) or \ (n.is_noninteger and n.is_negative): return 4**n*gamma(n + S.Half)/(gamma(S.Half)*gamma(n + 2)) if (n.is_integer and n.is_negative): if (n + 1).is_negative: return S.Zero if (n + 1).is_zero: return Rational(-1, 2) def fdiff(self, argindex=1): from sympy.functions.special.gamma_functions import polygamma n = self.args[0] return catalan(n)*(polygamma(0, n + S.Half) - polygamma(0, n + 2) + log(4)) def _eval_rewrite_as_binomial(self, n, **kwargs): return binomial(2*n, n)/(n + 1) def _eval_rewrite_as_factorial(self, n, **kwargs): return factorial(2*n) / (factorial(n+1) * factorial(n)) def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs): from sympy.functions.special.gamma_functions import gamma # The gamma function allows to generalize Catalan numbers to complex n return 4**n*gamma(n + S.Half)/(gamma(S.Half)*gamma(n + 2)) def _eval_rewrite_as_hyper(self, n, **kwargs): from sympy.functions.special.hyper import hyper return hyper([1 - n, -n], [2], 1) def _eval_rewrite_as_Product(self, n, **kwargs): from sympy.concrete.products import Product if not (n.is_integer and n.is_nonnegative): return self k = Dummy('k', integer=True, positive=True) return Product((n + k) / k, (k, 2, n)) def _eval_is_integer(self): if self.args[0].is_integer and self.args[0].is_nonnegative: return True def _eval_is_positive(self): if self.args[0].is_nonnegative: return True def _eval_is_composite(self): if self.args[0].is_integer and (self.args[0] - 3).is_positive: return True def _eval_evalf(self, prec): from sympy.functions.special.gamma_functions import gamma if self.args[0].is_number: return self.rewrite(gamma)._eval_evalf(prec) #----------------------------------------------------------------------------# # # # Genocchi numbers # # # #----------------------------------------------------------------------------# class genocchi(Function): r""" Genocchi numbers The Genocchi numbers are a sequence of integers `G_n` that satisfy the relation: .. math:: \frac{2t}{e^t + 1} = \sum_{n=1}^\infty \frac{G_n t^n}{n!} Examples ======== >>> from sympy import genocchi, Symbol >>> [genocchi(n) for n in range(1, 9)] [1, -1, 0, 1, 0, -3, 0, 17] >>> n = Symbol('n', integer=True, positive=True) >>> genocchi(2*n + 1) 0 See Also ======== bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, partition, tribonacci References ========== .. [1] https://en.wikipedia.org/wiki/Genocchi_number .. [2] http://mathworld.wolfram.com/GenocchiNumber.html """ @classmethod def eval(cls, n): if n.is_Number: if (not n.is_Integer) or n.is_nonpositive: raise ValueError("Genocchi numbers are defined only for " + "positive integers") return 2 * (1 - S(2) ** n) * bernoulli(n) if n.is_odd and (n - 1).is_positive: return S.Zero if (n - 1).is_zero: return S.One def _eval_rewrite_as_bernoulli(self, n, **kwargs): if n.is_integer and n.is_nonnegative: return (1 - S(2) ** n) * bernoulli(n) * 2 def _eval_is_integer(self): if self.args[0].is_integer and self.args[0].is_positive: return True def _eval_is_negative(self): n = self.args[0] if n.is_integer and n.is_positive: if n.is_odd: return False return (n / 2).is_odd def _eval_is_positive(self): n = self.args[0] if n.is_integer and n.is_positive: if n.is_odd: return fuzzy_not((n - 1).is_positive) return (n / 2).is_even def _eval_is_even(self): n = self.args[0] if n.is_integer and n.is_positive: if n.is_even: return False return (n - 1).is_positive def _eval_is_odd(self): n = self.args[0] if n.is_integer and n.is_positive: if n.is_even: return True return fuzzy_not((n - 1).is_positive) def _eval_is_prime(self): n = self.args[0] # only G_6 = -3 and G_8 = 17 are prime, # but SymPy does not consider negatives as prime # so only n=8 is tested return (n - 8).is_zero #----------------------------------------------------------------------------# # # # Partition numbers # # # #----------------------------------------------------------------------------# _npartition = [1, 1] class partition(Function): r""" Partition numbers The Partition numbers are a sequence of integers `p_n` that represent the number of distinct ways of representing `n` as a sum of natural numbers (with order irrelevant). The generating function for `p_n` is given by: .. math:: \sum_{n=0}^\infty p_n x^n = \prod_{k=1}^\infty (1 - x^k)^{-1} Examples ======== >>> from sympy import partition, Symbol >>> [partition(n) for n in range(9)] [1, 1, 2, 3, 5, 7, 11, 15, 22] >>> n = Symbol('n', integer=True, negative=True) >>> partition(n) 0 See Also ======== bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, tribonacci References ========== .. [1] https://en.wikipedia.org/wiki/Partition_(number_theory%29 .. [2] https://en.wikipedia.org/wiki/Pentagonal_number_theorem """ @staticmethod def _partition(n): L = len(_npartition) if n < L: return _npartition[n] # lengthen cache for _n in range(L, n + 1): v, p, i = 0, 0, 0 while 1: s = 0 p += 3*i + 1 # p = pentagonal number: 1, 5, 12, ... if _n >= p: s += _npartition[_n - p] i += 1 gp = p + i # gp = generalized pentagonal: 2, 7, 15, ... if _n >= gp: s += _npartition[_n - gp] if s == 0: break else: v += s if i%2 == 1 else -s _npartition.append(v) return v @classmethod def eval(cls, n): is_int = n.is_integer if is_int == False: raise ValueError("Partition numbers are defined only for " "integers") elif is_int: if n.is_negative: return S.Zero if n.is_zero or (n - 1).is_zero: return S.One if n.is_Integer: return Integer(cls._partition(n)) def _eval_is_integer(self): if self.args[0].is_integer: return True def _eval_is_negative(self): if self.args[0].is_integer: return False def _eval_is_positive(self): n = self.args[0] if n.is_nonnegative and n.is_integer: return True ####################################################################### ### ### Functions for enumerating partitions, permutations and combinations ### ####################################################################### class _MultisetHistogram(tuple): pass _N = -1 _ITEMS = -2 _M = slice(None, _ITEMS) def _multiset_histogram(n): """Return tuple used in permutation and combination counting. Input is a dictionary giving items with counts as values or a sequence of items (which need not be sorted). The data is stored in a class deriving from tuple so it is easily recognized and so it can be converted easily to a list. """ if isinstance(n, dict): # item: count if not all(isinstance(v, int) and v >= 0 for v in n.values()): raise ValueError tot = sum(n.values()) items = sum(1 for k in n if n[k] > 0) return _MultisetHistogram([n[k] for k in n if n[k] > 0] + [items, tot]) else: n = list(n) s = set(n) lens = len(s) lenn = len(n) if lens == lenn: n = [1]*lenn + [lenn, lenn] return _MultisetHistogram(n) m = dict(zip(s, range(lens))) d = dict(zip(range(lens), (0,)*lens)) for i in n: d[m[i]] += 1 return _multiset_histogram(d) def nP(n, k=None, replacement=False): """Return the number of permutations of ``n`` items taken ``k`` at a time. Possible values for ``n``: integer - set of length ``n`` sequence - converted to a multiset internally multiset - {element: multiplicity} If ``k`` is None then the total of all permutations of length 0 through the number of items represented by ``n`` will be returned. If ``replacement`` is True then a given item can appear more than once in the ``k`` items. (For example, for 'ab' permutations of 2 would include 'aa', 'ab', 'ba' and 'bb'.) The multiplicity of elements in ``n`` is ignored when ``replacement`` is True but the total number of elements is considered since no element can appear more times than the number of elements in ``n``. Examples ======== >>> from sympy.functions.combinatorial.numbers import nP >>> from sympy.utilities.iterables import multiset_permutations, multiset >>> nP(3, 2) 6 >>> nP('abc', 2) == nP(multiset('abc'), 2) == 6 True >>> nP('aab', 2) 3 >>> nP([1, 2, 2], 2) 3 >>> [nP(3, i) for i in range(4)] [1, 3, 6, 6] >>> nP(3) == sum(_) True When ``replacement`` is True, each item can have multiplicity equal to the length represented by ``n``: >>> nP('aabc', replacement=True) 121 >>> [len(list(multiset_permutations('aaaabbbbcccc', i))) for i in range(5)] [1, 3, 9, 27, 81] >>> sum(_) 121 See Also ======== sympy.utilities.iterables.multiset_permutations References ========== .. [1] https://en.wikipedia.org/wiki/Permutation """ try: n = as_int(n) except ValueError: return Integer(_nP(_multiset_histogram(n), k, replacement)) return Integer(_nP(n, k, replacement)) @cacheit def _nP(n, k=None, replacement=False): if k == 0: return 1 if isinstance(n, SYMPY_INTS): # n different items # assert n >= 0 if k is None: return sum(_nP(n, i, replacement) for i in range(n + 1)) elif replacement: return n**k elif k > n: return 0 elif k == n: return factorial(k) elif k == 1: return n else: # assert k >= 0 return _product(n - k + 1, n) elif isinstance(n, _MultisetHistogram): if k is None: return sum(_nP(n, i, replacement) for i in range(n[_N] + 1)) elif replacement: return n[_ITEMS]**k elif k == n[_N]: return factorial(k)/prod([factorial(i) for i in n[_M] if i > 1]) elif k > n[_N]: return 0 elif k == 1: return n[_ITEMS] else: # assert k >= 0 tot = 0 n = list(n) for i in range(len(n[_M])): if not n[i]: continue n[_N] -= 1 if n[i] == 1: n[i] = 0 n[_ITEMS] -= 1 tot += _nP(_MultisetHistogram(n), k - 1) n[_ITEMS] += 1 n[i] = 1 else: n[i] -= 1 tot += _nP(_MultisetHistogram(n), k - 1) n[i] += 1 n[_N] += 1 return tot @cacheit def _AOP_product(n): """for n = (m1, m2, .., mk) return the coefficients of the polynomial, prod(sum(x**i for i in range(nj + 1)) for nj in n); i.e. the coefficients of the product of AOPs (all-one polynomials) or order given in n. The resulting coefficient corresponding to x**r is the number of r-length combinations of sum(n) elements with multiplicities given in n. The coefficients are given as a default dictionary (so if a query is made for a key that is not present, 0 will be returned). Examples ======== >>> from sympy.functions.combinatorial.numbers import _AOP_product >>> from sympy.abc import x >>> n = (2, 2, 3) # e.g. aabbccc >>> prod = ((x**2 + x + 1)*(x**2 + x + 1)*(x**3 + x**2 + x + 1)).expand() >>> c = _AOP_product(n); dict(c) {0: 1, 1: 3, 2: 6, 3: 8, 4: 8, 5: 6, 6: 3, 7: 1} >>> [c[i] for i in range(8)] == [prod.coeff(x, i) for i in range(8)] True The generating poly used here is the same as that listed in http://tinyurl.com/cep849r, but in a refactored form. """ from collections import defaultdict n = list(n) ord = sum(n) need = (ord + 2)//2 rv = [1]*(n.pop() + 1) rv.extend((0,) * (need - len(rv))) rv = rv[:need] while n: ni = n.pop() N = ni + 1 was = rv[:] for i in range(1, min(N, len(rv))): rv[i] += rv[i - 1] for i in range(N, need): rv[i] += rv[i - 1] - was[i - N] rev = list(reversed(rv)) if ord % 2: rv = rv + rev else: rv[-1:] = rev d = defaultdict(int) for i in range(len(rv)): d[i] = rv[i] return d def nC(n, k=None, replacement=False): """Return the number of combinations of ``n`` items taken ``k`` at a time. Possible values for ``n``: integer - set of length ``n`` sequence - converted to a multiset internally multiset - {element: multiplicity} If ``k`` is None then the total of all combinations of length 0 through the number of items represented in ``n`` will be returned. If ``replacement`` is True then a given item can appear more than once in the ``k`` items. (For example, for 'ab' sets of 2 would include 'aa', 'ab', and 'bb'.) The multiplicity of elements in ``n`` is ignored when ``replacement`` is True but the total number of elements is considered since no element can appear more times than the number of elements in ``n``. Examples ======== >>> from sympy.functions.combinatorial.numbers import nC >>> from sympy.utilities.iterables import multiset_combinations >>> nC(3, 2) 3 >>> nC('abc', 2) 3 >>> nC('aab', 2) 2 When ``replacement`` is True, each item can have multiplicity equal to the length represented by ``n``: >>> nC('aabc', replacement=True) 35 >>> [len(list(multiset_combinations('aaaabbbbcccc', i))) for i in range(5)] [1, 3, 6, 10, 15] >>> sum(_) 35 If there are ``k`` items with multiplicities ``m_1, m_2, ..., m_k`` then the total of all combinations of length 0 through ``k`` is the product, ``(m_1 + 1)*(m_2 + 1)*...*(m_k + 1)``. When the multiplicity of each item is 1 (i.e., k unique items) then there are 2**k combinations. For example, if there are 4 unique items, the total number of combinations is 16: >>> sum(nC(4, i) for i in range(5)) 16 See Also ======== sympy.utilities.iterables.multiset_combinations References ========== .. [1] https://en.wikipedia.org/wiki/Combination .. [2] http://tinyurl.com/cep849r """ if isinstance(n, SYMPY_INTS): if k is None: if not replacement: return 2**n return sum(nC(n, i, replacement) for i in range(n + 1)) if k < 0: raise ValueError("k cannot be negative") if replacement: return binomial(n + k - 1, k) return binomial(n, k) if isinstance(n, _MultisetHistogram): N = n[_N] if k is None: if not replacement: return prod(m + 1 for m in n[_M]) return sum(nC(n, i, replacement) for i in range(N + 1)) elif replacement: return nC(n[_ITEMS], k, replacement) # assert k >= 0 elif k in (1, N - 1): return n[_ITEMS] elif k in (0, N): return 1 return _AOP_product(tuple(n[_M]))[k] else: return nC(_multiset_histogram(n), k, replacement) def _eval_stirling1(n, k): if n == k == 0: return S.One if 0 in (n, k): return S.Zero # some special values if n == k: return S.One elif k == n - 1: return binomial(n, 2) elif k == n - 2: return (3*n - 1)*binomial(n, 3)/4 elif k == n - 3: return binomial(n, 2)*binomial(n, 4) return _stirling1(n, k) @cacheit def _stirling1(n, k): row = [0, 1]+[0]*(k-1) # for n = 1 for i in range(2, n+1): for j in range(min(k,i), 0, -1): row[j] = (i-1) * row[j] + row[j-1] return Integer(row[k]) def _eval_stirling2(n, k): if n == k == 0: return S.One if 0 in (n, k): return S.Zero # some special values if n == k: return S.One elif k == n - 1: return binomial(n, 2) elif k == 1: return S.One elif k == 2: return Integer(2**(n - 1) - 1) return _stirling2(n, k) @cacheit def _stirling2(n, k): row = [0, 1]+[0]*(k-1) # for n = 1 for i in range(2, n+1): for j in range(min(k,i), 0, -1): row[j] = j * row[j] + row[j-1] return Integer(row[k]) def stirling(n, k, d=None, kind=2, signed=False): r"""Return Stirling number $S(n, k)$ of the first or second (default) kind. The sum of all Stirling numbers of the second kind for $k = 1$ through $n$ is ``bell(n)``. The recurrence relationship for these numbers is: .. math :: {0 \brace 0} = 1; {n \brace 0} = {0 \brace k} = 0; .. math :: {{n+1} \brace k} = j {n \brace k} + {n \brace {k-1}} where $j$ is: $n$ for Stirling numbers of the first kind, $-n$ for signed Stirling numbers of the first kind, $k$ for Stirling numbers of the second kind. The first kind of Stirling number counts the number of permutations of ``n`` distinct items that have ``k`` cycles; the second kind counts the ways in which ``n`` distinct items can be partitioned into ``k`` parts. If ``d`` is given, the "reduced Stirling number of the second kind" is returned: $S^{d}(n, k) = S(n - d + 1, k - d + 1)$ with $n \ge k \ge d$. (This counts the ways to partition $n$ consecutive integers into $k$ groups with no pairwise difference less than $d$. See example below.) To obtain the signed Stirling numbers of the first kind, use keyword ``signed=True``. Using this keyword automatically sets ``kind`` to 1. Examples ======== >>> from sympy.functions.combinatorial.numbers import stirling, bell >>> from sympy.combinatorics import Permutation >>> from sympy.utilities.iterables import multiset_partitions, permutations First kind (unsigned by default): >>> [stirling(6, i, kind=1) for i in range(7)] [0, 120, 274, 225, 85, 15, 1] >>> perms = list(permutations(range(4))) >>> [sum(Permutation(p).cycles == i for p in perms) for i in range(5)] [0, 6, 11, 6, 1] >>> [stirling(4, i, kind=1) for i in range(5)] [0, 6, 11, 6, 1] First kind (signed): >>> [stirling(4, i, signed=True) for i in range(5)] [0, -6, 11, -6, 1] Second kind: >>> [stirling(10, i) for i in range(12)] [0, 1, 511, 9330, 34105, 42525, 22827, 5880, 750, 45, 1, 0] >>> sum(_) == bell(10) True >>> len(list(multiset_partitions(range(4), 2))) == stirling(4, 2) True Reduced second kind: >>> from sympy import subsets, oo >>> def delta(p): ... if len(p) == 1: ... return oo ... return min(abs(i[0] - i[1]) for i in subsets(p, 2)) >>> parts = multiset_partitions(range(5), 3) >>> d = 2 >>> sum(1 for p in parts if all(delta(i) >= d for i in p)) 7 >>> stirling(5, 3, 2) 7 See Also ======== sympy.utilities.iterables.multiset_partitions References ========== .. [1] https://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind .. [2] https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind """ # TODO: make this a class like bell() n = as_int(n) k = as_int(k) if n < 0: raise ValueError('n must be nonnegative') if k > n: return S.Zero if d: # assert k >= d # kind is ignored -- only kind=2 is supported return _eval_stirling2(n - d + 1, k - d + 1) elif signed: # kind is ignored -- only kind=1 is supported return S.NegativeOne**(n - k)*_eval_stirling1(n, k) if kind == 1: return _eval_stirling1(n, k) elif kind == 2: return _eval_stirling2(n, k) else: raise ValueError('kind must be 1 or 2, not %s' % k) @cacheit def _nT(n, k): """Return the partitions of ``n`` items into ``k`` parts. This is used by ``nT`` for the case when ``n`` is an integer.""" # really quick exits if k > n or k < 0: return 0 if k in (1, n): return 1 if k == 0: return 0 # exits that could be done below but this is quicker if k == 2: return n//2 d = n - k if d <= 3: return d # quick exit if 3*k >= n: # or, equivalently, 2*k >= d # all the information needed in this case # will be in the cache needed to calculate # partition(d), so... # update cache tot = partition._partition(d) # and correct for values not needed if d - k > 0: tot -= sum(_npartition[:d - k]) return tot # regular exit # nT(n, k) = Sum(nT(n - k, m), (m, 1, k)); # calculate needed nT(i, j) values p = [1]*d for i in range(2, k + 1): for m in range(i + 1, d): p[m] += p[m - i] d -= 1 # if p[0] were appended to the end of p then the last # k values of p are the nT(n, j) values for 0 < j < k in reverse # order p[-1] = nT(n, 1), p[-2] = nT(n, 2), etc.... Instead of # putting the 1 from p[0] there, however, it is simply added to # the sum below which is valid for 1 < k <= n//2 return (1 + sum(p[1 - k:])) def nT(n, k=None): """Return the number of ``k``-sized partitions of ``n`` items. Possible values for ``n``: integer - ``n`` identical items sequence - converted to a multiset internally multiset - {element: multiplicity} Note: the convention for ``nT`` is different than that of ``nC`` and ``nP`` in that here an integer indicates ``n`` *identical* items instead of a set of length ``n``; this is in keeping with the ``partitions`` function which treats its integer-``n`` input like a list of ``n`` 1s. One can use ``range(n)`` for ``n`` to indicate ``n`` distinct items. If ``k`` is None then the total number of ways to partition the elements represented in ``n`` will be returned. Examples ======== >>> from sympy.functions.combinatorial.numbers import nT Partitions of the given multiset: >>> [nT('aabbc', i) for i in range(1, 7)] [1, 8, 11, 5, 1, 0] >>> nT('aabbc') == sum(_) True >>> [nT("mississippi", i) for i in range(1, 12)] [1, 74, 609, 1521, 1768, 1224, 579, 197, 50, 9, 1] Partitions when all items are identical: >>> [nT(5, i) for i in range(1, 6)] [1, 2, 2, 1, 1] >>> nT('1'*5) == sum(_) True When all items are different: >>> [nT(range(5), i) for i in range(1, 6)] [1, 15, 25, 10, 1] >>> nT(range(5)) == sum(_) True Partitions of an integer expressed as a sum of positive integers: >>> from sympy import partition >>> partition(4) 5 >>> nT(4, 1) + nT(4, 2) + nT(4, 3) + nT(4, 4) 5 >>> nT('1'*4) 5 See Also ======== sympy.utilities.iterables.partitions sympy.utilities.iterables.multiset_partitions sympy.functions.combinatorial.numbers.partition References ========== .. [1] http://undergraduate.csse.uwa.edu.au/units/CITS7209/partition.pdf """ if isinstance(n, SYMPY_INTS): # n identical items if k is None: return partition(n) if isinstance(k, SYMPY_INTS): n = as_int(n) k = as_int(k) return Integer(_nT(n, k)) if not isinstance(n, _MultisetHistogram): try: # if n contains hashable items there is some # quick handling that can be done u = len(set(n)) if u <= 1: return nT(len(n), k) elif u == len(n): n = range(u) raise TypeError except TypeError: n = _multiset_histogram(n) N = n[_N] if k is None and N == 1: return 1 if k in (1, N): return 1 if k == 2 or N == 2 and k is None: m, r = divmod(N, 2) rv = sum(nC(n, i) for i in range(1, m + 1)) if not r: rv -= nC(n, m)//2 if k is None: rv += 1 # for k == 1 return rv if N == n[_ITEMS]: # all distinct if k is None: return bell(N) return stirling(N, k) m = MultisetPartitionTraverser() if k is None: return m.count_partitions(n[_M]) # MultisetPartitionTraverser does not have a range-limited count # method, so need to enumerate and count tot = 0 for discard in m.enum_range(n[_M], k-1, k): tot += 1 return tot #-----------------------------------------------------------------------------# # # # Motzkin numbers # # # #-----------------------------------------------------------------------------# class motzkin(Function): """ The nth Motzkin number is the number of ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). The Motzkin numbers are named after Theodore Motzkin and have diverse applications in geometry, combinatorics and number theory. Motzkin numbers are the integer sequence defined by the initial terms `M_0 = 1`, `M_1 = 1` and the two-term recurrence relation `M_n = \frac{2*n + 1}{n + 2} * M_{n-1} + \frac{3n - 3}{n + 2} * M_{n-2}`. Examples ======== >>> from sympy import motzkin >>> motzkin.is_motzkin(5) False >>> motzkin.find_motzkin_numbers_in_range(2,300) [2, 4, 9, 21, 51, 127] >>> motzkin.find_motzkin_numbers_in_range(2,900) [2, 4, 9, 21, 51, 127, 323, 835] >>> motzkin.find_first_n_motzkins(10) [1, 1, 2, 4, 9, 21, 51, 127, 323, 835] References ========== .. [1] https://en.wikipedia.org/wiki/Motzkin_number .. [2] https://mathworld.wolfram.com/MotzkinNumber.html """ @staticmethod def is_motzkin(n): try: n = as_int(n) except ValueError: return False if n > 0: if n in (1, 2): return True tn1 = 1 tn = 2 i = 3 while tn < n: a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2) i += 1 tn1 = tn tn = a if tn == n: return True else: return False else: return False @staticmethod def find_motzkin_numbers_in_range(x, y): if 0 <= x <= y: motzkins = list() if x <= 1 <= y: motzkins.append(1) tn1 = 1 tn = 2 i = 3 while tn <= y: if tn >= x: motzkins.append(tn) a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2) i += 1 tn1 = tn tn = int(a) return motzkins else: raise ValueError('The provided range is not valid. This condition should satisfy x <= y') @staticmethod def find_first_n_motzkins(n): try: n = as_int(n) except ValueError: raise ValueError('The provided number must be a positive integer') if n < 0: raise ValueError('The provided number must be a positive integer') motzkins = [1] if n >= 1: motzkins.append(1) tn1 = 1 tn = 2 i = 3 while i <= n: motzkins.append(tn) a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2) i += 1 tn1 = tn tn = int(a) return motzkins @staticmethod @recurrence_memo([S.One, S.One]) def _motzkin(n, prev): return ((2*n + 1)*prev[-1] + (3*n - 3)*prev[-2]) // (n + 2) @classmethod def eval(cls, n): try: n = as_int(n) except ValueError: raise ValueError('The provided number must be a positive integer') if n < 0: raise ValueError('The provided number must be a positive integer') return Integer(cls._motzkin(n - 1)) def nD(i=None, brute=None, *, n=None, m=None): """return the number of derangements for: ``n`` unique items, ``i`` items (as a sequence or multiset), or multiplicities, ``m`` given as a sequence or multiset. Examples ======== >>> from sympy.utilities.iterables import generate_derangements as enum >>> from sympy.functions.combinatorial.numbers import nD A derangement ``d`` of sequence ``s`` has all ``d[i] != s[i]``: >>> set([''.join(i) for i in enum('abc')]) {'bca', 'cab'} >>> nD('abc') 2 Input as iterable or dictionary (multiset form) is accepted: >>> assert nD([1, 2, 2, 3, 3, 3]) == nD({1: 1, 2: 2, 3: 3}) By default, a brute-force enumeration and count of multiset permutations is only done if there are fewer than 9 elements. There may be cases when there is high multiplicty with few unique elements that will benefit from a brute-force enumeration, too. For this reason, the `brute` keyword (default None) is provided. When False, the brute-force enumeration will never be used. When True, it will always be used. >>> nD('1111222233', brute=True) 44 For convenience, one may specify ``n`` distinct items using the ``n`` keyword: >>> assert nD(n=3) == nD('abc') == 2 Since the number of derangments depends on the multiplicity of the elements and not the elements themselves, it may be more convenient to give a list or multiset of multiplicities using keyword ``m``: >>> assert nD('abc') == nD(m=(1,1,1)) == nD(m={1:3}) == 2 """ from sympy.integrals.integrals import integrate from sympy.functions.elementary.exponential import exp from sympy.functions.special.polynomials import laguerre from sympy.abc import x def ok(x): if not isinstance(x, SYMPY_INTS): raise TypeError('expecting integer values') if x < 0: raise ValueError('value must not be negative') return True if (i, n, m).count(None) != 2: raise ValueError('enter only 1 of i, n, or m') if i is not None: if isinstance(i, SYMPY_INTS): raise TypeError('items must be a list or dictionary') if not i: return S.Zero if type(i) is not dict: s = list(i) ms = multiset(s) elif type(i) is dict: all(ok(_) for _ in i.values()) ms = {k: v for k, v in i.items() if v} s = None if not ms: return S.Zero N = sum(ms.values()) counts = multiset(ms.values()) nkey = len(ms) elif n is not None: ok(n) if not n: return S.Zero return subfactorial(n) elif m is not None: if isinstance(m, dict): all(ok(i) and ok(j) for i, j in m.items()) counts = {k: v for k, v in m.items() if k*v} elif iterable(m) or isinstance(m, str): m = list(m) all(ok(i) for i in m) counts = multiset([i for i in m if i]) else: raise TypeError('expecting iterable') if not counts: return S.Zero N = sum(k*v for k, v in counts.items()) nkey = sum(counts.values()) s = None big = int(max(counts)) if big == 1: # no repetition return subfactorial(nkey) nval = len(counts) if big*2 > N: return S.Zero if big*2 == N: if nkey == 2 and nval == 1: return S.One # aaabbb if nkey - 1 == big: # one element repeated return factorial(big) # e.g. abc part of abcddd if N < 9 and brute is None or brute: # for all possibilities, this was found to be faster if s is None: s = [] i = 0 for m, v in counts.items(): for j in range(v): s.extend([i]*m) i += 1 return Integer(sum(1 for i in multiset_derangements(s))) return Integer(abs(integrate(exp(-x)*Mul(*[ laguerre(i, x)**m for i, m in counts.items()]), (x, 0, oo))))
d70e7cb1f24967d7d432691d79c241fa16d2d86286de275a063f8f0e1f7a102c
from typing import Tuple as tTuple from sympy.core.add import Add from sympy.core.basic import sympify, cacheit from sympy.core.expr import Expr from sympy.core.function import Function, ArgumentIndexError, PoleError, expand_mul from sympy.core.logic import fuzzy_not, fuzzy_or, FuzzyBool, fuzzy_and from sympy.core.numbers import igcdex, Rational, pi, Integer from sympy.core.relational import Ne from sympy.core.singleton import S from sympy.core.symbol import Symbol, Dummy from sympy.functions.combinatorial.factorials import factorial, RisingFactorial from sympy.functions.elementary.exponential import log, exp from sympy.functions.elementary.integers import floor from sympy.functions.elementary.hyperbolic import (acoth, asinh, atanh, cosh, coth, HyperbolicFunction, sinh, tanh) from sympy.functions.elementary.miscellaneous import sqrt, Min, Max from sympy.functions.elementary.piecewise import Piecewise from sympy.sets.setexpr import SetExpr from sympy.sets.sets import FiniteSet from sympy.utilities.iterables import numbered_symbols ############################################################################### ########################## TRIGONOMETRIC FUNCTIONS ############################ ############################################################################### class TrigonometricFunction(Function): """Base class for trigonometric functions. """ unbranched = True _singularities = (S.ComplexInfinity,) def _eval_is_rational(self): s = self.func(*self.args) if s.func == self.func: if s.args[0].is_rational and fuzzy_not(s.args[0].is_zero): return False else: return s.is_rational def _eval_is_algebraic(self): s = self.func(*self.args) if s.func == self.func: if fuzzy_not(self.args[0].is_zero) and self.args[0].is_algebraic: return False pi_coeff = _pi_coeff(self.args[0]) if pi_coeff is not None and pi_coeff.is_rational: return True else: return s.is_algebraic def _eval_expand_complex(self, deep=True, **hints): re_part, im_part = self.as_real_imag(deep=deep, **hints) return re_part + im_part*S.ImaginaryUnit def _as_real_imag(self, deep=True, **hints): if self.args[0].is_extended_real: if deep: hints['complex'] = False return (self.args[0].expand(deep, **hints), S.Zero) else: return (self.args[0], S.Zero) if deep: re, im = self.args[0].expand(deep, **hints).as_real_imag() else: re, im = self.args[0].as_real_imag() return (re, im) def _period(self, general_period, symbol=None): f = expand_mul(self.args[0]) if symbol is None: symbol = tuple(f.free_symbols)[0] if not f.has(symbol): return S.Zero if f == symbol: return general_period if symbol in f.free_symbols: if f.is_Mul: g, h = f.as_independent(symbol) if h == symbol: return general_period/abs(g) if f.is_Add: a, h = f.as_independent(symbol) g, h = h.as_independent(symbol, as_Add=False) if h == symbol: return general_period/abs(g) raise NotImplementedError("Use the periodicity function instead.") def _peeloff_pi(arg): """ Split ARG into two parts, a "rest" and a multiple of pi. This assumes ARG to be an Add. The multiple of pi returned in the second position is always a Rational. Examples ======== >>> from sympy.functions.elementary.trigonometric import _peeloff_pi as peel >>> from sympy import pi >>> from sympy.abc import x, y >>> peel(x + pi/2) (x, 1/2) >>> peel(x + 2*pi/3 + pi*y) (x + pi*y + pi/6, 1/2) """ pi_coeff = S.Zero rest_terms = [] for a in Add.make_args(arg): K = a.coeff(S.Pi) if K and K.is_rational: pi_coeff += K else: rest_terms.append(a) if pi_coeff is S.Zero: return arg, S.Zero m1 = (pi_coeff % S.Half) m2 = pi_coeff - m1 if m2.is_integer or ((2*m2).is_integer and m2.is_even is False): return Add(*(rest_terms + [m1*pi])), m2 return arg, S.Zero def _pi_coeff(arg, cycles=1): """ When arg is a Number times pi (e.g. 3*pi/2) then return the Number normalized to be in the range [0, 2], else None. When an even multiple of pi is encountered, if it is multiplying something with known parity then the multiple is returned as 0 otherwise as 2. Examples ======== >>> from sympy.functions.elementary.trigonometric import _pi_coeff as coeff >>> from sympy import pi, Dummy >>> from sympy.abc import x >>> coeff(3*x*pi) 3*x >>> coeff(11*pi/7) 11/7 >>> coeff(-11*pi/7) 3/7 >>> coeff(4*pi) 0 >>> coeff(5*pi) 1 >>> coeff(5.0*pi) 1 >>> coeff(5.5*pi) 3/2 >>> coeff(2 + pi) >>> coeff(2*Dummy(integer=True)*pi) 2 >>> coeff(2*Dummy(even=True)*pi) 0 """ arg = sympify(arg) if arg is S.Pi: return S.One elif not arg: return S.Zero elif arg.is_Mul: cx = arg.coeff(S.Pi) if cx: c, x = cx.as_coeff_Mul() # pi is not included as coeff if c.is_Float: # recast exact binary fractions to Rationals f = abs(c) % 1 if f != 0: p = -int(round(log(f, 2).evalf())) m = 2**p cm = c*m i = int(cm) if i == cm: c = Rational(i, m) cx = c*x else: c = Rational(int(c)) cx = c*x if x.is_integer: c2 = c % 2 if c2 == 1: return x elif not c2: if x.is_even is not None: # known parity return S.Zero return Integer(2) else: return c2*x return cx elif arg.is_zero: return S.Zero class sin(TrigonometricFunction): """ The sine function. Returns the sine of x (measured in radians). Explanation =========== This function will evaluate automatically in the case x/pi is some rational number [4]_. For example, if x is a multiple of pi, pi/2, pi/3, pi/4 and pi/6. Examples ======== >>> from sympy import sin, pi >>> from sympy.abc import x >>> sin(x**2).diff(x) 2*x*cos(x**2) >>> sin(1).diff(x) 0 >>> sin(pi) 0 >>> sin(pi/2) 1 >>> sin(pi/6) 1/2 >>> sin(pi/12) -sqrt(2)/4 + sqrt(6)/4 See Also ======== csc, cos, sec, tan, cot asin, acsc, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_functions .. [2] http://dlmf.nist.gov/4.14 .. [3] http://functions.wolfram.com/ElementaryFunctions/Sin .. [4] http://mathworld.wolfram.com/TrigonometryAngles.html """ def period(self, symbol=None): return self._period(2*pi, symbol) def fdiff(self, argindex=1): if argindex == 1: return cos(self.args[0]) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): from sympy.calculus.accumulationbounds import AccumBounds if arg.is_Number: if arg is S.NaN: return S.NaN elif arg.is_zero: return S.Zero elif arg in (S.Infinity, S.NegativeInfinity): return AccumBounds(-1, 1) if arg is S.ComplexInfinity: return S.NaN if isinstance(arg, AccumBounds): min, max = arg.min, arg.max d = floor(min/(2*S.Pi)) if min is not S.NegativeInfinity: min = min - d*2*S.Pi if max is not S.Infinity: max = max - d*2*S.Pi if AccumBounds(min, max).intersection(FiniteSet(S.Pi/2, S.Pi*Rational(5, 2))) \ is not S.EmptySet and \ AccumBounds(min, max).intersection(FiniteSet(S.Pi*Rational(3, 2), S.Pi*Rational(7, 2))) is not S.EmptySet: return AccumBounds(-1, 1) elif AccumBounds(min, max).intersection(FiniteSet(S.Pi/2, S.Pi*Rational(5, 2))) \ is not S.EmptySet: return AccumBounds(Min(sin(min), sin(max)), 1) elif AccumBounds(min, max).intersection(FiniteSet(S.Pi*Rational(3, 2), S.Pi*Rational(8, 2))) \ is not S.EmptySet: return AccumBounds(-1, Max(sin(min), sin(max))) else: return AccumBounds(Min(sin(min), sin(max)), Max(sin(min), sin(max))) elif isinstance(arg, SetExpr): return arg._eval_func(cls) if arg.could_extract_minus_sign(): return -cls(-arg) i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: return S.ImaginaryUnit*sinh(i_coeff) pi_coeff = _pi_coeff(arg) if pi_coeff is not None: if pi_coeff.is_integer: return S.Zero if (2*pi_coeff).is_integer: # is_even-case handled above as then pi_coeff.is_integer, # so check if known to be not even if pi_coeff.is_even is False: return S.NegativeOne**(pi_coeff - S.Half) if not pi_coeff.is_Rational: narg = pi_coeff*S.Pi if narg != arg: return cls(narg) return None # https://github.com/sympy/sympy/issues/6048 # transform a sine to a cosine, to avoid redundant code if pi_coeff.is_Rational: x = pi_coeff % 2 if x > 1: return -cls((x % 1)*S.Pi) if 2*x > 1: return cls((1 - x)*S.Pi) narg = ((pi_coeff + Rational(3, 2)) % 2)*S.Pi result = cos(narg) if not isinstance(result, cos): return result if pi_coeff*S.Pi != arg: return cls(pi_coeff*S.Pi) return None if arg.is_Add: x, m = _peeloff_pi(arg) if m: m = m*S.Pi return sin(m)*cos(x) + cos(m)*sin(x) if arg.is_zero: return S.Zero if isinstance(arg, asin): return arg.args[0] if isinstance(arg, atan): x = arg.args[0] return x/sqrt(1 + x**2) if isinstance(arg, atan2): y, x = arg.args return y/sqrt(x**2 + y**2) if isinstance(arg, acos): x = arg.args[0] return sqrt(1 - x**2) if isinstance(arg, acot): x = arg.args[0] return 1/(sqrt(1 + 1/x**2)*x) if isinstance(arg, acsc): x = arg.args[0] return 1/x if isinstance(arg, asec): x = arg.args[0] return sqrt(1 - 1/x**2) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) if len(previous_terms) > 2: p = previous_terms[-2] return -p*x**2/(n*(n - 1)) else: return S.NegativeOne**(n//2)*x**n/factorial(n) def _eval_nseries(self, x, n, logx, cdir=0): arg = self.args[0] if logx is not None: arg = arg.subs(log(x), logx) if arg.subs(x, 0).has(S.NaN, S.ComplexInfinity): raise PoleError("Cannot expand %s around 0" % (self)) return Function._eval_nseries(self, x, n=n, logx=logx, cdir=cdir) def _eval_rewrite_as_exp(self, arg, **kwargs): I = S.ImaginaryUnit if isinstance(arg, (TrigonometricFunction, HyperbolicFunction)): arg = arg.func(arg.args[0]).rewrite(exp) return (exp(arg*I) - exp(-arg*I))/(2*I) def _eval_rewrite_as_Pow(self, arg, **kwargs): if isinstance(arg, log): I = S.ImaginaryUnit x = arg.args[0] return I*x**-I/2 - I*x**I /2 def _eval_rewrite_as_cos(self, arg, **kwargs): return cos(arg - S.Pi/2, evaluate=False) def _eval_rewrite_as_tan(self, arg, **kwargs): tan_half = tan(S.Half*arg) return 2*tan_half/(1 + tan_half**2) def _eval_rewrite_as_sincos(self, arg, **kwargs): return sin(arg)*cos(arg)/cos(arg) def _eval_rewrite_as_cot(self, arg, **kwargs): cot_half = cot(S.Half*arg) return 2*cot_half/(1 + cot_half**2) def _eval_rewrite_as_pow(self, arg, **kwargs): return self.rewrite(cos).rewrite(pow) def _eval_rewrite_as_sqrt(self, arg, **kwargs): return self.rewrite(cos).rewrite(sqrt) def _eval_rewrite_as_csc(self, arg, **kwargs): return 1/csc(arg) def _eval_rewrite_as_sec(self, arg, **kwargs): return 1/sec(arg - S.Pi/2, evaluate=False) def _eval_rewrite_as_sinc(self, arg, **kwargs): return arg*sinc(arg) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): re, im = self._as_real_imag(deep=deep, **hints) return (sin(re)*cosh(im), cos(re)*sinh(im)) def _eval_expand_trig(self, **hints): from sympy.functions.special.polynomials import chebyshevt, chebyshevu arg = self.args[0] x = None if arg.is_Add: # TODO, implement more if deep stuff here # TODO: Do this more efficiently for more than two terms x, y = arg.as_two_terms() sx = sin(x, evaluate=False)._eval_expand_trig() sy = sin(y, evaluate=False)._eval_expand_trig() cx = cos(x, evaluate=False)._eval_expand_trig() cy = cos(y, evaluate=False)._eval_expand_trig() return sx*cy + sy*cx elif arg.is_Mul: n, x = arg.as_coeff_Mul(rational=True) if n.is_Integer: # n will be positive because of .eval # canonicalization # See http://mathworld.wolfram.com/Multiple-AngleFormulas.html if n.is_odd: return S.NegativeOne**((n - 1)/2)*chebyshevt(n, sin(x)) else: return expand_mul(S.NegativeOne**(n/2 - 1)*cos(x)* chebyshevu(n - 1, sin(x)), deep=False) pi_coeff = _pi_coeff(arg) if pi_coeff is not None: if pi_coeff.is_Rational: return self.rewrite(sqrt) return sin(arg) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.functions.elementary.complexes import re from sympy.calculus.accumulationbounds import AccumBounds arg = self.args[0] x0 = arg.subs(x, 0).cancel() n = x0/S.Pi if n.is_integer: lt = (arg - n*S.Pi).as_leading_term(x) return (S.NegativeOne**n)*lt if x0 is S.ComplexInfinity: x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if x0 in [S.Infinity, S.NegativeInfinity]: return AccumBounds(-1, 1) return self.func(x0) if x0.is_finite else self def _eval_is_extended_real(self): if self.args[0].is_extended_real: return True def _eval_is_finite(self): arg = self.args[0] if arg.is_extended_real: return True def _eval_is_zero(self): rest, pi_mult = _peeloff_pi(self.args[0]) if rest.is_zero: return pi_mult.is_integer def _eval_is_complex(self): if self.args[0].is_extended_real \ or self.args[0].is_complex: return True class cos(TrigonometricFunction): """ The cosine function. Returns the cosine of x (measured in radians). Explanation =========== See :func:`sin` for notes about automatic evaluation. Examples ======== >>> from sympy import cos, pi >>> from sympy.abc import x >>> cos(x**2).diff(x) -2*x*sin(x**2) >>> cos(1).diff(x) 0 >>> cos(pi) -1 >>> cos(pi/2) 0 >>> cos(2*pi/3) -1/2 >>> cos(pi/12) sqrt(2)/4 + sqrt(6)/4 See Also ======== sin, csc, sec, tan, cot asin, acsc, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_functions .. [2] http://dlmf.nist.gov/4.14 .. [3] http://functions.wolfram.com/ElementaryFunctions/Cos """ def period(self, symbol=None): return self._period(2*pi, symbol) def fdiff(self, argindex=1): if argindex == 1: return -sin(self.args[0]) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): from sympy.functions.special.polynomials import chebyshevt from sympy.calculus.accumulationbounds import AccumBounds if arg.is_Number: if arg is S.NaN: return S.NaN elif arg.is_zero: return S.One elif arg in (S.Infinity, S.NegativeInfinity): # In this case it is better to return AccumBounds(-1, 1) # rather than returning S.NaN, since AccumBounds(-1, 1) # preserves the information that sin(oo) is between # -1 and 1, where S.NaN does not do that. return AccumBounds(-1, 1) if arg is S.ComplexInfinity: return S.NaN if isinstance(arg, AccumBounds): return sin(arg + S.Pi/2) elif isinstance(arg, SetExpr): return arg._eval_func(cls) if arg.is_extended_real and arg.is_finite is False: return AccumBounds(-1, 1) if arg.could_extract_minus_sign(): return cls(-arg) i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: return cosh(i_coeff) pi_coeff = _pi_coeff(arg) if pi_coeff is not None: if pi_coeff.is_integer: return (S.NegativeOne)**pi_coeff if (2*pi_coeff).is_integer: # is_even-case handled above as then pi_coeff.is_integer, # so check if known to be not even if pi_coeff.is_even is False: return S.Zero if not pi_coeff.is_Rational: narg = pi_coeff*S.Pi if narg != arg: return cls(narg) return None # cosine formula ##################### # https://github.com/sympy/sympy/issues/6048 # explicit calculations are performed for # cos(k pi/n) for n = 8,10,12,15,20,24,30,40,60,120 # Some other exact values like cos(k pi/240) can be # calculated using a partial-fraction decomposition # by calling cos( X ).rewrite(sqrt) cst_table_some = { 3: S.Half, 5: (sqrt(5) + 1)/4, } if pi_coeff.is_Rational: q = pi_coeff.q p = pi_coeff.p % (2*q) if p > q: narg = (pi_coeff - 1)*S.Pi return -cls(narg) if 2*p > q: narg = (1 - pi_coeff)*S.Pi return -cls(narg) # If nested sqrt's are worse than un-evaluation # you can require q to be in (1, 2, 3, 4, 6, 12) # q <= 12, q=15, q=20, q=24, q=30, q=40, q=60, q=120 return # expressions with 2 or fewer sqrt nestings. table2 = { 12: (3, 4), 20: (4, 5), 30: (5, 6), 15: (6, 10), 24: (6, 8), 40: (8, 10), 60: (20, 30), 120: (40, 60) } if q in table2: a, b = p*S.Pi/table2[q][0], p*S.Pi/table2[q][1] nvala, nvalb = cls(a), cls(b) if None in (nvala, nvalb): return None return nvala*nvalb + cls(S.Pi/2 - a)*cls(S.Pi/2 - b) if q > 12: return None if q in cst_table_some: cts = cst_table_some[pi_coeff.q] return chebyshevt(pi_coeff.p, cts).expand() if 0 == q % 2: narg = (pi_coeff*2)*S.Pi nval = cls(narg) if None == nval: return None x = (2*pi_coeff + 1)/2 sign_cos = (-1)**((-1 if x < 0 else 1)*int(abs(x))) return sign_cos*sqrt( (1 + nval)/2 ) return None if arg.is_Add: x, m = _peeloff_pi(arg) if m: m = m*S.Pi return cos(m)*cos(x) - sin(m)*sin(x) if arg.is_zero: return S.One if isinstance(arg, acos): return arg.args[0] if isinstance(arg, atan): x = arg.args[0] return 1/sqrt(1 + x**2) if isinstance(arg, atan2): y, x = arg.args return x/sqrt(x**2 + y**2) if isinstance(arg, asin): x = arg.args[0] return sqrt(1 - x ** 2) if isinstance(arg, acot): x = arg.args[0] return 1/sqrt(1 + 1/x**2) if isinstance(arg, acsc): x = arg.args[0] return sqrt(1 - 1/x**2) if isinstance(arg, asec): x = arg.args[0] return 1/x @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 1: return S.Zero else: x = sympify(x) if len(previous_terms) > 2: p = previous_terms[-2] return -p*x**2/(n*(n - 1)) else: return S.NegativeOne**(n//2)*x**n/factorial(n) def _eval_nseries(self, x, n, logx, cdir=0): arg = self.args[0] if logx is not None: arg = arg.subs(log(x), logx) if arg.subs(x, 0).has(S.NaN, S.ComplexInfinity): raise PoleError("Cannot expand %s around 0" % (self)) return Function._eval_nseries(self, x, n=n, logx=logx, cdir=cdir) def _eval_rewrite_as_exp(self, arg, **kwargs): I = S.ImaginaryUnit if isinstance(arg, (TrigonometricFunction, HyperbolicFunction)): arg = arg.func(arg.args[0]).rewrite(exp) return (exp(arg*I) + exp(-arg*I))/2 def _eval_rewrite_as_Pow(self, arg, **kwargs): if isinstance(arg, log): I = S.ImaginaryUnit x = arg.args[0] return x**I/2 + x**-I/2 def _eval_rewrite_as_sin(self, arg, **kwargs): return sin(arg + S.Pi/2, evaluate=False) def _eval_rewrite_as_tan(self, arg, **kwargs): tan_half = tan(S.Half*arg)**2 return (1 - tan_half)/(1 + tan_half) def _eval_rewrite_as_sincos(self, arg, **kwargs): return sin(arg)*cos(arg)/sin(arg) def _eval_rewrite_as_cot(self, arg, **kwargs): cot_half = cot(S.Half*arg)**2 return (cot_half - 1)/(cot_half + 1) def _eval_rewrite_as_pow(self, arg, **kwargs): return self._eval_rewrite_as_sqrt(arg) def _eval_rewrite_as_sqrt(self, arg, **kwargs): from sympy.functions.special.polynomials import chebyshevt def migcdex(x): # recursive calcuation of gcd and linear combination # for a sequence of integers. # Given (x1, x2, x3) # Returns (y1, y1, y3, g) # such that g is the gcd and x1*y1+x2*y2+x3*y3 - g = 0 # Note, that this is only one such linear combination. if len(x) == 1: return (1, x[0]) if len(x) == 2: return igcdex(x[0], x[-1]) g = migcdex(x[1:]) u, v, h = igcdex(x[0], g[-1]) return tuple([u] + [v*i for i in g[0:-1] ] + [h]) def ipartfrac(r, factors=None): from sympy.ntheory import factorint if isinstance(r, int): return r if not isinstance(r, Rational): raise TypeError("r is not rational") n = r.q if 2 > r.q*r.q: return r.q if None == factors: a = [n//x**y for x, y in factorint(r.q).items()] else: a = [n//x for x in factors] if len(a) == 1: return [ r ] h = migcdex(a) ans = [ r.p*Rational(i*j, r.q) for i, j in zip(h[:-1], a) ] assert r == sum(ans) return ans pi_coeff = _pi_coeff(arg) if pi_coeff is None: return None if pi_coeff.is_integer: # it was unevaluated return self.func(pi_coeff*S.Pi) if not pi_coeff.is_Rational: return None def _cospi257(): """ Express cos(pi/257) explicitly as a function of radicals Based upon the equations in http://math.stackexchange.com/questions/516142/how-does-cos2-pi-257-look-like-in-real-radicals See also http://www.susqu.edu/brakke/constructions/257-gon.m.txt """ def f1(a, b): return (a + sqrt(a**2 + b))/2, (a - sqrt(a**2 + b))/2 def f2(a, b): return (a - sqrt(a**2 + b))/2 t1, t2 = f1(-1, 256) z1, z3 = f1(t1, 64) z2, z4 = f1(t2, 64) y1, y5 = f1(z1, 4*(5 + t1 + 2*z1)) y6, y2 = f1(z2, 4*(5 + t2 + 2*z2)) y3, y7 = f1(z3, 4*(5 + t1 + 2*z3)) y8, y4 = f1(z4, 4*(5 + t2 + 2*z4)) x1, x9 = f1(y1, -4*(t1 + y1 + y3 + 2*y6)) x2, x10 = f1(y2, -4*(t2 + y2 + y4 + 2*y7)) x3, x11 = f1(y3, -4*(t1 + y3 + y5 + 2*y8)) x4, x12 = f1(y4, -4*(t2 + y4 + y6 + 2*y1)) x5, x13 = f1(y5, -4*(t1 + y5 + y7 + 2*y2)) x6, x14 = f1(y6, -4*(t2 + y6 + y8 + 2*y3)) x15, x7 = f1(y7, -4*(t1 + y7 + y1 + 2*y4)) x8, x16 = f1(y8, -4*(t2 + y8 + y2 + 2*y5)) v1 = f2(x1, -4*(x1 + x2 + x3 + x6)) v2 = f2(x2, -4*(x2 + x3 + x4 + x7)) v3 = f2(x8, -4*(x8 + x9 + x10 + x13)) v4 = f2(x9, -4*(x9 + x10 + x11 + x14)) v5 = f2(x10, -4*(x10 + x11 + x12 + x15)) v6 = f2(x16, -4*(x16 + x1 + x2 + x5)) u1 = -f2(-v1, -4*(v2 + v3)) u2 = -f2(-v4, -4*(v5 + v6)) w1 = -2*f2(-u1, -4*u2) return sqrt(sqrt(2)*sqrt(w1 + 4)/8 + S.Half) cst_table_some = { 3: S.Half, 5: (sqrt(5) + 1)/4, 17: sqrt((15 + sqrt(17))/32 + sqrt(2)*(sqrt(17 - sqrt(17)) + sqrt(sqrt(2)*(-8*sqrt(17 + sqrt(17)) - (1 - sqrt(17)) *sqrt(17 - sqrt(17))) + 6*sqrt(17) + 34))/32), 257: _cospi257() # 65537 is the only other known Fermat prime and the very # large expression is intentionally omitted from SymPy; see # http://www.susqu.edu/brakke/constructions/65537-gon.m.txt } def _fermatCoords(n): # if n can be factored in terms of Fermat primes with # multiplicity of each being 1, return those primes, else # False primes = [] for p_i in cst_table_some: quotient, remainder = divmod(n, p_i) if remainder == 0: n = quotient primes.append(p_i) if n == 1: return tuple(primes) return False if pi_coeff.q in cst_table_some: rv = chebyshevt(pi_coeff.p, cst_table_some[pi_coeff.q]) if pi_coeff.q < 257: rv = rv.expand() return rv if not pi_coeff.q % 2: # recursively remove factors of 2 pico2 = pi_coeff*2 nval = cos(pico2*S.Pi).rewrite(sqrt) x = (pico2 + 1)/2 sign_cos = -1 if int(x) % 2 else 1 return sign_cos*sqrt( (1 + nval)/2 ) FC = _fermatCoords(pi_coeff.q) if FC: decomp = ipartfrac(pi_coeff, FC) X = [(x[1], x[0]*S.Pi) for x in zip(decomp, numbered_symbols('z'))] pcls = cos(sum([x[0] for x in X]))._eval_expand_trig().subs(X) return pcls.rewrite(sqrt) else: decomp = ipartfrac(pi_coeff) X = [(x[1], x[0]*S.Pi) for x in zip(decomp, numbered_symbols('z'))] pcls = cos(sum([x[0] for x in X]))._eval_expand_trig().subs(X) return pcls def _eval_rewrite_as_sec(self, arg, **kwargs): return 1/sec(arg) def _eval_rewrite_as_csc(self, arg, **kwargs): return 1/sec(arg).rewrite(csc) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): re, im = self._as_real_imag(deep=deep, **hints) return (cos(re)*cosh(im), -sin(re)*sinh(im)) def _eval_expand_trig(self, **hints): from sympy.functions.special.polynomials import chebyshevt arg = self.args[0] x = None if arg.is_Add: # TODO: Do this more efficiently for more than two terms x, y = arg.as_two_terms() sx = sin(x, evaluate=False)._eval_expand_trig() sy = sin(y, evaluate=False)._eval_expand_trig() cx = cos(x, evaluate=False)._eval_expand_trig() cy = cos(y, evaluate=False)._eval_expand_trig() return cx*cy - sx*sy elif arg.is_Mul: coeff, terms = arg.as_coeff_Mul(rational=True) if coeff.is_Integer: return chebyshevt(coeff, cos(terms)) pi_coeff = _pi_coeff(arg) if pi_coeff is not None: if pi_coeff.is_Rational: return self.rewrite(sqrt) return cos(arg) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.functions.elementary.complexes import re from sympy.calculus.accumulationbounds import AccumBounds arg = self.args[0] x0 = arg.subs(x, 0).cancel() n = (x0 + S.Pi/2)/S.Pi if n.is_integer: lt = (arg - n*S.Pi + S.Pi/2).as_leading_term(x) return (S.NegativeOne**n)*lt if x0 is S.ComplexInfinity: x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if x0 in [S.Infinity, S.NegativeInfinity]: return AccumBounds(-1, 1) return self.func(x0) if x0.is_finite else self def _eval_is_extended_real(self): if self.args[0].is_extended_real: return True def _eval_is_finite(self): arg = self.args[0] if arg.is_extended_real: return True def _eval_is_complex(self): if self.args[0].is_extended_real \ or self.args[0].is_complex: return True def _eval_is_zero(self): rest, pi_mult = _peeloff_pi(self.args[0]) if pi_mult: return fuzzy_and([(pi_mult - S.Half).is_integer, rest.is_zero]) else: return rest.is_zero class tan(TrigonometricFunction): """ The tangent function. Returns the tangent of x (measured in radians). Explanation =========== See :func:`sin` for notes about automatic evaluation. Examples ======== >>> from sympy import tan, pi >>> from sympy.abc import x >>> tan(x**2).diff(x) 2*x*(tan(x**2)**2 + 1) >>> tan(1).diff(x) 0 >>> tan(pi/8).expand() -1 + sqrt(2) See Also ======== sin, csc, cos, sec, cot asin, acsc, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_functions .. [2] http://dlmf.nist.gov/4.14 .. [3] http://functions.wolfram.com/ElementaryFunctions/Tan """ def period(self, symbol=None): return self._period(pi, symbol) def fdiff(self, argindex=1): if argindex == 1: return S.One + self**2 else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return atan @classmethod def eval(cls, arg): from sympy.calculus.accumulationbounds import AccumBounds if arg.is_Number: if arg is S.NaN: return S.NaN elif arg.is_zero: return S.Zero elif arg in (S.Infinity, S.NegativeInfinity): return AccumBounds(S.NegativeInfinity, S.Infinity) if arg is S.ComplexInfinity: return S.NaN if isinstance(arg, AccumBounds): min, max = arg.min, arg.max d = floor(min/S.Pi) if min is not S.NegativeInfinity: min = min - d*S.Pi if max is not S.Infinity: max = max - d*S.Pi if AccumBounds(min, max).intersection(FiniteSet(S.Pi/2, S.Pi*Rational(3, 2))): return AccumBounds(S.NegativeInfinity, S.Infinity) else: return AccumBounds(tan(min), tan(max)) if arg.could_extract_minus_sign(): return -cls(-arg) i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: return S.ImaginaryUnit*tanh(i_coeff) pi_coeff = _pi_coeff(arg, 2) if pi_coeff is not None: if pi_coeff.is_integer: return S.Zero if not pi_coeff.is_Rational: narg = pi_coeff*S.Pi if narg != arg: return cls(narg) return None if pi_coeff.is_Rational: q = pi_coeff.q p = pi_coeff.p % q # ensure simplified results are returned for n*pi/5, n*pi/10 table10 = { 1: sqrt(1 - 2*sqrt(5)/5), 2: sqrt(5 - 2*sqrt(5)), 3: sqrt(1 + 2*sqrt(5)/5), 4: sqrt(5 + 2*sqrt(5)) } if q in (5, 10): n = 10*p/q if n > 5: n = 10 - n return -table10[n] else: return table10[n] if not pi_coeff.q % 2: narg = pi_coeff*S.Pi*2 cresult, sresult = cos(narg), cos(narg - S.Pi/2) if not isinstance(cresult, cos) \ and not isinstance(sresult, cos): if sresult == 0: return S.ComplexInfinity return 1/sresult - cresult/sresult table2 = { 12: (3, 4), 20: (4, 5), 30: (5, 6), 15: (6, 10), 24: (6, 8), 40: (8, 10), 60: (20, 30), 120: (40, 60) } if q in table2: nvala, nvalb = cls(p*S.Pi/table2[q][0]), cls(p*S.Pi/table2[q][1]) if None in (nvala, nvalb): return None return (nvala - nvalb)/(1 + nvala*nvalb) narg = ((pi_coeff + S.Half) % 1 - S.Half)*S.Pi # see cos() to specify which expressions should be # expanded automatically in terms of radicals cresult, sresult = cos(narg), cos(narg - S.Pi/2) if not isinstance(cresult, cos) \ and not isinstance(sresult, cos): if cresult == 0: return S.ComplexInfinity return (sresult/cresult) if narg != arg: return cls(narg) if arg.is_Add: x, m = _peeloff_pi(arg) if m: tanm = tan(m*S.Pi) if tanm is S.ComplexInfinity: return -cot(x) else: # tanm == 0 return tan(x) if arg.is_zero: return S.Zero if isinstance(arg, atan): return arg.args[0] if isinstance(arg, atan2): y, x = arg.args return y/x if isinstance(arg, asin): x = arg.args[0] return x/sqrt(1 - x**2) if isinstance(arg, acos): x = arg.args[0] return sqrt(1 - x**2)/x if isinstance(arg, acot): x = arg.args[0] return 1/x if isinstance(arg, acsc): x = arg.args[0] return 1/(sqrt(1 - 1/x**2)*x) if isinstance(arg, asec): x = arg.args[0] return sqrt(1 - 1/x**2)*x @staticmethod @cacheit def taylor_term(n, x, *previous_terms): from sympy.functions.combinatorial.numbers import bernoulli if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) a, b = ((n - 1)//2), 2**(n + 1) B = bernoulli(n + 1) F = factorial(n + 1) return S.NegativeOne**a*b*(b - 1)*B/F*x**n def _eval_nseries(self, x, n, logx, cdir=0): i = self.args[0].limit(x, 0)*2/S.Pi if i and i.is_Integer: return self.rewrite(cos)._eval_nseries(x, n=n, logx=logx) return Function._eval_nseries(self, x, n=n, logx=logx) def _eval_rewrite_as_Pow(self, arg, **kwargs): if isinstance(arg, log): I = S.ImaginaryUnit x = arg.args[0] return I*(x**-I - x**I)/(x**-I + x**I) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): re, im = self._as_real_imag(deep=deep, **hints) if im: denom = cos(2*re) + cosh(2*im) return (sin(2*re)/denom, sinh(2*im)/denom) else: return (self.func(re), S.Zero) def _eval_expand_trig(self, **hints): from sympy.functions.elementary.complexes import (im, re) arg = self.args[0] x = None if arg.is_Add: from sympy.polys.specialpolys import symmetric_poly n = len(arg.args) TX = [] for x in arg.args: tx = tan(x, evaluate=False)._eval_expand_trig() TX.append(tx) Yg = numbered_symbols('Y') Y = [ next(Yg) for i in range(n) ] p = [0, 0] for i in range(n + 1): p[1 - i % 2] += symmetric_poly(i, Y)*(-1)**((i % 4)//2) return (p[0]/p[1]).subs(list(zip(Y, TX))) elif arg.is_Mul: coeff, terms = arg.as_coeff_Mul(rational=True) if coeff.is_Integer and coeff > 1: I = S.ImaginaryUnit z = Symbol('dummy', real=True) P = ((1 + I*z)**coeff).expand() return (im(P)/re(P)).subs([(z, tan(terms))]) return tan(arg) def _eval_rewrite_as_exp(self, arg, **kwargs): I = S.ImaginaryUnit if isinstance(arg, (TrigonometricFunction, HyperbolicFunction)): arg = arg.func(arg.args[0]).rewrite(exp) neg_exp, pos_exp = exp(-arg*I), exp(arg*I) return I*(neg_exp - pos_exp)/(neg_exp + pos_exp) def _eval_rewrite_as_sin(self, x, **kwargs): return 2*sin(x)**2/sin(2*x) def _eval_rewrite_as_cos(self, x, **kwargs): return cos(x - S.Pi/2, evaluate=False)/cos(x) def _eval_rewrite_as_sincos(self, arg, **kwargs): return sin(arg)/cos(arg) def _eval_rewrite_as_cot(self, arg, **kwargs): return 1/cot(arg) def _eval_rewrite_as_sec(self, arg, **kwargs): sin_in_sec_form = sin(arg).rewrite(sec) cos_in_sec_form = cos(arg).rewrite(sec) return sin_in_sec_form/cos_in_sec_form def _eval_rewrite_as_csc(self, arg, **kwargs): sin_in_csc_form = sin(arg).rewrite(csc) cos_in_csc_form = cos(arg).rewrite(csc) return sin_in_csc_form/cos_in_csc_form def _eval_rewrite_as_pow(self, arg, **kwargs): y = self.rewrite(cos).rewrite(pow) if y.has(cos): return None return y def _eval_rewrite_as_sqrt(self, arg, **kwargs): y = self.rewrite(cos).rewrite(sqrt) if y.has(cos): return None return y def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0] x0 = arg.subs(x, 0).cancel() n = 2*x0/S.Pi if n.is_integer: lt = (arg - n*S.Pi/2).as_leading_term(x) return lt if n.is_even else -1/lt return self.func(x0) if x0.is_finite else self def _eval_is_extended_real(self): # FIXME: currently tan(pi/2) return zoo return self.args[0].is_extended_real def _eval_is_real(self): arg = self.args[0] if arg.is_real and (arg/pi - S.Half).is_integer is False: return True def _eval_is_finite(self): arg = self.args[0] if arg.is_real and (arg/pi - S.Half).is_integer is False: return True if arg.is_imaginary: return True def _eval_is_zero(self): rest, pi_mult = _peeloff_pi(self.args[0]) if rest.is_zero: return pi_mult.is_integer def _eval_is_complex(self): arg = self.args[0] if arg.is_real and (arg/pi - S.Half).is_integer is False: return True class cot(TrigonometricFunction): """ The cotangent function. Returns the cotangent of x (measured in radians). Explanation =========== See :func:`sin` for notes about automatic evaluation. Examples ======== >>> from sympy import cot, pi >>> from sympy.abc import x >>> cot(x**2).diff(x) 2*x*(-cot(x**2)**2 - 1) >>> cot(1).diff(x) 0 >>> cot(pi/12) sqrt(3) + 2 See Also ======== sin, csc, cos, sec, tan asin, acsc, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_functions .. [2] http://dlmf.nist.gov/4.14 .. [3] http://functions.wolfram.com/ElementaryFunctions/Cot """ def period(self, symbol=None): return self._period(pi, symbol) def fdiff(self, argindex=1): if argindex == 1: return S.NegativeOne - self**2 else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return acot @classmethod def eval(cls, arg): from sympy.calculus.accumulationbounds import AccumBounds if arg.is_Number: if arg is S.NaN: return S.NaN if arg.is_zero: return S.ComplexInfinity if arg is S.ComplexInfinity: return S.NaN if isinstance(arg, AccumBounds): return -tan(arg + S.Pi/2) if arg.could_extract_minus_sign(): return -cls(-arg) i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: return -S.ImaginaryUnit*coth(i_coeff) pi_coeff = _pi_coeff(arg, 2) if pi_coeff is not None: if pi_coeff.is_integer: return S.ComplexInfinity if not pi_coeff.is_Rational: narg = pi_coeff*S.Pi if narg != arg: return cls(narg) return None if pi_coeff.is_Rational: if pi_coeff.q in (5, 10): return tan(S.Pi/2 - arg) if pi_coeff.q > 2 and not pi_coeff.q % 2: narg = pi_coeff*S.Pi*2 cresult, sresult = cos(narg), cos(narg - S.Pi/2) if not isinstance(cresult, cos) \ and not isinstance(sresult, cos): return 1/sresult + cresult/sresult table2 = { 12: (3, 4), 20: (4, 5), 30: (5, 6), 15: (6, 10), 24: (6, 8), 40: (8, 10), 60: (20, 30), 120: (40, 60) } q = pi_coeff.q p = pi_coeff.p % q if q in table2: nvala, nvalb = cls(p*S.Pi/table2[q][0]), cls(p*S.Pi/table2[q][1]) if None in (nvala, nvalb): return None return (1 + nvala*nvalb)/(nvalb - nvala) narg = (((pi_coeff + S.Half) % 1) - S.Half)*S.Pi # see cos() to specify which expressions should be # expanded automatically in terms of radicals cresult, sresult = cos(narg), cos(narg - S.Pi/2) if not isinstance(cresult, cos) \ and not isinstance(sresult, cos): if sresult == 0: return S.ComplexInfinity return cresult/sresult if narg != arg: return cls(narg) if arg.is_Add: x, m = _peeloff_pi(arg) if m: cotm = cot(m*S.Pi) if cotm is S.ComplexInfinity: return cot(x) else: # cotm == 0 return -tan(x) if arg.is_zero: return S.ComplexInfinity if isinstance(arg, acot): return arg.args[0] if isinstance(arg, atan): x = arg.args[0] return 1/x if isinstance(arg, atan2): y, x = arg.args return x/y if isinstance(arg, asin): x = arg.args[0] return sqrt(1 - x**2)/x if isinstance(arg, acos): x = arg.args[0] return x/sqrt(1 - x**2) if isinstance(arg, acsc): x = arg.args[0] return sqrt(1 - 1/x**2)*x if isinstance(arg, asec): x = arg.args[0] return 1/(sqrt(1 - 1/x**2)*x) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): from sympy.functions.combinatorial.numbers import bernoulli if n == 0: return 1/sympify(x) elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) B = bernoulli(n + 1) F = factorial(n + 1) return S.NegativeOne**((n + 1)//2)*2**(n + 1)*B/F*x**n def _eval_nseries(self, x, n, logx, cdir=0): i = self.args[0].limit(x, 0)/S.Pi if i and i.is_Integer: return self.rewrite(cos)._eval_nseries(x, n=n, logx=logx) return self.rewrite(tan)._eval_nseries(x, n=n, logx=logx) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): re, im = self._as_real_imag(deep=deep, **hints) if im: denom = cos(2*re) - cosh(2*im) return (-sin(2*re)/denom, sinh(2*im)/denom) else: return (self.func(re), S.Zero) def _eval_rewrite_as_exp(self, arg, **kwargs): I = S.ImaginaryUnit if isinstance(arg, (TrigonometricFunction, HyperbolicFunction)): arg = arg.func(arg.args[0]).rewrite(exp) neg_exp, pos_exp = exp(-arg*I), exp(arg*I) return I*(pos_exp + neg_exp)/(pos_exp - neg_exp) def _eval_rewrite_as_Pow(self, arg, **kwargs): if isinstance(arg, log): I = S.ImaginaryUnit x = arg.args[0] return -I*(x**-I + x**I)/(x**-I - x**I) def _eval_rewrite_as_sin(self, x, **kwargs): return sin(2*x)/(2*(sin(x)**2)) def _eval_rewrite_as_cos(self, x, **kwargs): return cos(x)/cos(x - S.Pi/2, evaluate=False) def _eval_rewrite_as_sincos(self, arg, **kwargs): return cos(arg)/sin(arg) def _eval_rewrite_as_tan(self, arg, **kwargs): return 1/tan(arg) def _eval_rewrite_as_sec(self, arg, **kwargs): cos_in_sec_form = cos(arg).rewrite(sec) sin_in_sec_form = sin(arg).rewrite(sec) return cos_in_sec_form/sin_in_sec_form def _eval_rewrite_as_csc(self, arg, **kwargs): cos_in_csc_form = cos(arg).rewrite(csc) sin_in_csc_form = sin(arg).rewrite(csc) return cos_in_csc_form/sin_in_csc_form def _eval_rewrite_as_pow(self, arg, **kwargs): y = self.rewrite(cos).rewrite(pow) if y.has(cos): return None return y def _eval_rewrite_as_sqrt(self, arg, **kwargs): y = self.rewrite(cos).rewrite(sqrt) if y.has(cos): return None return y def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0] x0 = arg.subs(x, 0).cancel() n = 2*x0/S.Pi if n.is_integer: lt = (arg - n*S.Pi/2).as_leading_term(x) return 1/lt if n.is_even else -lt return self.func(x0) if x0.is_finite else self def _eval_is_extended_real(self): return self.args[0].is_extended_real def _eval_expand_trig(self, **hints): from sympy.functions.elementary.complexes import (im, re) arg = self.args[0] x = None if arg.is_Add: from sympy.polys.specialpolys import symmetric_poly n = len(arg.args) CX = [] for x in arg.args: cx = cot(x, evaluate=False)._eval_expand_trig() CX.append(cx) Yg = numbered_symbols('Y') Y = [ next(Yg) for i in range(n) ] p = [0, 0] for i in range(n, -1, -1): p[(n - i) % 2] += symmetric_poly(i, Y)*(-1)**(((n - i) % 4)//2) return (p[0]/p[1]).subs(list(zip(Y, CX))) elif arg.is_Mul: coeff, terms = arg.as_coeff_Mul(rational=True) if coeff.is_Integer and coeff > 1: I = S.ImaginaryUnit z = Symbol('dummy', real=True) P = ((z + I)**coeff).expand() return (re(P)/im(P)).subs([(z, cot(terms))]) return cot(arg) # XXX sec and csc return 1/cos and 1/sin def _eval_is_finite(self): arg = self.args[0] if arg.is_real and (arg/pi).is_integer is False: return True if arg.is_imaginary: return True def _eval_is_real(self): arg = self.args[0] if arg.is_real and (arg/pi).is_integer is False: return True def _eval_is_complex(self): arg = self.args[0] if arg.is_real and (arg/pi).is_integer is False: return True def _eval_is_zero(self): rest, pimult = _peeloff_pi(self.args[0]) if pimult and rest.is_zero: return (pimult - S.Half).is_integer def _eval_subs(self, old, new): arg = self.args[0] argnew = arg.subs(old, new) if arg != argnew and (argnew/S.Pi).is_integer: return S.ComplexInfinity return cot(argnew) class ReciprocalTrigonometricFunction(TrigonometricFunction): """Base class for reciprocal functions of trigonometric functions. """ _reciprocal_of = None # mandatory, to be defined in subclass _singularities = (S.ComplexInfinity,) # _is_even and _is_odd are used for correct evaluation of csc(-x), sec(-x) # TODO refactor into TrigonometricFunction common parts of # trigonometric functions eval() like even/odd, func(x+2*k*pi), etc. # optional, to be defined in subclasses: _is_even = None # type: FuzzyBool _is_odd = None # type: FuzzyBool @classmethod def eval(cls, arg): if arg.could_extract_minus_sign(): if cls._is_even: return cls(-arg) if cls._is_odd: return -cls(-arg) pi_coeff = _pi_coeff(arg) if (pi_coeff is not None and not (2*pi_coeff).is_integer and pi_coeff.is_Rational): q = pi_coeff.q p = pi_coeff.p % (2*q) if p > q: narg = (pi_coeff - 1)*S.Pi return -cls(narg) if 2*p > q: narg = (1 - pi_coeff)*S.Pi if cls._is_odd: return cls(narg) elif cls._is_even: return -cls(narg) if hasattr(arg, 'inverse') and arg.inverse() == cls: return arg.args[0] t = cls._reciprocal_of.eval(arg) if t is None: return t elif any(isinstance(i, cos) for i in (t, -t)): return (1/t).rewrite(sec) elif any(isinstance(i, sin) for i in (t, -t)): return (1/t).rewrite(csc) else: return 1/t def _call_reciprocal(self, method_name, *args, **kwargs): # Calls method_name on _reciprocal_of o = self._reciprocal_of(self.args[0]) return getattr(o, method_name)(*args, **kwargs) def _calculate_reciprocal(self, method_name, *args, **kwargs): # If calling method_name on _reciprocal_of returns a value != None # then return the reciprocal of that value t = self._call_reciprocal(method_name, *args, **kwargs) return 1/t if t is not None else t def _rewrite_reciprocal(self, method_name, arg): # Special handling for rewrite functions. If reciprocal rewrite returns # unmodified expression, then return None t = self._call_reciprocal(method_name, arg) if t is not None and t != self._reciprocal_of(arg): return 1/t def _period(self, symbol): f = expand_mul(self.args[0]) return self._reciprocal_of(f).period(symbol) def fdiff(self, argindex=1): return -self._calculate_reciprocal("fdiff", argindex)/self**2 def _eval_rewrite_as_exp(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_exp", arg) def _eval_rewrite_as_Pow(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_Pow", arg) def _eval_rewrite_as_sin(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_sin", arg) def _eval_rewrite_as_cos(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_cos", arg) def _eval_rewrite_as_tan(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_tan", arg) def _eval_rewrite_as_pow(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_pow", arg) def _eval_rewrite_as_sqrt(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_sqrt", arg) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): return (1/self._reciprocal_of(self.args[0])).as_real_imag(deep, **hints) def _eval_expand_trig(self, **hints): return self._calculate_reciprocal("_eval_expand_trig", **hints) def _eval_is_extended_real(self): return self._reciprocal_of(self.args[0])._eval_is_extended_real() def _eval_as_leading_term(self, x, logx=None, cdir=0): return (1/self._reciprocal_of(self.args[0]))._eval_as_leading_term(x) def _eval_is_finite(self): return (1/self._reciprocal_of(self.args[0])).is_finite def _eval_nseries(self, x, n, logx, cdir=0): return (1/self._reciprocal_of(self.args[0]))._eval_nseries(x, n, logx) class sec(ReciprocalTrigonometricFunction): """ The secant function. Returns the secant of x (measured in radians). Explanation =========== See :func:`sin` for notes about automatic evaluation. Examples ======== >>> from sympy import sec >>> from sympy.abc import x >>> sec(x**2).diff(x) 2*x*tan(x**2)*sec(x**2) >>> sec(1).diff(x) 0 See Also ======== sin, csc, cos, tan, cot asin, acsc, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_functions .. [2] http://dlmf.nist.gov/4.14 .. [3] http://functions.wolfram.com/ElementaryFunctions/Sec """ _reciprocal_of = cos _is_even = True def period(self, symbol=None): return self._period(symbol) def _eval_rewrite_as_cot(self, arg, **kwargs): cot_half_sq = cot(arg/2)**2 return (cot_half_sq + 1)/(cot_half_sq - 1) def _eval_rewrite_as_cos(self, arg, **kwargs): return (1/cos(arg)) def _eval_rewrite_as_sincos(self, arg, **kwargs): return sin(arg)/(cos(arg)*sin(arg)) def _eval_rewrite_as_sin(self, arg, **kwargs): return (1/cos(arg).rewrite(sin)) def _eval_rewrite_as_tan(self, arg, **kwargs): return (1/cos(arg).rewrite(tan)) def _eval_rewrite_as_csc(self, arg, **kwargs): return csc(pi/2 - arg, evaluate=False) def fdiff(self, argindex=1): if argindex == 1: return tan(self.args[0])*sec(self.args[0]) else: raise ArgumentIndexError(self, argindex) def _eval_is_complex(self): arg = self.args[0] if arg.is_complex and (arg/pi - S.Half).is_integer is False: return True @staticmethod @cacheit def taylor_term(n, x, *previous_terms): # Reference Formula: # http://functions.wolfram.com/ElementaryFunctions/Sec/06/01/02/01/ from sympy.functions.combinatorial.numbers import euler if n < 0 or n % 2 == 1: return S.Zero else: x = sympify(x) k = n//2 return S.NegativeOne**k*euler(2*k)/factorial(2*k)*x**(2*k) def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0] x0 = arg.subs(x, 0).cancel() n = (x0 + S.Pi/2)/S.Pi if n.is_integer: lt = (arg - n*S.Pi + S.Pi/2).as_leading_term(x) return (S.NegativeOne**n)/lt return self.func(x0) class csc(ReciprocalTrigonometricFunction): """ The cosecant function. Returns the cosecant of x (measured in radians). Explanation =========== See :func:`sin` for notes about automatic evaluation. Examples ======== >>> from sympy import csc >>> from sympy.abc import x >>> csc(x**2).diff(x) -2*x*cot(x**2)*csc(x**2) >>> csc(1).diff(x) 0 See Also ======== sin, cos, sec, tan, cot asin, acsc, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Trigonometric_functions .. [2] http://dlmf.nist.gov/4.14 .. [3] http://functions.wolfram.com/ElementaryFunctions/Csc """ _reciprocal_of = sin _is_odd = True def period(self, symbol=None): return self._period(symbol) def _eval_rewrite_as_sin(self, arg, **kwargs): return (1/sin(arg)) def _eval_rewrite_as_sincos(self, arg, **kwargs): return cos(arg)/(sin(arg)*cos(arg)) def _eval_rewrite_as_cot(self, arg, **kwargs): cot_half = cot(arg/2) return (1 + cot_half**2)/(2*cot_half) def _eval_rewrite_as_cos(self, arg, **kwargs): return 1/sin(arg).rewrite(cos) def _eval_rewrite_as_sec(self, arg, **kwargs): return sec(pi/2 - arg, evaluate=False) def _eval_rewrite_as_tan(self, arg, **kwargs): return (1/sin(arg).rewrite(tan)) def fdiff(self, argindex=1): if argindex == 1: return -cot(self.args[0])*csc(self.args[0]) else: raise ArgumentIndexError(self, argindex) def _eval_is_complex(self): arg = self.args[0] if arg.is_real and (arg/pi).is_integer is False: return True @staticmethod @cacheit def taylor_term(n, x, *previous_terms): from sympy.functions.combinatorial.numbers import bernoulli if n == 0: return 1/sympify(x) elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) k = n//2 + 1 return (S.NegativeOne**(k - 1)*2*(2**(2*k - 1) - 1)* bernoulli(2*k)*x**(2*k - 1)/factorial(2*k)) class sinc(Function): r""" Represents an unnormalized sinc function: .. math:: \operatorname{sinc}(x) = \begin{cases} \frac{\sin x}{x} & \qquad x \neq 0 \\ 1 & \qquad x = 0 \end{cases} Examples ======== >>> from sympy import sinc, oo, jn >>> from sympy.abc import x >>> sinc(x) sinc(x) * Automated Evaluation >>> sinc(0) 1 >>> sinc(oo) 0 * Differentiation >>> sinc(x).diff() cos(x)/x - sin(x)/x**2 * Series Expansion >>> sinc(x).series() 1 - x**2/6 + x**4/120 + O(x**6) * As zero'th order spherical Bessel Function >>> sinc(x).rewrite(jn) jn(0, x) See also ======== sin References ========== .. [1] https://en.wikipedia.org/wiki/Sinc_function """ _singularities = (S.ComplexInfinity,) def fdiff(self, argindex=1): x = self.args[0] if argindex == 1: # We would like to return the Piecewise here, but Piecewise.diff # currently can't handle removable singularities, meaning things # like sinc(x).diff(x, 2) give the wrong answer at x = 0. See # https://github.com/sympy/sympy/issues/11402. # # return Piecewise(((x*cos(x) - sin(x))/x**2, Ne(x, S.Zero)), (S.Zero, S.true)) return cos(x)/x - sin(x)/x**2 else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): if arg.is_zero: return S.One if arg.is_Number: if arg in [S.Infinity, S.NegativeInfinity]: return S.Zero elif arg is S.NaN: return S.NaN if arg is S.ComplexInfinity: return S.NaN if arg.could_extract_minus_sign(): return cls(-arg) pi_coeff = _pi_coeff(arg) if pi_coeff is not None: if pi_coeff.is_integer: if fuzzy_not(arg.is_zero): return S.Zero elif (2*pi_coeff).is_integer: return S.NegativeOne**(pi_coeff - S.Half)/arg def _eval_nseries(self, x, n, logx, cdir=0): x = self.args[0] return (sin(x)/x)._eval_nseries(x, n, logx) def _eval_rewrite_as_jn(self, arg, **kwargs): from sympy.functions.special.bessel import jn return jn(0, arg) def _eval_rewrite_as_sin(self, arg, **kwargs): return Piecewise((sin(arg)/arg, Ne(arg, S.Zero)), (S.One, S.true)) def _eval_is_zero(self): if self.args[0].is_infinite: return True rest, pi_mult = _peeloff_pi(self.args[0]) if rest.is_zero: return fuzzy_and([pi_mult.is_integer, pi_mult.is_nonzero]) if rest.is_Number and pi_mult.is_integer: return False def _eval_is_real(self): if self.args[0].is_extended_real or self.args[0].is_imaginary: return True _eval_is_finite = _eval_is_real ############################################################################### ########################### TRIGONOMETRIC INVERSES ############################ ############################################################################### class InverseTrigonometricFunction(Function): """Base class for inverse trigonometric functions.""" _singularities = (S.One, S.NegativeOne, S.Zero, S.ComplexInfinity) # type: tTuple[Expr, ...] @staticmethod def _asin_table(): # Only keys with could_extract_minus_sign() == False # are actually needed. return { sqrt(3)/2: S.Pi/3, sqrt(2)/2: S.Pi/4, 1/sqrt(2): S.Pi/4, sqrt((5 - sqrt(5))/8): S.Pi/5, sqrt(2)*sqrt(5 - sqrt(5))/4: S.Pi/5, sqrt((5 + sqrt(5))/8): S.Pi*Rational(2, 5), sqrt(2)*sqrt(5 + sqrt(5))/4: S.Pi*Rational(2, 5), S.Half: S.Pi/6, sqrt(2 - sqrt(2))/2: S.Pi/8, sqrt(S.Half - sqrt(2)/4): S.Pi/8, sqrt(2 + sqrt(2))/2: S.Pi*Rational(3, 8), sqrt(S.Half + sqrt(2)/4): S.Pi*Rational(3, 8), (sqrt(5) - 1)/4: S.Pi/10, (1 - sqrt(5))/4: -S.Pi/10, (sqrt(5) + 1)/4: S.Pi*Rational(3, 10), sqrt(6)/4 - sqrt(2)/4: S.Pi/12, -sqrt(6)/4 + sqrt(2)/4: -S.Pi/12, (sqrt(3) - 1)/sqrt(8): S.Pi/12, (1 - sqrt(3))/sqrt(8): -S.Pi/12, sqrt(6)/4 + sqrt(2)/4: S.Pi*Rational(5, 12), (1 + sqrt(3))/sqrt(8): S.Pi*Rational(5, 12) } @staticmethod def _atan_table(): # Only keys with could_extract_minus_sign() == False # are actually needed. return { sqrt(3)/3: S.Pi/6, 1/sqrt(3): S.Pi/6, sqrt(3): S.Pi/3, sqrt(2) - 1: S.Pi/8, 1 - sqrt(2): -S.Pi/8, 1 + sqrt(2): S.Pi*Rational(3, 8), sqrt(5 - 2*sqrt(5)): S.Pi/5, sqrt(5 + 2*sqrt(5)): S.Pi*Rational(2, 5), sqrt(1 - 2*sqrt(5)/5): S.Pi/10, sqrt(1 + 2*sqrt(5)/5): S.Pi*Rational(3, 10), 2 - sqrt(3): S.Pi/12, -2 + sqrt(3): -S.Pi/12, 2 + sqrt(3): S.Pi*Rational(5, 12) } @staticmethod def _acsc_table(): # Keys for which could_extract_minus_sign() # will obviously return True are omitted. return { 2*sqrt(3)/3: S.Pi/3, sqrt(2): S.Pi/4, sqrt(2 + 2*sqrt(5)/5): S.Pi/5, 1/sqrt(Rational(5, 8) - sqrt(5)/8): S.Pi/5, sqrt(2 - 2*sqrt(5)/5): S.Pi*Rational(2, 5), 1/sqrt(Rational(5, 8) + sqrt(5)/8): S.Pi*Rational(2, 5), 2: S.Pi/6, sqrt(4 + 2*sqrt(2)): S.Pi/8, 2/sqrt(2 - sqrt(2)): S.Pi/8, sqrt(4 - 2*sqrt(2)): S.Pi*Rational(3, 8), 2/sqrt(2 + sqrt(2)): S.Pi*Rational(3, 8), 1 + sqrt(5): S.Pi/10, sqrt(5) - 1: S.Pi*Rational(3, 10), -(sqrt(5) - 1): S.Pi*Rational(-3, 10), sqrt(6) + sqrt(2): S.Pi/12, sqrt(6) - sqrt(2): S.Pi*Rational(5, 12), -(sqrt(6) - sqrt(2)): S.Pi*Rational(-5, 12) } class asin(InverseTrigonometricFunction): """ The inverse sine function. Returns the arcsine of x in radians. Explanation =========== ``asin(x)`` will evaluate automatically in the cases ``oo``, ``-oo``, ``0``, ``1``, ``-1`` and for some instances when the result is a rational multiple of pi (see the eval class method). A purely imaginary argument will lead to an asinh expression. Examples ======== >>> from sympy import asin, oo >>> asin(1) pi/2 >>> asin(-1) -pi/2 >>> asin(-oo) oo*I >>> asin(oo) -oo*I See Also ======== sin, csc, cos, sec, tan, cot acsc, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions .. [2] http://dlmf.nist.gov/4.23 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcSin """ def fdiff(self, argindex=1): if argindex == 1: return 1/sqrt(1 - self.args[0]**2) else: raise ArgumentIndexError(self, argindex) def _eval_is_rational(self): s = self.func(*self.args) if s.func == self.func: if s.args[0].is_rational: return False else: return s.is_rational def _eval_is_positive(self): return self._eval_is_extended_real() and self.args[0].is_positive def _eval_is_negative(self): return self._eval_is_extended_real() and self.args[0].is_negative @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.NegativeInfinity*S.ImaginaryUnit elif arg is S.NegativeInfinity: return S.Infinity*S.ImaginaryUnit elif arg.is_zero: return S.Zero elif arg is S.One: return S.Pi/2 elif arg is S.NegativeOne: return -S.Pi/2 if arg is S.ComplexInfinity: return S.ComplexInfinity if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_number: asin_table = cls._asin_table() if arg in asin_table: return asin_table[arg] i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: return S.ImaginaryUnit*asinh(i_coeff) if arg.is_zero: return S.Zero if isinstance(arg, sin): ang = arg.args[0] if ang.is_comparable: ang %= 2*pi # restrict to [0,2*pi) if ang > pi: # restrict to (-pi,pi] ang = pi - ang # restrict to [-pi/2,pi/2] if ang > pi/2: ang = pi - ang if ang < -pi/2: ang = -pi - ang return ang if isinstance(arg, cos): # acos(x) + asin(x) = pi/2 ang = arg.args[0] if ang.is_comparable: return pi/2 - acos(arg) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) if len(previous_terms) >= 2 and n > 2: p = previous_terms[-2] return p*(n - 2)**2/(n*(n - 1))*x**2 else: k = (n - 1) // 2 R = RisingFactorial(S.Half, k) F = factorial(k) return R/F*x**n/n def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.functions.elementary.complexes import im arg = self.args[0] x0 = arg.subs(x, 0).cancel() if x0.is_zero: return arg.as_leading_term(x) if x0 is S.ComplexInfinity: return S.ImaginaryUnit*log(arg.as_leading_term(x)) if cdir != 0: cdir = arg.dir(x, cdir) if im(cdir) < 0 and x0.is_real and x0 < S.NegativeOne: return -S.Pi - self.func(x0) elif im(cdir) > 0 and x0.is_real and x0 > S.One: return S.Pi - self.func(x0) return self.func(x0) def _eval_nseries(self, x, n, logx, cdir=0): # asin from sympy.functions.elementary.complexes import im from sympy.series.order import O arg0 = self.args[0].subs(x, 0) if arg0 is S.One: t = Dummy('t', positive=True) ser = asin(S.One - t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.One - self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f if not g.is_meromorphic(x, 0): # cannot be expanded return O(1) if n == 0 else S.Pi/2 + O(sqrt(x)) res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) if arg0 is S.NegativeOne: t = Dummy('t', positive=True) ser = asin(S.NegativeOne + t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.One + self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f if not g.is_meromorphic(x, 0): # cannot be expanded return O(1) if n == 0 else -S.Pi/2 + O(sqrt(x)) res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) res = Function._eval_nseries(self, x, n=n, logx=logx) if arg0 is S.ComplexInfinity: return res if cdir != 0: cdir = self.args[0].dir(x, cdir) if im(cdir) < 0 and arg0.is_real and arg0 < S.NegativeOne: return -S.Pi - res elif im(cdir) > 0 and arg0.is_real and arg0 > S.One: return S.Pi - res return res def _eval_rewrite_as_acos(self, x, **kwargs): return S.Pi/2 - acos(x) def _eval_rewrite_as_atan(self, x, **kwargs): return 2*atan(x/(1 + sqrt(1 - x**2))) def _eval_rewrite_as_log(self, x, **kwargs): return -S.ImaginaryUnit*log(S.ImaginaryUnit*x + sqrt(1 - x**2)) def _eval_rewrite_as_acot(self, arg, **kwargs): return 2*acot((1 + sqrt(1 - arg**2))/arg) def _eval_rewrite_as_asec(self, arg, **kwargs): return S.Pi/2 - asec(1/arg) def _eval_rewrite_as_acsc(self, arg, **kwargs): return acsc(1/arg) def _eval_is_extended_real(self): x = self.args[0] return x.is_extended_real and (1 - abs(x)).is_nonnegative def inverse(self, argindex=1): """ Returns the inverse of this function. """ return sin class acos(InverseTrigonometricFunction): """ The inverse cosine function. Returns the arc cosine of x (measured in radians). Examples ======== ``acos(x)`` will evaluate automatically in the cases ``oo``, ``-oo``, ``0``, ``1``, ``-1`` and for some instances when the result is a rational multiple of pi (see the eval class method). ``acos(zoo)`` evaluates to ``zoo`` (see note in :class:`sympy.functions.elementary.trigonometric.asec`) A purely imaginary argument will be rewritten to asinh. Examples ======== >>> from sympy import acos, oo >>> acos(1) 0 >>> acos(0) pi/2 >>> acos(oo) oo*I See Also ======== sin, csc, cos, sec, tan, cot asin, acsc, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions .. [2] http://dlmf.nist.gov/4.23 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcCos """ def fdiff(self, argindex=1): if argindex == 1: return -1/sqrt(1 - self.args[0]**2) else: raise ArgumentIndexError(self, argindex) def _eval_is_rational(self): s = self.func(*self.args) if s.func == self.func: if s.args[0].is_rational: return False else: return s.is_rational @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity*S.ImaginaryUnit elif arg is S.NegativeInfinity: return S.NegativeInfinity*S.ImaginaryUnit elif arg.is_zero: return S.Pi/2 elif arg is S.One: return S.Zero elif arg is S.NegativeOne: return S.Pi if arg is S.ComplexInfinity: return S.ComplexInfinity if arg.is_number: asin_table = cls._asin_table() if arg in asin_table: return pi/2 - asin_table[arg] elif -arg in asin_table: return pi/2 + asin_table[-arg] i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: return pi/2 - asin(arg) if isinstance(arg, cos): ang = arg.args[0] if ang.is_comparable: ang %= 2*pi # restrict to [0,2*pi) if ang > pi: # restrict to [0,pi] ang = 2*pi - ang return ang if isinstance(arg, sin): # acos(x) + asin(x) = pi/2 ang = arg.args[0] if ang.is_comparable: return pi/2 - asin(arg) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return S.Pi/2 elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) if len(previous_terms) >= 2 and n > 2: p = previous_terms[-2] return p*(n - 2)**2/(n*(n - 1))*x**2 else: k = (n - 1) // 2 R = RisingFactorial(S.Half, k) F = factorial(k) return -R/F*x**n/n def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.functions.elementary.complexes import im arg = self.args[0] x0 = arg.subs(x, 0).cancel() if x0 == 1: return sqrt(2)*sqrt((S.One - arg).as_leading_term(x)) if x0 is S.ComplexInfinity: return S.ImaginaryUnit*log(arg.as_leading_term(x)) if cdir != 0: cdir = arg.dir(x, cdir) if im(cdir) < 0 and x0.is_real and x0 < S.NegativeOne: return 2*S.Pi - self.func(x0) elif im(cdir) > 0 and x0.is_real and x0 > S.One: return -self.func(x0) return self.func(x0) def _eval_is_extended_real(self): x = self.args[0] return x.is_extended_real and (1 - abs(x)).is_nonnegative def _eval_is_nonnegative(self): return self._eval_is_extended_real() def _eval_nseries(self, x, n, logx, cdir=0): # acos from sympy.functions.elementary.complexes import im from sympy.series.order import O arg0 = self.args[0].subs(x, 0) if arg0 is S.One: t = Dummy('t', positive=True) ser = acos(S.One - t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.One - self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f if not g.is_meromorphic(x, 0): # cannot be expanded return O(1) if n == 0 else O(sqrt(x)) res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) if arg0 is S.NegativeOne: t = Dummy('t', positive=True) ser = acos(S.NegativeOne + t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.One + self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f if not g.is_meromorphic(x, 0): # cannot be expanded return O(1) if n == 0 else S.Pi + O(sqrt(x)) res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) res = Function._eval_nseries(self, x, n=n, logx=logx) if arg0 is S.ComplexInfinity: return res if cdir != 0: cdir = self.args[0].dir(x, cdir) if im(cdir) < 0 and arg0.is_real and arg0 < S.NegativeOne: return 2*S.Pi - res elif im(cdir) > 0 and arg0.is_real and arg0 > S.One: return -res return res def _eval_rewrite_as_log(self, x, **kwargs): return S.Pi/2 + S.ImaginaryUnit*\ log(S.ImaginaryUnit*x + sqrt(1 - x**2)) def _eval_rewrite_as_asin(self, x, **kwargs): return S.Pi/2 - asin(x) def _eval_rewrite_as_atan(self, x, **kwargs): return atan(sqrt(1 - x**2)/x) + (S.Pi/2)*(1 - x*sqrt(1/x**2)) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return cos def _eval_rewrite_as_acot(self, arg, **kwargs): return S.Pi/2 - 2*acot((1 + sqrt(1 - arg**2))/arg) def _eval_rewrite_as_asec(self, arg, **kwargs): return asec(1/arg) def _eval_rewrite_as_acsc(self, arg, **kwargs): return S.Pi/2 - acsc(1/arg) def _eval_conjugate(self): z = self.args[0] r = self.func(self.args[0].conjugate()) if z.is_extended_real is False: return r elif z.is_extended_real and (z + 1).is_nonnegative and (z - 1).is_nonpositive: return r class atan(InverseTrigonometricFunction): """ The inverse tangent function. Returns the arc tangent of x (measured in radians). Explanation =========== ``atan(x)`` will evaluate automatically in the cases ``oo``, ``-oo``, ``0``, ``1``, ``-1`` and for some instances when the result is a rational multiple of pi (see the eval class method). Examples ======== >>> from sympy import atan, oo >>> atan(0) 0 >>> atan(1) pi/4 >>> atan(oo) pi/2 See Also ======== sin, csc, cos, sec, tan, cot asin, acsc, acos, asec, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions .. [2] http://dlmf.nist.gov/4.23 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcTan """ args: tTuple[Expr] _singularities = (S.ImaginaryUnit, -S.ImaginaryUnit) def fdiff(self, argindex=1): if argindex == 1: return 1/(1 + self.args[0]**2) else: raise ArgumentIndexError(self, argindex) def _eval_is_rational(self): s = self.func(*self.args) if s.func == self.func: if s.args[0].is_rational: return False else: return s.is_rational def _eval_is_positive(self): return self.args[0].is_extended_positive def _eval_is_nonnegative(self): return self.args[0].is_extended_nonnegative def _eval_is_zero(self): return self.args[0].is_zero def _eval_is_real(self): return self.args[0].is_extended_real @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Pi/2 elif arg is S.NegativeInfinity: return -S.Pi/2 elif arg.is_zero: return S.Zero elif arg is S.One: return S.Pi/4 elif arg is S.NegativeOne: return -S.Pi/4 if arg is S.ComplexInfinity: from sympy.calculus.accumulationbounds import AccumBounds return AccumBounds(-S.Pi/2, S.Pi/2) if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_number: atan_table = cls._atan_table() if arg in atan_table: return atan_table[arg] i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: return S.ImaginaryUnit*atanh(i_coeff) if arg.is_zero: return S.Zero if isinstance(arg, tan): ang = arg.args[0] if ang.is_comparable: ang %= pi # restrict to [0,pi) if ang > pi/2: # restrict to [-pi/2,pi/2] ang -= pi return ang if isinstance(arg, cot): # atan(x) + acot(x) = pi/2 ang = arg.args[0] if ang.is_comparable: ang = pi/2 - acot(arg) if ang > pi/2: # restrict to [-pi/2,pi/2] ang -= pi return ang @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) return S.NegativeOne**((n - 1)//2)*x**n/n def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.functions.elementary.complexes import (im, re) arg = self.args[0] x0 = arg.subs(x, 0).cancel() if x0.is_zero: return arg.as_leading_term(x) if x0 is S.ComplexInfinity: return acot(1/arg)._eval_as_leading_term(x, cdir=cdir) if cdir != 0: cdir = arg.dir(x, cdir) if re(cdir) < 0 and re(x0).is_zero and im(x0) > S.One: return self.func(x0) - S.Pi elif re(cdir) > 0 and re(x0).is_zero and im(x0) < S.NegativeOne: return self.func(x0) + S.Pi return self.func(x0) def _eval_nseries(self, x, n, logx, cdir=0): # atan from sympy.functions.elementary.complexes import (im, re) arg0 = self.args[0].subs(x, 0) res = Function._eval_nseries(self, x, n=n, logx=logx) if cdir != 0: cdir = self.args[0].dir(x, cdir) if arg0 is S.ComplexInfinity: if re(cdir) > 0: return res - S.Pi return res if re(cdir) < 0 and re(arg0).is_zero and im(arg0) > S.One: return res - S.Pi elif re(cdir) > 0 and re(arg0).is_zero and im(arg0) < S.NegativeOne: return res + S.Pi return res def _eval_rewrite_as_log(self, x, **kwargs): return S.ImaginaryUnit/2*(log(S.One - S.ImaginaryUnit*x) - log(S.One + S.ImaginaryUnit*x)) def _eval_aseries(self, n, args0, x, logx): if args0[0] is S.Infinity: return (S.Pi/2 - atan(1/self.args[0]))._eval_nseries(x, n, logx) elif args0[0] is S.NegativeInfinity: return (-S.Pi/2 - atan(1/self.args[0]))._eval_nseries(x, n, logx) else: return super()._eval_aseries(n, args0, x, logx) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return tan def _eval_rewrite_as_asin(self, arg, **kwargs): return sqrt(arg**2)/arg*(S.Pi/2 - asin(1/sqrt(1 + arg**2))) def _eval_rewrite_as_acos(self, arg, **kwargs): return sqrt(arg**2)/arg*acos(1/sqrt(1 + arg**2)) def _eval_rewrite_as_acot(self, arg, **kwargs): return acot(1/arg) def _eval_rewrite_as_asec(self, arg, **kwargs): return sqrt(arg**2)/arg*asec(sqrt(1 + arg**2)) def _eval_rewrite_as_acsc(self, arg, **kwargs): return sqrt(arg**2)/arg*(S.Pi/2 - acsc(sqrt(1 + arg**2))) class acot(InverseTrigonometricFunction): r""" The inverse cotangent function. Returns the arc cotangent of x (measured in radians). Explanation =========== ``acot(x)`` will evaluate automatically in the cases ``oo``, ``-oo``, ``zoo``, ``0``, ``1``, ``-1`` and for some instances when the result is a rational multiple of pi (see the eval class method). A purely imaginary argument will lead to an ``acoth`` expression. ``acot(x)`` has a branch cut along `(-i, i)`, hence it is discontinuous at 0. Its range for real ``x`` is `(-\frac{\pi}{2}, \frac{\pi}{2}]`. Examples ======== >>> from sympy import acot, sqrt >>> acot(0) pi/2 >>> acot(1) pi/4 >>> acot(sqrt(3) - 2) -5*pi/12 See Also ======== sin, csc, cos, sec, tan, cot asin, acsc, acos, asec, atan, atan2 References ========== .. [1] http://dlmf.nist.gov/4.23 .. [2] http://functions.wolfram.com/ElementaryFunctions/ArcCot """ _singularities = (S.ImaginaryUnit, -S.ImaginaryUnit) def fdiff(self, argindex=1): if argindex == 1: return -1/(1 + self.args[0]**2) else: raise ArgumentIndexError(self, argindex) def _eval_is_rational(self): s = self.func(*self.args) if s.func == self.func: if s.args[0].is_rational: return False else: return s.is_rational def _eval_is_positive(self): return self.args[0].is_nonnegative def _eval_is_negative(self): return self.args[0].is_negative def _eval_is_extended_real(self): return self.args[0].is_extended_real @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Zero elif arg is S.NegativeInfinity: return S.Zero elif arg.is_zero: return S.Pi/ 2 elif arg is S.One: return S.Pi/4 elif arg is S.NegativeOne: return -S.Pi/4 if arg is S.ComplexInfinity: return S.Zero if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_number: atan_table = cls._atan_table() if arg in atan_table: ang = pi/2 - atan_table[arg] if ang > pi/2: # restrict to (-pi/2,pi/2] ang -= pi return ang i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: return -S.ImaginaryUnit*acoth(i_coeff) if arg.is_zero: return S.Pi*S.Half if isinstance(arg, cot): ang = arg.args[0] if ang.is_comparable: ang %= pi # restrict to [0,pi) if ang > pi/2: # restrict to (-pi/2,pi/2] ang -= pi; return ang if isinstance(arg, tan): # atan(x) + acot(x) = pi/2 ang = arg.args[0] if ang.is_comparable: ang = pi/2 - atan(arg) if ang > pi/2: # restrict to (-pi/2,pi/2] ang -= pi return ang @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return S.Pi/2 # FIX THIS elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) return S.NegativeOne**((n + 1)//2)*x**n/n def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.functions.elementary.complexes import (im, re) arg = self.args[0] x0 = arg.subs(x, 0).cancel() if x0 is S.ComplexInfinity: return (1/arg).as_leading_term(x) if cdir != 0: cdir = arg.dir(x, cdir) if x0.is_zero: if re(cdir) < 0: return self.func(x0) - S.Pi return self.func(x0) if re(cdir) > 0 and re(x0).is_zero and im(x0) > S.Zero and im(x0) < S.One: return self.func(x0) + S.Pi if re(cdir) < 0 and re(x0).is_zero and im(x0) < S.Zero and im(x0) > S.NegativeOne: return self.func(x0) - S.Pi return self.func(x0) def _eval_nseries(self, x, n, logx, cdir=0): # acot from sympy.functions.elementary.complexes import (im, re) arg0 = self.args[0].subs(x, 0) res = Function._eval_nseries(self, x, n=n, logx=logx) if arg0 is S.ComplexInfinity: return res if cdir != 0: cdir = self.args[0].dir(x, cdir) if arg0.is_zero: if re(cdir) < 0: return res - S.Pi return res if re(cdir) > 0 and re(arg0).is_zero and im(arg0) > S.Zero and im(arg0) < S.One: return res + S.Pi if re(cdir) < 0 and re(arg0).is_zero and im(arg0) < S.Zero and im(arg0) > S.NegativeOne: return res - S.Pi return res def _eval_aseries(self, n, args0, x, logx): if args0[0] is S.Infinity: return (S.Pi/2 - acot(1/self.args[0]))._eval_nseries(x, n, logx) elif args0[0] is S.NegativeInfinity: return (S.Pi*Rational(3, 2) - acot(1/self.args[0]))._eval_nseries(x, n, logx) else: return super(atan, self)._eval_aseries(n, args0, x, logx) def _eval_rewrite_as_log(self, x, **kwargs): return S.ImaginaryUnit/2*(log(1 - S.ImaginaryUnit/x) - log(1 + S.ImaginaryUnit/x)) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return cot def _eval_rewrite_as_asin(self, arg, **kwargs): return (arg*sqrt(1/arg**2)* (S.Pi/2 - asin(sqrt(-arg**2)/sqrt(-arg**2 - 1)))) def _eval_rewrite_as_acos(self, arg, **kwargs): return arg*sqrt(1/arg**2)*acos(sqrt(-arg**2)/sqrt(-arg**2 - 1)) def _eval_rewrite_as_atan(self, arg, **kwargs): return atan(1/arg) def _eval_rewrite_as_asec(self, arg, **kwargs): return arg*sqrt(1/arg**2)*asec(sqrt((1 + arg**2)/arg**2)) def _eval_rewrite_as_acsc(self, arg, **kwargs): return arg*sqrt(1/arg**2)*(S.Pi/2 - acsc(sqrt((1 + arg**2)/arg**2))) class asec(InverseTrigonometricFunction): r""" The inverse secant function. Returns the arc secant of x (measured in radians). Explanation =========== ``asec(x)`` will evaluate automatically in the cases ``oo``, ``-oo``, ``0``, ``1``, ``-1`` and for some instances when the result is a rational multiple of pi (see the eval class method). ``asec(x)`` has branch cut in the interval [-1, 1]. For complex arguments, it can be defined [4]_ as .. math:: \operatorname{sec^{-1}}(z) = -i\frac{\log\left(\sqrt{1 - z^2} + 1\right)}{z} At ``x = 0``, for positive branch cut, the limit evaluates to ``zoo``. For negative branch cut, the limit .. math:: \lim_{z \to 0}-i\frac{\log\left(-\sqrt{1 - z^2} + 1\right)}{z} simplifies to :math:`-i\log\left(z/2 + O\left(z^3\right)\right)` which ultimately evaluates to ``zoo``. As ``acos(x)`` = ``asec(1/x)``, a similar argument can be given for ``acos(x)``. Examples ======== >>> from sympy import asec, oo >>> asec(1) 0 >>> asec(-1) pi >>> asec(0) zoo >>> asec(-oo) pi/2 See Also ======== sin, csc, cos, sec, tan, cot asin, acsc, acos, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions .. [2] http://dlmf.nist.gov/4.23 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcSec .. [4] http://reference.wolfram.com/language/ref/ArcSec.html """ @classmethod def eval(cls, arg): if arg.is_zero: return S.ComplexInfinity if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.One: return S.Zero elif arg is S.NegativeOne: return S.Pi if arg in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]: return S.Pi/2 if arg.is_number: acsc_table = cls._acsc_table() if arg in acsc_table: return pi/2 - acsc_table[arg] elif -arg in acsc_table: return pi/2 + acsc_table[-arg] if isinstance(arg, sec): ang = arg.args[0] if ang.is_comparable: ang %= 2*pi # restrict to [0,2*pi) if ang > pi: # restrict to [0,pi] ang = 2*pi - ang return ang if isinstance(arg, csc): # asec(x) + acsc(x) = pi/2 ang = arg.args[0] if ang.is_comparable: return pi/2 - acsc(arg) def fdiff(self, argindex=1): if argindex == 1: return 1/(self.args[0]**2*sqrt(1 - 1/self.args[0]**2)) else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return sec def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.functions.elementary.complexes import im arg = self.args[0] x0 = arg.subs(x, 0).cancel() if x0 == 1: return sqrt(2)*sqrt((arg - S.One).as_leading_term(x)) if x0.is_zero: return S.ImaginaryUnit*log(arg.as_leading_term(x)) if cdir != 0: cdir = arg.dir(x, cdir) if im(cdir) < 0 and x0.is_real and x0 > S.Zero and x0 < S.One: return -self.func(x0) elif im(cdir) > 0 and x0.is_real and x0 < S.Zero and x0 > S.NegativeOne: return 2*S.Pi - self.func(x0) return self.func(x0) def _eval_nseries(self, x, n, logx, cdir=0): # asec from sympy.functions.elementary.complexes import im from sympy.series.order import O arg0 = self.args[0].subs(x, 0) if arg0 is S.One: t = Dummy('t', positive=True) ser = asec(S.One + t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.NegativeOne + self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) if arg0 is S.NegativeOne: t = Dummy('t', positive=True) ser = asec(S.NegativeOne - t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.NegativeOne - self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) res = Function._eval_nseries(self, x, n=n, logx=logx) if arg0 is S.ComplexInfinity: return res if cdir != 0: cdir = self.args[0].dir(x, cdir) if im(cdir) < 0 and arg0.is_real and arg0 > S.Zero and arg0 < S.One: return -res elif im(cdir) > 0 and arg0.is_real and arg0 < S.Zero and arg0 > S.NegativeOne: return 2*S.Pi - res return res def _eval_is_extended_real(self): x = self.args[0] if x.is_extended_real is False: return False return fuzzy_or(((x - 1).is_nonnegative, (-x - 1).is_nonnegative)) def _eval_rewrite_as_log(self, arg, **kwargs): return S.Pi/2 + S.ImaginaryUnit*log(S.ImaginaryUnit/arg + sqrt(1 - 1/arg**2)) def _eval_rewrite_as_asin(self, arg, **kwargs): return S.Pi/2 - asin(1/arg) def _eval_rewrite_as_acos(self, arg, **kwargs): return acos(1/arg) def _eval_rewrite_as_atan(self, arg, **kwargs): return sqrt(arg**2)/arg*(-S.Pi/2 + 2*atan(arg + sqrt(arg**2 - 1))) def _eval_rewrite_as_acot(self, arg, **kwargs): return sqrt(arg**2)/arg*(-S.Pi/2 + 2*acot(arg - sqrt(arg**2 - 1))) def _eval_rewrite_as_acsc(self, arg, **kwargs): return S.Pi/2 - acsc(arg) class acsc(InverseTrigonometricFunction): """ The inverse cosecant function. Returns the arc cosecant of x (measured in radians). Explanation =========== ``acsc(x)`` will evaluate automatically in the cases ``oo``, ``-oo``, ``0``, ``1``, ``-1`` and for some instances when the result is a rational multiple of pi (see the eval class method). Examples ======== >>> from sympy import acsc, oo >>> acsc(1) pi/2 >>> acsc(-1) -pi/2 >>> acsc(oo) 0 >>> acsc(-oo) == acsc(oo) True >>> acsc(0) zoo See Also ======== sin, csc, cos, sec, tan, cot asin, acos, asec, atan, acot, atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions .. [2] http://dlmf.nist.gov/4.23 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcCsc """ @classmethod def eval(cls, arg): if arg.is_zero: return S.ComplexInfinity if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.One: return S.Pi/2 elif arg is S.NegativeOne: return -S.Pi/2 if arg in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]: return S.Zero if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_number: acsc_table = cls._acsc_table() if arg in acsc_table: return acsc_table[arg] if isinstance(arg, csc): ang = arg.args[0] if ang.is_comparable: ang %= 2*pi # restrict to [0,2*pi) if ang > pi: # restrict to (-pi,pi] ang = pi - ang # restrict to [-pi/2,pi/2] if ang > pi/2: ang = pi - ang if ang < -pi/2: ang = -pi - ang return ang if isinstance(arg, sec): # asec(x) + acsc(x) = pi/2 ang = arg.args[0] if ang.is_comparable: return pi/2 - asec(arg) def fdiff(self, argindex=1): if argindex == 1: return -1/(self.args[0]**2*sqrt(1 - 1/self.args[0]**2)) else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return csc def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.functions.elementary.complexes import im arg = self.args[0] x0 = arg.subs(x, 0).cancel() if x0.is_zero: return S.ImaginaryUnit*log(arg.as_leading_term(x)) if x0 is S.ComplexInfinity: return arg.as_leading_term(x) if cdir != 0: cdir = arg.dir(x, cdir) if im(cdir) < 0 and x0.is_real and x0 > S.Zero and x0 < S.One: return S.Pi - self.func(x0) elif im(cdir) > 0 and x0.is_real and x0 < S.Zero and x0 > S.NegativeOne: return -S.Pi - self.func(x0) return self.func(x0) def _eval_nseries(self, x, n, logx, cdir=0): # acsc from sympy.functions.elementary.complexes import im from sympy.series.order import O arg0 = self.args[0].subs(x, 0) if arg0 is S.One: t = Dummy('t', positive=True) ser = acsc(S.One + t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.NegativeOne + self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) if arg0 is S.NegativeOne: t = Dummy('t', positive=True) ser = acsc(S.NegativeOne - t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.NegativeOne - self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) res = Function._eval_nseries(self, x, n=n, logx=logx) if arg0 is S.ComplexInfinity: return res if cdir != 0: cdir = self.args[0].dir(x, cdir) if im(cdir) < 0 and arg0.is_real and arg0 > S.Zero and arg0 < S.One: return S.Pi - res elif im(cdir) > 0 and arg0.is_real and arg0 < S.Zero and arg0 > S.NegativeOne: return -S.Pi - res return res def _eval_rewrite_as_log(self, arg, **kwargs): return -S.ImaginaryUnit*log(S.ImaginaryUnit/arg + sqrt(1 - 1/arg**2)) def _eval_rewrite_as_asin(self, arg, **kwargs): return asin(1/arg) def _eval_rewrite_as_acos(self, arg, **kwargs): return S.Pi/2 - acos(1/arg) def _eval_rewrite_as_atan(self, arg, **kwargs): return sqrt(arg**2)/arg*(S.Pi/2 - atan(sqrt(arg**2 - 1))) def _eval_rewrite_as_acot(self, arg, **kwargs): return sqrt(arg**2)/arg*(S.Pi/2 - acot(1/sqrt(arg**2 - 1))) def _eval_rewrite_as_asec(self, arg, **kwargs): return S.Pi/2 - asec(arg) class atan2(InverseTrigonometricFunction): r""" The function ``atan2(y, x)`` computes `\operatorname{atan}(y/x)` taking two arguments `y` and `x`. Signs of both `y` and `x` are considered to determine the appropriate quadrant of `\operatorname{atan}(y/x)`. The range is `(-\pi, \pi]`. The complete definition reads as follows: .. math:: \operatorname{atan2}(y, x) = \begin{cases} \arctan\left(\frac y x\right) & \qquad x > 0 \\ \arctan\left(\frac y x\right) + \pi& \qquad y \ge 0, x < 0 \\ \arctan\left(\frac y x\right) - \pi& \qquad y < 0, x < 0 \\ +\frac{\pi}{2} & \qquad y > 0, x = 0 \\ -\frac{\pi}{2} & \qquad y < 0, x = 0 \\ \text{undefined} & \qquad y = 0, x = 0 \end{cases} Attention: Note the role reversal of both arguments. The `y`-coordinate is the first argument and the `x`-coordinate the second. If either `x` or `y` is complex: .. math:: \operatorname{atan2}(y, x) = -i\log\left(\frac{x + iy}{\sqrt{x^2 + y^2}}\right) Examples ======== Going counter-clock wise around the origin we find the following angles: >>> from sympy import atan2 >>> atan2(0, 1) 0 >>> atan2(1, 1) pi/4 >>> atan2(1, 0) pi/2 >>> atan2(1, -1) 3*pi/4 >>> atan2(0, -1) pi >>> atan2(-1, -1) -3*pi/4 >>> atan2(-1, 0) -pi/2 >>> atan2(-1, 1) -pi/4 which are all correct. Compare this to the results of the ordinary `\operatorname{atan}` function for the point `(x, y) = (-1, 1)` >>> from sympy import atan, S >>> atan(S(1)/-1) -pi/4 >>> atan2(1, -1) 3*pi/4 where only the `\operatorname{atan2}` function reurns what we expect. We can differentiate the function with respect to both arguments: >>> from sympy import diff >>> from sympy.abc import x, y >>> diff(atan2(y, x), x) -y/(x**2 + y**2) >>> diff(atan2(y, x), y) x/(x**2 + y**2) We can express the `\operatorname{atan2}` function in terms of complex logarithms: >>> from sympy import log >>> atan2(y, x).rewrite(log) -I*log((x + I*y)/sqrt(x**2 + y**2)) and in terms of `\operatorname(atan)`: >>> from sympy import atan >>> atan2(y, x).rewrite(atan) Piecewise((2*atan(y/(x + sqrt(x**2 + y**2))), Ne(y, 0)), (pi, re(x) < 0), (0, Ne(x, 0)), (nan, True)) but note that this form is undefined on the negative real axis. See Also ======== sin, csc, cos, sec, tan, cot asin, acsc, acos, asec, atan, acot References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions .. [2] https://en.wikipedia.org/wiki/Atan2 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcTan2 """ @classmethod def eval(cls, y, x): from sympy.functions.elementary.complexes import (im, re) from sympy.functions.special.delta_functions import Heaviside if x is S.NegativeInfinity: if y.is_zero: # Special case y = 0 because we define Heaviside(0) = 1/2 return S.Pi return 2*S.Pi*(Heaviside(re(y))) - S.Pi elif x is S.Infinity: return S.Zero elif x.is_imaginary and y.is_imaginary and x.is_number and y.is_number: x = im(x) y = im(y) if x.is_extended_real and y.is_extended_real: if x.is_positive: return atan(y/x) elif x.is_negative: if y.is_negative: return atan(y/x) - S.Pi elif y.is_nonnegative: return atan(y/x) + S.Pi elif x.is_zero: if y.is_positive: return S.Pi/2 elif y.is_negative: return -S.Pi/2 elif y.is_zero: return S.NaN if y.is_zero: if x.is_extended_nonzero: return S.Pi*(S.One - Heaviside(x)) if x.is_number: return Piecewise((S.Pi, re(x) < 0), (0, Ne(x, 0)), (S.NaN, True)) if x.is_number and y.is_number: return -S.ImaginaryUnit*log( (x + S.ImaginaryUnit*y)/sqrt(x**2 + y**2)) def _eval_rewrite_as_log(self, y, x, **kwargs): return -S.ImaginaryUnit*log((x + S.ImaginaryUnit*y)/sqrt(x**2 + y**2)) def _eval_rewrite_as_atan(self, y, x, **kwargs): from sympy.functions.elementary.complexes import re return Piecewise((2*atan(y/(x + sqrt(x**2 + y**2))), Ne(y, 0)), (pi, re(x) < 0), (0, Ne(x, 0)), (S.NaN, True)) def _eval_rewrite_as_arg(self, y, x, **kwargs): from sympy.functions.elementary.complexes import arg if x.is_extended_real and y.is_extended_real: return arg(x + y*S.ImaginaryUnit) n = x + S.ImaginaryUnit*y d = x**2 + y**2 return arg(n/sqrt(d)) - S.ImaginaryUnit*log(abs(n)/sqrt(abs(d))) def _eval_is_extended_real(self): return self.args[0].is_extended_real and self.args[1].is_extended_real def _eval_conjugate(self): return self.func(self.args[0].conjugate(), self.args[1].conjugate()) def fdiff(self, argindex): y, x = self.args if argindex == 1: # Diff wrt y return x/(x**2 + y**2) elif argindex == 2: # Diff wrt x return -y/(x**2 + y**2) else: raise ArgumentIndexError(self, argindex) def _eval_evalf(self, prec): y, x = self.args if x.is_extended_real and y.is_extended_real: return super()._eval_evalf(prec)
fa344abeb70e90513f3ca66f27dacc5e77ef3b65902024a05c629d58630c9e88
from sympy.core import Function, S, sympify, NumberKind from sympy.utilities.iterables import sift from sympy.core.add import Add from sympy.core.containers import Tuple from sympy.core.operations import LatticeOp, ShortCircuit from sympy.core.function import (Application, Lambda, ArgumentIndexError) from sympy.core.expr import Expr from sympy.core.exprtools import factor_terms from sympy.core.mod import Mod from sympy.core.mul import Mul from sympy.core.numbers import Rational from sympy.core.power import Pow from sympy.core.relational import Eq, Relational from sympy.core.singleton import Singleton from sympy.core.sorting import ordered from sympy.core.symbol import Dummy from sympy.core.rules import Transform from sympy.core.logic import fuzzy_and, fuzzy_or, _torf from sympy.core.traversal import walk from sympy.core.numbers import Integer from sympy.logic.boolalg import And, Or def _minmax_as_Piecewise(op, *args): # helper for Min/Max rewrite as Piecewise from sympy.functions.elementary.piecewise import Piecewise ec = [] for i, a in enumerate(args): c = [] for j in range(i + 1, len(args)): c.append(Relational(a, args[j], op)) ec.append((a, And(*c))) return Piecewise(*ec) class IdentityFunction(Lambda, metaclass=Singleton): """ The identity function Examples ======== >>> from sympy import Id, Symbol >>> x = Symbol('x') >>> Id(x) x """ _symbol = Dummy('x') @property def signature(self): return Tuple(self._symbol) @property def expr(self): return self._symbol Id = S.IdentityFunction ############################################################################### ############################# ROOT and SQUARE ROOT FUNCTION ################### ############################################################################### def sqrt(arg, evaluate=None): """Returns the principal square root. Parameters ========== evaluate : bool, optional The parameter determines if the expression should be evaluated. If ``None``, its value is taken from ``global_parameters.evaluate``. Examples ======== >>> from sympy import sqrt, Symbol, S >>> x = Symbol('x') >>> sqrt(x) sqrt(x) >>> sqrt(x)**2 x Note that sqrt(x**2) does not simplify to x. >>> sqrt(x**2) sqrt(x**2) This is because the two are not equal to each other in general. For example, consider x == -1: >>> from sympy import Eq >>> Eq(sqrt(x**2), x).subs(x, -1) False This is because sqrt computes the principal square root, so the square may put the argument in a different branch. This identity does hold if x is positive: >>> y = Symbol('y', positive=True) >>> sqrt(y**2) y You can force this simplification by using the powdenest() function with the force option set to True: >>> from sympy import powdenest >>> sqrt(x**2) sqrt(x**2) >>> powdenest(sqrt(x**2), force=True) x To get both branches of the square root you can use the rootof function: >>> from sympy import rootof >>> [rootof(x**2-3,i) for i in (0,1)] [-sqrt(3), sqrt(3)] Although ``sqrt`` is printed, there is no ``sqrt`` function so looking for ``sqrt`` in an expression will fail: >>> from sympy.utilities.misc import func_name >>> func_name(sqrt(x)) 'Pow' >>> sqrt(x).has(sqrt) False To find ``sqrt`` look for ``Pow`` with an exponent of ``1/2``: >>> (x + 1/sqrt(x)).find(lambda i: i.is_Pow and abs(i.exp) is S.Half) {1/sqrt(x)} See Also ======== sympy.polys.rootoftools.rootof, root, real_root References ========== .. [1] https://en.wikipedia.org/wiki/Square_root .. [2] https://en.wikipedia.org/wiki/Principal_value """ # arg = sympify(arg) is handled by Pow return Pow(arg, S.Half, evaluate=evaluate) def cbrt(arg, evaluate=None): """Returns the principal cube root. Parameters ========== evaluate : bool, optional The parameter determines if the expression should be evaluated. If ``None``, its value is taken from ``global_parameters.evaluate``. Examples ======== >>> from sympy import cbrt, Symbol >>> x = Symbol('x') >>> cbrt(x) x**(1/3) >>> cbrt(x)**3 x Note that cbrt(x**3) does not simplify to x. >>> cbrt(x**3) (x**3)**(1/3) This is because the two are not equal to each other in general. For example, consider `x == -1`: >>> from sympy import Eq >>> Eq(cbrt(x**3), x).subs(x, -1) False This is because cbrt computes the principal cube root, this identity does hold if `x` is positive: >>> y = Symbol('y', positive=True) >>> cbrt(y**3) y See Also ======== sympy.polys.rootoftools.rootof, root, real_root References ========== .. [1] https://en.wikipedia.org/wiki/Cube_root .. [2] https://en.wikipedia.org/wiki/Principal_value """ return Pow(arg, Rational(1, 3), evaluate=evaluate) def root(arg, n, k=0, evaluate=None): r"""Returns the *k*-th *n*-th root of ``arg``. Parameters ========== k : int, optional Should be an integer in $\{0, 1, ..., n-1\}$. Defaults to the principal root if $0$. evaluate : bool, optional The parameter determines if the expression should be evaluated. If ``None``, its value is taken from ``global_parameters.evaluate``. Examples ======== >>> from sympy import root, Rational >>> from sympy.abc import x, n >>> root(x, 2) sqrt(x) >>> root(x, 3) x**(1/3) >>> root(x, n) x**(1/n) >>> root(x, -Rational(2, 3)) x**(-3/2) To get the k-th n-th root, specify k: >>> root(-2, 3, 2) -(-1)**(2/3)*2**(1/3) To get all n n-th roots you can use the rootof function. The following examples show the roots of unity for n equal 2, 3 and 4: >>> from sympy import rootof >>> [rootof(x**2 - 1, i) for i in range(2)] [-1, 1] >>> [rootof(x**3 - 1,i) for i in range(3)] [1, -1/2 - sqrt(3)*I/2, -1/2 + sqrt(3)*I/2] >>> [rootof(x**4 - 1,i) for i in range(4)] [-1, 1, -I, I] SymPy, like other symbolic algebra systems, returns the complex root of negative numbers. This is the principal root and differs from the text-book result that one might be expecting. For example, the cube root of -8 does not come back as -2: >>> root(-8, 3) 2*(-1)**(1/3) The real_root function can be used to either make the principal result real (or simply to return the real root directly): >>> from sympy import real_root >>> real_root(_) -2 >>> real_root(-32, 5) -2 Alternatively, the n//2-th n-th root of a negative number can be computed with root: >>> root(-32, 5, 5//2) -2 See Also ======== sympy.polys.rootoftools.rootof sympy.core.power.integer_nthroot sqrt, real_root References ========== .. [1] https://en.wikipedia.org/wiki/Square_root .. [2] https://en.wikipedia.org/wiki/Real_root .. [3] https://en.wikipedia.org/wiki/Root_of_unity .. [4] https://en.wikipedia.org/wiki/Principal_value .. [5] http://mathworld.wolfram.com/CubeRoot.html """ n = sympify(n) if k: return Mul(Pow(arg, S.One/n, evaluate=evaluate), S.NegativeOne**(2*k/n), evaluate=evaluate) return Pow(arg, 1/n, evaluate=evaluate) def real_root(arg, n=None, evaluate=None): """Return the real *n*'th-root of *arg* if possible. Parameters ========== n : int or None, optional If *n* is ``None``, then all instances of ``(-n)**(1/odd)`` will be changed to ``-n**(1/odd)``. This will only create a real root of a principal root. The presence of other factors may cause the result to not be real. evaluate : bool, optional The parameter determines if the expression should be evaluated. If ``None``, its value is taken from ``global_parameters.evaluate``. Examples ======== >>> from sympy import root, real_root >>> real_root(-8, 3) -2 >>> root(-8, 3) 2*(-1)**(1/3) >>> real_root(_) -2 If one creates a non-principal root and applies real_root, the result will not be real (so use with caution): >>> root(-8, 3, 2) -2*(-1)**(2/3) >>> real_root(_) -2*(-1)**(2/3) See Also ======== sympy.polys.rootoftools.rootof sympy.core.power.integer_nthroot root, sqrt """ from sympy.functions.elementary.complexes import Abs, im, sign from sympy.functions.elementary.piecewise import Piecewise if n is not None: return Piecewise( (root(arg, n, evaluate=evaluate), Or(Eq(n, S.One), Eq(n, S.NegativeOne))), (Mul(sign(arg), root(Abs(arg), n, evaluate=evaluate), evaluate=evaluate), And(Eq(im(arg), S.Zero), Eq(Mod(n, 2), S.One))), (root(arg, n, evaluate=evaluate), True)) rv = sympify(arg) n1pow = Transform(lambda x: -(-x.base)**x.exp, lambda x: x.is_Pow and x.base.is_negative and x.exp.is_Rational and x.exp.p == 1 and x.exp.q % 2) return rv.xreplace(n1pow) ############################################################################### ############################# MINIMUM and MAXIMUM ############################# ############################################################################### class MinMaxBase(Expr, LatticeOp): def __new__(cls, *args, **assumptions): evaluate = assumptions.pop('evaluate', True) args = (sympify(arg) for arg in args) # first standard filter, for cls.zero and cls.identity # also reshape Max(a, Max(b, c)) to Max(a, b, c) if evaluate: try: args = frozenset(cls._new_args_filter(args)) except ShortCircuit: return cls.zero else: args = frozenset(args) if evaluate: # remove redundant args that are easily identified args = cls._collapse_arguments(args, **assumptions) # find local zeros args = cls._find_localzeros(args, **assumptions) if not args: return cls.identity if len(args) == 1: return list(args).pop() # base creation _args = frozenset(args) obj = Expr.__new__(cls, *ordered(_args), **assumptions) obj._argset = _args return obj @classmethod def _collapse_arguments(cls, args, **assumptions): """Remove redundant args. Examples ======== >>> from sympy import Min, Max >>> from sympy.abc import a, b, c, d, e Any arg in parent that appears in any parent-like function in any of the flat args of parent can be removed from that sub-arg: >>> Min(a, Max(b, Min(a, c, d))) Min(a, Max(b, Min(c, d))) If the arg of parent appears in an opposite-than parent function in any of the flat args of parent that function can be replaced with the arg: >>> Min(a, Max(b, Min(c, d, Max(a, e)))) Min(a, Max(b, Min(a, c, d))) """ if not args: return args args = list(ordered(args)) if cls == Min: other = Max else: other = Min # find global comparable max of Max and min of Min if a new # value is being introduced in these args at position 0 of # the ordered args if args[0].is_number: sifted = mins, maxs = [], [] for i in args: for v in walk(i, Min, Max): if v.args[0].is_comparable: sifted[isinstance(v, Max)].append(v) small = Min.identity for i in mins: v = i.args[0] if v.is_number and (v < small) == True: small = v big = Max.identity for i in maxs: v = i.args[0] if v.is_number and (v > big) == True: big = v # at the point when this function is called from __new__, # there may be more than one numeric arg present since # local zeros have not been handled yet, so look through # more than the first arg if cls == Min: for i in range(len(args)): if not args[i].is_number: break if (args[i] < small) == True: small = args[i] elif cls == Max: for i in range(len(args)): if not args[i].is_number: break if (args[i] > big) == True: big = args[i] T = None if cls == Min: if small != Min.identity: other = Max T = small elif big != Max.identity: other = Min T = big if T is not None: # remove numerical redundancy for i in range(len(args)): a = args[i] if isinstance(a, other): a0 = a.args[0] if ((a0 > T) if other == Max else (a0 < T)) == True: args[i] = cls.identity # remove redundant symbolic args def do(ai, a): if not isinstance(ai, (Min, Max)): return ai cond = a in ai.args if not cond: return ai.func(*[do(i, a) for i in ai.args], evaluate=False) if isinstance(ai, cls): return ai.func(*[do(i, a) for i in ai.args if i != a], evaluate=False) return a for i, a in enumerate(args): args[i + 1:] = [do(ai, a) for ai in args[i + 1:]] # factor out common elements as for # Min(Max(x, y), Max(x, z)) -> Max(x, Min(y, z)) # and vice versa when swapping Min/Max -- do this only for the # easy case where all functions contain something in common; # trying to find some optimal subset of args to modify takes # too long def factor_minmax(args): is_other = lambda arg: isinstance(arg, other) other_args, remaining_args = sift(args, is_other, binary=True) if not other_args: return args # Min(Max(x, y, z), Max(x, y, u, v)) -> {x,y}, ({z}, {u,v}) arg_sets = [set(arg.args) for arg in other_args] common = set.intersection(*arg_sets) if not common: return args new_other_args = list(common) arg_sets_diff = [arg_set - common for arg_set in arg_sets] # If any set is empty after removing common then all can be # discarded e.g. Min(Max(a, b, c), Max(a, b)) -> Max(a, b) if all(arg_sets_diff): other_args_diff = [other(*s, evaluate=False) for s in arg_sets_diff] new_other_args.append(cls(*other_args_diff, evaluate=False)) other_args_factored = other(*new_other_args, evaluate=False) return remaining_args + [other_args_factored] if len(args) > 1: args = factor_minmax(args) return args @classmethod def _new_args_filter(cls, arg_sequence): """ Generator filtering args. first standard filter, for cls.zero and cls.identity. Also reshape Max(a, Max(b, c)) to Max(a, b, c), and check arguments for comparability """ for arg in arg_sequence: # pre-filter, checking comparability of arguments if not isinstance(arg, Expr) or arg.is_extended_real is False or ( arg.is_number and not arg.is_comparable): raise ValueError("The argument '%s' is not comparable." % arg) if arg == cls.zero: raise ShortCircuit(arg) elif arg == cls.identity: continue elif arg.func == cls: yield from arg.args else: yield arg @classmethod def _find_localzeros(cls, values, **options): """ Sequentially allocate values to localzeros. When a value is identified as being more extreme than another member it replaces that member; if this is never true, then the value is simply appended to the localzeros. """ localzeros = set() for v in values: is_newzero = True localzeros_ = list(localzeros) for z in localzeros_: if id(v) == id(z): is_newzero = False else: con = cls._is_connected(v, z) if con: is_newzero = False if con is True or con == cls: localzeros.remove(z) localzeros.update([v]) if is_newzero: localzeros.update([v]) return localzeros @classmethod def _is_connected(cls, x, y): """ Check if x and y are connected somehow. """ for i in range(2): if x == y: return True t, f = Max, Min for op in "><": for j in range(2): try: if op == ">": v = x >= y else: v = x <= y except TypeError: return False # non-real arg if not v.is_Relational: return t if v else f t, f = f, t x, y = y, x x, y = y, x # run next pass with reversed order relative to start # simplification can be expensive, so be conservative # in what is attempted x = factor_terms(x - y) y = S.Zero return False def _eval_derivative(self, s): # f(x).diff(s) -> x.diff(s) * f.fdiff(1)(s) i = 0 l = [] for a in self.args: i += 1 da = a.diff(s) if da.is_zero: continue try: df = self.fdiff(i) except ArgumentIndexError: df = Function.fdiff(self, i) l.append(df * da) return Add(*l) def _eval_rewrite_as_Abs(self, *args, **kwargs): from sympy.functions.elementary.complexes import Abs s = (args[0] + self.func(*args[1:]))/2 d = abs(args[0] - self.func(*args[1:]))/2 return (s + d if isinstance(self, Max) else s - d).rewrite(Abs) def evalf(self, n=15, **options): return self.func(*[a.evalf(n, **options) for a in self.args]) def n(self, *args, **kwargs): return self.evalf(*args, **kwargs) _eval_is_algebraic = lambda s: _torf(i.is_algebraic for i in s.args) _eval_is_antihermitian = lambda s: _torf(i.is_antihermitian for i in s.args) _eval_is_commutative = lambda s: _torf(i.is_commutative for i in s.args) _eval_is_complex = lambda s: _torf(i.is_complex for i in s.args) _eval_is_composite = lambda s: _torf(i.is_composite for i in s.args) _eval_is_even = lambda s: _torf(i.is_even for i in s.args) _eval_is_finite = lambda s: _torf(i.is_finite for i in s.args) _eval_is_hermitian = lambda s: _torf(i.is_hermitian for i in s.args) _eval_is_imaginary = lambda s: _torf(i.is_imaginary for i in s.args) _eval_is_infinite = lambda s: _torf(i.is_infinite for i in s.args) _eval_is_integer = lambda s: _torf(i.is_integer for i in s.args) _eval_is_irrational = lambda s: _torf(i.is_irrational for i in s.args) _eval_is_negative = lambda s: _torf(i.is_negative for i in s.args) _eval_is_noninteger = lambda s: _torf(i.is_noninteger for i in s.args) _eval_is_nonnegative = lambda s: _torf(i.is_nonnegative for i in s.args) _eval_is_nonpositive = lambda s: _torf(i.is_nonpositive for i in s.args) _eval_is_nonzero = lambda s: _torf(i.is_nonzero for i in s.args) _eval_is_odd = lambda s: _torf(i.is_odd for i in s.args) _eval_is_polar = lambda s: _torf(i.is_polar for i in s.args) _eval_is_positive = lambda s: _torf(i.is_positive for i in s.args) _eval_is_prime = lambda s: _torf(i.is_prime for i in s.args) _eval_is_rational = lambda s: _torf(i.is_rational for i in s.args) _eval_is_real = lambda s: _torf(i.is_real for i in s.args) _eval_is_extended_real = lambda s: _torf(i.is_extended_real for i in s.args) _eval_is_transcendental = lambda s: _torf(i.is_transcendental for i in s.args) _eval_is_zero = lambda s: _torf(i.is_zero for i in s.args) class Max(MinMaxBase, Application): """ Return, if possible, the maximum value of the list. When number of arguments is equal one, then return this argument. When number of arguments is equal two, then return, if possible, the value from (a, b) that is >= the other. In common case, when the length of list greater than 2, the task is more complicated. Return only the arguments, which are greater than others, if it is possible to determine directional relation. If is not possible to determine such a relation, return a partially evaluated result. Assumptions are used to make the decision too. Also, only comparable arguments are permitted. It is named ``Max`` and not ``max`` to avoid conflicts with the built-in function ``max``. Examples ======== >>> from sympy import Max, Symbol, oo >>> from sympy.abc import x, y, z >>> p = Symbol('p', positive=True) >>> n = Symbol('n', negative=True) >>> Max(x, -2) Max(-2, x) >>> Max(x, -2).subs(x, 3) 3 >>> Max(p, -2) p >>> Max(x, y) Max(x, y) >>> Max(x, y) == Max(y, x) True >>> Max(x, Max(y, z)) Max(x, y, z) >>> Max(n, 8, p, 7, -oo) Max(8, p) >>> Max (1, x, oo) oo * Algorithm The task can be considered as searching of supremums in the directed complete partial orders [1]_. The source values are sequentially allocated by the isolated subsets in which supremums are searched and result as Max arguments. If the resulted supremum is single, then it is returned. The isolated subsets are the sets of values which are only the comparable with each other in the current set. E.g. natural numbers are comparable with each other, but not comparable with the `x` symbol. Another example: the symbol `x` with negative assumption is comparable with a natural number. Also there are "least" elements, which are comparable with all others, and have a zero property (maximum or minimum for all elements). E.g. `oo`. In case of it the allocation operation is terminated and only this value is returned. Assumption: - if A > B > C then A > C - if A == B then B can be removed References ========== .. [1] https://en.wikipedia.org/wiki/Directed_complete_partial_order .. [2] https://en.wikipedia.org/wiki/Lattice_%28order%29 See Also ======== Min : find minimum values """ zero = S.Infinity identity = S.NegativeInfinity def fdiff( self, argindex ): from sympy.functions.special.delta_functions import Heaviside n = len(self.args) if 0 < argindex and argindex <= n: argindex -= 1 if n == 2: return Heaviside(self.args[argindex] - self.args[1 - argindex]) newargs = tuple([self.args[i] for i in range(n) if i != argindex]) return Heaviside(self.args[argindex] - Max(*newargs)) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_Heaviside(self, *args, **kwargs): from sympy.functions.special.delta_functions import Heaviside return Add(*[j*Mul(*[Heaviside(j - i) for i in args if i!=j]) \ for j in args]) def _eval_rewrite_as_Piecewise(self, *args, **kwargs): return _minmax_as_Piecewise('>=', *args) def _eval_is_positive(self): return fuzzy_or(a.is_positive for a in self.args) def _eval_is_nonnegative(self): return fuzzy_or(a.is_nonnegative for a in self.args) def _eval_is_negative(self): return fuzzy_and(a.is_negative for a in self.args) class Min(MinMaxBase, Application): """ Return, if possible, the minimum value of the list. It is named ``Min`` and not ``min`` to avoid conflicts with the built-in function ``min``. Examples ======== >>> from sympy import Min, Symbol, oo >>> from sympy.abc import x, y >>> p = Symbol('p', positive=True) >>> n = Symbol('n', negative=True) >>> Min(x, -2) Min(-2, x) >>> Min(x, -2).subs(x, 3) -2 >>> Min(p, -3) -3 >>> Min(x, y) Min(x, y) >>> Min(n, 8, p, -7, p, oo) Min(-7, n) See Also ======== Max : find maximum values """ zero = S.NegativeInfinity identity = S.Infinity def fdiff( self, argindex ): from sympy.functions.special.delta_functions import Heaviside n = len(self.args) if 0 < argindex and argindex <= n: argindex -= 1 if n == 2: return Heaviside( self.args[1-argindex] - self.args[argindex] ) newargs = tuple([ self.args[i] for i in range(n) if i != argindex]) return Heaviside( Min(*newargs) - self.args[argindex] ) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_Heaviside(self, *args, **kwargs): from sympy.functions.special.delta_functions import Heaviside return Add(*[j*Mul(*[Heaviside(i-j) for i in args if i!=j]) \ for j in args]) def _eval_rewrite_as_Piecewise(self, *args, **kwargs): return _minmax_as_Piecewise('<=', *args) def _eval_is_positive(self): return fuzzy_and(a.is_positive for a in self.args) def _eval_is_nonnegative(self): return fuzzy_and(a.is_nonnegative for a in self.args) def _eval_is_negative(self): return fuzzy_or(a.is_negative for a in self.args) class Rem(Function): """Returns the remainder when ``p`` is divided by ``q`` where ``p`` is finite and ``q`` is not equal to zero. The result, ``p - int(p/q)*q``, has the same sign as the divisor. Parameters ========== p : Expr Dividend. q : Expr Divisor. Notes ===== ``Rem`` corresponds to the ``%`` operator in C. Examples ======== >>> from sympy.abc import x, y >>> from sympy import Rem >>> Rem(x**3, y) Rem(x**3, y) >>> Rem(x**3, y).subs({x: -5, y: 3}) -2 See Also ======== Mod """ kind = NumberKind @classmethod def eval(cls, p, q): def doit(p, q): """ the function remainder if both p,q are numbers and q is not zero """ if q.is_zero: raise ZeroDivisionError("Division by zero") if p is S.NaN or q is S.NaN or p.is_finite is False or q.is_finite is False: return S.NaN if p is S.Zero or p in (q, -q) or (p.is_integer and q == 1): return S.Zero if q.is_Number: if p.is_Number: return p - Integer(p/q)*q rv = doit(p, q) if rv is not None: return rv
35e7aea270621765fcff4d7b1f5106beccbd2ecc0259100cf957bf762954b24f
from sympy.core import S, Function, diff, Tuple, Dummy from sympy.core.basic import Basic, as_Basic from sympy.core.numbers import Rational, NumberSymbol from sympy.core.parameters import global_parameters from sympy.core.relational import (Lt, Gt, Eq, Ne, Relational, _canonical, _canonical_coeff) from sympy.core.sorting import ordered from sympy.functions.elementary.miscellaneous import Max, Min from sympy.logic.boolalg import (And, Boolean, distribute_and_over_or, Not, true, false, Or, ITE, simplify_logic, to_cnf, distribute_or_over_and) from sympy.polys.polyutils import illegal from sympy.utilities.iterables import uniq, sift, common_prefix from sympy.utilities.misc import filldedent, func_name from itertools import product Undefined = S.NaN # Piecewise() class ExprCondPair(Tuple): """Represents an expression, condition pair.""" def __new__(cls, expr, cond): expr = as_Basic(expr) if cond == True: return Tuple.__new__(cls, expr, true) elif cond == False: return Tuple.__new__(cls, expr, false) elif isinstance(cond, Basic) and cond.has(Piecewise): cond = piecewise_fold(cond) if isinstance(cond, Piecewise): cond = cond.rewrite(ITE) if not isinstance(cond, Boolean): raise TypeError(filldedent(''' Second argument must be a Boolean, not `%s`''' % func_name(cond))) return Tuple.__new__(cls, expr, cond) @property def expr(self): """ Returns the expression of this pair. """ return self.args[0] @property def cond(self): """ Returns the condition of this pair. """ return self.args[1] @property def is_commutative(self): return self.expr.is_commutative def __iter__(self): yield self.expr yield self.cond def _eval_simplify(self, **kwargs): return self.func(*[a.simplify(**kwargs) for a in self.args]) class Piecewise(Function): """ Represents a piecewise function. Usage: Piecewise( (expr,cond), (expr,cond), ... ) - Each argument is a 2-tuple defining an expression and condition - The conds are evaluated in turn returning the first that is True. If any of the evaluated conds are not explicitly False, e.g. ``x < 1``, the function is returned in symbolic form. - If the function is evaluated at a place where all conditions are False, nan will be returned. - Pairs where the cond is explicitly False, will be removed and no pair appearing after a True condition will ever be retained. If a single pair with a True condition remains, it will be returned, even when evaluation is False. Examples ======== >>> from sympy import Piecewise, log, piecewise_fold >>> from sympy.abc import x, y >>> f = x**2 >>> g = log(x) >>> p = Piecewise((0, x < -1), (f, x <= 1), (g, True)) >>> p.subs(x,1) 1 >>> p.subs(x,5) log(5) Booleans can contain Piecewise elements: >>> cond = (x < y).subs(x, Piecewise((2, x < 0), (3, True))); cond Piecewise((2, x < 0), (3, True)) < y The folded version of this results in a Piecewise whose expressions are Booleans: >>> folded_cond = piecewise_fold(cond); folded_cond Piecewise((2 < y, x < 0), (3 < y, True)) When a Boolean containing Piecewise (like cond) or a Piecewise with Boolean expressions (like folded_cond) is used as a condition, it is converted to an equivalent ITE object: >>> Piecewise((1, folded_cond)) Piecewise((1, ITE(x < 0, y > 2, y > 3))) When a condition is an ITE, it will be converted to a simplified Boolean expression: >>> piecewise_fold(_) Piecewise((1, ((x >= 0) | (y > 2)) & ((y > 3) | (x < 0)))) See Also ======== piecewise_fold, ITE """ nargs = None is_Piecewise = True def __new__(cls, *args, **options): if len(args) == 0: raise TypeError("At least one (expr, cond) pair expected.") # (Try to) sympify args first newargs = [] for ec in args: # ec could be a ExprCondPair or a tuple pair = ExprCondPair(*getattr(ec, 'args', ec)) cond = pair.cond if cond is false: continue newargs.append(pair) if cond is true: break eval = options.pop('evaluate', global_parameters.evaluate) if eval: r = cls.eval(*newargs) if r is not None: return r elif len(newargs) == 1 and newargs[0].cond == True: return newargs[0].expr return Basic.__new__(cls, *newargs, **options) @classmethod def eval(cls, *_args): """Either return a modified version of the args or, if no modifications were made, return None. Modifications that are made here: 1) relationals are made canonical 2) any False conditions are dropped 3) any repeat of a previous condition is ignored 3) any args past one with a true condition are dropped If there are no args left, nan will be returned. If there is a single arg with a True condition, its corresponding expression will be returned. EXAMPLES ======== >>> from sympy import Piecewise >>> from sympy.abc import x >>> cond = -x < -1 >>> args = [(1, cond), (4, cond), (3, False), (2, True), (5, x < 1)] >>> Piecewise(*args, evaluate=False) Piecewise((1, -x < -1), (4, -x < -1), (2, True)) >>> Piecewise(*args) Piecewise((1, x > 1), (2, True)) """ if not _args: return Undefined if len(_args) == 1 and _args[0][-1] == True: return _args[0][0] newargs = [] # the unevaluated conditions current_cond = set() # the conditions up to a given e, c pair for expr, cond in _args: cond = cond.replace( lambda _: _.is_Relational, _canonical_coeff) # Check here if expr is a Piecewise and collapse if one of # the conds in expr matches cond. This allows the collapsing # of Piecewise((Piecewise((x,x<0)),x<0)) to Piecewise((x,x<0)). # This is important when using piecewise_fold to simplify # multiple Piecewise instances having the same conds. # Eventually, this code should be able to collapse Piecewise's # having different intervals, but this will probably require # using the new assumptions. if isinstance(expr, Piecewise): unmatching = [] for i, (e, c) in enumerate(expr.args): if c in current_cond: # this would already have triggered continue if c == cond: if c != True: # nothing past this condition will ever # trigger and only those args before this # that didn't match a previous condition # could possibly trigger if unmatching: expr = Piecewise(*( unmatching + [(e, c)])) else: expr = e break else: unmatching.append((e, c)) # check for condition repeats got = False # -- if an And contains a condition that was # already encountered, then the And will be # False: if the previous condition was False # then the And will be False and if the previous # condition is True then then we wouldn't get to # this point. In either case, we can skip this condition. for i in ([cond] + (list(cond.args) if isinstance(cond, And) else [])): if i in current_cond: got = True break if got: continue # -- if not(c) is already in current_cond then c is # a redundant condition in an And. This does not # apply to Or, however: (e1, c), (e2, Or(~c, d)) # is not (e1, c), (e2, d) because if c and d are # both False this would give no results when the # true answer should be (e2, True) if isinstance(cond, And): nonredundant = [] for c in cond.args: if isinstance(c, Relational): if c.negated.canonical in current_cond: continue # if a strict inequality appears after # a non-strict one, then the condition is # redundant if isinstance(c, (Lt, Gt)) and ( c.weak in current_cond): cond = False break nonredundant.append(c) else: cond = cond.func(*nonredundant) elif isinstance(cond, Relational): if cond.negated.canonical in current_cond: cond = S.true current_cond.add(cond) # collect successive e,c pairs when exprs or cond match if newargs: if newargs[-1].expr == expr: orcond = Or(cond, newargs[-1].cond) if isinstance(orcond, (And, Or)): orcond = distribute_and_over_or(orcond) newargs[-1] = ExprCondPair(expr, orcond) continue elif newargs[-1].cond == cond: newargs[-1] = ExprCondPair(expr, cond) continue newargs.append(ExprCondPair(expr, cond)) # some conditions may have been redundant missing = len(newargs) != len(_args) # some conditions may have changed same = all(a == b for a, b in zip(newargs, _args)) # if either change happened we return the expr with the # updated args if not newargs: raise ValueError(filldedent(''' There are no conditions (or none that are not trivially false) to define an expression.''')) if missing or not same: return cls(*newargs) def doit(self, **hints): """ Evaluate this piecewise function. """ newargs = [] for e, c in self.args: if hints.get('deep', True): if isinstance(e, Basic): newe = e.doit(**hints) if newe != self: e = newe if isinstance(c, Basic): c = c.doit(**hints) newargs.append((e, c)) return self.func(*newargs) def _eval_simplify(self, **kwargs): return piecewise_simplify(self, **kwargs) def _eval_as_leading_term(self, x, logx=None, cdir=0): for e, c in self.args: if c == True or c.subs(x, 0) == True: return e.as_leading_term(x) def _eval_adjoint(self): return self.func(*[(e.adjoint(), c) for e, c in self.args]) def _eval_conjugate(self): return self.func(*[(e.conjugate(), c) for e, c in self.args]) def _eval_derivative(self, x): return self.func(*[(diff(e, x), c) for e, c in self.args]) def _eval_evalf(self, prec): return self.func(*[(e._evalf(prec), c) for e, c in self.args]) def piecewise_integrate(self, x, **kwargs): """Return the Piecewise with each expression being replaced with its antiderivative. To obtain a continuous antiderivative, use the `integrate` function or method. Examples ======== >>> from sympy import Piecewise >>> from sympy.abc import x >>> p = Piecewise((0, x < 0), (1, x < 1), (2, True)) >>> p.piecewise_integrate(x) Piecewise((0, x < 0), (x, x < 1), (2*x, True)) Note that this does not give a continuous function, e.g. at x = 1 the 3rd condition applies and the antiderivative there is 2*x so the value of the antiderivative is 2: >>> anti = _ >>> anti.subs(x, 1) 2 The continuous derivative accounts for the integral *up to* the point of interest, however: >>> p.integrate(x) Piecewise((0, x < 0), (x, x < 1), (2*x - 1, True)) >>> _.subs(x, 1) 1 See Also ======== Piecewise._eval_integral """ from sympy.integrals import integrate return self.func(*[(integrate(e, x, **kwargs), c) for e, c in self.args]) def _handle_irel(self, x, handler): """Return either None (if the conditions of self depend only on x) else a Piecewise expression whose expressions (handled by the handler that was passed) are paired with the governing x-independent relationals, e.g. Piecewise((A, a(x) & b(y)), (B, c(x) | c(y)) -> Piecewise( (handler(Piecewise((A, a(x) & True), (B, c(x) | True)), b(y) & c(y)), (handler(Piecewise((A, a(x) & True), (B, c(x) | False)), b(y)), (handler(Piecewise((A, a(x) & False), (B, c(x) | True)), c(y)), (handler(Piecewise((A, a(x) & False), (B, c(x) | False)), True)) """ # identify governing relationals rel = self.atoms(Relational) irel = list(ordered([r for r in rel if x not in r.free_symbols and r not in (S.true, S.false)])) if irel: args = {} exprinorder = [] for truth in product((1, 0), repeat=len(irel)): reps = dict(zip(irel, truth)) # only store the true conditions since the false are implied # when they appear lower in the Piecewise args if 1 not in truth: cond = None # flag this one so it doesn't get combined else: andargs = Tuple(*[i for i in reps if reps[i]]) free = list(andargs.free_symbols) if len(free) == 1: from sympy.solvers.inequalities import ( reduce_inequalities, _solve_inequality) try: t = reduce_inequalities(andargs, free[0]) # ValueError when there are potentially # nonvanishing imaginary parts except (ValueError, NotImplementedError): # at least isolate free symbol on left t = And(*[_solve_inequality( a, free[0], linear=True) for a in andargs]) else: t = And(*andargs) if t is S.false: continue # an impossible combination cond = t expr = handler(self.xreplace(reps)) if isinstance(expr, self.func) and len(expr.args) == 1: expr, econd = expr.args[0] cond = And(econd, True if cond is None else cond) # the ec pairs are being collected since all possibilities # are being enumerated, but don't put the last one in since # its expr might match a previous expression and it # must appear last in the args if cond is not None: args.setdefault(expr, []).append(cond) # but since we only store the true conditions we must maintain # the order so that the expression with the most true values # comes first exprinorder.append(expr) # convert collected conditions as args of Or for k in args: args[k] = Or(*args[k]) # take them in the order obtained args = [(e, args[e]) for e in uniq(exprinorder)] # add in the last arg args.append((expr, True)) return Piecewise(*args) def _eval_integral(self, x, _first=True, **kwargs): """Return the indefinite integral of the Piecewise such that subsequent substitution of x with a value will give the value of the integral (not including the constant of integration) up to that point. To only integrate the individual parts of Piecewise, use the `piecewise_integrate` method. Examples ======== >>> from sympy import Piecewise >>> from sympy.abc import x >>> p = Piecewise((0, x < 0), (1, x < 1), (2, True)) >>> p.integrate(x) Piecewise((0, x < 0), (x, x < 1), (2*x - 1, True)) >>> p.piecewise_integrate(x) Piecewise((0, x < 0), (x, x < 1), (2*x, True)) See Also ======== Piecewise.piecewise_integrate """ from sympy.integrals.integrals import integrate if _first: def handler(ipw): if isinstance(ipw, self.func): return ipw._eval_integral(x, _first=False, **kwargs) else: return ipw.integrate(x, **kwargs) irv = self._handle_irel(x, handler) if irv is not None: return irv # handle a Piecewise from -oo to oo with and no x-independent relationals # ----------------------------------------------------------------------- ok, abei = self._intervals(x) if not ok: from sympy.integrals.integrals import Integral return Integral(self, x) # unevaluated pieces = [(a, b) for a, b, _, _ in abei] oo = S.Infinity done = [(-oo, oo, -1)] for k, p in enumerate(pieces): if p == (-oo, oo): # all undone intervals will get this key for j, (a, b, i) in enumerate(done): if i == -1: done[j] = a, b, k break # nothing else to consider N = len(done) - 1 for j, (a, b, i) in enumerate(reversed(done)): if i == -1: j = N - j done[j: j + 1] = _clip(p, (a, b), k) done = [(a, b, i) for a, b, i in done if a != b] # append an arg if there is a hole so a reference to # argument -1 will give Undefined if any(i == -1 for (a, b, i) in done): abei.append((-oo, oo, Undefined, -1)) # return the sum of the intervals args = [] sum = None for a, b, i in done: anti = integrate(abei[i][-2], x, **kwargs) if sum is None: sum = anti else: sum = sum.subs(x, a) e = anti._eval_interval(x, a, x) if sum.has(*illegal) or e.has(*illegal): sum = anti else: sum += e # see if we know whether b is contained in original # condition if b is S.Infinity: cond = True elif self.args[abei[i][-1]].cond.subs(x, b) == False: cond = (x < b) else: cond = (x <= b) args.append((sum, cond)) return Piecewise(*args) def _eval_interval(self, sym, a, b, _first=True): """Evaluates the function along the sym in a given interval [a, b]""" # FIXME: Currently complex intervals are not supported. A possible # replacement algorithm, discussed in issue 5227, can be found in the # following papers; # http://portal.acm.org/citation.cfm?id=281649 # http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.70.4127&rep=rep1&type=pdf if a is None or b is None: # In this case, it is just simple substitution return super()._eval_interval(sym, a, b) else: x, lo, hi = map(as_Basic, (sym, a, b)) if _first: # get only x-dependent relationals def handler(ipw): if isinstance(ipw, self.func): return ipw._eval_interval(x, lo, hi, _first=None) else: return ipw._eval_interval(x, lo, hi) irv = self._handle_irel(x, handler) if irv is not None: return irv if (lo < hi) is S.false or ( lo is S.Infinity or hi is S.NegativeInfinity): rv = self._eval_interval(x, hi, lo, _first=False) if isinstance(rv, Piecewise): rv = Piecewise(*[(-e, c) for e, c in rv.args]) else: rv = -rv return rv if (lo < hi) is S.true or ( hi is S.Infinity or lo is S.NegativeInfinity): pass else: _a = Dummy('lo') _b = Dummy('hi') a = lo if lo.is_comparable else _a b = hi if hi.is_comparable else _b pos = self._eval_interval(x, a, b, _first=False) if a == _a and b == _b: # it's purely symbolic so just swap lo and hi and # change the sign to get the value for when lo > hi neg, pos = (-pos.xreplace({_a: hi, _b: lo}), pos.xreplace({_a: lo, _b: hi})) else: # at least one of the bounds was comparable, so allow # _eval_interval to use that information when computing # the interval with lo and hi reversed neg, pos = (-self._eval_interval(x, hi, lo, _first=False), pos.xreplace({_a: lo, _b: hi})) # allow simplification based on ordering of lo and hi p = Dummy('', positive=True) if lo.is_Symbol: pos = pos.xreplace({lo: hi - p}).xreplace({p: hi - lo}) neg = neg.xreplace({lo: hi + p}).xreplace({p: lo - hi}) elif hi.is_Symbol: pos = pos.xreplace({hi: lo + p}).xreplace({p: hi - lo}) neg = neg.xreplace({hi: lo - p}).xreplace({p: lo - hi}) # evaluate limits that may have unevaluate Min/Max touch = lambda _: _.replace( lambda x: isinstance(x, (Min, Max)), lambda x: x.func(*x.args)) neg = touch(neg) pos = touch(pos) # assemble return expression; make the first condition be Lt # b/c then the first expression will look the same whether # the lo or hi limit is symbolic if a == _a: # the lower limit was symbolic rv = Piecewise( (pos, lo < hi), (neg, True)) else: rv = Piecewise( (neg, hi < lo), (pos, True)) if rv == Undefined: raise ValueError("Can't integrate across undefined region.") if any(isinstance(i, Piecewise) for i in (pos, neg)): rv = piecewise_fold(rv) return rv # handle a Piecewise with lo <= hi and no x-independent relationals # ----------------------------------------------------------------- ok, abei = self._intervals(x) if not ok: from sympy.integrals.integrals import Integral # not being able to do the interval of f(x) can # be stated as not being able to do the integral # of f'(x) over the same range return Integral(self.diff(x), (x, lo, hi)) # unevaluated pieces = [(a, b) for a, b, _, _ in abei] done = [(lo, hi, -1)] oo = S.Infinity for k, p in enumerate(pieces): if p[:2] == (-oo, oo): # all undone intervals will get this key for j, (a, b, i) in enumerate(done): if i == -1: done[j] = a, b, k break # nothing else to consider N = len(done) - 1 for j, (a, b, i) in enumerate(reversed(done)): if i == -1: j = N - j done[j: j + 1] = _clip(p, (a, b), k) done = [(a, b, i) for a, b, i in done if a != b] # return the sum of the intervals sum = S.Zero upto = None for a, b, i in done: if i == -1: if upto is None: return Undefined # TODO simplify hi <= upto return Piecewise((sum, hi <= upto), (Undefined, True)) sum += abei[i][-2]._eval_interval(x, a, b) upto = b return sum def _intervals(self, sym, err_on_Eq=False): """Return a bool and a message (when bool is False), else a list of unique tuples, (a, b, e, i), where a and b are the lower and upper bounds in which the expression e of argument i in self is defined and a < b (when involving numbers) or a <= b when involving symbols. If there are any relationals not involving sym, or any relational cannot be solved for sym, the bool will be False a message be given as the second return value. The calling routine should have removed such relationals before calling this routine. The evaluated conditions will be returned as ranges. Discontinuous ranges will be returned separately with identical expressions. The first condition that evaluates to True will be returned as the last tuple with a, b = -oo, oo. """ from sympy.solvers.inequalities import _solve_inequality assert isinstance(self, Piecewise) def nonsymfail(cond): return False, filldedent(''' A condition not involving %s appeared: %s''' % (sym, cond)) def _solve_relational(r): if sym not in r.free_symbols: return nonsymfail(r) try: rv = _solve_inequality(r, sym) except NotImplementedError: return False, 'Unable to solve relational %s for %s.' % (r, sym) if isinstance(rv, Relational): free = rv.args[1].free_symbols if rv.args[0] != sym or sym in free: return False, 'Unable to solve relational %s for %s.' % (r, sym) if rv.rel_op == '==': # this equality has been affirmed to have the form # Eq(sym, rhs) where rhs is sym-free; it represents # a zero-width interval which will be ignored # whether it is an isolated condition or contained # within an And or an Or rv = S.false elif rv.rel_op == '!=': try: rv = Or(sym < rv.rhs, sym > rv.rhs) except TypeError: # e.g. x != I ==> all real x satisfy rv = S.true elif rv == (S.NegativeInfinity < sym) & (sym < S.Infinity): rv = S.true return True, rv args = list(self.args) # make self canonical wrt Relationals keys = self.atoms(Relational) reps = {} for r in keys: ok, s = _solve_relational(r) if ok != True: return False, ok reps[r] = s # process args individually so if any evaluate, their position # in the original Piecewise will be known args = [i.xreplace(reps) for i in self.args] # precondition args expr_cond = [] default = idefault = None for i, (expr, cond) in enumerate(args): if cond is S.false: continue if cond is S.true: default = expr idefault = i break if isinstance(cond, Eq): # unanticipated condition, but it is here in case a # replacement caused an Eq to appear if err_on_Eq: return False, 'encountered Eq condition: %s' % cond continue # zero width interval cond = to_cnf(cond) if isinstance(cond, And): cond = distribute_or_over_and(cond) if isinstance(cond, Or): expr_cond.extend( [(i, expr, o) for o in cond.args if not isinstance(o, Eq)]) elif cond is not S.false: expr_cond.append((i, expr, cond)) elif cond is S.true: default = expr idefault = i break # determine intervals represented by conditions int_expr = [] for iarg, expr, cond in expr_cond: if isinstance(cond, And): lower = S.NegativeInfinity upper = S.Infinity exclude = [] for cond2 in cond.args: if not isinstance(cond2, Relational): return False, 'expecting only Relationals' if isinstance(cond2, Eq): lower = upper # ignore if err_on_Eq: return False, 'encountered secondary Eq condition' break elif isinstance(cond2, Ne): l, r = cond2.args if l == sym: exclude.append(r) elif r == sym: exclude.append(l) else: return nonsymfail(cond2) continue elif cond2.lts == sym: upper = Min(cond2.gts, upper) elif cond2.gts == sym: lower = Max(cond2.lts, lower) else: return nonsymfail(cond2) # should never get here if exclude: exclude = list(ordered(exclude)) newcond = [] for i, e in enumerate(exclude): if e < lower == True or e > upper == True: continue if not newcond: newcond.append((None, lower)) # add a primer newcond.append((newcond[-1][1], e)) newcond.append((newcond[-1][1], upper)) newcond.pop(0) # remove the primer expr_cond.extend([(iarg, expr, And(i[0] < sym, sym < i[1])) for i in newcond]) continue elif isinstance(cond, Relational) and cond.rel_op != '!=': lower, upper = cond.lts, cond.gts # part 1: initialize with givens if cond.lts == sym: # part 1a: expand the side ... lower = S.NegativeInfinity # e.g. x <= 0 ---> -oo <= 0 elif cond.gts == sym: # part 1a: ... that can be expanded upper = S.Infinity # e.g. x >= 0 ---> oo >= 0 else: return nonsymfail(cond) else: return False, 'unrecognized condition: %s' % cond lower, upper = lower, Max(lower, upper) if err_on_Eq and lower == upper: return False, 'encountered Eq condition' if (lower >= upper) is not S.true: int_expr.append((lower, upper, expr, iarg)) if default is not None: int_expr.append( (S.NegativeInfinity, S.Infinity, default, idefault)) return True, list(uniq(int_expr)) def _eval_nseries(self, x, n, logx, cdir=0): args = [(ec.expr._eval_nseries(x, n, logx), ec.cond) for ec in self.args] return self.func(*args) def _eval_power(self, s): return self.func(*[(e**s, c) for e, c in self.args]) def _eval_subs(self, old, new): # this is strictly not necessary, but we can keep track # of whether True or False conditions arise and be # somewhat more efficient by avoiding other substitutions # and avoiding invalid conditions that appear after a # True condition args = list(self.args) args_exist = False for i, (e, c) in enumerate(args): c = c._subs(old, new) if c != False: args_exist = True e = e._subs(old, new) args[i] = (e, c) if c == True: break if not args_exist: args = ((Undefined, True),) return self.func(*args) def _eval_transpose(self): return self.func(*[(e.transpose(), c) for e, c in self.args]) def _eval_template_is_attr(self, is_attr): b = None for expr, _ in self.args: a = getattr(expr, is_attr) if a is None: return if b is None: b = a elif b is not a: return return b _eval_is_finite = lambda self: self._eval_template_is_attr( 'is_finite') _eval_is_complex = lambda self: self._eval_template_is_attr('is_complex') _eval_is_even = lambda self: self._eval_template_is_attr('is_even') _eval_is_imaginary = lambda self: self._eval_template_is_attr( 'is_imaginary') _eval_is_integer = lambda self: self._eval_template_is_attr('is_integer') _eval_is_irrational = lambda self: self._eval_template_is_attr( 'is_irrational') _eval_is_negative = lambda self: self._eval_template_is_attr('is_negative') _eval_is_nonnegative = lambda self: self._eval_template_is_attr( 'is_nonnegative') _eval_is_nonpositive = lambda self: self._eval_template_is_attr( 'is_nonpositive') _eval_is_nonzero = lambda self: self._eval_template_is_attr( 'is_nonzero') _eval_is_odd = lambda self: self._eval_template_is_attr('is_odd') _eval_is_polar = lambda self: self._eval_template_is_attr('is_polar') _eval_is_positive = lambda self: self._eval_template_is_attr('is_positive') _eval_is_extended_real = lambda self: self._eval_template_is_attr( 'is_extended_real') _eval_is_extended_positive = lambda self: self._eval_template_is_attr( 'is_extended_positive') _eval_is_extended_negative = lambda self: self._eval_template_is_attr( 'is_extended_negative') _eval_is_extended_nonzero = lambda self: self._eval_template_is_attr( 'is_extended_nonzero') _eval_is_extended_nonpositive = lambda self: self._eval_template_is_attr( 'is_extended_nonpositive') _eval_is_extended_nonnegative = lambda self: self._eval_template_is_attr( 'is_extended_nonnegative') _eval_is_real = lambda self: self._eval_template_is_attr('is_real') _eval_is_zero = lambda self: self._eval_template_is_attr( 'is_zero') @classmethod def __eval_cond(cls, cond): """Return the truth value of the condition.""" if cond == True: return True if isinstance(cond, Eq): try: diff = cond.lhs - cond.rhs if diff.is_commutative: return diff.is_zero except TypeError: pass def as_expr_set_pairs(self, domain=None): """Return tuples for each argument of self that give the expression and the interval in which it is valid which is contained within the given domain. If a condition cannot be converted to a set, an error will be raised. The variable of the conditions is assumed to be real; sets of real values are returned. Examples ======== >>> from sympy import Piecewise, Interval >>> from sympy.abc import x >>> p = Piecewise( ... (1, x < 2), ... (2,(x > 0) & (x < 4)), ... (3, True)) >>> p.as_expr_set_pairs() [(1, Interval.open(-oo, 2)), (2, Interval.Ropen(2, 4)), (3, Interval(4, oo))] >>> p.as_expr_set_pairs(Interval(0, 3)) [(1, Interval.Ropen(0, 2)), (2, Interval(2, 3))] """ if domain is None: domain = S.Reals exp_sets = [] U = domain complex = not domain.is_subset(S.Reals) cond_free = set() for expr, cond in self.args: cond_free |= cond.free_symbols if len(cond_free) > 1: raise NotImplementedError(filldedent(''' multivariate conditions are not handled.''')) if complex: for i in cond.atoms(Relational): if not isinstance(i, (Eq, Ne)): raise ValueError(filldedent(''' Inequalities in the complex domain are not supported. Try the real domain by setting domain=S.Reals''')) cond_int = U.intersect(cond.as_set()) U = U - cond_int if cond_int != S.EmptySet: exp_sets.append((expr, cond_int)) return exp_sets def _eval_rewrite_as_ITE(self, *args, **kwargs): byfree = {} args = list(args) default = any(c == True for b, c in args) for i, (b, c) in enumerate(args): if not isinstance(b, Boolean) and b != True: raise TypeError(filldedent(''' Expecting Boolean or bool but got `%s` ''' % func_name(b))) if c == True: break # loop over independent conditions for this b for c in c.args if isinstance(c, Or) else [c]: free = c.free_symbols x = free.pop() try: byfree[x] = byfree.setdefault( x, S.EmptySet).union(c.as_set()) except NotImplementedError: if not default: raise NotImplementedError(filldedent(''' A method to determine whether a multivariate conditional is consistent with a complete coverage of all variables has not been implemented so the rewrite is being stopped after encountering `%s`. This error would not occur if a default expression like `(foo, True)` were given. ''' % c)) if byfree[x] in (S.UniversalSet, S.Reals): # collapse the ith condition to True and break args[i] = list(args[i]) c = args[i][1] = True break if c == True: break if c != True: raise ValueError(filldedent(''' Conditions must cover all reals or a final default condition `(foo, True)` must be given. ''')) last, _ = args[i] # ignore all past ith arg for a, c in reversed(args[:i]): last = ITE(c, a, last) return _canonical(last) def _eval_rewrite_as_KroneckerDelta(self, *args): from sympy.functions.special.tensor_functions import KroneckerDelta rules = { And: [False, False], Or: [True, True], Not: [True, False], Eq: [None, None], Ne: [None, None] } class UnrecognizedCondition(Exception): pass def rewrite(cond): if isinstance(cond, Eq): return KroneckerDelta(*cond.args) if isinstance(cond, Ne): return 1 - KroneckerDelta(*cond.args) cls, args = type(cond), cond.args if cls not in rules: raise UnrecognizedCondition(cls) b1, b2 = rules[cls] k = 1 for c in args: if b1: k *= 1 - rewrite(c) else: k *= rewrite(c) if b2: return 1 - k return k conditions = [] true_value = None for value, cond in args: if type(cond) in rules: conditions.append((value, cond)) elif cond is S.true: if true_value is None: true_value = value else: return if true_value is not None: result = true_value for value, cond in conditions[::-1]: try: k = rewrite(cond) result = k * value + (1 - k) * result except UnrecognizedCondition: return return result def piecewise_fold(expr, evaluate=True): """ Takes an expression containing a piecewise function and returns the expression in piecewise form. In addition, any ITE conditions are rewritten in negation normal form and simplified. The final Piecewise is evaluated (default) but if the raw form is desired, send ``evaluate=False``; if trivial evaluation is desired, send ``evaluate=None`` and duplicate conditions and processing of True and False will be handled. Examples ======== >>> from sympy import Piecewise, piecewise_fold, sympify as S >>> from sympy.abc import x >>> p = Piecewise((x, x < 1), (1, S(1) <= x)) >>> piecewise_fold(x*p) Piecewise((x**2, x < 1), (x, True)) See Also ======== Piecewise """ if not isinstance(expr, Basic) or not expr.has(Piecewise): return expr new_args = [] if isinstance(expr, (ExprCondPair, Piecewise)): for e, c in expr.args: if not isinstance(e, Piecewise): e = piecewise_fold(e) # we don't keep Piecewise in condition because # it has to be checked to see that it's complete # and we convert it to ITE at that time assert not c.has(Piecewise) # pragma: no cover if isinstance(c, ITE): c = c.to_nnf() c = simplify_logic(c, form='cnf') if isinstance(e, Piecewise): new_args.extend([(piecewise_fold(ei), And(ci, c)) for ei, ci in e.args]) else: new_args.append((e, c)) else: # Given # P1 = Piecewise((e11, c1), (e12, c2), A) # P2 = Piecewise((e21, c1), (e22, c2), B) # ... # the folding of f(P1, P2) is trivially # Piecewise( # (f(e11, e21), c1), # (f(e12, e22), c2), # (f(Piecewise(A), Piecewise(B)), True)) # Certain objects end up rewriting themselves as thus, so # we do that grouping before the more generic folding. # The following applies this idea when f = Add or f = Mul # (and the expression is commutative). if expr.is_Add or expr.is_Mul and expr.is_commutative: p, args = sift(expr.args, lambda x: x.is_Piecewise, binary=True) pc = sift(p, lambda x: tuple([c for e,c in x.args])) for c in list(ordered(pc)): if len(pc[c]) > 1: pargs = [list(i.args) for i in pc[c]] # the first one is the same; there may be more com = common_prefix(*[ [i.cond for i in j] for j in pargs]) n = len(com) collected = [] for i in range(n): collected.append(( expr.func(*[ai[i].expr for ai in pargs]), com[i])) remains = [] for a in pargs: if n == len(a): # no more args continue if a[n].cond == True: # no longer Piecewise remains.append(a[n].expr) else: # restore the remaining Piecewise remains.append( Piecewise(*a[n:], evaluate=False)) if remains: collected.append((expr.func(*remains), True)) args.append(Piecewise(*collected, evaluate=False)) continue args.extend(pc[c]) else: args = expr.args # fold folded = list(map(piecewise_fold, args)) for ec in product(*[ (i.args if isinstance(i, Piecewise) else [(i, true)]) for i in folded]): e, c = zip(*ec) new_args.append((expr.func(*e), And(*c))) if evaluate is None: # don't return duplicate conditions, otherwise don't evaluate new_args = list(reversed([(e, c) for c, e in { c: e for e, c in reversed(new_args)}.items()])) rv = Piecewise(*new_args, evaluate=evaluate) if evaluate is None and len(rv.args) == 1 and rv.args[0].cond == True: return rv.args[0].expr return rv def _clip(A, B, k): """Return interval B as intervals that are covered by A (keyed to k) and all other intervals of B not covered by A keyed to -1. The reference point of each interval is the rhs; if the lhs is greater than the rhs then an interval of zero width interval will result, e.g. (4, 1) is treated like (1, 1). Examples ======== >>> from sympy.functions.elementary.piecewise import _clip >>> from sympy import Tuple >>> A = Tuple(1, 3) >>> B = Tuple(2, 4) >>> _clip(A, B, 0) [(2, 3, 0), (3, 4, -1)] Interpretation: interval portion (2, 3) of interval (2, 4) is covered by interval (1, 3) and is keyed to 0 as requested; interval (3, 4) was not covered by (1, 3) and is keyed to -1. """ a, b = B c, d = A c, d = Min(Max(c, a), b), Min(Max(d, a), b) a, b = Min(a, b), b p = [] if a != c: p.append((a, c, -1)) else: pass if c != d: p.append((c, d, k)) else: pass if b != d: if d == c and p and p[-1][-1] == -1: p[-1] = p[-1][0], b, -1 else: p.append((d, b, -1)) else: pass return p def piecewise_simplify_arguments(expr, **kwargs): from sympy.simplify.simplify import simplify args = [] f1 = expr.args[0].cond.free_symbols if len(f1) == 1 and not expr.atoms(Eq): x = f1.pop() # this won't return intervals involving Eq # and it won't handle symbols treated as # booleans ok, abe_ = expr._intervals(x, err_on_Eq=True) if ok: args = [] for a, b, e, i in abe_: c = expr.args[i].cond if a is S.NegativeInfinity: if b is S.Infinity: c = S.true else: if c.subs(x, b) == True: c = (x <= b) else: c = (x < b) else: incl_a = (c.subs(x, a) == True) incl_b = (c.subs(x, b) == True) if incl_a and incl_b: if b.is_infinite: c = (x >= a) else: c = And(a <= x, x <= b) elif incl_a: c = And(a <= x, x < b) elif incl_b: if b.is_infinite: c = (x > a) else: c = And(a < x, x <= b) else: c = And(a < x, x < b) args.append((e, c)) args.append((Undefined, True)) expr = Piecewise(*args) for e, c in expr.args: if isinstance(e, Basic): doit = kwargs.pop('doit', None) # Skip doit to avoid growth at every call for some integrals # and sums, see sympy/sympy#17165 newe = simplify(e, doit=False, **kwargs) if newe != expr: e = newe if isinstance(c, Basic): c = simplify(c, doit=doit, **kwargs) args.append((e, c)) return Piecewise(*args) def piecewise_simplify(expr, **kwargs): expr = piecewise_simplify_arguments(expr, **kwargs) if not isinstance(expr, Piecewise): return expr args = list(expr.args) _blessed = lambda e: getattr(e.lhs, '_diff_wrt', False) and ( getattr(e.rhs, '_diff_wrt', None) or isinstance(e.rhs, (Rational, NumberSymbol))) for i, (expr, cond) in enumerate(args): # try to simplify conditions and the expression for # equalities that are part of the condition, e.g. # Piecewise((n, And(Eq(n,0), Eq(n + m, 0))), (1, True)) # -> Piecewise((0, And(Eq(n, 0), Eq(m, 0))), (1, True)) if isinstance(cond, And): eqs, other = sift(cond.args, lambda i: isinstance(i, Eq), binary=True) elif isinstance(cond, Eq): eqs, other = [cond], [] else: eqs = other = [] if eqs: eqs = list(ordered(eqs)) for j, e in enumerate(eqs): # these blessed lhs objects behave like Symbols # and the rhs are simple replacements for the "symbols" if _blessed(e): expr = expr.subs(*e.args) eqs[j + 1:] = [ei.subs(*e.args) for ei in eqs[j + 1:]] other = [ei.subs(*e.args) for ei in other] cond = And(*(eqs + other)) args[i] = args[i].func(expr, cond) # See if expressions valid for an Equal expression happens to evaluate # to the same function as in the next piecewise segment, see: # https://github.com/sympy/sympy/issues/8458 prevexpr = None for i, (expr, cond) in reversed(list(enumerate(args))): if prevexpr is not None: if isinstance(cond, And): eqs, other = sift(cond.args, lambda i: isinstance(i, Eq), binary=True) elif isinstance(cond, Eq): eqs, other = [cond], [] else: eqs = other = [] _prevexpr = prevexpr _expr = expr if eqs and not other: eqs = list(ordered(eqs)) for e in eqs: # allow 2 args to collapse into 1 for any e # otherwise limit simplification to only simple-arg # Eq instances if len(args) == 2 or _blessed(e): _prevexpr = _prevexpr.subs(*e.args) _expr = _expr.subs(*e.args) # Did it evaluate to the same? if _prevexpr == _expr: # Set the expression for the Not equal section to the same # as the next. These will be merged when creating the new # Piecewise args[i] = args[i].func(args[i+1][0], cond) else: # Update the expression that we compare against prevexpr = expr else: prevexpr = expr return Piecewise(*args)
a727af32187b49ece5d58374a40b49b376d9769aed17db90600d9ef01e318b19
from typing import Tuple as tTuple from sympy.core.basic import Basic from sympy.core.expr import Expr from sympy.core import Add, S from sympy.core.evalf import get_integer_part, PrecisionExhausted from sympy.core.function import Function from sympy.core.logic import fuzzy_or from sympy.core.numbers import Integer from sympy.core.relational import Gt, Lt, Ge, Le, Relational, is_eq from sympy.core.symbol import Symbol from sympy.core.sympify import _sympify from sympy.multipledispatch import dispatch ############################################################################### ######################### FLOOR and CEILING FUNCTIONS ######################### ############################################################################### class RoundFunction(Function): """The base class for rounding functions.""" args: tTuple[Expr] @classmethod def eval(cls, arg): from sympy.functions.elementary.complexes import im v = cls._eval_number(arg) if v is not None: return v if arg.is_integer or arg.is_finite is False: return arg if arg.is_imaginary or (S.ImaginaryUnit*arg).is_real: i = im(arg) if not i.has(S.ImaginaryUnit): return cls(i)*S.ImaginaryUnit return cls(arg, evaluate=False) # Integral, numerical, symbolic part ipart = npart = spart = S.Zero # Extract integral (or complex integral) terms terms = Add.make_args(arg) for t in terms: if t.is_integer or (t.is_imaginary and im(t).is_integer): ipart += t elif t.has(Symbol): spart += t else: npart += t if not (npart or spart): return ipart # Evaluate npart numerically if independent of spart if npart and ( not spart or npart.is_real and (spart.is_imaginary or (S.ImaginaryUnit*spart).is_real) or npart.is_imaginary and spart.is_real): try: r, i = get_integer_part( npart, cls._dir, {}, return_ints=True) ipart += Integer(r) + Integer(i)*S.ImaginaryUnit npart = S.Zero except (PrecisionExhausted, NotImplementedError): pass spart += npart if not spart: return ipart elif spart.is_imaginary or (S.ImaginaryUnit*spart).is_real: return ipart + cls(im(spart), evaluate=False)*S.ImaginaryUnit elif isinstance(spart, (floor, ceiling)): return ipart + spart else: return ipart + cls(spart, evaluate=False) def _eval_is_finite(self): return self.args[0].is_finite def _eval_is_real(self): return self.args[0].is_real def _eval_is_integer(self): return self.args[0].is_real class floor(RoundFunction): """ Floor is a univariate function which returns the largest integer value not greater than its argument. This implementation generalizes floor to complex numbers by taking the floor of the real and imaginary parts separately. Examples ======== >>> from sympy import floor, E, I, S, Float, Rational >>> floor(17) 17 >>> floor(Rational(23, 10)) 2 >>> floor(2*E) 5 >>> floor(-Float(0.567)) -1 >>> floor(-I/2) -I >>> floor(S(5)/2 + 5*I/2) 2 + 2*I See Also ======== sympy.functions.elementary.integers.ceiling References ========== .. [1] "Concrete mathematics" by Graham, pp. 87 .. [2] http://mathworld.wolfram.com/FloorFunction.html """ _dir = -1 @classmethod def _eval_number(cls, arg): if arg.is_Number: return arg.floor() elif any(isinstance(i, j) for i in (arg, -arg) for j in (floor, ceiling)): return arg if arg.is_NumberSymbol: return arg.approximation_interval(Integer)[0] def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0] arg0 = arg.subs(x, 0) r = self.subs(x, 0) if arg0.is_finite: if arg0 == r: if cdir == 0: ndirl = arg.dir(x, cdir=-1) ndir = arg.dir(x, cdir=1) if ndir != ndirl: raise ValueError("Two sided limit of %s around 0" "does not exist" % self) else: ndir = arg.dir(x, cdir=cdir) return r - 1 if ndir.is_negative else r else: return r return arg.as_leading_term(x, logx=logx, cdir=cdir) def _eval_nseries(self, x, n, logx, cdir=0): arg = self.args[0] arg0 = arg.subs(x, 0) if arg0.is_infinite: from sympy.calculus.accumulationbounds import AccumBounds from sympy.series.order import Order s = arg._eval_nseries(x, n, logx, cdir) o = Order(1, (x, 0)) if n <= 0 else AccumBounds(-1, 0) return s + o r = self.subs(x, 0) if arg0 == r: ndir = arg.dir(x, cdir=cdir if cdir != 0 else 1) return r - 1 if ndir.is_negative else r else: return r def _eval_is_negative(self): return self.args[0].is_negative def _eval_is_nonnegative(self): return self.args[0].is_nonnegative def _eval_rewrite_as_ceiling(self, arg, **kwargs): return -ceiling(-arg) def _eval_rewrite_as_frac(self, arg, **kwargs): return arg - frac(arg) def __le__(self, other): other = S(other) if self.args[0].is_real: if other.is_integer: return self.args[0] < other + 1 if other.is_number and other.is_real: return self.args[0] < ceiling(other) if self.args[0] == other and other.is_real: return S.true if other is S.Infinity and self.is_finite: return S.true return Le(self, other, evaluate=False) def __ge__(self, other): other = S(other) if self.args[0].is_real: if other.is_integer: return self.args[0] >= other if other.is_number and other.is_real: return self.args[0] >= ceiling(other) if self.args[0] == other and other.is_real: return S.false if other is S.NegativeInfinity and self.is_finite: return S.true return Ge(self, other, evaluate=False) def __gt__(self, other): other = S(other) if self.args[0].is_real: if other.is_integer: return self.args[0] >= other + 1 if other.is_number and other.is_real: return self.args[0] >= ceiling(other) if self.args[0] == other and other.is_real: return S.false if other is S.NegativeInfinity and self.is_finite: return S.true return Gt(self, other, evaluate=False) def __lt__(self, other): other = S(other) if self.args[0].is_real: if other.is_integer: return self.args[0] < other if other.is_number and other.is_real: return self.args[0] < ceiling(other) if self.args[0] == other and other.is_real: return S.false if other is S.Infinity and self.is_finite: return S.true return Lt(self, other, evaluate=False) @dispatch(floor, Expr) def _eval_is_eq(lhs, rhs): # noqa:F811 return is_eq(lhs.rewrite(ceiling), rhs) or \ is_eq(lhs.rewrite(frac),rhs) class ceiling(RoundFunction): """ Ceiling is a univariate function which returns the smallest integer value not less than its argument. This implementation generalizes ceiling to complex numbers by taking the ceiling of the real and imaginary parts separately. Examples ======== >>> from sympy import ceiling, E, I, S, Float, Rational >>> ceiling(17) 17 >>> ceiling(Rational(23, 10)) 3 >>> ceiling(2*E) 6 >>> ceiling(-Float(0.567)) 0 >>> ceiling(I/2) I >>> ceiling(S(5)/2 + 5*I/2) 3 + 3*I See Also ======== sympy.functions.elementary.integers.floor References ========== .. [1] "Concrete mathematics" by Graham, pp. 87 .. [2] http://mathworld.wolfram.com/CeilingFunction.html """ _dir = 1 @classmethod def _eval_number(cls, arg): if arg.is_Number: return arg.ceiling() elif any(isinstance(i, j) for i in (arg, -arg) for j in (floor, ceiling)): return arg if arg.is_NumberSymbol: return arg.approximation_interval(Integer)[1] def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0] arg0 = arg.subs(x, 0) r = self.subs(x, 0) if arg0.is_finite: if arg0 == r: if cdir == 0: ndirl = arg.dir(x, cdir=-1) ndir = arg.dir(x, cdir=1) if ndir != ndirl: raise ValueError("Two sided limit of %s around 0" "does not exist" % self) else: ndir = arg.dir(x, cdir=cdir) return r if ndir.is_negative else r + 1 else: return r return arg.as_leading_term(x, logx=logx, cdir=cdir) def _eval_nseries(self, x, n, logx, cdir=0): arg = self.args[0] arg0 = arg.subs(x, 0) if arg0.is_infinite: from sympy.calculus.accumulationbounds import AccumBounds from sympy.series.order import Order s = arg._eval_nseries(x, n, logx, cdir) o = Order(1, (x, 0)) if n <= 0 else AccumBounds(0, 1) return s + o r = self.subs(x, 0) if arg0 == r: ndir = arg.dir(x, cdir=cdir if cdir != 0 else 1) return r if ndir.is_negative else r + 1 else: return r def _eval_rewrite_as_floor(self, arg, **kwargs): return -floor(-arg) def _eval_rewrite_as_frac(self, arg, **kwargs): return arg + frac(-arg) def _eval_is_positive(self): return self.args[0].is_positive def _eval_is_nonpositive(self): return self.args[0].is_nonpositive def __lt__(self, other): other = S(other) if self.args[0].is_real: if other.is_integer: return self.args[0] <= other - 1 if other.is_number and other.is_real: return self.args[0] <= floor(other) if self.args[0] == other and other.is_real: return S.false if other is S.Infinity and self.is_finite: return S.true return Lt(self, other, evaluate=False) def __gt__(self, other): other = S(other) if self.args[0].is_real: if other.is_integer: return self.args[0] > other if other.is_number and other.is_real: return self.args[0] > floor(other) if self.args[0] == other and other.is_real: return S.false if other is S.NegativeInfinity and self.is_finite: return S.true return Gt(self, other, evaluate=False) def __ge__(self, other): other = S(other) if self.args[0].is_real: if other.is_integer: return self.args[0] > other - 1 if other.is_number and other.is_real: return self.args[0] > floor(other) if self.args[0] == other and other.is_real: return S.true if other is S.NegativeInfinity and self.is_finite: return S.true return Ge(self, other, evaluate=False) def __le__(self, other): other = S(other) if self.args[0].is_real: if other.is_integer: return self.args[0] <= other if other.is_number and other.is_real: return self.args[0] <= floor(other) if self.args[0] == other and other.is_real: return S.false if other is S.Infinity and self.is_finite: return S.true return Le(self, other, evaluate=False) @dispatch(ceiling, Basic) # type:ignore def _eval_is_eq(lhs, rhs): # noqa:F811 return is_eq(lhs.rewrite(floor), rhs) or is_eq(lhs.rewrite(frac),rhs) class frac(Function): r"""Represents the fractional part of x For real numbers it is defined [1]_ as .. math:: x - \left\lfloor{x}\right\rfloor Examples ======== >>> from sympy import Symbol, frac, Rational, floor, I >>> frac(Rational(4, 3)) 1/3 >>> frac(-Rational(4, 3)) 2/3 returns zero for integer arguments >>> n = Symbol('n', integer=True) >>> frac(n) 0 rewrite as floor >>> x = Symbol('x') >>> frac(x).rewrite(floor) x - floor(x) for complex arguments >>> r = Symbol('r', real=True) >>> t = Symbol('t', real=True) >>> frac(t + I*r) I*frac(r) + frac(t) See Also ======== sympy.functions.elementary.integers.floor sympy.functions.elementary.integers.ceiling References =========== .. [1] https://en.wikipedia.org/wiki/Fractional_part .. [2] http://mathworld.wolfram.com/FractionalPart.html """ @classmethod def eval(cls, arg): from sympy.calculus.accumulationbounds import AccumBounds from sympy.functions.elementary.complexes import im def _eval(arg): if arg in (S.Infinity, S.NegativeInfinity): return AccumBounds(0, 1) if arg.is_integer: return S.Zero if arg.is_number: if arg is S.NaN: return S.NaN elif arg is S.ComplexInfinity: return S.NaN else: return arg - floor(arg) return cls(arg, evaluate=False) terms = Add.make_args(arg) real, imag = S.Zero, S.Zero for t in terms: # Two checks are needed for complex arguments # see issue-7649 for details if t.is_imaginary or (S.ImaginaryUnit*t).is_real: i = im(t) if not i.has(S.ImaginaryUnit): imag += i else: real += t else: real += t real = _eval(real) imag = _eval(imag) return real + S.ImaginaryUnit*imag def _eval_rewrite_as_floor(self, arg, **kwargs): return arg - floor(arg) def _eval_rewrite_as_ceiling(self, arg, **kwargs): return arg + ceiling(-arg) def _eval_is_finite(self): return True def _eval_is_real(self): return self.args[0].is_extended_real def _eval_is_imaginary(self): return self.args[0].is_imaginary def _eval_is_integer(self): return self.args[0].is_integer def _eval_is_zero(self): return fuzzy_or([self.args[0].is_zero, self.args[0].is_integer]) def _eval_is_negative(self): return False def __ge__(self, other): if self.is_extended_real: other = _sympify(other) # Check if other <= 0 if other.is_extended_nonpositive: return S.true # Check if other >= 1 res = self._value_one_or_more(other) if res is not None: return not(res) return Ge(self, other, evaluate=False) def __gt__(self, other): if self.is_extended_real: other = _sympify(other) # Check if other < 0 res = self._value_one_or_more(other) if res is not None: return not(res) # Check if other >= 1 if other.is_extended_negative: return S.true return Gt(self, other, evaluate=False) def __le__(self, other): if self.is_extended_real: other = _sympify(other) # Check if other < 0 if other.is_extended_negative: return S.false # Check if other >= 1 res = self._value_one_or_more(other) if res is not None: return res return Le(self, other, evaluate=False) def __lt__(self, other): if self.is_extended_real: other = _sympify(other) # Check if other <= 0 if other.is_extended_nonpositive: return S.false # Check if other >= 1 res = self._value_one_or_more(other) if res is not None: return res return Lt(self, other, evaluate=False) def _value_one_or_more(self, other): if other.is_extended_real: if other.is_number: res = other >= 1 if res and not isinstance(res, Relational): return S.true if other.is_integer and other.is_positive: return S.true @dispatch(frac, Basic) # type:ignore def _eval_is_eq(lhs, rhs): # noqa:F811 if (lhs.rewrite(floor) == rhs) or \ (lhs.rewrite(ceiling) == rhs): return True # Check if other < 0 if rhs.is_extended_negative: return False # Check if other >= 1 res = lhs._value_one_or_more(rhs) if res is not None: return False
9159a54b3cdc73a77912c5153c168190754fcb0f9f1e6a82d3f847eb1a2b6758
from typing import Tuple as tTuple from sympy.core.expr import Expr from sympy.core import sympify from sympy.core.add import Add from sympy.core.cache import cacheit from sympy.core.function import (Function, ArgumentIndexError, expand_log, expand_mul, FunctionClass, PoleError, expand_multinomial, expand_complex) from sympy.core.logic import fuzzy_and, fuzzy_not, fuzzy_or from sympy.core.mul import Mul from sympy.core.numbers import Integer, Rational, pi, I from sympy.core.parameters import global_parameters from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import Wild, Dummy from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.miscellaneous import sqrt from sympy.ntheory import multiplicity, perfect_power from sympy.sets.setexpr import SetExpr # NOTE IMPORTANT # The series expansion code in this file is an important part of the gruntz # algorithm for determining limits. _eval_nseries has to return a generalized # power series with coefficients in C(log(x), log). # In more detail, the result of _eval_nseries(self, x, n) must be # c_0*x**e_0 + ... (finitely many terms) # where e_i are numbers (not necessarily integers) and c_i involve only # numbers, the function log, and log(x). [This also means it must not contain # log(x(1+p)), this *has* to be expanded to log(x)+log(1+p) if x.is_positive and # p.is_positive.] class ExpBase(Function): unbranched = True _singularities = (S.ComplexInfinity,) @property def kind(self): return self.exp.kind def inverse(self, argindex=1): """ Returns the inverse function of ``exp(x)``. """ return log def as_numer_denom(self): """ Returns this with a positive exponent as a 2-tuple (a fraction). Examples ======== >>> from sympy import exp >>> from sympy.abc import x >>> exp(-x).as_numer_denom() (1, exp(x)) >>> exp(x).as_numer_denom() (exp(x), 1) """ # this should be the same as Pow.as_numer_denom wrt # exponent handling exp = self.exp neg_exp = exp.is_negative if not neg_exp and not (-exp).is_negative: neg_exp = exp.could_extract_minus_sign() if neg_exp: return S.One, self.func(-exp) return self, S.One @property def exp(self): """ Returns the exponent of the function. """ return self.args[0] def as_base_exp(self): """ Returns the 2-tuple (base, exponent). """ return self.func(1), Mul(*self.args) def _eval_adjoint(self): return self.func(self.exp.adjoint()) def _eval_conjugate(self): return self.func(self.exp.conjugate()) def _eval_transpose(self): return self.func(self.exp.transpose()) def _eval_is_finite(self): arg = self.exp if arg.is_infinite: if arg.is_extended_negative: return True if arg.is_extended_positive: return False if arg.is_finite: return True def _eval_is_rational(self): s = self.func(*self.args) if s.func == self.func: z = s.exp.is_zero if z: return True elif s.exp.is_rational and fuzzy_not(z): return False else: return s.is_rational def _eval_is_zero(self): return self.exp is S.NegativeInfinity def _eval_power(self, other): """exp(arg)**e -> exp(arg*e) if assumptions allow it. """ b, e = self.as_base_exp() return Pow._eval_power(Pow(b, e, evaluate=False), other) def _eval_expand_power_exp(self, **hints): from sympy.concrete.products import Product from sympy.concrete.summations import Sum arg = self.args[0] if arg.is_Add and arg.is_commutative: return Mul.fromiter(self.func(x) for x in arg.args) elif isinstance(arg, Sum) and arg.is_commutative: return Product(self.func(arg.function), *arg.limits) return self.func(arg) class exp_polar(ExpBase): r""" Represent a 'polar number' (see g-function Sphinx documentation). Explanation =========== ``exp_polar`` represents the function `Exp: \mathbb{C} \rightarrow \mathcal{S}`, sending the complex number `z = a + bi` to the polar number `r = exp(a), \theta = b`. It is one of the main functions to construct polar numbers. Examples ======== >>> from sympy import exp_polar, pi, I, exp The main difference is that polar numbers don't "wrap around" at `2 \pi`: >>> exp(2*pi*I) 1 >>> exp_polar(2*pi*I) exp_polar(2*I*pi) apart from that they behave mostly like classical complex numbers: >>> exp_polar(2)*exp_polar(3) exp_polar(5) See Also ======== sympy.simplify.powsimp.powsimp polar_lift periodic_argument principal_branch """ is_polar = True is_comparable = False # cannot be evalf'd def _eval_Abs(self): # Abs is never a polar number from sympy.functions.elementary.complexes import re return exp(re(self.args[0])) def _eval_evalf(self, prec): """ Careful! any evalf of polar numbers is flaky """ from sympy.functions.elementary.complexes import (im, re) i = im(self.args[0]) try: bad = (i <= -pi or i > pi) except TypeError: bad = True if bad: return self # cannot evalf for this argument res = exp(self.args[0])._eval_evalf(prec) if i > 0 and im(res) < 0: # i ~ pi, but exp(I*i) evaluated to argument slightly bigger than pi return re(res) return res def _eval_power(self, other): return self.func(self.args[0]*other) def _eval_is_extended_real(self): if self.args[0].is_extended_real: return True def as_base_exp(self): # XXX exp_polar(0) is special! if self.args[0] == 0: return self, S.One return ExpBase.as_base_exp(self) class ExpMeta(FunctionClass): def __instancecheck__(cls, instance): if exp in instance.__class__.__mro__: return True return isinstance(instance, Pow) and instance.base is S.Exp1 class exp(ExpBase, metaclass=ExpMeta): """ The exponential function, :math:`e^x`. Examples ======== >>> from sympy import exp, I, pi >>> from sympy.abc import x >>> exp(x) exp(x) >>> exp(x).diff(x) exp(x) >>> exp(I*pi) -1 Parameters ========== arg : Expr See Also ======== log """ def fdiff(self, argindex=1): """ Returns the first derivative of this function. """ if argindex == 1: return self else: raise ArgumentIndexError(self, argindex) def _eval_refine(self, assumptions): from sympy.assumptions import ask, Q arg = self.args[0] if arg.is_Mul: Ioo = S.ImaginaryUnit*S.Infinity if arg in [Ioo, -Ioo]: return S.NaN coeff = arg.as_coefficient(S.Pi*S.ImaginaryUnit) if coeff: if ask(Q.integer(2*coeff)): if ask(Q.even(coeff)): return S.One elif ask(Q.odd(coeff)): return S.NegativeOne elif ask(Q.even(coeff + S.Half)): return -S.ImaginaryUnit elif ask(Q.odd(coeff + S.Half)): return S.ImaginaryUnit @classmethod def eval(cls, arg): from sympy.calculus import AccumBounds from sympy.matrices.matrices import MatrixBase from sympy.functions.elementary.complexes import (im, re) from sympy.simplify.simplify import logcombine if isinstance(arg, MatrixBase): return arg.exp() elif global_parameters.exp_is_pow: return Pow(S.Exp1, arg) elif arg.is_Number: if arg is S.NaN: return S.NaN elif arg.is_zero: return S.One elif arg is S.One: return S.Exp1 elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.Zero elif arg is S.ComplexInfinity: return S.NaN elif isinstance(arg, log): return arg.args[0] elif isinstance(arg, AccumBounds): return AccumBounds(exp(arg.min), exp(arg.max)) elif isinstance(arg, SetExpr): return arg._eval_func(cls) elif arg.is_Mul: coeff = arg.as_coefficient(S.Pi*S.ImaginaryUnit) if coeff: if (2*coeff).is_integer: if coeff.is_even: return S.One elif coeff.is_odd: return S.NegativeOne elif (coeff + S.Half).is_even: return -S.ImaginaryUnit elif (coeff + S.Half).is_odd: return S.ImaginaryUnit elif coeff.is_Rational: ncoeff = coeff % 2 # restrict to [0, 2pi) if ncoeff > 1: # restrict to (-pi, pi] ncoeff -= 2 if ncoeff != coeff: return cls(ncoeff*S.Pi*S.ImaginaryUnit) # Warning: code in risch.py will be very sensitive to changes # in this (see DifferentialExtension). # look for a single log factor coeff, terms = arg.as_coeff_Mul() # but it can't be multiplied by oo if coeff in [S.NegativeInfinity, S.Infinity]: if terms.is_number: if coeff is S.NegativeInfinity: terms = -terms if re(terms).is_zero and terms is not S.Zero: return S.NaN if re(terms).is_positive and im(terms) is not S.Zero: return S.ComplexInfinity if re(terms).is_negative: return S.Zero return None coeffs, log_term = [coeff], None for term in Mul.make_args(terms): term_ = logcombine(term) if isinstance(term_, log): if log_term is None: log_term = term_.args[0] else: return None elif term.is_comparable: coeffs.append(term) else: return None return log_term**Mul(*coeffs) if log_term else None elif arg.is_Add: out = [] add = [] argchanged = False for a in arg.args: if a is S.One: add.append(a) continue newa = cls(a) if isinstance(newa, cls): if newa.args[0] != a: add.append(newa.args[0]) argchanged = True else: add.append(a) else: out.append(newa) if out or argchanged: return Mul(*out)*cls(Add(*add), evaluate=False) if arg.is_zero: return S.One @property def base(self): """ Returns the base of the exponential function. """ return S.Exp1 @staticmethod @cacheit def taylor_term(n, x, *previous_terms): """ Calculates the next term in the Taylor series expansion. """ if n < 0: return S.Zero if n == 0: return S.One x = sympify(x) if previous_terms: p = previous_terms[-1] if p is not None: return p * x / n return x**n/factorial(n) def as_real_imag(self, deep=True, **hints): """ Returns this function as a 2-tuple representing a complex number. Examples ======== >>> from sympy import exp, I >>> from sympy.abc import x >>> exp(x).as_real_imag() (exp(re(x))*cos(im(x)), exp(re(x))*sin(im(x))) >>> exp(1).as_real_imag() (E, 0) >>> exp(I).as_real_imag() (cos(1), sin(1)) >>> exp(1+I).as_real_imag() (E*cos(1), E*sin(1)) See Also ======== sympy.functions.elementary.complexes.re sympy.functions.elementary.complexes.im """ from sympy.functions.elementary.trigonometric import cos, sin re, im = self.args[0].as_real_imag() if deep: re = re.expand(deep, **hints) im = im.expand(deep, **hints) cos, sin = cos(im), sin(im) return (exp(re)*cos, exp(re)*sin) def _eval_subs(self, old, new): # keep processing of power-like args centralized in Pow if old.is_Pow: # handle (exp(3*log(x))).subs(x**2, z) -> z**(3/2) old = exp(old.exp*log(old.base)) elif old is S.Exp1 and new.is_Function: old = exp if isinstance(old, exp) or old is S.Exp1: f = lambda a: Pow(*a.as_base_exp(), evaluate=False) if ( a.is_Pow or isinstance(a, exp)) else a return Pow._eval_subs(f(self), f(old), new) if old is exp and not new.is_Function: return new**self.exp._subs(old, new) return Function._eval_subs(self, old, new) def _eval_is_extended_real(self): if self.args[0].is_extended_real: return True elif self.args[0].is_imaginary: arg2 = -S(2) * S.ImaginaryUnit * self.args[0] / S.Pi return arg2.is_even def _eval_is_complex(self): def complex_extended_negative(arg): yield arg.is_complex yield arg.is_extended_negative return fuzzy_or(complex_extended_negative(self.args[0])) def _eval_is_algebraic(self): if (self.exp / S.Pi / S.ImaginaryUnit).is_rational: return True if fuzzy_not(self.exp.is_zero): if self.exp.is_algebraic: return False elif (self.exp / S.Pi).is_rational: return False def _eval_is_extended_positive(self): if self.exp.is_extended_real: return self.args[0] is not S.NegativeInfinity elif self.exp.is_imaginary: arg2 = -S.ImaginaryUnit * self.args[0] / S.Pi return arg2.is_even def _eval_nseries(self, x, n, logx, cdir=0): # NOTE Please see the comment at the beginning of this file, labelled # IMPORTANT. from sympy.functions.elementary.integers import ceiling from sympy.series.limits import limit from sympy.series.order import Order from sympy.simplify.powsimp import powsimp arg = self.exp arg_series = arg._eval_nseries(x, n=n, logx=logx) if arg_series.is_Order: return 1 + arg_series arg0 = limit(arg_series.removeO(), x, 0) if arg0 is S.NegativeInfinity: return Order(x**n, x) if arg0 is S.Infinity: return self t = Dummy("t") nterms = n try: cf = Order(arg.as_leading_term(x, logx=logx), x).getn() except (NotImplementedError, PoleError): cf = 0 if cf and cf > 0: nterms = ceiling(n/cf) exp_series = exp(t)._taylor(t, nterms) r = exp(arg0)*exp_series.subs(t, arg_series - arg0) if cf and cf > 1: r += Order((arg_series - arg0)**n, x)/x**((cf-1)*n) else: r += Order((arg_series - arg0)**n, x) r = r.expand() r = powsimp(r, deep=True, combine='exp') # powsimp may introduce unexpanded (-1)**Rational; see PR #17201 simplerat = lambda x: x.is_Rational and x.q in [3, 4, 6] w = Wild('w', properties=[simplerat]) r = r.replace(S.NegativeOne**w, expand_complex(S.NegativeOne**w)) return r def _taylor(self, x, n): l = [] g = None for i in range(n): g = self.taylor_term(i, self.args[0], g) g = g.nseries(x, n=n) l.append(g.removeO()) return Add(*l) def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].cancel().as_leading_term(x, logx=logx) arg0 = arg.subs(x, 0) if arg0 is S.NaN: arg0 = arg.limit(x, 0) if arg0.is_infinite is False: return exp(arg0) raise PoleError("Cannot expand %s around 0" % (self)) def _eval_rewrite_as_sin(self, arg, **kwargs): from sympy.functions.elementary.trigonometric import sin I = S.ImaginaryUnit return sin(I*arg + S.Pi/2) - I*sin(I*arg) def _eval_rewrite_as_cos(self, arg, **kwargs): from sympy.functions.elementary.trigonometric import cos I = S.ImaginaryUnit return cos(I*arg) + I*cos(I*arg + S.Pi/2) def _eval_rewrite_as_tanh(self, arg, **kwargs): from sympy.functions.elementary.hyperbolic import tanh return (1 + tanh(arg/2))/(1 - tanh(arg/2)) def _eval_rewrite_as_sqrt(self, arg, **kwargs): from sympy.functions.elementary.trigonometric import sin, cos if arg.is_Mul: coeff = arg.coeff(S.Pi*S.ImaginaryUnit) if coeff and coeff.is_number: cosine, sine = cos(S.Pi*coeff), sin(S.Pi*coeff) if not isinstance(cosine, cos) and not isinstance (sine, sin): return cosine + S.ImaginaryUnit*sine def _eval_rewrite_as_Pow(self, arg, **kwargs): if arg.is_Mul: logs = [a for a in arg.args if isinstance(a, log) and len(a.args) == 1] if logs: return Pow(logs[0].args[0], arg.coeff(logs[0])) def match_real_imag(expr): """ Try to match expr with a + b*I for real a and b. ``match_real_imag`` returns a tuple containing the real and imaginary parts of expr or (None, None) if direct matching is not possible. Contrary to ``re()``, ``im()``, ``as_real_imag()``, this helper will not force things by returning expressions themselves containing ``re()`` or ``im()`` and it does not expand its argument either. """ r_, i_ = expr.as_independent(S.ImaginaryUnit, as_Add=True) if i_ == 0 and r_.is_real: return (r_, i_) i_ = i_.as_coefficient(S.ImaginaryUnit) if i_ and i_.is_real and r_.is_real: return (r_, i_) else: return (None, None) # simpler to check for than None class log(Function): r""" The natural logarithm function `\ln(x)` or `\log(x)`. Explanation =========== Logarithms are taken with the natural base, `e`. To get a logarithm of a different base ``b``, use ``log(x, b)``, which is essentially short-hand for ``log(x)/log(b)``. ``log`` represents the principal branch of the natural logarithm. As such it has a branch cut along the negative real axis and returns values having a complex argument in `(-\pi, \pi]`. Examples ======== >>> from sympy import log, sqrt, S, I >>> log(8, 2) 3 >>> log(S(8)/3, 2) -log(3)/log(2) + 3 >>> log(-1 + I*sqrt(3)) log(2) + 2*I*pi/3 See Also ======== exp """ args: tTuple[Expr] _singularities = (S.Zero, S.ComplexInfinity) def fdiff(self, argindex=1): """ Returns the first derivative of the function. """ if argindex == 1: return 1/self.args[0] else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): r""" Returns `e^x`, the inverse function of `\log(x)`. """ return exp @classmethod def eval(cls, arg, base=None): from sympy.functions.elementary.complexes import unpolarify from sympy.calculus import AccumBounds from sympy.functions.elementary.complexes import Abs arg = sympify(arg) if base is not None: base = sympify(base) if base == 1: if arg == 1: return S.NaN else: return S.ComplexInfinity try: # handle extraction of powers of the base now # or else expand_log in Mul would have to handle this n = multiplicity(base, arg) if n: return n + log(arg / base**n) / log(base) else: return log(arg)/log(base) except ValueError: pass if base is not S.Exp1: return cls(arg)/cls(base) else: return cls(arg) if arg.is_Number: if arg.is_zero: return S.ComplexInfinity elif arg is S.One: return S.Zero elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.Infinity elif arg is S.NaN: return S.NaN elif arg.is_Rational and arg.p == 1: return -cls(arg.q) if arg.is_Pow and arg.base is S.Exp1 and arg.exp.is_extended_real: return arg.exp I = S.ImaginaryUnit if isinstance(arg, exp) and arg.exp.is_extended_real: return arg.exp elif isinstance(arg, exp) and arg.exp.is_number: r_, i_ = match_real_imag(arg.exp) if i_ and i_.is_comparable: i_ %= 2*S.Pi if i_ > S.Pi: i_ -= 2*S.Pi return r_ + expand_mul(i_ * I, deep=False) elif isinstance(arg, exp_polar): return unpolarify(arg.exp) elif isinstance(arg, AccumBounds): if arg.min.is_positive: return AccumBounds(log(arg.min), log(arg.max)) else: return elif isinstance(arg, SetExpr): return arg._eval_func(cls) if arg.is_number: if arg.is_negative: return S.Pi * I + cls(-arg) elif arg is S.ComplexInfinity: return S.ComplexInfinity elif arg is S.Exp1: return S.One if arg.is_zero: return S.ComplexInfinity # don't autoexpand Pow or Mul (see the issue 3351): if not arg.is_Add: coeff = arg.as_coefficient(I) if coeff is not None: if coeff is S.Infinity: return S.Infinity elif coeff is S.NegativeInfinity: return S.Infinity elif coeff.is_Rational: if coeff.is_nonnegative: return S.Pi * I * S.Half + cls(coeff) else: return -S.Pi * I * S.Half + cls(-coeff) if arg.is_number and arg.is_algebraic: # Match arg = coeff*(r_ + i_*I) with coeff>0, r_ and i_ real. coeff, arg_ = arg.as_independent(I, as_Add=False) if coeff.is_negative: coeff *= -1 arg_ *= -1 arg_ = expand_mul(arg_, deep=False) r_, i_ = arg_.as_independent(I, as_Add=True) i_ = i_.as_coefficient(I) if coeff.is_real and i_ and i_.is_real and r_.is_real: if r_.is_zero: if i_.is_positive: return S.Pi * I * S.Half + cls(coeff * i_) elif i_.is_negative: return -S.Pi * I * S.Half + cls(coeff * -i_) else: from sympy.simplify import ratsimp # Check for arguments involving rational multiples of pi t = (i_/r_).cancel() t1 = (-t).cancel() atan_table = { # first quadrant only sqrt(3): S.Pi/3, 1: S.Pi/4, sqrt(5 - 2*sqrt(5)): S.Pi/5, sqrt(2)*sqrt(5 - sqrt(5))/(1 + sqrt(5)): S.Pi/5, sqrt(5 + 2*sqrt(5)): S.Pi*Rational(2, 5), sqrt(2)*sqrt(sqrt(5) + 5)/(-1 + sqrt(5)): S.Pi*Rational(2, 5), sqrt(3)/3: S.Pi/6, sqrt(2) - 1: S.Pi/8, sqrt(2 - sqrt(2))/sqrt(sqrt(2) + 2): S.Pi/8, sqrt(2) + 1: S.Pi*Rational(3, 8), sqrt(sqrt(2) + 2)/sqrt(2 - sqrt(2)): S.Pi*Rational(3, 8), sqrt(1 - 2*sqrt(5)/5): S.Pi/10, (-sqrt(2) + sqrt(10))/(2*sqrt(sqrt(5) + 5)): S.Pi/10, sqrt(1 + 2*sqrt(5)/5): S.Pi*Rational(3, 10), (sqrt(2) + sqrt(10))/(2*sqrt(5 - sqrt(5))): S.Pi*Rational(3, 10), 2 - sqrt(3): S.Pi/12, (-1 + sqrt(3))/(1 + sqrt(3)): S.Pi/12, 2 + sqrt(3): S.Pi*Rational(5, 12), (1 + sqrt(3))/(-1 + sqrt(3)): S.Pi*Rational(5, 12) } if t in atan_table: modulus = ratsimp(coeff * Abs(arg_)) if r_.is_positive: return cls(modulus) + I * atan_table[t] else: return cls(modulus) + I * (atan_table[t] - S.Pi) elif t1 in atan_table: modulus = ratsimp(coeff * Abs(arg_)) if r_.is_positive: return cls(modulus) + I * (-atan_table[t1]) else: return cls(modulus) + I * (S.Pi - atan_table[t1]) def as_base_exp(self): """ Returns this function in the form (base, exponent). """ return self, S.One @staticmethod @cacheit def taylor_term(n, x, *previous_terms): # of log(1+x) r""" Returns the next term in the Taylor series expansion of `\log(1+x)`. """ from sympy.simplify.powsimp import powsimp if n < 0: return S.Zero x = sympify(x) if n == 0: return x if previous_terms: p = previous_terms[-1] if p is not None: return powsimp((-n) * p * x / (n + 1), deep=True, combine='exp') return (1 - 2*(n % 2)) * x**(n + 1)/(n + 1) def _eval_expand_log(self, deep=True, **hints): from sympy.functions.elementary.complexes import unpolarify from sympy.ntheory.factor_ import factorint from sympy.concrete import Sum, Product force = hints.get('force', False) factor = hints.get('factor', False) if (len(self.args) == 2): return expand_log(self.func(*self.args), deep=deep, force=force) arg = self.args[0] if arg.is_Integer: # remove perfect powers p = perfect_power(arg) logarg = None coeff = 1 if p is not False: arg, coeff = p logarg = self.func(arg) # expand as product of its prime factors if factor=True if factor: p = factorint(arg) if arg not in p.keys(): logarg = sum(n*log(val) for val, n in p.items()) if logarg is not None: return coeff*logarg elif arg.is_Rational: return log(arg.p) - log(arg.q) elif arg.is_Mul: expr = [] nonpos = [] for x in arg.args: if force or x.is_positive or x.is_polar: a = self.func(x) if isinstance(a, log): expr.append(self.func(x)._eval_expand_log(**hints)) else: expr.append(a) elif x.is_negative: a = self.func(-x) expr.append(a) nonpos.append(S.NegativeOne) else: nonpos.append(x) return Add(*expr) + log(Mul(*nonpos)) elif arg.is_Pow or isinstance(arg, exp): if force or (arg.exp.is_extended_real and (arg.base.is_positive or ((arg.exp+1) .is_positive and (arg.exp-1).is_nonpositive))) or arg.base.is_polar: b = arg.base e = arg.exp a = self.func(b) if isinstance(a, log): return unpolarify(e) * a._eval_expand_log(**hints) else: return unpolarify(e) * a elif isinstance(arg, Product): if force or arg.function.is_positive: return Sum(log(arg.function), *arg.limits) return self.func(arg) def _eval_simplify(self, **kwargs): from sympy.simplify.simplify import expand_log, simplify, inversecombine if len(self.args) == 2: # it's unevaluated return simplify(self.func(*self.args), **kwargs) expr = self.func(simplify(self.args[0], **kwargs)) if kwargs['inverse']: expr = inversecombine(expr) expr = expand_log(expr, deep=True) return min([expr, self], key=kwargs['measure']) def as_real_imag(self, deep=True, **hints): """ Returns this function as a complex coordinate. Examples ======== >>> from sympy import I, log >>> from sympy.abc import x >>> log(x).as_real_imag() (log(Abs(x)), arg(x)) >>> log(I).as_real_imag() (0, pi/2) >>> log(1 + I).as_real_imag() (log(sqrt(2)), pi/4) >>> log(I*x).as_real_imag() (log(Abs(x)), arg(I*x)) """ from sympy.functions.elementary.complexes import (Abs, arg) sarg = self.args[0] if deep: sarg = self.args[0].expand(deep, **hints) abs = Abs(sarg) if abs == sarg: return self, S.Zero arg = arg(sarg) if hints.get('log', False): # Expand the log hints['complex'] = False return (log(abs).expand(deep, **hints), arg) else: return log(abs), arg def _eval_is_rational(self): s = self.func(*self.args) if s.func == self.func: if (self.args[0] - 1).is_zero: return True if s.args[0].is_rational and fuzzy_not((self.args[0] - 1).is_zero): return False else: return s.is_rational def _eval_is_algebraic(self): s = self.func(*self.args) if s.func == self.func: if (self.args[0] - 1).is_zero: return True elif fuzzy_not((self.args[0] - 1).is_zero): if self.args[0].is_algebraic: return False else: return s.is_algebraic def _eval_is_extended_real(self): return self.args[0].is_extended_positive def _eval_is_complex(self): z = self.args[0] return fuzzy_and([z.is_complex, fuzzy_not(z.is_zero)]) def _eval_is_finite(self): arg = self.args[0] if arg.is_zero: return False return arg.is_finite def _eval_is_extended_positive(self): return (self.args[0] - 1).is_extended_positive def _eval_is_zero(self): return (self.args[0] - 1).is_zero def _eval_is_extended_nonnegative(self): return (self.args[0] - 1).is_extended_nonnegative def _eval_nseries(self, x, n, logx, cdir=0): # NOTE Please see the comment at the beginning of this file, labelled # IMPORTANT. from sympy.functions.elementary.complexes import im from sympy.polys.polytools import cancel from sympy.series.order import Order from sympy.simplify.simplify import logcombine from itertools import product if not logx: logx = log(x) if self.args[0] == x: return logx arg = self.args[0] k, l = Wild("k"), Wild("l") r = arg.match(k*x**l) if r is not None: k, l = r[k], r[l] if l != 0 and not l.has(x) and not k.has(x): r = log(k) + l*logx # XXX true regardless of assumptions? return r def coeff_exp(term, x): coeff, exp = S.One, S.Zero for factor in Mul.make_args(term): if factor.has(x): base, exp = factor.as_base_exp() if base != x: try: return term.leadterm(x) except ValueError: return term, S.Zero else: coeff *= factor return coeff, exp # TODO new and probably slow try: a, b = arg.leadterm(x) s = arg.nseries(x, n=n+b, logx=logx) except (ValueError, NotImplementedError, PoleError): s = arg.nseries(x, n=n, logx=logx) while s.is_Order: n += 1 s = arg.nseries(x, n=n, logx=logx) a, b = s.removeO().leadterm(x) p = cancel(s/(a*x**b) - 1).expand().powsimp() if p.has(exp): p = logcombine(p) if isinstance(p, Order): n = p.getn() _, d = coeff_exp(p, x) if not d.is_positive: return log(a) + b*logx + Order(x**n, x) def mul(d1, d2): res = {} for e1, e2 in product(d1, d2): ex = e1 + e2 if ex < n: res[ex] = res.get(ex, S.Zero) + d1[e1]*d2[e2] return res pterms = {} for term in Add.make_args(p): co1, e1 = coeff_exp(term, x) pterms[e1] = pterms.get(e1, S.Zero) + co1.removeO() k = S.One terms = {} pk = pterms while k*d < n: coeff = -S.NegativeOne**k/k for ex in pk: terms[ex] = terms.get(ex, S.Zero) + coeff*pk[ex] pk = mul(pk, pterms) k += S.One res = log(a) + b*logx for ex in terms: res += terms[ex]*x**(ex) if cdir != 0: cdir = self.args[0].dir(x, cdir) if a.is_real and a.is_negative and im(cdir) < 0: res -= 2*I*S.Pi return res + Order(x**n, x) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.functions.elementary.complexes import (im, re) arg0 = self.args[0].together() arg = arg0.as_leading_term(x, cdir=cdir) x0 = arg0.subs(x, 0) if (x0 is S.NaN and logx is None): x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if x0 in (S.NegativeInfinity, S.Infinity): raise PoleError("Cannot expand %s around 0" % (self)) if x0 == 1: return (arg0 - S.One).as_leading_term(x) if cdir != 0: cdir = arg0.dir(x, cdir) if x0.is_real and x0.is_negative and im(cdir).is_negative: return self.func(x0) - 2*I*S.Pi return self.func(arg) class LambertW(Function): r""" The Lambert W function `W(z)` is defined as the inverse function of `w \exp(w)` [1]_. Explanation =========== In other words, the value of `W(z)` is such that `z = W(z) \exp(W(z))` for any complex number `z`. The Lambert W function is a multivalued function with infinitely many branches `W_k(z)`, indexed by `k \in \mathbb{Z}`. Each branch gives a different solution `w` of the equation `z = w \exp(w)`. The Lambert W function has two partially real branches: the principal branch (`k = 0`) is real for real `z > -1/e`, and the `k = -1` branch is real for `-1/e < z < 0`. All branches except `k = 0` have a logarithmic singularity at `z = 0`. Examples ======== >>> from sympy import LambertW >>> LambertW(1.2) 0.635564016364870 >>> LambertW(1.2, -1).n() -1.34747534407696 - 4.41624341514535*I >>> LambertW(-1).is_real False References ========== .. [1] https://en.wikipedia.org/wiki/Lambert_W_function """ _singularities = (-Pow(S.Exp1, -1, evaluate=False), S.ComplexInfinity) @classmethod def eval(cls, x, k=None): if k == S.Zero: return cls(x) elif k is None: k = S.Zero if k.is_zero: if x.is_zero: return S.Zero if x is S.Exp1: return S.One if x == -1/S.Exp1: return S.NegativeOne if x == -log(2)/2: return -log(2) if x == 2*log(2): return log(2) if x == -S.Pi/2: return S.ImaginaryUnit*S.Pi/2 if x == exp(1 + S.Exp1): return S.Exp1 if x is S.Infinity: return S.Infinity if x.is_zero: return S.Zero if fuzzy_not(k.is_zero): if x.is_zero: return S.NegativeInfinity if k is S.NegativeOne: if x == -S.Pi/2: return -S.ImaginaryUnit*S.Pi/2 elif x == -1/S.Exp1: return S.NegativeOne elif x == -2*exp(-2): return -Integer(2) def fdiff(self, argindex=1): """ Return the first derivative of this function. """ x = self.args[0] if len(self.args) == 1: if argindex == 1: return LambertW(x)/(x*(1 + LambertW(x))) else: k = self.args[1] if argindex == 1: return LambertW(x, k)/(x*(1 + LambertW(x, k))) raise ArgumentIndexError(self, argindex) def _eval_is_extended_real(self): x = self.args[0] if len(self.args) == 1: k = S.Zero else: k = self.args[1] if k.is_zero: if (x + 1/S.Exp1).is_positive: return True elif (x + 1/S.Exp1).is_nonpositive: return False elif (k + 1).is_zero: if x.is_negative and (x + 1/S.Exp1).is_positive: return True elif x.is_nonpositive or (x + 1/S.Exp1).is_nonnegative: return False elif fuzzy_not(k.is_zero) and fuzzy_not((k + 1).is_zero): if x.is_extended_real: return False def _eval_is_finite(self): return self.args[0].is_finite def _eval_is_algebraic(self): s = self.func(*self.args) if s.func == self.func: if fuzzy_not(self.args[0].is_zero) and self.args[0].is_algebraic: return False else: return s.is_algebraic def _eval_as_leading_term(self, x, logx=None, cdir=0): if len(self.args) == 1: arg = self.args[0] arg0 = arg.subs(x, 0).cancel() if not arg0.is_zero: return self.func(arg0) return arg.as_leading_term(x) def _eval_nseries(self, x, n, logx, cdir=0): if len(self.args) == 1: from sympy.functions.elementary.integers import ceiling from sympy.series.order import Order arg = self.args[0].nseries(x, n=n, logx=logx) lt = arg.compute_leading_term(x, logx=logx) lte = 1 if lt.is_Pow: lte = lt.exp if ceiling(n/lte) >= 1: s = Add(*[(-S.One)**(k - 1)*Integer(k)**(k - 2)/ factorial(k - 1)*arg**k for k in range(1, ceiling(n/lte))]) s = expand_multinomial(s) else: s = S.Zero return s + Order(x**n, x) return super()._eval_nseries(x, n, logx) def _eval_is_zero(self): x = self.args[0] if len(self.args) == 1: return x.is_zero else: return fuzzy_and([x.is_zero, self.args[1].is_zero])
6a5137c3838c0289d6083406acb10a681a4b04a58b1376633e0f16488aebf0a8
from sympy.core.logic import FuzzyBool from sympy.core import S, sympify, cacheit, pi, I, Rational from sympy.core.add import Add from sympy.core.function import Function, ArgumentIndexError from sympy.functions.combinatorial.factorials import factorial, RisingFactorial from sympy.functions.elementary.exponential import exp, log, match_real_imag from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.integers import floor from sympy.core.logic import fuzzy_or, fuzzy_and def _rewrite_hyperbolics_as_exp(expr): expr = sympify(expr) return expr.xreplace({h: h.rewrite(exp) for h in expr.atoms(HyperbolicFunction)}) ############################################################################### ########################### HYPERBOLIC FUNCTIONS ############################## ############################################################################### class HyperbolicFunction(Function): """ Base class for hyperbolic functions. See Also ======== sinh, cosh, tanh, coth """ unbranched = True def _peeloff_ipi(arg): """ Split ARG into two parts, a "rest" and a multiple of I*pi. This assumes ARG to be an Add. The multiple of I*pi returned in the second position is always a Rational. Examples ======== >>> from sympy.functions.elementary.hyperbolic import _peeloff_ipi as peel >>> from sympy import pi, I >>> from sympy.abc import x, y >>> peel(x + I*pi/2) (x, 1/2) >>> peel(x + I*2*pi/3 + I*pi*y) (x + I*pi*y + I*pi/6, 1/2) """ ipi = S.Pi*S.ImaginaryUnit for a in Add.make_args(arg): if a == ipi: K = S.One break elif a.is_Mul: K, p = a.as_two_terms() if p == ipi and K.is_Rational: break else: return arg, S.Zero m1 = (K % S.Half) m2 = K - m1 return arg - m2*ipi, m2 class sinh(HyperbolicFunction): r""" sinh(x) is the hyperbolic sine of x. The hyperbolic sine function is $\frac{e^x - e^{-x}}{2}$. Examples ======== >>> from sympy import sinh >>> from sympy.abc import x >>> sinh(x) sinh(x) See Also ======== cosh, tanh, asinh """ def fdiff(self, argindex=1): """ Returns the first derivative of this function. """ if argindex == 1: return cosh(self.args[0]) else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return asinh @classmethod def eval(cls, arg): from sympy.functions.elementary.trigonometric import sin arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.NegativeInfinity elif arg.is_zero: return S.Zero elif arg.is_negative: return -cls(-arg) else: if arg is S.ComplexInfinity: return S.NaN i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: return S.ImaginaryUnit * sin(i_coeff) else: if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_Add: x, m = _peeloff_ipi(arg) if m: m = m*S.Pi*S.ImaginaryUnit return sinh(m)*cosh(x) + cosh(m)*sinh(x) if arg.is_zero: return S.Zero if arg.func == asinh: return arg.args[0] if arg.func == acosh: x = arg.args[0] return sqrt(x - 1) * sqrt(x + 1) if arg.func == atanh: x = arg.args[0] return x/sqrt(1 - x**2) if arg.func == acoth: x = arg.args[0] return 1/(sqrt(x - 1) * sqrt(x + 1)) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): """ Returns the next term in the Taylor series expansion. """ if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) if len(previous_terms) > 2: p = previous_terms[-2] return p * x**2 / (n*(n - 1)) else: return x**(n) / factorial(n) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): """ Returns this function as a complex coordinate. """ from sympy.functions.elementary.trigonometric import (cos, sin) if self.args[0].is_extended_real: if deep: hints['complex'] = False return (self.expand(deep, **hints), S.Zero) else: return (self, S.Zero) if deep: re, im = self.args[0].expand(deep, **hints).as_real_imag() else: re, im = self.args[0].as_real_imag() return (sinh(re)*cos(im), cosh(re)*sin(im)) def _eval_expand_complex(self, deep=True, **hints): re_part, im_part = self.as_real_imag(deep=deep, **hints) return re_part + im_part*S.ImaginaryUnit def _eval_expand_trig(self, deep=True, **hints): if deep: arg = self.args[0].expand(deep, **hints) else: arg = self.args[0] x = None if arg.is_Add: # TODO, implement more if deep stuff here x, y = arg.as_two_terms() else: coeff, terms = arg.as_coeff_Mul(rational=True) if coeff is not S.One and coeff.is_Integer and terms is not S.One: x = terms y = (coeff - 1)*x if x is not None: return (sinh(x)*cosh(y) + sinh(y)*cosh(x)).expand(trig=True) return sinh(arg) def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs): return (exp(arg) - exp(-arg)) / 2 def _eval_rewrite_as_exp(self, arg, **kwargs): return (exp(arg) - exp(-arg)) / 2 def _eval_rewrite_as_cosh(self, arg, **kwargs): return -S.ImaginaryUnit*cosh(arg + S.Pi*S.ImaginaryUnit/2) def _eval_rewrite_as_tanh(self, arg, **kwargs): tanh_half = tanh(S.Half*arg) return 2*tanh_half/(1 - tanh_half**2) def _eval_rewrite_as_coth(self, arg, **kwargs): coth_half = coth(S.Half*arg) return 2*coth_half/(coth_half**2 - 1) def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.NaN: arg0 = arg.limit(x, 0, dir='-' if cdir.is_negative else '+') if arg0.is_zero: return arg elif arg0.is_finite: return self.func(arg0) else: return self def _eval_is_real(self): arg = self.args[0] if arg.is_real: return True # if `im` is of the form n*pi # else, check if it is a number re, im = arg.as_real_imag() return (im%pi).is_zero def _eval_is_extended_real(self): if self.args[0].is_extended_real: return True def _eval_is_positive(self): if self.args[0].is_extended_real: return self.args[0].is_positive def _eval_is_negative(self): if self.args[0].is_extended_real: return self.args[0].is_negative def _eval_is_finite(self): arg = self.args[0] return arg.is_finite def _eval_is_zero(self): rest, ipi_mult = _peeloff_ipi(self.args[0]) if rest.is_zero: return ipi_mult.is_integer class cosh(HyperbolicFunction): r""" cosh(x) is the hyperbolic cosine of x. The hyperbolic cosine function is $\frac{e^x + e^{-x}}{2}$. Examples ======== >>> from sympy import cosh >>> from sympy.abc import x >>> cosh(x) cosh(x) See Also ======== sinh, tanh, acosh """ def fdiff(self, argindex=1): if argindex == 1: return sinh(self.args[0]) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): from sympy.functions.elementary.trigonometric import cos arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.Infinity elif arg.is_zero: return S.One elif arg.is_negative: return cls(-arg) else: if arg is S.ComplexInfinity: return S.NaN i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: return cos(i_coeff) else: if arg.could_extract_minus_sign(): return cls(-arg) if arg.is_Add: x, m = _peeloff_ipi(arg) if m: m = m*S.Pi*S.ImaginaryUnit return cosh(m)*cosh(x) + sinh(m)*sinh(x) if arg.is_zero: return S.One if arg.func == asinh: return sqrt(1 + arg.args[0]**2) if arg.func == acosh: return arg.args[0] if arg.func == atanh: return 1/sqrt(1 - arg.args[0]**2) if arg.func == acoth: x = arg.args[0] return x/(sqrt(x - 1) * sqrt(x + 1)) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 1: return S.Zero else: x = sympify(x) if len(previous_terms) > 2: p = previous_terms[-2] return p * x**2 / (n*(n - 1)) else: return x**(n)/factorial(n) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): from sympy.functions.elementary.trigonometric import (cos, sin) if self.args[0].is_extended_real: if deep: hints['complex'] = False return (self.expand(deep, **hints), S.Zero) else: return (self, S.Zero) if deep: re, im = self.args[0].expand(deep, **hints).as_real_imag() else: re, im = self.args[0].as_real_imag() return (cosh(re)*cos(im), sinh(re)*sin(im)) def _eval_expand_complex(self, deep=True, **hints): re_part, im_part = self.as_real_imag(deep=deep, **hints) return re_part + im_part*S.ImaginaryUnit def _eval_expand_trig(self, deep=True, **hints): if deep: arg = self.args[0].expand(deep, **hints) else: arg = self.args[0] x = None if arg.is_Add: # TODO, implement more if deep stuff here x, y = arg.as_two_terms() else: coeff, terms = arg.as_coeff_Mul(rational=True) if coeff is not S.One and coeff.is_Integer and terms is not S.One: x = terms y = (coeff - 1)*x if x is not None: return (cosh(x)*cosh(y) + sinh(x)*sinh(y)).expand(trig=True) return cosh(arg) def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs): return (exp(arg) + exp(-arg)) / 2 def _eval_rewrite_as_exp(self, arg, **kwargs): return (exp(arg) + exp(-arg)) / 2 def _eval_rewrite_as_sinh(self, arg, **kwargs): return -S.ImaginaryUnit*sinh(arg + S.Pi*S.ImaginaryUnit/2) def _eval_rewrite_as_tanh(self, arg, **kwargs): tanh_half = tanh(S.Half*arg)**2 return (1 + tanh_half)/(1 - tanh_half) def _eval_rewrite_as_coth(self, arg, **kwargs): coth_half = coth(S.Half*arg)**2 return (coth_half + 1)/(coth_half - 1) def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir) arg0 = arg.subs(x, 0) if arg0 is S.NaN: arg0 = arg.limit(x, 0, dir='-' if cdir.is_negative else '+') if arg0.is_zero: return S.One elif arg0.is_finite: return self.func(arg0) else: return self def _eval_is_real(self): arg = self.args[0] # `cosh(x)` is real for real OR purely imaginary `x` if arg.is_real or arg.is_imaginary: return True # cosh(a+ib) = cos(b)*cosh(a) + i*sin(b)*sinh(a) # the imaginary part can be an expression like n*pi # if not, check if the imaginary part is a number re, im = arg.as_real_imag() return (im%pi).is_zero def _eval_is_positive(self): # cosh(x+I*y) = cos(y)*cosh(x) + I*sin(y)*sinh(x) # cosh(z) is positive iff it is real and the real part is positive. # So we need sin(y)*sinh(x) = 0 which gives x=0 or y=n*pi # Case 1 (y=n*pi): cosh(z) = (-1)**n * cosh(x) -> positive for n even # Case 2 (x=0): cosh(z) = cos(y) -> positive when cos(y) is positive z = self.args[0] x, y = z.as_real_imag() ymod = y % (2*pi) yzero = ymod.is_zero # shortcut if ymod is zero if yzero: return True xzero = x.is_zero # shortcut x is not zero if xzero is False: return yzero return fuzzy_or([ # Case 1: yzero, # Case 2: fuzzy_and([ xzero, fuzzy_or([ymod < pi/2, ymod > 3*pi/2]) ]) ]) def _eval_is_nonnegative(self): z = self.args[0] x, y = z.as_real_imag() ymod = y % (2*pi) yzero = ymod.is_zero # shortcut if ymod is zero if yzero: return True xzero = x.is_zero # shortcut x is not zero if xzero is False: return yzero return fuzzy_or([ # Case 1: yzero, # Case 2: fuzzy_and([ xzero, fuzzy_or([ymod <= pi/2, ymod >= 3*pi/2]) ]) ]) def _eval_is_finite(self): arg = self.args[0] return arg.is_finite def _eval_is_zero(self): rest, ipi_mult = _peeloff_ipi(self.args[0]) if ipi_mult and rest.is_zero: return (ipi_mult - S.Half).is_integer class tanh(HyperbolicFunction): r""" tanh(x) is the hyperbolic tangent of x. The hyperbolic tangent function is $\frac{\sinh(x)}{\cosh(x)}$. Examples ======== >>> from sympy import tanh >>> from sympy.abc import x >>> tanh(x) tanh(x) See Also ======== sinh, cosh, atanh """ def fdiff(self, argindex=1): if argindex == 1: return S.One - tanh(self.args[0])**2 else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return atanh @classmethod def eval(cls, arg): from sympy.functions.elementary.trigonometric import tan arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.One elif arg is S.NegativeInfinity: return S.NegativeOne elif arg.is_zero: return S.Zero elif arg.is_negative: return -cls(-arg) else: if arg is S.ComplexInfinity: return S.NaN i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: if i_coeff.could_extract_minus_sign(): return -S.ImaginaryUnit * tan(-i_coeff) return S.ImaginaryUnit * tan(i_coeff) else: if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_Add: x, m = _peeloff_ipi(arg) if m: tanhm = tanh(m*S.Pi*S.ImaginaryUnit) if tanhm is S.ComplexInfinity: return coth(x) else: # tanhm == 0 return tanh(x) if arg.is_zero: return S.Zero if arg.func == asinh: x = arg.args[0] return x/sqrt(1 + x**2) if arg.func == acosh: x = arg.args[0] return sqrt(x - 1) * sqrt(x + 1) / x if arg.func == atanh: return arg.args[0] if arg.func == acoth: return 1/arg.args[0] @staticmethod @cacheit def taylor_term(n, x, *previous_terms): from sympy.functions.combinatorial.numbers import bernoulli if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) a = 2**(n + 1) B = bernoulli(n + 1) F = factorial(n + 1) return a*(a - 1) * B/F * x**n def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): from sympy.functions.elementary.trigonometric import (cos, sin) if self.args[0].is_extended_real: if deep: hints['complex'] = False return (self.expand(deep, **hints), S.Zero) else: return (self, S.Zero) if deep: re, im = self.args[0].expand(deep, **hints).as_real_imag() else: re, im = self.args[0].as_real_imag() denom = sinh(re)**2 + cos(im)**2 return (sinh(re)*cosh(re)/denom, sin(im)*cos(im)/denom) def _eval_expand_trig(self, **hints): arg = self.args[0] if arg.is_Add: from sympy.polys.specialpolys import symmetric_poly n = len(arg.args) TX = [tanh(x, evaluate=False)._eval_expand_trig() for x in arg.args] p = [0, 0] # [den, num] for i in range(n + 1): p[i % 2] += symmetric_poly(i, TX) return p[1]/p[0] elif arg.is_Mul: from sympy.functions.combinatorial.numbers import nC coeff, terms = arg.as_coeff_Mul() if coeff.is_Integer and coeff > 1: n = [] d = [] T = tanh(terms) for k in range(1, coeff + 1, 2): n.append(nC(range(coeff), k)*T**k) for k in range(0, coeff + 1, 2): d.append(nC(range(coeff), k)*T**k) return Add(*n)/Add(*d) return tanh(arg) def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs): neg_exp, pos_exp = exp(-arg), exp(arg) return (pos_exp - neg_exp)/(pos_exp + neg_exp) def _eval_rewrite_as_exp(self, arg, **kwargs): neg_exp, pos_exp = exp(-arg), exp(arg) return (pos_exp - neg_exp)/(pos_exp + neg_exp) def _eval_rewrite_as_sinh(self, arg, **kwargs): return S.ImaginaryUnit*sinh(arg)/sinh(S.Pi*S.ImaginaryUnit/2 - arg) def _eval_rewrite_as_cosh(self, arg, **kwargs): return S.ImaginaryUnit*cosh(S.Pi*S.ImaginaryUnit/2 - arg)/cosh(arg) def _eval_rewrite_as_coth(self, arg, **kwargs): return 1/coth(arg) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.series.order import Order arg = self.args[0].as_leading_term(x) if x in arg.free_symbols and Order(1, x).contains(arg): return arg else: return self.func(arg) def _eval_is_real(self): arg = self.args[0] if arg.is_real: return True re, im = arg.as_real_imag() # if denom = 0, tanh(arg) = zoo if re == 0 and im % pi == pi/2: return None # check if im is of the form n*pi/2 to make sin(2*im) = 0 # if not, im could be a number, return False in that case return (im % (pi/2)).is_zero def _eval_is_extended_real(self): if self.args[0].is_extended_real: return True def _eval_is_positive(self): if self.args[0].is_extended_real: return self.args[0].is_positive def _eval_is_negative(self): if self.args[0].is_extended_real: return self.args[0].is_negative def _eval_is_finite(self): from sympy.functions.elementary.trigonometric import cos arg = self.args[0] re, im = arg.as_real_imag() denom = cos(im)**2 + sinh(re)**2 if denom == 0: return False elif denom.is_number: return True if arg.is_extended_real: return True def _eval_is_zero(self): arg = self.args[0] if arg.is_zero: return True class coth(HyperbolicFunction): r""" coth(x) is the hyperbolic cotangent of x. The hyperbolic cotangent function is $\frac{\cosh(x)}{\sinh(x)}$. Examples ======== >>> from sympy import coth >>> from sympy.abc import x >>> coth(x) coth(x) See Also ======== sinh, cosh, acoth """ def fdiff(self, argindex=1): if argindex == 1: return -1/sinh(self.args[0])**2 else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return acoth @classmethod def eval(cls, arg): from sympy.functions.elementary.trigonometric import cot arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.One elif arg is S.NegativeInfinity: return S.NegativeOne elif arg.is_zero: return S.ComplexInfinity elif arg.is_negative: return -cls(-arg) else: if arg is S.ComplexInfinity: return S.NaN i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: if i_coeff.could_extract_minus_sign(): return S.ImaginaryUnit * cot(-i_coeff) return -S.ImaginaryUnit * cot(i_coeff) else: if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_Add: x, m = _peeloff_ipi(arg) if m: cothm = coth(m*S.Pi*S.ImaginaryUnit) if cothm is S.ComplexInfinity: return coth(x) else: # cothm == 0 return tanh(x) if arg.is_zero: return S.ComplexInfinity if arg.func == asinh: x = arg.args[0] return sqrt(1 + x**2)/x if arg.func == acosh: x = arg.args[0] return x/(sqrt(x - 1) * sqrt(x + 1)) if arg.func == atanh: return 1/arg.args[0] if arg.func == acoth: return arg.args[0] @staticmethod @cacheit def taylor_term(n, x, *previous_terms): from sympy.functions.combinatorial.numbers import bernoulli if n == 0: return 1 / sympify(x) elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) B = bernoulli(n + 1) F = factorial(n + 1) return 2**(n + 1) * B/F * x**n def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def as_real_imag(self, deep=True, **hints): from sympy.functions.elementary.trigonometric import (cos, sin) if self.args[0].is_extended_real: if deep: hints['complex'] = False return (self.expand(deep, **hints), S.Zero) else: return (self, S.Zero) if deep: re, im = self.args[0].expand(deep, **hints).as_real_imag() else: re, im = self.args[0].as_real_imag() denom = sinh(re)**2 + sin(im)**2 return (sinh(re)*cosh(re)/denom, -sin(im)*cos(im)/denom) def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs): neg_exp, pos_exp = exp(-arg), exp(arg) return (pos_exp + neg_exp)/(pos_exp - neg_exp) def _eval_rewrite_as_exp(self, arg, **kwargs): neg_exp, pos_exp = exp(-arg), exp(arg) return (pos_exp + neg_exp)/(pos_exp - neg_exp) def _eval_rewrite_as_sinh(self, arg, **kwargs): return -S.ImaginaryUnit*sinh(S.Pi*S.ImaginaryUnit/2 - arg)/sinh(arg) def _eval_rewrite_as_cosh(self, arg, **kwargs): return -S.ImaginaryUnit*cosh(arg)/cosh(S.Pi*S.ImaginaryUnit/2 - arg) def _eval_rewrite_as_tanh(self, arg, **kwargs): return 1/tanh(arg) def _eval_is_positive(self): if self.args[0].is_extended_real: return self.args[0].is_positive def _eval_is_negative(self): if self.args[0].is_extended_real: return self.args[0].is_negative def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.series.order import Order arg = self.args[0].as_leading_term(x) if x in arg.free_symbols and Order(1, x).contains(arg): return 1/arg else: return self.func(arg) def _eval_expand_trig(self, **hints): arg = self.args[0] if arg.is_Add: from sympy.polys.specialpolys import symmetric_poly CX = [coth(x, evaluate=False)._eval_expand_trig() for x in arg.args] p = [[], []] n = len(arg.args) for i in range(n, -1, -1): p[(n - i) % 2].append(symmetric_poly(i, CX)) return Add(*p[0])/Add(*p[1]) elif arg.is_Mul: from sympy.functions.combinatorial.factorials import binomial coeff, x = arg.as_coeff_Mul(rational=True) if coeff.is_Integer and coeff > 1: c = coth(x, evaluate=False) p = [[], []] for i in range(coeff, -1, -1): p[(coeff - i) % 2].append(binomial(coeff, i)*c**i) return Add(*p[0])/Add(*p[1]) return coth(arg) class ReciprocalHyperbolicFunction(HyperbolicFunction): """Base class for reciprocal functions of hyperbolic functions. """ #To be defined in class _reciprocal_of = None _is_even = None # type: FuzzyBool _is_odd = None # type: FuzzyBool @classmethod def eval(cls, arg): if arg.could_extract_minus_sign(): if cls._is_even: return cls(-arg) if cls._is_odd: return -cls(-arg) t = cls._reciprocal_of.eval(arg) if hasattr(arg, 'inverse') and arg.inverse() == cls: return arg.args[0] return 1/t if t is not None else t def _call_reciprocal(self, method_name, *args, **kwargs): # Calls method_name on _reciprocal_of o = self._reciprocal_of(self.args[0]) return getattr(o, method_name)(*args, **kwargs) def _calculate_reciprocal(self, method_name, *args, **kwargs): # If calling method_name on _reciprocal_of returns a value != None # then return the reciprocal of that value t = self._call_reciprocal(method_name, *args, **kwargs) return 1/t if t is not None else t def _rewrite_reciprocal(self, method_name, arg): # Special handling for rewrite functions. If reciprocal rewrite returns # unmodified expression, then return None t = self._call_reciprocal(method_name, arg) if t is not None and t != self._reciprocal_of(arg): return 1/t def _eval_rewrite_as_exp(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_exp", arg) def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_tractable", arg) def _eval_rewrite_as_tanh(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_tanh", arg) def _eval_rewrite_as_coth(self, arg, **kwargs): return self._rewrite_reciprocal("_eval_rewrite_as_coth", arg) def as_real_imag(self, deep = True, **hints): return (1 / self._reciprocal_of(self.args[0])).as_real_imag(deep, **hints) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def _eval_expand_complex(self, deep=True, **hints): re_part, im_part = self.as_real_imag(deep=True, **hints) return re_part + S.ImaginaryUnit*im_part def _eval_expand_trig(self, **hints): return self._calculate_reciprocal("_eval_expand_trig", **hints) def _eval_as_leading_term(self, x, logx=None, cdir=0): return (1/self._reciprocal_of(self.args[0]))._eval_as_leading_term(x) def _eval_is_extended_real(self): return self._reciprocal_of(self.args[0]).is_extended_real def _eval_is_finite(self): return (1/self._reciprocal_of(self.args[0])).is_finite class csch(ReciprocalHyperbolicFunction): r""" csch(x) is the hyperbolic cosecant of x. The hyperbolic cosecant function is $\frac{2}{e^x - e^{-x}}$ Examples ======== >>> from sympy import csch >>> from sympy.abc import x >>> csch(x) csch(x) See Also ======== sinh, cosh, tanh, sech, asinh, acosh """ _reciprocal_of = sinh _is_odd = True def fdiff(self, argindex=1): """ Returns the first derivative of this function """ if argindex == 1: return -coth(self.args[0]) * csch(self.args[0]) else: raise ArgumentIndexError(self, argindex) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): """ Returns the next term in the Taylor series expansion """ from sympy.functions.combinatorial.numbers import bernoulli if n == 0: return 1/sympify(x) elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) B = bernoulli(n + 1) F = factorial(n + 1) return 2 * (1 - 2**n) * B/F * x**n def _eval_rewrite_as_cosh(self, arg, **kwargs): return S.ImaginaryUnit / cosh(arg + S.ImaginaryUnit * S.Pi / 2) def _eval_is_positive(self): if self.args[0].is_extended_real: return self.args[0].is_positive def _eval_is_negative(self): if self.args[0].is_extended_real: return self.args[0].is_negative class sech(ReciprocalHyperbolicFunction): r""" sech(x) is the hyperbolic secant of x. The hyperbolic secant function is $\frac{2}{e^x + e^{-x}}$ Examples ======== >>> from sympy import sech >>> from sympy.abc import x >>> sech(x) sech(x) See Also ======== sinh, cosh, tanh, coth, csch, asinh, acosh """ _reciprocal_of = cosh _is_even = True def fdiff(self, argindex=1): if argindex == 1: return - tanh(self.args[0])*sech(self.args[0]) else: raise ArgumentIndexError(self, argindex) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): from sympy.functions.combinatorial.numbers import euler if n < 0 or n % 2 == 1: return S.Zero else: x = sympify(x) return euler(n) / factorial(n) * x**(n) def _eval_rewrite_as_sinh(self, arg, **kwargs): return S.ImaginaryUnit / sinh(arg + S.ImaginaryUnit * S.Pi /2) def _eval_is_positive(self): if self.args[0].is_extended_real: return True ############################################################################### ############################# HYPERBOLIC INVERSES ############################# ############################################################################### class InverseHyperbolicFunction(Function): """Base class for inverse hyperbolic functions.""" pass class asinh(InverseHyperbolicFunction): """ asinh(x) is the inverse hyperbolic sine of x. The inverse hyperbolic sine function. Examples ======== >>> from sympy import asinh >>> from sympy.abc import x >>> asinh(x).diff(x) 1/sqrt(x**2 + 1) >>> asinh(1) log(1 + sqrt(2)) See Also ======== acosh, atanh, sinh """ def fdiff(self, argindex=1): if argindex == 1: return 1/sqrt(self.args[0]**2 + 1) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): from sympy.functions.elementary.trigonometric import asin arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.NegativeInfinity elif arg.is_zero: return S.Zero elif arg is S.One: return log(sqrt(2) + 1) elif arg is S.NegativeOne: return log(sqrt(2) - 1) elif arg.is_negative: return -cls(-arg) else: if arg is S.ComplexInfinity: return S.ComplexInfinity if arg.is_zero: return S.Zero i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: return S.ImaginaryUnit * asin(i_coeff) else: if arg.could_extract_minus_sign(): return -cls(-arg) if isinstance(arg, sinh) and arg.args[0].is_number: z = arg.args[0] if z.is_real: return z r, i = match_real_imag(z) if r is not None and i is not None: f = floor((i + pi/2)/pi) m = z - I*pi*f even = f.is_even if even is True: return m elif even is False: return -m @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) if len(previous_terms) >= 2 and n > 2: p = previous_terms[-2] return -p * (n - 2)**2/(n*(n - 1)) * x**2 else: k = (n - 1) // 2 R = RisingFactorial(S.Half, k) F = factorial(k) return S.NegativeOne**k * R / F * x**n / n def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.series.order import Order arg = self.args[0].as_leading_term(x) if x in arg.free_symbols and Order(1, x).contains(arg): return arg else: return self.func(arg) def _eval_rewrite_as_log(self, x, **kwargs): return log(x + sqrt(x**2 + 1)) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return sinh def _eval_is_zero(self): return self.args[0].is_zero class acosh(InverseHyperbolicFunction): """ acosh(x) is the inverse hyperbolic cosine of x. The inverse hyperbolic cosine function. Examples ======== >>> from sympy import acosh >>> from sympy.abc import x >>> acosh(x).diff(x) 1/sqrt(x**2 - 1) >>> acosh(1) 0 See Also ======== asinh, atanh, cosh """ def fdiff(self, argindex=1): if argindex == 1: return 1/sqrt(self.args[0]**2 - 1) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.Infinity elif arg.is_zero: return S.Pi*S.ImaginaryUnit / 2 elif arg is S.One: return S.Zero elif arg is S.NegativeOne: return S.Pi*S.ImaginaryUnit if arg.is_number: cst_table = { S.ImaginaryUnit: log(S.ImaginaryUnit*(1 + sqrt(2))), -S.ImaginaryUnit: log(-S.ImaginaryUnit*(1 + sqrt(2))), S.Half: S.Pi/3, Rational(-1, 2): S.Pi*Rational(2, 3), sqrt(2)/2: S.Pi/4, -sqrt(2)/2: S.Pi*Rational(3, 4), 1/sqrt(2): S.Pi/4, -1/sqrt(2): S.Pi*Rational(3, 4), sqrt(3)/2: S.Pi/6, -sqrt(3)/2: S.Pi*Rational(5, 6), (sqrt(3) - 1)/sqrt(2**3): S.Pi*Rational(5, 12), -(sqrt(3) - 1)/sqrt(2**3): S.Pi*Rational(7, 12), sqrt(2 + sqrt(2))/2: S.Pi/8, -sqrt(2 + sqrt(2))/2: S.Pi*Rational(7, 8), sqrt(2 - sqrt(2))/2: S.Pi*Rational(3, 8), -sqrt(2 - sqrt(2))/2: S.Pi*Rational(5, 8), (1 + sqrt(3))/(2*sqrt(2)): S.Pi/12, -(1 + sqrt(3))/(2*sqrt(2)): S.Pi*Rational(11, 12), (sqrt(5) + 1)/4: S.Pi/5, -(sqrt(5) + 1)/4: S.Pi*Rational(4, 5) } if arg in cst_table: if arg.is_extended_real: return cst_table[arg]*S.ImaginaryUnit return cst_table[arg] if arg is S.ComplexInfinity: return S.ComplexInfinity if arg == S.ImaginaryUnit*S.Infinity: return S.Infinity + S.ImaginaryUnit*S.Pi/2 if arg == -S.ImaginaryUnit*S.Infinity: return S.Infinity - S.ImaginaryUnit*S.Pi/2 if arg.is_zero: return S.Pi*S.ImaginaryUnit*S.Half if isinstance(arg, cosh) and arg.args[0].is_number: z = arg.args[0] if z.is_real: from sympy.functions.elementary.complexes import Abs return Abs(z) r, i = match_real_imag(z) if r is not None and i is not None: f = floor(i/pi) m = z - I*pi*f even = f.is_even if even is True: if r.is_nonnegative: return m elif r.is_negative: return -m elif even is False: m -= I*pi if r.is_nonpositive: return -m elif r.is_positive: return m @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return S.Pi*S.ImaginaryUnit / 2 elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) if len(previous_terms) >= 2 and n > 2: p = previous_terms[-2] return p * (n - 2)**2/(n*(n - 1)) * x**2 else: k = (n - 1) // 2 R = RisingFactorial(S.Half, k) F = factorial(k) return -R / F * S.ImaginaryUnit * x**n / n def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.series.order import Order arg = self.args[0].as_leading_term(x) if x in arg.free_symbols and Order(1, x).contains(arg): return S.ImaginaryUnit*S.Pi/2 else: return self.func(arg) def _eval_rewrite_as_log(self, x, **kwargs): return log(x + sqrt(x + 1) * sqrt(x - 1)) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return cosh def _eval_is_zero(self): if (self.args[0] - 1).is_zero: return True class atanh(InverseHyperbolicFunction): """ atanh(x) is the inverse hyperbolic tangent of x. The inverse hyperbolic tangent function. Examples ======== >>> from sympy import atanh >>> from sympy.abc import x >>> atanh(x).diff(x) 1/(1 - x**2) See Also ======== asinh, acosh, tanh """ def fdiff(self, argindex=1): if argindex == 1: return 1/(1 - self.args[0]**2) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): from sympy.functions.elementary.trigonometric import atan arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg.is_zero: return S.Zero elif arg is S.One: return S.Infinity elif arg is S.NegativeOne: return S.NegativeInfinity elif arg is S.Infinity: return -S.ImaginaryUnit * atan(arg) elif arg is S.NegativeInfinity: return S.ImaginaryUnit * atan(-arg) elif arg.is_negative: return -cls(-arg) else: if arg is S.ComplexInfinity: from sympy.calculus.accumulationbounds import AccumBounds return S.ImaginaryUnit*AccumBounds(-S.Pi/2, S.Pi/2) i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: return S.ImaginaryUnit * atan(i_coeff) else: if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_zero: return S.Zero if isinstance(arg, tanh) and arg.args[0].is_number: z = arg.args[0] if z.is_real: return z r, i = match_real_imag(z) if r is not None and i is not None: f = floor(2*i/pi) even = f.is_even m = z - I*f*pi/2 if even is True: return m elif even is False: return m - I*pi/2 @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) return x**n / n def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.series.order import Order arg = self.args[0].as_leading_term(x) if x in arg.free_symbols and Order(1, x).contains(arg): return arg else: return self.func(arg) def _eval_rewrite_as_log(self, x, **kwargs): return (log(1 + x) - log(1 - x)) / 2 def _eval_is_zero(self): if self.args[0].is_zero: return True def _eval_is_imaginary(self): return self.args[0].is_imaginary def inverse(self, argindex=1): """ Returns the inverse of this function. """ return tanh class acoth(InverseHyperbolicFunction): """ acoth(x) is the inverse hyperbolic cotangent of x. The inverse hyperbolic cotangent function. Examples ======== >>> from sympy import acoth >>> from sympy.abc import x >>> acoth(x).diff(x) 1/(1 - x**2) See Also ======== asinh, acosh, coth """ def fdiff(self, argindex=1): if argindex == 1: return 1/(1 - self.args[0]**2) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): from sympy.functions.elementary.trigonometric import acot arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Zero elif arg is S.NegativeInfinity: return S.Zero elif arg.is_zero: return S.Pi*S.ImaginaryUnit / 2 elif arg is S.One: return S.Infinity elif arg is S.NegativeOne: return S.NegativeInfinity elif arg.is_negative: return -cls(-arg) else: if arg is S.ComplexInfinity: return S.Zero i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: return -S.ImaginaryUnit * acot(i_coeff) else: if arg.could_extract_minus_sign(): return -cls(-arg) if arg.is_zero: return S.Pi*S.ImaginaryUnit*S.Half @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return S.Pi*S.ImaginaryUnit / 2 elif n < 0 or n % 2 == 0: return S.Zero else: x = sympify(x) return x**n / n def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.series.order import Order arg = self.args[0].as_leading_term(x) if x in arg.free_symbols and Order(1, x).contains(arg): return S.ImaginaryUnit*S.Pi/2 else: return self.func(arg) def _eval_rewrite_as_log(self, x, **kwargs): return (log(1 + 1/x) - log(1 - 1/x)) / 2 def inverse(self, argindex=1): """ Returns the inverse of this function. """ return coth class asech(InverseHyperbolicFunction): """ asech(x) is the inverse hyperbolic secant of x. The inverse hyperbolic secant function. Examples ======== >>> from sympy import asech, sqrt, S >>> from sympy.abc import x >>> asech(x).diff(x) -1/(x*sqrt(1 - x**2)) >>> asech(1).diff(x) 0 >>> asech(1) 0 >>> asech(S(2)) I*pi/3 >>> asech(-sqrt(2)) 3*I*pi/4 >>> asech((sqrt(6) - sqrt(2))) I*pi/12 See Also ======== asinh, atanh, cosh, acoth References ========== .. [1] https://en.wikipedia.org/wiki/Hyperbolic_function .. [2] http://dlmf.nist.gov/4.37 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcSech/ """ def fdiff(self, argindex=1): if argindex == 1: z = self.args[0] return -1/(z*sqrt(1 - z**2)) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Pi*S.ImaginaryUnit / 2 elif arg is S.NegativeInfinity: return S.Pi*S.ImaginaryUnit / 2 elif arg.is_zero: return S.Infinity elif arg is S.One: return S.Zero elif arg is S.NegativeOne: return S.Pi*S.ImaginaryUnit if arg.is_number: cst_table = { S.ImaginaryUnit: - (S.Pi*S.ImaginaryUnit / 2) + log(1 + sqrt(2)), -S.ImaginaryUnit: (S.Pi*S.ImaginaryUnit / 2) + log(1 + sqrt(2)), (sqrt(6) - sqrt(2)): S.Pi / 12, (sqrt(2) - sqrt(6)): 11*S.Pi / 12, sqrt(2 - 2/sqrt(5)): S.Pi / 10, -sqrt(2 - 2/sqrt(5)): 9*S.Pi / 10, 2 / sqrt(2 + sqrt(2)): S.Pi / 8, -2 / sqrt(2 + sqrt(2)): 7*S.Pi / 8, 2 / sqrt(3): S.Pi / 6, -2 / sqrt(3): 5*S.Pi / 6, (sqrt(5) - 1): S.Pi / 5, (1 - sqrt(5)): 4*S.Pi / 5, sqrt(2): S.Pi / 4, -sqrt(2): 3*S.Pi / 4, sqrt(2 + 2/sqrt(5)): 3*S.Pi / 10, -sqrt(2 + 2/sqrt(5)): 7*S.Pi / 10, S(2): S.Pi / 3, -S(2): 2*S.Pi / 3, sqrt(2*(2 + sqrt(2))): 3*S.Pi / 8, -sqrt(2*(2 + sqrt(2))): 5*S.Pi / 8, (1 + sqrt(5)): 2*S.Pi / 5, (-1 - sqrt(5)): 3*S.Pi / 5, (sqrt(6) + sqrt(2)): 5*S.Pi / 12, (-sqrt(6) - sqrt(2)): 7*S.Pi / 12, } if arg in cst_table: if arg.is_extended_real: return cst_table[arg]*S.ImaginaryUnit return cst_table[arg] if arg is S.ComplexInfinity: from sympy.calculus.accumulationbounds import AccumBounds return S.ImaginaryUnit*AccumBounds(-S.Pi/2, S.Pi/2) if arg.is_zero: return S.Infinity @staticmethod @cacheit def expansion_term(n, x, *previous_terms): if n == 0: return log(2 / x) elif n < 0 or n % 2 == 1: return S.Zero else: x = sympify(x) if len(previous_terms) > 2 and n > 2: p = previous_terms[-2] return p * (n - 1)**2 // (n // 2)**2 * x**2 / 4 else: k = n // 2 R = RisingFactorial(S.Half, k) * n F = factorial(k) * n // 2 * n // 2 return -1 * R / F * x**n / 4 def inverse(self, argindex=1): """ Returns the inverse of this function. """ return sech def _eval_rewrite_as_log(self, arg, **kwargs): return log(1/arg + sqrt(1/arg - 1) * sqrt(1/arg + 1)) class acsch(InverseHyperbolicFunction): """ acsch(x) is the inverse hyperbolic cosecant of x. The inverse hyperbolic cosecant function. Examples ======== >>> from sympy import acsch, sqrt, S >>> from sympy.abc import x >>> acsch(x).diff(x) -1/(x**2*sqrt(1 + x**(-2))) >>> acsch(1).diff(x) 0 >>> acsch(1) log(1 + sqrt(2)) >>> acsch(S.ImaginaryUnit) -I*pi/2 >>> acsch(-2*S.ImaginaryUnit) I*pi/6 >>> acsch(S.ImaginaryUnit*(sqrt(6) - sqrt(2))) -5*I*pi/12 See Also ======== asinh References ========== .. [1] https://en.wikipedia.org/wiki/Hyperbolic_function .. [2] http://dlmf.nist.gov/4.37 .. [3] http://functions.wolfram.com/ElementaryFunctions/ArcCsch/ """ def fdiff(self, argindex=1): if argindex == 1: z = self.args[0] return -1/(z**2*sqrt(1 + 1/z**2)) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Zero elif arg is S.NegativeInfinity: return S.Zero elif arg.is_zero: return S.ComplexInfinity elif arg is S.One: return log(1 + sqrt(2)) elif arg is S.NegativeOne: return - log(1 + sqrt(2)) if arg.is_number: cst_table = { S.ImaginaryUnit: -S.Pi / 2, S.ImaginaryUnit*(sqrt(2) + sqrt(6)): -S.Pi / 12, S.ImaginaryUnit*(1 + sqrt(5)): -S.Pi / 10, S.ImaginaryUnit*2 / sqrt(2 - sqrt(2)): -S.Pi / 8, S.ImaginaryUnit*2: -S.Pi / 6, S.ImaginaryUnit*sqrt(2 + 2/sqrt(5)): -S.Pi / 5, S.ImaginaryUnit*sqrt(2): -S.Pi / 4, S.ImaginaryUnit*(sqrt(5)-1): -3*S.Pi / 10, S.ImaginaryUnit*2 / sqrt(3): -S.Pi / 3, S.ImaginaryUnit*2 / sqrt(2 + sqrt(2)): -3*S.Pi / 8, S.ImaginaryUnit*sqrt(2 - 2/sqrt(5)): -2*S.Pi / 5, S.ImaginaryUnit*(sqrt(6) - sqrt(2)): -5*S.Pi / 12, S(2): -S.ImaginaryUnit*log((1+sqrt(5))/2), } if arg in cst_table: return cst_table[arg]*S.ImaginaryUnit if arg is S.ComplexInfinity: return S.Zero if arg.is_zero: return S.ComplexInfinity if arg.could_extract_minus_sign(): return -cls(-arg) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return csch def _eval_rewrite_as_log(self, arg, **kwargs): return log(1/arg + sqrt(1/arg**2 + 1)) def _eval_is_zero(self): return self.args[0].is_infinite
fa71512340dea1400cfdc32ca5ade6e70c5de71f971389e9f38b5a49ec12b933
from sympy.core import Add, S, sympify, Dummy, expand_func from sympy.core.expr import Expr from sympy.core.function import Function, ArgumentIndexError, PoleError from sympy.core.logic import fuzzy_and, fuzzy_not from sympy.core.numbers import Rational, pi, oo, I from sympy.core.power import Pow from sympy.functions.special.zeta_functions import zeta from sympy.functions.special.error_functions import erf, erfc, Ei from sympy.functions.elementary.complexes import re, unpolarify from sympy.functions.elementary.exponential import exp, log from sympy.functions.elementary.integers import ceiling, floor from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import sin, cos, cot from sympy.functions.combinatorial.numbers import bernoulli, harmonic from sympy.functions.combinatorial.factorials import factorial, rf, RisingFactorial from sympy.utilities.misc import as_int from mpmath import mp, workprec from mpmath.libmp.libmpf import prec_to_dps def intlike(n): try: as_int(n, strict=False) return True except ValueError: return False ############################################################################### ############################ COMPLETE GAMMA FUNCTION ########################## ############################################################################### class gamma(Function): r""" The gamma function .. math:: \Gamma(x) := \int^{\infty}_{0} t^{x-1} e^{-t} \mathrm{d}t. Explanation =========== The ``gamma`` function implements the function which passes through the values of the factorial function (i.e., $\Gamma(n) = (n - 1)!$ when n is an integer). More generally, $\Gamma(z)$ is defined in the whole complex plane except at the negative integers where there are simple poles. Examples ======== >>> from sympy import S, I, pi, gamma >>> from sympy.abc import x Several special values are known: >>> gamma(1) 1 >>> gamma(4) 6 >>> gamma(S(3)/2) sqrt(pi)/2 The ``gamma`` function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(gamma(x)) gamma(conjugate(x)) Differentiation with respect to $x$ is supported: >>> from sympy import diff >>> diff(gamma(x), x) gamma(x)*polygamma(0, x) Series expansion is also supported: >>> from sympy import series >>> series(gamma(x), x, 0, 3) 1/x - EulerGamma + x*(EulerGamma**2/2 + pi**2/12) + x**2*(-EulerGamma*pi**2/12 + polygamma(2, 1)/6 - EulerGamma**3/6) + O(x**3) We can numerically evaluate the ``gamma`` function to arbitrary precision on the whole complex plane: >>> gamma(pi).evalf(40) 2.288037795340032417959588909060233922890 >>> gamma(1+I).evalf(20) 0.49801566811835604271 - 0.15494982830181068512*I See Also ======== lowergamma: Lower incomplete gamma function. uppergamma: Upper incomplete gamma function. polygamma: Polygamma function. loggamma: Log Gamma function. digamma: Digamma function. trigamma: Trigamma function. beta: Euler Beta function. References ========== .. [1] https://en.wikipedia.org/wiki/Gamma_function .. [2] http://dlmf.nist.gov/5 .. [3] http://mathworld.wolfram.com/GammaFunction.html .. [4] http://functions.wolfram.com/GammaBetaErf/Gamma/ """ unbranched = True _singularities = (S.ComplexInfinity,) def fdiff(self, argindex=1): if argindex == 1: return self.func(self.args[0])*polygamma(0, self.args[0]) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity elif intlike(arg): if arg.is_positive: return factorial(arg - 1) else: return S.ComplexInfinity elif arg.is_Rational: if arg.q == 2: n = abs(arg.p) // arg.q if arg.is_positive: k, coeff = n, S.One else: n = k = n + 1 if n & 1 == 0: coeff = S.One else: coeff = S.NegativeOne for i in range(3, 2*k, 2): coeff *= i if arg.is_positive: return coeff*sqrt(S.Pi) / 2**n else: return 2**n*sqrt(S.Pi) / coeff def _eval_expand_func(self, **hints): arg = self.args[0] if arg.is_Rational: if abs(arg.p) > arg.q: x = Dummy('x') n = arg.p // arg.q p = arg.p - n*arg.q return self.func(x + n)._eval_expand_func().subs(x, Rational(p, arg.q)) if arg.is_Add: coeff, tail = arg.as_coeff_add() if coeff and coeff.q != 1: intpart = floor(coeff) tail = (coeff - intpart,) + tail coeff = intpart tail = arg._new_rawargs(*tail, reeval=False) return self.func(tail)*RisingFactorial(tail, coeff) return self.func(*self.args) def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def _eval_is_real(self): x = self.args[0] if x.is_nonpositive and x.is_integer: return False if intlike(x) and x <= 0: return False if x.is_positive or x.is_noninteger: return True def _eval_is_positive(self): x = self.args[0] if x.is_positive: return True elif x.is_noninteger: return floor(x).is_even def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs): return exp(loggamma(z)) def _eval_rewrite_as_factorial(self, z, **kwargs): return factorial(z - 1) def _eval_nseries(self, x, n, logx, cdir=0): x0 = self.args[0].limit(x, 0) if not (x0.is_Integer and x0 <= 0): return super()._eval_nseries(x, n, logx) t = self.args[0] - x0 return (self.func(t + 1)/rf(self.args[0], -x0 + 1))._eval_nseries(x, n, logx) def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0] x0 = arg.subs(x, 0) if x0.is_integer and x0.is_nonpositive: n = -x0 res = S.NegativeOne**n/self.func(n + 1) return res/(arg + n).as_leading_term(x) elif not x0.is_infinite: return self.func(x0) raise PoleError() ############################################################################### ################## LOWER and UPPER INCOMPLETE GAMMA FUNCTIONS ################# ############################################################################### class lowergamma(Function): r""" The lower incomplete gamma function. Explanation =========== It can be defined as the meromorphic continuation of .. math:: \gamma(s, x) := \int_0^x t^{s-1} e^{-t} \mathrm{d}t = \Gamma(s) - \Gamma(s, x). This can be shown to be the same as .. math:: \gamma(s, x) = \frac{x^s}{s} {}_1F_1\left({s \atop s+1} \middle| -x\right), where ${}_1F_1$ is the (confluent) hypergeometric function. Examples ======== >>> from sympy import lowergamma, S >>> from sympy.abc import s, x >>> lowergamma(s, x) lowergamma(s, x) >>> lowergamma(3, x) -2*(x**2/2 + x + 1)*exp(-x) + 2 >>> lowergamma(-S(1)/2, x) -2*sqrt(pi)*erf(sqrt(x)) - 2*exp(-x)/sqrt(x) See Also ======== gamma: Gamma function. uppergamma: Upper incomplete gamma function. polygamma: Polygamma function. loggamma: Log Gamma function. digamma: Digamma function. trigamma: Trigamma function. beta: Euler Beta function. References ========== .. [1] https://en.wikipedia.org/wiki/Incomplete_gamma_function#Lower_incomplete_Gamma_function .. [2] Abramowitz, Milton; Stegun, Irene A., eds. (1965), Chapter 6, Section 5, Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables .. [3] http://dlmf.nist.gov/8 .. [4] http://functions.wolfram.com/GammaBetaErf/Gamma2/ .. [5] http://functions.wolfram.com/GammaBetaErf/Gamma3/ """ def fdiff(self, argindex=2): from sympy.functions.special.hyper import meijerg if argindex == 2: a, z = self.args return exp(-unpolarify(z))*z**(a - 1) elif argindex == 1: a, z = self.args return gamma(a)*digamma(a) - log(z)*uppergamma(a, z) \ - meijerg([], [1, 1], [0, 0, a], [], z) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, a, x): # For lack of a better place, we use this one to extract branching # information. The following can be # found in the literature (c/f references given above), albeit scattered: # 1) For fixed x != 0, lowergamma(s, x) is an entire function of s # 2) For fixed positive integers s, lowergamma(s, x) is an entire # function of x. # 3) For fixed non-positive integers s, # lowergamma(s, exp(I*2*pi*n)*x) = # 2*pi*I*n*(-1)**(-s)/factorial(-s) + lowergamma(s, x) # (this follows from lowergamma(s, x).diff(x) = x**(s-1)*exp(-x)). # 4) For fixed non-integral s, # lowergamma(s, x) = x**s*gamma(s)*lowergamma_unbranched(s, x), # where lowergamma_unbranched(s, x) is an entire function (in fact # of both s and x), i.e. # lowergamma(s, exp(2*I*pi*n)*x) = exp(2*pi*I*n*a)*lowergamma(a, x) if x is S.Zero: return S.Zero nx, n = x.extract_branch_factor() if a.is_integer and a.is_positive: nx = unpolarify(x) if nx != x: return lowergamma(a, nx) elif a.is_integer and a.is_nonpositive: if n != 0: return 2*pi*I*n*S.NegativeOne**(-a)/factorial(-a) + lowergamma(a, nx) elif n != 0: return exp(2*pi*I*n*a)*lowergamma(a, nx) # Special values. if a.is_Number: if a is S.One: return S.One - exp(-x) elif a is S.Half: return sqrt(pi)*erf(sqrt(x)) elif a.is_Integer or (2*a).is_Integer: b = a - 1 if b.is_positive: if a.is_integer: return factorial(b) - exp(-x) * factorial(b) * Add(*[x ** k / factorial(k) for k in range(a)]) else: 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)])) if not a.is_Integer: 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)]) if x.is_zero: return S.Zero def _eval_evalf(self, prec): if all(x.is_number for x in self.args): a = self.args[0]._to_mpmath(prec) z = self.args[1]._to_mpmath(prec) with workprec(prec): res = mp.gammainc(a, 0, z) return Expr._from_mpmath(res, prec) else: return self def _eval_conjugate(self): x = self.args[1] if x not in (S.Zero, S.NegativeInfinity): return self.func(self.args[0].conjugate(), x.conjugate()) def _eval_is_meromorphic(self, x, a): # By https://en.wikipedia.org/wiki/Incomplete_gamma_function#Holomorphic_extension, # lowergamma(s, z) = z**s*gamma(s)*gammastar(s, z), # where gammastar(s, z) is holomorphic for all s and z. # Hence the singularities of lowergamma are z = 0 (branch # point) and nonpositive integer values of s (poles of gamma(s)). s, z = self.args args_merom = fuzzy_and([z._eval_is_meromorphic(x, a), s._eval_is_meromorphic(x, a)]) if not args_merom: return args_merom z0 = z.subs(x, a) if s.is_integer: return fuzzy_and([s.is_positive, z0.is_finite]) s0 = s.subs(x, a) return fuzzy_and([s0.is_finite, z0.is_finite, fuzzy_not(z0.is_zero)]) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import O s, z = self.args if args0[0] is S.Infinity and not z.has(x): coeff = z**s*exp(-z) sum_expr = sum(z**k/rf(s, k + 1) for k in range(n - 1)) o = O(z**s*s**(-n)) return coeff*sum_expr + o return super()._eval_aseries(n, args0, x, logx) def _eval_rewrite_as_uppergamma(self, s, x, **kwargs): return gamma(s) - uppergamma(s, x) def _eval_rewrite_as_expint(self, s, x, **kwargs): from sympy.functions.special.error_functions import expint if s.is_integer and s.is_nonpositive: return self return self.rewrite(uppergamma).rewrite(expint) def _eval_is_zero(self): x = self.args[1] if x.is_zero: return True class uppergamma(Function): r""" The upper incomplete gamma function. Explanation =========== It can be defined as the meromorphic continuation of .. math:: \Gamma(s, x) := \int_x^\infty t^{s-1} e^{-t} \mathrm{d}t = \Gamma(s) - \gamma(s, x). where $\gamma(s, x)$ is the lower incomplete gamma function, :class:`lowergamma`. This can be shown to be the same as .. math:: \Gamma(s, x) = \Gamma(s) - \frac{x^s}{s} {}_1F_1\left({s \atop s+1} \middle| -x\right), where ${}_1F_1$ is the (confluent) hypergeometric function. The upper incomplete gamma function is also essentially equivalent to the generalized exponential integral: .. math:: \operatorname{E}_{n}(x) = \int_{1}^{\infty}{\frac{e^{-xt}}{t^n} \, dt} = x^{n-1}\Gamma(1-n,x). Examples ======== >>> from sympy import uppergamma, S >>> from sympy.abc import s, x >>> uppergamma(s, x) uppergamma(s, x) >>> uppergamma(3, x) 2*(x**2/2 + x + 1)*exp(-x) >>> uppergamma(-S(1)/2, x) -2*sqrt(pi)*erfc(sqrt(x)) + 2*exp(-x)/sqrt(x) >>> uppergamma(-2, x) expint(3, x)/x**2 See Also ======== gamma: Gamma function. lowergamma: Lower incomplete gamma function. polygamma: Polygamma function. loggamma: Log Gamma function. digamma: Digamma function. trigamma: Trigamma function. beta: Euler Beta function. References ========== .. [1] https://en.wikipedia.org/wiki/Incomplete_gamma_function#Upper_incomplete_Gamma_function .. [2] Abramowitz, Milton; Stegun, Irene A., eds. (1965), Chapter 6, Section 5, Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables .. [3] http://dlmf.nist.gov/8 .. [4] http://functions.wolfram.com/GammaBetaErf/Gamma2/ .. [5] http://functions.wolfram.com/GammaBetaErf/Gamma3/ .. [6] https://en.wikipedia.org/wiki/Exponential_integral#Relation_with_other_functions """ def fdiff(self, argindex=2): from sympy.functions.special.hyper import meijerg if argindex == 2: a, z = self.args return -exp(-unpolarify(z))*z**(a - 1) elif argindex == 1: a, z = self.args return uppergamma(a, z)*log(z) + meijerg([], [1, 1], [0, 0, a], [], z) else: raise ArgumentIndexError(self, argindex) def _eval_evalf(self, prec): if all(x.is_number for x in self.args): a = self.args[0]._to_mpmath(prec) z = self.args[1]._to_mpmath(prec) with workprec(prec): res = mp.gammainc(a, z, mp.inf) return Expr._from_mpmath(res, prec) return self @classmethod def eval(cls, a, z): from sympy.functions.special.error_functions import expint if z.is_Number: if z is S.NaN: return S.NaN elif z is S.Infinity: return S.Zero elif z.is_zero: if re(a).is_positive: return gamma(a) # We extract branching information here. C/f lowergamma. nx, n = z.extract_branch_factor() if a.is_integer and a.is_positive: nx = unpolarify(z) if z != nx: return uppergamma(a, nx) elif a.is_integer and a.is_nonpositive: if n != 0: return -2*pi*I*n*S.NegativeOne**(-a)/factorial(-a) + uppergamma(a, nx) elif n != 0: return gamma(a)*(1 - exp(2*pi*I*n*a)) + exp(2*pi*I*n*a)*uppergamma(a, nx) # Special values. if a.is_Number: if a is S.Zero and z.is_positive: return -Ei(-z) elif a is S.One: return exp(-z) elif a is S.Half: return sqrt(pi)*erfc(sqrt(z)) elif a.is_Integer or (2*a).is_Integer: b = a - 1 if b.is_positive: if a.is_integer: return exp(-z) * factorial(b) * Add(*[z**k / factorial(k) for k in range(a)]) else: return (gamma(a) * erfc(sqrt(z)) + S.NegativeOne**(a - S(3)/2) * exp(-z) * sqrt(z) * Add(*[gamma(-S.Half - k) * (-z)**k / gamma(1-a) for k in range(a - S.Half)])) elif b.is_Integer: return expint(-b, z)*unpolarify(z)**(b + 1) if not a.is_Integer: return (S.NegativeOne**(S.Half - a) * pi*erfc(sqrt(z))/gamma(1-a) - z**a * exp(-z) * Add(*[z**k * gamma(a) / gamma(a+k+1) for k in range(S.Half - a)])) if a.is_zero and z.is_positive: return -Ei(-z) if z.is_zero and re(a).is_positive: return gamma(a) def _eval_conjugate(self): z = self.args[1] if z not in (S.Zero, S.NegativeInfinity): return self.func(self.args[0].conjugate(), z.conjugate()) def _eval_is_meromorphic(self, x, a): return lowergamma._eval_is_meromorphic(self, x, a) def _eval_rewrite_as_lowergamma(self, s, x, **kwargs): return gamma(s) - lowergamma(s, x) def _eval_rewrite_as_tractable(self, s, x, **kwargs): return exp(loggamma(s)) - lowergamma(s, x) def _eval_rewrite_as_expint(self, s, x, **kwargs): from sympy.functions.special.error_functions import expint return expint(1 - s, x)*x**s ############################################################################### ###################### POLYGAMMA and LOGGAMMA FUNCTIONS ####################### ############################################################################### class polygamma(Function): r""" The function ``polygamma(n, z)`` returns ``log(gamma(z)).diff(n + 1)``. Explanation =========== It is a meromorphic function on $\mathbb{C}$ and defined as the $(n+1)$-th derivative of the logarithm of the gamma function: .. math:: \psi^{(n)} (z) := \frac{\mathrm{d}^{n+1}}{\mathrm{d} z^{n+1}} \log\Gamma(z). Examples ======== Several special values are known: >>> from sympy import S, polygamma >>> polygamma(0, 1) -EulerGamma >>> polygamma(0, 1/S(2)) -2*log(2) - EulerGamma >>> polygamma(0, 1/S(3)) -log(3) - sqrt(3)*pi/6 - EulerGamma - log(sqrt(3)) >>> polygamma(0, 1/S(4)) -pi/2 - log(4) - log(2) - EulerGamma >>> polygamma(0, 2) 1 - EulerGamma >>> polygamma(0, 23) 19093197/5173168 - EulerGamma >>> from sympy import oo, I >>> polygamma(0, oo) oo >>> polygamma(0, -oo) oo >>> polygamma(0, I*oo) oo >>> polygamma(0, -I*oo) oo Differentiation with respect to $x$ is supported: >>> from sympy import Symbol, diff >>> x = Symbol("x") >>> diff(polygamma(0, x), x) polygamma(1, x) >>> diff(polygamma(0, x), x, 2) polygamma(2, x) >>> diff(polygamma(0, x), x, 3) polygamma(3, x) >>> diff(polygamma(1, x), x) polygamma(2, x) >>> diff(polygamma(1, x), x, 2) polygamma(3, x) >>> diff(polygamma(2, x), x) polygamma(3, x) >>> diff(polygamma(2, x), x, 2) polygamma(4, x) >>> n = Symbol("n") >>> diff(polygamma(n, x), x) polygamma(n + 1, x) >>> diff(polygamma(n, x), x, 2) polygamma(n + 2, x) We can rewrite ``polygamma`` functions in terms of harmonic numbers: >>> from sympy import harmonic >>> polygamma(0, x).rewrite(harmonic) harmonic(x - 1) - EulerGamma >>> polygamma(2, x).rewrite(harmonic) 2*harmonic(x - 1, 3) - 2*zeta(3) >>> ni = Symbol("n", integer=True) >>> polygamma(ni, x).rewrite(harmonic) (-1)**(n + 1)*(-harmonic(x - 1, n + 1) + zeta(n + 1))*factorial(n) See Also ======== gamma: Gamma function. lowergamma: Lower incomplete gamma function. uppergamma: Upper incomplete gamma function. loggamma: Log Gamma function. digamma: Digamma function. trigamma: Trigamma function. beta: Euler Beta function. References ========== .. [1] https://en.wikipedia.org/wiki/Polygamma_function .. [2] http://mathworld.wolfram.com/PolygammaFunction.html .. [3] http://functions.wolfram.com/GammaBetaErf/PolyGamma/ .. [4] http://functions.wolfram.com/GammaBetaErf/PolyGamma2/ """ def _eval_evalf(self, prec): n = self.args[0] # the mpmath polygamma implementation valid only for nonnegative integers if n.is_number and n.is_real: if (n.is_integer or n == int(n)) and n.is_nonnegative: return super()._eval_evalf(prec) def fdiff(self, argindex=2): if argindex == 2: n, z = self.args[:2] return polygamma(n + 1, z) else: raise ArgumentIndexError(self, argindex) def _eval_is_real(self): if self.args[0].is_positive and self.args[1].is_positive: return True def _eval_is_complex(self): z = self.args[1] is_negative_integer = fuzzy_and([z.is_negative, z.is_integer]) return fuzzy_and([z.is_complex, fuzzy_not(is_negative_integer)]) def _eval_is_positive(self): if self.args[0].is_positive and self.args[1].is_positive: return self.args[0].is_odd def _eval_is_negative(self): if self.args[0].is_positive and self.args[1].is_positive: return self.args[0].is_even def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order if args0[1] != oo or not \ (self.args[0].is_Integer and self.args[0].is_nonnegative): return super()._eval_aseries(n, args0, x, logx) z = self.args[1] N = self.args[0] if N == 0: # digamma function series # Abramowitz & Stegun, p. 259, 6.3.18 r = log(z) - 1/(2*z) o = None if n < 2: o = Order(1/z, x) else: m = ceiling((n + 1)//2) l = [bernoulli(2*k) / (2*k*z**(2*k)) for k in range(1, m)] r -= Add(*l) o = Order(1/z**n, x) return r._eval_nseries(x, n, logx) + o else: # proper polygamma function # Abramowitz & Stegun, p. 260, 6.4.10 # We return terms to order higher than O(x**n) on purpose # -- otherwise we would not be able to return any terms for # quite a long time! fac = gamma(N) e0 = fac + N*fac/(2*z) m = ceiling((n + 1)//2) for k in range(1, m): fac = fac*(2*k + N - 1)*(2*k + N - 2) / ((2*k)*(2*k - 1)) e0 += bernoulli(2*k)*fac/z**(2*k) o = Order(1/z**(2*m), x) if n == 0: o = Order(1/z, x) elif n == 1: o = Order(1/z**2, x) r = e0._eval_nseries(z, n, logx) + o return (-1 * (-1/z)**N * r)._eval_nseries(x, n, logx) @classmethod def eval(cls, n, z): n, z = map(sympify, (n, z)) if n.is_integer: if n.is_nonnegative: nz = unpolarify(z) if z != nz: return polygamma(n, nz) if n.is_positive: if z is S.Half: return S.NegativeOne**(n + 1)*factorial(n)*(2**(n + 1) - 1)*zeta(n + 1) if n is S.NegativeOne: return loggamma(z) else: if z.is_Number: if z is S.NaN: return S.NaN elif z is S.Infinity: if n.is_Number: if n.is_zero: return S.Infinity else: return S.Zero if n.is_zero: return S.Infinity elif z.is_Integer: if z.is_nonpositive: return S.ComplexInfinity else: if n.is_zero: return harmonic(z - 1, 1) - S.EulerGamma elif n.is_odd: return S.NegativeOne**(n + 1)*factorial(n)*zeta(n + 1, z) if n.is_zero: if z is S.NaN: return S.NaN elif z.is_Rational: p, q = z.as_numer_denom() # only expand for small denominators to avoid creating long expressions if q <= 5: return expand_func(polygamma(S.Zero, z, evaluate=False)) elif z in (S.Infinity, S.NegativeInfinity): return S.Infinity else: t = z.extract_multiplicatively(S.ImaginaryUnit) if t in (S.Infinity, S.NegativeInfinity): return S.Infinity # TODO n == 1 also can do some rational z def _eval_expand_func(self, **hints): n, z = self.args if n.is_Integer and n.is_nonnegative: if z.is_Add: coeff = z.args[0] if coeff.is_Integer: e = -(n + 1) if coeff > 0: tail = Add(*[Pow( z - i, e) for i in range(1, int(coeff) + 1)]) else: tail = -Add(*[Pow( z + i, e) for i in range(0, int(-coeff))]) return polygamma(n, z - coeff) + S.NegativeOne**n*factorial(n)*tail elif z.is_Mul: coeff, z = z.as_two_terms() if coeff.is_Integer and coeff.is_positive: tail = [ polygamma(n, z + Rational( i, coeff)) for i in range(0, int(coeff)) ] if n == 0: return Add(*tail)/coeff + log(coeff) else: return Add(*tail)/coeff**(n + 1) z *= coeff if n == 0 and z.is_Rational: p, q = z.as_numer_denom() # Reference: # Values of the polygamma functions at rational arguments, J. Choi, 2007 part_1 = -S.EulerGamma - pi * cot(p * pi / q) / 2 - log(q) + Add( *[cos(2 * k * pi * p / q) * log(2 * sin(k * pi / q)) for k in range(1, q)]) if z > 0: n = floor(z) z0 = z - n return part_1 + Add(*[1 / (z0 + k) for k in range(n)]) elif z < 0: n = floor(1 - z) z0 = z + n return part_1 - Add(*[1 / (z0 - 1 - k) for k in range(n)]) return polygamma(n, z) def _eval_rewrite_as_zeta(self, n, z, **kwargs): if n.is_integer: if (n - S.One).is_nonnegative: return S.NegativeOne**(n + 1)*factorial(n)*zeta(n + 1, z) def _eval_rewrite_as_harmonic(self, n, z, **kwargs): if n.is_integer: if n.is_zero: return harmonic(z - 1) - S.EulerGamma else: return S.NegativeOne**(n+1) * factorial(n) * (zeta(n+1) - harmonic(z-1, n+1)) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.series.order import Order n, z = [a.as_leading_term(x) for a in self.args] o = Order(z, x) if n == 0 and o.contains(1/x): return o.getn() * log(x) else: return self.func(n, z) class loggamma(Function): r""" The ``loggamma`` function implements the logarithm of the gamma function (i.e., $\log\Gamma(x)$). Examples ======== Several special values are known. For numerical integral arguments we have: >>> from sympy import loggamma >>> loggamma(-2) oo >>> loggamma(0) oo >>> loggamma(1) 0 >>> loggamma(2) 0 >>> loggamma(3) log(2) And for symbolic values: >>> from sympy import Symbol >>> n = Symbol("n", integer=True, positive=True) >>> loggamma(n) log(gamma(n)) >>> loggamma(-n) oo For half-integral values: >>> from sympy import S >>> loggamma(S(5)/2) log(3*sqrt(pi)/4) >>> loggamma(n/2) log(2**(1 - n)*sqrt(pi)*gamma(n)/gamma(n/2 + 1/2)) And general rational arguments: >>> from sympy import expand_func >>> L = loggamma(S(16)/3) >>> expand_func(L).doit() -5*log(3) + loggamma(1/3) + log(4) + log(7) + log(10) + log(13) >>> L = loggamma(S(19)/4) >>> expand_func(L).doit() -4*log(4) + loggamma(3/4) + log(3) + log(7) + log(11) + log(15) >>> L = loggamma(S(23)/7) >>> expand_func(L).doit() -3*log(7) + log(2) + loggamma(2/7) + log(9) + log(16) The ``loggamma`` function has the following limits towards infinity: >>> from sympy import oo >>> loggamma(oo) oo >>> loggamma(-oo) zoo The ``loggamma`` function obeys the mirror symmetry if $x \in \mathbb{C} \setminus \{-\infty, 0\}$: >>> from sympy.abc import x >>> from sympy import conjugate >>> conjugate(loggamma(x)) loggamma(conjugate(x)) Differentiation with respect to $x$ is supported: >>> from sympy import diff >>> diff(loggamma(x), x) polygamma(0, x) Series expansion is also supported: >>> from sympy import series >>> series(loggamma(x), x, 0, 4).cancel() -log(x) - EulerGamma*x + pi**2*x**2/12 + x**3*polygamma(2, 1)/6 + O(x**4) We can numerically evaluate the ``gamma`` function to arbitrary precision on the whole complex plane: >>> from sympy import I >>> loggamma(5).evalf(30) 3.17805383034794561964694160130 >>> loggamma(I).evalf(20) -0.65092319930185633889 - 1.8724366472624298171*I See Also ======== gamma: Gamma function. lowergamma: Lower incomplete gamma function. uppergamma: Upper incomplete gamma function. polygamma: Polygamma function. digamma: Digamma function. trigamma: Trigamma function. beta: Euler Beta function. References ========== .. [1] https://en.wikipedia.org/wiki/Gamma_function .. [2] http://dlmf.nist.gov/5 .. [3] http://mathworld.wolfram.com/LogGammaFunction.html .. [4] http://functions.wolfram.com/GammaBetaErf/LogGamma/ """ @classmethod def eval(cls, z): z = sympify(z) if z.is_integer: if z.is_nonpositive: return S.Infinity elif z.is_positive: return log(gamma(z)) elif z.is_rational: p, q = z.as_numer_denom() # Half-integral values: if p.is_positive and q == 2: return log(sqrt(S.Pi) * 2**(1 - p) * gamma(p) / gamma((p + 1)*S.Half)) if z is S.Infinity: return S.Infinity elif abs(z) is S.Infinity: return S.ComplexInfinity if z is S.NaN: return S.NaN def _eval_expand_func(self, **hints): from sympy.concrete.summations import Sum z = self.args[0] if z.is_Rational: p, q = z.as_numer_denom() # General rational arguments (u + p/q) # Split z as n + p/q with p < q n = p // q p = p - n*q if p.is_positive and q.is_positive and p < q: k = Dummy("k") if n.is_positive: return loggamma(p / q) - n*log(q) + Sum(log((k - 1)*q + p), (k, 1, n)) elif n.is_negative: return loggamma(p / q) - n*log(q) + S.Pi*S.ImaginaryUnit*n - Sum(log(k*q - p), (k, 1, -n)) elif n.is_zero: return loggamma(p / q) return self def _eval_nseries(self, x, n, logx=None, cdir=0): x0 = self.args[0].limit(x, 0) if x0.is_zero: f = self._eval_rewrite_as_intractable(*self.args) return f._eval_nseries(x, n, logx) return super()._eval_nseries(x, n, logx) def _eval_aseries(self, n, args0, x, logx): from sympy.series.order import Order if args0[0] != oo: return super()._eval_aseries(n, args0, x, logx) z = self.args[0] r = log(z)*(z - S.Half) - z + log(2*pi)/2 l = [bernoulli(2*k) / (2*k*(2*k - 1)*z**(2*k - 1)) for k in range(1, n)] o = None if n == 0: o = Order(1, x) else: o = Order(1/z**n, x) # It is very inefficient to first add the order and then do the nseries return (r + Add(*l))._eval_nseries(x, n, logx) + o def _eval_rewrite_as_intractable(self, z, **kwargs): return log(gamma(z)) def _eval_is_real(self): z = self.args[0] if z.is_positive: return True elif z.is_nonpositive: return False def _eval_conjugate(self): z = self.args[0] if z not in (S.Zero, S.NegativeInfinity): return self.func(z.conjugate()) def fdiff(self, argindex=1): if argindex == 1: return polygamma(0, self.args[0]) else: raise ArgumentIndexError(self, argindex) class digamma(Function): r""" The ``digamma`` function is the first derivative of the ``loggamma`` function .. math:: \psi(x) := \frac{\mathrm{d}}{\mathrm{d} z} \log\Gamma(z) = \frac{\Gamma'(z)}{\Gamma(z) }. In this case, ``digamma(z) = polygamma(0, z)``. Examples ======== >>> from sympy import digamma >>> digamma(0) zoo >>> from sympy import Symbol >>> z = Symbol('z') >>> digamma(z) polygamma(0, z) To retain ``digamma`` as it is: >>> digamma(0, evaluate=False) digamma(0) >>> digamma(z, evaluate=False) digamma(z) See Also ======== gamma: Gamma function. lowergamma: Lower incomplete gamma function. uppergamma: Upper incomplete gamma function. polygamma: Polygamma function. loggamma: Log Gamma function. trigamma: Trigamma function. beta: Euler Beta function. References ========== .. [1] https://en.wikipedia.org/wiki/Digamma_function .. [2] http://mathworld.wolfram.com/DigammaFunction.html .. [3] http://functions.wolfram.com/GammaBetaErf/PolyGamma2/ """ def _eval_evalf(self, prec): z = self.args[0] nprec = prec_to_dps(prec) return polygamma(0, z).evalf(n=nprec) def fdiff(self, argindex=1): z = self.args[0] return polygamma(0, z).fdiff() def _eval_is_real(self): z = self.args[0] return polygamma(0, z).is_real def _eval_is_positive(self): z = self.args[0] return polygamma(0, z).is_positive def _eval_is_negative(self): z = self.args[0] return polygamma(0, z).is_negative def _eval_aseries(self, n, args0, x, logx): as_polygamma = self.rewrite(polygamma) args0 = [S.Zero,] + args0 return as_polygamma._eval_aseries(n, args0, x, logx) @classmethod def eval(cls, z): return polygamma(0, z) def _eval_expand_func(self, **hints): z = self.args[0] return polygamma(0, z).expand(func=True) def _eval_rewrite_as_harmonic(self, z, **kwargs): return harmonic(z - 1) - S.EulerGamma def _eval_rewrite_as_polygamma(self, z, **kwargs): return polygamma(0, z) def _eval_as_leading_term(self, x, logx=None, cdir=0): z = self.args[0] return polygamma(0, z).as_leading_term(x) class trigamma(Function): r""" The ``trigamma`` function is the second derivative of the ``loggamma`` function .. math:: \psi^{(1)}(z) := \frac{\mathrm{d}^{2}}{\mathrm{d} z^{2}} \log\Gamma(z). In this case, ``trigamma(z) = polygamma(1, z)``. Examples ======== >>> from sympy import trigamma >>> trigamma(0) zoo >>> from sympy import Symbol >>> z = Symbol('z') >>> trigamma(z) polygamma(1, z) To retain ``trigamma`` as it is: >>> trigamma(0, evaluate=False) trigamma(0) >>> trigamma(z, evaluate=False) trigamma(z) See Also ======== gamma: Gamma function. lowergamma: Lower incomplete gamma function. uppergamma: Upper incomplete gamma function. polygamma: Polygamma function. loggamma: Log Gamma function. digamma: Digamma function. beta: Euler Beta function. References ========== .. [1] https://en.wikipedia.org/wiki/Trigamma_function .. [2] http://mathworld.wolfram.com/TrigammaFunction.html .. [3] http://functions.wolfram.com/GammaBetaErf/PolyGamma2/ """ def _eval_evalf(self, prec): z = self.args[0] nprec = prec_to_dps(prec) return polygamma(1, z).evalf(n=nprec) def fdiff(self, argindex=1): z = self.args[0] return polygamma(1, z).fdiff() def _eval_is_real(self): z = self.args[0] return polygamma(1, z).is_real def _eval_is_positive(self): z = self.args[0] return polygamma(1, z).is_positive def _eval_is_negative(self): z = self.args[0] return polygamma(1, z).is_negative def _eval_aseries(self, n, args0, x, logx): as_polygamma = self.rewrite(polygamma) args0 = [S.One,] + args0 return as_polygamma._eval_aseries(n, args0, x, logx) @classmethod def eval(cls, z): return polygamma(1, z) def _eval_expand_func(self, **hints): z = self.args[0] return polygamma(1, z).expand(func=True) def _eval_rewrite_as_zeta(self, z, **kwargs): return zeta(2, z) def _eval_rewrite_as_polygamma(self, z, **kwargs): return polygamma(1, z) def _eval_rewrite_as_harmonic(self, z, **kwargs): return -harmonic(z - 1, 2) + S.Pi**2 / 6 def _eval_as_leading_term(self, x, logx=None, cdir=0): z = self.args[0] return polygamma(1, z).as_leading_term(x) ############################################################################### ##################### COMPLETE MULTIVARIATE GAMMA FUNCTION #################### ############################################################################### class multigamma(Function): r""" The multivariate gamma function is a generalization of the gamma function .. math:: \Gamma_p(z) = \pi^{p(p-1)/4}\prod_{k=1}^p \Gamma[z + (1 - k)/2]. In a special case, ``multigamma(x, 1) = gamma(x)``. Examples ======== >>> from sympy import S, multigamma >>> from sympy import Symbol >>> x = Symbol('x') >>> p = Symbol('p', positive=True, integer=True) >>> multigamma(x, p) pi**(p*(p - 1)/4)*Product(gamma(-_k/2 + x + 1/2), (_k, 1, p)) Several special values are known: >>> multigamma(1, 1) 1 >>> multigamma(4, 1) 6 >>> multigamma(S(3)/2, 1) sqrt(pi)/2 Writing ``multigamma`` in terms of the ``gamma`` function: >>> multigamma(x, 1) gamma(x) >>> multigamma(x, 2) sqrt(pi)*gamma(x)*gamma(x - 1/2) >>> multigamma(x, 3) pi**(3/2)*gamma(x)*gamma(x - 1)*gamma(x - 1/2) Parameters ========== p : order or dimension of the multivariate gamma function See Also ======== gamma, lowergamma, uppergamma, polygamma, loggamma, digamma, trigamma, beta References ========== .. [1] https://en.wikipedia.org/wiki/Multivariate_gamma_function """ unbranched = True def fdiff(self, argindex=2): from sympy.concrete.summations import Sum if argindex == 2: x, p = self.args k = Dummy("k") return self.func(x, p)*Sum(polygamma(0, x + (1 - k)/2), (k, 1, p)) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, x, p): from sympy.concrete.products import Product x, p = map(sympify, (x, p)) if p.is_positive is False or p.is_integer is False: raise ValueError('Order parameter p must be positive integer.') k = Dummy("k") return (pi**(p*(p - 1)/4)*Product(gamma(x + (1 - k)/2), (k, 1, p))).doit() def _eval_conjugate(self): x, p = self.args return self.func(x.conjugate(), p) def _eval_is_real(self): x, p = self.args y = 2*x if y.is_integer and (y <= (p - 1)) is True: return False if intlike(y) and (y <= (p - 1)): return False if y > (p - 1) or y.is_noninteger: return True
feec2a06297889b8eaa4dfafe2bd4e2facf274573fbd7b000376dc4ecfdca3e4
from sympy.core import S, Integer from sympy.core.function import Function from sympy.core.logic import fuzzy_not from sympy.core.mul import prod from sympy.core.relational import Ne from sympy.core.sorting import default_sort_key from sympy.external.gmpy import SYMPY_INTS from sympy.utilities.iterables import has_dups ############################################################################### ###################### Kronecker Delta, Levi-Civita etc. ###################### ############################################################################### def Eijk(*args, **kwargs): """ Represent the Levi-Civita symbol. This is a compatibility wrapper to ``LeviCivita()``. See Also ======== LeviCivita """ return LeviCivita(*args, **kwargs) def eval_levicivita(*args): """Evaluate Levi-Civita symbol.""" from sympy.functions.combinatorial.factorials import factorial n = len(args) return prod( prod(args[j] - args[i] for j in range(i + 1, n)) / factorial(i) for i in range(n)) # converting factorial(i) to int is slightly faster class LeviCivita(Function): """ Represent the Levi-Civita symbol. Explanation =========== For even permutations of indices it returns 1, for odd permutations -1, and for everything else (a repeated index) it returns 0. Thus it represents an alternating pseudotensor. Examples ======== >>> from sympy import LeviCivita >>> from sympy.abc import i, j, k >>> LeviCivita(1, 2, 3) 1 >>> LeviCivita(1, 3, 2) -1 >>> LeviCivita(1, 2, 2) 0 >>> LeviCivita(i, j, k) LeviCivita(i, j, k) >>> LeviCivita(i, j, i) 0 See Also ======== Eijk """ is_integer = True @classmethod def eval(cls, *args): if all(isinstance(a, (SYMPY_INTS, Integer)) for a in args): return eval_levicivita(*args) if has_dups(args): return S.Zero def doit(self): return eval_levicivita(*self.args) class KroneckerDelta(Function): """ The discrete, or Kronecker, delta function. Explanation =========== A function that takes in two integers $i$ and $j$. It returns $0$ if $i$ and $j$ are not equal, or it returns $1$ if $i$ and $j$ are equal. Examples ======== An example with integer indices: >>> from sympy import KroneckerDelta >>> KroneckerDelta(1, 2) 0 >>> KroneckerDelta(3, 3) 1 Symbolic indices: >>> from sympy.abc import i, j, k >>> KroneckerDelta(i, j) KroneckerDelta(i, j) >>> KroneckerDelta(i, i) 1 >>> KroneckerDelta(i, i + 1) 0 >>> KroneckerDelta(i, i + 1 + k) KroneckerDelta(i, i + k + 1) Parameters ========== i : Number, Symbol The first index of the delta function. j : Number, Symbol The second index of the delta function. See Also ======== eval DiracDelta References ========== .. [1] https://en.wikipedia.org/wiki/Kronecker_delta """ is_integer = True @classmethod def eval(cls, i, j, delta_range=None): """ Evaluates the discrete delta function. Examples ======== >>> from sympy import KroneckerDelta >>> from sympy.abc import i, j, k >>> KroneckerDelta(i, j) KroneckerDelta(i, j) >>> KroneckerDelta(i, i) 1 >>> KroneckerDelta(i, i + 1) 0 >>> KroneckerDelta(i, i + 1 + k) KroneckerDelta(i, i + k + 1) # indirect doctest """ if delta_range is not None: dinf, dsup = delta_range if (dinf - i > 0) == True: return S.Zero if (dinf - j > 0) == True: return S.Zero if (dsup - i < 0) == True: return S.Zero if (dsup - j < 0) == True: return S.Zero diff = i - j if diff.is_zero: return S.One elif fuzzy_not(diff.is_zero): return S.Zero if i.assumptions0.get("below_fermi") and \ j.assumptions0.get("above_fermi"): return S.Zero if j.assumptions0.get("below_fermi") and \ i.assumptions0.get("above_fermi"): return S.Zero # to make KroneckerDelta canonical # following lines will check if inputs are in order # if not, will return KroneckerDelta with correct order if i != min(i, j, key=default_sort_key): if delta_range: return cls(j, i, delta_range) else: return cls(j, i) @property def delta_range(self): if len(self.args) > 2: return self.args[2] def _eval_power(self, expt): if expt.is_positive: return self if expt.is_negative and expt is not S.NegativeOne: return 1/self @property def is_above_fermi(self): """ True if Delta can be non-zero above fermi. Examples ======== >>> from sympy import KroneckerDelta, Symbol >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> q = Symbol('q') >>> KroneckerDelta(p, a).is_above_fermi True >>> KroneckerDelta(p, i).is_above_fermi False >>> KroneckerDelta(p, q).is_above_fermi True See Also ======== is_below_fermi, is_only_below_fermi, is_only_above_fermi """ if self.args[0].assumptions0.get("below_fermi"): return False if self.args[1].assumptions0.get("below_fermi"): return False return True @property def is_below_fermi(self): """ True if Delta can be non-zero below fermi. Examples ======== >>> from sympy import KroneckerDelta, Symbol >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> q = Symbol('q') >>> KroneckerDelta(p, a).is_below_fermi False >>> KroneckerDelta(p, i).is_below_fermi True >>> KroneckerDelta(p, q).is_below_fermi True See Also ======== is_above_fermi, is_only_above_fermi, is_only_below_fermi """ if self.args[0].assumptions0.get("above_fermi"): return False if self.args[1].assumptions0.get("above_fermi"): return False return True @property def is_only_above_fermi(self): """ True if Delta is restricted to above fermi. Examples ======== >>> from sympy import KroneckerDelta, Symbol >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> q = Symbol('q') >>> KroneckerDelta(p, a).is_only_above_fermi True >>> KroneckerDelta(p, q).is_only_above_fermi False >>> KroneckerDelta(p, i).is_only_above_fermi False See Also ======== is_above_fermi, is_below_fermi, is_only_below_fermi """ return ( self.args[0].assumptions0.get("above_fermi") or self.args[1].assumptions0.get("above_fermi") ) or False @property def is_only_below_fermi(self): """ True if Delta is restricted to below fermi. Examples ======== >>> from sympy import KroneckerDelta, Symbol >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> q = Symbol('q') >>> KroneckerDelta(p, i).is_only_below_fermi True >>> KroneckerDelta(p, q).is_only_below_fermi False >>> KroneckerDelta(p, a).is_only_below_fermi False See Also ======== is_above_fermi, is_below_fermi, is_only_above_fermi """ return ( self.args[0].assumptions0.get("below_fermi") or self.args[1].assumptions0.get("below_fermi") ) or False @property def indices_contain_equal_information(self): """ Returns True if indices are either both above or below fermi. Examples ======== >>> from sympy import KroneckerDelta, Symbol >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> q = Symbol('q') >>> KroneckerDelta(p, q).indices_contain_equal_information True >>> KroneckerDelta(p, q+1).indices_contain_equal_information True >>> KroneckerDelta(i, p).indices_contain_equal_information False """ if (self.args[0].assumptions0.get("below_fermi") and self.args[1].assumptions0.get("below_fermi")): return True if (self.args[0].assumptions0.get("above_fermi") and self.args[1].assumptions0.get("above_fermi")): return True # if both indices are general we are True, else false return self.is_below_fermi and self.is_above_fermi @property def preferred_index(self): """ Returns the index which is preferred to keep in the final expression. Explanation =========== The preferred index is the index with more information regarding fermi level. If indices contain the same information, 'a' is preferred before 'b'. Examples ======== >>> from sympy import KroneckerDelta, Symbol >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> j = Symbol('j', below_fermi=True) >>> p = Symbol('p') >>> KroneckerDelta(p, i).preferred_index i >>> KroneckerDelta(p, a).preferred_index a >>> KroneckerDelta(i, j).preferred_index i See Also ======== killable_index """ if self._get_preferred_index(): return self.args[1] else: return self.args[0] @property def killable_index(self): """ Returns the index which is preferred to substitute in the final expression. Explanation =========== The index to substitute is the index with less information regarding fermi level. If indices contain the same information, 'a' is preferred before 'b'. Examples ======== >>> from sympy import KroneckerDelta, Symbol >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> j = Symbol('j', below_fermi=True) >>> p = Symbol('p') >>> KroneckerDelta(p, i).killable_index p >>> KroneckerDelta(p, a).killable_index p >>> KroneckerDelta(i, j).killable_index j See Also ======== preferred_index """ if self._get_preferred_index(): return self.args[0] else: return self.args[1] def _get_preferred_index(self): """ Returns the index which is preferred to keep in the final expression. The preferred index is the index with more information regarding fermi level. If indices contain the same information, index 0 is returned. """ if not self.is_above_fermi: if self.args[0].assumptions0.get("below_fermi"): return 0 else: return 1 elif not self.is_below_fermi: if self.args[0].assumptions0.get("above_fermi"): return 0 else: return 1 else: return 0 @property def indices(self): return self.args[0:2] def _eval_rewrite_as_Piecewise(self, *args, **kwargs): from sympy.functions.elementary.piecewise import Piecewise i, j = args return Piecewise((0, Ne(i, j)), (1, True))
1ba24a0d556fa13367bf42ec0c9b1ef2f4079a98cc1cc20c539cd83b498035ca
import string from sympy.concrete.products import Product from sympy.concrete.summations import Sum from sympy.core.function import (diff, expand_func) from sympy.core import (EulerGamma, TribonacciConstant) from sympy.core.numbers import (I, Rational, oo, pi) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, symbols) from sympy.functions.combinatorial.numbers import carmichael from sympy.functions.elementary.complexes import (im, re) from sympy.functions.elementary.integers import floor from sympy.polys.polytools import cancel from sympy.series.limits import limit from sympy.functions import ( bernoulli, harmonic, bell, fibonacci, tribonacci, lucas, euler, catalan, genocchi, partition, motzkin, binomial, gamma, sqrt, cbrt, hyper, log, digamma, trigamma, polygamma, factorial, sin, cos, cot, zeta) from sympy.functions.combinatorial.numbers import _nT from sympy.core.expr import unchanged from sympy.core.numbers import GoldenRatio, Integer from sympy.testing.pytest import XFAIL, raises, nocache_fail from sympy.abc import x def test_carmichael(): assert carmichael.find_carmichael_numbers_in_range(0, 561) == [] assert carmichael.find_carmichael_numbers_in_range(561, 562) == [561] assert carmichael.find_carmichael_numbers_in_range(561, 1105) == carmichael.find_carmichael_numbers_in_range(561, 562) assert carmichael.find_first_n_carmichaels(5) == [561, 1105, 1729, 2465, 2821] assert carmichael.is_prime(2821) == False assert carmichael.is_prime(2465) == False assert carmichael.is_prime(1729) == False assert carmichael.is_prime(1105) == False assert carmichael.is_prime(561) == False raises(ValueError, lambda: carmichael.is_carmichael(-2)) raises(ValueError, lambda: carmichael.find_carmichael_numbers_in_range(-2, 2)) raises(ValueError, lambda: carmichael.find_carmichael_numbers_in_range(22, 2)) def test_bernoulli(): assert bernoulli(0) == 1 assert bernoulli(1) == Rational(-1, 2) assert bernoulli(2) == Rational(1, 6) assert bernoulli(3) == 0 assert bernoulli(4) == Rational(-1, 30) assert bernoulli(5) == 0 assert bernoulli(6) == Rational(1, 42) assert bernoulli(7) == 0 assert bernoulli(8) == Rational(-1, 30) assert bernoulli(10) == Rational(5, 66) assert bernoulli(1000001) == 0 assert bernoulli(0, x) == 1 assert bernoulli(1, x) == x - S.Half assert bernoulli(2, x) == x**2 - x + Rational(1, 6) assert bernoulli(3, x) == x**3 - (3*x**2)/2 + x/2 # Should be fast; computed with mpmath b = bernoulli(1000) assert b.p % 10**10 == 7950421099 assert b.q == 342999030 b = bernoulli(10**6, evaluate=False).evalf() assert str(b) == '-2.23799235765713e+4767529' # Issue #8527 l = Symbol('l', integer=True) m = Symbol('m', integer=True, nonnegative=True) n = Symbol('n', integer=True, positive=True) assert isinstance(bernoulli(2 * l + 1), bernoulli) assert isinstance(bernoulli(2 * m + 1), bernoulli) assert bernoulli(2 * n + 1) == 0 raises(ValueError, lambda: bernoulli(-2)) def test_fibonacci(): assert [fibonacci(n) for n in range(-3, 5)] == [2, -1, 1, 0, 1, 1, 2, 3] assert fibonacci(100) == 354224848179261915075 assert [lucas(n) for n in range(-3, 5)] == [-4, 3, -1, 2, 1, 3, 4, 7] assert lucas(100) == 792070839848372253127 assert fibonacci(1, x) == 1 assert fibonacci(2, x) == x assert fibonacci(3, x) == x**2 + 1 assert fibonacci(4, x) == x**3 + 2*x # issue #8800 n = Dummy('n') assert fibonacci(n).limit(n, S.Infinity) is S.Infinity assert lucas(n).limit(n, S.Infinity) is S.Infinity assert fibonacci(n).rewrite(sqrt) == \ 2**(-n)*sqrt(5)*((1 + sqrt(5))**n - (-sqrt(5) + 1)**n) / 5 assert fibonacci(n).rewrite(sqrt).subs(n, 10).expand() == fibonacci(10) assert fibonacci(n).rewrite(GoldenRatio).subs(n,10).evalf() == \ fibonacci(10) assert lucas(n).rewrite(sqrt) == \ (fibonacci(n-1).rewrite(sqrt) + fibonacci(n+1).rewrite(sqrt)).simplify() assert lucas(n).rewrite(sqrt).subs(n, 10).expand() == lucas(10) raises(ValueError, lambda: fibonacci(-3, x)) def test_tribonacci(): assert [tribonacci(n) for n in range(8)] == [0, 1, 1, 2, 4, 7, 13, 24] assert tribonacci(100) == 98079530178586034536500564 assert tribonacci(0, x) == 0 assert tribonacci(1, x) == 1 assert tribonacci(2, x) == x**2 assert tribonacci(3, x) == x**4 + x assert tribonacci(4, x) == x**6 + 2*x**3 + 1 assert tribonacci(5, x) == x**8 + 3*x**5 + 3*x**2 n = Dummy('n') assert tribonacci(n).limit(n, S.Infinity) is S.Infinity w = (-1 + S.ImaginaryUnit * sqrt(3)) / 2 a = (1 + cbrt(19 + 3*sqrt(33)) + cbrt(19 - 3*sqrt(33))) / 3 b = (1 + w*cbrt(19 + 3*sqrt(33)) + w**2*cbrt(19 - 3*sqrt(33))) / 3 c = (1 + w**2*cbrt(19 + 3*sqrt(33)) + w*cbrt(19 - 3*sqrt(33))) / 3 assert tribonacci(n).rewrite(sqrt) == \ (a**(n + 1)/((a - b)*(a - c)) + b**(n + 1)/((b - a)*(b - c)) + c**(n + 1)/((c - a)*(c - b))) assert tribonacci(n).rewrite(sqrt).subs(n, 4).simplify() == tribonacci(4) assert tribonacci(n).rewrite(GoldenRatio).subs(n,10).evalf() == \ tribonacci(10) assert tribonacci(n).rewrite(TribonacciConstant) == floor( 3*TribonacciConstant**n*(102*sqrt(33) + 586)**Rational(1, 3)/ (-2*(102*sqrt(33) + 586)**Rational(1, 3) + 4 + (102*sqrt(33) + 586)**Rational(2, 3)) + S.Half) raises(ValueError, lambda: tribonacci(-1, x)) @nocache_fail def test_bell(): assert [bell(n) for n in range(8)] == [1, 1, 2, 5, 15, 52, 203, 877] assert bell(0, x) == 1 assert bell(1, x) == x assert bell(2, x) == x**2 + x assert bell(5, x) == x**5 + 10*x**4 + 25*x**3 + 15*x**2 + x assert bell(oo) is S.Infinity raises(ValueError, lambda: bell(oo, x)) raises(ValueError, lambda: bell(-1)) raises(ValueError, lambda: bell(S.Half)) X = symbols('x:6') # X = (x0, x1, .. x5) # at the same time: X[1] = x1, X[2] = x2 for standard readablity. # but we must supply zero-based indexed object X[1:] = (x1, .. x5) assert bell(6, 2, X[1:]) == 6*X[5]*X[1] + 15*X[4]*X[2] + 10*X[3]**2 assert bell( 6, 3, X[1:]) == 15*X[4]*X[1]**2 + 60*X[3]*X[2]*X[1] + 15*X[2]**3 X = (1, 10, 100, 1000, 10000) assert bell(6, 2, X) == (6 + 15 + 10)*10000 X = (1, 2, 3, 3, 5) assert bell(6, 2, X) == 6*5 + 15*3*2 + 10*3**2 X = (1, 2, 3, 5) assert bell(6, 3, X) == 15*5 + 60*3*2 + 15*2**3 # Dobinski's formula n = Symbol('n', integer=True, nonnegative=True) # For large numbers, this is too slow # For nonintegers, there are significant precision errors for i in [0, 2, 3, 7, 13, 42, 55]: # Running without the cache this is either very slow or goes into an # infinite loop. assert bell(i).evalf() == bell(n).rewrite(Sum).evalf(subs={n: i}) m = Symbol("m") assert bell(m).rewrite(Sum) == bell(m) assert bell(n, m).rewrite(Sum) == bell(n, m) # issue 9184 n = Dummy('n') assert bell(n).limit(n, S.Infinity) is S.Infinity def test_harmonic(): n = Symbol("n") m = Symbol("m") assert harmonic(n, 0) == n assert harmonic(n).evalf() == harmonic(n) assert harmonic(n, 1) == harmonic(n) assert harmonic(1, n).evalf() == harmonic(1, n) assert harmonic(0, 1) == 0 assert harmonic(1, 1) == 1 assert harmonic(2, 1) == Rational(3, 2) assert harmonic(3, 1) == Rational(11, 6) assert harmonic(4, 1) == Rational(25, 12) assert harmonic(0, 2) == 0 assert harmonic(1, 2) == 1 assert harmonic(2, 2) == Rational(5, 4) assert harmonic(3, 2) == Rational(49, 36) assert harmonic(4, 2) == Rational(205, 144) assert harmonic(0, 3) == 0 assert harmonic(1, 3) == 1 assert harmonic(2, 3) == Rational(9, 8) assert harmonic(3, 3) == Rational(251, 216) assert harmonic(4, 3) == Rational(2035, 1728) assert harmonic(oo, -1) is S.NaN assert harmonic(oo, 0) is oo assert harmonic(oo, S.Half) is oo assert harmonic(oo, 1) is oo assert harmonic(oo, 2) == (pi**2)/6 assert harmonic(oo, 3) == zeta(3) assert harmonic(oo, Dummy(negative=True)) is S.NaN ip = Dummy(integer=True, positive=True) if (1/ip <= 1) is True: #---------------------------------+ assert None, 'delete this if-block and the next line' #| ip = Dummy(even=True, positive=True) #--------------------+ assert harmonic(oo, 1/ip) is oo assert harmonic(oo, 1 + ip) is zeta(1 + ip) assert harmonic(0, m) == 0 def test_harmonic_rational(): ne = S(6) no = S(5) pe = S(8) po = S(9) qe = S(10) qo = S(13) Heee = harmonic(ne + pe/qe) Aeee = (-log(10) + 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8))) + 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8))) + pi*sqrt(2*sqrt(5)/5 + 1)/2 + Rational(13944145, 4720968)) Heeo = harmonic(ne + pe/qo) 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)) + 2*log(sin(pi*Rational(5, 13)))*cos(pi*Rational(80, 13)) - 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(5, 13)) - 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)) + Rational(2422020029, 702257080)) Heoe = harmonic(ne + po/qe) Aeoe = (-log(20) + 2*(Rational(1, 4) + sqrt(5)/4)*log(Rational(-1, 4) + sqrt(5)/4) + 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8))) + 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8))) + 2*(-sqrt(5)/4 + Rational(1, 4))*log(Rational(1, 4) + sqrt(5)/4) + Rational(11818877030, 4286604231) + pi*sqrt(2*sqrt(5) + 5)/2) Heoo = harmonic(ne + po/qo) 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)) + 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(108, 13)) - 2*log(sin(pi*Rational(5, 13)))*cos(pi/13) - 2*log(sin(pi/13))*cos(pi*Rational(5, 13)) + pi*cot(pi*Rational(4, 13))/2 - 2*log(sin(pi*Rational(2, 13)))*cos(pi*Rational(3, 13)) + Rational(11669332571, 3628714320)) Hoee = harmonic(no + pe/qe) Aoee = (-log(10) + 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8))) + 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8))) + pi*sqrt(2*sqrt(5)/5 + 1)/2 + Rational(779405, 277704)) Hoeo = harmonic(no + pe/qo) 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)) + 2*log(sin(pi*Rational(5, 13)))*cos(pi*Rational(80, 13)) - 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(5, 13)) - 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)) + Rational(53857323, 16331560)) Hooe = harmonic(no + po/qe) Aooe = (-log(20) + 2*(Rational(1, 4) + sqrt(5)/4)*log(Rational(-1, 4) + sqrt(5)/4) + 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8))) + 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8))) + 2*(-sqrt(5)/4 + Rational(1, 4))*log(Rational(1, 4) + sqrt(5)/4) + Rational(486853480, 186374097) + pi*sqrt(2*sqrt(5) + 5)/2) Hooo = harmonic(no + po/qo) 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)) + 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(108, 13)) - 2*log(sin(pi*Rational(5, 13)))*cos(pi/13) - 2*log(sin(pi/13))*cos(pi*Rational(5, 13)) + pi*cot(pi*Rational(4, 13))/2 - 2*log(sin(pi*Rational(2, 13)))*cos(3*pi/13) + Rational(383693479, 125128080)) H = [Heee, Heeo, Heoe, Heoo, Hoee, Hoeo, Hooe, Hooo] A = [Aeee, Aeeo, Aeoe, Aeoo, Aoee, Aoeo, Aooe, Aooo] for h, a in zip(H, A): e = expand_func(h).doit() assert cancel(e/a) == 1 assert abs(h.n() - a.n()) < 1e-12 def test_harmonic_evalf(): assert str(harmonic(1.5).evalf(n=10)) == '1.280372306' assert str(harmonic(1.5, 2).evalf(n=10)) == '1.154576311' # issue 7443 def test_harmonic_rewrite(): n = Symbol("n") m = Symbol("m") assert harmonic(n).rewrite(digamma) == polygamma(0, n + 1) + EulerGamma assert harmonic(n).rewrite(trigamma) == polygamma(0, n + 1) + EulerGamma assert harmonic(n).rewrite(polygamma) == polygamma(0, n + 1) + EulerGamma assert harmonic(n,3).rewrite(polygamma) == polygamma(2, n + 1)/2 - polygamma(2, 1)/2 assert harmonic(n,m).rewrite(polygamma) == (-1)**m*(polygamma(m - 1, 1) - polygamma(m - 1, n + 1))/factorial(m - 1) assert expand_func(harmonic(n+4)) == harmonic(n) + 1/(n + 4) + 1/(n + 3) + 1/(n + 2) + 1/(n + 1) assert expand_func(harmonic(n-4)) == harmonic(n) - 1/(n - 1) - 1/(n - 2) - 1/(n - 3) - 1/n assert harmonic(n, m).rewrite("tractable") == harmonic(n, m).rewrite(polygamma) _k = Dummy("k") assert harmonic(n).rewrite(Sum).dummy_eq(Sum(1/_k, (_k, 1, n))) assert harmonic(n, m).rewrite(Sum).dummy_eq(Sum(_k**(-m), (_k, 1, n))) @XFAIL def test_harmonic_limit_fail(): n = Symbol("n") m = Symbol("m") # For m > 1: assert limit(harmonic(n, m), n, oo) == zeta(m) def test_euler(): assert euler(0) == 1 assert euler(1) == 0 assert euler(2) == -1 assert euler(3) == 0 assert euler(4) == 5 assert euler(6) == -61 assert euler(8) == 1385 assert euler(20, evaluate=False) != 370371188237525 n = Symbol('n', integer=True) assert euler(n) != -1 assert euler(n).subs(n, 2) == -1 raises(ValueError, lambda: euler(-2)) raises(ValueError, lambda: euler(-3)) raises(ValueError, lambda: euler(2.3)) assert euler(20).evalf() == 370371188237525.0 assert euler(20, evaluate=False).evalf() == 370371188237525.0 assert euler(n).rewrite(Sum) == euler(n) n = Symbol('n', integer=True, nonnegative=True) assert euler(2*n + 1).rewrite(Sum) == 0 _j = Dummy('j') _k = Dummy('k') assert euler(2*n).rewrite(Sum).dummy_eq( I*Sum((-1)**_j*2**(-_k)*I**(-_k)*(-2*_j + _k)**(2*n + 1)* binomial(_k, _j)/_k, (_j, 0, _k), (_k, 1, 2*n + 1))) def test_euler_odd(): n = Symbol('n', odd=True, positive=True) assert euler(n) == 0 n = Symbol('n', odd=True) assert euler(n) != 0 def test_euler_polynomials(): assert euler(0, x) == 1 assert euler(1, x) == x - S.Half assert euler(2, x) == x**2 - x assert euler(3, x) == x**3 - (3*x**2)/2 + Rational(1, 4) m = Symbol('m') assert isinstance(euler(m, x), euler) from sympy.core.numbers import Float A = Float('-0.46237208575048694923364757452876131e8') # from Maple B = euler(19, S.Pi.evalf(32)) assert abs((A - B)/A) < 1e-31 # expect low relative error C = euler(19, S.Pi, evaluate=False).evalf(32) assert abs((A - C)/A) < 1e-31 def test_euler_polynomial_rewrite(): m = Symbol('m') A = euler(m, x).rewrite('Sum'); assert A.subs({m:3, x:5}).doit() == euler(3, 5) def test_catalan(): n = Symbol('n', integer=True) m = Symbol('m', integer=True, positive=True) k = Symbol('k', integer=True, nonnegative=True) p = Symbol('p', nonnegative=True) catalans = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786] for i, c in enumerate(catalans): assert catalan(i) == c assert catalan(n).rewrite(factorial).subs(n, i) == c assert catalan(n).rewrite(Product).subs(n, i).doit() == c assert unchanged(catalan, x) assert catalan(2*x).rewrite(binomial) == binomial(4*x, 2*x)/(2*x + 1) assert catalan(S.Half).rewrite(gamma) == 8/(3*pi) assert catalan(S.Half).rewrite(factorial).rewrite(gamma) ==\ 8 / (3 * pi) assert catalan(3*x).rewrite(gamma) == 4**( 3*x)*gamma(3*x + S.Half)/(sqrt(pi)*gamma(3*x + 2)) assert catalan(x).rewrite(hyper) == hyper((-x + 1, -x), (2,), 1) assert catalan(n).rewrite(factorial) == factorial(2*n) / (factorial(n + 1) * factorial(n)) assert isinstance(catalan(n).rewrite(Product), catalan) assert isinstance(catalan(m).rewrite(Product), Product) assert diff(catalan(x), x) == (polygamma( 0, x + S.Half) - polygamma(0, x + 2) + log(4))*catalan(x) assert catalan(x).evalf() == catalan(x) c = catalan(S.Half).evalf() assert str(c) == '0.848826363156775' c = catalan(I).evalf(3) assert str((re(c), im(c))) == '(0.398, -0.0209)' # Assumptions assert catalan(p).is_positive is True assert catalan(k).is_integer is True assert catalan(m+3).is_composite is True def test_genocchi(): genocchis = [1, -1, 0, 1, 0, -3, 0, 17] for n, g in enumerate(genocchis): assert genocchi(n + 1) == g m = Symbol('m', integer=True) n = Symbol('n', integer=True, positive=True) assert unchanged(genocchi, m) assert genocchi(2*n + 1) == 0 assert genocchi(n).rewrite(bernoulli) == (1 - 2 ** n) * bernoulli(n) * 2 assert genocchi(2 * n).is_odd assert genocchi(2 * n).is_even is False assert genocchi(2 * n + 1).is_even assert genocchi(n).is_integer assert genocchi(4 * n).is_positive # these are the only 2 prime Genocchi numbers assert genocchi(6, evaluate=False).is_prime == S(-3).is_prime assert genocchi(8, evaluate=False).is_prime assert genocchi(4 * n + 2).is_negative assert genocchi(4 * n + 1).is_negative is False assert genocchi(4 * n - 2).is_negative raises(ValueError, lambda: genocchi(Rational(5, 4))) raises(ValueError, lambda: genocchi(-2)) @nocache_fail def test_partition(): partition_nums = [1, 1, 2, 3, 5, 7, 11, 15, 22] for n, p in enumerate(partition_nums): assert partition(n) == p x = Symbol('x') y = Symbol('y', real=True) m = Symbol('m', integer=True) n = Symbol('n', integer=True, negative=True) p = Symbol('p', integer=True, nonnegative=True) assert partition(m).is_integer assert not partition(m).is_negative assert partition(m).is_nonnegative assert partition(n).is_zero assert partition(p).is_positive assert partition(x).subs(x, 7) == 15 assert partition(y).subs(y, 8) == 22 raises(ValueError, lambda: partition(Rational(5, 4))) def test__nT(): assert [_nT(i, j) for i in range(5) for j in range(i + 2)] == [ 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 2, 1, 1, 0] check = [_nT(10, i) for i in range(11)] assert check == [0, 1, 5, 8, 9, 7, 5, 3, 2, 1, 1] assert all(type(i) is int for i in check) assert _nT(10, 5) == 7 assert _nT(100, 98) == 2 assert _nT(100, 100) == 1 assert _nT(10, 3) == 8 def test_nC_nP_nT(): from sympy.utilities.iterables import ( multiset_permutations, multiset_combinations, multiset_partitions, partitions, subsets, permutations) from sympy.functions.combinatorial.numbers import ( nP, nC, nT, stirling, _stirling1, _stirling2, _multiset_histogram, _AOP_product) from sympy.combinatorics.permutations import Permutation from sympy.core.random import choice c = string.ascii_lowercase for i in range(100): s = ''.join(choice(c) for i in range(7)) u = len(s) == len(set(s)) try: tot = 0 for i in range(8): check = nP(s, i) tot += check assert len(list(multiset_permutations(s, i))) == check if u: assert nP(len(s), i) == check assert nP(s) == tot except AssertionError: print(s, i, 'failed perm test') raise ValueError() for i in range(100): s = ''.join(choice(c) for i in range(7)) u = len(s) == len(set(s)) try: tot = 0 for i in range(8): check = nC(s, i) tot += check assert len(list(multiset_combinations(s, i))) == check if u: assert nC(len(s), i) == check assert nC(s) == tot if u: assert nC(len(s)) == tot except AssertionError: print(s, i, 'failed combo test') raise ValueError() for i in range(1, 10): tot = 0 for j in range(1, i + 2): check = nT(i, j) assert check.is_Integer tot += check assert sum(1 for p in partitions(i, j, size=True) if p[0] == j) == check assert nT(i) == tot for i in range(1, 10): tot = 0 for j in range(1, i + 2): check = nT(range(i), j) tot += check assert len(list(multiset_partitions(list(range(i)), j))) == check assert nT(range(i)) == tot for i in range(100): s = ''.join(choice(c) for i in range(7)) u = len(s) == len(set(s)) try: tot = 0 for i in range(1, 8): check = nT(s, i) tot += check assert len(list(multiset_partitions(s, i))) == check if u: assert nT(range(len(s)), i) == check if u: assert nT(range(len(s))) == tot assert nT(s) == tot except AssertionError: print(s, i, 'failed partition test') raise ValueError() # tests for Stirling numbers of the first kind that are not tested in the # above assert [stirling(9, i, kind=1) for i in range(11)] == [ 0, 40320, 109584, 118124, 67284, 22449, 4536, 546, 36, 1, 0] perms = list(permutations(range(4))) assert [sum(1 for p in perms if Permutation(p).cycles == i) for i in range(5)] == [0, 6, 11, 6, 1] == [ stirling(4, i, kind=1) for i in range(5)] # http://oeis.org/A008275 assert [stirling(n, k, signed=1) for n in range(10) for k in range(1, n + 1)] == [ 1, -1, 1, 2, -3, 1, -6, 11, -6, 1, 24, -50, 35, -10, 1, -120, 274, -225, 85, -15, 1, 720, -1764, 1624, -735, 175, -21, 1, -5040, 13068, -13132, 6769, -1960, 322, -28, 1, 40320, -109584, 118124, -67284, 22449, -4536, 546, -36, 1] # https://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind assert [stirling(n, k, kind=1) for n in range(10) for k in range(n+1)] == [ 1, 0, 1, 0, 1, 1, 0, 2, 3, 1, 0, 6, 11, 6, 1, 0, 24, 50, 35, 10, 1, 0, 120, 274, 225, 85, 15, 1, 0, 720, 1764, 1624, 735, 175, 21, 1, 0, 5040, 13068, 13132, 6769, 1960, 322, 28, 1, 0, 40320, 109584, 118124, 67284, 22449, 4536, 546, 36, 1] # https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind assert [stirling(n, k, kind=2) for n in range(10) for k in range(n+1)] == [ 1, 0, 1, 0, 1, 1, 0, 1, 3, 1, 0, 1, 7, 6, 1, 0, 1, 15, 25, 10, 1, 0, 1, 31, 90, 65, 15, 1, 0, 1, 63, 301, 350, 140, 21, 1, 0, 1, 127, 966, 1701, 1050, 266, 28, 1, 0, 1, 255, 3025, 7770, 6951, 2646, 462, 36, 1] assert stirling(3, 4, kind=1) == stirling(3, 4, kind=1) == 0 raises(ValueError, lambda: stirling(-2, 2)) # Assertion that the return type is SymPy Integer. assert isinstance(_stirling1(6, 3), Integer) assert isinstance(_stirling2(6, 3), Integer) def delta(p): if len(p) == 1: return oo return min(abs(i[0] - i[1]) for i in subsets(p, 2)) parts = multiset_partitions(range(5), 3) d = 2 assert (sum(1 for p in parts if all(delta(i) >= d for i in p)) == stirling(5, 3, d=d) == 7) # other coverage tests assert nC('abb', 2) == nC('aab', 2) == 2 assert nP(3, 3, replacement=True) == nP('aabc', 3, replacement=True) == 27 assert nP(3, 4) == 0 assert nP('aabc', 5) == 0 assert nC(4, 2, replacement=True) == nC('abcdd', 2, replacement=True) == \ len(list(multiset_combinations('aabbccdd', 2))) == 10 assert nC('abcdd') == sum(nC('abcdd', i) for i in range(6)) == 24 assert nC(list('abcdd'), 4) == 4 assert nT('aaaa') == nT(4) == len(list(partitions(4))) == 5 assert nT('aaab') == len(list(multiset_partitions('aaab'))) == 7 assert nC('aabb'*3, 3) == 4 # aaa, bbb, abb, baa assert dict(_AOP_product((4,1,1,1))) == { 0: 1, 1: 4, 2: 7, 3: 8, 4: 8, 5: 7, 6: 4, 7: 1} # the following was the first t that showed a problem in a previous form of # the function, so it's not as random as it may appear t = (3, 9, 4, 6, 6, 5, 5, 2, 10, 4) assert sum(_AOP_product(t)[i] for i in range(55)) == 58212000 raises(ValueError, lambda: _multiset_histogram({1:'a'})) def test_PR_14617(): from sympy.functions.combinatorial.numbers import nT for n in (0, []): for k in (-1, 0, 1): if k == 0: assert nT(n, k) == 1 else: assert nT(n, k) == 0 def test_issue_8496(): n = Symbol("n") k = Symbol("k") raises(TypeError, lambda: catalan(n, k)) def test_issue_8601(): n = Symbol('n', integer=True, negative=True) assert catalan(n - 1) is S.Zero assert catalan(Rational(-1, 2)) is S.ComplexInfinity assert catalan(-S.One) == Rational(-1, 2) c1 = catalan(-5.6).evalf() assert str(c1) == '6.93334070531408e-5' c2 = catalan(-35.4).evalf() assert str(c2) == '-4.14189164517449e-24' def test_motzkin(): assert motzkin.is_motzkin(4) == True assert motzkin.is_motzkin(9) == True assert motzkin.is_motzkin(10) == False assert motzkin.find_motzkin_numbers_in_range(10,200) == [21, 51, 127] assert motzkin.find_motzkin_numbers_in_range(10,400) == [21, 51, 127, 323] assert motzkin.find_motzkin_numbers_in_range(10,1600) == [21, 51, 127, 323, 835] assert motzkin.find_first_n_motzkins(5) == [1, 1, 2, 4, 9] assert motzkin.find_first_n_motzkins(7) == [1, 1, 2, 4, 9, 21, 51] assert motzkin.find_first_n_motzkins(10) == [1, 1, 2, 4, 9, 21, 51, 127, 323, 835] raises(ValueError, lambda: motzkin.eval(77.58)) raises(ValueError, lambda: motzkin.eval(-8)) raises(ValueError, lambda: motzkin.find_motzkin_numbers_in_range(-2,7)) raises(ValueError, lambda: motzkin.find_motzkin_numbers_in_range(13,7)) raises(ValueError, lambda: motzkin.find_first_n_motzkins(112.8)) def test_nD_derangements(): from sympy.utilities.iterables import (partitions, multiset, multiset_derangements, multiset_permutations) from sympy.functions.combinatorial.numbers import nD got = [] for i in partitions(8, k=4): s = [] it = 0 for k, v in i.items(): for i in range(v): s.extend([it]*k) it += 1 ms = multiset(s) c1 = sum(1 for i in multiset_permutations(s) if all(i != j for i, j in zip(i, s))) assert c1 == nD(ms) == nD(ms, 0) == nD(ms, 1) v = [tuple(i) for i in multiset_derangements(s)] c2 = len(v) assert c2 == len(set(v)) assert c1 == c2 got.append(c1) assert got == [1, 4, 6, 12, 24, 24, 61, 126, 315, 780, 297, 772, 2033, 5430, 14833] assert nD('1112233456', brute=True) == nD('1112233456') == 16356 assert nD('') == nD([]) == nD({}) == 0 assert nD({1: 0}) == 0 raises(ValueError, lambda: nD({1: -1})) assert nD('112') == 0 assert nD(i='112') == 0 assert [nD(n=i) for i in range(6)] == [0, 0, 1, 2, 9, 44] assert nD((i for i in range(4))) == nD('0123') == 9 assert nD(m=(i for i in range(4))) == 3 assert nD(m={0: 1, 1: 1, 2: 1, 3: 1}) == 3 assert nD(m=[0, 1, 2, 3]) == 3 raises(TypeError, lambda: nD(m=0)) raises(TypeError, lambda: nD(-1)) assert nD({-1: 1, -2: 1}) == 1 assert nD(m={0: 3}) == 0 raises(ValueError, lambda: nD(i='123', n=3)) raises(ValueError, lambda: nD(i='123', m=(1,2))) raises(ValueError, lambda: nD(n=0, m=(1,2))) raises(ValueError, lambda: nD({1: -1})) raises(ValueError, lambda: nD(m={-1: 1, 2: 1})) raises(ValueError, lambda: nD(m={1: -1, 2: 1})) raises(ValueError, lambda: nD(m=[-1, 2])) raises(TypeError, lambda: nD({1: x})) raises(TypeError, lambda: nD(m={1: x})) raises(TypeError, lambda: nD(m={x: 1}))
bd03ee37fbc9c417eeb8d1631e5e8534647b472e3daa8a932c22be6b7604d4ab
from sympy.assumptions.refine import refine from sympy.calculus.accumulationbounds import AccumBounds from sympy.concrete.products import Product from sympy.concrete.summations import Sum from sympy.core.function import expand_log from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi, zoo) from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import (adjoint, conjugate, re, sign, transpose) from sympy.functions.elementary.exponential import (LambertW, exp, exp_polar, log) from sympy.functions.elementary.hyperbolic import (cosh, sinh, tanh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.polys.polytools import gcd from sympy.series.order import O from sympy.simplify.simplify import simplify from sympy.core.parameters import global_parameters from sympy.functions.elementary.exponential import match_real_imag from sympy.abc import x, y, z from sympy.core.expr import unchanged from sympy.core.function import ArgumentIndexError from sympy.testing.pytest import raises, XFAIL, _both_exp_pow @_both_exp_pow def test_exp_values(): if global_parameters.exp_is_pow: assert type(exp(x)) is Pow else: assert type(exp(x)) is exp k = Symbol('k', integer=True) assert exp(nan) is nan assert exp(oo) is oo assert exp(-oo) == 0 assert exp(0) == 1 assert exp(1) == E assert exp(-1 + x).as_base_exp() == (S.Exp1, x - 1) assert exp(1 + x).as_base_exp() == (S.Exp1, x + 1) assert exp(pi*I/2) == I assert exp(pi*I) == -1 assert exp(pi*I*Rational(3, 2)) == -I assert exp(2*pi*I) == 1 assert refine(exp(pi*I*2*k)) == 1 assert refine(exp(pi*I*2*(k + S.Half))) == -1 assert refine(exp(pi*I*2*(k + Rational(1, 4)))) == I assert refine(exp(pi*I*2*(k + Rational(3, 4)))) == -I assert exp(log(x)) == x assert exp(2*log(x)) == x**2 assert exp(pi*log(x)) == x**pi assert exp(17*log(x) + E*log(y)) == x**17 * y**E assert exp(x*log(x)) != x**x assert exp(sin(x)*log(x)) != x assert exp(3*log(x) + oo*x) == exp(oo*x) * x**3 assert exp(4*log(x)*log(y) + 3*log(x)) == x**3 * exp(4*log(x)*log(y)) assert exp(-oo, evaluate=False).is_finite is True assert exp(oo, evaluate=False).is_finite is False @_both_exp_pow def test_exp_period(): assert exp(I*pi*Rational(9, 4)) == exp(I*pi/4) assert exp(I*pi*Rational(46, 18)) == exp(I*pi*Rational(5, 9)) assert exp(I*pi*Rational(25, 7)) == exp(I*pi*Rational(-3, 7)) assert exp(I*pi*Rational(-19, 3)) == exp(-I*pi/3) assert exp(I*pi*Rational(37, 8)) - exp(I*pi*Rational(-11, 8)) == 0 assert exp(I*pi*Rational(-5, 3)) / exp(I*pi*Rational(11, 5)) * exp(I*pi*Rational(148, 15)) == 1 assert exp(2 - I*pi*Rational(17, 5)) == exp(2 + I*pi*Rational(3, 5)) assert exp(log(3) + I*pi*Rational(29, 9)) == 3 * exp(I*pi*Rational(-7, 9)) n = Symbol('n', integer=True) e = Symbol('e', even=True) assert exp(e*I*pi) == 1 assert exp((e + 1)*I*pi) == -1 assert exp((1 + 4*n)*I*pi/2) == I assert exp((-1 + 4*n)*I*pi/2) == -I @_both_exp_pow def test_exp_log(): x = Symbol("x", real=True) assert log(exp(x)) == x assert exp(log(x)) == x if not global_parameters.exp_is_pow: assert log(x).inverse() == exp assert exp(x).inverse() == log y = Symbol("y", polar=True) assert log(exp_polar(z)) == z assert exp(log(y)) == y @_both_exp_pow def test_exp_expand(): e = exp(log(Rational(2))*(1 + x) - log(Rational(2))*x) assert e.expand() == 2 assert exp(x + y) != exp(x)*exp(y) assert exp(x + y).expand() == exp(x)*exp(y) @_both_exp_pow def test_exp__as_base_exp(): assert exp(x).as_base_exp() == (E, x) assert exp(2*x).as_base_exp() == (E, 2*x) assert exp(x*y).as_base_exp() == (E, x*y) assert exp(-x).as_base_exp() == (E, -x) # Pow( *expr.as_base_exp() ) == expr invariant should hold assert E**x == exp(x) assert E**(2*x) == exp(2*x) assert E**(x*y) == exp(x*y) assert exp(x).base is S.Exp1 assert exp(x).exp == x @_both_exp_pow def test_exp_infinity(): assert exp(I*y) != nan assert refine(exp(I*oo)) is nan assert refine(exp(-I*oo)) is nan assert exp(y*I*oo) != nan assert exp(zoo) is nan x = Symbol('x', extended_real=True, finite=False) assert exp(x).is_complex is None @_both_exp_pow def test_exp_subs(): x = Symbol('x') e = (exp(3*log(x), evaluate=False)) # evaluates to x**3 assert e.subs(x**3, y**3) == e assert e.subs(x**2, 5) == e assert (x**3).subs(x**2, y) != y**Rational(3, 2) assert exp(exp(x) + exp(x**2)).subs(exp(exp(x)), y) == y * exp(exp(x**2)) assert exp(x).subs(E, y) == y**x x = symbols('x', real=True) assert exp(5*x).subs(exp(7*x), y) == y**Rational(5, 7) assert exp(2*x + 7).subs(exp(3*x), y) == y**Rational(2, 3) * exp(7) x = symbols('x', positive=True) assert exp(3*log(x)).subs(x**2, y) == y**Rational(3, 2) # differentiate between E and exp assert exp(exp(x + E)).subs(exp, 3) == 3**(3**(x + E)) assert exp(exp(x + E)).subs(exp, sin) == sin(sin(x + E)) assert exp(exp(x + E)).subs(E, 3) == 3**(3**(x + 3)) assert exp(3).subs(E, sin) == sin(3) def test_exp_adjoint(): assert adjoint(exp(x)) == exp(adjoint(x)) def test_exp_conjugate(): assert conjugate(exp(x)) == exp(conjugate(x)) @_both_exp_pow def test_exp_transpose(): assert transpose(exp(x)) == exp(transpose(x)) @_both_exp_pow def test_exp_rewrite(): assert exp(x).rewrite(sin) == sinh(x) + cosh(x) assert exp(x*I).rewrite(cos) == cos(x) + I*sin(x) assert exp(1).rewrite(cos) == sinh(1) + cosh(1) assert exp(1).rewrite(sin) == sinh(1) + cosh(1) assert exp(1).rewrite(sin) == sinh(1) + cosh(1) assert exp(x).rewrite(tanh) == (1 + tanh(x/2))/(1 - tanh(x/2)) assert exp(pi*I/4).rewrite(sqrt) == sqrt(2)/2 + sqrt(2)*I/2 assert exp(pi*I/3).rewrite(sqrt) == S.Half + sqrt(3)*I/2 if not global_parameters.exp_is_pow: assert exp(x*log(y)).rewrite(Pow) == y**x assert exp(log(x)*log(y)).rewrite(Pow) in [x**log(y), y**log(x)] assert exp(log(log(x))*y).rewrite(Pow) == log(x)**y n = Symbol('n', integer=True) assert Sum((exp(pi*I/2)/2)**n, (n, 0, oo)).rewrite(sqrt).doit() == Rational(4, 5) + I*2/5 assert Sum((exp(pi*I/4)/2)**n, (n, 0, oo)).rewrite(sqrt).doit() == 1/(1 - sqrt(2)*(1 + I)/4) assert (Sum((exp(pi*I/3)/2)**n, (n, 0, oo)).rewrite(sqrt).doit().cancel() == 4*I/(sqrt(3) + 3*I)) @_both_exp_pow def test_exp_leading_term(): assert exp(x).as_leading_term(x) == 1 assert exp(2 + x).as_leading_term(x) == exp(2) assert exp((2*x + 3) / (x+1)).as_leading_term(x) == exp(3) # The following tests are commented, since now SymPy returns the # original function when the leading term in the series expansion does # not exist. # raises(NotImplementedError, lambda: exp(1/x).as_leading_term(x)) # raises(NotImplementedError, lambda: exp((x + 1) / x**2).as_leading_term(x)) # raises(NotImplementedError, lambda: exp(x + 1/x).as_leading_term(x)) @_both_exp_pow def test_exp_taylor_term(): x = symbols('x') assert exp(x).taylor_term(1, x) == x assert exp(x).taylor_term(3, x) == x**3/6 assert exp(x).taylor_term(4, x) == x**4/24 assert exp(x).taylor_term(-1, x) is S.Zero def test_exp_MatrixSymbol(): A = MatrixSymbol("A", 2, 2) assert exp(A).has(exp) def test_exp_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: exp(x).fdiff(2)) def test_log_values(): assert log(nan) is nan assert log(oo) is oo assert log(-oo) is oo assert log(zoo) is zoo assert log(-zoo) is zoo assert log(0) is zoo assert log(1) == 0 assert log(-1) == I*pi assert log(E) == 1 assert log(-E).expand() == 1 + I*pi assert unchanged(log, pi) assert log(-pi).expand() == log(pi) + I*pi assert unchanged(log, 17) assert log(-17) == log(17) + I*pi assert log(I) == I*pi/2 assert log(-I) == -I*pi/2 assert log(17*I) == I*pi/2 + log(17) assert log(-17*I).expand() == -I*pi/2 + log(17) assert log(oo*I) is oo assert log(-oo*I) is oo assert log(0, 2) is zoo assert log(0, 5) is zoo assert exp(-log(3))**(-1) == 3 assert log(S.Half) == -log(2) assert log(2*3).func is log assert log(2*3**2).func is log def test_match_real_imag(): x, y = symbols('x,y', real=True) i = Symbol('i', imaginary=True) assert match_real_imag(S.One) == (1, 0) assert match_real_imag(I) == (0, 1) assert match_real_imag(3 - 5*I) == (3, -5) assert match_real_imag(-sqrt(3) + S.Half*I) == (-sqrt(3), S.Half) assert match_real_imag(x + y*I) == (x, y) assert match_real_imag(x*I + y*I) == (0, x + y) assert match_real_imag((x + y)*I) == (0, x + y) assert match_real_imag(Rational(-2, 3)*i*I) == (None, None) assert match_real_imag(1 - 2*i) == (None, None) assert match_real_imag(sqrt(2)*(3 - 5*I)) == (None, None) def test_log_exact(): # check for pi/2, pi/3, pi/4, pi/6, pi/8, pi/12; pi/5, pi/10: for n in range(-23, 24): if gcd(n, 24) != 1: assert log(exp(n*I*pi/24).rewrite(sqrt)) == n*I*pi/24 for n in range(-9, 10): assert log(exp(n*I*pi/10).rewrite(sqrt)) == n*I*pi/10 assert log(S.Half - I*sqrt(3)/2) == -I*pi/3 assert log(Rational(-1, 2) + I*sqrt(3)/2) == I*pi*Rational(2, 3) assert log(-sqrt(2)/2 - I*sqrt(2)/2) == -I*pi*Rational(3, 4) assert log(-sqrt(3)/2 - I*S.Half) == -I*pi*Rational(5, 6) assert log(Rational(-1, 4) + sqrt(5)/4 - I*sqrt(sqrt(5)/8 + Rational(5, 8))) == -I*pi*Rational(2, 5) assert log(sqrt(Rational(5, 8) - sqrt(5)/8) + I*(Rational(1, 4) + sqrt(5)/4)) == I*pi*Rational(3, 10) assert log(-sqrt(sqrt(2)/4 + S.Half) + I*sqrt(S.Half - sqrt(2)/4)) == I*pi*Rational(7, 8) assert log(-sqrt(6)/4 - sqrt(2)/4 + I*(-sqrt(6)/4 + sqrt(2)/4)) == -I*pi*Rational(11, 12) assert log(-1 + I*sqrt(3)) == log(2) + I*pi*Rational(2, 3) assert log(5 + 5*I) == log(5*sqrt(2)) + I*pi/4 assert log(sqrt(-12)) == log(2*sqrt(3)) + I*pi/2 assert log(-sqrt(6) + sqrt(2) - I*sqrt(6) - I*sqrt(2)) == log(4) - I*pi*Rational(7, 12) assert log(-sqrt(6-3*sqrt(2)) - I*sqrt(6+3*sqrt(2))) == log(2*sqrt(3)) - I*pi*Rational(5, 8) assert log(1 + I*sqrt(2-sqrt(2))/sqrt(2+sqrt(2))) == log(2/sqrt(sqrt(2) + 2)) + I*pi/8 assert log(cos(pi*Rational(7, 12)) + I*sin(pi*Rational(7, 12))) == I*pi*Rational(7, 12) assert log(cos(pi*Rational(6, 5)) + I*sin(pi*Rational(6, 5))) == I*pi*Rational(-4, 5) assert log(5*(1 + I)/sqrt(2)) == log(5) + I*pi/4 assert log(sqrt(2)*(-sqrt(3) + 1 - sqrt(3)*I - I)) == log(4) - I*pi*Rational(7, 12) assert log(-sqrt(2)*(1 - I*sqrt(3))) == log(2*sqrt(2)) + I*pi*Rational(2, 3) assert log(sqrt(3)*I*(-sqrt(6 - 3*sqrt(2)) - I*sqrt(3*sqrt(2) + 6))) == log(6) - I*pi/8 zero = (1 + sqrt(2))**2 - 3 - 2*sqrt(2) assert log(zero - I*sqrt(3)) == log(sqrt(3)) - I*pi/2 assert unchanged(log, zero + I*zero) or log(zero + zero*I) is zoo # bail quickly if no obvious simplification is possible: assert unchanged(log, (sqrt(2)-1/sqrt(sqrt(3)+I))**1000) # beware of non-real coefficients assert unchanged(log, sqrt(2-sqrt(5))*(1 + I)) def test_log_base(): assert log(1, 2) == 0 assert log(2, 2) == 1 assert log(3, 2) == log(3)/log(2) assert log(6, 2) == 1 + log(3)/log(2) assert log(6, 3) == 1 + log(2)/log(3) assert log(2**3, 2) == 3 assert log(3**3, 3) == 3 assert log(5, 1) is zoo assert log(1, 1) is nan assert log(Rational(2, 3), 10) == log(Rational(2, 3))/log(10) assert log(Rational(2, 3), Rational(1, 3)) == -log(2)/log(3) + 1 assert log(Rational(2, 3), Rational(2, 5)) == \ log(Rational(2, 3))/log(Rational(2, 5)) # issue 17148 assert log(Rational(8, 3), 2) == -log(3)/log(2) + 3 def test_log_symbolic(): assert log(x, exp(1)) == log(x) assert log(exp(x)) != x assert log(x, exp(1)) == log(x) assert log(x*y) != log(x) + log(y) assert log(x/y).expand() != log(x) - log(y) assert log(x/y).expand(force=True) == log(x) - log(y) assert log(x**y).expand() != y*log(x) assert log(x**y).expand(force=True) == y*log(x) assert log(x, 2) == log(x)/log(2) assert log(E, 2) == 1/log(2) p, q = symbols('p,q', positive=True) r = Symbol('r', real=True) assert log(p**2) != 2*log(p) assert log(p**2).expand() == 2*log(p) assert log(x**2).expand() != 2*log(x) assert log(p**q) != q*log(p) assert log(exp(p)) == p assert log(p*q) != log(p) + log(q) assert log(p*q).expand() == log(p) + log(q) assert log(-sqrt(3)) == log(sqrt(3)) + I*pi assert log(-exp(p)) != p + I*pi assert log(-exp(x)).expand() != x + I*pi assert log(-exp(r)).expand() == r + I*pi assert log(x**y) != y*log(x) assert (log(x**-5)**-1).expand() != -1/log(x)/5 assert (log(p**-5)**-1).expand() == -1/log(p)/5 assert log(-x).func is log and log(-x).args[0] == -x assert log(-p).func is log and log(-p).args[0] == -p def test_log_exp(): assert log(exp(4*I*pi)) == 0 # exp evaluates assert log(exp(-5*I*pi)) == I*pi # exp evaluates assert log(exp(I*pi*Rational(19, 4))) == I*pi*Rational(3, 4) assert log(exp(I*pi*Rational(25, 7))) == I*pi*Rational(-3, 7) assert log(exp(-5*I)) == -5*I + 2*I*pi @_both_exp_pow def test_exp_assumptions(): r = Symbol('r', real=True) i = Symbol('i', imaginary=True) for e in exp, exp_polar: assert e(x).is_real is None assert e(x).is_imaginary is None assert e(i).is_real is None assert e(i).is_imaginary is None assert e(r).is_real is True assert e(r).is_imaginary is False assert e(re(x)).is_extended_real is True assert e(re(x)).is_imaginary is False assert Pow(E, I*pi, evaluate=False).is_imaginary == False assert Pow(E, 2*I*pi, evaluate=False).is_imaginary == False assert Pow(E, I*pi/2, evaluate=False).is_imaginary == True assert Pow(E, I*pi/3, evaluate=False).is_imaginary is None assert exp(0, evaluate=False).is_algebraic a = Symbol('a', algebraic=True) an = Symbol('an', algebraic=True, nonzero=True) r = Symbol('r', rational=True) rn = Symbol('rn', rational=True, nonzero=True) assert exp(a).is_algebraic is None assert exp(an).is_algebraic is False assert exp(pi*r).is_algebraic is None assert exp(pi*rn).is_algebraic is False assert exp(0, evaluate=False).is_algebraic is True assert exp(I*pi/3, evaluate=False).is_algebraic is True assert exp(I*pi*r, evaluate=False).is_algebraic is True @_both_exp_pow def test_exp_AccumBounds(): assert exp(AccumBounds(1, 2)) == AccumBounds(E, E**2) def test_log_assumptions(): p = symbols('p', positive=True) n = symbols('n', negative=True) z = symbols('z', zero=True) x = symbols('x', infinite=True, extended_positive=True) assert log(z).is_positive is False assert log(x).is_extended_positive is True assert log(2) > 0 assert log(1, evaluate=False).is_zero assert log(1 + z).is_zero assert log(p).is_zero is None assert log(n).is_zero is False assert log(0.5).is_negative is True assert log(exp(p) + 1).is_positive assert log(1, evaluate=False).is_algebraic assert log(42, evaluate=False).is_algebraic is False assert log(1 + z).is_rational def test_log_hashing(): assert x != log(log(x)) assert hash(x) != hash(log(log(x))) assert log(x) != log(log(log(x))) e = 1/log(log(x) + log(log(x))) assert e.base.func is log e = 1/log(log(x) + log(log(log(x)))) assert e.base.func is log e = log(log(x)) assert e.func is log assert x.func is not log assert hash(log(log(x))) != hash(x) assert e != x def test_log_sign(): assert sign(log(2)) == 1 def test_log_expand_complex(): assert log(1 + I).expand(complex=True) == log(2)/2 + I*pi/4 assert log(1 - sqrt(2)).expand(complex=True) == log(sqrt(2) - 1) + I*pi def test_log_apply_evalf(): value = (log(3)/log(2) - 1).evalf() assert value.epsilon_eq(Float("0.58496250072115618145373")) def test_log_nseries(): assert log(x - 1)._eval_nseries(x, 4, None, I) == I*pi - x - x**2/2 - x**3/3 + O(x**4) assert log(x - 1)._eval_nseries(x, 4, None, -I) == -I*pi - x - x**2/2 - x**3/3 + O(x**4) assert log(I*x + I*x**3 - 1)._eval_nseries(x, 3, None, 1) == I*pi - I*x + x**2/2 + O(x**3) assert log(I*x + I*x**3 - 1)._eval_nseries(x, 3, None, -1) == -I*pi - I*x + x**2/2 + O(x**3) assert log(I*x**2 + I*x**3 - 1)._eval_nseries(x, 3, None, 1) == I*pi - I*x**2 + O(x**3) assert log(I*x**2 + I*x**3 - 1)._eval_nseries(x, 3, None, -1) == I*pi - I*x**2 + O(x**3) def test_log_expand(): w = Symbol("w", positive=True) e = log(w**(log(5)/log(3))) assert e.expand() == log(5)/log(3) * log(w) x, y, z = symbols('x,y,z', positive=True) assert log(x*(y + z)).expand(mul=False) == log(x) + log(y + z) assert log(log(x**2)*log(y*z)).expand() in [log(2*log(x)*log(y) + 2*log(x)*log(z)), log(log(x)*log(z) + log(y)*log(x)) + log(2), log((log(y) + log(z))*log(x)) + log(2)] assert log(x**log(x**2)).expand(deep=False) == log(x)*log(x**2) assert log(x**log(x**2)).expand() == 2*log(x)**2 x, y = symbols('x,y') assert log(x*y).expand(force=True) == log(x) + log(y) assert log(x**y).expand(force=True) == y*log(x) assert log(exp(x)).expand(force=True) == x # there's generally no need to expand out logs since this requires # factoring and if simplification is sought, it's cheaper to put # logs together than it is to take them apart. assert log(2*3**2).expand() != 2*log(3) + log(2) @XFAIL def test_log_expand_fail(): x, y, z = symbols('x,y,z', positive=True) assert (log(x*(y + z))*(x + y)).expand(mul=True, log=True) == y*log( x) + y*log(y + z) + z*log(x) + z*log(y + z) def test_log_simplify(): x = Symbol("x", positive=True) assert log(x**2).expand() == 2*log(x) assert expand_log(log(x**(2 + log(2)))) == (2 + log(2))*log(x) z = Symbol('z') assert log(sqrt(z)).expand() == log(z)/2 assert expand_log(log(z**(log(2) - 1))) == (log(2) - 1)*log(z) assert log(z**(-1)).expand() != -log(z) assert log(z**(x/(x+1))).expand() == x*log(z)/(x + 1) def test_log_AccumBounds(): assert log(AccumBounds(1, E)) == AccumBounds(0, 1) @_both_exp_pow def test_lambertw(): k = Symbol('k') assert LambertW(x, 0) == LambertW(x) assert LambertW(x, 0, evaluate=False) != LambertW(x) assert LambertW(0) == 0 assert LambertW(E) == 1 assert LambertW(-1/E) == -1 assert LambertW(-log(2)/2) == -log(2) assert LambertW(oo) is oo assert LambertW(0, 1) is -oo assert LambertW(0, 42) is -oo assert LambertW(-pi/2, -1) == -I*pi/2 assert LambertW(-1/E, -1) == -1 assert LambertW(-2*exp(-2), -1) == -2 assert LambertW(2*log(2)) == log(2) assert LambertW(-pi/2) == I*pi/2 assert LambertW(exp(1 + E)) == E assert LambertW(x**2).diff(x) == 2*LambertW(x**2)/x/(1 + LambertW(x**2)) assert LambertW(x, k).diff(x) == LambertW(x, k)/x/(1 + LambertW(x, k)) assert LambertW(sqrt(2)).evalf(30).epsilon_eq( Float("0.701338383413663009202120278965", 30), 1e-29) assert re(LambertW(2, -1)).evalf().epsilon_eq(Float("-0.834310366631110")) assert LambertW(-1).is_real is False # issue 5215 assert LambertW(2, evaluate=False).is_real p = Symbol('p', positive=True) assert LambertW(p, evaluate=False).is_real assert LambertW(p - 1, evaluate=False).is_real is None assert LambertW(-p - 2/S.Exp1, evaluate=False).is_real is False assert LambertW(S.Half, -1, evaluate=False).is_real is False assert LambertW(Rational(-1, 10), -1, evaluate=False).is_real assert LambertW(-10, -1, evaluate=False).is_real is False assert LambertW(-2, 2, evaluate=False).is_real is False assert LambertW(0, evaluate=False).is_algebraic na = Symbol('na', nonzero=True, algebraic=True) assert LambertW(na).is_algebraic is False assert LambertW(p).is_zero is False n = Symbol('n', negative=True) assert LambertW(n).is_zero is False def test_issue_5673(): e = LambertW(-1) assert e.is_comparable is False assert e.is_positive is not True e2 = 1 - 1/(1 - exp(-1000)) assert e2.is_positive is not True e3 = -2 + exp(exp(LambertW(log(2)))*LambertW(log(2))) assert e3.is_nonzero is not True def test_log_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: log(x).fdiff(2)) def test_log_taylor_term(): x = symbols('x') assert log(x).taylor_term(0, x) == x assert log(x).taylor_term(1, x) == -x**2/2 assert log(x).taylor_term(4, x) == x**5/5 assert log(x).taylor_term(-1, x) is S.Zero def test_exp_expand_NC(): A, B, C = symbols('A,B,C', commutative=False) assert exp(A + B).expand() == exp(A + B) assert exp(A + B + C).expand() == exp(A + B + C) assert exp(x + y).expand() == exp(x)*exp(y) assert exp(x + y + z).expand() == exp(x)*exp(y)*exp(z) @_both_exp_pow def test_as_numer_denom(): n = symbols('n', negative=True) assert exp(x).as_numer_denom() == (exp(x), 1) assert exp(-x).as_numer_denom() == (1, exp(x)) assert exp(-2*x).as_numer_denom() == (1, exp(2*x)) assert exp(-2).as_numer_denom() == (1, exp(2)) assert exp(n).as_numer_denom() == (1, exp(-n)) assert exp(-n).as_numer_denom() == (exp(-n), 1) assert exp(-I*x).as_numer_denom() == (1, exp(I*x)) assert exp(-I*n).as_numer_denom() == (1, exp(I*n)) assert exp(-n).as_numer_denom() == (exp(-n), 1) @_both_exp_pow def test_polar(): x, y = symbols('x y', polar=True) assert abs(exp_polar(I*4)) == 1 assert abs(exp_polar(0)) == 1 assert abs(exp_polar(2 + 3*I)) == exp(2) assert exp_polar(I*10).n() == exp_polar(I*10) assert log(exp_polar(z)) == z assert log(x*y).expand() == log(x) + log(y) assert log(x**z).expand() == z*log(x) assert exp_polar(3).exp == 3 # Compare exp(1.0*pi*I). assert (exp_polar(1.0*pi*I).n(n=5)).as_real_imag()[1] >= 0 assert exp_polar(0).is_rational is True # issue 8008 def test_exp_summation(): w = symbols("w") m, n, i, j = symbols("m n i j") expr = exp(Sum(w*i, (i, 0, n), (j, 0, m))) assert expr.expand() == Product(exp(w*i), (i, 0, n), (j, 0, m)) def test_log_product(): from sympy.abc import n, m i, j = symbols('i,j', positive=True, integer=True) x, y = symbols('x,y', positive=True) z = symbols('z', real=True) w = symbols('w') expr = log(Product(x**i, (i, 1, n))) assert simplify(expr) == expr assert expr.expand() == Sum(i*log(x), (i, 1, n)) expr = log(Product(x**i*y**j, (i, 1, n), (j, 1, m))) assert simplify(expr) == expr assert expr.expand() == Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m)) expr = log(Product(-2, (n, 0, 4))) assert simplify(expr) == expr assert expr.expand() == expr assert expr.expand(force=True) == Sum(log(-2), (n, 0, 4)) expr = log(Product(exp(z*i), (i, 0, n))) assert expr.expand() == Sum(z*i, (i, 0, n)) expr = log(Product(exp(w*i), (i, 0, n))) assert expr.expand() == expr assert expr.expand(force=True) == Sum(w*i, (i, 0, n)) expr = log(Product(i**2*abs(j), (i, 1, n), (j, 1, m))) assert expr.expand() == Sum(2*log(i) + log(j), (i, 1, n), (j, 1, m)) @XFAIL def test_log_product_simplify_to_sum(): from sympy.abc import n, m i, j = symbols('i,j', positive=True, integer=True) x, y = symbols('x,y', positive=True) assert simplify(log(Product(x**i, (i, 1, n)))) == Sum(i*log(x), (i, 1, n)) assert simplify(log(Product(x**i*y**j, (i, 1, n), (j, 1, m)))) == \ Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m)) def test_issue_8866(): assert simplify(log(x, 10, evaluate=False)) == simplify(log(x, 10)) assert expand_log(log(x, 10, evaluate=False)) == expand_log(log(x, 10)) y = Symbol('y', positive=True) l1 = log(exp(y), exp(10)) b1 = log(exp(y), exp(5)) l2 = log(exp(y), exp(10), evaluate=False) b2 = log(exp(y), exp(5), evaluate=False) assert simplify(log(l1, b1)) == simplify(log(l2, b2)) assert expand_log(log(l1, b1)) == expand_log(log(l2, b2)) def test_log_expand_factor(): assert (log(18)/log(3) - 2).expand(factor=True) == log(2)/log(3) assert (log(12)/log(2)).expand(factor=True) == log(3)/log(2) + 2 assert (log(15)/log(3)).expand(factor=True) == 1 + log(5)/log(3) assert (log(2)/(-log(12) + log(24))).expand(factor=True) == 1 assert expand_log(log(12), factor=True) == log(3) + 2*log(2) assert expand_log(log(21)/log(7), factor=False) == log(3)/log(7) + 1 assert expand_log(log(45)/log(5) + log(20), factor=False) == \ 1 + 2*log(3)/log(5) + log(20) assert expand_log(log(45)/log(5) + log(26), factor=True) == \ log(2) + log(13) + (log(5) + 2*log(3))/log(5) def test_issue_9116(): n = Symbol('n', positive=True, integer=True) assert log(n).is_nonnegative is True
ccc58cab84c9e4535b1fe99a77f4840ab0c93737c8bef4260fc1b887561bdea0
from sympy.calculus.accumulationbounds import AccumBounds from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi, zoo) from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.integers import (ceiling, floor, frac) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import sin from sympy.core.expr import unchanged from sympy.testing.pytest import XFAIL x = Symbol('x') i = Symbol('i', imaginary=True) y = Symbol('y', real=True) k, n = symbols('k,n', integer=True) def test_floor(): assert floor(nan) is nan assert floor(oo) is oo assert floor(-oo) is -oo assert floor(zoo) is zoo assert floor(0) == 0 assert floor(1) == 1 assert floor(-1) == -1 assert floor(E) == 2 assert floor(-E) == -3 assert floor(2*E) == 5 assert floor(-2*E) == -6 assert floor(pi) == 3 assert floor(-pi) == -4 assert floor(S.Half) == 0 assert floor(Rational(-1, 2)) == -1 assert floor(Rational(7, 3)) == 2 assert floor(Rational(-7, 3)) == -3 assert floor(-Rational(7, 3)) == -3 assert floor(Float(17.0)) == 17 assert floor(-Float(17.0)) == -17 assert floor(Float(7.69)) == 7 assert floor(-Float(7.69)) == -8 assert floor(I) == I assert floor(-I) == -I e = floor(i) assert e.func is floor and e.args[0] == i assert floor(oo*I) == oo*I assert floor(-oo*I) == -oo*I assert floor(exp(I*pi/4)*oo) == exp(I*pi/4)*oo assert floor(2*I) == 2*I assert floor(-2*I) == -2*I assert floor(I/2) == 0 assert floor(-I/2) == -I assert floor(E + 17) == 19 assert floor(pi + 2) == 5 assert floor(E + pi) == 5 assert floor(I + pi) == 3 + I assert floor(floor(pi)) == 3 assert floor(floor(y)) == floor(y) assert floor(floor(x)) == floor(x) assert unchanged(floor, x) assert unchanged(floor, 2*x) assert unchanged(floor, k*x) assert floor(k) == k assert floor(2*k) == 2*k assert floor(k*n) == k*n assert unchanged(floor, k/2) assert unchanged(floor, x + y) assert floor(x + 3) == floor(x) + 3 assert floor(x + k) == floor(x) + k assert floor(y + 3) == floor(y) + 3 assert floor(y + k) == floor(y) + k assert floor(3 + I*y + pi) == 6 + floor(y)*I assert floor(k + n) == k + n assert unchanged(floor, x*I) assert floor(k*I) == k*I assert floor(Rational(23, 10) - E*I) == 2 - 3*I assert floor(sin(1)) == 0 assert floor(sin(-1)) == -1 assert floor(exp(2)) == 7 assert floor(log(8)/log(2)) != 2 assert int(floor(log(8)/log(2)).evalf(chop=True)) == 3 assert floor(factorial(50)/exp(1)) == \ 11188719610782480504630258070757734324011354208865721592720336800 assert (floor(y) < y) == False assert (floor(y) <= y) == True assert (floor(y) > y) == False assert (floor(y) >= y) == False assert (floor(x) <= x).is_Relational # x could be non-real assert (floor(x) > x).is_Relational assert (floor(x) <= y).is_Relational # arg is not same as rhs assert (floor(x) > y).is_Relational assert (floor(y) <= oo) == True assert (floor(y) < oo) == True assert (floor(y) >= -oo) == True assert (floor(y) > -oo) == True assert floor(y).rewrite(frac) == y - frac(y) assert floor(y).rewrite(ceiling) == -ceiling(-y) assert floor(y).rewrite(frac).subs(y, -pi) == floor(-pi) assert floor(y).rewrite(frac).subs(y, E) == floor(E) assert floor(y).rewrite(ceiling).subs(y, E) == -ceiling(-E) assert floor(y).rewrite(ceiling).subs(y, -pi) == -ceiling(pi) assert Eq(floor(y), y - frac(y)) assert Eq(floor(y), -ceiling(-y)) neg = Symbol('neg', negative=True) nn = Symbol('nn', nonnegative=True) pos = Symbol('pos', positive=True) np = Symbol('np', nonpositive=True) assert (floor(neg) < 0) == True assert (floor(neg) <= 0) == True assert (floor(neg) > 0) == False assert (floor(neg) >= 0) == False assert (floor(neg) <= -1) == True assert (floor(neg) >= -3) == (neg >= -3) assert (floor(neg) < 5) == (neg < 5) assert (floor(nn) < 0) == False assert (floor(nn) >= 0) == True assert (floor(pos) < 0) == False assert (floor(pos) <= 0) == (pos < 1) assert (floor(pos) > 0) == (pos >= 1) assert (floor(pos) >= 0) == True assert (floor(pos) >= 3) == (pos >= 3) assert (floor(np) <= 0) == True assert (floor(np) > 0) == False assert floor(neg).is_negative == True assert floor(neg).is_nonnegative == False assert floor(nn).is_negative == False assert floor(nn).is_nonnegative == True assert floor(pos).is_negative == False assert floor(pos).is_nonnegative == True assert floor(np).is_negative is None assert floor(np).is_nonnegative is None assert (floor(7, evaluate=False) >= 7) == True assert (floor(7, evaluate=False) > 7) == False assert (floor(7, evaluate=False) <= 7) == True assert (floor(7, evaluate=False) < 7) == False assert (floor(7, evaluate=False) >= 6) == True assert (floor(7, evaluate=False) > 6) == True assert (floor(7, evaluate=False) <= 6) == False assert (floor(7, evaluate=False) < 6) == False assert (floor(7, evaluate=False) >= 8) == False assert (floor(7, evaluate=False) > 8) == False assert (floor(7, evaluate=False) <= 8) == True assert (floor(7, evaluate=False) < 8) == True assert (floor(x) <= 5.5) == Le(floor(x), 5.5, evaluate=False) assert (floor(x) >= -3.2) == Ge(floor(x), -3.2, evaluate=False) assert (floor(x) < 2.9) == Lt(floor(x), 2.9, evaluate=False) assert (floor(x) > -1.7) == Gt(floor(x), -1.7, evaluate=False) assert (floor(y) <= 5.5) == (y < 6) assert (floor(y) >= -3.2) == (y >= -3) assert (floor(y) < 2.9) == (y < 3) assert (floor(y) > -1.7) == (y >= -1) assert (floor(y) <= n) == (y < n + 1) assert (floor(y) >= n) == (y >= n) assert (floor(y) < n) == (y < n) assert (floor(y) > n) == (y >= n + 1) def test_ceiling(): assert ceiling(nan) is nan assert ceiling(oo) is oo assert ceiling(-oo) is -oo assert ceiling(zoo) is zoo assert ceiling(0) == 0 assert ceiling(1) == 1 assert ceiling(-1) == -1 assert ceiling(E) == 3 assert ceiling(-E) == -2 assert ceiling(2*E) == 6 assert ceiling(-2*E) == -5 assert ceiling(pi) == 4 assert ceiling(-pi) == -3 assert ceiling(S.Half) == 1 assert ceiling(Rational(-1, 2)) == 0 assert ceiling(Rational(7, 3)) == 3 assert ceiling(-Rational(7, 3)) == -2 assert ceiling(Float(17.0)) == 17 assert ceiling(-Float(17.0)) == -17 assert ceiling(Float(7.69)) == 8 assert ceiling(-Float(7.69)) == -7 assert ceiling(I) == I assert ceiling(-I) == -I e = ceiling(i) assert e.func is ceiling and e.args[0] == i assert ceiling(oo*I) == oo*I assert ceiling(-oo*I) == -oo*I assert ceiling(exp(I*pi/4)*oo) == exp(I*pi/4)*oo assert ceiling(2*I) == 2*I assert ceiling(-2*I) == -2*I assert ceiling(I/2) == I assert ceiling(-I/2) == 0 assert ceiling(E + 17) == 20 assert ceiling(pi + 2) == 6 assert ceiling(E + pi) == 6 assert ceiling(I + pi) == I + 4 assert ceiling(ceiling(pi)) == 4 assert ceiling(ceiling(y)) == ceiling(y) assert ceiling(ceiling(x)) == ceiling(x) assert unchanged(ceiling, x) assert unchanged(ceiling, 2*x) assert unchanged(ceiling, k*x) assert ceiling(k) == k assert ceiling(2*k) == 2*k assert ceiling(k*n) == k*n assert unchanged(ceiling, k/2) assert unchanged(ceiling, x + y) assert ceiling(x + 3) == ceiling(x) + 3 assert ceiling(x + k) == ceiling(x) + k assert ceiling(y + 3) == ceiling(y) + 3 assert ceiling(y + k) == ceiling(y) + k assert ceiling(3 + pi + y*I) == 7 + ceiling(y)*I assert ceiling(k + n) == k + n assert unchanged(ceiling, x*I) assert ceiling(k*I) == k*I assert ceiling(Rational(23, 10) - E*I) == 3 - 2*I assert ceiling(sin(1)) == 1 assert ceiling(sin(-1)) == 0 assert ceiling(exp(2)) == 8 assert ceiling(-log(8)/log(2)) != -2 assert int(ceiling(-log(8)/log(2)).evalf(chop=True)) == -3 assert ceiling(factorial(50)/exp(1)) == \ 11188719610782480504630258070757734324011354208865721592720336801 assert (ceiling(y) >= y) == True assert (ceiling(y) > y) == False assert (ceiling(y) < y) == False assert (ceiling(y) <= y) == False assert (ceiling(x) >= x).is_Relational # x could be non-real assert (ceiling(x) < x).is_Relational assert (ceiling(x) >= y).is_Relational # arg is not same as rhs assert (ceiling(x) < y).is_Relational assert (ceiling(y) >= -oo) == True assert (ceiling(y) > -oo) == True assert (ceiling(y) <= oo) == True assert (ceiling(y) < oo) == True assert ceiling(y).rewrite(floor) == -floor(-y) assert ceiling(y).rewrite(frac) == y + frac(-y) assert ceiling(y).rewrite(floor).subs(y, -pi) == -floor(pi) assert ceiling(y).rewrite(floor).subs(y, E) == -floor(-E) assert ceiling(y).rewrite(frac).subs(y, pi) == ceiling(pi) assert ceiling(y).rewrite(frac).subs(y, -E) == ceiling(-E) assert Eq(ceiling(y), y + frac(-y)) assert Eq(ceiling(y), -floor(-y)) neg = Symbol('neg', negative=True) nn = Symbol('nn', nonnegative=True) pos = Symbol('pos', positive=True) np = Symbol('np', nonpositive=True) assert (ceiling(neg) <= 0) == True assert (ceiling(neg) < 0) == (neg <= -1) assert (ceiling(neg) > 0) == False assert (ceiling(neg) >= 0) == (neg > -1) assert (ceiling(neg) > -3) == (neg > -3) assert (ceiling(neg) <= 10) == (neg <= 10) assert (ceiling(nn) < 0) == False assert (ceiling(nn) >= 0) == True assert (ceiling(pos) < 0) == False assert (ceiling(pos) <= 0) == False assert (ceiling(pos) > 0) == True assert (ceiling(pos) >= 0) == True assert (ceiling(pos) >= 1) == True assert (ceiling(pos) > 5) == (pos > 5) assert (ceiling(np) <= 0) == True assert (ceiling(np) > 0) == False assert ceiling(neg).is_positive == False assert ceiling(neg).is_nonpositive == True assert ceiling(nn).is_positive is None assert ceiling(nn).is_nonpositive is None assert ceiling(pos).is_positive == True assert ceiling(pos).is_nonpositive == False assert ceiling(np).is_positive == False assert ceiling(np).is_nonpositive == True assert (ceiling(7, evaluate=False) >= 7) == True assert (ceiling(7, evaluate=False) > 7) == False assert (ceiling(7, evaluate=False) <= 7) == True assert (ceiling(7, evaluate=False) < 7) == False assert (ceiling(7, evaluate=False) >= 6) == True assert (ceiling(7, evaluate=False) > 6) == True assert (ceiling(7, evaluate=False) <= 6) == False assert (ceiling(7, evaluate=False) < 6) == False assert (ceiling(7, evaluate=False) >= 8) == False assert (ceiling(7, evaluate=False) > 8) == False assert (ceiling(7, evaluate=False) <= 8) == True assert (ceiling(7, evaluate=False) < 8) == True assert (ceiling(x) <= 5.5) == Le(ceiling(x), 5.5, evaluate=False) assert (ceiling(x) >= -3.2) == Ge(ceiling(x), -3.2, evaluate=False) assert (ceiling(x) < 2.9) == Lt(ceiling(x), 2.9, evaluate=False) assert (ceiling(x) > -1.7) == Gt(ceiling(x), -1.7, evaluate=False) assert (ceiling(y) <= 5.5) == (y <= 5) assert (ceiling(y) >= -3.2) == (y > -4) assert (ceiling(y) < 2.9) == (y <= 2) assert (ceiling(y) > -1.7) == (y > -2) assert (ceiling(y) <= n) == (y <= n) assert (ceiling(y) >= n) == (y > n - 1) assert (ceiling(y) < n) == (y <= n - 1) assert (ceiling(y) > n) == (y > n) def test_frac(): assert isinstance(frac(x), frac) assert frac(oo) == AccumBounds(0, 1) assert frac(-oo) == AccumBounds(0, 1) assert frac(zoo) is nan assert frac(n) == 0 assert frac(nan) is nan assert frac(Rational(4, 3)) == Rational(1, 3) assert frac(-Rational(4, 3)) == Rational(2, 3) assert frac(Rational(-4, 3)) == Rational(2, 3) r = Symbol('r', real=True) assert frac(I*r) == I*frac(r) assert frac(1 + I*r) == I*frac(r) assert frac(0.5 + I*r) == 0.5 + I*frac(r) assert frac(n + I*r) == I*frac(r) assert frac(n + I*k) == 0 assert unchanged(frac, x + I*x) assert frac(x + I*n) == frac(x) assert frac(x).rewrite(floor) == x - floor(x) assert frac(x).rewrite(ceiling) == x + ceiling(-x) assert frac(y).rewrite(floor).subs(y, pi) == frac(pi) assert frac(y).rewrite(floor).subs(y, -E) == frac(-E) assert frac(y).rewrite(ceiling).subs(y, -pi) == frac(-pi) assert frac(y).rewrite(ceiling).subs(y, E) == frac(E) assert Eq(frac(y), y - floor(y)) assert Eq(frac(y), y + ceiling(-y)) r = Symbol('r', real=True) p_i = Symbol('p_i', integer=True, positive=True) n_i = Symbol('p_i', integer=True, negative=True) np_i = Symbol('np_i', integer=True, nonpositive=True) nn_i = Symbol('nn_i', integer=True, nonnegative=True) p_r = Symbol('p_r', positive=True) n_r = Symbol('n_r', negative=True) np_r = Symbol('np_r', real=True, nonpositive=True) nn_r = Symbol('nn_r', real=True, nonnegative=True) # Real frac argument, integer rhs assert frac(r) <= p_i assert not frac(r) <= n_i assert (frac(r) <= np_i).has(Le) assert (frac(r) <= nn_i).has(Le) assert frac(r) < p_i assert not frac(r) < n_i assert not frac(r) < np_i assert (frac(r) < nn_i).has(Lt) assert not frac(r) >= p_i assert frac(r) >= n_i assert frac(r) >= np_i assert (frac(r) >= nn_i).has(Ge) assert not frac(r) > p_i assert frac(r) > n_i assert (frac(r) > np_i).has(Gt) assert (frac(r) > nn_i).has(Gt) assert not Eq(frac(r), p_i) assert not Eq(frac(r), n_i) assert Eq(frac(r), np_i).has(Eq) assert Eq(frac(r), nn_i).has(Eq) assert Ne(frac(r), p_i) assert Ne(frac(r), n_i) assert Ne(frac(r), np_i).has(Ne) assert Ne(frac(r), nn_i).has(Ne) # Real frac argument, real rhs assert (frac(r) <= p_r).has(Le) assert not frac(r) <= n_r assert (frac(r) <= np_r).has(Le) assert (frac(r) <= nn_r).has(Le) assert (frac(r) < p_r).has(Lt) assert not frac(r) < n_r assert not frac(r) < np_r assert (frac(r) < nn_r).has(Lt) assert (frac(r) >= p_r).has(Ge) assert frac(r) >= n_r assert frac(r) >= np_r assert (frac(r) >= nn_r).has(Ge) assert (frac(r) > p_r).has(Gt) assert frac(r) > n_r assert (frac(r) > np_r).has(Gt) assert (frac(r) > nn_r).has(Gt) assert not Eq(frac(r), n_r) assert Eq(frac(r), p_r).has(Eq) assert Eq(frac(r), np_r).has(Eq) assert Eq(frac(r), nn_r).has(Eq) assert Ne(frac(r), p_r).has(Ne) assert Ne(frac(r), n_r) assert Ne(frac(r), np_r).has(Ne) assert Ne(frac(r), nn_r).has(Ne) # Real frac argument, +/- oo rhs assert frac(r) < oo assert frac(r) <= oo assert not frac(r) > oo assert not frac(r) >= oo assert not frac(r) < -oo assert not frac(r) <= -oo assert frac(r) > -oo assert frac(r) >= -oo assert frac(r) < 1 assert frac(r) <= 1 assert not frac(r) > 1 assert not frac(r) >= 1 assert not frac(r) < 0 assert (frac(r) <= 0).has(Le) assert (frac(r) > 0).has(Gt) assert frac(r) >= 0 # Some test for numbers assert frac(r) <= sqrt(2) assert (frac(r) <= sqrt(3) - sqrt(2)).has(Le) assert not frac(r) <= sqrt(2) - sqrt(3) assert not frac(r) >= sqrt(2) assert (frac(r) >= sqrt(3) - sqrt(2)).has(Ge) assert frac(r) >= sqrt(2) - sqrt(3) assert not Eq(frac(r), sqrt(2)) assert Eq(frac(r), sqrt(3) - sqrt(2)).has(Eq) assert not Eq(frac(r), sqrt(2) - sqrt(3)) assert Ne(frac(r), sqrt(2)) assert Ne(frac(r), sqrt(3) - sqrt(2)).has(Ne) assert Ne(frac(r), sqrt(2) - sqrt(3)) assert frac(p_i, evaluate=False).is_zero assert frac(p_i, evaluate=False).is_finite assert frac(p_i, evaluate=False).is_integer assert frac(p_i, evaluate=False).is_real assert frac(r).is_finite assert frac(r).is_real assert frac(r).is_zero is None assert frac(r).is_integer is None assert frac(oo).is_finite assert frac(oo).is_real def test_series(): x, y = symbols('x,y') assert floor(x).nseries(x, y, 100) == floor(y) assert ceiling(x).nseries(x, y, 100) == ceiling(y) assert floor(x).nseries(x, pi, 100) == 3 assert ceiling(x).nseries(x, pi, 100) == 4 assert floor(x).nseries(x, 0, 100) == 0 assert ceiling(x).nseries(x, 0, 100) == 1 assert floor(-x).nseries(x, 0, 100) == -1 assert ceiling(-x).nseries(x, 0, 100) == 0 @XFAIL def test_issue_4149(): assert floor(3 + pi*I + y*I) == 3 + floor(pi + y)*I assert floor(3*I + pi*I + y*I) == floor(3 + pi + y)*I assert floor(3 + E + pi*I + y*I) == 5 + floor(pi + y)*I def test_issue_21651(): k = Symbol('k', positive=True, integer=True) exp = 2*2**(-k) assert isinstance(floor(exp), floor) def test_issue_11207(): assert floor(floor(x)) == floor(x) assert floor(ceiling(x)) == ceiling(x) assert ceiling(floor(x)) == floor(x) assert ceiling(ceiling(x)) == ceiling(x) def test_nested_floor_ceiling(): assert floor(-floor(ceiling(x**3)/y)) == -floor(ceiling(x**3)/y) assert ceiling(-floor(ceiling(x**3)/y)) == -floor(ceiling(x**3)/y) assert floor(ceiling(-floor(x**Rational(7, 2)/y))) == -floor(x**Rational(7, 2)/y) assert -ceiling(-ceiling(floor(x)/y)) == ceiling(floor(x)/y) def test_issue_18689(): assert floor(floor(floor(x)) + 3) == floor(x) + 3 assert ceiling(ceiling(ceiling(x)) + 1) == ceiling(x) + 1 assert ceiling(ceiling(floor(x)) + 3) == floor(x) + 3 def test_issue_18421(): assert floor(float(0)) is S.Zero assert ceiling(float(0)) is S.Zero
246054e0cec04f3835508f3c58fbf570f3ef4252465e685794438fd493d79830
from sympy.calculus.accumulationbounds import AccumBounds from sympy.core.add import Add from sympy.core.function import (Lambda, diff) from sympy.core.mul import Mul from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi, zoo) from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import (arg, conjugate, im, re) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.hyperbolic import (acoth, asinh, atanh, cosh, coth, sinh, tanh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acos, acot, acsc, asec, asin, atan, atan2, cos, cot, csc, sec, sin, sinc, tan) from sympy.functions.special.bessel import (besselj, jn) from sympy.functions.special.delta_functions import Heaviside from sympy.matrices.dense import Matrix from sympy.polys.polytools import (cancel, gcd) from sympy.series.limits import limit from sympy.series.order import O from sympy.series.series import series from sympy.sets.fancysets import ImageSet from sympy.sets.sets import (FiniteSet, Interval) from sympy.simplify.simplify import simplify from sympy.core.expr import unchanged from sympy.core.function import ArgumentIndexError from sympy.core.relational import Ne, Eq from sympy.functions.elementary.piecewise import Piecewise from sympy.sets.setexpr import SetExpr from sympy.testing.pytest import XFAIL, slow, raises x, y, z = symbols('x y z') r = Symbol('r', real=True) k, m = symbols('k m', integer=True) p = Symbol('p', positive=True) n = Symbol('n', negative=True) np = Symbol('p', nonpositive=True) nn = Symbol('n', nonnegative=True) nz = Symbol('nz', nonzero=True) ep = Symbol('ep', extended_positive=True) en = Symbol('en', extended_negative=True) enp = Symbol('ep', extended_nonpositive=True) enn = Symbol('en', extended_nonnegative=True) enz = Symbol('enz', extended_nonzero=True) a = Symbol('a', algebraic=True) na = Symbol('na', nonzero=True, algebraic=True) def test_sin(): x, y = symbols('x y') assert sin.nargs == FiniteSet(1) assert sin(nan) is nan assert sin(zoo) is nan assert sin(oo) == AccumBounds(-1, 1) assert sin(oo) - sin(oo) == AccumBounds(-2, 2) assert sin(oo*I) == oo*I assert sin(-oo*I) == -oo*I assert 0*sin(oo) is S.Zero assert 0/sin(oo) is S.Zero assert 0 + sin(oo) == AccumBounds(-1, 1) assert 5 + sin(oo) == AccumBounds(4, 6) assert sin(0) == 0 assert sin(asin(x)) == x assert sin(atan(x)) == x / sqrt(1 + x**2) assert sin(acos(x)) == sqrt(1 - x**2) assert sin(acot(x)) == 1 / (sqrt(1 + 1 / x**2) * x) assert sin(acsc(x)) == 1 / x assert sin(asec(x)) == sqrt(1 - 1 / x**2) assert sin(atan2(y, x)) == y / sqrt(x**2 + y**2) assert sin(pi*I) == sinh(pi)*I assert sin(-pi*I) == -sinh(pi)*I assert sin(-2*I) == -sinh(2)*I assert sin(pi) == 0 assert sin(-pi) == 0 assert sin(2*pi) == 0 assert sin(-2*pi) == 0 assert sin(-3*10**73*pi) == 0 assert sin(7*10**103*pi) == 0 assert sin(pi/2) == 1 assert sin(-pi/2) == -1 assert sin(pi*Rational(5, 2)) == 1 assert sin(pi*Rational(7, 2)) == -1 ne = symbols('ne', integer=True, even=False) e = symbols('e', even=True) assert sin(pi*ne/2) == (-1)**(ne/2 - S.Half) assert sin(pi*k/2).func == sin assert sin(pi*e/2) == 0 assert sin(pi*k) == 0 assert sin(pi*k).subs(k, 3) == sin(pi*k/2).subs(k, 6) # issue 8298 assert sin(pi/3) == S.Half*sqrt(3) assert sin(pi*Rational(-2, 3)) == Rational(-1, 2)*sqrt(3) assert sin(pi/4) == S.Half*sqrt(2) assert sin(-pi/4) == Rational(-1, 2)*sqrt(2) assert sin(pi*Rational(17, 4)) == S.Half*sqrt(2) assert sin(pi*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2) assert sin(pi/6) == S.Half assert sin(-pi/6) == Rational(-1, 2) assert sin(pi*Rational(7, 6)) == Rational(-1, 2) assert sin(pi*Rational(-5, 6)) == Rational(-1, 2) assert sin(pi*Rational(1, 5)) == sqrt((5 - sqrt(5)) / 8) assert sin(pi*Rational(2, 5)) == sqrt((5 + sqrt(5)) / 8) assert sin(pi*Rational(3, 5)) == sin(pi*Rational(2, 5)) assert sin(pi*Rational(4, 5)) == sin(pi*Rational(1, 5)) assert sin(pi*Rational(6, 5)) == -sin(pi*Rational(1, 5)) assert sin(pi*Rational(8, 5)) == -sin(pi*Rational(2, 5)) assert sin(pi*Rational(-1273, 5)) == -sin(pi*Rational(2, 5)) assert sin(pi/8) == sqrt((2 - sqrt(2))/4) assert sin(pi/10) == Rational(-1, 4) + sqrt(5)/4 assert sin(pi/12) == -sqrt(2)/4 + sqrt(6)/4 assert sin(pi*Rational(5, 12)) == sqrt(2)/4 + sqrt(6)/4 assert sin(pi*Rational(-7, 12)) == -sqrt(2)/4 - sqrt(6)/4 assert sin(pi*Rational(-11, 12)) == sqrt(2)/4 - sqrt(6)/4 assert sin(pi*Rational(104, 105)) == sin(pi/105) assert sin(pi*Rational(106, 105)) == -sin(pi/105) assert sin(pi*Rational(-104, 105)) == -sin(pi/105) assert sin(pi*Rational(-106, 105)) == sin(pi/105) assert sin(x*I) == sinh(x)*I assert sin(k*pi) == 0 assert sin(17*k*pi) == 0 assert sin(2*k*pi + 4) == sin(4) assert sin(2*k*pi + m*pi + 1) == (-1)**(m + 2*k)*sin(1) assert sin(k*pi*I) == sinh(k*pi)*I assert sin(r).is_real is True assert sin(0, evaluate=False).is_algebraic assert sin(a).is_algebraic is None assert sin(na).is_algebraic is False q = Symbol('q', rational=True) assert sin(pi*q).is_algebraic qn = Symbol('qn', rational=True, nonzero=True) assert sin(qn).is_rational is False assert sin(q).is_rational is None # issue 8653 assert isinstance(sin( re(x) - im(y)), sin) is True assert isinstance(sin(-re(x) + im(y)), sin) is False assert sin(SetExpr(Interval(0, 1))) == SetExpr(ImageSet(Lambda(x, sin(x)), Interval(0, 1))) for d in list(range(1, 22)) + [60, 85]: for n in range(0, d*2 + 1): x = n*pi/d e = abs( float(sin(x)) - sin(float(x)) ) assert e < 1e-12 assert sin(0, evaluate=False).is_zero is True assert sin(k*pi, evaluate=False).is_zero is True assert sin(Add(1, -1, evaluate=False), evaluate=False).is_zero is True def test_sin_cos(): for d in [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 24, 30, 40, 60, 120]: # list is not exhaustive... for n in range(-2*d, d*2): x = n*pi/d assert sin(x + pi/2) == cos(x), "fails for %d*pi/%d" % (n, d) assert sin(x - pi/2) == -cos(x), "fails for %d*pi/%d" % (n, d) assert sin(x) == cos(x - pi/2), "fails for %d*pi/%d" % (n, d) assert -sin(x) == cos(x + pi/2), "fails for %d*pi/%d" % (n, d) def test_sin_series(): assert sin(x).series(x, 0, 9) == \ x - x**3/6 + x**5/120 - x**7/5040 + O(x**9) def test_sin_rewrite(): assert sin(x).rewrite(exp) == -I*(exp(I*x) - exp(-I*x))/2 assert sin(x).rewrite(tan) == 2*tan(x/2)/(1 + tan(x/2)**2) assert sin(x).rewrite(cot) == 2*cot(x/2)/(1 + cot(x/2)**2) assert sin(sinh(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, sinh(3)).n() assert sin(cosh(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cosh(3)).n() assert sin(tanh(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, tanh(3)).n() assert sin(coth(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, coth(3)).n() assert sin(sin(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, sin(3)).n() assert sin(cos(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cos(3)).n() assert sin(tan(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, tan(3)).n() assert sin(cot(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cot(3)).n() assert sin(log(x)).rewrite(Pow) == I*x**-I / 2 - I*x**I /2 assert sin(x).rewrite(csc) == 1/csc(x) assert sin(x).rewrite(cos) == cos(x - pi / 2, evaluate=False) assert sin(x).rewrite(sec) == 1 / sec(x - pi / 2, evaluate=False) assert sin(cos(x)).rewrite(Pow) == sin(cos(x)) def _test_extrig(f, i, e): from sympy.core.function import expand_trig assert unchanged(f, i) assert expand_trig(f(i)) == f(i) # testing directly instead of with .expand(trig=True) # because the other expansions undo the unevaluated Mul assert expand_trig(f(Mul(i, 1, evaluate=False))) == e assert abs(f(i) - e).n() < 1e-10 def test_sin_expansion(): # Note: these formulas are not unique. The ones here come from the # Chebyshev formulas. assert sin(x + y).expand(trig=True) == sin(x)*cos(y) + cos(x)*sin(y) assert sin(x - y).expand(trig=True) == sin(x)*cos(y) - cos(x)*sin(y) assert sin(y - x).expand(trig=True) == cos(x)*sin(y) - sin(x)*cos(y) assert sin(2*x).expand(trig=True) == 2*sin(x)*cos(x) assert sin(3*x).expand(trig=True) == -4*sin(x)**3 + 3*sin(x) assert sin(4*x).expand(trig=True) == -8*sin(x)**3*cos(x) + 4*sin(x)*cos(x) _test_extrig(sin, 2, 2*sin(1)*cos(1)) _test_extrig(sin, 3, -4*sin(1)**3 + 3*sin(1)) def test_sin_AccumBounds(): assert sin(AccumBounds(-oo, oo)) == AccumBounds(-1, 1) assert sin(AccumBounds(0, oo)) == AccumBounds(-1, 1) assert sin(AccumBounds(-oo, 0)) == AccumBounds(-1, 1) assert sin(AccumBounds(0, 2*S.Pi)) == AccumBounds(-1, 1) assert sin(AccumBounds(0, S.Pi*Rational(3, 4))) == AccumBounds(0, 1) assert sin(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(7, 4))) == AccumBounds(-1, sin(S.Pi*Rational(3, 4))) assert sin(AccumBounds(S.Pi/4, S.Pi/3)) == AccumBounds(sin(S.Pi/4), sin(S.Pi/3)) 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))) def test_sin_fdiff(): assert sin(x).fdiff() == cos(x) raises(ArgumentIndexError, lambda: sin(x).fdiff(2)) def test_trig_symmetry(): assert sin(-x) == -sin(x) assert cos(-x) == cos(x) assert tan(-x) == -tan(x) assert cot(-x) == -cot(x) assert sin(x + pi) == -sin(x) assert sin(x + 2*pi) == sin(x) assert sin(x + 3*pi) == -sin(x) assert sin(x + 4*pi) == sin(x) assert sin(x - 5*pi) == -sin(x) assert cos(x + pi) == -cos(x) assert cos(x + 2*pi) == cos(x) assert cos(x + 3*pi) == -cos(x) assert cos(x + 4*pi) == cos(x) assert cos(x - 5*pi) == -cos(x) assert tan(x + pi) == tan(x) assert tan(x - 3*pi) == tan(x) assert cot(x + pi) == cot(x) assert cot(x - 3*pi) == cot(x) assert sin(pi/2 - x) == cos(x) assert sin(pi*Rational(3, 2) - x) == -cos(x) assert sin(pi*Rational(5, 2) - x) == cos(x) assert cos(pi/2 - x) == sin(x) assert cos(pi*Rational(3, 2) - x) == -sin(x) assert cos(pi*Rational(5, 2) - x) == sin(x) assert tan(pi/2 - x) == cot(x) assert tan(pi*Rational(3, 2) - x) == cot(x) assert tan(pi*Rational(5, 2) - x) == cot(x) assert cot(pi/2 - x) == tan(x) assert cot(pi*Rational(3, 2) - x) == tan(x) assert cot(pi*Rational(5, 2) - x) == tan(x) assert sin(pi/2 + x) == cos(x) assert cos(pi/2 + x) == -sin(x) assert tan(pi/2 + x) == -cot(x) assert cot(pi/2 + x) == -tan(x) def test_cos(): x, y = symbols('x y') assert cos.nargs == FiniteSet(1) assert cos(nan) is nan assert cos(oo) == AccumBounds(-1, 1) assert cos(oo) - cos(oo) == AccumBounds(-2, 2) assert cos(oo*I) is oo assert cos(-oo*I) is oo assert cos(zoo) is nan assert cos(0) == 1 assert cos(acos(x)) == x assert cos(atan(x)) == 1 / sqrt(1 + x**2) assert cos(asin(x)) == sqrt(1 - x**2) assert cos(acot(x)) == 1 / sqrt(1 + 1 / x**2) assert cos(acsc(x)) == sqrt(1 - 1 / x**2) assert cos(asec(x)) == 1 / x assert cos(atan2(y, x)) == x / sqrt(x**2 + y**2) assert cos(pi*I) == cosh(pi) assert cos(-pi*I) == cosh(pi) assert cos(-2*I) == cosh(2) assert cos(pi/2) == 0 assert cos(-pi/2) == 0 assert cos(pi/2) == 0 assert cos(-pi/2) == 0 assert cos((-3*10**73 + 1)*pi/2) == 0 assert cos((7*10**103 + 1)*pi/2) == 0 n = symbols('n', integer=True, even=False) e = symbols('e', even=True) assert cos(pi*n/2) == 0 assert cos(pi*e/2) == (-1)**(e/2) assert cos(pi) == -1 assert cos(-pi) == -1 assert cos(2*pi) == 1 assert cos(5*pi) == -1 assert cos(8*pi) == 1 assert cos(pi/3) == S.Half assert cos(pi*Rational(-2, 3)) == Rational(-1, 2) assert cos(pi/4) == S.Half*sqrt(2) assert cos(-pi/4) == S.Half*sqrt(2) assert cos(pi*Rational(11, 4)) == Rational(-1, 2)*sqrt(2) assert cos(pi*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2) assert cos(pi/6) == S.Half*sqrt(3) assert cos(-pi/6) == S.Half*sqrt(3) assert cos(pi*Rational(7, 6)) == Rational(-1, 2)*sqrt(3) assert cos(pi*Rational(-5, 6)) == Rational(-1, 2)*sqrt(3) assert cos(pi*Rational(1, 5)) == (sqrt(5) + 1)/4 assert cos(pi*Rational(2, 5)) == (sqrt(5) - 1)/4 assert cos(pi*Rational(3, 5)) == -cos(pi*Rational(2, 5)) assert cos(pi*Rational(4, 5)) == -cos(pi*Rational(1, 5)) assert cos(pi*Rational(6, 5)) == -cos(pi*Rational(1, 5)) assert cos(pi*Rational(8, 5)) == cos(pi*Rational(2, 5)) assert cos(pi*Rational(-1273, 5)) == -cos(pi*Rational(2, 5)) assert cos(pi/8) == sqrt((2 + sqrt(2))/4) assert cos(pi/12) == sqrt(2)/4 + sqrt(6)/4 assert cos(pi*Rational(5, 12)) == -sqrt(2)/4 + sqrt(6)/4 assert cos(pi*Rational(7, 12)) == sqrt(2)/4 - sqrt(6)/4 assert cos(pi*Rational(11, 12)) == -sqrt(2)/4 - sqrt(6)/4 assert cos(pi*Rational(104, 105)) == -cos(pi/105) assert cos(pi*Rational(106, 105)) == -cos(pi/105) assert cos(pi*Rational(-104, 105)) == -cos(pi/105) assert cos(pi*Rational(-106, 105)) == -cos(pi/105) assert cos(x*I) == cosh(x) assert cos(k*pi*I) == cosh(k*pi) assert cos(r).is_real is True assert cos(0, evaluate=False).is_algebraic assert cos(a).is_algebraic is None assert cos(na).is_algebraic is False q = Symbol('q', rational=True) assert cos(pi*q).is_algebraic assert cos(pi*Rational(2, 7)).is_algebraic assert cos(k*pi) == (-1)**k assert cos(2*k*pi) == 1 for d in list(range(1, 22)) + [60, 85]: for n in range(0, 2*d + 1): x = n*pi/d e = abs( float(cos(x)) - cos(float(x)) ) assert e < 1e-12 def test_issue_6190(): c = Float('123456789012345678901234567890.25', '') for cls in [sin, cos, tan, cot]: assert cls(c*pi) == cls(pi/4) assert cls(4.125*pi) == cls(pi/8) assert cls(4.7*pi) == cls((4.7 % 2)*pi) def test_cos_series(): assert cos(x).series(x, 0, 9) == \ 1 - x**2/2 + x**4/24 - x**6/720 + x**8/40320 + O(x**9) def test_cos_rewrite(): assert cos(x).rewrite(exp) == exp(I*x)/2 + exp(-I*x)/2 assert cos(x).rewrite(tan) == (1 - tan(x/2)**2)/(1 + tan(x/2)**2) assert cos(x).rewrite(cot) == -(1 - cot(x/2)**2)/(1 + cot(x/2)**2) assert cos(sinh(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, sinh(3)).n() assert cos(cosh(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cosh(3)).n() assert cos(tanh(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, tanh(3)).n() assert cos(coth(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, coth(3)).n() assert cos(sin(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, sin(3)).n() assert cos(cos(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cos(3)).n() assert cos(tan(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, tan(3)).n() assert cos(cot(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cot(3)).n() assert cos(log(x)).rewrite(Pow) == x**I/2 + x**-I/2 assert cos(x).rewrite(sec) == 1/sec(x) assert cos(x).rewrite(sin) == sin(x + pi/2, evaluate=False) assert cos(x).rewrite(csc) == 1/csc(-x + pi/2, evaluate=False) assert cos(sin(x)).rewrite(Pow) == cos(sin(x)) def test_cos_expansion(): assert cos(x + y).expand(trig=True) == cos(x)*cos(y) - sin(x)*sin(y) assert cos(x - y).expand(trig=True) == cos(x)*cos(y) + sin(x)*sin(y) assert cos(y - x).expand(trig=True) == cos(x)*cos(y) + sin(x)*sin(y) assert cos(2*x).expand(trig=True) == 2*cos(x)**2 - 1 assert cos(3*x).expand(trig=True) == 4*cos(x)**3 - 3*cos(x) assert cos(4*x).expand(trig=True) == 8*cos(x)**4 - 8*cos(x)**2 + 1 _test_extrig(cos, 2, 2*cos(1)**2 - 1) _test_extrig(cos, 3, 4*cos(1)**3 - 3*cos(1)) def test_cos_AccumBounds(): assert cos(AccumBounds(-oo, oo)) == AccumBounds(-1, 1) assert cos(AccumBounds(0, oo)) == AccumBounds(-1, 1) assert cos(AccumBounds(-oo, 0)) == AccumBounds(-1, 1) assert cos(AccumBounds(0, 2*S.Pi)) == AccumBounds(-1, 1) assert cos(AccumBounds(-S.Pi/3, S.Pi/4)) == AccumBounds(cos(-S.Pi/3), 1) assert cos(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(5, 4))) == AccumBounds(-1, cos(S.Pi*Rational(3, 4))) 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))) assert cos(AccumBounds(S.Pi/4, S.Pi/3)) == AccumBounds(cos(S.Pi/3), cos(S.Pi/4)) def test_cos_fdiff(): assert cos(x).fdiff() == -sin(x) raises(ArgumentIndexError, lambda: cos(x).fdiff(2)) def test_tan(): assert tan(nan) is nan assert tan(zoo) is nan assert tan(oo) == AccumBounds(-oo, oo) assert tan(oo) - tan(oo) == AccumBounds(-oo, oo) assert tan.nargs == FiniteSet(1) assert tan(oo*I) == I assert tan(-oo*I) == -I assert tan(0) == 0 assert tan(atan(x)) == x assert tan(asin(x)) == x / sqrt(1 - x**2) assert tan(acos(x)) == sqrt(1 - x**2) / x assert tan(acot(x)) == 1 / x assert tan(acsc(x)) == 1 / (sqrt(1 - 1 / x**2) * x) assert tan(asec(x)) == sqrt(1 - 1 / x**2) * x assert tan(atan2(y, x)) == y/x assert tan(pi*I) == tanh(pi)*I assert tan(-pi*I) == -tanh(pi)*I assert tan(-2*I) == -tanh(2)*I assert tan(pi) == 0 assert tan(-pi) == 0 assert tan(2*pi) == 0 assert tan(-2*pi) == 0 assert tan(-3*10**73*pi) == 0 assert tan(pi/2) is zoo assert tan(pi*Rational(3, 2)) is zoo assert tan(pi/3) == sqrt(3) assert tan(pi*Rational(-2, 3)) == sqrt(3) assert tan(pi/4) is S.One assert tan(-pi/4) is S.NegativeOne assert tan(pi*Rational(17, 4)) is S.One assert tan(pi*Rational(-3, 4)) is S.One assert tan(pi/5) == sqrt(5 - 2*sqrt(5)) assert tan(pi*Rational(2, 5)) == sqrt(5 + 2*sqrt(5)) assert tan(pi*Rational(18, 5)) == -sqrt(5 + 2*sqrt(5)) assert tan(pi*Rational(-16, 5)) == -sqrt(5 - 2*sqrt(5)) assert tan(pi/6) == 1/sqrt(3) assert tan(-pi/6) == -1/sqrt(3) assert tan(pi*Rational(7, 6)) == 1/sqrt(3) assert tan(pi*Rational(-5, 6)) == 1/sqrt(3) assert tan(pi/8) == -1 + sqrt(2) assert tan(pi*Rational(3, 8)) == 1 + sqrt(2) # issue 15959 assert tan(pi*Rational(5, 8)) == -1 - sqrt(2) assert tan(pi*Rational(7, 8)) == 1 - sqrt(2) assert tan(pi/10) == sqrt(1 - 2*sqrt(5)/5) assert tan(pi*Rational(3, 10)) == sqrt(1 + 2*sqrt(5)/5) assert tan(pi*Rational(17, 10)) == -sqrt(1 + 2*sqrt(5)/5) assert tan(pi*Rational(-31, 10)) == -sqrt(1 - 2*sqrt(5)/5) assert tan(pi/12) == -sqrt(3) + 2 assert tan(pi*Rational(5, 12)) == sqrt(3) + 2 assert tan(pi*Rational(7, 12)) == -sqrt(3) - 2 assert tan(pi*Rational(11, 12)) == sqrt(3) - 2 assert tan(pi/24).radsimp() == -2 - sqrt(3) + sqrt(2) + sqrt(6) assert tan(pi*Rational(5, 24)).radsimp() == -2 + sqrt(3) - sqrt(2) + sqrt(6) assert tan(pi*Rational(7, 24)).radsimp() == 2 - sqrt(3) - sqrt(2) + sqrt(6) assert tan(pi*Rational(11, 24)).radsimp() == 2 + sqrt(3) + sqrt(2) + sqrt(6) assert tan(pi*Rational(13, 24)).radsimp() == -2 - sqrt(3) - sqrt(2) - sqrt(6) assert tan(pi*Rational(17, 24)).radsimp() == -2 + sqrt(3) + sqrt(2) - sqrt(6) assert tan(pi*Rational(19, 24)).radsimp() == 2 - sqrt(3) + sqrt(2) - sqrt(6) assert tan(pi*Rational(23, 24)).radsimp() == 2 + sqrt(3) - sqrt(2) - sqrt(6) assert tan(x*I) == tanh(x)*I assert tan(k*pi) == 0 assert tan(17*k*pi) == 0 assert tan(k*pi*I) == tanh(k*pi)*I assert tan(r).is_real is None assert tan(r).is_extended_real is True assert tan(0, evaluate=False).is_algebraic assert tan(a).is_algebraic is None assert tan(na).is_algebraic is False assert tan(pi*Rational(10, 7)) == tan(pi*Rational(3, 7)) assert tan(pi*Rational(11, 7)) == -tan(pi*Rational(3, 7)) assert tan(pi*Rational(-11, 7)) == tan(pi*Rational(3, 7)) assert tan(pi*Rational(15, 14)) == tan(pi/14) assert tan(pi*Rational(-15, 14)) == -tan(pi/14) assert tan(r).is_finite is None assert tan(I*r).is_finite is True # https://github.com/sympy/sympy/issues/21177 f = tan(pi*(x + S(3)/2))/(3*x) assert f.as_leading_term(x) == -1/(3*pi*x**2) def test_tan_series(): assert tan(x).series(x, 0, 9) == \ x + x**3/3 + 2*x**5/15 + 17*x**7/315 + O(x**9) def test_tan_rewrite(): neg_exp, pos_exp = exp(-x*I), exp(x*I) assert tan(x).rewrite(exp) == I*(neg_exp - pos_exp)/(neg_exp + pos_exp) assert tan(x).rewrite(sin) == 2*sin(x)**2/sin(2*x) assert tan(x).rewrite(cos) == cos(x - S.Pi/2, evaluate=False)/cos(x) assert tan(x).rewrite(cot) == 1/cot(x) assert tan(sinh(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, sinh(3)).n() assert tan(cosh(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cosh(3)).n() assert tan(tanh(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, tanh(3)).n() assert tan(coth(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, coth(3)).n() assert tan(sin(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, sin(3)).n() assert tan(cos(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cos(3)).n() assert tan(tan(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, tan(3)).n() assert tan(cot(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cot(3)).n() assert tan(log(x)).rewrite(Pow) == I*(x**-I - x**I)/(x**-I + x**I) assert 0 == (cos(pi/34)*tan(pi/34) - sin(pi/34)).rewrite(pow) assert 0 == (cos(pi/17)*tan(pi/17) - sin(pi/17)).rewrite(pow) assert tan(pi/19).rewrite(pow) == tan(pi/19) assert tan(pi*Rational(8, 19)).rewrite(sqrt) == tan(pi*Rational(8, 19)) assert tan(x).rewrite(sec) == sec(x)/sec(x - pi/2, evaluate=False) assert tan(x).rewrite(csc) == csc(-x + pi/2, evaluate=False)/csc(x) assert tan(sin(x)).rewrite(Pow) == tan(sin(x)) assert tan(pi*Rational(2, 5), evaluate=False).rewrite(sqrt) == sqrt(sqrt(5)/8 + Rational(5, 8))/(Rational(-1, 4) + sqrt(5)/4) def test_tan_subs(): assert tan(x).subs(tan(x), y) == y assert tan(x).subs(x, y) == tan(y) assert tan(x).subs(x, S.Pi/2) is zoo assert tan(x).subs(x, S.Pi*Rational(3, 2)) is zoo def test_tan_expansion(): assert tan(x + y).expand(trig=True) == ((tan(x) + tan(y))/(1 - tan(x)*tan(y))).expand() assert tan(x - y).expand(trig=True) == ((tan(x) - tan(y))/(1 + tan(x)*tan(y))).expand() assert tan(x + y + z).expand(trig=True) == ( (tan(x) + tan(y) + tan(z) - tan(x)*tan(y)*tan(z))/ (1 - tan(x)*tan(y) - tan(x)*tan(z) - tan(y)*tan(z))).expand() assert 0 == tan(2*x).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 7))])*24 - 7 assert 0 == tan(3*x).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 5))])*55 - 37 assert 0 == tan(4*x - pi/4).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 5))])*239 - 1 _test_extrig(tan, 2, 2*tan(1)/(1 - tan(1)**2)) _test_extrig(tan, 3, (-tan(1)**3 + 3*tan(1))/(1 - 3*tan(1)**2)) def test_tan_AccumBounds(): assert tan(AccumBounds(-oo, oo)) == AccumBounds(-oo, oo) assert tan(AccumBounds(S.Pi/3, S.Pi*Rational(2, 3))) == AccumBounds(-oo, oo) assert tan(AccumBounds(S.Pi/6, S.Pi/3)) == AccumBounds(tan(S.Pi/6), tan(S.Pi/3)) def test_tan_fdiff(): assert tan(x).fdiff() == tan(x)**2 + 1 raises(ArgumentIndexError, lambda: tan(x).fdiff(2)) def test_cot(): assert cot(nan) is nan assert cot.nargs == FiniteSet(1) assert cot(oo*I) == -I assert cot(-oo*I) == I assert cot(zoo) is nan assert cot(0) is zoo assert cot(2*pi) is zoo assert cot(acot(x)) == x assert cot(atan(x)) == 1 / x assert cot(asin(x)) == sqrt(1 - x**2) / x assert cot(acos(x)) == x / sqrt(1 - x**2) assert cot(acsc(x)) == sqrt(1 - 1 / x**2) * x assert cot(asec(x)) == 1 / (sqrt(1 - 1 / x**2) * x) assert cot(atan2(y, x)) == x/y assert cot(pi*I) == -coth(pi)*I assert cot(-pi*I) == coth(pi)*I assert cot(-2*I) == coth(2)*I assert cot(pi) == cot(2*pi) == cot(3*pi) assert cot(-pi) == cot(-2*pi) == cot(-3*pi) assert cot(pi/2) == 0 assert cot(-pi/2) == 0 assert cot(pi*Rational(5, 2)) == 0 assert cot(pi*Rational(7, 2)) == 0 assert cot(pi/3) == 1/sqrt(3) assert cot(pi*Rational(-2, 3)) == 1/sqrt(3) assert cot(pi/4) is S.One assert cot(-pi/4) is S.NegativeOne assert cot(pi*Rational(17, 4)) is S.One assert cot(pi*Rational(-3, 4)) is S.One assert cot(pi/6) == sqrt(3) assert cot(-pi/6) == -sqrt(3) assert cot(pi*Rational(7, 6)) == sqrt(3) assert cot(pi*Rational(-5, 6)) == sqrt(3) assert cot(pi/8) == 1 + sqrt(2) assert cot(pi*Rational(3, 8)) == -1 + sqrt(2) assert cot(pi*Rational(5, 8)) == 1 - sqrt(2) assert cot(pi*Rational(7, 8)) == -1 - sqrt(2) assert cot(pi/12) == sqrt(3) + 2 assert cot(pi*Rational(5, 12)) == -sqrt(3) + 2 assert cot(pi*Rational(7, 12)) == sqrt(3) - 2 assert cot(pi*Rational(11, 12)) == -sqrt(3) - 2 assert cot(pi/24).radsimp() == sqrt(2) + sqrt(3) + 2 + sqrt(6) assert cot(pi*Rational(5, 24)).radsimp() == -sqrt(2) - sqrt(3) + 2 + sqrt(6) assert cot(pi*Rational(7, 24)).radsimp() == -sqrt(2) + sqrt(3) - 2 + sqrt(6) assert cot(pi*Rational(11, 24)).radsimp() == sqrt(2) - sqrt(3) - 2 + sqrt(6) assert cot(pi*Rational(13, 24)).radsimp() == -sqrt(2) + sqrt(3) + 2 - sqrt(6) assert cot(pi*Rational(17, 24)).radsimp() == sqrt(2) - sqrt(3) + 2 - sqrt(6) assert cot(pi*Rational(19, 24)).radsimp() == sqrt(2) + sqrt(3) - 2 - sqrt(6) assert cot(pi*Rational(23, 24)).radsimp() == -sqrt(2) - sqrt(3) - 2 - sqrt(6) assert cot(x*I) == -coth(x)*I assert cot(k*pi*I) == -coth(k*pi)*I assert cot(r).is_real is None assert cot(r).is_extended_real is True assert cot(a).is_algebraic is None assert cot(na).is_algebraic is False assert cot(pi*Rational(10, 7)) == cot(pi*Rational(3, 7)) assert cot(pi*Rational(11, 7)) == -cot(pi*Rational(3, 7)) assert cot(pi*Rational(-11, 7)) == cot(pi*Rational(3, 7)) assert cot(pi*Rational(39, 34)) == cot(pi*Rational(5, 34)) assert cot(pi*Rational(-41, 34)) == -cot(pi*Rational(7, 34)) assert cot(x).is_finite is None assert cot(r).is_finite is None i = Symbol('i', imaginary=True) assert cot(i).is_finite is True assert cot(x).subs(x, 3*pi) is zoo # https://github.com/sympy/sympy/issues/21177 f = cot(pi*(x + 4))/(3*x) assert f.as_leading_term(x) == 1/(3*pi*x**2) def test_tan_cot_sin_cos_evalf(): assert abs((tan(pi*Rational(8, 15))*cos(pi*Rational(8, 15))/sin(pi*Rational(8, 15)) - 1).evalf()) < 1e-14 assert abs((cot(pi*Rational(4, 15))*sin(pi*Rational(4, 15))/cos(pi*Rational(4, 15)) - 1).evalf()) < 1e-14 @XFAIL def test_tan_cot_sin_cos_ratsimp(): assert 1 == (tan(pi*Rational(8, 15))*cos(pi*Rational(8, 15))/sin(pi*Rational(8, 15))).ratsimp() assert 1 == (cot(pi*Rational(4, 15))*sin(pi*Rational(4, 15))/cos(pi*Rational(4, 15))).ratsimp() def test_cot_series(): assert cot(x).series(x, 0, 9) == \ 1/x - x/3 - x**3/45 - 2*x**5/945 - x**7/4725 + O(x**9) # issue 6210 assert cot(x**4 + x**5).series(x, 0, 1) == \ x**(-4) - 1/x**3 + x**(-2) - 1/x + 1 + O(x) assert cot(pi*(1-x)).series(x, 0, 3) == -1/(pi*x) + pi*x/3 + O(x**3) assert cot(x).taylor_term(0, x) == 1/x assert cot(x).taylor_term(2, x) is S.Zero assert cot(x).taylor_term(3, x) == -x**3/45 def test_cot_rewrite(): neg_exp, pos_exp = exp(-x*I), exp(x*I) assert cot(x).rewrite(exp) == I*(pos_exp + neg_exp)/(pos_exp - neg_exp) assert cot(x).rewrite(sin) == sin(2*x)/(2*(sin(x)**2)) assert cot(x).rewrite(cos) == cos(x)/cos(x - pi/2, evaluate=False) assert cot(x).rewrite(tan) == 1/tan(x) def check(func): z = cot(func(x)).rewrite(exp ) - cot(x).rewrite(exp).subs(x, func(x)) assert z.rewrite(exp).expand() == 0 check(sinh) check(cosh) check(tanh) check(coth) check(sin) check(cos) check(tan) assert cot(log(x)).rewrite(Pow) == -I*(x**-I + x**I)/(x**-I - x**I) assert cot(pi*Rational(4, 34)).rewrite(pow).ratsimp() == (cos(pi*Rational(4, 34))/sin(pi*Rational(4, 34))).rewrite(pow).ratsimp() assert cot(pi*Rational(4, 17)).rewrite(pow) == (cos(pi*Rational(4, 17))/sin(pi*Rational(4, 17))).rewrite(pow) assert cot(pi/19).rewrite(pow) == cot(pi/19) assert cot(pi/19).rewrite(sqrt) == cot(pi/19) assert cot(x).rewrite(sec) == sec(x - pi / 2, evaluate=False) / sec(x) assert cot(x).rewrite(csc) == csc(x) / csc(- x + pi / 2, evaluate=False) assert cot(sin(x)).rewrite(Pow) == cot(sin(x)) assert cot(pi*Rational(2, 5), evaluate=False).rewrite(sqrt) == (Rational(-1, 4) + sqrt(5)/4)/\ sqrt(sqrt(5)/8 + Rational(5, 8)) def test_cot_subs(): assert cot(x).subs(cot(x), y) == y assert cot(x).subs(x, y) == cot(y) assert cot(x).subs(x, 0) is zoo assert cot(x).subs(x, S.Pi) is zoo def test_cot_expansion(): assert cot(x + y).expand(trig=True).together() == ( (cot(x)*cot(y) - 1)/(cot(x) + cot(y))) assert cot(x - y).expand(trig=True).together() == ( cot(x)*cot(-y) - 1)/(cot(x) + cot(-y)) assert cot(x + y + z).expand(trig=True).together() == ( (cot(x)*cot(y)*cot(z) - cot(x) - cot(y) - cot(z))/ (-1 + cot(x)*cot(y) + cot(x)*cot(z) + cot(y)*cot(z))) assert cot(3*x).expand(trig=True).together() == ( (cot(x)**2 - 3)*cot(x)/(3*cot(x)**2 - 1)) assert cot(2*x).expand(trig=True) == cot(x)/2 - 1/(2*cot(x)) assert cot(3*x).expand(trig=True).together() == ( cot(x)**2 - 3)*cot(x)/(3*cot(x)**2 - 1) assert cot(4*x - pi/4).expand(trig=True).cancel() == ( -tan(x)**4 + 4*tan(x)**3 + 6*tan(x)**2 - 4*tan(x) - 1 )/(tan(x)**4 + 4*tan(x)**3 - 6*tan(x)**2 - 4*tan(x) + 1) _test_extrig(cot, 2, (-1 + cot(1)**2)/(2*cot(1))) _test_extrig(cot, 3, (-3*cot(1) + cot(1)**3)/(-1 + 3*cot(1)**2)) def test_cot_AccumBounds(): assert cot(AccumBounds(-oo, oo)) == AccumBounds(-oo, oo) assert cot(AccumBounds(-S.Pi/3, S.Pi/3)) == AccumBounds(-oo, oo) assert cot(AccumBounds(S.Pi/6, S.Pi/3)) == AccumBounds(cot(S.Pi/3), cot(S.Pi/6)) def test_cot_fdiff(): assert cot(x).fdiff() == -cot(x)**2 - 1 raises(ArgumentIndexError, lambda: cot(x).fdiff(2)) def test_sinc(): assert isinstance(sinc(x), sinc) s = Symbol('s', zero=True) assert sinc(s) is S.One assert sinc(S.Infinity) is S.Zero assert sinc(S.NegativeInfinity) is S.Zero assert sinc(S.NaN) is S.NaN assert sinc(S.ComplexInfinity) is S.NaN n = Symbol('n', integer=True, nonzero=True) assert sinc(n*pi) is S.Zero assert sinc(-n*pi) is S.Zero assert sinc(pi/2) == 2 / pi assert sinc(-pi/2) == 2 / pi assert sinc(pi*Rational(5, 2)) == 2 / (5*pi) assert sinc(pi*Rational(7, 2)) == -2 / (7*pi) assert sinc(-x) == sinc(x) assert sinc(x).diff(x) == cos(x)/x - sin(x)/x**2 assert sinc(x).diff(x) == (sin(x)/x).diff(x) assert sinc(x).diff(x, x) == (-sin(x) - 2*cos(x)/x + 2*sin(x)/x**2)/x assert sinc(x).diff(x, x) == (sin(x)/x).diff(x, x) assert limit(sinc(x).diff(x), x, 0) == 0 assert limit(sinc(x).diff(x, x), x, 0) == -S(1)/3 # https://github.com/sympy/sympy/issues/11402 # # assert sinc(x).diff(x) == Piecewise(((x*cos(x) - sin(x)) / x**2, Ne(x, 0)), (0, True)) # # assert sinc(x).diff(x).equals(sinc(x).rewrite(sin).diff(x)) # # assert sinc(x).diff(x).subs(x, 0) is S.Zero assert sinc(x).series() == 1 - x**2/6 + x**4/120 + O(x**6) assert sinc(x).rewrite(jn) == jn(0, x) assert sinc(x).rewrite(sin) == Piecewise((sin(x)/x, Ne(x, 0)), (1, True)) assert sinc(pi, evaluate=False).is_zero is True assert sinc(0, evaluate=False).is_zero is False assert sinc(n*pi, evaluate=False).is_zero is True assert sinc(x).is_zero is None xr = Symbol('xr', real=True, nonzero=True) assert sinc(x).is_real is None assert sinc(xr).is_real is True assert sinc(I*xr).is_real is True assert sinc(I*100).is_real is True assert sinc(x).is_finite is None assert sinc(xr).is_finite is True def test_asin(): assert asin(nan) is nan assert asin.nargs == FiniteSet(1) assert asin(oo) == -I*oo assert asin(-oo) == I*oo assert asin(zoo) is zoo # Note: asin(-x) = - asin(x) assert asin(0) == 0 assert asin(1) == pi/2 assert asin(-1) == -pi/2 assert asin(sqrt(3)/2) == pi/3 assert asin(-sqrt(3)/2) == -pi/3 assert asin(sqrt(2)/2) == pi/4 assert asin(-sqrt(2)/2) == -pi/4 assert asin(sqrt((5 - sqrt(5))/8)) == pi/5 assert asin(-sqrt((5 - sqrt(5))/8)) == -pi/5 assert asin(S.Half) == pi/6 assert asin(Rational(-1, 2)) == -pi/6 assert asin((sqrt(2 - sqrt(2)))/2) == pi/8 assert asin(-(sqrt(2 - sqrt(2)))/2) == -pi/8 assert asin((sqrt(5) - 1)/4) == pi/10 assert asin(-(sqrt(5) - 1)/4) == -pi/10 assert asin((sqrt(3) - 1)/sqrt(2**3)) == pi/12 assert asin(-(sqrt(3) - 1)/sqrt(2**3)) == -pi/12 # check round-trip for exact values: for d in [5, 6, 8, 10, 12]: for n in range(-(d//2), d//2 + 1): if gcd(n, d) == 1: assert asin(sin(n*pi/d)) == n*pi/d assert asin(x).diff(x) == 1/sqrt(1 - x**2) assert asin(1/x).as_leading_term(x) == I*log(1/x) assert asin(0.2, evaluate=False).is_real is True assert asin(-2).is_real is False assert asin(r).is_real is None assert asin(-2*I) == -I*asinh(2) assert asin(Rational(1, 7), evaluate=False).is_positive is True assert asin(Rational(-1, 7), evaluate=False).is_positive is False assert asin(p).is_positive is None assert asin(sin(Rational(7, 2))) == Rational(-7, 2) + pi assert asin(sin(Rational(-7, 4))) == Rational(7, 4) - pi assert unchanged(asin, cos(x)) def test_asin_series(): assert asin(x).series(x, 0, 9) == \ x + x**3/6 + 3*x**5/40 + 5*x**7/112 + O(x**9) t5 = asin(x).taylor_term(5, x) assert t5 == 3*x**5/40 assert asin(x).taylor_term(7, x, t5, 0) == 5*x**7/112 def test_asin_rewrite(): assert asin(x).rewrite(log) == -I*log(I*x + sqrt(1 - x**2)) assert asin(x).rewrite(atan) == 2*atan(x/(1 + sqrt(1 - x**2))) assert asin(x).rewrite(acos) == S.Pi/2 - acos(x) assert asin(x).rewrite(acot) == 2*acot((sqrt(-x**2 + 1) + 1)/x) assert asin(x).rewrite(asec) == -asec(1/x) + pi/2 assert asin(x).rewrite(acsc) == acsc(1/x) def test_asin_fdiff(): assert asin(x).fdiff() == 1/sqrt(1 - x**2) raises(ArgumentIndexError, lambda: asin(x).fdiff(2)) def test_acos(): assert acos(nan) is nan assert acos(zoo) is zoo assert acos.nargs == FiniteSet(1) assert acos(oo) == I*oo assert acos(-oo) == -I*oo # Note: acos(-x) = pi - acos(x) assert acos(0) == pi/2 assert acos(S.Half) == pi/3 assert acos(Rational(-1, 2)) == pi*Rational(2, 3) assert acos(1) == 0 assert acos(-1) == pi assert acos(sqrt(2)/2) == pi/4 assert acos(-sqrt(2)/2) == pi*Rational(3, 4) # check round-trip for exact values: for d in [5, 6, 8, 10, 12]: for num in range(d): if gcd(num, d) == 1: assert acos(cos(num*pi/d)) == num*pi/d assert acos(2*I) == pi/2 - asin(2*I) assert acos(x).diff(x) == -1/sqrt(1 - x**2) assert acos(1/x).as_leading_term(x) == I*log(1/x) assert acos(0.2).is_real is True assert acos(-2).is_real is False assert acos(r).is_real is None assert acos(Rational(1, 7), evaluate=False).is_positive is True assert acos(Rational(-1, 7), evaluate=False).is_positive is True assert acos(Rational(3, 2), evaluate=False).is_positive is False assert acos(p).is_positive is None assert acos(2 + p).conjugate() != acos(10 + p) assert acos(-3 + n).conjugate() != acos(-3 + n) assert acos(Rational(1, 3)).conjugate() == acos(Rational(1, 3)) assert acos(Rational(-1, 3)).conjugate() == acos(Rational(-1, 3)) assert acos(p + n*I).conjugate() == acos(p - n*I) assert acos(z).conjugate() != acos(conjugate(z)) def test_acos_series(): assert acos(x).series(x, 0, 8) == \ pi/2 - x - x**3/6 - 3*x**5/40 - 5*x**7/112 + O(x**8) assert acos(x).series(x, 0, 8) == pi/2 - asin(x).series(x, 0, 8) t5 = acos(x).taylor_term(5, x) assert t5 == -3*x**5/40 assert acos(x).taylor_term(7, x, t5, 0) == -5*x**7/112 assert acos(x).taylor_term(0, x) == pi/2 assert acos(x).taylor_term(2, x) is S.Zero def test_acos_rewrite(): assert acos(x).rewrite(log) == pi/2 + I*log(I*x + sqrt(1 - x**2)) assert acos(x).rewrite(atan) == \ atan(sqrt(1 - x**2)/x) + (pi/2)*(1 - x*sqrt(1/x**2)) assert acos(0).rewrite(atan) == S.Pi/2 assert acos(0.5).rewrite(atan) == acos(0.5).rewrite(log) assert acos(x).rewrite(asin) == S.Pi/2 - asin(x) assert acos(x).rewrite(acot) == -2*acot((sqrt(-x**2 + 1) + 1)/x) + pi/2 assert acos(x).rewrite(asec) == asec(1/x) assert acos(x).rewrite(acsc) == -acsc(1/x) + pi/2 def test_acos_fdiff(): assert acos(x).fdiff() == -1/sqrt(1 - x**2) raises(ArgumentIndexError, lambda: acos(x).fdiff(2)) def test_atan(): assert atan(nan) is nan assert atan.nargs == FiniteSet(1) assert atan(oo) == pi/2 assert atan(-oo) == -pi/2 assert atan(zoo) == AccumBounds(-pi/2, pi/2) assert atan(0) == 0 assert atan(1) == pi/4 assert atan(sqrt(3)) == pi/3 assert atan(-(1 + sqrt(2))) == pi*Rational(-3, 8) assert atan(sqrt(5 - 2 * sqrt(5))) == pi/5 assert atan(-sqrt(1 - 2 * sqrt(5)/ 5)) == -pi/10 assert atan(sqrt(1 + 2 * sqrt(5) / 5)) == pi*Rational(3, 10) assert atan(-2 + sqrt(3)) == -pi/12 assert atan(2 + sqrt(3)) == pi*Rational(5, 12) assert atan(-2 - sqrt(3)) == pi*Rational(-5, 12) # check round-trip for exact values: for d in [5, 6, 8, 10, 12]: for num in range(-(d//2), d//2 + 1): if gcd(num, d) == 1: assert atan(tan(num*pi/d)) == num*pi/d assert atan(oo) == pi/2 assert atan(x).diff(x) == 1/(1 + x**2) assert atan(1/x).as_leading_term(x) == pi/2 assert atan(r).is_real is True assert atan(-2*I) == -I*atanh(2) assert unchanged(atan, cot(x)) assert atan(cot(Rational(1, 4))) == Rational(-1, 4) + pi/2 assert acot(Rational(1, 4)).is_rational is False for s in (x, p, n, np, nn, nz, ep, en, enp, enn, enz): if s.is_real or s.is_extended_real is None: assert s.is_nonzero is atan(s).is_nonzero assert s.is_positive is atan(s).is_positive assert s.is_negative is atan(s).is_negative assert s.is_nonpositive is atan(s).is_nonpositive assert s.is_nonnegative is atan(s).is_nonnegative else: assert s.is_extended_nonzero is atan(s).is_nonzero assert s.is_extended_positive is atan(s).is_positive assert s.is_extended_negative is atan(s).is_negative assert s.is_extended_nonpositive is atan(s).is_nonpositive assert s.is_extended_nonnegative is atan(s).is_nonnegative assert s.is_extended_nonzero is atan(s).is_extended_nonzero assert s.is_extended_positive is atan(s).is_extended_positive assert s.is_extended_negative is atan(s).is_extended_negative assert s.is_extended_nonpositive is atan(s).is_extended_nonpositive assert s.is_extended_nonnegative is atan(s).is_extended_nonnegative def test_atan_rewrite(): assert atan(x).rewrite(log) == I*(log(1 - I*x)-log(1 + I*x))/2 assert atan(x).rewrite(asin) == (-asin(1/sqrt(x**2 + 1)) + pi/2)*sqrt(x**2)/x assert atan(x).rewrite(acos) == sqrt(x**2)*acos(1/sqrt(x**2 + 1))/x assert atan(x).rewrite(acot) == acot(1/x) assert atan(x).rewrite(asec) == sqrt(x**2)*asec(sqrt(x**2 + 1))/x assert atan(x).rewrite(acsc) == (-acsc(sqrt(x**2 + 1)) + pi/2)*sqrt(x**2)/x assert atan(-5*I).evalf() == atan(x).rewrite(log).evalf(subs={x:-5*I}) assert atan(5*I).evalf() == atan(x).rewrite(log).evalf(subs={x:5*I}) def test_atan_fdiff(): assert atan(x).fdiff() == 1/(x**2 + 1) raises(ArgumentIndexError, lambda: atan(x).fdiff(2)) def test_atan2(): assert atan2.nargs == FiniteSet(2) assert atan2(0, 0) is S.NaN assert atan2(0, 1) == 0 assert atan2(1, 1) == pi/4 assert atan2(1, 0) == pi/2 assert atan2(1, -1) == pi*Rational(3, 4) assert atan2(0, -1) == pi assert atan2(-1, -1) == pi*Rational(-3, 4) assert atan2(-1, 0) == -pi/2 assert atan2(-1, 1) == -pi/4 i = symbols('i', imaginary=True) r = symbols('r', real=True) eq = atan2(r, i) ans = -I*log((i + I*r)/sqrt(i**2 + r**2)) reps = ((r, 2), (i, I)) assert eq.subs(reps) == ans.subs(reps) x = Symbol('x', negative=True) y = Symbol('y', negative=True) assert atan2(y, x) == atan(y/x) - pi y = Symbol('y', nonnegative=True) assert atan2(y, x) == atan(y/x) + pi y = Symbol('y') assert atan2(y, x) == atan2(y, x, evaluate=False) u = Symbol("u", positive=True) assert atan2(0, u) == 0 u = Symbol("u", negative=True) assert atan2(0, u) == pi assert atan2(y, oo) == 0 assert atan2(y, -oo)== 2*pi*Heaviside(re(y), S.Half) - pi assert atan2(y, x).rewrite(log) == -I*log((x + I*y)/sqrt(x**2 + y**2)) assert atan2(0, 0) is S.NaN ex = atan2(y, x) - arg(x + I*y) assert ex.subs({x:2, y:3}).rewrite(arg) == 0 assert ex.subs({x:2, y:3*I}).rewrite(arg) == -pi - I*log(sqrt(5)*I/5) assert ex.subs({x:2*I, y:3}).rewrite(arg) == -pi/2 - I*log(sqrt(5)*I) assert ex.subs({x:2*I, y:3*I}).rewrite(arg) == -pi + atan(Rational(2, 3)) + atan(Rational(3, 2)) i = symbols('i', imaginary=True) r = symbols('r', real=True) e = atan2(i, r) rewrite = e.rewrite(arg) reps = {i: I, r: -2} assert rewrite == -I*log(abs(I*i + r)/sqrt(abs(i**2 + r**2))) + arg((I*i + r)/sqrt(i**2 + r**2)) assert (e - rewrite).subs(reps).equals(0) assert atan2(0, x).rewrite(atan) == Piecewise((pi, re(x) < 0), (0, Ne(x, 0)), (nan, True)) assert atan2(0, r).rewrite(atan) == Piecewise((pi, r < 0), (0, Ne(r, 0)), (S.NaN, True)) assert atan2(0, i),rewrite(atan) == 0 assert atan2(0, r + i).rewrite(atan) == Piecewise((pi, r < 0), (0, True)) assert atan2(y, x).rewrite(atan) == Piecewise( (2*atan(y/(x + sqrt(x**2 + y**2))), Ne(y, 0)), (pi, re(x) < 0), (0, (re(x) > 0) | Ne(im(x), 0)), (nan, True)) assert conjugate(atan2(x, y)) == atan2(conjugate(x), conjugate(y)) assert diff(atan2(y, x), x) == -y/(x**2 + y**2) assert diff(atan2(y, x), y) == x/(x**2 + y**2) assert simplify(diff(atan2(y, x).rewrite(log), x)) == -y/(x**2 + y**2) assert simplify(diff(atan2(y, x).rewrite(log), y)) == x/(x**2 + y**2) assert str(atan2(1, 2).evalf(5)) == '0.46365' raises(ArgumentIndexError, lambda: atan2(x, y).fdiff(3)) def test_issue_17461(): class A(Symbol): is_extended_real = True def _eval_evalf(self, prec): return Float(5.0) x = A('X') y = A('Y') assert abs(atan2(x, y).evalf() - 0.785398163397448) <= 1e-10 def test_acot(): assert acot(nan) is nan assert acot.nargs == FiniteSet(1) assert acot(-oo) == 0 assert acot(oo) == 0 assert acot(zoo) == 0 assert acot(1) == pi/4 assert acot(0) == pi/2 assert acot(sqrt(3)/3) == pi/3 assert acot(1/sqrt(3)) == pi/3 assert acot(-1/sqrt(3)) == -pi/3 assert acot(x).diff(x) == -1/(1 + x**2) assert acot(1/x).as_leading_term(x) == x assert acot(r).is_extended_real is True assert acot(I*pi) == -I*acoth(pi) assert acot(-2*I) == I*acoth(2) assert acot(x).is_positive is None assert acot(n).is_positive is False assert acot(p).is_positive is True assert acot(I).is_positive is False assert acot(Rational(1, 4)).is_rational is False assert unchanged(acot, cot(x)) assert unchanged(acot, tan(x)) assert acot(cot(Rational(1, 4))) == Rational(1, 4) assert acot(tan(Rational(-1, 4))) == Rational(1, 4) - pi/2 def test_acot_rewrite(): assert acot(x).rewrite(log) == I*(log(1 - I/x)-log(1 + I/x))/2 assert acot(x).rewrite(asin) == x*(-asin(sqrt(-x**2)/sqrt(-x**2 - 1)) + pi/2)*sqrt(x**(-2)) assert acot(x).rewrite(acos) == x*sqrt(x**(-2))*acos(sqrt(-x**2)/sqrt(-x**2 - 1)) assert acot(x).rewrite(atan) == atan(1/x) assert acot(x).rewrite(asec) == x*sqrt(x**(-2))*asec(sqrt((x**2 + 1)/x**2)) assert acot(x).rewrite(acsc) == x*(-acsc(sqrt((x**2 + 1)/x**2)) + pi/2)*sqrt(x**(-2)) assert acot(-I/5).evalf() == acot(x).rewrite(log).evalf(subs={x:-I/5}) assert acot(I/5).evalf() == acot(x).rewrite(log).evalf(subs={x:I/5}) def test_acot_fdiff(): assert acot(x).fdiff() == -1/(x**2 + 1) raises(ArgumentIndexError, lambda: acot(x).fdiff(2)) def test_attributes(): assert sin(x).args == (x,) def test_sincos_rewrite(): assert sin(pi/2 - x) == cos(x) assert sin(pi - x) == sin(x) assert cos(pi/2 - x) == sin(x) assert cos(pi - x) == -cos(x) def _check_even_rewrite(func, arg): """Checks that the expr has been rewritten using f(-x) -> f(x) arg : -x """ return func(arg).args[0] == -arg def _check_odd_rewrite(func, arg): """Checks that the expr has been rewritten using f(-x) -> -f(x) arg : -x """ return func(arg).func.is_Mul def _check_no_rewrite(func, arg): """Checks that the expr is not rewritten""" return func(arg).args[0] == arg def test_evenodd_rewrite(): a = cos(2) # negative b = sin(1) # positive even = [cos] odd = [sin, tan, cot, asin, atan, acot] with_minus = [-1, -2**1024 * E, -pi/105, -x*y, -x - y] for func in even: for expr in with_minus: assert _check_even_rewrite(func, expr) assert _check_no_rewrite(func, a*b) assert func( x - y) == func(y - x) # it doesn't matter which form is canonical for func in odd: for expr in with_minus: assert _check_odd_rewrite(func, expr) assert _check_no_rewrite(func, a*b) assert func( x - y) == -func(y - x) # it doesn't matter which form is canonical def test_issue_4547(): assert sin(x).rewrite(cot) == 2*cot(x/2)/(1 + cot(x/2)**2) assert cos(x).rewrite(cot) == -(1 - cot(x/2)**2)/(1 + cot(x/2)**2) assert tan(x).rewrite(cot) == 1/cot(x) assert cot(x).fdiff() == -1 - cot(x)**2 def test_as_leading_term_issue_5272(): assert sin(x).as_leading_term(x) == x assert cos(x).as_leading_term(x) == 1 assert tan(x).as_leading_term(x) == x assert cot(x).as_leading_term(x) == 1/x assert asin(x).as_leading_term(x) == x assert acos(x).as_leading_term(x) == pi/2 assert atan(x).as_leading_term(x) == x assert acot(x).as_leading_term(x) == pi/2 def test_leading_terms(): assert sin(1/x).as_leading_term(x) == AccumBounds(-1, 1) assert sin(S.Half).as_leading_term(x) == sin(S.Half) assert cos(1/x).as_leading_term(x) == AccumBounds(-1, 1) assert cos(S.Half).as_leading_term(x) == cos(S.Half) for func in [tan, cot]: for a in (1/x, S.Half): eq = func(a) assert eq.as_leading_term(x) == eq # https://github.com/sympy/sympy/issues/21038 f = sin(pi*(x + 4))/(3*x) assert f.as_leading_term(x) == pi/3 def test_atan2_expansion(): assert cancel(atan2(x**2, x + 1).diff(x) - atan(x**2/(x + 1)).diff(x)) == 0 assert cancel(atan(y/x).series(y, 0, 5) - atan2(y, x).series(y, 0, 5) + atan2(0, x) - atan(0)) == O(y**5) assert cancel(atan(y/x).series(x, 1, 4) - atan2(y, x).series(x, 1, 4) + atan2(y, 1) - atan(y)) == O((x - 1)**4, (x, 1)) assert cancel(atan((y + x)/x).series(x, 1, 3) - atan2(y + x, x).series(x, 1, 3) + atan2(1 + y, 1) - atan(1 + y)) == O((x - 1)**3, (x, 1)) assert Matrix([atan2(y, x)]).jacobian([y, x]) == \ Matrix([[x/(y**2 + x**2), -y/(y**2 + x**2)]]) def test_aseries(): def t(n, v, d, e): assert abs( n(1/v).evalf() - n(1/x).series(x, dir=d).removeO().subs(x, v)) < e t(atan, 0.1, '+', 1e-5) t(atan, -0.1, '-', 1e-5) t(acot, 0.1, '+', 1e-5) t(acot, -0.1, '-', 1e-5) def test_issue_4420(): i = Symbol('i', integer=True) e = Symbol('e', even=True) o = Symbol('o', odd=True) # unknown parity for variable assert cos(4*i*pi) == 1 assert sin(4*i*pi) == 0 assert tan(4*i*pi) == 0 assert cot(4*i*pi) is zoo assert cos(3*i*pi) == cos(pi*i) # +/-1 assert sin(3*i*pi) == 0 assert tan(3*i*pi) == 0 assert cot(3*i*pi) is zoo assert cos(4.0*i*pi) == 1 assert sin(4.0*i*pi) == 0 assert tan(4.0*i*pi) == 0 assert cot(4.0*i*pi) is zoo assert cos(3.0*i*pi) == cos(pi*i) # +/-1 assert sin(3.0*i*pi) == 0 assert tan(3.0*i*pi) == 0 assert cot(3.0*i*pi) is zoo assert cos(4.5*i*pi) == cos(0.5*pi*i) assert sin(4.5*i*pi) == sin(0.5*pi*i) assert tan(4.5*i*pi) == tan(0.5*pi*i) assert cot(4.5*i*pi) == cot(0.5*pi*i) # parity of variable is known assert cos(4*e*pi) == 1 assert sin(4*e*pi) == 0 assert tan(4*e*pi) == 0 assert cot(4*e*pi) is zoo assert cos(3*e*pi) == 1 assert sin(3*e*pi) == 0 assert tan(3*e*pi) == 0 assert cot(3*e*pi) is zoo assert cos(4.0*e*pi) == 1 assert sin(4.0*e*pi) == 0 assert tan(4.0*e*pi) == 0 assert cot(4.0*e*pi) is zoo assert cos(3.0*e*pi) == 1 assert sin(3.0*e*pi) == 0 assert tan(3.0*e*pi) == 0 assert cot(3.0*e*pi) is zoo assert cos(4.5*e*pi) == cos(0.5*pi*e) assert sin(4.5*e*pi) == sin(0.5*pi*e) assert tan(4.5*e*pi) == tan(0.5*pi*e) assert cot(4.5*e*pi) == cot(0.5*pi*e) assert cos(4*o*pi) == 1 assert sin(4*o*pi) == 0 assert tan(4*o*pi) == 0 assert cot(4*o*pi) is zoo assert cos(3*o*pi) == -1 assert sin(3*o*pi) == 0 assert tan(3*o*pi) == 0 assert cot(3*o*pi) is zoo assert cos(4.0*o*pi) == 1 assert sin(4.0*o*pi) == 0 assert tan(4.0*o*pi) == 0 assert cot(4.0*o*pi) is zoo assert cos(3.0*o*pi) == -1 assert sin(3.0*o*pi) == 0 assert tan(3.0*o*pi) == 0 assert cot(3.0*o*pi) is zoo assert cos(4.5*o*pi) == cos(0.5*pi*o) assert sin(4.5*o*pi) == sin(0.5*pi*o) assert tan(4.5*o*pi) == tan(0.5*pi*o) assert cot(4.5*o*pi) == cot(0.5*pi*o) # x could be imaginary assert cos(4*x*pi) == cos(4*pi*x) assert sin(4*x*pi) == sin(4*pi*x) assert tan(4*x*pi) == tan(4*pi*x) assert cot(4*x*pi) == cot(4*pi*x) assert cos(3*x*pi) == cos(3*pi*x) assert sin(3*x*pi) == sin(3*pi*x) assert tan(3*x*pi) == tan(3*pi*x) assert cot(3*x*pi) == cot(3*pi*x) assert cos(4.0*x*pi) == cos(4.0*pi*x) assert sin(4.0*x*pi) == sin(4.0*pi*x) assert tan(4.0*x*pi) == tan(4.0*pi*x) assert cot(4.0*x*pi) == cot(4.0*pi*x) assert cos(3.0*x*pi) == cos(3.0*pi*x) assert sin(3.0*x*pi) == sin(3.0*pi*x) assert tan(3.0*x*pi) == tan(3.0*pi*x) assert cot(3.0*x*pi) == cot(3.0*pi*x) assert cos(4.5*x*pi) == cos(4.5*pi*x) assert sin(4.5*x*pi) == sin(4.5*pi*x) assert tan(4.5*x*pi) == tan(4.5*pi*x) assert cot(4.5*x*pi) == cot(4.5*pi*x) def test_inverses(): raises(AttributeError, lambda: sin(x).inverse()) raises(AttributeError, lambda: cos(x).inverse()) assert tan(x).inverse() == atan assert cot(x).inverse() == acot raises(AttributeError, lambda: csc(x).inverse()) raises(AttributeError, lambda: sec(x).inverse()) assert asin(x).inverse() == sin assert acos(x).inverse() == cos assert atan(x).inverse() == tan assert acot(x).inverse() == cot def test_real_imag(): a, b = symbols('a b', real=True) z = a + b*I for deep in [True, False]: assert sin( z).as_real_imag(deep=deep) == (sin(a)*cosh(b), cos(a)*sinh(b)) assert cos( z).as_real_imag(deep=deep) == (cos(a)*cosh(b), -sin(a)*sinh(b)) assert tan(z).as_real_imag(deep=deep) == (sin(2*a)/(cos(2*a) + cosh(2*b)), sinh(2*b)/(cos(2*a) + cosh(2*b))) assert cot(z).as_real_imag(deep=deep) == (-sin(2*a)/(cos(2*a) - cosh(2*b)), sinh(2*b)/(cos(2*a) - cosh(2*b))) assert sin(a).as_real_imag(deep=deep) == (sin(a), 0) assert cos(a).as_real_imag(deep=deep) == (cos(a), 0) assert tan(a).as_real_imag(deep=deep) == (tan(a), 0) assert cot(a).as_real_imag(deep=deep) == (cot(a), 0) @XFAIL def test_sin_cos_with_infinity(): # Test for issue 5196 # https://github.com/sympy/sympy/issues/5196 assert sin(oo) is S.NaN assert cos(oo) is S.NaN @slow def test_sincos_rewrite_sqrt(): # equivalent to testing rewrite(pow) for p in [1, 3, 5, 17]: for t in [1, 8]: n = t*p # The vertices `exp(i*pi/n)` of a regular `n`-gon can # be expressed by means of nested square roots if and # only if `n` is a product of Fermat primes, `p`, and # powers of 2, `t'. The code aims to check all vertices # not belonging to an `m`-gon for `m < n`(`gcd(i, n) == 1`). # For large `n` this makes the test too slow, therefore # the vertices are limited to those of index `i < 10`. for i in range(1, min((n + 1)//2 + 1, 10)): if 1 == gcd(i, n): x = i*pi/n s1 = sin(x).rewrite(sqrt) c1 = cos(x).rewrite(sqrt) assert not s1.has(cos, sin), "fails for %d*pi/%d" % (i, n) assert not c1.has(cos, sin), "fails for %d*pi/%d" % (i, n) assert 1e-3 > abs(sin(x.evalf(5)) - s1.evalf(2)), "fails for %d*pi/%d" % (i, n) assert 1e-3 > abs(cos(x.evalf(5)) - c1.evalf(2)), "fails for %d*pi/%d" % (i, n) assert cos(pi/14).rewrite(sqrt) == sqrt(cos(pi/7)/2 + S.Half) assert cos(pi/257).rewrite(sqrt).evalf(64) == cos(pi/257).evalf(64) assert cos(pi*Rational(-15, 2)/11, evaluate=False).rewrite( sqrt) == -sqrt(-cos(pi*Rational(4, 11))/2 + S.Half) assert cos(Mul(2, pi, S.Half, evaluate=False), evaluate=False).rewrite( sqrt) == -1 e = cos(pi/3/17) # don't use pi/15 since that is caught at instantiation a = ( -3*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17) + 17)/64 - 3*sqrt(34)*sqrt(sqrt(17) + 17)/128 - sqrt(sqrt(17) + 17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 - sqrt(-sqrt(17) + 17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/128 - Rational(1, 32) + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 + 3*sqrt(2)*sqrt(sqrt(17) + 17)/128 + sqrt(34)*sqrt(-sqrt(17) + 17)/128 + 13*sqrt(2)*sqrt(-sqrt(17) + 17)/128 + sqrt(17)*sqrt(-sqrt(17) + 17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/128 + 5*sqrt(17)/32 + sqrt(3)*sqrt(-sqrt(2)*sqrt(sqrt(17) + 17)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/8 - 5*sqrt(2)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 - 3*sqrt(2)*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/32 + sqrt(34)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 + sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/2 + S.Half + sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + sqrt(34)*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/32)/2) assert e.rewrite(sqrt) == a assert e.n() == a.n() # coverage of fermatCoords: multiplicity > 1; the following could be # different but that portion of the code should be tested in some way assert cos(pi/9/17).rewrite(sqrt) == \ sin(pi/9)*sin(pi*Rational(2, 17)) + cos(pi/9)*cos(pi*Rational(2, 17)) @slow def test_tancot_rewrite_sqrt(): # equivalent to testing rewrite(pow) for p in [1, 3, 5, 17]: for t in [1, 8]: n = t*p for i in range(1, min((n + 1)//2 + 1, 10)): if 1 == gcd(i, n): x = i*pi/n if 2*i != n and 3*i != 2*n: t1 = tan(x).rewrite(sqrt) assert not t1.has(cot, tan), "fails for %d*pi/%d" % (i, n) assert 1e-3 > abs( tan(x.evalf(7)) - t1.evalf(4) ), "fails for %d*pi/%d" % (i, n) if i != 0 and i != n: c1 = cot(x).rewrite(sqrt) assert not c1.has(cot, tan), "fails for %d*pi/%d" % (i, n) assert 1e-3 > abs( cot(x.evalf(7)) - c1.evalf(4) ), "fails for %d*pi/%d" % (i, n) def test_sec(): x = symbols('x', real=True) z = symbols('z') assert sec.nargs == FiniteSet(1) assert sec(zoo) is nan assert sec(0) == 1 assert sec(pi) == -1 assert sec(pi/2) is zoo assert sec(-pi/2) is zoo assert sec(pi/6) == 2*sqrt(3)/3 assert sec(pi/3) == 2 assert sec(pi*Rational(5, 2)) is zoo assert sec(pi*Rational(9, 7)) == -sec(pi*Rational(2, 7)) assert sec(pi*Rational(3, 4)) == -sqrt(2) # issue 8421 assert sec(I) == 1/cosh(1) assert sec(x*I) == 1/cosh(x) assert sec(-x) == sec(x) assert sec(asec(x)) == x assert sec(z).conjugate() == sec(conjugate(z)) assert (sec(z).as_real_imag() == (cos(re(z))*cosh(im(z))/(sin(re(z))**2*sinh(im(z))**2 + cos(re(z))**2*cosh(im(z))**2), sin(re(z))*sinh(im(z))/(sin(re(z))**2*sinh(im(z))**2 + cos(re(z))**2*cosh(im(z))**2))) assert sec(x).expand(trig=True) == 1/cos(x) assert sec(2*x).expand(trig=True) == 1/(2*cos(x)**2 - 1) assert sec(x).is_extended_real == True assert sec(z).is_real == None assert sec(a).is_algebraic is None assert sec(na).is_algebraic is False assert sec(x).as_leading_term() == sec(x) assert sec(0, evaluate=False).is_finite == True assert sec(x).is_finite == None assert sec(pi/2, evaluate=False).is_finite == False assert series(sec(x), x, x0=0, n=6) == 1 + x**2/2 + 5*x**4/24 + O(x**6) # https://github.com/sympy/sympy/issues/7166 assert series(sqrt(sec(x))) == 1 + x**2/4 + 7*x**4/96 + O(x**6) # https://github.com/sympy/sympy/issues/7167 assert (series(sqrt(sec(x)), x, x0=pi*3/2, n=4) == 1/sqrt(x - pi*Rational(3, 2)) + (x - pi*Rational(3, 2))**Rational(3, 2)/12 + (x - pi*Rational(3, 2))**Rational(7, 2)/160 + O((x - pi*Rational(3, 2))**4, (x, pi*Rational(3, 2)))) assert sec(x).diff(x) == tan(x)*sec(x) # Taylor Term checks assert sec(z).taylor_term(4, z) == 5*z**4/24 assert sec(z).taylor_term(6, z) == 61*z**6/720 assert sec(z).taylor_term(5, z) == 0 def test_sec_rewrite(): assert sec(x).rewrite(exp) == 1/(exp(I*x)/2 + exp(-I*x)/2) assert sec(x).rewrite(cos) == 1/cos(x) assert sec(x).rewrite(tan) == (tan(x/2)**2 + 1)/(-tan(x/2)**2 + 1) assert sec(x).rewrite(pow) == sec(x) assert sec(x).rewrite(sqrt) == sec(x) assert sec(z).rewrite(cot) == (cot(z/2)**2 + 1)/(cot(z/2)**2 - 1) assert sec(x).rewrite(sin) == 1 / sin(x + pi / 2, evaluate=False) assert sec(x).rewrite(tan) == (tan(x / 2)**2 + 1) / (-tan(x / 2)**2 + 1) assert sec(x).rewrite(csc) == csc(-x + pi/2, evaluate=False) def test_sec_fdiff(): assert sec(x).fdiff() == tan(x)*sec(x) raises(ArgumentIndexError, lambda: sec(x).fdiff(2)) def test_csc(): x = symbols('x', real=True) z = symbols('z') # https://github.com/sympy/sympy/issues/6707 cosecant = csc('x') alternate = 1/sin('x') assert cosecant.equals(alternate) == True assert alternate.equals(cosecant) == True assert csc.nargs == FiniteSet(1) assert csc(0) is zoo assert csc(pi) is zoo assert csc(zoo) is nan assert csc(pi/2) == 1 assert csc(-pi/2) == -1 assert csc(pi/6) == 2 assert csc(pi/3) == 2*sqrt(3)/3 assert csc(pi*Rational(5, 2)) == 1 assert csc(pi*Rational(9, 7)) == -csc(pi*Rational(2, 7)) assert csc(pi*Rational(3, 4)) == sqrt(2) # issue 8421 assert csc(I) == -I/sinh(1) assert csc(x*I) == -I/sinh(x) assert csc(-x) == -csc(x) assert csc(acsc(x)) == x assert csc(z).conjugate() == csc(conjugate(z)) assert (csc(z).as_real_imag() == (sin(re(z))*cosh(im(z))/(sin(re(z))**2*cosh(im(z))**2 + cos(re(z))**2*sinh(im(z))**2), -cos(re(z))*sinh(im(z))/(sin(re(z))**2*cosh(im(z))**2 + cos(re(z))**2*sinh(im(z))**2))) assert csc(x).expand(trig=True) == 1/sin(x) assert csc(2*x).expand(trig=True) == 1/(2*sin(x)*cos(x)) assert csc(x).is_extended_real == True assert csc(z).is_real == None assert csc(a).is_algebraic is None assert csc(na).is_algebraic is False assert csc(x).as_leading_term() == csc(x) assert csc(0, evaluate=False).is_finite == False assert csc(x).is_finite == None assert csc(pi/2, evaluate=False).is_finite == True assert series(csc(x), x, x0=pi/2, n=6) == \ 1 + (x - pi/2)**2/2 + 5*(x - pi/2)**4/24 + O((x - pi/2)**6, (x, pi/2)) assert series(csc(x), x, x0=0, n=6) == \ 1/x + x/6 + 7*x**3/360 + 31*x**5/15120 + O(x**6) assert csc(x).diff(x) == -cot(x)*csc(x) assert csc(x).taylor_term(2, x) == 0 assert csc(x).taylor_term(3, x) == 7*x**3/360 assert csc(x).taylor_term(5, x) == 31*x**5/15120 raises(ArgumentIndexError, lambda: csc(x).fdiff(2)) def test_asec(): z = Symbol('z', zero=True) assert asec(z) is zoo assert asec(nan) is nan assert asec(1) == 0 assert asec(-1) == pi assert asec(oo) == pi/2 assert asec(-oo) == pi/2 assert asec(zoo) == pi/2 assert asec(sec(pi*Rational(13, 4))) == pi*Rational(3, 4) assert asec(1 + sqrt(5)) == pi*Rational(2, 5) assert asec(2/sqrt(3)) == pi/6 assert asec(sqrt(4 - 2*sqrt(2))) == pi/8 assert asec(-sqrt(4 + 2*sqrt(2))) == pi*Rational(5, 8) assert asec(sqrt(2 + 2*sqrt(5)/5)) == pi*Rational(3, 10) assert asec(-sqrt(2 + 2*sqrt(5)/5)) == pi*Rational(7, 10) assert asec(sqrt(2) - sqrt(6)) == pi*Rational(11, 12) assert asec(x).diff(x) == 1/(x**2*sqrt(1 - 1/x**2)) assert asec(x).as_leading_term(x) == I*log(x) assert asec(x).rewrite(log) == I*log(sqrt(1 - 1/x**2) + I/x) + pi/2 assert asec(x).rewrite(asin) == -asin(1/x) + pi/2 assert asec(x).rewrite(acos) == acos(1/x) assert asec(x).rewrite(atan) == (2*atan(x + sqrt(x**2 - 1)) - pi/2)*sqrt(x**2)/x assert asec(x).rewrite(acot) == (2*acot(x - sqrt(x**2 - 1)) - pi/2)*sqrt(x**2)/x assert asec(x).rewrite(acsc) == -acsc(x) + pi/2 raises(ArgumentIndexError, lambda: asec(x).fdiff(2)) def test_asec_is_real(): assert asec(S.Half).is_real is False n = Symbol('n', positive=True, integer=True) assert asec(n).is_extended_real is True assert asec(x).is_real is None assert asec(r).is_real is None t = Symbol('t', real=False, finite=True) assert asec(t).is_real is False def test_acsc(): assert acsc(nan) is nan assert acsc(1) == pi/2 assert acsc(-1) == -pi/2 assert acsc(oo) == 0 assert acsc(-oo) == 0 assert acsc(zoo) == 0 assert acsc(0) is zoo assert acsc(csc(3)) == -3 + pi assert acsc(csc(4)) == -4 + pi assert acsc(csc(6)) == 6 - 2*pi assert unchanged(acsc, csc(x)) assert unchanged(acsc, sec(x)) assert acsc(2/sqrt(3)) == pi/3 assert acsc(csc(pi*Rational(13, 4))) == -pi/4 assert acsc(sqrt(2 + 2*sqrt(5)/5)) == pi/5 assert acsc(-sqrt(2 + 2*sqrt(5)/5)) == -pi/5 assert acsc(-2) == -pi/6 assert acsc(-sqrt(4 + 2*sqrt(2))) == -pi/8 assert acsc(sqrt(4 - 2*sqrt(2))) == pi*Rational(3, 8) assert acsc(1 + sqrt(5)) == pi/10 assert acsc(sqrt(2) - sqrt(6)) == pi*Rational(-5, 12) assert acsc(x).diff(x) == -1/(x**2*sqrt(1 - 1/x**2)) assert acsc(x).as_leading_term(x) == I*log(x) assert acsc(x).rewrite(log) == -I*log(sqrt(1 - 1/x**2) + I/x) assert acsc(x).rewrite(asin) == asin(1/x) assert acsc(x).rewrite(acos) == -acos(1/x) + pi/2 assert acsc(x).rewrite(atan) == (-atan(sqrt(x**2 - 1)) + pi/2)*sqrt(x**2)/x assert acsc(x).rewrite(acot) == (-acot(1/sqrt(x**2 - 1)) + pi/2)*sqrt(x**2)/x assert acsc(x).rewrite(asec) == -asec(x) + pi/2 raises(ArgumentIndexError, lambda: acsc(x).fdiff(2)) def test_csc_rewrite(): assert csc(x).rewrite(pow) == csc(x) assert csc(x).rewrite(sqrt) == csc(x) assert csc(x).rewrite(exp) == 2*I/(exp(I*x) - exp(-I*x)) assert csc(x).rewrite(sin) == 1/sin(x) assert csc(x).rewrite(tan) == (tan(x/2)**2 + 1)/(2*tan(x/2)) assert csc(x).rewrite(cot) == (cot(x/2)**2 + 1)/(2*cot(x/2)) assert csc(x).rewrite(cos) == 1/cos(x - pi/2, evaluate=False) assert csc(x).rewrite(sec) == sec(-x + pi/2, evaluate=False) # issue 17349 assert csc(1 - exp(-besselj(I, I))).rewrite(cos) == \ -1/cos(-pi/2 - 1 + cos(I*besselj(I, I)) + I*cos(-pi/2 + I*besselj(I, I), evaluate=False), evaluate=False) def test_inverses_nseries(): assert asin(x + 2)._eval_nseries(x, 4, None, I) == -asin(2) + pi + sqrt(3)*I*x/3 - sqrt(3)*I*x**2/9 + \ sqrt(3)*I*x**3/18 + O(x**4) assert asin(x + 2)._eval_nseries(x, 4, None, -I) == asin(2) - sqrt(3)*I*x/3 + sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4) assert asin(x - 2)._eval_nseries(x, 4, None, I) == -asin(2) - sqrt(3)*I*x/3 - sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4) assert asin(x - 2)._eval_nseries(x, 4, None, -I) == asin(2) - pi + sqrt(3)*I*x/3 + sqrt(3)*I*x**2/9 + \ sqrt(3)*I*x**3/18 + O(x**4) assert asin(I*x + I*x**3 + 2)._eval_nseries(x, 3, None, 1) == -asin(2) + pi - sqrt(3)*x/3 + sqrt(3)*I*x**2/9 + O(x**3) assert asin(I*x + I*x**3 + 2)._eval_nseries(x, 3, None, -1) == asin(2) + sqrt(3)*x/3 - sqrt(3)*I*x**2/9 + O(x**3) assert asin(I*x + I*x**3 - 2)._eval_nseries(x, 3, None, 1) == -asin(2) + sqrt(3)*x/3 + sqrt(3)*I*x**2/9 + O(x**3) assert asin(I*x + I*x**3 - 2)._eval_nseries(x, 3, None, -1) == asin(2) - pi - sqrt(3)*x/3 - sqrt(3)*I*x**2/9 + O(x**3) assert asin(I*x**2 + I*x**3 + 2)._eval_nseries(x, 3, None, 1) == -asin(2) + pi - sqrt(3)*x**2/3 + O(x**3) assert asin(I*x**2 + I*x**3 + 2)._eval_nseries(x, 3, None, -1) == -asin(2) + pi - sqrt(3)*x**2/3 + O(x**3) assert asin(I*x**2 + I*x**3 - 2)._eval_nseries(x, 3, None, 1) == -asin(2) + sqrt(3)*x**2/3 + O(x**3) assert asin(I*x**2 + I*x**3 - 2)._eval_nseries(x, 3, None, -1) == -asin(2) + sqrt(3)*x**2/3 + O(x**3) assert asin(1 + x)._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(-x) - \ sqrt(2)*(-x)**(S(3)/2)/12 - 3*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3) assert asin(-1 + x)._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(x) + \ sqrt(2)*x**(S(3)/2)/12 + 3*sqrt(2)*x**(S(5)/2)/160 + O(x**3) assert asin(exp(x))._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(-x) + \ sqrt(2)*(-x)**(S(3)/2)/6 - sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3) assert asin(-exp(x))._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(-x) - \ sqrt(2)*(-x)**(S(3)/2)/6 + sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3) assert acos(x + 2)._eval_nseries(x, 4, None, I) == -acos(2) - sqrt(3)*I*x/3 + sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4) assert acos(x + 2)._eval_nseries(x, 4, None, -I) == acos(2) + sqrt(3)*I*x/3 - sqrt(3)*I*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4) assert acos(x - 2)._eval_nseries(x, 4, None, I) == acos(-2) + sqrt(3)*I*x/3 + sqrt(3)*I*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4) assert acos(x - 2)._eval_nseries(x, 4, None, -I) == -acos(-2) + 2*pi - sqrt(3)*I*x/3 - \ sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4) # assert acos(I*x + I*x**3 + 2)._eval_nseries(x, 3, None, 1) == -acos(2) + sqrt(3)*x/3 - sqrt(3)*I*x**2/9 + O(x**3) # assert acos(I*x + I*x**3 + 2)._eval_nseries(x, 3, None, -1) == acos(2) - sqrt(3)*x/3 + sqrt(3)*I*x**2/9 + O(x**3) # assert acos(I*x + I*x**3 - 2)._eval_nseries(x, 3, None, 1) == acos(-2) - sqrt(3)*x/3 - sqrt(3)*I*x**2/9 + O(x**3) # assert acos(I*x + I*x**3 - 2)._eval_nseries(x, 3, None, -1) == -acos(-2) + 2*pi + sqrt(3)*x/3 + sqrt(3)*I*x**2/9 + O(x**3) # assert acos(I*x**2 + I*x**3 + 2)._eval_nseries(x, 3, None, 1) == -acos(2) + sqrt(3)*x**2/3 + O(x**3) # assert acos(I*x**2 + I*x**3 + 2)._eval_nseries(x, 3, None, -1) == -acos(2) + sqrt(3)*x**2/3 + O(x**3) # assert acos(I*x**2 + I*x**3 - 2)._eval_nseries(x, 3, None, 1) == acos(-2) - sqrt(3)*x**2/3 + O(x**3) # assert acos(I*x**2 + I*x**3 - 2)._eval_nseries(x, 3, None, -1) == acos(-2) - sqrt(3)*x**2/3 + O(x**3) # assert acos(1 + x)._eval_nseries(x, 3, None) == sqrt(2)*sqrt(-x) + sqrt(2)*(-x)**(S(3)/2)/12 + 3*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3) # assert acos(-1 + x)._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(x) - sqrt(2)*x**(S(3)/2)/12 - 3*sqrt(2)*x**(S(5)/2)/160 + O(x**3) # assert acos(exp(x))._eval_nseries(x, 3, None) == sqrt(2)*sqrt(-x) - sqrt(2)*(-x)**(S(3)/2)/6 + sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3) # assert acos(-exp(x))._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(-x) + sqrt(2)*(-x)**(S(3)/2)/6 - sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3) assert atan(x + 2*I)._eval_nseries(x, 4, None, 1) == I*atanh(2) - x/3 - 2*I*x**2/9 + 13*x**3/81 + O(x**4) assert atan(x + 2*I)._eval_nseries(x, 4, None, -1) == I*atanh(2) - pi - x/3 - 2*I*x**2/9 + 13*x**3/81 + O(x**4) assert atan(x - 2*I)._eval_nseries(x, 4, None, 1) == -I*atanh(2) + pi - x/3 + 2*I*x**2/9 + 13*x**3/81 + O(x**4) assert atan(x - 2*I)._eval_nseries(x, 4, None, -1) == -I*atanh(2) - x/3 + 2*I*x**2/9 + 13*x**3/81 + O(x**4) # assert atan(x**2 + 2*I)._eval_nseries(x, 3, None, 1) == I*atanh(2) - x**2/3 + O(x**3) # assert atan(x**2 + 2*I)._eval_nseries(x, 3, None, -1) == I*atanh(2) - x**2/3 + O(x**3) # assert atan(x**2 - 2*I)._eval_nseries(x, 3, None, 1) == -I*atanh(2) + pi - x**2/3 + O(x**3) # assert atan(x**2 - 2*I)._eval_nseries(x, 3, None, -1) == -I*atanh(2) + pi - x**2/3 + O(x**3) assert atan(1/x)._eval_nseries(x, 2, None, 1) == pi/2 - x + O(x**2) assert atan(1/x)._eval_nseries(x, 2, None, -1) == -pi/2 - x + O(x**2) assert acot(x + S(1)/2*I)._eval_nseries(x, 4, None, 1) == -I*acoth(S(1)/2) + pi - 4*x/3 + 8*I*x**2/9 + 112*x**3/81 + O(x**4) assert acot(x + S(1)/2*I)._eval_nseries(x, 4, None, -1) == -I*acoth(S(1)/2) - 4*x/3 + 8*I*x**2/9 + 112*x**3/81 + O(x**4) assert acot(x - S(1)/2*I)._eval_nseries(x, 4, None, 1) == I*acoth(S(1)/2) - 4*x/3 - 8*I*x**2/9 + 112*x**3/81 + O(x**4) assert acot(x - S(1)/2*I)._eval_nseries(x, 4, None, -1) == I*acoth(S(1)/2) - pi - 4*x/3 - 8*I*x**2/9 + 112*x**3/81 + O(x**4) # assert acot(x**2 + S(1)/2*I)._eval_nseries(x, 3, None, 1) == -I*acoth(S(1)/2) + pi - 4*x**2/3 + O(x**3) # assert acot(x**2 + S(1)/2*I)._eval_nseries(x, 3, None, -1) == -I*acoth(S(1)/2) + pi - 4*x**2/3 + O(x**3) # assert acot(x**2 - S(1)/2*I)._eval_nseries(x, 3, None, 1) == I*acoth(S(1)/2) - 4*x**2/3 + O(x**3) # assert acot(x**2 - S(1)/2*I)._eval_nseries(x, 3, None, -1) == I*acoth(S(1)/2) - 4*x**2/3 + O(x**3) # assert acot(x)._eval_nseries(x, 2, None, 1) == pi/2 - x + O(x**2) # assert acot(x)._eval_nseries(x, 2, None, -1) == -pi/2 - x + O(x**2) assert asec(x + S(1)/2)._eval_nseries(x, 4, None, I) == asec(S(1)/2) - 4*sqrt(3)*I*x/3 + \ 8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4) assert asec(x + S(1)/2)._eval_nseries(x, 4, None, -I) == -asec(S(1)/2) + 4*sqrt(3)*I*x/3 - \ 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4) assert asec(x - S(1)/2)._eval_nseries(x, 4, None, I) == -asec(-S(1)/2) + 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) assert asec(x - S(1)/2)._eval_nseries(x, 4, None, -I) == asec(-S(1)/2) - 4*sqrt(3)*I*x/3 - \ 8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4) # assert asec(I*x + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, 1) == asec(S(1)/2) + 4*sqrt(3)*x/3 - 8*sqrt(3)*I*x**2/9 + O(x**3) # assert asec(I*x + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, -1) == -asec(S(1)/2) - 4*sqrt(3)*x/3 + 8*sqrt(3)*I*x**2/9 + O(x**3) # assert asec(I*x + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, 1) == -asec(-S(1)/2) + 2*pi - 4*sqrt(3)*x/3 - 8*sqrt(3)*I*x**2/9 + O(x**3) # assert asec(I*x + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, -1) == asec(-S(1)/2) + 4*sqrt(3)*x/3 + 8*sqrt(3)*I*x**2/9 + O(x**3) # assert asec(I*x**2 + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, 1) == asec(S(1)/2) + 4*sqrt(3)*x**2/3 + O(x**3) # assert asec(I*x**2 + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, -1) == asec(S(1)/2) + 4*sqrt(3)*x**2/3 + O(x**3) # assert asec(I*x**2 + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, 1) == -asec(-S(1)/2) + 2*pi - 4*sqrt(3)*x**2/3 + O(x**3) # assert asec(I*x**2 + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, -1) == -asec(-S(1)/2) + 2*pi - 4*sqrt(3)*x**2/3 + O(x**3) # assert asec(1 + x)._eval_nseries(x, 3, None) == sqrt(2)*sqrt(x) - 5*sqrt(2)*x**(S(3)/2)/12 + 43*sqrt(2)*x**(S(5)/2)/160 + O(x**3) # assert asec(-1 + x)._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(-x) + 5*sqrt(2)*(-x)**(S(3)/2)/12 - 43*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3) # assert asec(exp(x))._eval_nseries(x, 3, None) == sqrt(2)*sqrt(x) - sqrt(2)*x**(S(3)/2)/6 + sqrt(2)*x**(S(5)/2)/120 + O(x**3) # assert asec(-exp(x))._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(x) + sqrt(2)*x**(S(3)/2)/6 - sqrt(2)*x**(S(5)/2)/120 + O(x**3) assert acsc(x + S(1)/2)._eval_nseries(x, 4, None, I) == acsc(S(1)/2) + 4*sqrt(3)*I*x/3 - \ 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4) assert acsc(x + S(1)/2)._eval_nseries(x, 4, None, -I) == -acsc(S(1)/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) assert acsc(x - S(1)/2)._eval_nseries(x, 4, None, I) == acsc(S(1)/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) assert acsc(x - S(1)/2)._eval_nseries(x, 4, None, -I) == -acsc(S(1)/2) + 4*sqrt(3)*I*x/3 + \ 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4) # assert acsc(I*x + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, 1) == acsc(S(1)/2) - 4*sqrt(3)*x/3 + 8*sqrt(3)*I*x**2/9 + O(x**3) # assert acsc(I*x + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, -1) == -acsc(S(1)/2) + pi + 4*sqrt(3)*x/3 - 8*sqrt(3)*I*x**2/9 + O(x**3) # assert acsc(I*x + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, 1) == acsc(S(1)/2) - pi + 4*sqrt(3)*x/3 + 8*sqrt(3)*I*x**2/9 + O(x**3) # assert acsc(I*x + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, -1) == -acsc(S(1)/2) - 4*sqrt(3)*x/3 - 8*sqrt(3)*I*x**2/9 + O(x**3) # assert acsc(I*x**2 + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, 1) == acsc(S(1)/2) - 4*sqrt(3)*x**2/3 + O(x**3) # assert acsc(I*x**2 + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, -1) == acsc(S(1)/2) - 4*sqrt(3)*x**2/3 + O(x**3) # assert acsc(I*x**2 + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, 1) == acsc(S(1)/2) - pi + 4*sqrt(3)*x**2/3 + O(x**3) # assert acsc(I*x**2 + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, -1) == acsc(S(1)/2) - pi + 4*sqrt(3)*x**2/3 + O(x**3) # assert acsc(1 + x)._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(x) + 5*sqrt(2)*x**(S(3)/2)/12 - 43*sqrt(2)*x**(S(5)/2)/160 + O(x**3) # assert acsc(-1 + x)._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(-x) - 5*sqrt(2)*(-x)**(S(3)/2)/12 + 43*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3) # assert acsc(exp(x))._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(x) + sqrt(2)*x**(S(3)/2)/6 - sqrt(2)*x**(S(5)/2)/120 + O(x**3) # assert acsc(-exp(x))._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(x) - sqrt(2)*x**(S(3)/2)/6 + sqrt(2)*x**(S(5)/2)/120 + O(x**3) def test_issue_8653(): n = Symbol('n', integer=True) assert sin(n).is_irrational is None assert cos(n).is_irrational is None assert tan(n).is_irrational is None def test_issue_9157(): n = Symbol('n', integer=True, positive=True) assert atan(n - 1).is_nonnegative is True def test_trig_period(): x, y = symbols('x, y') assert sin(x).period() == 2*pi assert cos(x).period() == 2*pi assert tan(x).period() == pi assert cot(x).period() == pi assert sec(x).period() == 2*pi assert csc(x).period() == 2*pi assert sin(2*x).period() == pi assert cot(4*x - 6).period() == pi/4 assert cos((-3)*x).period() == pi*Rational(2, 3) assert cos(x*y).period(x) == 2*pi/abs(y) assert sin(3*x*y + 2*pi).period(y) == 2*pi/abs(3*x) assert tan(3*x).period(y) is S.Zero raises(NotImplementedError, lambda: sin(x**2).period(x)) def test_issue_7171(): assert sin(x).rewrite(sqrt) == sin(x) assert sin(x).rewrite(pow) == sin(x) def test_issue_11864(): w, k = symbols('w, k', real=True) F = Piecewise((1, Eq(2*pi*k, 0)), (sin(pi*k)/(pi*k), True)) soln = Piecewise((1, Eq(2*pi*k, 0)), (sinc(pi*k), True)) assert F.rewrite(sinc) == soln def test_real_assumptions(): z = Symbol('z', real=False, finite=True) assert sin(z).is_real is None assert cos(z).is_real is None assert tan(z).is_real is False assert sec(z).is_real is None assert csc(z).is_real is None assert cot(z).is_real is False assert asin(p).is_real is None assert asin(n).is_real is None assert asec(p).is_real is None assert asec(n).is_real is None assert acos(p).is_real is None assert acos(n).is_real is None assert acsc(p).is_real is None assert acsc(n).is_real is None assert atan(p).is_positive is True assert atan(n).is_negative is True assert acot(p).is_positive is True assert acot(n).is_negative is True def test_issue_14320(): assert asin(sin(2)) == -2 + pi and (-pi/2 <= -2 + pi <= pi/2) and sin(2) == sin(-2 + pi) assert asin(cos(2)) == -2 + pi/2 and (-pi/2 <= -2 + pi/2 <= pi/2) and cos(2) == sin(-2 + pi/2) assert acos(sin(2)) == -pi/2 + 2 and (0 <= -pi/2 + 2 <= pi) and sin(2) == cos(-pi/2 + 2) assert acos(cos(20)) == -6*pi + 20 and (0 <= -6*pi + 20 <= pi) and cos(20) == cos(-6*pi + 20) assert acos(cos(30)) == -30 + 10*pi and (0 <= -30 + 10*pi <= pi) and cos(30) == cos(-30 + 10*pi) assert atan(tan(17)) == -5*pi + 17 and (-pi/2 < -5*pi + 17 < pi/2) and tan(17) == tan(-5*pi + 17) assert atan(tan(15)) == -5*pi + 15 and (-pi/2 < -5*pi + 15 < pi/2) and tan(15) == tan(-5*pi + 15) 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)) assert acot(cot(15)) == -5*pi + 15 and (-pi/2 < -5*pi + 15 <= pi/2) and cot(15) == cot(-5*pi + 15) 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)) assert asec(sec(11)) == -11 + 4*pi and (0 <= -11 + 4*pi <= pi) and cos(11) == cos(-11 + 4*pi) 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)) assert acsc(csc(14)) == -4*pi + 14 and (-pi/2 <= -4*pi + 14 <= pi/2) and sin(14) == sin(-4*pi + 14) 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) def test_issue_14543(): assert sec(2*pi + 11) == sec(11) assert sec(2*pi - 11) == sec(11) assert sec(pi + 11) == -sec(11) assert sec(pi - 11) == -sec(11) assert csc(2*pi + 17) == csc(17) assert csc(2*pi - 17) == -csc(17) assert csc(pi + 17) == -csc(17) assert csc(pi - 17) == csc(17) x = Symbol('x') assert csc(pi/2 + x) == sec(x) assert csc(pi/2 - x) == sec(x) assert csc(pi*Rational(3, 2) + x) == -sec(x) assert csc(pi*Rational(3, 2) - x) == -sec(x) assert sec(pi/2 - x) == csc(x) assert sec(pi/2 + x) == -csc(x) assert sec(pi*Rational(3, 2) + x) == csc(x) assert sec(pi*Rational(3, 2) - x) == -csc(x) def test_as_real_imag(): # This is for https://github.com/sympy/sympy/issues/17142 # If it start failing again in irrelevant builds or in the master # please open up the issue again. expr = atan(I/(I + I*tan(1))) assert expr.as_real_imag() == (expr, 0) def test_issue_18746(): e3 = cos(S.Pi*(x/4 + 1/4)) assert e3.period() == 8
dc3b58d10415ec5eb9db5e585a8d8cdc2304b92c3ce9db128b3bcadd5403aa95
from sympy.concrete.summations import Sum from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.containers import Tuple from sympy.core.function import (Function, diff, expand) from sympy.core.mul import Mul from sympy.core.numbers import (Float, I, Rational, oo, pi, zoo) from sympy.core.relational import (Eq, Ge, Gt, Ne) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.complexes import (Abs, adjoint, arg, conjugate, im, re, transpose) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt) from sympy.functions.elementary.piecewise import (Piecewise, piecewise_fold) from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.delta_functions import (DiracDelta, Heaviside) from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.integrals.integrals import (Integral, integrate) from sympy.logic.boolalg import (And, ITE, Not, Or) from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.sets.contains import Contains from sympy.sets.sets import Interval from sympy.solvers.solvers import solve from sympy.utilities.lambdify import lambdify from sympy.core.expr import unchanged from sympy.functions.elementary.piecewise import Undefined, ExprCondPair from sympy.printing import srepr from sympy.testing.pytest import raises, slow from sympy.simplify import simplify a, b, c, d, x, y = symbols('a:d, x, y') z = symbols('z', nonzero=True) def test_piecewise1(): # Test canonicalization assert unchanged(Piecewise, ExprCondPair(x, x < 1), ExprCondPair(0, True)) assert Piecewise((x, x < 1), (0, True)) == Piecewise(ExprCondPair(x, x < 1), ExprCondPair(0, True)) assert Piecewise((x, x < 1), (0, True), (1, True)) == \ Piecewise((x, x < 1), (0, True)) assert Piecewise((x, x < 1), (0, False), (-1, 1 > 2)) == \ Piecewise((x, x < 1)) assert Piecewise((x, x < 1), (0, x < 1), (0, True)) == \ Piecewise((x, x < 1), (0, True)) assert Piecewise((x, x < 1), (0, x < 2), (0, True)) == \ Piecewise((x, x < 1), (0, True)) assert Piecewise((x, x < 1), (x, x < 2), (0, True)) == \ Piecewise((x, Or(x < 1, x < 2)), (0, True)) assert Piecewise((x, x < 1), (x, x < 2), (x, True)) == x assert Piecewise((x, True)) == x # Explicitly constructed empty Piecewise not accepted raises(TypeError, lambda: Piecewise()) # False condition is never retained assert Piecewise((2*x, x < 0), (x, False)) == \ Piecewise((2*x, x < 0), (x, False), evaluate=False) == \ Piecewise((2*x, x < 0)) assert Piecewise((x, False)) == Undefined raises(TypeError, lambda: Piecewise(x)) assert Piecewise((x, 1)) == x # 1 and 0 are accepted as True/False raises(TypeError, lambda: Piecewise((x, 2))) raises(TypeError, lambda: Piecewise((x, x**2))) raises(TypeError, lambda: Piecewise(([1], True))) assert Piecewise(((1, 2), True)) == Tuple(1, 2) cond = (Piecewise((1, x < 0), (2, True)) < y) assert Piecewise((1, cond) ) == Piecewise((1, ITE(x < 0, y > 1, y > 2))) assert Piecewise((1, x > 0), (2, And(x <= 0, x > -1)) ) == Piecewise((1, x > 0), (2, x > -1)) assert Piecewise((1, x <= 0), (2, (x < 0) & (x > -1)) ) == Piecewise((1, x <= 0)) # test for supporting Contains in Piecewise pwise = Piecewise( (1, And(x <= 6, x > 1, Contains(x, S.Integers))), (0, True)) assert pwise.subs(x, pi) == 0 assert pwise.subs(x, 2) == 1 assert pwise.subs(x, 7) == 0 # Test subs p = Piecewise((-1, x < -1), (x**2, x < 0), (log(x), x >= 0)) p_x2 = Piecewise((-1, x**2 < -1), (x**4, x**2 < 0), (log(x**2), x**2 >= 0)) assert p.subs(x, x**2) == p_x2 assert p.subs(x, -5) == -1 assert p.subs(x, -1) == 1 assert p.subs(x, 1) == log(1) # More subs tests p2 = Piecewise((1, x < pi), (-1, x < 2*pi), (0, x > 2*pi)) p3 = Piecewise((1, Eq(x, 0)), (1/x, True)) p4 = Piecewise((1, Eq(x, 0)), (2, 1/x>2)) assert p2.subs(x, 2) == 1 assert p2.subs(x, 4) == -1 assert p2.subs(x, 10) == 0 assert p3.subs(x, 0.0) == 1 assert p4.subs(x, 0.0) == 1 f, g, h = symbols('f,g,h', cls=Function) pf = Piecewise((f(x), x < -1), (f(x) + h(x) + 2, x <= 1)) pg = Piecewise((g(x), x < -1), (g(x) + h(x) + 2, x <= 1)) assert pg.subs(g, f) == pf assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 0) == 1 assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 1) == 0 assert Piecewise((1, Eq(x, y)), (0, True)).subs(x, y) == 1 assert Piecewise((1, Eq(x, z)), (0, True)).subs(x, z) == 1 assert Piecewise((1, Eq(exp(x), cos(z))), (0, True)).subs(x, z) == \ Piecewise((1, Eq(exp(z), cos(z))), (0, True)) p5 = Piecewise( (0, Eq(cos(x) + y, 0)), (1, True)) assert p5.subs(y, 0) == Piecewise( (0, Eq(cos(x), 0)), (1, True)) assert Piecewise((-1, y < 1), (0, x < 0), (1, Eq(x, 0)), (2, True) ).subs(x, 1) == Piecewise((-1, y < 1), (2, True)) assert Piecewise((1, Eq(x**2, -1)), (2, x < 0)).subs(x, I) == 1 p6 = Piecewise((x, x > 0)) n = symbols('n', negative=True) assert p6.subs(x, n) == Undefined # Test evalf assert p.evalf() == p assert p.evalf(subs={x: -2}) == -1 assert p.evalf(subs={x: -1}) == 1 assert p.evalf(subs={x: 1}) == log(1) assert p6.evalf(subs={x: -5}) == Undefined # Test doit f_int = Piecewise((Integral(x, (x, 0, 1)), x < 1)) assert f_int.doit() == Piecewise( (S.Half, x < 1) ) # Test differentiation f = x fp = x*p dp = Piecewise((0, x < -1), (2*x, x < 0), (1/x, x >= 0)) fp_dx = x*dp + p assert diff(p, x) == dp assert diff(f*p, x) == fp_dx # Test simple arithmetic assert x*p == fp assert x*p + p == p + x*p assert p + f == f + p assert p + dp == dp + p assert p - dp == -(dp - p) # Test power dp2 = Piecewise((0, x < -1), (4*x**2, x < 0), (1/x**2, x >= 0)) assert dp**2 == dp2 # Test _eval_interval f1 = x*y + 2 f2 = x*y**2 + 3 peval = Piecewise((f1, x < 0), (f2, x > 0)) peval_interval = f1.subs( x, 0) - f1.subs(x, -1) + f2.subs(x, 1) - f2.subs(x, 0) assert peval._eval_interval(x, 0, 0) == 0 assert peval._eval_interval(x, -1, 1) == peval_interval peval2 = Piecewise((f1, x < 0), (f2, True)) assert peval2._eval_interval(x, 0, 0) == 0 assert peval2._eval_interval(x, 1, -1) == -peval_interval assert peval2._eval_interval(x, -1, -2) == f1.subs(x, -2) - f1.subs(x, -1) assert peval2._eval_interval(x, -1, 1) == peval_interval assert peval2._eval_interval(x, None, 0) == peval2.subs(x, 0) assert peval2._eval_interval(x, -1, None) == -peval2.subs(x, -1) # Test integration assert p.integrate() == Piecewise( (-x, x < -1), (x**3/3 + Rational(4, 3), x < 0), (x*log(x) - x + Rational(4, 3), True)) p = Piecewise((x, x < 1), (x**2, -1 <= x), (x, 3 < x)) assert integrate(p, (x, -2, 2)) == Rational(5, 6) assert integrate(p, (x, 2, -2)) == Rational(-5, 6) p = Piecewise((0, x < 0), (1, x < 1), (0, x < 2), (1, x < 3), (0, True)) assert integrate(p, (x, -oo, oo)) == 2 p = Piecewise((x, x < -10), (x**2, x <= -1), (x, 1 < x)) assert integrate(p, (x, -2, 2)) == Undefined # Test commutativity assert isinstance(p, Piecewise) and p.is_commutative is True def test_piecewise_free_symbols(): f = Piecewise((x, a < 0), (y, True)) assert f.free_symbols == {x, y, a} def test_piecewise_integrate1(): x, y = symbols('x y', real=True) f = Piecewise(((x - 2)**2, x >= 0), (1, True)) assert integrate(f, (x, -2, 2)) == Rational(14, 3) g = Piecewise(((x - 5)**5, x >= 4), (f, True)) assert integrate(g, (x, -2, 2)) == Rational(14, 3) assert integrate(g, (x, -2, 5)) == Rational(43, 6) assert g == Piecewise(((x - 5)**5, x >= 4), (f, x < 4)) g = Piecewise(((x - 5)**5, 2 <= x), (f, x < 2)) assert integrate(g, (x, -2, 2)) == Rational(14, 3) assert integrate(g, (x, -2, 5)) == Rational(-701, 6) assert g == Piecewise(((x - 5)**5, 2 <= x), (f, True)) g = Piecewise(((x - 5)**5, 2 <= x), (2*f, True)) assert integrate(g, (x, -2, 2)) == Rational(28, 3) assert integrate(g, (x, -2, 5)) == Rational(-673, 6) def test_piecewise_integrate1b(): g = Piecewise((1, x > 0), (0, Eq(x, 0)), (-1, x < 0)) assert integrate(g, (x, -1, 1)) == 0 g = Piecewise((1, x - y < 0), (0, True)) assert integrate(g, (y, -oo, 0)) == -Min(0, x) assert g.subs(x, -3).integrate((y, -oo, 0)) == 3 assert integrate(g, (y, 0, -oo)) == Min(0, x) assert integrate(g, (y, 0, oo)) == -Max(0, x) + oo assert integrate(g, (y, -oo, 42)) == -Min(42, x) + 42 assert integrate(g, (y, -oo, oo)) == -x + oo g = Piecewise((0, x < 0), (x, x <= 1), (1, True)) gy1 = g.integrate((x, y, 1)) g1y = g.integrate((x, 1, y)) for yy in (-1, S.Half, 2): assert g.integrate((x, yy, 1)) == gy1.subs(y, yy) assert g.integrate((x, 1, yy)) == g1y.subs(y, yy) assert gy1 == Piecewise( (-Min(1, Max(0, y))**2/2 + S.Half, y < 1), (-y + 1, True)) assert g1y == Piecewise( (Min(1, Max(0, y))**2/2 - S.Half, y < 1), (y - 1, True)) @slow def test_piecewise_integrate1ca(): y = symbols('y', real=True) g = Piecewise( (1 - x, Interval(0, 1).contains(x)), (1 + x, Interval(-1, 0).contains(x)), (0, True) ) gy1 = g.integrate((x, y, 1)) g1y = g.integrate((x, 1, y)) assert g.integrate((x, -2, 1)) == gy1.subs(y, -2) assert g.integrate((x, 1, -2)) == g1y.subs(y, -2) assert g.integrate((x, 0, 1)) == gy1.subs(y, 0) assert g.integrate((x, 1, 0)) == g1y.subs(y, 0) assert g.integrate((x, 2, 1)) == gy1.subs(y, 2) assert g.integrate((x, 1, 2)) == g1y.subs(y, 2) assert piecewise_fold(gy1.rewrite(Piecewise) ).simplify() == Piecewise( (1, y <= -1), (-y**2/2 - y + S.Half, y <= 0), (y**2/2 - y + S.Half, y < 1), (0, True)) assert piecewise_fold(g1y.rewrite(Piecewise) ).simplify() == Piecewise( (-1, y <= -1), (y**2/2 + y - S.Half, y <= 0), (-y**2/2 + y - S.Half, y < 1), (0, True)) assert gy1 == Piecewise( ( -Min(1, Max(-1, y))**2/2 - Min(1, Max(-1, y)) + Min(1, Max(0, y))**2 + S.Half, y < 1), (0, True) ) assert g1y == Piecewise( ( Min(1, Max(-1, y))**2/2 + Min(1, Max(-1, y)) - Min(1, Max(0, y))**2 - S.Half, y < 1), (0, True)) @slow def test_piecewise_integrate1cb(): y = symbols('y', real=True) g = Piecewise( (0, Or(x <= -1, x >= 1)), (1 - x, x > 0), (1 + x, True) ) gy1 = g.integrate((x, y, 1)) g1y = g.integrate((x, 1, y)) assert g.integrate((x, -2, 1)) == gy1.subs(y, -2) assert g.integrate((x, 1, -2)) == g1y.subs(y, -2) assert g.integrate((x, 0, 1)) == gy1.subs(y, 0) assert g.integrate((x, 1, 0)) == g1y.subs(y, 0) assert g.integrate((x, 2, 1)) == gy1.subs(y, 2) assert g.integrate((x, 1, 2)) == g1y.subs(y, 2) assert piecewise_fold(gy1.rewrite(Piecewise) ).simplify() == Piecewise( (1, y <= -1), (-y**2/2 - y + S.Half, y <= 0), (y**2/2 - y + S.Half, y < 1), (0, True)) assert piecewise_fold(g1y.rewrite(Piecewise) ).simplify() == Piecewise( (-1, y <= -1), (y**2/2 + y - S.Half, y <= 0), (-y**2/2 + y - S.Half, y < 1), (0, True)) # g1y and gy1 should simplify if the condition that y < 1 # is applied, e.g. Min(1, Max(-1, y)) --> Max(-1, y) assert gy1 == Piecewise( ( -Min(1, Max(-1, y))**2/2 - Min(1, Max(-1, y)) + Min(1, Max(0, y))**2 + S.Half, y < 1), (0, True) ) assert g1y == Piecewise( ( Min(1, Max(-1, y))**2/2 + Min(1, Max(-1, y)) - Min(1, Max(0, y))**2 - S.Half, y < 1), (0, True)) def test_piecewise_integrate2(): from itertools import permutations lim = Tuple(x, c, d) p = Piecewise((1, x < a), (2, x > b), (3, True)) q = p.integrate(lim) assert q == Piecewise( (-c + 2*d - 2*Min(d, Max(a, c)) + Min(d, Max(a, b, c)), c < d), (-2*c + d + 2*Min(c, Max(a, d)) - Min(c, Max(a, b, d)), True)) for v in permutations((1, 2, 3, 4)): r = dict(zip((a, b, c, d), v)) assert p.subs(r).integrate(lim.subs(r)) == q.subs(r) def test_meijer_bypass(): # totally bypass meijerg machinery when dealing # with Piecewise in integrate assert Piecewise((1, x < 4), (0, True)).integrate((x, oo, 1)) == -3 def test_piecewise_integrate3_inequality_conditions(): from sympy.utilities.iterables import cartes lim = (x, 0, 5) # set below includes two pts below range, 2 pts in range, # 2 pts above range, and the boundaries N = (-2, -1, 0, 1, 2, 5, 6, 7) p = Piecewise((1, x > a), (2, x > b), (0, True)) ans = p.integrate(lim) for i, j in cartes(N, repeat=2): reps = dict(zip((a, b), (i, j))) assert ans.subs(reps) == p.subs(reps).integrate(lim) assert ans.subs(a, 4).subs(b, 1) == 0 + 2*3 + 1 p = Piecewise((1, x > a), (2, x < b), (0, True)) ans = p.integrate(lim) for i, j in cartes(N, repeat=2): reps = dict(zip((a, b), (i, j))) assert ans.subs(reps) == p.subs(reps).integrate(lim) # delete old tests that involved c1 and c2 since those # reduce to the above except that a value of 0 was used # for two expressions whereas the above uses 3 different # values @slow def test_piecewise_integrate4_symbolic_conditions(): a = Symbol('a', real=True) b = Symbol('b', real=True) x = Symbol('x', real=True) y = Symbol('y', real=True) p0 = Piecewise((0, Or(x < a, x > b)), (1, True)) p1 = Piecewise((0, x < a), (0, x > b), (1, True)) p2 = Piecewise((0, x > b), (0, x < a), (1, True)) p3 = Piecewise((0, x < a), (1, x < b), (0, True)) p4 = Piecewise((0, x > b), (1, x > a), (0, True)) p5 = Piecewise((1, And(a < x, x < b)), (0, True)) # check values of a=1, b=3 (and reversed) with values # of y of 0, 1, 2, 3, 4 lim = Tuple(x, -oo, y) for p in (p0, p1, p2, p3, p4, p5): ans = p.integrate(lim) for i in range(5): reps = {a:1, b:3, y:i} assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) reps = {a: 3, b:1, y:i} assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) lim = Tuple(x, y, oo) for p in (p0, p1, p2, p3, p4, p5): ans = p.integrate(lim) for i in range(5): reps = {a:1, b:3, y:i} assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) reps = {a:3, b:1, y:i} assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) ans = Piecewise( (0, x <= Min(a, b)), (x - Min(a, b), x <= b), (b - Min(a, b), True)) for i in (p0, p1, p2, p4): assert i.integrate(x) == ans assert p3.integrate(x) == Piecewise( (0, x < a), (-a + x, x <= Max(a, b)), (-a + Max(a, b), True)) assert p5.integrate(x) == Piecewise( (0, x <= a), (-a + x, x <= Max(a, b)), (-a + Max(a, b), True)) p1 = Piecewise((0, x < a), (0.5, x > b), (1, True)) p2 = Piecewise((0.5, x > b), (0, x < a), (1, True)) p3 = Piecewise((0, x < a), (1, x < b), (0.5, True)) p4 = Piecewise((0.5, x > b), (1, x > a), (0, True)) p5 = Piecewise((1, And(a < x, x < b)), (0.5, x > b), (0, True)) # check values of a=1, b=3 (and reversed) with values # of y of 0, 1, 2, 3, 4 lim = Tuple(x, -oo, y) for p in (p1, p2, p3, p4, p5): ans = p.integrate(lim) for i in range(5): reps = {a:1, b:3, y:i} assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) reps = {a: 3, b:1, y:i} assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) def test_piecewise_integrate5_independent_conditions(): p = Piecewise((0, Eq(y, 0)), (x*y, True)) assert integrate(p, (x, 1, 3)) == Piecewise((0, Eq(y, 0)), (4*y, True)) def test_piecewise_simplify(): p = Piecewise(((x**2 + 1)/x**2, Eq(x*(1 + x) - x**2, 0)), ((-1)**x*(-1), True)) assert p.simplify() == \ Piecewise((zoo, Eq(x, 0)), ((-1)**(x + 1), True)) # simplify when there are Eq in conditions assert Piecewise( (a, And(Eq(a, 0), Eq(a + b, 0))), (1, True)).simplify( ) == Piecewise( (0, And(Eq(a, 0), Eq(b, 0))), (1, True)) assert Piecewise((2*x*factorial(a)/(factorial(y)*factorial(-y + a)), Eq(y, 0) & Eq(-y + a, 0)), (2*factorial(a)/(factorial(y)*factorial(-y + a)), Eq(y, 0) & Eq(-y + a, 1)), (0, True)).simplify( ) == Piecewise( (2*x, And(Eq(a, 0), Eq(y, 0))), (2, And(Eq(a, 1), Eq(y, 0))), (0, True)) args = (2, And(Eq(x, 2), Ge(y, 0))), (x, True) assert Piecewise(*args).simplify() == Piecewise(*args) args = (1, Eq(x, 0)), (sin(x)/x, True) assert Piecewise(*args).simplify() == Piecewise(*args) assert Piecewise((2 + y, And(Eq(x, 2), Eq(y, 0))), (x, True) ).simplify() == x # check that x or f(x) are recognized as being Symbol-like for lhs args = Tuple((1, Eq(x, 0)), (sin(x) + 1 + x, True)) ans = x + sin(x) + 1 f = Function('f') assert Piecewise(*args).simplify() == ans assert Piecewise(*args.subs(x, f(x))).simplify() == ans.subs(x, f(x)) # issue 18634 d = Symbol("d", integer=True) n = Symbol("n", integer=True) t = Symbol("t", positive=True) expr = Piecewise((-d + 2*n, Eq(1/t, 1)), (t**(1 - 4*n)*t**(4*n - 1)*(-d + 2*n), True)) assert expr.simplify() == -d + 2*n def test_piecewise_solve(): abs2 = Piecewise((-x, x <= 0), (x, x > 0)) f = abs2.subs(x, x - 2) assert solve(f, x) == [2] assert solve(f - 1, x) == [1, 3] f = Piecewise(((x - 2)**2, x >= 0), (1, True)) assert solve(f, x) == [2] g = Piecewise(((x - 5)**5, x >= 4), (f, True)) assert solve(g, x) == [2, 5] g = Piecewise(((x - 5)**5, x >= 4), (f, x < 4)) assert solve(g, x) == [2, 5] g = Piecewise(((x - 5)**5, x >= 2), (f, x < 2)) assert solve(g, x) == [5] g = Piecewise(((x - 5)**5, x >= 2), (f, True)) assert solve(g, x) == [5] g = Piecewise(((x - 5)**5, x >= 2), (f, True), (10, False)) assert solve(g, x) == [5] g = Piecewise(((x - 5)**5, x >= 2), (-x + 2, x - 2 <= 0), (x - 2, x - 2 > 0)) assert solve(g, x) == [5] # if no symbol is given the piecewise detection must still work assert solve(Piecewise((x - 2, x > 2), (2 - x, True)) - 3) == [-1, 5] f = Piecewise(((x - 2)**2, x >= 0), (0, True)) raises(NotImplementedError, lambda: solve(f, x)) def nona(ans): return list(filter(lambda x: x is not S.NaN, ans)) p = Piecewise((x**2 - 4, x < y), (x - 2, True)) ans = solve(p, x) assert nona([i.subs(y, -2) for i in ans]) == [2] assert nona([i.subs(y, 2) for i in ans]) == [-2, 2] assert nona([i.subs(y, 3) for i in ans]) == [-2, 2] assert ans == [ Piecewise((-2, y > -2), (S.NaN, True)), Piecewise((2, y <= 2), (S.NaN, True)), Piecewise((2, y > 2), (S.NaN, True))] # issue 6060 absxm3 = Piecewise( (x - 3, 0 <= x - 3), (3 - x, 0 > x - 3) ) assert solve(absxm3 - y, x) == [ Piecewise((-y + 3, -y < 0), (S.NaN, True)), Piecewise((y + 3, y >= 0), (S.NaN, True))] p = Symbol('p', positive=True) assert solve(absxm3 - p, x) == [-p + 3, p + 3] # issue 6989 f = Function('f') assert solve(Eq(-f(x), Piecewise((1, x > 0), (0, True))), f(x)) == \ [Piecewise((-1, x > 0), (0, True))] # issue 8587 f = Piecewise((2*x**2, And(0 < x, x < 1)), (2, True)) assert solve(f - 1) == [1/sqrt(2)] def test_piecewise_fold(): p = Piecewise((x, x < 1), (1, 1 <= x)) assert piecewise_fold(x*p) == Piecewise((x**2, x < 1), (x, 1 <= x)) assert piecewise_fold(p + p) == Piecewise((2*x, x < 1), (2, 1 <= x)) assert piecewise_fold(Piecewise((1, x < 0), (2, True)) + Piecewise((10, x < 0), (-10, True))) == \ Piecewise((11, x < 0), (-8, True)) p1 = Piecewise((0, x < 0), (x, x <= 1), (0, True)) p2 = Piecewise((0, x < 0), (1 - x, x <= 1), (0, True)) p = 4*p1 + 2*p2 assert integrate( piecewise_fold(p), (x, -oo, oo)) == integrate(2*x + 2, (x, 0, 1)) assert piecewise_fold( Piecewise((1, y <= 0), (-Piecewise((2, y >= 0)), True) )) == Piecewise((1, y <= 0), (-2, y >= 0)) assert piecewise_fold(Piecewise((x, ITE(x > 0, y < 1, y > 1))) ) == Piecewise((x, ((x <= 0) | (y < 1)) & ((x > 0) | (y > 1)))) a, b = (Piecewise((2, Eq(x, 0)), (0, True)), Piecewise((x, Eq(-x + y, 0)), (1, Eq(-x + y, 1)), (0, True))) assert piecewise_fold(Mul(a, b, evaluate=False) ) == piecewise_fold(Mul(b, a, evaluate=False)) def test_piecewise_fold_piecewise_in_cond(): p1 = Piecewise((cos(x), x < 0), (0, True)) p2 = Piecewise((0, Eq(p1, 0)), (p1 / Abs(p1), True)) assert p2.subs(x, -pi/2) == 0 assert p2.subs(x, 1) == 0 assert p2.subs(x, -pi/4) == 1 p4 = Piecewise((0, Eq(p1, 0)), (1,True)) ans = piecewise_fold(p4) for i in range(-1, 1): assert ans.subs(x, i) == p4.subs(x, i) r1 = 1 < Piecewise((1, x < 1), (3, True)) ans = piecewise_fold(r1) for i in range(2): assert ans.subs(x, i) == r1.subs(x, i) p5 = Piecewise((1, x < 0), (3, True)) p6 = Piecewise((1, x < 1), (3, True)) p7 = Piecewise((1, p5 < p6), (0, True)) ans = piecewise_fold(p7) for i in range(-1, 2): assert ans.subs(x, i) == p7.subs(x, i) def test_piecewise_fold_piecewise_in_cond_2(): p1 = Piecewise((cos(x), x < 0), (0, True)) p2 = Piecewise((0, Eq(p1, 0)), (1 / p1, True)) p3 = Piecewise( (0, (x >= 0) | Eq(cos(x), 0)), (1/cos(x), x < 0), (zoo, True)) # redundant b/c all x are already covered assert(piecewise_fold(p2) == p3) def test_piecewise_fold_expand(): p1 = Piecewise((1, Interval(0, 1, False, True).contains(x)), (0, True)) p2 = piecewise_fold(expand((1 - x)*p1)) cond = ((x >= 0) & (x < 1)) assert piecewise_fold(expand((1 - x)*p1), evaluate=False ) == Piecewise((1 - x, cond), (-x, cond), (1, cond), (0, True), evaluate=False) assert piecewise_fold(expand((1 - x)*p1), evaluate=None ) == Piecewise((1 - x, cond), (0, True)) assert p2 == Piecewise((1 - x, cond), (0, True)) assert p2 == expand(piecewise_fold((1 - x)*p1)) def test_piecewise_duplicate(): p = Piecewise((x, x < -10), (x**2, x <= -1), (x, 1 < x)) assert p == Piecewise(*p.args) def test_doit(): p1 = Piecewise((x, x < 1), (x**2, -1 <= x), (x, 3 < x)) p2 = Piecewise((x, x < 1), (Integral(2 * x), -1 <= x), (x, 3 < x)) assert p2.doit() == p1 assert p2.doit(deep=False) == p2 # issue 17165 p1 = Sum(y**x, (x, -1, oo)).doit() assert p1.doit() == p1 def test_piecewise_interval(): p1 = Piecewise((x, Interval(0, 1).contains(x)), (0, True)) assert p1.subs(x, -0.5) == 0 assert p1.subs(x, 0.5) == 0.5 assert p1.diff(x) == Piecewise((1, Interval(0, 1).contains(x)), (0, True)) assert integrate(p1, x) == Piecewise( (0, x <= 0), (x**2/2, x <= 1), (S.Half, True)) def test_piecewise_collapse(): assert Piecewise((x, True)) == x a = x < 1 assert Piecewise((x, a), (x + 1, a)) == Piecewise((x, a)) assert Piecewise((x, a), (x + 1, a.reversed)) == Piecewise((x, a)) b = x < 5 def canonical(i): if isinstance(i, Piecewise): return Piecewise(*i.args) return i for args in [ ((1, a), (Piecewise((2, a), (3, b)), b)), ((1, a), (Piecewise((2, a), (3, b.reversed)), b)), ((1, a), (Piecewise((2, a), (3, b)), b), (4, True)), ((1, a), (Piecewise((2, a), (3, b), (4, True)), b)), ((1, a), (Piecewise((2, a), (3, b), (4, True)), b), (5, True))]: for i in (0, 2, 10): assert canonical( Piecewise(*args, evaluate=False).subs(x, i) ) == canonical(Piecewise(*args).subs(x, i)) r1, r2, r3, r4 = symbols('r1:5') a = x < r1 b = x < r2 c = x < r3 d = x < r4 assert Piecewise((1, a), (Piecewise( (2, a), (3, b), (4, c)), b), (5, c) ) == Piecewise((1, a), (3, b), (5, c)) assert Piecewise((1, a), (Piecewise( (2, a), (3, b), (4, c), (6, True)), c), (5, d) ) == Piecewise((1, a), (Piecewise( (3, b), (4, c)), c), (5, d)) assert Piecewise((1, Or(a, d)), (Piecewise( (2, d), (3, b), (4, c)), b), (5, c) ) == Piecewise((1, Or(a, d)), (Piecewise( (2, d), (3, b)), b), (5, c)) assert Piecewise((1, c), (2, ~c), (3, S.true) ) == Piecewise((1, c), (2, S.true)) assert Piecewise((1, c), (2, And(~c, b)), (3,True) ) == Piecewise((1, c), (2, b), (3, True)) assert Piecewise((1, c), (2, Or(~c, b)), (3,True) ).subs(dict(zip((r1, r2, r3, r4, x), (1, 2, 3, 4, 3.5)))) == 2 assert Piecewise((1, c), (2, ~c)) == Piecewise((1, c), (2, True)) def test_piecewise_lambdify(): p = Piecewise( (x**2, x < 0), (x, Interval(0, 1, False, True).contains(x)), (2 - x, x >= 1), (0, True) ) f = lambdify(x, p) assert f(-2.0) == 4.0 assert f(0.0) == 0.0 assert f(0.5) == 0.5 assert f(2.0) == 0.0 def test_piecewise_series(): from sympy.series.order import O p1 = Piecewise((sin(x), x < 0), (cos(x), x > 0)) p2 = Piecewise((x + O(x**2), x < 0), (1 + O(x**2), x > 0)) assert p1.nseries(x, n=2) == p2 def test_piecewise_as_leading_term(): p1 = Piecewise((1/x, x > 1), (0, True)) p2 = Piecewise((x, x > 1), (0, True)) p3 = Piecewise((1/x, x > 1), (x, True)) p4 = Piecewise((x, x > 1), (1/x, True)) p5 = Piecewise((1/x, x > 1), (x, True)) p6 = Piecewise((1/x, x < 1), (x, True)) p7 = Piecewise((x, x < 1), (1/x, True)) p8 = Piecewise((x, x > 1), (1/x, True)) assert p1.as_leading_term(x) == 0 assert p2.as_leading_term(x) == 0 assert p3.as_leading_term(x) == x assert p4.as_leading_term(x) == 1/x assert p5.as_leading_term(x) == x assert p6.as_leading_term(x) == 1/x assert p7.as_leading_term(x) == x assert p8.as_leading_term(x) == 1/x def test_piecewise_complex(): p1 = Piecewise((2, x < 0), (1, 0 <= x)) p2 = Piecewise((2*I, x < 0), (I, 0 <= x)) p3 = Piecewise((I*x, x > 1), (1 + I, True)) p4 = Piecewise((-I*conjugate(x), x > 1), (1 - I, True)) assert conjugate(p1) == p1 assert conjugate(p2) == piecewise_fold(-p2) assert conjugate(p3) == p4 assert p1.is_imaginary is False assert p1.is_real is True assert p2.is_imaginary is True assert p2.is_real is False assert p3.is_imaginary is None assert p3.is_real is None assert p1.as_real_imag() == (p1, 0) assert p2.as_real_imag() == (0, -I*p2) def test_conjugate_transpose(): A, B = symbols("A B", commutative=False) p = Piecewise((A*B**2, x > 0), (A**2*B, True)) assert p.adjoint() == \ Piecewise((adjoint(A*B**2), x > 0), (adjoint(A**2*B), True)) assert p.conjugate() == \ Piecewise((conjugate(A*B**2), x > 0), (conjugate(A**2*B), True)) assert p.transpose() == \ Piecewise((transpose(A*B**2), x > 0), (transpose(A**2*B), True)) def test_piecewise_evaluate(): assert Piecewise((x, True)) == x assert Piecewise((x, True), evaluate=True) == x assert Piecewise((1, Eq(1, x))).args == ((1, Eq(x, 1)),) assert Piecewise((1, Eq(1, x)), evaluate=False).args == ( (1, Eq(1, x)),) # like the additive and multiplicative identities that # cannot be kept in Add/Mul, we also do not keep a single True p = Piecewise((x, True), evaluate=False) assert p == x def test_as_expr_set_pairs(): assert Piecewise((x, x > 0), (-x, x <= 0)).as_expr_set_pairs() == \ [(x, Interval(0, oo, True, True)), (-x, Interval(-oo, 0))] assert Piecewise(((x - 2)**2, x >= 0), (0, True)).as_expr_set_pairs() == \ [((x - 2)**2, Interval(0, oo)), (0, Interval(-oo, 0, True, True))] def test_S_srepr_is_identity(): p = Piecewise((10, Eq(x, 0)), (12, True)) q = S(srepr(p)) assert p == q def test_issue_12587(): # sort holes into intervals p = Piecewise((1, x > 4), (2, Not((x <= 3) & (x > -1))), (3, True)) assert p.integrate((x, -5, 5)) == 23 p = Piecewise((1, x > 1), (2, x < y), (3, True)) lim = x, -3, 3 ans = p.integrate(lim) for i in range(-1, 3): assert ans.subs(y, i) == p.subs(y, i).integrate(lim) def test_issue_11045(): assert integrate(1/(x*sqrt(x**2 - 1)), (x, 1, 2)) == pi/3 # handle And with Or arguments assert Piecewise((1, And(Or(x < 1, x > 3), x < 2)), (0, True) ).integrate((x, 0, 3)) == 1 # hidden false assert Piecewise((1, x > 1), (2, x > x + 1), (3, True) ).integrate((x, 0, 3)) == 5 # targetcond is Eq assert Piecewise((1, x > 1), (2, Eq(1, x)), (3, True) ).integrate((x, 0, 4)) == 6 # And has Relational needing to be solved assert Piecewise((1, And(2*x > x + 1, x < 2)), (0, True) ).integrate((x, 0, 3)) == 1 # Or has Relational needing to be solved assert Piecewise((1, Or(2*x > x + 2, x < 1)), (0, True) ).integrate((x, 0, 3)) == 2 # ignore hidden false (handled in canonicalization) assert Piecewise((1, x > 1), (2, x > x + 1), (3, True) ).integrate((x, 0, 3)) == 5 # watch for hidden True Piecewise assert Piecewise((2, Eq(1 - x, x*(1/x - 1))), (0, True) ).integrate((x, 0, 3)) == 6 # overlapping conditions of targetcond are recognized and ignored; # the condition x > 3 will be pre-empted by the first condition assert Piecewise((1, Or(x < 1, x > 2)), (2, x > 3), (3, True) ).integrate((x, 0, 4)) == 6 # convert Ne to Or assert Piecewise((1, Ne(x, 0)), (2, True) ).integrate((x, -1, 1)) == 2 # no default but well defined assert Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4)) ).integrate((x, 1, 4)) == 5 p = Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4))) nan = Undefined i = p.integrate((x, 1, y)) assert i == Piecewise( (y - 1, y < 1), (Min(3, y)**2/2 - Min(3, y) + Min(4, y) - S.Half, y <= Min(4, y)), (nan, True)) assert p.integrate((x, 1, -1)) == i.subs(y, -1) assert p.integrate((x, 1, 4)) == 5 assert p.integrate((x, 1, 5)) is nan # handle Not p = Piecewise((1, x > 1), (2, Not(And(x > 1, x< 3))), (3, True)) assert p.integrate((x, 0, 3)) == 4 # handle updating of int_expr when there is overlap p = Piecewise( (1, And(5 > x, x > 1)), (2, Or(x < 3, x > 7)), (4, x < 8)) assert p.integrate((x, 0, 10)) == 20 # And with Eq arg handling assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1)) ).integrate((x, 0, 3)) is S.NaN assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1)), (3, True) ).integrate((x, 0, 3)) == 7 assert Piecewise((1, x < 0), (2, And(Eq(x, 3), x < 1)), (3, True) ).integrate((x, -1, 1)) == 4 # middle condition doesn't matter: it's a zero width interval assert Piecewise((1, x < 1), (2, Eq(x, 3) & (y < x)), (3, True) ).integrate((x, 0, 3)) == 7 def test_holes(): nan = Undefined assert Piecewise((1, x < 2)).integrate(x) == Piecewise( (x, x < 2), (nan, True)) assert Piecewise((1, And(x > 1, x < 2))).integrate(x) == Piecewise( (nan, x < 1), (x, x < 2), (nan, True)) assert Piecewise((1, And(x > 1, x < 2))).integrate((x, 0, 3)) is nan assert Piecewise((1, And(x > 0, x < 4))).integrate((x, 1, 3)) == 2 # this also tests that the integrate method is used on non-Piecwise # arguments in _eval_integral A, B = symbols("A B") a, b = symbols('a b', real=True) assert Piecewise((A, And(x < 0, a < 1)), (B, Or(x < 1, a > 2)) ).integrate(x) == Piecewise( (B*x, (a > 2)), (Piecewise((A*x, x < 0), (B*x, x < 1), (nan, True)), a < 1), (Piecewise((B*x, x < 1), (nan, True)), True)) def test_issue_11922(): def f(x): return Piecewise((0, x < -1), (1 - x**2, x < 1), (0, True)) autocorr = lambda k: ( f(x) * f(x + k)).integrate((x, -1, 1)) assert autocorr(1.9) > 0 k = symbols('k') good_autocorr = lambda k: ( (1 - x**2) * f(x + k)).integrate((x, -1, 1)) a = good_autocorr(k) assert a.subs(k, 3) == 0 k = symbols('k', positive=True) a = good_autocorr(k) assert a.subs(k, 3) == 0 assert Piecewise((0, x < 1), (10, (x >= 1)) ).integrate() == Piecewise((0, x < 1), (10*x - 10, True)) def test_issue_5227(): f = 0.0032513612725229*Piecewise((0, x < -80.8461538461539), (-0.0160799238820171*x + 1.33215984776403, x < 2), (Piecewise((0.3, x > 123), (0.7, True)) + Piecewise((0.4, x > 2), (0.6, True)), x <= 123), (-0.00817409766454352*x + 2.10541401273885, x < 380.571428571429), (0, True)) i = integrate(f, (x, -oo, oo)) assert i == Integral(f, (x, -oo, oo)).doit() assert str(i) == '1.00195081676351' assert Piecewise((1, x - y < 0), (0, True) ).integrate(y) == Piecewise((0, y <= x), (-x + y, True)) def test_issue_10137(): a = Symbol('a', real=True) b = Symbol('b', real=True) x = Symbol('x', real=True) y = Symbol('y', real=True) p0 = Piecewise((0, Or(x < a, x > b)), (1, True)) p1 = Piecewise((0, Or(a > x, b < x)), (1, True)) assert integrate(p0, (x, y, oo)) == integrate(p1, (x, y, oo)) p3 = Piecewise((1, And(0 < x, x < a)), (0, True)) p4 = Piecewise((1, And(a > x, x > 0)), (0, True)) ip3 = integrate(p3, x) assert ip3 == Piecewise( (0, x <= 0), (x, x <= Max(0, a)), (Max(0, a), True)) ip4 = integrate(p4, x) assert ip4 == ip3 assert p3.integrate((x, 2, 4)) == Min(4, Max(2, a)) - 2 assert p4.integrate((x, 2, 4)) == Min(4, Max(2, a)) - 2 def test_stackoverflow_43852159(): f = lambda x: Piecewise((1, (x >= -1) & (x <= 1)), (0, True)) Conv = lambda x: integrate(f(x - y)*f(y), (y, -oo, +oo)) cx = Conv(x) assert cx.subs(x, -1.5) == cx.subs(x, 1.5) assert cx.subs(x, 3) == 0 assert piecewise_fold(f(x - y)*f(y)) == Piecewise( (1, (y >= -1) & (y <= 1) & (x - y >= -1) & (x - y <= 1)), (0, True)) def test_issue_12557(): ''' # 3200 seconds to compute the fourier part of issue import sympy as sym x,y,z,t = sym.symbols('x y z t') k = sym.symbols("k", integer=True) fourier = sym.fourier_series(sym.cos(k*x)*sym.sqrt(x**2), (x, -sym.pi, sym.pi)) assert fourier == FourierSeries( sqrt(x**2)*cos(k*x), (x, -pi, pi), (Piecewise((pi**2, Eq(k, 0)), (2*(-1)**k/k**2 - 2/k**2, True))/(2*pi), SeqFormula(Piecewise((pi**2, (Eq(_n, 0) & Eq(k, 0)) | (Eq(_n, 0) & Eq(_n, k) & Eq(k, 0)) | (Eq(_n, 0) & Eq(k, 0) & Eq(_n, -k)) | (Eq(_n, 0) & Eq(_n, k) & Eq(k, 0) & Eq(_n, -k))), (pi**2/2, Eq(_n, k) | Eq(_n, -k) | (Eq(_n, 0) & Eq(_n, k)) | (Eq(_n, k) & Eq(k, 0)) | (Eq(_n, 0) & Eq(_n, -k)) | (Eq(_n, k) & Eq(_n, -k)) | (Eq(k, 0) & Eq(_n, -k)) | (Eq(_n, 0) & Eq(_n, k) & Eq(_n, -k)) | (Eq(_n, k) & Eq(k, 0) & Eq(_n, -k))), ((-1)**k*pi**2*_n**3*sin(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 + pi*k**4) - (-1)**k*pi**2*_n**3*sin(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 - pi*k**4) + (-1)**k*pi*_n**2*cos(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 + pi*k**4) - (-1)**k*pi*_n**2*cos(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 - pi*k**4) - (-1)**k*pi**2*_n*k**2*sin(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 + pi*k**4) + (-1)**k*pi**2*_n*k**2*sin(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 - pi*k**4) + (-1)**k*pi*k**2*cos(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 + pi*k**4) - (-1)**k*pi*k**2*cos(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 - pi*k**4) - (2*_n**2 + 2*k**2)/(_n**4 - 2*_n**2*k**2 + k**4), True))*cos(_n*x)/pi, (_n, 1, oo)), SeqFormula(0, (_k, 1, oo)))) ''' x = symbols("x", real=True) k = symbols('k', integer=True, finite=True) abs2 = lambda x: Piecewise((-x, x <= 0), (x, x > 0)) assert integrate(abs2(x), (x, -pi, pi)) == pi**2 func = cos(k*x)*sqrt(x**2) assert integrate(func, (x, -pi, pi)) == Piecewise( (2*(-1)**k/k**2 - 2/k**2, Ne(k, 0)), (pi**2, True)) def test_issue_6900(): from itertools import permutations t0, t1, T, t = symbols('t0, t1 T t') f = Piecewise((0, t < t0), (x, And(t0 <= t, t < t1)), (0, t >= t1)) g = f.integrate(t) assert g == Piecewise( (0, t <= t0), (t*x - t0*x, t <= Max(t0, t1)), (-t0*x + x*Max(t0, t1), True)) for i in permutations(range(2)): reps = dict(zip((t0,t1), i)) for tt in range(-1,3): assert (g.xreplace(reps).subs(t,tt) == f.xreplace(reps).integrate(t).subs(t,tt)) lim = Tuple(t, t0, T) g = f.integrate(lim) ans = Piecewise( (-t0*x + x*Min(T, Max(t0, t1)), T > t0), (0, True)) for i in permutations(range(3)): reps = dict(zip((t0,t1,T), i)) tru = f.xreplace(reps).integrate(lim.xreplace(reps)) assert tru == ans.xreplace(reps) assert g == ans def test_issue_10122(): assert solve(abs(x) + abs(x - 1) - 1 > 0, x ) == Or(And(-oo < x, x < S.Zero), And(S.One < x, x < oo)) def test_issue_4313(): u = Piecewise((0, x <= 0), (1, x >= a), (x/a, True)) e = (u - u.subs(x, y))**2/(x - y)**2 M = Max(0, a) assert integrate(e, x).expand() == Piecewise( (Piecewise( (0, x <= 0), (-y**2/(a**2*x - a**2*y) + x/a**2 - 2*y*log(-y)/a**2 + 2*y*log(x - y)/a**2 - y/a**2, x <= M), (-y**2/(-a**2*y + a**2*M) + 1/(-y + M) - 1/(x - y) - 2*y*log(-y)/a**2 + 2*y*log(-y + M)/a**2 - y/a**2 + M/a**2, True)), ((a <= y) & (y <= 0)) | ((y <= 0) & (y > -oo))), (Piecewise( (-1/(x - y), x <= 0), (-a**2/(a**2*x - a**2*y) + 2*a*y/(a**2*x - a**2*y) - y**2/(a**2*x - a**2*y) + 2*log(-y)/a - 2*log(x - y)/a + 2/a + x/a**2 - 2*y*log(-y)/a**2 + 2*y*log(x - y)/a**2 - y/a**2, x <= M), (-a**2/(-a**2*y + a**2*M) + 2*a*y/(-a**2*y + a**2*M) - y**2/(-a**2*y + a**2*M) + 2*log(-y)/a - 2*log(-y + M)/a + 2/a - 2*y*log(-y)/a**2 + 2*y*log(-y + M)/a**2 - y/a**2 + M/a**2, True)), a <= y), (Piecewise( (-y**2/(a**2*x - a**2*y), x <= 0), (x/a**2 + y/a**2, x <= M), (a**2/(-a**2*y + a**2*M) - a**2/(a**2*x - a**2*y) - 2*a*y/(-a**2*y + a**2*M) + 2*a*y/(a**2*x - a**2*y) + y**2/(-a**2*y + a**2*M) - y**2/(a**2*x - a**2*y) + y/a**2 + M/a**2, True)), True)) def test__intervals(): assert Piecewise((x + 2, Eq(x, 3)))._intervals(x) == (True, []) assert Piecewise( (1, x > x + 1), (Piecewise((1, x < x + 1)), 2*x < 2*x + 1), (1, True))._intervals(x) == (True, [(-oo, oo, 1, 1)]) assert Piecewise((1, Ne(x, I)), (0, True))._intervals(x) == (True, [(-oo, oo, 1, 0)]) assert Piecewise((-cos(x), sin(x) >= 0), (cos(x), True) )._intervals(x) == (True, [(0, pi, -cos(x), 0), (-oo, oo, cos(x), 1)]) # the following tests that duplicates are removed and that non-Eq # generated zero-width intervals are removed assert Piecewise((1, Abs(x**(-2)) > 1), (0, True) )._intervals(x) == (True, [(-1, 0, 1, 0), (0, 1, 1, 0), (-oo, oo, 0, 1)]) def test_containment(): a, b, c, d, e = [1, 2, 3, 4, 5] p = (Piecewise((d, x > 1), (e, True))* Piecewise((a, Abs(x - 1) < 1), (b, Abs(x - 2) < 2), (c, True))) assert p.integrate(x).diff(x) == Piecewise( (c*e, x <= 0), (a*e, x <= 1), (a*d, x < 2), # this is what we want to get right (b*d, x < 4), (c*d, True)) def test_piecewise_with_DiracDelta(): d1 = DiracDelta(x - 1) assert integrate(d1, (x, -oo, oo)) == 1 assert integrate(d1, (x, 0, 2)) == 1 assert Piecewise((d1, Eq(x, 2)), (0, True)).integrate(x) == 0 assert Piecewise((d1, x < 2), (0, True)).integrate(x) == Piecewise( (Heaviside(x - 1), x < 2), (1, True)) # TODO raise error if function is discontinuous at limit of # integration, e.g. integrate(d1, (x, -2, 1)) or Piecewise( # (d1, Eq(x, 1) def test_issue_10258(): assert Piecewise((0, x < 1), (1, True)).is_zero is None assert Piecewise((-1, x < 1), (1, True)).is_zero is False a = Symbol('a', zero=True) assert Piecewise((0, x < 1), (a, True)).is_zero assert Piecewise((1, x < 1), (a, x < 3)).is_zero is None a = Symbol('a') assert Piecewise((0, x < 1), (a, True)).is_zero is None assert Piecewise((0, x < 1), (1, True)).is_nonzero is None assert Piecewise((1, x < 1), (2, True)).is_nonzero assert Piecewise((0, x < 1), (oo, True)).is_finite is None assert Piecewise((0, x < 1), (1, True)).is_finite b = Basic() assert Piecewise((b, x < 1)).is_finite is None # 10258 c = Piecewise((1, x < 0), (2, True)) < 3 assert c != True assert piecewise_fold(c) == True def test_issue_10087(): a, b = Piecewise((x, x > 1), (2, True)), Piecewise((x, x > 3), (3, True)) m = a*b f = piecewise_fold(m) for i in (0, 2, 4): assert m.subs(x, i) == f.subs(x, i) m = a + b f = piecewise_fold(m) for i in (0, 2, 4): assert m.subs(x, i) == f.subs(x, i) def test_issue_8919(): c = symbols('c:5') x = symbols("x") f1 = Piecewise((c[1], x < 1), (c[2], True)) f2 = Piecewise((c[3], x < Rational(1, 3)), (c[4], True)) assert integrate(f1*f2, (x, 0, 2) ) == c[1]*c[3]/3 + 2*c[1]*c[4]/3 + c[2]*c[4] f1 = Piecewise((0, x < 1), (2, True)) f2 = Piecewise((3, x < 2), (0, True)) assert integrate(f1*f2, (x, 0, 3)) == 6 y = symbols("y", positive=True) a, b, c, x, z = symbols("a,b,c,x,z", real=True) I = Integral(Piecewise( (0, (x >= y) | (x < 0) | (b > c)), (a, True)), (x, 0, z)) ans = I.doit() assert ans == Piecewise((0, b > c), (a*Min(y, z) - a*Min(0, z), True)) for cond in (True, False): for yy in range(1, 3): for zz in range(-yy, 0, yy): reps = [(b > c, cond), (y, yy), (z, zz)] assert ans.subs(reps) == I.subs(reps).doit() def test_unevaluated_integrals(): f = Function('f') p = Piecewise((1, Eq(f(x) - 1, 0)), (2, x - 10 < 0), (0, True)) assert p.integrate(x) == Integral(p, x) assert p.integrate((x, 0, 5)) == Integral(p, (x, 0, 5)) # test it by replacing f(x) with x%2 which will not # affect the answer: the integrand is essentially 2 over # the domain of integration assert Integral(p, (x, 0, 5)).subs(f(x), x%2).n() == 10 # this is a test of using _solve_inequality when # solve_univariate_inequality fails assert p.integrate(y) == Piecewise( (y, Eq(f(x), 1) | ((x < 10) & Eq(f(x), 1))), (2*y, (x > -oo) & (x < 10)), (0, True)) def test_conditions_as_alternate_booleans(): a, b, c = symbols('a:c') assert Piecewise((x, Piecewise((y < 1, x > 0), (y > 1, True))) ) == Piecewise((x, ITE(x > 0, y < 1, y > 1))) def test_Piecewise_rewrite_as_ITE(): a, b, c, d = symbols('a:d') def _ITE(*args): return Piecewise(*args).rewrite(ITE) assert _ITE((a, x < 1), (b, x >= 1)) == ITE(x < 1, a, b) assert _ITE((a, x < 1), (b, x < oo)) == ITE(x < 1, a, b) assert _ITE((a, x < 1), (b, Or(y < 1, x < oo)), (c, y > 0) ) == ITE(x < 1, a, b) assert _ITE((a, x < 1), (b, True)) == ITE(x < 1, a, b) assert _ITE((a, x < 1), (b, x < 2), (c, True) ) == ITE(x < 1, a, ITE(x < 2, b, c)) assert _ITE((a, x < 1), (b, y < 2), (c, True) ) == ITE(x < 1, a, ITE(y < 2, b, c)) assert _ITE((a, x < 1), (b, x < oo), (c, y < 1) ) == ITE(x < 1, a, b) assert _ITE((a, x < 1), (c, y < 1), (b, x < oo), (d, True) ) == ITE(x < 1, a, ITE(y < 1, c, b)) assert _ITE((a, x < 0), (b, Or(x < oo, y < 1)) ) == ITE(x < 0, a, b) raises(TypeError, lambda: _ITE((x + 1, x < 1), (x, True))) # if `a` in the following were replaced with y then the coverage # is complete but something other than as_set would need to be # used to detect this raises(NotImplementedError, lambda: _ITE((x, x < y), (y, x >= a))) raises(ValueError, lambda: _ITE((a, x < 2), (b, x > 3))) def test_issue_14052(): assert integrate(abs(sin(x)), (x, 0, 2*pi)) == 4 def test_issue_14240(): assert piecewise_fold( Piecewise((1, a), (2, b), (4, True)) + Piecewise((8, a), (16, True)) ) == Piecewise((9, a), (18, b), (20, True)) assert piecewise_fold( Piecewise((2, a), (3, b), (5, True)) * Piecewise((7, a), (11, True)) ) == Piecewise((14, a), (33, b), (55, True)) # these will hang if naive folding is used assert piecewise_fold(Add(*[ Piecewise((i, a), (0, True)) for i in range(40)]) ) == Piecewise((780, a), (0, True)) assert piecewise_fold(Mul(*[ Piecewise((i, a), (0, True)) for i in range(1, 41)]) ) == Piecewise((factorial(40), a), (0, True)) def test_issue_14787(): x = Symbol('x') f = Piecewise((x, x < 1), ((S(58) / 7), True)) assert str(f.evalf()) == "Piecewise((x, x < 1), (8.28571428571429, True))" def test_issue_8458(): x, y = symbols('x y') # Original issue p1 = Piecewise((0, Eq(x, 0)), (sin(x), True)) assert p1.simplify() == sin(x) # Slightly larger variant p2 = Piecewise((x, Eq(x, 0)), (4*x + (y-2)**4, Eq(x, 0) & Eq(x+y, 2)), (sin(x), True)) assert p2.simplify() == sin(x) # Test for problem highlighted during review p3 = Piecewise((x+1, Eq(x, -1)), (4*x + (y-2)**4, Eq(x, 0) & Eq(x+y, 2)), (sin(x), True)) assert p3.simplify() == Piecewise((0, Eq(x, -1)), (sin(x), True)) def test_issue_16417(): z = Symbol('z') assert unchanged(Piecewise, (1, Or(Eq(im(z), 0), Gt(re(z), 0))), (2, True)) x = Symbol('x') assert unchanged(Piecewise, (S.Pi, re(x) < 0), (0, Or(re(x) > 0, Ne(im(x), 0))), (S.NaN, True)) r = Symbol('r', real=True) p = Piecewise((S.Pi, re(r) < 0), (0, Or(re(r) > 0, Ne(im(r), 0))), (S.NaN, True)) assert p == Piecewise((S.Pi, r < 0), (0, r > 0), (S.NaN, True), evaluate=False) # Does not work since imaginary != 0... #i = Symbol('i', imaginary=True) #p = Piecewise((S.Pi, re(i) < 0), # (0, Or(re(i) > 0, Ne(im(i), 0))), # (S.NaN, True)) #assert p == Piecewise((0, Ne(im(i), 0)), # (S.NaN, True), evaluate=False) i = I*r p = Piecewise((S.Pi, re(i) < 0), (0, Or(re(i) > 0, Ne(im(i), 0))), (S.NaN, True)) assert p == Piecewise((0, Ne(im(i), 0)), (S.NaN, True), evaluate=False) assert p == Piecewise((0, Ne(r, 0)), (S.NaN, True), evaluate=False) def test_eval_rewrite_as_KroneckerDelta(): x, y, z, n, t, m = symbols('x y z n t m') K = KroneckerDelta f = lambda p: expand(p.rewrite(K)) p1 = Piecewise((0, Eq(x, y)), (1, True)) assert f(p1) == 1 - K(x, y) p2 = Piecewise((x, Eq(y,0)), (z, Eq(t,0)), (n, True)) assert f(p2) == n*K(0, t)*K(0, y) - n*K(0, t) - n*K(0, y) + n + \ x*K(0, y) - z*K(0, t)*K(0, y) + z*K(0, t) p3 = Piecewise((1, Ne(x, y)), (0, True)) assert f(p3) == 1 - K(x, y) p4 = Piecewise((1, Eq(x, 3)), (4, True), (5, True)) assert f(p4) == 4 - 3*K(3, x) p5 = Piecewise((3, Ne(x, 2)), (4, Eq(y, 2)), (5, True)) assert f(p5) == -K(2, x)*K(2, y) + 2*K(2, x) + 3 p6 = Piecewise((0, Ne(x, 1) & Ne(y, 4)), (1, True)) assert f(p6) == -K(1, x)*K(4, y) + K(1, x) + K(4, y) p7 = Piecewise((2, Eq(y, 3) & Ne(x, 2)), (1, True)) assert f(p7) == -K(2, x)*K(3, y) + K(3, y) + 1 p8 = Piecewise((4, Eq(x, 3) & Ne(y, 2)), (1, True)) assert f(p8) == -3*K(2, y)*K(3, x) + 3*K(3, x) + 1 p9 = Piecewise((6, Eq(x, 4) & Eq(y, 1)), (1, True)) assert f(p9) == 5 * K(1, y) * K(4, x) + 1 p10 = Piecewise((4, Ne(x, -4) | Ne(y, 1)), (1, True)) assert f(p10) == -3 * K(-4, x) * K(1, y) + 4 p11 = Piecewise((1, Eq(y, 2) | Ne(x, -3)), (2, True)) assert f(p11) == -K(-3, x)*K(2, y) + K(-3, x) + 1 p12 = Piecewise((-1, Eq(x, 1) | Ne(y, 3)), (1, True)) assert f(p12) == -2*K(1, x)*K(3, y) + 2*K(3, y) - 1 p13 = Piecewise((3, Eq(x, 2) | Eq(y, 4)), (1, True)) assert f(p13) == -2*K(2, x)*K(4, y) + 2*K(2, x) + 2*K(4, y) + 1 p14 = Piecewise((1, Ne(x, 0) | Ne(y, 1)), (3, True)) assert f(p14) == 2 * K(0, x) * K(1, y) + 1 p15 = Piecewise((2, Eq(x, 3) | Ne(y, 2)), (3, Eq(x, 4) & Eq(y, 5)), (1, True)) assert f(p15) == -2*K(2, y)*K(3, x)*K(4, x)*K(5, y) + K(2, y)*K(3, x) + \ 2*K(2, y)*K(4, x)*K(5, y) - K(2, y) + 2 p16 = Piecewise((0, Ne(m, n)), (1, True))*Piecewise((0, Ne(n, t)), (1, True))\ *Piecewise((0, Ne(n, x)), (1, True)) - Piecewise((0, Ne(t, x)), (1, True)) assert f(p16) == K(m, n)*K(n, t)*K(n, x) - K(t, x) p17 = Piecewise((0, Ne(t, x) & (Ne(m, n) | Ne(n, t) | Ne(n, x))), (1, Ne(t, x)), (-1, Ne(m, n) | Ne(n, t) | Ne(n, x)), (0, True)) assert f(p17) == K(m, n)*K(n, t)*K(n, x) - K(t, x) p18 = Piecewise((-4, Eq(y, 1) | (Eq(x, -5) & Eq(x, z))), (4, True)) 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 p19 = Piecewise((0, x > 2), (1, True)) assert f(p19) == p19 p20 = Piecewise((0, And(x < 2, x > -5)), (1, True)) assert f(p20) == p20 p21 = Piecewise((0, Or(x > 1, x < 0)), (1, True)) assert f(p21) == p21 p22 = Piecewise((0, ~((Eq(y, -1) | Ne(x, 0)) & (Ne(x, 1) | Ne(y, -1)))), (1, True)) assert f(p22) == K(-1, y)*K(0, x) - K(-1, y)*K(1, x) - K(0, x) + 1 @slow def test_identical_conds_issue(): from sympy.stats import Uniform, density u1 = Uniform('u1', 0, 1) u2 = Uniform('u2', 0, 1) # Result is quite big, so not really important here (and should ideally be # simpler). Should not give an exception though. density(u1 + u2) def test_issue_7370(): f = Piecewise((1, x <= 2400)) v = integrate(f, (x, 0, Float("252.4", 30))) assert str(v) == '252.400000000000000000000000000' def test_issue_14933(): x = Symbol('x') y = Symbol('y') inp = MatrixSymbol('inp', 1, 1) rep_dict = {y: inp[0, 0], x: inp[0, 0]} p = Piecewise((1, ITE(y > 0, x < 0, True))) assert p.xreplace(rep_dict) == Piecewise((1, ITE(inp[0, 0] > 0, inp[0, 0] < 0, True))) def test_issue_16715(): raises(NotImplementedError, lambda: Piecewise((x, x<0), (0, y>1)).as_expr_set_pairs()) def test_issue_20360(): t, tau = symbols("t tau", real=True) n = symbols("n", integer=True) lam = pi * (n - S.Half) eq = integrate(exp(lam * tau), (tau, 0, t)) assert simplify(eq) == (2*exp(pi*t*(2*n - 1)/2) - 2)/(pi*(2*n - 1)) def test_piecewise_eval(): # XXX these tests might need modification if this # simplification is moved out of eval and into # boolalg or Piecewise simplification functions f = lambda x: x.args[0].cond # unsimplified assert f(Piecewise((x, (x > -oo) & (x < 3))) ) == ((x > -oo) & (x < 3)) assert f(Piecewise((x, (x > -oo) & (x < oo))) ) == ((x > -oo) & (x < oo)) assert f(Piecewise((x, (x > -3) & (x < 3))) ) == ((x > -3) & (x < 3)) assert f(Piecewise((x, (x > -3) & (x < oo))) ) == ((x > -3) & (x < oo)) assert f(Piecewise((x, (x <= 3) & (x > -oo))) ) == ((x <= 3) & (x > -oo)) assert f(Piecewise((x, (x <= 3) & (x > -3))) ) == ((x <= 3) & (x > -3)) assert f(Piecewise((x, (x >= -3) & (x < 3))) ) == ((x >= -3) & (x < 3)) assert f(Piecewise((x, (x >= -3) & (x < oo))) ) == ((x >= -3) & (x < oo)) assert f(Piecewise((x, (x >= -3) & (x <= 3))) ) == ((x >= -3) & (x <= 3)) # could simplify by keeping only the first # arg of result assert f(Piecewise((x, (x <= oo) & (x > -oo))) ) == (x > -oo) & (x <= oo) assert f(Piecewise((x, (x <= oo) & (x > -3))) ) == (x > -3) & (x <= oo) assert f(Piecewise((x, (x >= -oo) & (x < 3))) ) == (x < 3) & (x >= -oo) assert f(Piecewise((x, (x >= -oo) & (x < oo))) ) == (x < oo) & (x >= -oo) assert f(Piecewise((x, (x >= -oo) & (x <= 3))) ) == (x <= 3) & (x >= -oo) assert f(Piecewise((x, (x >= -oo) & (x <= oo))) ) == (x <= oo) & (x >= -oo) # but cannot be True unless x is real assert f(Piecewise((x, (x >= -3) & (x <= oo))) ) == (x >= -3) & (x <= oo) assert f(Piecewise((x, (Abs(arg(a)) <= 1) | (Abs(arg(a)) < 1))) ) == (Abs(arg(a)) <= 1) | (Abs(arg(a)) < 1) def test_issue_22533(): x = Symbol('x', real=True) f = Piecewise((-1 / x, x <= 0), (1 / x, True)) assert integrate(f, x) == Piecewise((-log(x), x <= 0), (log(x), True))
ab51e9bb558c43674a588701e26fdb0f2c1b25aac418d1da8992c4e18534e0f6
import itertools as it from sympy.core.expr import unchanged from sympy.core.function import Function from sympy.core.numbers import I, oo, Rational from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.external import import_module from sympy.functions.elementary.exponential import log from sympy.functions.elementary.integers import floor, ceiling from sympy.functions.elementary.miscellaneous import (sqrt, cbrt, root, Min, Max, real_root, Rem) from sympy.functions.elementary.trigonometric import cos, sin from sympy.functions.special.delta_functions import Heaviside from sympy.utilities.lambdify import lambdify from sympy.testing.pytest import raises, skip, ignore_warnings def test_Min(): from sympy.abc import x, y, z n = Symbol('n', negative=True) n_ = Symbol('n_', negative=True) nn = Symbol('nn', nonnegative=True) nn_ = Symbol('nn_', nonnegative=True) p = Symbol('p', positive=True) p_ = Symbol('p_', positive=True) np = Symbol('np', nonpositive=True) np_ = Symbol('np_', nonpositive=True) r = Symbol('r', real=True) assert Min(5, 4) == 4 assert Min(-oo, -oo) is -oo assert Min(-oo, n) is -oo assert Min(n, -oo) is -oo assert Min(-oo, np) is -oo assert Min(np, -oo) is -oo assert Min(-oo, 0) is -oo assert Min(0, -oo) is -oo assert Min(-oo, nn) is -oo assert Min(nn, -oo) is -oo assert Min(-oo, p) is -oo assert Min(p, -oo) is -oo assert Min(-oo, oo) is -oo assert Min(oo, -oo) is -oo assert Min(n, n) == n assert unchanged(Min, n, np) assert Min(np, n) == Min(n, np) assert Min(n, 0) == n assert Min(0, n) == n assert Min(n, nn) == n assert Min(nn, n) == n assert Min(n, p) == n assert Min(p, n) == n assert Min(n, oo) == n assert Min(oo, n) == n assert Min(np, np) == np assert Min(np, 0) == np assert Min(0, np) == np assert Min(np, nn) == np assert Min(nn, np) == np assert Min(np, p) == np assert Min(p, np) == np assert Min(np, oo) == np assert Min(oo, np) == np assert Min(0, 0) == 0 assert Min(0, nn) == 0 assert Min(nn, 0) == 0 assert Min(0, p) == 0 assert Min(p, 0) == 0 assert Min(0, oo) == 0 assert Min(oo, 0) == 0 assert Min(nn, nn) == nn assert unchanged(Min, nn, p) assert Min(p, nn) == Min(nn, p) assert Min(nn, oo) == nn assert Min(oo, nn) == nn assert Min(p, p) == p assert Min(p, oo) == p assert Min(oo, p) == p assert Min(oo, oo) is oo assert Min(n, n_).func is Min assert Min(nn, nn_).func is Min assert Min(np, np_).func is Min assert Min(p, p_).func is Min # lists assert Min() is S.Infinity assert Min(x) == x assert Min(x, y) == Min(y, x) assert Min(x, y, z) == Min(z, y, x) assert Min(x, Min(y, z)) == Min(z, y, x) assert Min(x, Max(y, -oo)) == Min(x, y) assert Min(p, oo, n, p, p, p_) == n assert Min(p_, n_, p) == n_ assert Min(n, oo, -7, p, p, 2) == Min(n, -7) assert Min(2, x, p, n, oo, n_, p, 2, -2, -2) == Min(-2, x, n, n_) assert Min(0, x, 1, y) == Min(0, x, y) assert Min(1000, 100, -100, x, p, n) == Min(n, x, -100) assert unchanged(Min, sin(x), cos(x)) assert Min(sin(x), cos(x)) == Min(cos(x), sin(x)) assert Min(cos(x), sin(x)).subs(x, 1) == cos(1) assert Min(cos(x), sin(x)).subs(x, S.Half) == sin(S.Half) raises(ValueError, lambda: Min(cos(x), sin(x)).subs(x, I)) raises(ValueError, lambda: Min(I)) raises(ValueError, lambda: Min(I, x)) raises(ValueError, lambda: Min(S.ComplexInfinity, x)) assert Min(1, x).diff(x) == Heaviside(1 - x) assert Min(x, 1).diff(x) == Heaviside(1 - x) assert Min(0, -x, 1 - 2*x).diff(x) == -Heaviside(x + Min(0, -2*x + 1)) \ - 2*Heaviside(2*x + Min(0, -x) - 1) # issue 7619 f = Function('f') assert Min(1, 2*Min(f(1), 2)) # doesn't fail # issue 7233 e = Min(0, x) assert e.n().args == (0, x) # issue 8643 m = Min(n, p_, n_, r) assert m.is_positive is False assert m.is_nonnegative is False assert m.is_negative is True m = Min(p, p_) assert m.is_positive is True assert m.is_nonnegative is True assert m.is_negative is False m = Min(p, nn_, p_) assert m.is_positive is None assert m.is_nonnegative is True assert m.is_negative is False m = Min(nn, p, r) assert m.is_positive is None assert m.is_nonnegative is None assert m.is_negative is None def test_Max(): from sympy.abc import x, y, z n = Symbol('n', negative=True) n_ = Symbol('n_', negative=True) nn = Symbol('nn', nonnegative=True) p = Symbol('p', positive=True) p_ = Symbol('p_', positive=True) r = Symbol('r', real=True) assert Max(5, 4) == 5 # lists assert Max() is S.NegativeInfinity assert Max(x) == x assert Max(x, y) == Max(y, x) assert Max(x, y, z) == Max(z, y, x) assert Max(x, Max(y, z)) == Max(z, y, x) assert Max(x, Min(y, oo)) == Max(x, y) assert Max(n, -oo, n_, p, 2) == Max(p, 2) assert Max(n, -oo, n_, p) == p assert Max(2, x, p, n, -oo, S.NegativeInfinity, n_, p, 2) == Max(2, x, p) assert Max(0, x, 1, y) == Max(1, x, y) assert Max(r, r + 1, r - 1) == 1 + r assert Max(1000, 100, -100, x, p, n) == Max(p, x, 1000) assert Max(cos(x), sin(x)) == Max(sin(x), cos(x)) assert Max(cos(x), sin(x)).subs(x, 1) == sin(1) assert Max(cos(x), sin(x)).subs(x, S.Half) == cos(S.Half) raises(ValueError, lambda: Max(cos(x), sin(x)).subs(x, I)) raises(ValueError, lambda: Max(I)) raises(ValueError, lambda: Max(I, x)) raises(ValueError, lambda: Max(S.ComplexInfinity, 1)) assert Max(n, -oo, n_, p, 2) == Max(p, 2) assert Max(n, -oo, n_, p, 1000) == Max(p, 1000) assert Max(1, x).diff(x) == Heaviside(x - 1) assert Max(x, 1).diff(x) == Heaviside(x - 1) assert Max(x**2, 1 + x, 1).diff(x) == \ 2*x*Heaviside(x**2 - Max(1, x + 1)) \ + Heaviside(x - Max(1, x**2) + 1) e = Max(0, x) assert e.n().args == (0, x) # issue 8643 m = Max(p, p_, n, r) assert m.is_positive is True assert m.is_nonnegative is True assert m.is_negative is False m = Max(n, n_) assert m.is_positive is False assert m.is_nonnegative is False assert m.is_negative is True m = Max(n, n_, r) assert m.is_positive is None assert m.is_nonnegative is None assert m.is_negative is None m = Max(n, nn, r) assert m.is_positive is None assert m.is_nonnegative is True assert m.is_negative is False def test_minmax_assumptions(): r = Symbol('r', real=True) a = Symbol('a', real=True, algebraic=True) t = Symbol('t', real=True, transcendental=True) q = Symbol('q', rational=True) p = Symbol('p', irrational=True) n = Symbol('n', rational=True, integer=False) i = Symbol('i', integer=True) o = Symbol('o', odd=True) e = Symbol('e', even=True) k = Symbol('k', prime=True) reals = [r, a, t, q, p, n, i, o, e, k] for ext in (Max, Min): for x, y in it.product(reals, repeat=2): # Must be real assert ext(x, y).is_real # Algebraic? if x.is_algebraic and y.is_algebraic: assert ext(x, y).is_algebraic elif x.is_transcendental and y.is_transcendental: assert ext(x, y).is_transcendental else: assert ext(x, y).is_algebraic is None # Rational? if x.is_rational and y.is_rational: assert ext(x, y).is_rational elif x.is_irrational and y.is_irrational: assert ext(x, y).is_irrational else: assert ext(x, y).is_rational is None # Integer? if x.is_integer and y.is_integer: assert ext(x, y).is_integer elif x.is_noninteger and y.is_noninteger: assert ext(x, y).is_noninteger else: assert ext(x, y).is_integer is None # Odd? if x.is_odd and y.is_odd: assert ext(x, y).is_odd elif x.is_odd is False and y.is_odd is False: assert ext(x, y).is_odd is False else: assert ext(x, y).is_odd is None # Even? if x.is_even and y.is_even: assert ext(x, y).is_even elif x.is_even is False and y.is_even is False: assert ext(x, y).is_even is False else: assert ext(x, y).is_even is None # Prime? if x.is_prime and y.is_prime: assert ext(x, y).is_prime elif x.is_prime is False and y.is_prime is False: assert ext(x, y).is_prime is False else: assert ext(x, y).is_prime is None def test_issue_8413(): x = Symbol('x', real=True) # we can't evaluate in general because non-reals are not # comparable: Min(floor(3.2 + I), 3.2 + I) -> ValueError assert Min(floor(x), x) == floor(x) assert Min(ceiling(x), x) == x assert Max(floor(x), x) == x assert Max(ceiling(x), x) == ceiling(x) def test_root(): from sympy.abc import x n = Symbol('n', integer=True) k = Symbol('k', integer=True) assert root(2, 2) == sqrt(2) assert root(2, 1) == 2 assert root(2, 3) == 2**Rational(1, 3) assert root(2, 3) == cbrt(2) assert root(2, -5) == 2**Rational(4, 5)/2 assert root(-2, 1) == -2 assert root(-2, 2) == sqrt(2)*I assert root(-2, 1) == -2 assert root(x, 2) == sqrt(x) assert root(x, 1) == x assert root(x, 3) == x**Rational(1, 3) assert root(x, 3) == cbrt(x) assert root(x, -5) == x**Rational(-1, 5) assert root(x, n) == x**(1/n) assert root(x, -n) == x**(-1/n) assert root(x, n, k) == (-1)**(2*k/n)*x**(1/n) def test_real_root(): assert real_root(-8, 3) == -2 assert real_root(-16, 4) == root(-16, 4) r = root(-7, 4) assert real_root(r) == r r1 = root(-1, 3) r2 = r1**2 r3 = root(-1, 4) assert real_root(r1 + r2 + r3) == -1 + r2 + r3 assert real_root(root(-2, 3)) == -root(2, 3) assert real_root(-8., 3) == -2 x = Symbol('x') n = Symbol('n') g = real_root(x, n) assert g.subs(dict(x=-8, n=3)) == -2 assert g.subs(dict(x=8, n=3)) == 2 # give principle root if there is no real root -- if this is not desired # then maybe a Root class is needed to raise an error instead assert g.subs(dict(x=I, n=3)) == cbrt(I) assert g.subs(dict(x=-8, n=2)) == sqrt(-8) assert g.subs(dict(x=I, n=2)) == sqrt(I) def test_issue_11463(): numpy = import_module('numpy') if not numpy: skip("numpy not installed.") x = Symbol('x') f = lambdify(x, real_root((log(x/(x-2))), 3), 'numpy') # numpy.select evaluates all options before considering conditions, # so it raises a warning about root of negative number which does # not affect the outcome. This warning is suppressed here with ignore_warnings(RuntimeWarning): assert f(numpy.array(-1)) < -1 def test_rewrite_MaxMin_as_Heaviside(): from sympy.abc import x assert Max(0, x).rewrite(Heaviside) == x*Heaviside(x) assert Max(3, x).rewrite(Heaviside) == x*Heaviside(x - 3) + \ 3*Heaviside(-x + 3) assert Max(0, x+2, 2*x).rewrite(Heaviside) == \ 2*x*Heaviside(2*x)*Heaviside(x - 2) + \ (x + 2)*Heaviside(-x + 2)*Heaviside(x + 2) assert Min(0, x).rewrite(Heaviside) == x*Heaviside(-x) assert Min(3, x).rewrite(Heaviside) == x*Heaviside(-x + 3) + \ 3*Heaviside(x - 3) assert Min(x, -x, -2).rewrite(Heaviside) == \ x*Heaviside(-2*x)*Heaviside(-x - 2) - \ x*Heaviside(2*x)*Heaviside(x - 2) \ - 2*Heaviside(-x + 2)*Heaviside(x + 2) def test_rewrite_MaxMin_as_Piecewise(): from sympy.core.symbol import symbols from sympy.functions.elementary.piecewise import Piecewise x, y, z, a, b = symbols('x y z a b', real=True) vx, vy, va = symbols('vx vy va') assert Max(a, b).rewrite(Piecewise) == Piecewise((a, a >= b), (b, True)) assert Max(x, y, z).rewrite(Piecewise) == Piecewise((x, (x >= y) & (x >= z)), (y, y >= z), (z, True)) assert Max(x, y, a, b).rewrite(Piecewise) == Piecewise((a, (a >= b) & (a >= x) & (a >= y)), (b, (b >= x) & (b >= y)), (x, x >= y), (y, True)) assert Min(a, b).rewrite(Piecewise) == Piecewise((a, a <= b), (b, True)) assert Min(x, y, z).rewrite(Piecewise) == Piecewise((x, (x <= y) & (x <= z)), (y, y <= z), (z, True)) assert Min(x, y, a, b).rewrite(Piecewise) == Piecewise((a, (a <= b) & (a <= x) & (a <= y)), (b, (b <= x) & (b <= y)), (x, x <= y), (y, True)) # Piecewise rewriting of Min/Max does also takes place for not explicitly real arguments assert Max(vx, vy).rewrite(Piecewise) == Piecewise((vx, vx >= vy), (vy, True)) assert Min(va, vx, vy).rewrite(Piecewise) == Piecewise((va, (va <= vx) & (va <= vy)), (vx, vx <= vy), (vy, True)) def test_issue_11099(): from sympy.abc import x, y # some fixed value tests fixed_test_data = {x: -2, y: 3} assert Min(x, y).evalf(subs=fixed_test_data) == \ Min(x, y).subs(fixed_test_data).evalf() assert Max(x, y).evalf(subs=fixed_test_data) == \ Max(x, y).subs(fixed_test_data).evalf() # randomly generate some test data from sympy.core.random import randint for i in range(20): random_test_data = {x: randint(-100, 100), y: randint(-100, 100)} assert Min(x, y).evalf(subs=random_test_data) == \ Min(x, y).subs(random_test_data).evalf() assert Max(x, y).evalf(subs=random_test_data) == \ Max(x, y).subs(random_test_data).evalf() def test_issue_12638(): from sympy.abc import a, b, c assert Min(a, b, c, Max(a, b)) == Min(a, b, c) assert Min(a, b, Max(a, b, c)) == Min(a, b) assert Min(a, b, Max(a, c)) == Min(a, b) def test_issue_21399(): from sympy.abc import a, b, c assert Max(Min(a, b), Min(a, b, c)) == Min(a, b) def test_instantiation_evaluation(): from sympy.abc import v, w, x, y, z assert Min(1, Max(2, x)) == 1 assert Max(3, Min(2, x)) == 3 assert Min(Max(x, y), Max(x, z)) == Max(x, Min(y, z)) assert set(Min(Max(w, x), Max(y, z)).args) == { Max(w, x), Max(y, z)} assert Min(Max(x, y), Max(x, z), w) == Min( w, Max(x, Min(y, z))) A, B = Min, Max for i in range(2): assert A(x, B(x, y)) == x assert A(x, B(y, A(x, w, z))) == A(x, B(y, A(w, z))) A, B = B, A assert Min(w, Max(x, y), Max(v, x, z)) == Min( w, Max(x, Min(y, Max(v, z)))) def test_rewrite_as_Abs(): from itertools import permutations from sympy.functions.elementary.complexes import Abs from sympy.abc import x, y, z, w def test(e): free = e.free_symbols a = e.rewrite(Abs) assert not a.has(Min, Max) for i in permutations(range(len(free))): reps = dict(zip(free, i)) assert a.xreplace(reps) == e.xreplace(reps) test(Min(x, y)) test(Max(x, y)) test(Min(x, y, z)) test(Min(Max(w, x), Max(y, z))) def test_issue_14000(): assert isinstance(sqrt(4, evaluate=False), Pow) == True assert isinstance(cbrt(3.5, evaluate=False), Pow) == True assert isinstance(root(16, 4, evaluate=False), Pow) == True assert sqrt(4, evaluate=False) == Pow(4, S.Half, evaluate=False) assert cbrt(3.5, evaluate=False) == Pow(3.5, Rational(1, 3), evaluate=False) assert root(4, 2, evaluate=False) == Pow(4, S.Half, evaluate=False) assert root(16, 4, 2, evaluate=False).has(Pow) == True assert real_root(-8, 3, evaluate=False).has(Pow) == True def test_issue_6899(): from sympy.core.function import Lambda x = Symbol('x') eqn = Lambda(x, x) assert eqn.func(*eqn.args) == eqn def test_Rem(): from sympy.abc import x, y assert Rem(5, 3) == 2 assert Rem(-5, 3) == -2 assert Rem(5, -3) == 2 assert Rem(-5, -3) == -2 assert Rem(x**3, y) == Rem(x**3, y) assert Rem(Rem(-5, 3) + 3, 3) == 1
a05ca412d5051a5e1bcdb2e59333e26c898facc1bad8202190c4316ded2d5445
from sympy.calculus.accumulationbounds import AccumBounds from sympy.core.function import (expand_mul, expand_trig) from sympy.core.numbers import (E, I, Integer, Rational, nan, oo, pi, zoo) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import (im, re) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.hyperbolic import (acosh, acoth, acsch, asech, asinh, atanh, cosh, coth, csch, sech, sinh, tanh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acos, asin, cos, cot, sec, sin, tan) from sympy.series.order import O from sympy.core.expr import unchanged from sympy.core.function import ArgumentIndexError from sympy.testing.pytest import raises def test_sinh(): x, y = symbols('x,y') k = Symbol('k', integer=True) assert sinh(nan) is nan assert sinh(zoo) is nan assert sinh(oo) is oo assert sinh(-oo) is -oo assert sinh(0) == 0 assert unchanged(sinh, 1) assert sinh(-1) == -sinh(1) assert unchanged(sinh, x) assert sinh(-x) == -sinh(x) assert unchanged(sinh, pi) assert sinh(-pi) == -sinh(pi) assert unchanged(sinh, 2**1024 * E) assert sinh(-2**1024 * E) == -sinh(2**1024 * E) assert sinh(pi*I) == 0 assert sinh(-pi*I) == 0 assert sinh(2*pi*I) == 0 assert sinh(-2*pi*I) == 0 assert sinh(-3*10**73*pi*I) == 0 assert sinh(7*10**103*pi*I) == 0 assert sinh(pi*I/2) == I assert sinh(-pi*I/2) == -I assert sinh(pi*I*Rational(5, 2)) == I assert sinh(pi*I*Rational(7, 2)) == -I assert sinh(pi*I/3) == S.Half*sqrt(3)*I assert sinh(pi*I*Rational(-2, 3)) == Rational(-1, 2)*sqrt(3)*I assert sinh(pi*I/4) == S.Half*sqrt(2)*I assert sinh(-pi*I/4) == Rational(-1, 2)*sqrt(2)*I assert sinh(pi*I*Rational(17, 4)) == S.Half*sqrt(2)*I assert sinh(pi*I*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)*I assert sinh(pi*I/6) == S.Half*I assert sinh(-pi*I/6) == Rational(-1, 2)*I assert sinh(pi*I*Rational(7, 6)) == Rational(-1, 2)*I assert sinh(pi*I*Rational(-5, 6)) == Rational(-1, 2)*I assert sinh(pi*I/105) == sin(pi/105)*I assert sinh(-pi*I/105) == -sin(pi/105)*I assert unchanged(sinh, 2 + 3*I) assert sinh(x*I) == sin(x)*I assert sinh(k*pi*I) == 0 assert sinh(17*k*pi*I) == 0 assert sinh(k*pi*I/2) == sin(k*pi/2)*I assert sinh(x).as_real_imag(deep=False) == (cos(im(x))*sinh(re(x)), sin(im(x))*cosh(re(x))) x = Symbol('x', extended_real=True) assert sinh(x).as_real_imag(deep=False) == (sinh(x), 0) x = Symbol('x', real=True) assert sinh(I*x).is_finite is True assert sinh(x).is_real is True assert sinh(I).is_real is False p = Symbol('p', positive=True) assert sinh(p).is_zero is False assert sinh(0, evaluate=False).is_zero is True assert sinh(2*pi*I, evaluate=False).is_zero is True def test_sinh_series(): x = Symbol('x') assert sinh(x).series(x, 0, 10) == \ x + x**3/6 + x**5/120 + x**7/5040 + x**9/362880 + O(x**10) def test_sinh_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: sinh(x).fdiff(2)) def test_cosh(): x, y = symbols('x,y') k = Symbol('k', integer=True) assert cosh(nan) is nan assert cosh(zoo) is nan assert cosh(oo) is oo assert cosh(-oo) is oo assert cosh(0) == 1 assert unchanged(cosh, 1) assert cosh(-1) == cosh(1) assert unchanged(cosh, x) assert cosh(-x) == cosh(x) assert cosh(pi*I) == cos(pi) assert cosh(-pi*I) == cos(pi) assert unchanged(cosh, 2**1024 * E) assert cosh(-2**1024 * E) == cosh(2**1024 * E) assert cosh(pi*I/2) == 0 assert cosh(-pi*I/2) == 0 assert cosh((-3*10**73 + 1)*pi*I/2) == 0 assert cosh((7*10**103 + 1)*pi*I/2) == 0 assert cosh(pi*I) == -1 assert cosh(-pi*I) == -1 assert cosh(5*pi*I) == -1 assert cosh(8*pi*I) == 1 assert cosh(pi*I/3) == S.Half assert cosh(pi*I*Rational(-2, 3)) == Rational(-1, 2) assert cosh(pi*I/4) == S.Half*sqrt(2) assert cosh(-pi*I/4) == S.Half*sqrt(2) assert cosh(pi*I*Rational(11, 4)) == Rational(-1, 2)*sqrt(2) assert cosh(pi*I*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2) assert cosh(pi*I/6) == S.Half*sqrt(3) assert cosh(-pi*I/6) == S.Half*sqrt(3) assert cosh(pi*I*Rational(7, 6)) == Rational(-1, 2)*sqrt(3) assert cosh(pi*I*Rational(-5, 6)) == Rational(-1, 2)*sqrt(3) assert cosh(pi*I/105) == cos(pi/105) assert cosh(-pi*I/105) == cos(pi/105) assert unchanged(cosh, 2 + 3*I) assert cosh(x*I) == cos(x) assert cosh(k*pi*I) == cos(k*pi) assert cosh(17*k*pi*I) == cos(17*k*pi) assert unchanged(cosh, k*pi) assert cosh(x).as_real_imag(deep=False) == (cos(im(x))*cosh(re(x)), sin(im(x))*sinh(re(x))) x = Symbol('x', extended_real=True) assert cosh(x).as_real_imag(deep=False) == (cosh(x), 0) x = Symbol('x', real=True) assert cosh(I*x).is_finite is True assert cosh(I*x).is_real is True assert cosh(I*2 + 1).is_real is False assert cosh(5*I*S.Pi/2, evaluate=False).is_zero is True assert cosh(x).is_zero is False def test_cosh_series(): x = Symbol('x') assert cosh(x).series(x, 0, 10) == \ 1 + x**2/2 + x**4/24 + x**6/720 + x**8/40320 + O(x**10) def test_cosh_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: cosh(x).fdiff(2)) def test_tanh(): x, y = symbols('x,y') k = Symbol('k', integer=True) assert tanh(nan) is nan assert tanh(zoo) is nan assert tanh(oo) == 1 assert tanh(-oo) == -1 assert tanh(0) == 0 assert unchanged(tanh, 1) assert tanh(-1) == -tanh(1) assert unchanged(tanh, x) assert tanh(-x) == -tanh(x) assert unchanged(tanh, pi) assert tanh(-pi) == -tanh(pi) assert unchanged(tanh, 2**1024 * E) assert tanh(-2**1024 * E) == -tanh(2**1024 * E) assert tanh(pi*I) == 0 assert tanh(-pi*I) == 0 assert tanh(2*pi*I) == 0 assert tanh(-2*pi*I) == 0 assert tanh(-3*10**73*pi*I) == 0 assert tanh(7*10**103*pi*I) == 0 assert tanh(pi*I/2) is zoo assert tanh(-pi*I/2) is zoo assert tanh(pi*I*Rational(5, 2)) is zoo assert tanh(pi*I*Rational(7, 2)) is zoo assert tanh(pi*I/3) == sqrt(3)*I assert tanh(pi*I*Rational(-2, 3)) == sqrt(3)*I assert tanh(pi*I/4) == I assert tanh(-pi*I/4) == -I assert tanh(pi*I*Rational(17, 4)) == I assert tanh(pi*I*Rational(-3, 4)) == I assert tanh(pi*I/6) == I/sqrt(3) assert tanh(-pi*I/6) == -I/sqrt(3) assert tanh(pi*I*Rational(7, 6)) == I/sqrt(3) assert tanh(pi*I*Rational(-5, 6)) == I/sqrt(3) assert tanh(pi*I/105) == tan(pi/105)*I assert tanh(-pi*I/105) == -tan(pi/105)*I assert unchanged(tanh, 2 + 3*I) assert tanh(x*I) == tan(x)*I assert tanh(k*pi*I) == 0 assert tanh(17*k*pi*I) == 0 assert tanh(k*pi*I/2) == tan(k*pi/2)*I assert tanh(x).as_real_imag(deep=False) == (sinh(re(x))*cosh(re(x))/(cos(im(x))**2 + sinh(re(x))**2), sin(im(x))*cos(im(x))/(cos(im(x))**2 + sinh(re(x))**2)) x = Symbol('x', extended_real=True) assert tanh(x).as_real_imag(deep=False) == (tanh(x), 0) assert tanh(I*pi/3 + 1).is_real is False assert tanh(x).is_real is True assert tanh(I*pi*x/2).is_real is None def test_tanh_series(): x = Symbol('x') assert tanh(x).series(x, 0, 10) == \ x - x**3/3 + 2*x**5/15 - 17*x**7/315 + 62*x**9/2835 + O(x**10) def test_tanh_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: tanh(x).fdiff(2)) def test_coth(): x, y = symbols('x,y') k = Symbol('k', integer=True) assert coth(nan) is nan assert coth(zoo) is nan assert coth(oo) == 1 assert coth(-oo) == -1 assert coth(0) is zoo assert unchanged(coth, 1) assert coth(-1) == -coth(1) assert unchanged(coth, x) assert coth(-x) == -coth(x) assert coth(pi*I) == -I*cot(pi) assert coth(-pi*I) == cot(pi)*I assert unchanged(coth, 2**1024 * E) assert coth(-2**1024 * E) == -coth(2**1024 * E) assert coth(pi*I) == -I*cot(pi) assert coth(-pi*I) == I*cot(pi) assert coth(2*pi*I) == -I*cot(2*pi) assert coth(-2*pi*I) == I*cot(2*pi) assert coth(-3*10**73*pi*I) == I*cot(3*10**73*pi) assert coth(7*10**103*pi*I) == -I*cot(7*10**103*pi) assert coth(pi*I/2) == 0 assert coth(-pi*I/2) == 0 assert coth(pi*I*Rational(5, 2)) == 0 assert coth(pi*I*Rational(7, 2)) == 0 assert coth(pi*I/3) == -I/sqrt(3) assert coth(pi*I*Rational(-2, 3)) == -I/sqrt(3) assert coth(pi*I/4) == -I assert coth(-pi*I/4) == I assert coth(pi*I*Rational(17, 4)) == -I assert coth(pi*I*Rational(-3, 4)) == -I assert coth(pi*I/6) == -sqrt(3)*I assert coth(-pi*I/6) == sqrt(3)*I assert coth(pi*I*Rational(7, 6)) == -sqrt(3)*I assert coth(pi*I*Rational(-5, 6)) == -sqrt(3)*I assert coth(pi*I/105) == -cot(pi/105)*I assert coth(-pi*I/105) == cot(pi/105)*I assert unchanged(coth, 2 + 3*I) assert coth(x*I) == -cot(x)*I assert coth(k*pi*I) == -cot(k*pi)*I assert coth(17*k*pi*I) == -cot(17*k*pi)*I assert coth(k*pi*I) == -cot(k*pi)*I assert coth(log(tan(2))) == coth(log(-tan(2))) assert coth(1 + I*pi/2) == tanh(1) assert coth(x).as_real_imag(deep=False) == (sinh(re(x))*cosh(re(x))/(sin(im(x))**2 + sinh(re(x))**2), -sin(im(x))*cos(im(x))/(sin(im(x))**2 + sinh(re(x))**2)) x = Symbol('x', extended_real=True) assert coth(x).as_real_imag(deep=False) == (coth(x), 0) assert expand_trig(coth(2*x)) == (coth(x)**2 + 1)/(2*coth(x)) assert expand_trig(coth(3*x)) == (coth(x)**3 + 3*coth(x))/(1 + 3*coth(x)**2) assert expand_trig(coth(x + y)) == (1 + coth(x)*coth(y))/(coth(x) + coth(y)) def test_coth_series(): x = Symbol('x') assert coth(x).series(x, 0, 8) == \ 1/x + x/3 - x**3/45 + 2*x**5/945 - x**7/4725 + O(x**8) def test_coth_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: coth(x).fdiff(2)) def test_csch(): x, y = symbols('x,y') k = Symbol('k', integer=True) n = Symbol('n', positive=True) assert csch(nan) is nan assert csch(zoo) is nan assert csch(oo) == 0 assert csch(-oo) == 0 assert csch(0) is zoo assert csch(-1) == -csch(1) assert csch(-x) == -csch(x) assert csch(-pi) == -csch(pi) assert csch(-2**1024 * E) == -csch(2**1024 * E) assert csch(pi*I) is zoo assert csch(-pi*I) is zoo assert csch(2*pi*I) is zoo assert csch(-2*pi*I) is zoo assert csch(-3*10**73*pi*I) is zoo assert csch(7*10**103*pi*I) is zoo assert csch(pi*I/2) == -I assert csch(-pi*I/2) == I assert csch(pi*I*Rational(5, 2)) == -I assert csch(pi*I*Rational(7, 2)) == I assert csch(pi*I/3) == -2/sqrt(3)*I assert csch(pi*I*Rational(-2, 3)) == 2/sqrt(3)*I assert csch(pi*I/4) == -sqrt(2)*I assert csch(-pi*I/4) == sqrt(2)*I assert csch(pi*I*Rational(7, 4)) == sqrt(2)*I assert csch(pi*I*Rational(-3, 4)) == sqrt(2)*I assert csch(pi*I/6) == -2*I assert csch(-pi*I/6) == 2*I assert csch(pi*I*Rational(7, 6)) == 2*I assert csch(pi*I*Rational(-7, 6)) == -2*I assert csch(pi*I*Rational(-5, 6)) == 2*I assert csch(pi*I/105) == -1/sin(pi/105)*I assert csch(-pi*I/105) == 1/sin(pi/105)*I assert csch(x*I) == -1/sin(x)*I assert csch(k*pi*I) is zoo assert csch(17*k*pi*I) is zoo assert csch(k*pi*I/2) == -1/sin(k*pi/2)*I assert csch(n).is_real is True assert expand_trig(csch(x + y)) == 1/(sinh(x)*cosh(y) + cosh(x)*sinh(y)) def test_csch_series(): x = Symbol('x') assert csch(x).series(x, 0, 10) == \ 1/ x - x/6 + 7*x**3/360 - 31*x**5/15120 + 127*x**7/604800 \ - 73*x**9/3421440 + O(x**10) def test_csch_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: csch(x).fdiff(2)) def test_sech(): x, y = symbols('x, y') k = Symbol('k', integer=True) n = Symbol('n', positive=True) assert sech(nan) is nan assert sech(zoo) is nan assert sech(oo) == 0 assert sech(-oo) == 0 assert sech(0) == 1 assert sech(-1) == sech(1) assert sech(-x) == sech(x) assert sech(pi*I) == sec(pi) assert sech(-pi*I) == sec(pi) assert sech(-2**1024 * E) == sech(2**1024 * E) assert sech(pi*I/2) is zoo assert sech(-pi*I/2) is zoo assert sech((-3*10**73 + 1)*pi*I/2) is zoo assert sech((7*10**103 + 1)*pi*I/2) is zoo assert sech(pi*I) == -1 assert sech(-pi*I) == -1 assert sech(5*pi*I) == -1 assert sech(8*pi*I) == 1 assert sech(pi*I/3) == 2 assert sech(pi*I*Rational(-2, 3)) == -2 assert sech(pi*I/4) == sqrt(2) assert sech(-pi*I/4) == sqrt(2) assert sech(pi*I*Rational(5, 4)) == -sqrt(2) assert sech(pi*I*Rational(-5, 4)) == -sqrt(2) assert sech(pi*I/6) == 2/sqrt(3) assert sech(-pi*I/6) == 2/sqrt(3) assert sech(pi*I*Rational(7, 6)) == -2/sqrt(3) assert sech(pi*I*Rational(-5, 6)) == -2/sqrt(3) assert sech(pi*I/105) == 1/cos(pi/105) assert sech(-pi*I/105) == 1/cos(pi/105) assert sech(x*I) == 1/cos(x) assert sech(k*pi*I) == 1/cos(k*pi) assert sech(17*k*pi*I) == 1/cos(17*k*pi) assert sech(n).is_real is True assert expand_trig(sech(x + y)) == 1/(cosh(x)*cosh(y) + sinh(x)*sinh(y)) def test_sech_series(): x = Symbol('x') assert sech(x).series(x, 0, 10) == \ 1 - x**2/2 + 5*x**4/24 - 61*x**6/720 + 277*x**8/8064 + O(x**10) def test_sech_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: sech(x).fdiff(2)) def test_asinh(): x, y = symbols('x,y') assert unchanged(asinh, x) assert asinh(-x) == -asinh(x) #at specific points assert asinh(nan) is nan assert asinh( 0) == 0 assert asinh(+1) == log(sqrt(2) + 1) assert asinh(-1) == log(sqrt(2) - 1) assert asinh(I) == pi*I/2 assert asinh(-I) == -pi*I/2 assert asinh(I/2) == pi*I/6 assert asinh(-I/2) == -pi*I/6 # at infinites assert asinh(oo) is oo assert asinh(-oo) is -oo assert asinh(I*oo) is oo assert asinh(-I *oo) is -oo assert asinh(zoo) is zoo #properties assert asinh(I *(sqrt(3) - 1)/(2**Rational(3, 2))) == pi*I/12 assert asinh(-I *(sqrt(3) - 1)/(2**Rational(3, 2))) == -pi*I/12 assert asinh(I*(sqrt(5) - 1)/4) == pi*I/10 assert asinh(-I*(sqrt(5) - 1)/4) == -pi*I/10 assert asinh(I*(sqrt(5) + 1)/4) == pi*I*Rational(3, 10) assert asinh(-I*(sqrt(5) + 1)/4) == pi*I*Rational(-3, 10) # Symmetry assert asinh(Rational(-1, 2)) == -asinh(S.Half) # inverse composition assert unchanged(asinh, sinh(Symbol('v1'))) assert asinh(sinh(0, evaluate=False)) == 0 assert asinh(sinh(-3, evaluate=False)) == -3 assert asinh(sinh(2, evaluate=False)) == 2 assert asinh(sinh(I, evaluate=False)) == I assert asinh(sinh(-I, evaluate=False)) == -I assert asinh(sinh(5*I, evaluate=False)) == -2*I*pi + 5*I assert asinh(sinh(15 + 11*I)) == 15 - 4*I*pi + 11*I assert asinh(sinh(-73 + 97*I)) == 73 - 97*I + 31*I*pi assert asinh(sinh(-7 - 23*I)) == 7 - 7*I*pi + 23*I assert asinh(sinh(13 - 3*I)) == -13 - I*pi + 3*I p = Symbol('p', positive=True) assert asinh(p).is_zero is False assert asinh(sinh(0, evaluate=False), evaluate=False).is_zero is True def test_asinh_rewrite(): x = Symbol('x') assert asinh(x).rewrite(log) == log(x + sqrt(x**2 + 1)) def test_asinh_series(): x = Symbol('x') assert asinh(x).series(x, 0, 8) == \ x - x**3/6 + 3*x**5/40 - 5*x**7/112 + O(x**8) t5 = asinh(x).taylor_term(5, x) assert t5 == 3*x**5/40 assert asinh(x).taylor_term(7, x, t5, 0) == -5*x**7/112 def test_asinh_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: asinh(x).fdiff(2)) def test_acosh(): x = Symbol('x') assert unchanged(acosh, -x) #at specific points assert acosh(1) == 0 assert acosh(-1) == pi*I assert acosh(0) == I*pi/2 assert acosh(S.Half) == I*pi/3 assert acosh(Rational(-1, 2)) == pi*I*Rational(2, 3) assert acosh(nan) is nan # at infinites assert acosh(oo) is oo assert acosh(-oo) is oo assert acosh(I*oo) == oo + I*pi/2 assert acosh(-I*oo) == oo - I*pi/2 assert acosh(zoo) is zoo assert acosh(I) == log(I*(1 + sqrt(2))) assert acosh(-I) == log(-I*(1 + sqrt(2))) assert acosh((sqrt(3) - 1)/(2*sqrt(2))) == pi*I*Rational(5, 12) assert acosh(-(sqrt(3) - 1)/(2*sqrt(2))) == pi*I*Rational(7, 12) assert acosh(sqrt(2)/2) == I*pi/4 assert acosh(-sqrt(2)/2) == I*pi*Rational(3, 4) assert acosh(sqrt(3)/2) == I*pi/6 assert acosh(-sqrt(3)/2) == I*pi*Rational(5, 6) assert acosh(sqrt(2 + sqrt(2))/2) == I*pi/8 assert acosh(-sqrt(2 + sqrt(2))/2) == I*pi*Rational(7, 8) assert acosh(sqrt(2 - sqrt(2))/2) == I*pi*Rational(3, 8) assert acosh(-sqrt(2 - sqrt(2))/2) == I*pi*Rational(5, 8) assert acosh((1 + sqrt(3))/(2*sqrt(2))) == I*pi/12 assert acosh(-(1 + sqrt(3))/(2*sqrt(2))) == I*pi*Rational(11, 12) assert acosh((sqrt(5) + 1)/4) == I*pi/5 assert acosh(-(sqrt(5) + 1)/4) == I*pi*Rational(4, 5) assert str(acosh(5*I).n(6)) == '2.31244 + 1.5708*I' assert str(acosh(-5*I).n(6)) == '2.31244 - 1.5708*I' # inverse composition assert unchanged(acosh, Symbol('v1')) assert acosh(cosh(-3, evaluate=False)) == 3 assert acosh(cosh(3, evaluate=False)) == 3 assert acosh(cosh(0, evaluate=False)) == 0 assert acosh(cosh(I, evaluate=False)) == I assert acosh(cosh(-I, evaluate=False)) == I assert acosh(cosh(7*I, evaluate=False)) == -2*I*pi + 7*I assert acosh(cosh(1 + I)) == 1 + I assert acosh(cosh(3 - 3*I)) == 3 - 3*I assert acosh(cosh(-3 + 2*I)) == 3 - 2*I assert acosh(cosh(-5 - 17*I)) == 5 - 6*I*pi + 17*I assert acosh(cosh(-21 + 11*I)) == 21 - 11*I + 4*I*pi assert acosh(cosh(cosh(1) + I)) == cosh(1) + I assert acosh(1, evaluate=False).is_zero is True def test_acosh_rewrite(): x = Symbol('x') assert acosh(x).rewrite(log) == log(x + sqrt(x - 1)*sqrt(x + 1)) def test_acosh_series(): x = Symbol('x') assert acosh(x).series(x, 0, 8) == \ -I*x + pi*I/2 - I*x**3/6 - 3*I*x**5/40 - 5*I*x**7/112 + O(x**8) t5 = acosh(x).taylor_term(5, x) assert t5 == - 3*I*x**5/40 assert acosh(x).taylor_term(7, x, t5, 0) == - 5*I*x**7/112 def test_acosh_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: acosh(x).fdiff(2)) def test_asech(): x = Symbol('x') assert unchanged(asech, -x) # values at fixed points assert asech(1) == 0 assert asech(-1) == pi*I assert asech(0) is oo assert asech(2) == I*pi/3 assert asech(-2) == 2*I*pi / 3 assert asech(nan) is nan # at infinites assert asech(oo) == I*pi/2 assert asech(-oo) == I*pi/2 assert asech(zoo) == I*AccumBounds(-pi/2, pi/2) assert asech(I) == log(1 + sqrt(2)) - I*pi/2 assert asech(-I) == log(1 + sqrt(2)) + I*pi/2 assert asech(sqrt(2) - sqrt(6)) == 11*I*pi / 12 assert asech(sqrt(2 - 2/sqrt(5))) == I*pi / 10 assert asech(-sqrt(2 - 2/sqrt(5))) == 9*I*pi / 10 assert asech(2 / sqrt(2 + sqrt(2))) == I*pi / 8 assert asech(-2 / sqrt(2 + sqrt(2))) == 7*I*pi / 8 assert asech(sqrt(5) - 1) == I*pi / 5 assert asech(1 - sqrt(5)) == 4*I*pi / 5 assert asech(-sqrt(2*(2 + sqrt(2)))) == 5*I*pi / 8 # properties # asech(x) == acosh(1/x) assert asech(sqrt(2)) == acosh(1/sqrt(2)) assert asech(2/sqrt(3)) == acosh(sqrt(3)/2) assert asech(2/sqrt(2 + sqrt(2))) == acosh(sqrt(2 + sqrt(2))/2) assert asech(2) == acosh(S.Half) # asech(x) == I*acos(1/x) # (Note: the exact formula is asech(x) == +/- I*acos(1/x)) assert asech(-sqrt(2)) == I*acos(-1/sqrt(2)) assert asech(-2/sqrt(3)) == I*acos(-sqrt(3)/2) assert asech(-S(2)) == I*acos(Rational(-1, 2)) assert asech(-2/sqrt(2)) == I*acos(-sqrt(2)/2) # sech(asech(x)) / x == 1 assert expand_mul(sech(asech(sqrt(6) - sqrt(2))) / (sqrt(6) - sqrt(2))) == 1 assert expand_mul(sech(asech(sqrt(6) + sqrt(2))) / (sqrt(6) + sqrt(2))) == 1 assert (sech(asech(sqrt(2 + 2/sqrt(5)))) / (sqrt(2 + 2/sqrt(5)))).simplify() == 1 assert (sech(asech(-sqrt(2 + 2/sqrt(5)))) / (-sqrt(2 + 2/sqrt(5)))).simplify() == 1 assert (sech(asech(sqrt(2*(2 + sqrt(2))))) / (sqrt(2*(2 + sqrt(2))))).simplify() == 1 assert expand_mul(sech(asech(1 + sqrt(5))) / (1 + sqrt(5))) == 1 assert expand_mul(sech(asech(-1 - sqrt(5))) / (-1 - sqrt(5))) == 1 assert expand_mul(sech(asech(-sqrt(6) - sqrt(2))) / (-sqrt(6) - sqrt(2))) == 1 # numerical evaluation assert str(asech(5*I).n(6)) == '0.19869 - 1.5708*I' assert str(asech(-5*I).n(6)) == '0.19869 + 1.5708*I' def test_asech_series(): x = Symbol('x') t6 = asech(x).expansion_term(6, x) assert t6 == -5*x**6/96 assert asech(x).expansion_term(8, x, t6, 0) == -35*x**8/1024 def test_asech_rewrite(): x = Symbol('x') assert asech(x).rewrite(log) == log(1/x + sqrt(1/x - 1) * sqrt(1/x + 1)) def test_asech_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: asech(x).fdiff(2)) def test_acsch(): x = Symbol('x') assert unchanged(acsch, x) assert acsch(-x) == -acsch(x) # values at fixed points assert acsch(1) == log(1 + sqrt(2)) assert acsch(-1) == - log(1 + sqrt(2)) assert acsch(0) is zoo assert acsch(2) == log((1+sqrt(5))/2) assert acsch(-2) == - log((1+sqrt(5))/2) assert acsch(I) == - I*pi/2 assert acsch(-I) == I*pi/2 assert acsch(-I*(sqrt(6) + sqrt(2))) == I*pi / 12 assert acsch(I*(sqrt(2) + sqrt(6))) == -I*pi / 12 assert acsch(-I*(1 + sqrt(5))) == I*pi / 10 assert acsch(I*(1 + sqrt(5))) == -I*pi / 10 assert acsch(-I*2 / sqrt(2 - sqrt(2))) == I*pi / 8 assert acsch(I*2 / sqrt(2 - sqrt(2))) == -I*pi / 8 assert acsch(-I*2) == I*pi / 6 assert acsch(I*2) == -I*pi / 6 assert acsch(-I*sqrt(2 + 2/sqrt(5))) == I*pi / 5 assert acsch(I*sqrt(2 + 2/sqrt(5))) == -I*pi / 5 assert acsch(-I*sqrt(2)) == I*pi / 4 assert acsch(I*sqrt(2)) == -I*pi / 4 assert acsch(-I*(sqrt(5)-1)) == 3*I*pi / 10 assert acsch(I*(sqrt(5)-1)) == -3*I*pi / 10 assert acsch(-I*2 / sqrt(3)) == I*pi / 3 assert acsch(I*2 / sqrt(3)) == -I*pi / 3 assert acsch(-I*2 / sqrt(2 + sqrt(2))) == 3*I*pi / 8 assert acsch(I*2 / sqrt(2 + sqrt(2))) == -3*I*pi / 8 assert acsch(-I*sqrt(2 - 2/sqrt(5))) == 2*I*pi / 5 assert acsch(I*sqrt(2 - 2/sqrt(5))) == -2*I*pi / 5 assert acsch(-I*(sqrt(6) - sqrt(2))) == 5*I*pi / 12 assert acsch(I*(sqrt(6) - sqrt(2))) == -5*I*pi / 12 assert acsch(nan) is nan # properties # acsch(x) == asinh(1/x) assert acsch(-I*sqrt(2)) == asinh(I/sqrt(2)) assert acsch(-I*2 / sqrt(3)) == asinh(I*sqrt(3) / 2) # acsch(x) == -I*asin(I/x) assert acsch(-I*sqrt(2)) == -I*asin(-1/sqrt(2)) assert acsch(-I*2 / sqrt(3)) == -I*asin(-sqrt(3)/2) # csch(acsch(x)) / x == 1 assert expand_mul(csch(acsch(-I*(sqrt(6) + sqrt(2)))) / (-I*(sqrt(6) + sqrt(2)))) == 1 assert expand_mul(csch(acsch(I*(1 + sqrt(5)))) / (I*(1 + sqrt(5)))) == 1 assert (csch(acsch(I*sqrt(2 - 2/sqrt(5)))) / (I*sqrt(2 - 2/sqrt(5)))).simplify() == 1 assert (csch(acsch(-I*sqrt(2 - 2/sqrt(5)))) / (-I*sqrt(2 - 2/sqrt(5)))).simplify() == 1 # numerical evaluation assert str(acsch(5*I+1).n(6)) == '0.0391819 - 0.193363*I' assert str(acsch(-5*I+1).n(6)) == '0.0391819 + 0.193363*I' def test_acsch_infinities(): assert acsch(oo) == 0 assert acsch(-oo) == 0 assert acsch(zoo) == 0 def test_acsch_rewrite(): x = Symbol('x') assert acsch(x).rewrite(log) == log(1/x + sqrt(1/x**2 + 1)) def test_acsch_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: acsch(x).fdiff(2)) def test_atanh(): x = Symbol('x') #at specific points assert atanh(0) == 0 assert atanh(I) == I*pi/4 assert atanh(-I) == -I*pi/4 assert atanh(1) is oo assert atanh(-1) is -oo assert atanh(nan) is nan # at infinites assert atanh(oo) == -I*pi/2 assert atanh(-oo) == I*pi/2 assert atanh(I*oo) == I*pi/2 assert atanh(-I*oo) == -I*pi/2 assert atanh(zoo) == I*AccumBounds(-pi/2, pi/2) #properties assert atanh(-x) == -atanh(x) assert atanh(I/sqrt(3)) == I*pi/6 assert atanh(-I/sqrt(3)) == -I*pi/6 assert atanh(I*sqrt(3)) == I*pi/3 assert atanh(-I*sqrt(3)) == -I*pi/3 assert atanh(I*(1 + sqrt(2))) == pi*I*Rational(3, 8) assert atanh(I*(sqrt(2) - 1)) == pi*I/8 assert atanh(I*(1 - sqrt(2))) == -pi*I/8 assert atanh(-I*(1 + sqrt(2))) == pi*I*Rational(-3, 8) assert atanh(I*sqrt(5 + 2*sqrt(5))) == I*pi*Rational(2, 5) assert atanh(-I*sqrt(5 + 2*sqrt(5))) == I*pi*Rational(-2, 5) assert atanh(I*(2 - sqrt(3))) == pi*I/12 assert atanh(I*(sqrt(3) - 2)) == -pi*I/12 assert atanh(oo) == -I*pi/2 # Symmetry assert atanh(Rational(-1, 2)) == -atanh(S.Half) # inverse composition assert unchanged(atanh, tanh(Symbol('v1'))) assert atanh(tanh(-5, evaluate=False)) == -5 assert atanh(tanh(0, evaluate=False)) == 0 assert atanh(tanh(7, evaluate=False)) == 7 assert atanh(tanh(I, evaluate=False)) == I assert atanh(tanh(-I, evaluate=False)) == -I assert atanh(tanh(-11*I, evaluate=False)) == -11*I + 4*I*pi assert atanh(tanh(3 + I)) == 3 + I assert atanh(tanh(4 + 5*I)) == 4 - 2*I*pi + 5*I assert atanh(tanh(pi/2)) == pi/2 assert atanh(tanh(pi)) == pi assert atanh(tanh(-3 + 7*I)) == -3 - 2*I*pi + 7*I assert atanh(tanh(9 - I*2/3)) == 9 - I*2/3 assert atanh(tanh(-32 - 123*I)) == -32 - 123*I + 39*I*pi def test_atanh_rewrite(): x = Symbol('x') assert atanh(x).rewrite(log) == (log(1 + x) - log(1 - x)) / 2 def test_atanh_series(): x = Symbol('x') assert atanh(x).series(x, 0, 10) == \ x + x**3/3 + x**5/5 + x**7/7 + x**9/9 + O(x**10) def test_atanh_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: atanh(x).fdiff(2)) def test_acoth(): x = Symbol('x') #at specific points assert acoth(0) == I*pi/2 assert acoth(I) == -I*pi/4 assert acoth(-I) == I*pi/4 assert acoth(1) is oo assert acoth(-1) is -oo assert acoth(nan) is nan # at infinites assert acoth(oo) == 0 assert acoth(-oo) == 0 assert acoth(I*oo) == 0 assert acoth(-I*oo) == 0 assert acoth(zoo) == 0 #properties assert acoth(-x) == -acoth(x) assert acoth(I/sqrt(3)) == -I*pi/3 assert acoth(-I/sqrt(3)) == I*pi/3 assert acoth(I*sqrt(3)) == -I*pi/6 assert acoth(-I*sqrt(3)) == I*pi/6 assert acoth(I*(1 + sqrt(2))) == -pi*I/8 assert acoth(-I*(sqrt(2) + 1)) == pi*I/8 assert acoth(I*(1 - sqrt(2))) == pi*I*Rational(3, 8) assert acoth(I*(sqrt(2) - 1)) == pi*I*Rational(-3, 8) assert acoth(I*sqrt(5 + 2*sqrt(5))) == -I*pi/10 assert acoth(-I*sqrt(5 + 2*sqrt(5))) == I*pi/10 assert acoth(I*(2 + sqrt(3))) == -pi*I/12 assert acoth(-I*(2 + sqrt(3))) == pi*I/12 assert acoth(I*(2 - sqrt(3))) == pi*I*Rational(-5, 12) assert acoth(I*(sqrt(3) - 2)) == pi*I*Rational(5, 12) # Symmetry assert acoth(Rational(-1, 2)) == -acoth(S.Half) def test_acoth_rewrite(): x = Symbol('x') assert acoth(x).rewrite(log) == (log(1 + 1/x) - log(1 - 1/x)) / 2 def test_acoth_series(): x = Symbol('x') assert acoth(x).series(x, 0, 10) == \ I*pi/2 + x + x**3/3 + x**5/5 + x**7/7 + x**9/9 + O(x**10) def test_acoth_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: acoth(x).fdiff(2)) def test_inverses(): x = Symbol('x') assert sinh(x).inverse() == asinh raises(AttributeError, lambda: cosh(x).inverse()) assert tanh(x).inverse() == atanh assert coth(x).inverse() == acoth assert asinh(x).inverse() == sinh assert acosh(x).inverse() == cosh assert atanh(x).inverse() == tanh assert acoth(x).inverse() == coth assert asech(x).inverse() == sech assert acsch(x).inverse() == csch def test_leading_term(): x = Symbol('x') assert cosh(x).as_leading_term(x) == 1 assert coth(x).as_leading_term(x) == 1/x assert acosh(x).as_leading_term(x) == I*pi/2 assert acoth(x).as_leading_term(x) == I*pi/2 for func in [sinh, tanh, asinh, atanh]: assert func(x).as_leading_term(x) == x for func in [sinh, cosh, tanh, coth, asinh, acosh, atanh, acoth]: for arg in (1/x, S.Half): eq = func(arg) assert eq.as_leading_term(x) == eq for func in [csch, sech]: eq = func(S.Half) assert eq.as_leading_term(x) == eq def test_complex(): a, b = symbols('a,b', real=True) z = a + b*I for func in [sinh, cosh, tanh, coth, sech, csch]: assert func(z).conjugate() == func(a - b*I) for deep in [True, False]: assert sinh(z).expand( complex=True, deep=deep) == sinh(a)*cos(b) + I*cosh(a)*sin(b) assert cosh(z).expand( complex=True, deep=deep) == cosh(a)*cos(b) + I*sinh(a)*sin(b) assert tanh(z).expand(complex=True, deep=deep) == sinh(a)*cosh( a)/(cos(b)**2 + sinh(a)**2) + I*sin(b)*cos(b)/(cos(b)**2 + sinh(a)**2) assert coth(z).expand(complex=True, deep=deep) == sinh(a)*cosh( a)/(sin(b)**2 + sinh(a)**2) - I*sin(b)*cos(b)/(sin(b)**2 + sinh(a)**2) assert csch(z).expand(complex=True, deep=deep) == cos(b) * sinh(a) / (sin(b)**2\ *cosh(a)**2 + cos(b)**2 * sinh(a)**2) - I*sin(b) * cosh(a) / (sin(b)**2\ *cosh(a)**2 + cos(b)**2 * sinh(a)**2) assert sech(z).expand(complex=True, deep=deep) == cos(b) * cosh(a) / (sin(b)**2\ *sinh(a)**2 + cos(b)**2 * cosh(a)**2) - I*sin(b) * sinh(a) / (sin(b)**2\ *sinh(a)**2 + cos(b)**2 * cosh(a)**2) def test_complex_2899(): a, b = symbols('a,b', real=True) for deep in [True, False]: for func in [sinh, cosh, tanh, coth]: assert func(a).expand(complex=True, deep=deep) == func(a) def test_simplifications(): x = Symbol('x') assert sinh(asinh(x)) == x assert sinh(acosh(x)) == sqrt(x - 1) * sqrt(x + 1) assert sinh(atanh(x)) == x/sqrt(1 - x**2) assert sinh(acoth(x)) == 1/(sqrt(x - 1) * sqrt(x + 1)) assert cosh(asinh(x)) == sqrt(1 + x**2) assert cosh(acosh(x)) == x assert cosh(atanh(x)) == 1/sqrt(1 - x**2) assert cosh(acoth(x)) == x/(sqrt(x - 1) * sqrt(x + 1)) assert tanh(asinh(x)) == x/sqrt(1 + x**2) assert tanh(acosh(x)) == sqrt(x - 1) * sqrt(x + 1) / x assert tanh(atanh(x)) == x assert tanh(acoth(x)) == 1/x assert coth(asinh(x)) == sqrt(1 + x**2)/x assert coth(acosh(x)) == x/(sqrt(x - 1) * sqrt(x + 1)) assert coth(atanh(x)) == 1/x assert coth(acoth(x)) == x assert csch(asinh(x)) == 1/x assert csch(acosh(x)) == 1/(sqrt(x - 1) * sqrt(x + 1)) assert csch(atanh(x)) == sqrt(1 - x**2)/x assert csch(acoth(x)) == sqrt(x - 1) * sqrt(x + 1) assert sech(asinh(x)) == 1/sqrt(1 + x**2) assert sech(acosh(x)) == 1/x assert sech(atanh(x)) == sqrt(1 - x**2) assert sech(acoth(x)) == sqrt(x - 1) * sqrt(x + 1)/x def test_issue_4136(): assert cosh(asinh(Integer(3)/2)) == sqrt(Integer(13)/4) def test_sinh_rewrite(): x = Symbol('x') assert sinh(x).rewrite(exp) == (exp(x) - exp(-x))/2 \ == sinh(x).rewrite('tractable') assert sinh(x).rewrite(cosh) == -I*cosh(x + I*pi/2) tanh_half = tanh(S.Half*x) assert sinh(x).rewrite(tanh) == 2*tanh_half/(1 - tanh_half**2) coth_half = coth(S.Half*x) assert sinh(x).rewrite(coth) == 2*coth_half/(coth_half**2 - 1) def test_cosh_rewrite(): x = Symbol('x') assert cosh(x).rewrite(exp) == (exp(x) + exp(-x))/2 \ == cosh(x).rewrite('tractable') assert cosh(x).rewrite(sinh) == -I*sinh(x + I*pi/2) tanh_half = tanh(S.Half*x)**2 assert cosh(x).rewrite(tanh) == (1 + tanh_half)/(1 - tanh_half) coth_half = coth(S.Half*x)**2 assert cosh(x).rewrite(coth) == (coth_half + 1)/(coth_half - 1) def test_tanh_rewrite(): x = Symbol('x') assert tanh(x).rewrite(exp) == (exp(x) - exp(-x))/(exp(x) + exp(-x)) \ == tanh(x).rewrite('tractable') assert tanh(x).rewrite(sinh) == I*sinh(x)/sinh(I*pi/2 - x) assert tanh(x).rewrite(cosh) == I*cosh(I*pi/2 - x)/cosh(x) assert tanh(x).rewrite(coth) == 1/coth(x) def test_coth_rewrite(): x = Symbol('x') assert coth(x).rewrite(exp) == (exp(x) + exp(-x))/(exp(x) - exp(-x)) \ == coth(x).rewrite('tractable') assert coth(x).rewrite(sinh) == -I*sinh(I*pi/2 - x)/sinh(x) assert coth(x).rewrite(cosh) == -I*cosh(x)/cosh(I*pi/2 - x) assert coth(x).rewrite(tanh) == 1/tanh(x) def test_csch_rewrite(): x = Symbol('x') assert csch(x).rewrite(exp) == 1 / (exp(x)/2 - exp(-x)/2) \ == csch(x).rewrite('tractable') assert csch(x).rewrite(cosh) == I/cosh(x + I*pi/2) tanh_half = tanh(S.Half*x) assert csch(x).rewrite(tanh) == (1 - tanh_half**2)/(2*tanh_half) coth_half = coth(S.Half*x) assert csch(x).rewrite(coth) == (coth_half**2 - 1)/(2*coth_half) def test_sech_rewrite(): x = Symbol('x') assert sech(x).rewrite(exp) == 1 / (exp(x)/2 + exp(-x)/2) \ == sech(x).rewrite('tractable') assert sech(x).rewrite(sinh) == I/sinh(x + I*pi/2) tanh_half = tanh(S.Half*x)**2 assert sech(x).rewrite(tanh) == (1 - tanh_half)/(1 + tanh_half) coth_half = coth(S.Half*x)**2 assert sech(x).rewrite(coth) == (coth_half - 1)/(coth_half + 1) def test_derivs(): x = Symbol('x') assert coth(x).diff(x) == -sinh(x)**(-2) assert sinh(x).diff(x) == cosh(x) assert cosh(x).diff(x) == sinh(x) assert tanh(x).diff(x) == -tanh(x)**2 + 1 assert csch(x).diff(x) == -coth(x)*csch(x) assert sech(x).diff(x) == -tanh(x)*sech(x) assert acoth(x).diff(x) == 1/(-x**2 + 1) assert asinh(x).diff(x) == 1/sqrt(x**2 + 1) assert acosh(x).diff(x) == 1/sqrt(x**2 - 1) assert atanh(x).diff(x) == 1/(-x**2 + 1) assert asech(x).diff(x) == -1/(x*sqrt(1 - x**2)) assert acsch(x).diff(x) == -1/(x**2*sqrt(1 + x**(-2))) def test_sinh_expansion(): x, y = symbols('x,y') assert sinh(x+y).expand(trig=True) == sinh(x)*cosh(y) + cosh(x)*sinh(y) assert sinh(2*x).expand(trig=True) == 2*sinh(x)*cosh(x) assert sinh(3*x).expand(trig=True).expand() == \ sinh(x)**3 + 3*sinh(x)*cosh(x)**2 def test_cosh_expansion(): x, y = symbols('x,y') assert cosh(x+y).expand(trig=True) == cosh(x)*cosh(y) + sinh(x)*sinh(y) assert cosh(2*x).expand(trig=True) == cosh(x)**2 + sinh(x)**2 assert cosh(3*x).expand(trig=True).expand() == \ 3*sinh(x)**2*cosh(x) + cosh(x)**3 def test_cosh_positive(): # See issue 11721 # cosh(x) is positive for real values of x k = symbols('k', real=True) n = symbols('n', integer=True) assert cosh(k, evaluate=False).is_positive is True assert cosh(k + 2*n*pi*I, evaluate=False).is_positive is True assert cosh(I*pi/4, evaluate=False).is_positive is True assert cosh(3*I*pi/4, evaluate=False).is_positive is False def test_cosh_nonnegative(): k = symbols('k', real=True) n = symbols('n', integer=True) assert cosh(k, evaluate=False).is_nonnegative is True assert cosh(k + 2*n*pi*I, evaluate=False).is_nonnegative is True assert cosh(I*pi/4, evaluate=False).is_nonnegative is True assert cosh(3*I*pi/4, evaluate=False).is_nonnegative is False assert cosh(S.Zero, evaluate=False).is_nonnegative is True def test_real_assumptions(): z = Symbol('z', real=False) assert sinh(z).is_real is None assert cosh(z).is_real is None assert tanh(z).is_real is None assert sech(z).is_real is None assert csch(z).is_real is None assert coth(z).is_real is None def test_sign_assumptions(): p = Symbol('p', positive=True) n = Symbol('n', negative=True) assert sinh(n).is_negative is True assert sinh(p).is_positive is True assert cosh(n).is_positive is True assert cosh(p).is_positive is True assert tanh(n).is_negative is True assert tanh(p).is_positive is True assert csch(n).is_negative is True assert csch(p).is_positive is True assert sech(n).is_positive is True assert sech(p).is_positive is True assert coth(n).is_negative is True assert coth(p).is_positive is True
1d12bdfd11c54f4cd0899507ba238fdb5d02c32c72f6746e1552e518384a97d1
from sympy.core.containers import Tuple from sympy.core.function import Derivative from sympy.core.numbers import (I, Rational, oo, pi) from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import cos from sympy.functions.special.gamma_functions import gamma from sympy.functions.special.hyper import (appellf1, hyper, meijerg) from sympy.series.order import O from sympy.abc import x, z, k from sympy.series.limits import limit from sympy.testing.pytest import raises, slow from sympy.core.random import ( random_complex_number as randcplx, verify_numerically as tn, test_derivative_numerically as td) def test_TupleParametersBase(): # test that our implementation of the chain rule works p = hyper((), (), z**2) assert p.diff(z) == p*2*z def test_hyper(): raises(TypeError, lambda: hyper(1, 2, z)) assert hyper((1, 2), (1,), z) == hyper(Tuple(1, 2), Tuple(1), z) h = hyper((1, 2), (3, 4, 5), z) assert h.ap == Tuple(1, 2) assert h.bq == Tuple(3, 4, 5) assert h.argument == z assert h.is_commutative is True # just a few checks to make sure that all arguments go where they should assert tn(hyper(Tuple(), Tuple(), z), exp(z), z) assert tn(z*hyper((1, 1), Tuple(2), -z), log(1 + z), z) # differentiation h = hyper( (randcplx(), randcplx(), randcplx()), (randcplx(), randcplx()), z) assert td(h, z) a1, a2, b1, b2, b3 = symbols('a1:3, b1:4') assert hyper((a1, a2), (b1, b2, b3), z).diff(z) == \ a1*a2/(b1*b2*b3) * hyper((a1 + 1, a2 + 1), (b1 + 1, b2 + 1, b3 + 1), z) # differentiation wrt parameters is not supported assert hyper([z], [], z).diff(z) == Derivative(hyper([z], [], z), z) # hyper is unbranched wrt parameters from sympy.functions.elementary.complexes import polar_lift assert hyper([polar_lift(z)], [polar_lift(k)], polar_lift(x)) == \ hyper([z], [k], polar_lift(x)) # hyper does not automatically evaluate anyway, but the test is to make # sure that the evaluate keyword is accepted assert hyper((1, 2), (1,), z, evaluate=False).func is hyper def test_expand_func(): # evaluation at 1 of Gauss' hypergeometric function: from sympy.abc import a, b, c from sympy.core.function import expand_func a1, b1, c1 = randcplx(), randcplx(), randcplx() + 5 assert expand_func(hyper([a, b], [c], 1)) == \ gamma(c)*gamma(-a - b + c)/(gamma(-a + c)*gamma(-b + c)) assert abs(expand_func(hyper([a1, b1], [c1], 1)).n() - hyper([a1, b1], [c1], 1).n()) < 1e-10 # hyperexpand wrapper for hyper: assert expand_func(hyper([], [], z)) == exp(z) assert expand_func(hyper([1, 2, 3], [], z)) == hyper([1, 2, 3], [], z) assert expand_func(meijerg([[1, 1], []], [[1], [0]], z)) == log(z + 1) assert expand_func(meijerg([[1, 1], []], [[], []], z)) == \ meijerg([[1, 1], []], [[], []], z) def replace_dummy(expr, sym): from sympy.core.symbol import Dummy dum = expr.atoms(Dummy) if not dum: return expr assert len(dum) == 1 return expr.xreplace({dum.pop(): sym}) def test_hyper_rewrite_sum(): from sympy.concrete.summations import Sum from sympy.core.symbol import Dummy from sympy.functions.combinatorial.factorials import (RisingFactorial, factorial) _k = Dummy("k") assert replace_dummy(hyper((1, 2), (1, 3), x).rewrite(Sum), _k) == \ Sum(x**_k / factorial(_k) * RisingFactorial(2, _k) / RisingFactorial(3, _k), (_k, 0, oo)) assert hyper((1, 2, 3), (-1, 3), z).rewrite(Sum) == \ hyper((1, 2, 3), (-1, 3), z) def test_radius_of_convergence(): assert hyper((1, 2), [3], z).radius_of_convergence == 1 assert hyper((1, 2), [3, 4], z).radius_of_convergence is oo assert hyper((1, 2, 3), [4], z).radius_of_convergence == 0 assert hyper((0, 1, 2), [4], z).radius_of_convergence is oo assert hyper((-1, 1, 2), [-4], z).radius_of_convergence == 0 assert hyper((-1, -2, 2), [-1], z).radius_of_convergence is oo assert hyper((-1, 2), [-1, -2], z).radius_of_convergence == 0 assert hyper([-1, 1, 3], [-2, 2], z).radius_of_convergence == 1 assert hyper([-1, 1], [-2, 2], z).radius_of_convergence is oo assert hyper([-1, 1, 3], [-2], z).radius_of_convergence == 0 assert hyper((-1, 2, 3, 4), [], z).radius_of_convergence is oo assert hyper([1, 1], [3], 1).convergence_statement == True assert hyper([1, 1], [2], 1).convergence_statement == False assert hyper([1, 1], [2], -1).convergence_statement == True assert hyper([1, 1], [1], -1).convergence_statement == False def test_meijer(): raises(TypeError, lambda: meijerg(1, z)) raises(TypeError, lambda: meijerg(((1,), (2,)), (3,), (4,), z)) assert meijerg(((1, 2), (3,)), ((4,), (5,)), z) == \ meijerg(Tuple(1, 2), Tuple(3), Tuple(4), Tuple(5), z) g = meijerg((1, 2), (3, 4, 5), (6, 7, 8, 9), (10, 11, 12, 13, 14), z) assert g.an == Tuple(1, 2) assert g.ap == Tuple(1, 2, 3, 4, 5) assert g.aother == Tuple(3, 4, 5) assert g.bm == Tuple(6, 7, 8, 9) assert g.bq == Tuple(6, 7, 8, 9, 10, 11, 12, 13, 14) assert g.bother == Tuple(10, 11, 12, 13, 14) assert g.argument == z assert g.nu == 75 assert g.delta == -1 assert g.is_commutative is True assert g.is_number is False #issue 13071 assert meijerg([[],[]], [[S.Half],[0]], 1).is_number is True assert meijerg([1, 2], [3], [4], [5], z).delta == S.Half # just a few checks to make sure that all arguments go where they should assert tn(meijerg(Tuple(), Tuple(), Tuple(0), Tuple(), -z), exp(z), z) assert tn(sqrt(pi)*meijerg(Tuple(), Tuple(), Tuple(0), Tuple(S.Half), z**2/4), cos(z), z) assert tn(meijerg(Tuple(1, 1), Tuple(), Tuple(1), Tuple(0), z), log(1 + z), z) # test exceptions raises(ValueError, lambda: meijerg(((3, 1), (2,)), ((oo,), (2, 0)), x)) raises(ValueError, lambda: meijerg(((3, 1), (2,)), ((1,), (2, 0)), x)) # differentiation g = meijerg((randcplx(),), (randcplx() + 2*I,), Tuple(), (randcplx(), randcplx()), z) assert td(g, z) g = meijerg(Tuple(), (randcplx(),), Tuple(), (randcplx(), randcplx()), z) assert td(g, z) g = meijerg(Tuple(), Tuple(), Tuple(randcplx()), Tuple(randcplx(), randcplx()), z) assert td(g, z) a1, a2, b1, b2, c1, c2, d1, d2 = symbols('a1:3, b1:3, c1:3, d1:3') assert meijerg((a1, a2), (b1, b2), (c1, c2), (d1, d2), z).diff(z) == \ (meijerg((a1 - 1, a2), (b1, b2), (c1, c2), (d1, d2), z) + (a1 - 1)*meijerg((a1, a2), (b1, b2), (c1, c2), (d1, d2), z))/z assert meijerg([z, z], [], [], [], z).diff(z) == \ Derivative(meijerg([z, z], [], [], [], z), z) # meijerg is unbranched wrt parameters from sympy.functions.elementary.complexes import polar_lift as pl assert meijerg([pl(a1)], [pl(a2)], [pl(b1)], [pl(b2)], pl(z)) == \ meijerg([a1], [a2], [b1], [b2], pl(z)) # integrand from sympy.abc import a, b, c, d, s assert meijerg([a], [b], [c], [d], z).integrand(s) == \ z**s*gamma(c - s)*gamma(-a + s + 1)/(gamma(b - s)*gamma(-d + s + 1)) def test_meijerg_derivative(): assert meijerg([], [1, 1], [0, 0, x], [], z).diff(x) == \ log(z)*meijerg([], [1, 1], [0, 0, x], [], z) \ + 2*meijerg([], [1, 1, 1], [0, 0, x, 0], [], z) y = randcplx() a = 5 # mpmath chokes with non-real numbers, and Mod1 with floats assert td(meijerg([x], [], [], [], y), x) assert td(meijerg([x**2], [], [], [], y), x) assert td(meijerg([], [x], [], [], y), x) assert td(meijerg([], [], [x], [], y), x) assert td(meijerg([], [], [], [x], y), x) assert td(meijerg([x], [a], [a + 1], [], y), x) assert td(meijerg([x], [a + 1], [a], [], y), x) assert td(meijerg([x, a], [], [], [a + 1], y), x) assert td(meijerg([x, a + 1], [], [], [a], y), x) b = Rational(3, 2) assert td(meijerg([a + 2], [b], [b - 3, x], [a], y), x) def test_meijerg_period(): assert meijerg([], [1], [0], [], x).get_period() == 2*pi assert meijerg([1], [], [], [0], x).get_period() == 2*pi assert meijerg([], [], [0], [], x).get_period() == 2*pi # exp(x) assert meijerg( [], [], [0], [S.Half], x).get_period() == 2*pi # cos(sqrt(x)) assert meijerg( [], [], [S.Half], [0], x).get_period() == 4*pi # sin(sqrt(x)) assert meijerg([1, 1], [], [1], [0], x).get_period() is oo # log(1 + x) def test_hyper_unpolarify(): from sympy.functions.elementary.exponential import exp_polar a = exp_polar(2*pi*I)*x b = x assert hyper([], [], a).argument == b assert hyper([0], [], a).argument == a assert hyper([0], [0], a).argument == b assert hyper([0, 1], [0], a).argument == a assert hyper([0, 1], [0], exp_polar(2*pi*I)).argument == 1 @slow def test_hyperrep(): from sympy.functions.special.hyper import (HyperRep, HyperRep_atanh, HyperRep_power1, HyperRep_power2, HyperRep_log1, HyperRep_asin1, HyperRep_asin2, HyperRep_sqrts1, HyperRep_sqrts2, HyperRep_log2, HyperRep_cosasin, HyperRep_sinasin) # First test the base class works. from sympy.functions.elementary.exponential import exp_polar from sympy.functions.elementary.piecewise import Piecewise a, b, c, d, z = symbols('a b c d z') class myrep(HyperRep): @classmethod def _expr_small(cls, x): return a @classmethod def _expr_small_minus(cls, x): return b @classmethod def _expr_big(cls, x, n): return c*n @classmethod def _expr_big_minus(cls, x, n): return d*n assert myrep(z).rewrite('nonrep') == Piecewise((0, abs(z) > 1), (a, True)) assert myrep(exp_polar(I*pi)*z).rewrite('nonrep') == \ Piecewise((0, abs(z) > 1), (b, True)) assert myrep(exp_polar(2*I*pi)*z).rewrite('nonrep') == \ Piecewise((c, abs(z) > 1), (a, True)) assert myrep(exp_polar(3*I*pi)*z).rewrite('nonrep') == \ Piecewise((d, abs(z) > 1), (b, True)) assert myrep(exp_polar(4*I*pi)*z).rewrite('nonrep') == \ Piecewise((2*c, abs(z) > 1), (a, True)) assert myrep(exp_polar(5*I*pi)*z).rewrite('nonrep') == \ Piecewise((2*d, abs(z) > 1), (b, True)) assert myrep(z).rewrite('nonrepsmall') == a assert myrep(exp_polar(I*pi)*z).rewrite('nonrepsmall') == b def t(func, hyp, z): """ Test that func is a valid representation of hyp. """ # First test that func agrees with hyp for small z if not tn(func.rewrite('nonrepsmall'), hyp, z, a=Rational(-1, 2), b=Rational(-1, 2), c=S.Half, d=S.Half): return False # Next check that the two small representations agree. if not tn( func.rewrite('nonrepsmall').subs( z, exp_polar(I*pi)*z).replace(exp_polar, exp), func.subs(z, exp_polar(I*pi)*z).rewrite('nonrepsmall'), z, a=Rational(-1, 2), b=Rational(-1, 2), c=S.Half, d=S.Half): return False # Next check continuity along exp_polar(I*pi)*t expr = func.subs(z, exp_polar(I*pi)*z).rewrite('nonrep') if abs(expr.subs(z, 1 + 1e-15).n() - expr.subs(z, 1 - 1e-15).n()) > 1e-10: return False # Finally check continuity of the big reps. def dosubs(func, a, b): rv = func.subs(z, exp_polar(a)*z).rewrite('nonrep') return rv.subs(z, exp_polar(b)*z).replace(exp_polar, exp) for n in [0, 1, 2, 3, 4, -1, -2, -3, -4]: expr1 = dosubs(func, 2*I*pi*n, I*pi/2) expr2 = dosubs(func, 2*I*pi*n + I*pi, -I*pi/2) if not tn(expr1, expr2, z): return False expr1 = dosubs(func, 2*I*pi*(n + 1), -I*pi/2) expr2 = dosubs(func, 2*I*pi*n + I*pi, I*pi/2) if not tn(expr1, expr2, z): return False return True # Now test the various representatives. a = Rational(1, 3) assert t(HyperRep_atanh(z), hyper([S.Half, 1], [Rational(3, 2)], z), z) assert t(HyperRep_power1(a, z), hyper([-a], [], z), z) assert t(HyperRep_power2(a, z), hyper([a, a - S.Half], [2*a], z), z) assert t(HyperRep_log1(z), -z*hyper([1, 1], [2], z), z) assert t(HyperRep_asin1(z), hyper([S.Half, S.Half], [Rational(3, 2)], z), z) assert t(HyperRep_asin2(z), hyper([1, 1], [Rational(3, 2)], z), z) assert t(HyperRep_sqrts1(a, z), hyper([-a, S.Half - a], [S.Half], z), z) assert t(HyperRep_sqrts2(a, z), -2*z/(2*a + 1)*hyper([-a - S.Half, -a], [S.Half], z).diff(z), z) assert t(HyperRep_log2(z), -z/4*hyper([Rational(3, 2), 1, 1], [2, 2], z), z) assert t(HyperRep_cosasin(a, z), hyper([-a, a], [S.Half], z), z) assert t(HyperRep_sinasin(a, z), 2*a*z*hyper([1 - a, 1 + a], [Rational(3, 2)], z), z) @slow def test_meijerg_eval(): from sympy.functions.elementary.exponential import exp_polar from sympy.functions.special.bessel import besseli from sympy.abc import l a = randcplx() arg = x*exp_polar(k*pi*I) expr1 = pi*meijerg([[], [(a + 1)/2]], [[a/2], [-a/2, (a + 1)/2]], arg**2/4) expr2 = besseli(a, arg) # Test that the two expressions agree for all arguments. for x_ in [0.5, 1.5]: for k_ in [0.0, 0.1, 0.3, 0.5, 0.8, 1, 5.751, 15.3]: assert abs((expr1 - expr2).n(subs={x: x_, k: k_})) < 1e-10 assert abs((expr1 - expr2).n(subs={x: x_, k: -k_})) < 1e-10 # Test continuity independently eps = 1e-13 expr2 = expr1.subs(k, l) for x_ in [0.5, 1.5]: for k_ in [0.5, Rational(1, 3), 0.25, 0.75, Rational(2, 3), 1.0, 1.5]: assert abs((expr1 - expr2).n( subs={x: x_, k: k_ + eps, l: k_ - eps})) < 1e-10 assert abs((expr1 - expr2).n( subs={x: x_, k: -k_ + eps, l: -k_ - eps})) < 1e-10 expr = (meijerg(((0.5,), ()), ((0.5, 0, 0.5), ()), exp_polar(-I*pi)/4) + meijerg(((0.5,), ()), ((0.5, 0, 0.5), ()), exp_polar(I*pi)/4)) \ /(2*sqrt(pi)) assert (expr - pi/exp(1)).n(chop=True) == 0 def test_limits(): k, x = symbols('k, x') assert hyper((1,), (Rational(4, 3), Rational(5, 3)), k**2).series(k) == \ 1 + 9*k**2/20 + 81*k**4/1120 + O(k**6) # issue 6350 assert limit(meijerg((), (), (1,), (0,), -x), x, 0) == \ meijerg(((), ()), ((1,), (0,)), 0) # issue 6052 # https://github.com/sympy/sympy/issues/11465 assert limit(1/hyper((1, ), (1, ), x), x, 0) == 1 def test_appellf1(): a, b1, b2, c, x, y = symbols('a b1 b2 c x y') assert appellf1(a, b2, b1, c, y, x) == appellf1(a, b1, b2, c, x, y) assert appellf1(a, b1, b1, c, y, x) == appellf1(a, b1, b1, c, x, y) assert appellf1(a, b1, b2, c, S.Zero, S.Zero) is S.One f = appellf1(a, b1, b2, c, S.Zero, S.Zero, evaluate=False) assert f.func is appellf1 assert f.doit() is S.One def test_derivative_appellf1(): from sympy.core.function import diff a, b1, b2, c, x, y, z = symbols('a b1 b2 c x y z') assert diff(appellf1(a, b1, b2, c, x, y), x) == a*b1*appellf1(a + 1, b2, b1 + 1, c + 1, y, x)/c assert diff(appellf1(a, b1, b2, c, x, y), y) == a*b2*appellf1(a + 1, b1, b2 + 1, c + 1, x, y)/c assert diff(appellf1(a, b1, b2, c, x, y), z) == 0 assert diff(appellf1(a, b1, b2, c, x, y), a) == Derivative(appellf1(a, b1, b2, c, x, y), a) def test_eval_nseries(): a1, b1, a2, b2 = symbols('a1 b1 a2 b2') assert hyper((1,2), (1,2,3), x**2)._eval_nseries(x, 7, None) == 1 + x**2/3 + x**4/24 + x**6/360 + O(x**7) assert exp(x)._eval_nseries(x,7,None) == hyper((a1, b1), (a1, b1), x)._eval_nseries(x, 7, None) assert hyper((a1, a2), (b1, b2), x)._eval_nseries(z, 7, None) == hyper((a1, a2), (b1, b2), x) + O(z**7)
7ea27217d5217b2df5543ec673bdf57f25ef900f2c096d2858fcf327ee3ab2a9
from sympy.concrete.summations import Sum from sympy.core.function import expand_func from sympy.core.numbers import (Float, I, Rational, nan, oo, pi, zoo) from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.functions.elementary.complexes import (Abs, polar_lift) from sympy.functions.elementary.exponential import (exp, exp_polar, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.special.zeta_functions import (dirichlet_eta, lerchphi, polylog, riemann_xi, stieltjes, zeta) from sympy.series.order import O from sympy.core.function import ArgumentIndexError from sympy.functions.combinatorial.numbers import bernoulli, factorial from sympy.testing.pytest import raises from sympy.core.random import (test_derivative_numerically as td, random_complex_number as randcplx, verify_numerically) x = Symbol('x') a = Symbol('a') b = Symbol('b', negative=True) z = Symbol('z') s = Symbol('s') def test_zeta_eval(): assert zeta(nan) is nan assert zeta(x, nan) is nan assert zeta(0) == Rational(-1, 2) assert zeta(0, x) == S.Half - x assert zeta(0, b) == S.Half - b assert zeta(1) is zoo assert zeta(1, 2) is zoo assert zeta(1, -7) is zoo assert zeta(1, x) is zoo assert zeta(2, 1) == pi**2/6 assert zeta(2) == pi**2/6 assert zeta(4) == pi**4/90 assert zeta(6) == pi**6/945 assert zeta(2, 2) == pi**2/6 - 1 assert zeta(4, 3) == pi**4/90 - Rational(17, 16) assert zeta(6, 4) == pi**6/945 - Rational(47449, 46656) assert zeta(2, -2) == pi**2/6 + Rational(5, 4) assert zeta(4, -3) == pi**4/90 + Rational(1393, 1296) assert zeta(6, -4) == pi**6/945 + Rational(3037465, 2985984) assert zeta(oo) == 1 assert zeta(-1) == Rational(-1, 12) assert zeta(-2) == 0 assert zeta(-3) == Rational(1, 120) assert zeta(-4) == 0 assert zeta(-5) == Rational(-1, 252) assert zeta(-1, 3) == Rational(-37, 12) assert zeta(-1, 7) == Rational(-253, 12) assert zeta(-1, -4) == Rational(119, 12) assert zeta(-1, -9) == Rational(539, 12) assert zeta(-4, 3) == -17 assert zeta(-4, -8) == 8772 assert zeta(0, 1) == Rational(-1, 2) assert zeta(0, -1) == Rational(3, 2) assert zeta(0, 2) == Rational(-3, 2) assert zeta(0, -2) == Rational(5, 2) assert zeta( 3).evalf(20).epsilon_eq(Float("1.2020569031595942854", 20), 1e-19) def test_zeta_series(): assert zeta(x, a).series(a, 0, 2) == \ zeta(x, 0) - x*a*zeta(x + 1, 0) + O(a**2) def test_dirichlet_eta_eval(): assert dirichlet_eta(0) == S.Half assert dirichlet_eta(-1) == Rational(1, 4) assert dirichlet_eta(1) == log(2) assert dirichlet_eta(2) == pi**2/12 assert dirichlet_eta(4) == pi**4*Rational(7, 720) def test_riemann_xi_eval(): assert riemann_xi(2) == pi/6 assert riemann_xi(0) == Rational(1, 2) assert riemann_xi(1) == Rational(1, 2) assert riemann_xi(3).rewrite(zeta) == 3*zeta(3)/(2*pi) assert riemann_xi(4) == pi**2/15 def test_rewriting(): assert dirichlet_eta(x).rewrite(zeta) == (1 - 2**(1 - x))*zeta(x) assert zeta(x).rewrite(dirichlet_eta) == dirichlet_eta(x)/(1 - 2**(1 - x)) assert zeta(x).rewrite(dirichlet_eta, a=2) == zeta(x) assert verify_numerically(dirichlet_eta(x), dirichlet_eta(x).rewrite(zeta), x) assert verify_numerically(zeta(x), zeta(x).rewrite(dirichlet_eta), x) assert zeta(x, a).rewrite(lerchphi) == lerchphi(1, x, a) assert polylog(s, z).rewrite(lerchphi) == lerchphi(z, s, 1)*z assert lerchphi(1, x, a).rewrite(zeta) == zeta(x, a) assert z*lerchphi(z, s, 1).rewrite(polylog) == polylog(s, z) def test_derivatives(): from sympy.core.function import Derivative assert zeta(x, a).diff(x) == Derivative(zeta(x, a), x) assert zeta(x, a).diff(a) == -x*zeta(x + 1, a) assert lerchphi( z, s, a).diff(z) == (lerchphi(z, s - 1, a) - a*lerchphi(z, s, a))/z assert lerchphi(z, s, a).diff(a) == -s*lerchphi(z, s + 1, a) assert polylog(s, z).diff(z) == polylog(s - 1, z)/z b = randcplx() c = randcplx() assert td(zeta(b, x), x) assert td(polylog(b, z), z) assert td(lerchphi(c, b, x), x) assert td(lerchphi(x, b, c), x) raises(ArgumentIndexError, lambda: lerchphi(c, b, x).fdiff(2)) raises(ArgumentIndexError, lambda: lerchphi(c, b, x).fdiff(4)) raises(ArgumentIndexError, lambda: polylog(b, z).fdiff(1)) raises(ArgumentIndexError, lambda: polylog(b, z).fdiff(3)) def myexpand(func, target): expanded = expand_func(func) if target is not None: return expanded == target if expanded == func: # it didn't expand return False # check to see that the expanded and original evaluate to the same value subs = {} for a in func.free_symbols: subs[a] = randcplx() return abs(func.subs(subs).n() - expanded.replace(exp_polar, exp).subs(subs).n()) < 1e-10 def test_polylog_expansion(): assert polylog(s, 0) == 0 assert polylog(s, 1) == zeta(s) assert polylog(s, -1) == -dirichlet_eta(s) assert polylog(s, exp_polar(I*pi*Rational(4, 3))) == polylog(s, exp(I*pi*Rational(4, 3))) assert polylog(s, exp_polar(I*pi)/3) == polylog(s, exp(I*pi)/3) assert myexpand(polylog(1, z), -log(1 - z)) assert myexpand(polylog(0, z), z/(1 - z)) assert myexpand(polylog(-1, z), z/(1 - z)**2) assert ((1-z)**3 * expand_func(polylog(-2, z))).simplify() == z*(1 + z) assert myexpand(polylog(-5, z), None) def test_polylog_series(): assert polylog(1, z).series(z, n=5) == z + z**2/2 + z**3/3 + z**4/4 + O(z**5) assert polylog(1, sqrt(z)).series(z, n=3) == z/2 + z**2/4 + sqrt(z)\ + z**(S(3)/2)/3 + z**(S(5)/2)/5 + O(z**3) # https://github.com/sympy/sympy/issues/9497 assert polylog(S(3)/2, -z).series(z, 0, 5) == -z + sqrt(2)*z**2/4\ - sqrt(3)*z**3/9 + z**4/8 + O(z**5) def test_issue_8404(): i = Symbol('i', integer=True) assert Abs(Sum(1/(3*i + 1)**2, (i, 0, S.Infinity)).doit().n(4) - 1.122) < 0.001 def test_polylog_values(): assert polylog(2, 2) == pi**2/4 - I*pi*log(2) assert polylog(2, S.Half) == pi**2/12 - log(2)**2/2 for z in [S.Half, 2, (sqrt(5)-1)/2, -(sqrt(5)-1)/2, -(sqrt(5)+1)/2, (3-sqrt(5))/2]: assert Abs(polylog(2, z).evalf() - polylog(2, z, evaluate=False).evalf()) < 1e-15 z = Symbol("z") for s in [-1, 0]: for _ in range(10): assert verify_numerically(polylog(s, z), polylog(s, z, evaluate=False), z, a=-3, b=-2, c=S.Half, d=2) assert verify_numerically(polylog(s, z), polylog(s, z, evaluate=False), z, a=2, b=-2, c=5, d=2) from sympy.integrals.integrals import Integral assert polylog(0, Integral(1, (x, 0, 1))) == -S.Half def test_lerchphi_expansion(): assert myexpand(lerchphi(1, s, a), zeta(s, a)) assert myexpand(lerchphi(z, s, 1), polylog(s, z)/z) # direct summation assert myexpand(lerchphi(z, -1, a), a/(1 - z) + z/(1 - z)**2) assert myexpand(lerchphi(z, -3, a), None) # polylog reduction assert myexpand(lerchphi(z, s, S.Half), 2**(s - 1)*(polylog(s, sqrt(z))/sqrt(z) - polylog(s, polar_lift(-1)*sqrt(z))/sqrt(z))) assert myexpand(lerchphi(z, s, 2), -1/z + polylog(s, z)/z**2) assert myexpand(lerchphi(z, s, Rational(3, 2)), None) assert myexpand(lerchphi(z, s, Rational(7, 3)), None) assert myexpand(lerchphi(z, s, Rational(-1, 3)), None) assert myexpand(lerchphi(z, s, Rational(-5, 2)), None) # hurwitz zeta reduction assert myexpand(lerchphi(-1, s, a), 2**(-s)*zeta(s, a/2) - 2**(-s)*zeta(s, (a + 1)/2)) assert myexpand(lerchphi(I, s, a), None) assert myexpand(lerchphi(-I, s, a), None) assert myexpand(lerchphi(exp(I*pi*Rational(2, 5)), s, a), None) def test_stieltjes(): assert isinstance(stieltjes(x), stieltjes) assert isinstance(stieltjes(x, a), stieltjes) # Zero'th constant EulerGamma assert stieltjes(0) == S.EulerGamma assert stieltjes(0, 1) == S.EulerGamma # Not defined assert stieltjes(nan) is nan assert stieltjes(0, nan) is nan assert stieltjes(-1) is S.ComplexInfinity assert stieltjes(1.5) is S.ComplexInfinity assert stieltjes(z, 0) is S.ComplexInfinity assert stieltjes(z, -1) is S.ComplexInfinity def test_stieltjes_evalf(): assert abs(stieltjes(0).evalf() - 0.577215664) < 1E-9 assert abs(stieltjes(0, 0.5).evalf() - 1.963510026) < 1E-9 assert abs(stieltjes(1, 2).evalf() + 0.072815845 ) < 1E-9 def test_issue_10475(): a = Symbol('a', extended_real=True) b = Symbol('b', extended_positive=True) s = Symbol('s', zero=False) assert zeta(2 + I).is_finite assert zeta(1).is_finite is False assert zeta(x).is_finite is None assert zeta(x + I).is_finite is None assert zeta(a).is_finite is None assert zeta(b).is_finite is None assert zeta(-b).is_finite is True assert zeta(b**2 - 2*b + 1).is_finite is None assert zeta(a + I).is_finite is True assert zeta(b + 1).is_finite is True assert zeta(s + 1).is_finite is True def test_issue_14177(): n = Symbol('n', positive=True, integer=True) assert zeta(2*n) == (-1)**(n + 1)*2**(2*n - 1)*pi**(2*n)*bernoulli(2*n)/factorial(2*n) assert zeta(-n) == (-1)**(-n)*bernoulli(n + 1)/(n + 1) n = Symbol('n') assert zeta(2*n) == zeta(2*n) # As sign of z (= 2*n) is not determined
d62688adca57e3dff86a1f4bbd85fb45c48ed801b189949f29d6542ff8cce4ae
from itertools import product from sympy.concrete.summations import Sum from sympy.core.function import (diff, expand_func) from sympy.core.numbers import (I, Rational, oo, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import (conjugate, polar_lift) from sympy.functions.elementary.exponential import (exp, exp_polar, log) from sympy.functions.elementary.hyperbolic import (cosh, sinh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.bessel import (besseli, besselj, besselk, bessely, hankel1, hankel2, hn1, hn2, jn, jn_zeros, yn) from sympy.functions.special.gamma_functions import (gamma, uppergamma) from sympy.functions.special.hyper import hyper from sympy.integrals.integrals import Integral from sympy.series.order import O from sympy.series.series import series from sympy.functions.special.bessel import (airyai, airybi, airyaiprime, airybiprime, marcumq) from sympy.core.random import (random_complex_number as randcplx, verify_numerically as tn, test_derivative_numerically as td, _randint) from sympy.simplify import besselsimp from sympy.testing.pytest import raises from sympy.abc import z, n, k, x randint = _randint() def test_bessel_rand(): for f in [besselj, bessely, besseli, besselk, hankel1, hankel2]: assert td(f(randcplx(), z), z) for f in [jn, yn, hn1, hn2]: assert td(f(randint(-10, 10), z), z) def test_bessel_twoinputs(): for f in [besselj, bessely, besseli, besselk, hankel1, hankel2, jn, yn]: raises(TypeError, lambda: f(1)) raises(TypeError, lambda: f(1, 2, 3)) def test_besselj_leading_term(): assert besselj(0, x).as_leading_term(x) == 1 assert besselj(1, sin(x)).as_leading_term(x) == x/2 assert besselj(1, 2*sqrt(x)).as_leading_term(x) == sqrt(x) # https://github.com/sympy/sympy/issues/21701 assert (besselj(z, x)/x**z).as_leading_term(x) == 1/(2**z*gamma(z + 1)) def test_bessely_leading_term(): assert bessely(0, x).as_leading_term(x) == (2*log(x) - 2*log(2))/pi assert bessely(1, sin(x)).as_leading_term(x) == (x*log(x) - x*log(2))/pi assert bessely(1, 2*sqrt(x)).as_leading_term(x) == sqrt(x)*log(x)/pi def test_besselj_series(): assert besselj(0, x).series(x) == 1 - x**2/4 + x**4/64 + O(x**6) assert besselj(0, x**(1.1)).series(x) == 1 + x**4.4/64 - x**2.2/4 + O(x**6) assert besselj(0, x**2 + x).series(x) == 1 - x**2/4 - x**3/2\ - 15*x**4/64 + x**5/16 + O(x**6) assert besselj(0, sqrt(x) + x).series(x, n=4) == 1 - x/4 - 15*x**2/64\ + 215*x**3/2304 - x**Rational(3, 2)/2 + x**Rational(5, 2)/16\ + 23*x**Rational(7, 2)/384 + O(x**4) assert besselj(0, x/(1 - x)).series(x) == 1 - x**2/4 - x**3/2 - 47*x**4/64\ - 15*x**5/16 + O(x**6) assert besselj(0, log(1 + x)).series(x) == 1 - x**2/4 + x**3/4\ - 41*x**4/192 + 17*x**5/96 + O(x**6) assert besselj(1, sin(x)).series(x) == x/2 - 7*x**3/48 + 73*x**5/1920 + O(x**6) assert besselj(1, 2*sqrt(x)).series(x) == sqrt(x) - x**Rational(3, 2)/2\ + x**Rational(5, 2)/12 - x**Rational(7, 2)/144 + x**Rational(9, 2)/2880\ - x**Rational(11, 2)/86400 + O(x**6) assert besselj(-2, sin(x)).series(x, n=4) == besselj(2, sin(x)).series(x, n=4) def test_bessely_series(): const = 2*S.EulerGamma/pi - 2*log(2)/pi + 2*log(x)/pi assert bessely(0, x).series(x, n=4) == const + x**2*(-log(x)/(2*pi)\ + (2 - 2*S.EulerGamma)/(4*pi) + log(2)/(2*pi)) + O(x**4*log(x)) assert bessely(0, x**(1.1)).series(x, n=4) == 2*S.EulerGamma/pi\ - 2*log(2)/pi + 2.2*log(x)/pi + x**2.2*(-0.55*log(x)/pi\ + (2 - 2*S.EulerGamma)/(4*pi) + log(2)/(2*pi)) + O(x**4*log(x)) assert bessely(0, x**2 + x).series(x, n=4) == \ const - (2 - 2*S.EulerGamma)*(-x**3/(2*pi) - x**2/(4*pi)) + 2*x/pi\ + x**2*(-log(x)/(2*pi) - 1/pi + log(2)/(2*pi))\ + x**3*(-log(x)/pi + 1/(6*pi) + log(2)/pi) + O(x**4*log(x)) assert bessely(0, x/(1 - x)).series(x, n=3) == const\ + 2*x/pi + x**2*(-log(x)/(2*pi) + (2 - 2*S.EulerGamma)/(4*pi)\ + log(2)/(2*pi) + 1/pi) + O(x**3*log(x)) assert bessely(0, log(1 + x)).series(x, n=3) == const\ - x/pi + x**2*(-log(x)/(2*pi) + (2 - 2*S.EulerGamma)/(4*pi)\ + log(2)/(2*pi) + 5/(12*pi)) + O(x**3*log(x)) assert bessely(1, sin(x)).series(x, n=4) == -(1/pi)*(1 - 2*S.EulerGamma)\ * (-x**3/12 + x/2) + x*(log(x)/pi - log(2)/pi) + x**3*(-7*log(x)\ / (24*pi) - 1/(6*pi) + (Rational(5, 2) - 2*S.EulerGamma)/(16*pi)\ + 7*log(2)/(24*pi)) + O(x**4*log(x)) assert bessely(1, 2*sqrt(x)).series(x, n=3) == sqrt(x)*(log(x)/pi \ - (1 - 2*S.EulerGamma)/pi) + x**Rational(3, 2)*(-log(x)/(2*pi)\ + (Rational(5, 2) - 2*S.EulerGamma)/(2*pi))\ + x**Rational(5, 2)*(log(x)/(12*pi)\ - (Rational(10, 3) - 2*S.EulerGamma)/(12*pi)) + O(x**3*log(x)) assert bessely(-2, sin(x)).series(x, n=4) == bessely(2, sin(x)).series(x, n=4) def test_diff(): assert besselj(n, z).diff(z) == besselj(n - 1, z)/2 - besselj(n + 1, z)/2 assert bessely(n, z).diff(z) == bessely(n - 1, z)/2 - bessely(n + 1, z)/2 assert besseli(n, z).diff(z) == besseli(n - 1, z)/2 + besseli(n + 1, z)/2 assert besselk(n, z).diff(z) == -besselk(n - 1, z)/2 - besselk(n + 1, z)/2 assert hankel1(n, z).diff(z) == hankel1(n - 1, z)/2 - hankel1(n + 1, z)/2 assert hankel2(n, z).diff(z) == hankel2(n - 1, z)/2 - hankel2(n + 1, z)/2 def test_rewrite(): assert besselj(n, z).rewrite(jn) == sqrt(2*z/pi)*jn(n - S.Half, z) assert bessely(n, z).rewrite(yn) == sqrt(2*z/pi)*yn(n - S.Half, z) assert besseli(n, z).rewrite(besselj) == \ exp(-I*n*pi/2)*besselj(n, polar_lift(I)*z) assert besselj(n, z).rewrite(besseli) == \ exp(I*n*pi/2)*besseli(n, polar_lift(-I)*z) nu = randcplx() assert tn(besselj(nu, z), besselj(nu, z).rewrite(besseli), z) assert tn(besselj(nu, z), besselj(nu, z).rewrite(bessely), z) assert tn(besseli(nu, z), besseli(nu, z).rewrite(besselj), z) assert tn(besseli(nu, z), besseli(nu, z).rewrite(bessely), z) assert tn(bessely(nu, z), bessely(nu, z).rewrite(besselj), z) assert tn(bessely(nu, z), bessely(nu, z).rewrite(besseli), z) assert tn(besselk(nu, z), besselk(nu, z).rewrite(besselj), z) assert tn(besselk(nu, z), besselk(nu, z).rewrite(besseli), z) assert tn(besselk(nu, z), besselk(nu, z).rewrite(bessely), z) # check that a rewrite was triggered, when the order is set to a generic # symbol 'nu' assert yn(nu, z) != yn(nu, z).rewrite(jn) assert hn1(nu, z) != hn1(nu, z).rewrite(jn) assert hn2(nu, z) != hn2(nu, z).rewrite(jn) assert jn(nu, z) != jn(nu, z).rewrite(yn) assert hn1(nu, z) != hn1(nu, z).rewrite(yn) assert hn2(nu, z) != hn2(nu, z).rewrite(yn) # rewriting spherical bessel functions (SBFs) w.r.t. besselj, bessely is # not allowed if a generic symbol 'nu' is used as the order of the SBFs # to avoid inconsistencies (the order of bessel[jy] is allowed to be # complex-valued, whereas SBFs are defined only for integer orders) order = nu for f in (besselj, bessely): assert hn1(order, z) == hn1(order, z).rewrite(f) assert hn2(order, z) == hn2(order, z).rewrite(f) assert jn(order, z).rewrite(besselj) == sqrt(2)*sqrt(pi)*sqrt(1/z)*besselj(order + S.Half, z)/2 assert jn(order, z).rewrite(bessely) == (-1)**nu*sqrt(2)*sqrt(pi)*sqrt(1/z)*bessely(-order - S.Half, z)/2 # for integral orders rewriting SBFs w.r.t bessel[jy] is allowed N = Symbol('n', integer=True) ri = randint(-11, 10) for order in (ri, N): for f in (besselj, bessely): assert yn(order, z) != yn(order, z).rewrite(f) assert jn(order, z) != jn(order, z).rewrite(f) assert hn1(order, z) != hn1(order, z).rewrite(f) assert hn2(order, z) != hn2(order, z).rewrite(f) for func, refunc in product((yn, jn, hn1, hn2), (jn, yn, besselj, bessely)): assert tn(func(ri, z), func(ri, z).rewrite(refunc), z) def test_expand(): assert expand_func(besselj(S.Half, z).rewrite(jn)) == \ sqrt(2)*sin(z)/(sqrt(pi)*sqrt(z)) assert expand_func(bessely(S.Half, z).rewrite(yn)) == \ -sqrt(2)*cos(z)/(sqrt(pi)*sqrt(z)) # XXX: teach sin/cos to work around arguments like # x*exp_polar(I*pi*n/2). Then change besselsimp -> expand_func assert besselsimp(besselj(S.Half, z)) == sqrt(2)*sin(z)/(sqrt(pi)*sqrt(z)) assert besselsimp(besselj(Rational(-1, 2), z)) == sqrt(2)*cos(z)/(sqrt(pi)*sqrt(z)) assert besselsimp(besselj(Rational(5, 2), z)) == \ -sqrt(2)*(z**2*sin(z) + 3*z*cos(z) - 3*sin(z))/(sqrt(pi)*z**Rational(5, 2)) assert besselsimp(besselj(Rational(-5, 2), z)) == \ -sqrt(2)*(z**2*cos(z) - 3*z*sin(z) - 3*cos(z))/(sqrt(pi)*z**Rational(5, 2)) assert besselsimp(bessely(S.Half, z)) == \ -(sqrt(2)*cos(z))/(sqrt(pi)*sqrt(z)) assert besselsimp(bessely(Rational(-1, 2), z)) == sqrt(2)*sin(z)/(sqrt(pi)*sqrt(z)) assert besselsimp(bessely(Rational(5, 2), z)) == \ sqrt(2)*(z**2*cos(z) - 3*z*sin(z) - 3*cos(z))/(sqrt(pi)*z**Rational(5, 2)) assert besselsimp(bessely(Rational(-5, 2), z)) == \ -sqrt(2)*(z**2*sin(z) + 3*z*cos(z) - 3*sin(z))/(sqrt(pi)*z**Rational(5, 2)) assert besselsimp(besseli(S.Half, z)) == sqrt(2)*sinh(z)/(sqrt(pi)*sqrt(z)) assert besselsimp(besseli(Rational(-1, 2), z)) == \ sqrt(2)*cosh(z)/(sqrt(pi)*sqrt(z)) assert besselsimp(besseli(Rational(5, 2), z)) == \ sqrt(2)*(z**2*sinh(z) - 3*z*cosh(z) + 3*sinh(z))/(sqrt(pi)*z**Rational(5, 2)) assert besselsimp(besseli(Rational(-5, 2), z)) == \ sqrt(2)*(z**2*cosh(z) - 3*z*sinh(z) + 3*cosh(z))/(sqrt(pi)*z**Rational(5, 2)) assert besselsimp(besselk(S.Half, z)) == \ besselsimp(besselk(Rational(-1, 2), z)) == sqrt(pi)*exp(-z)/(sqrt(2)*sqrt(z)) assert besselsimp(besselk(Rational(5, 2), z)) == \ besselsimp(besselk(Rational(-5, 2), z)) == \ sqrt(2)*sqrt(pi)*(z**2 + 3*z + 3)*exp(-z)/(2*z**Rational(5, 2)) n = Symbol('n', integer=True, positive=True) assert expand_func(besseli(n + 2, z)) == \ besseli(n, z) + (-2*n - 2)*(-2*n*besseli(n, z)/z + besseli(n - 1, z))/z assert expand_func(besselj(n + 2, z)) == \ -besselj(n, z) + (2*n + 2)*(2*n*besselj(n, z)/z - besselj(n - 1, z))/z assert expand_func(besselk(n + 2, z)) == \ besselk(n, z) + (2*n + 2)*(2*n*besselk(n, z)/z + besselk(n - 1, z))/z assert expand_func(bessely(n + 2, z)) == \ -bessely(n, z) + (2*n + 2)*(2*n*bessely(n, z)/z - bessely(n - 1, z))/z assert expand_func(besseli(n + S.Half, z).rewrite(jn)) == \ (sqrt(2)*sqrt(z)*exp(-I*pi*(n + S.Half)/2) * exp_polar(I*pi/4)*jn(n, z*exp_polar(I*pi/2))/sqrt(pi)) assert expand_func(besselj(n + S.Half, z).rewrite(jn)) == \ sqrt(2)*sqrt(z)*jn(n, z)/sqrt(pi) r = Symbol('r', real=True) p = Symbol('p', positive=True) i = Symbol('i', integer=True) for besselx in [besselj, bessely, besseli, besselk]: assert besselx(i, p).is_extended_real is True assert besselx(i, x).is_extended_real is None assert besselx(x, z).is_extended_real is None for besselx in [besselj, besseli]: assert besselx(i, r).is_extended_real is True for besselx in [bessely, besselk]: assert besselx(i, r).is_extended_real is None for besselx in [besselj, bessely, besseli, besselk]: assert expand_func(besselx(oo, x)) == besselx(oo, x, evaluate=False) assert expand_func(besselx(-oo, x)) == besselx(-oo, x, evaluate=False) def test_slow_expand(): def check(eq, ans): return tn(eq, ans) and eq == ans rn = randcplx(a=1, b=0, d=0, c=2) for besselx in [besselj, bessely, besseli, besselk]: ri = S(2*randint(-11, 10) + 1) / 2 # half integer in [-21/2, 21/2] assert tn(besselsimp(besselx(ri, z)), besselx(ri, z)) assert check(expand_func(besseli(rn, x)), besseli(rn - 2, x) - 2*(rn - 1)*besseli(rn - 1, x)/x) assert check(expand_func(besseli(-rn, x)), besseli(-rn + 2, x) + 2*(-rn + 1)*besseli(-rn + 1, x)/x) assert check(expand_func(besselj(rn, x)), -besselj(rn - 2, x) + 2*(rn - 1)*besselj(rn - 1, x)/x) assert check(expand_func(besselj(-rn, x)), -besselj(-rn + 2, x) + 2*(-rn + 1)*besselj(-rn + 1, x)/x) assert check(expand_func(besselk(rn, x)), besselk(rn - 2, x) + 2*(rn - 1)*besselk(rn - 1, x)/x) assert check(expand_func(besselk(-rn, x)), besselk(-rn + 2, x) - 2*(-rn + 1)*besselk(-rn + 1, x)/x) assert check(expand_func(bessely(rn, x)), -bessely(rn - 2, x) + 2*(rn - 1)*bessely(rn - 1, x)/x) assert check(expand_func(bessely(-rn, x)), -bessely(-rn + 2, x) + 2*(-rn + 1)*bessely(-rn + 1, x)/x) def mjn(n, z): return expand_func(jn(n, z)) def myn(n, z): return expand_func(yn(n, z)) def test_jn(): z = symbols("z") assert jn(0, 0) == 1 assert jn(1, 0) == 0 assert jn(-1, 0) == S.ComplexInfinity assert jn(z, 0) == jn(z, 0, evaluate=False) assert jn(0, oo) == 0 assert jn(0, -oo) == 0 assert mjn(0, z) == sin(z)/z assert mjn(1, z) == sin(z)/z**2 - cos(z)/z assert mjn(2, z) == (3/z**3 - 1/z)*sin(z) - (3/z**2) * cos(z) assert mjn(3, z) == (15/z**4 - 6/z**2)*sin(z) + (1/z - 15/z**3)*cos(z) assert mjn(4, z) == (1/z + 105/z**5 - 45/z**3)*sin(z) + \ (-105/z**4 + 10/z**2)*cos(z) assert mjn(5, z) == (945/z**6 - 420/z**4 + 15/z**2)*sin(z) + \ (-1/z - 945/z**5 + 105/z**3)*cos(z) assert mjn(6, z) == (-1/z + 10395/z**7 - 4725/z**5 + 210/z**3)*sin(z) + \ (-10395/z**6 + 1260/z**4 - 21/z**2)*cos(z) assert expand_func(jn(n, z)) == jn(n, z) # SBFs not defined for complex-valued orders assert jn(2+3j, 5.2+0.3j).evalf() == jn(2+3j, 5.2+0.3j) assert eq([jn(2, 5.2+0.3j).evalf(10)], [0.09941975672 - 0.05452508024*I]) def test_yn(): z = symbols("z") assert myn(0, z) == -cos(z)/z assert myn(1, z) == -cos(z)/z**2 - sin(z)/z assert myn(2, z) == -((3/z**3 - 1/z)*cos(z) + (3/z**2)*sin(z)) assert expand_func(yn(n, z)) == yn(n, z) # SBFs not defined for complex-valued orders assert yn(2+3j, 5.2+0.3j).evalf() == yn(2+3j, 5.2+0.3j) assert eq([yn(2, 5.2+0.3j).evalf(10)], [0.185250342 + 0.01489557397*I]) def test_sympify_yn(): assert S(15) in myn(3, pi).atoms() assert myn(3, pi) == 15/pi**4 - 6/pi**2 def eq(a, b, tol=1e-6): for u, v in zip(a, b): if not (abs(u - v) < tol): return False return True def test_jn_zeros(): assert eq(jn_zeros(0, 4), [3.141592, 6.283185, 9.424777, 12.566370]) assert eq(jn_zeros(1, 4), [4.493409, 7.725251, 10.904121, 14.066193]) assert eq(jn_zeros(2, 4), [5.763459, 9.095011, 12.322940, 15.514603]) assert eq(jn_zeros(3, 4), [6.987932, 10.417118, 13.698023, 16.923621]) assert eq(jn_zeros(4, 4), [8.182561, 11.704907, 15.039664, 18.301255]) def test_bessel_eval(): n, m, k = Symbol('n', integer=True), Symbol('m'), Symbol('k', integer=True, zero=False) for f in [besselj, besseli]: assert f(0, 0) is S.One assert f(2.1, 0) is S.Zero assert f(-3, 0) is S.Zero assert f(-10.2, 0) is S.ComplexInfinity assert f(1 + 3*I, 0) is S.Zero assert f(-3 + I, 0) is S.ComplexInfinity assert f(-2*I, 0) is S.NaN assert f(n, 0) != S.One and f(n, 0) != S.Zero assert f(m, 0) != S.One and f(m, 0) != S.Zero assert f(k, 0) is S.Zero assert bessely(0, 0) is S.NegativeInfinity assert besselk(0, 0) is S.Infinity for f in [bessely, besselk]: assert f(1 + I, 0) is S.ComplexInfinity assert f(I, 0) is S.NaN for f in [besselj, bessely]: assert f(m, S.Infinity) is S.Zero assert f(m, S.NegativeInfinity) is S.Zero for f in [besseli, besselk]: assert f(m, I*S.Infinity) is S.Zero assert f(m, I*S.NegativeInfinity) is S.Zero for f in [besseli, besselk]: assert f(-4, z) == f(4, z) assert f(-3, z) == f(3, z) assert f(-n, z) == f(n, z) assert f(-m, z) != f(m, z) for f in [besselj, bessely]: assert f(-4, z) == f(4, z) assert f(-3, z) == -f(3, z) assert f(-n, z) == (-1)**n*f(n, z) assert f(-m, z) != (-1)**m*f(m, z) for f in [besselj, besseli]: assert f(m, -z) == (-z)**m*z**(-m)*f(m, z) assert besseli(2, -z) == besseli(2, z) assert besseli(3, -z) == -besseli(3, z) assert besselj(0, -z) == besselj(0, z) assert besselj(1, -z) == -besselj(1, z) assert besseli(0, I*z) == besselj(0, z) assert besseli(1, I*z) == I*besselj(1, z) assert besselj(3, I*z) == -I*besseli(3, z) def test_bessel_nan(): # FIXME: could have these return NaN; for now just fix infinite recursion for f in [besselj, bessely, besseli, besselk, hankel1, hankel2, yn, jn]: assert f(1, S.NaN) == f(1, S.NaN, evaluate=False) def test_meromorphic(): assert besselj(2, x).is_meromorphic(x, 1) == True assert besselj(2, x).is_meromorphic(x, 0) == True assert besselj(2, x).is_meromorphic(x, oo) == False assert besselj(S(2)/3, x).is_meromorphic(x, 1) == True assert besselj(S(2)/3, x).is_meromorphic(x, 0) == False assert besselj(S(2)/3, x).is_meromorphic(x, oo) == False assert besselj(x, 2*x).is_meromorphic(x, 2) == False assert besselk(0, x).is_meromorphic(x, 1) == True assert besselk(2, x).is_meromorphic(x, 0) == True assert besseli(0, x).is_meromorphic(x, 1) == True assert besseli(2, x).is_meromorphic(x, 0) == True assert bessely(0, x).is_meromorphic(x, 1) == True assert bessely(0, x).is_meromorphic(x, 0) == False assert bessely(2, x).is_meromorphic(x, 0) == True assert hankel1(3, x**2 + 2*x).is_meromorphic(x, 1) == True assert hankel1(0, x).is_meromorphic(x, 0) == False assert hankel2(11, 4).is_meromorphic(x, 5) == True assert hn1(6, 7*x**3 + 4).is_meromorphic(x, 7) == True assert hn2(3, 2*x).is_meromorphic(x, 9) == True assert jn(5, 2*x + 7).is_meromorphic(x, 4) == True assert yn(8, x**2 + 11).is_meromorphic(x, 6) == True def test_conjugate(): n = Symbol('n') z = Symbol('z', extended_real=False) x = Symbol('x', extended_real=True) y = Symbol('y', positive=True) t = Symbol('t', negative=True) for f in [besseli, besselj, besselk, bessely, hankel1, hankel2]: assert f(n, -1).conjugate() != f(conjugate(n), -1) assert f(n, x).conjugate() != f(conjugate(n), x) assert f(n, t).conjugate() != f(conjugate(n), t) rz = randcplx(b=0.5) for f in [besseli, besselj, besselk, bessely]: assert f(n, 1 + I).conjugate() == f(conjugate(n), 1 - I) assert f(n, 0).conjugate() == f(conjugate(n), 0) assert f(n, 1).conjugate() == f(conjugate(n), 1) assert f(n, z).conjugate() == f(conjugate(n), conjugate(z)) assert f(n, y).conjugate() == f(conjugate(n), y) assert tn(f(n, rz).conjugate(), f(conjugate(n), conjugate(rz))) assert hankel1(n, 1 + I).conjugate() == hankel2(conjugate(n), 1 - I) assert hankel1(n, 0).conjugate() == hankel2(conjugate(n), 0) assert hankel1(n, 1).conjugate() == hankel2(conjugate(n), 1) assert hankel1(n, y).conjugate() == hankel2(conjugate(n), y) assert hankel1(n, z).conjugate() == hankel2(conjugate(n), conjugate(z)) assert tn(hankel1(n, rz).conjugate(), hankel2(conjugate(n), conjugate(rz))) assert hankel2(n, 1 + I).conjugate() == hankel1(conjugate(n), 1 - I) assert hankel2(n, 0).conjugate() == hankel1(conjugate(n), 0) assert hankel2(n, 1).conjugate() == hankel1(conjugate(n), 1) assert hankel2(n, y).conjugate() == hankel1(conjugate(n), y) assert hankel2(n, z).conjugate() == hankel1(conjugate(n), conjugate(z)) assert tn(hankel2(n, rz).conjugate(), hankel1(conjugate(n), conjugate(rz))) def test_branching(): assert besselj(polar_lift(k), x) == besselj(k, x) assert besseli(polar_lift(k), x) == besseli(k, x) n = Symbol('n', integer=True) assert besselj(n, exp_polar(2*pi*I)*x) == besselj(n, x) assert besselj(n, polar_lift(x)) == besselj(n, x) assert besseli(n, exp_polar(2*pi*I)*x) == besseli(n, x) assert besseli(n, polar_lift(x)) == besseli(n, x) def tn(func, s): from sympy.core.random import uniform c = uniform(1, 5) expr = func(s, c*exp_polar(I*pi)) - func(s, c*exp_polar(-I*pi)) eps = 1e-15 expr2 = func(s + eps, -c + eps*I) - func(s + eps, -c - eps*I) return abs(expr.n() - expr2.n()).n() < 1e-10 nu = Symbol('nu') assert besselj(nu, exp_polar(2*pi*I)*x) == exp(2*pi*I*nu)*besselj(nu, x) assert besseli(nu, exp_polar(2*pi*I)*x) == exp(2*pi*I*nu)*besseli(nu, x) assert tn(besselj, 2) assert tn(besselj, pi) assert tn(besselj, I) assert tn(besseli, 2) assert tn(besseli, pi) assert tn(besseli, I) def test_airy_base(): z = Symbol('z') x = Symbol('x', real=True) y = Symbol('y', real=True) assert conjugate(airyai(z)) == airyai(conjugate(z)) assert airyai(x).is_extended_real assert airyai(x+I*y).as_real_imag() == ( airyai(x - I*y)/2 + airyai(x + I*y)/2, I*(airyai(x - I*y) - airyai(x + I*y))/2) def test_airyai(): z = Symbol('z', real=False) t = Symbol('t', negative=True) p = Symbol('p', positive=True) assert isinstance(airyai(z), airyai) assert airyai(0) == 3**Rational(1, 3)/(3*gamma(Rational(2, 3))) assert airyai(oo) == 0 assert airyai(-oo) == 0 assert diff(airyai(z), z) == airyaiprime(z) assert series(airyai(z), z, 0, 3) == ( 3**Rational(5, 6)*gamma(Rational(1, 3))/(6*pi) - 3**Rational(1, 6)*z*gamma(Rational(2, 3))/(2*pi) + O(z**3)) assert airyai(z).rewrite(hyper) == ( -3**Rational(2, 3)*z*hyper((), (Rational(4, 3),), z**3/9)/(3*gamma(Rational(1, 3))) + 3**Rational(1, 3)*hyper((), (Rational(2, 3),), z**3/9)/(3*gamma(Rational(2, 3)))) assert isinstance(airyai(z).rewrite(besselj), airyai) assert airyai(t).rewrite(besselj) == ( sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) + besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3) assert airyai(z).rewrite(besseli) == ( -z*besseli(Rational(1, 3), 2*z**Rational(3, 2)/3)/(3*(z**Rational(3, 2))**Rational(1, 3)) + (z**Rational(3, 2))**Rational(1, 3)*besseli(Rational(-1, 3), 2*z**Rational(3, 2)/3)/3) assert airyai(p).rewrite(besseli) == ( sqrt(p)*(besseli(Rational(-1, 3), 2*p**Rational(3, 2)/3) - besseli(Rational(1, 3), 2*p**Rational(3, 2)/3))/3) assert expand_func(airyai(2*(3*z**5)**Rational(1, 3))) == ( -sqrt(3)*(-1 + (z**5)**Rational(1, 3)/z**Rational(5, 3))*airybi(2*3**Rational(1, 3)*z**Rational(5, 3))/6 + (1 + (z**5)**Rational(1, 3)/z**Rational(5, 3))*airyai(2*3**Rational(1, 3)*z**Rational(5, 3))/2) def test_airybi(): z = Symbol('z', real=False) t = Symbol('t', negative=True) p = Symbol('p', positive=True) assert isinstance(airybi(z), airybi) assert airybi(0) == 3**Rational(5, 6)/(3*gamma(Rational(2, 3))) assert airybi(oo) is oo assert airybi(-oo) == 0 assert diff(airybi(z), z) == airybiprime(z) assert series(airybi(z), z, 0, 3) == ( 3**Rational(1, 3)*gamma(Rational(1, 3))/(2*pi) + 3**Rational(2, 3)*z*gamma(Rational(2, 3))/(2*pi) + O(z**3)) assert airybi(z).rewrite(hyper) == ( 3**Rational(1, 6)*z*hyper((), (Rational(4, 3),), z**3/9)/gamma(Rational(1, 3)) + 3**Rational(5, 6)*hyper((), (Rational(2, 3),), z**3/9)/(3*gamma(Rational(2, 3)))) assert isinstance(airybi(z).rewrite(besselj), airybi) assert airyai(t).rewrite(besselj) == ( sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) + besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3) assert airybi(z).rewrite(besseli) == ( sqrt(3)*(z*besseli(Rational(1, 3), 2*z**Rational(3, 2)/3)/(z**Rational(3, 2))**Rational(1, 3) + (z**Rational(3, 2))**Rational(1, 3)*besseli(Rational(-1, 3), 2*z**Rational(3, 2)/3))/3) assert airybi(p).rewrite(besseli) == ( sqrt(3)*sqrt(p)*(besseli(Rational(-1, 3), 2*p**Rational(3, 2)/3) + besseli(Rational(1, 3), 2*p**Rational(3, 2)/3))/3) assert expand_func(airybi(2*(3*z**5)**Rational(1, 3))) == ( sqrt(3)*(1 - (z**5)**Rational(1, 3)/z**Rational(5, 3))*airyai(2*3**Rational(1, 3)*z**Rational(5, 3))/2 + (1 + (z**5)**Rational(1, 3)/z**Rational(5, 3))*airybi(2*3**Rational(1, 3)*z**Rational(5, 3))/2) def test_airyaiprime(): z = Symbol('z', real=False) t = Symbol('t', negative=True) p = Symbol('p', positive=True) assert isinstance(airyaiprime(z), airyaiprime) assert airyaiprime(0) == -3**Rational(2, 3)/(3*gamma(Rational(1, 3))) assert airyaiprime(oo) == 0 assert diff(airyaiprime(z), z) == z*airyai(z) assert series(airyaiprime(z), z, 0, 3) == ( -3**Rational(2, 3)/(3*gamma(Rational(1, 3))) + 3**Rational(1, 3)*z**2/(6*gamma(Rational(2, 3))) + O(z**3)) assert airyaiprime(z).rewrite(hyper) == ( 3**Rational(1, 3)*z**2*hyper((), (Rational(5, 3),), z**3/9)/(6*gamma(Rational(2, 3))) - 3**Rational(2, 3)*hyper((), (Rational(1, 3),), z**3/9)/(3*gamma(Rational(1, 3)))) assert isinstance(airyaiprime(z).rewrite(besselj), airyaiprime) assert airyai(t).rewrite(besselj) == ( sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) + besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3) assert airyaiprime(z).rewrite(besseli) == ( z**2*besseli(Rational(2, 3), 2*z**Rational(3, 2)/3)/(3*(z**Rational(3, 2))**Rational(2, 3)) - (z**Rational(3, 2))**Rational(2, 3)*besseli(Rational(-1, 3), 2*z**Rational(3, 2)/3)/3) assert airyaiprime(p).rewrite(besseli) == ( p*(-besseli(Rational(-2, 3), 2*p**Rational(3, 2)/3) + besseli(Rational(2, 3), 2*p**Rational(3, 2)/3))/3) assert expand_func(airyaiprime(2*(3*z**5)**Rational(1, 3))) == ( sqrt(3)*(z**Rational(5, 3)/(z**5)**Rational(1, 3) - 1)*airybiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/6 + (z**Rational(5, 3)/(z**5)**Rational(1, 3) + 1)*airyaiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/2) def test_airybiprime(): z = Symbol('z', real=False) t = Symbol('t', negative=True) p = Symbol('p', positive=True) assert isinstance(airybiprime(z), airybiprime) assert airybiprime(0) == 3**Rational(1, 6)/gamma(Rational(1, 3)) assert airybiprime(oo) is oo assert airybiprime(-oo) == 0 assert diff(airybiprime(z), z) == z*airybi(z) assert series(airybiprime(z), z, 0, 3) == ( 3**Rational(1, 6)/gamma(Rational(1, 3)) + 3**Rational(5, 6)*z**2/(6*gamma(Rational(2, 3))) + O(z**3)) assert airybiprime(z).rewrite(hyper) == ( 3**Rational(5, 6)*z**2*hyper((), (Rational(5, 3),), z**3/9)/(6*gamma(Rational(2, 3))) + 3**Rational(1, 6)*hyper((), (Rational(1, 3),), z**3/9)/gamma(Rational(1, 3))) assert isinstance(airybiprime(z).rewrite(besselj), airybiprime) assert airyai(t).rewrite(besselj) == ( sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) + besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3) assert airybiprime(z).rewrite(besseli) == ( sqrt(3)*(z**2*besseli(Rational(2, 3), 2*z**Rational(3, 2)/3)/(z**Rational(3, 2))**Rational(2, 3) + (z**Rational(3, 2))**Rational(2, 3)*besseli(Rational(-2, 3), 2*z**Rational(3, 2)/3))/3) assert airybiprime(p).rewrite(besseli) == ( sqrt(3)*p*(besseli(Rational(-2, 3), 2*p**Rational(3, 2)/3) + besseli(Rational(2, 3), 2*p**Rational(3, 2)/3))/3) assert expand_func(airybiprime(2*(3*z**5)**Rational(1, 3))) == ( sqrt(3)*(z**Rational(5, 3)/(z**5)**Rational(1, 3) - 1)*airyaiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/2 + (z**Rational(5, 3)/(z**5)**Rational(1, 3) + 1)*airybiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/2) def test_marcumq(): m = Symbol('m') a = Symbol('a') b = Symbol('b') assert marcumq(0, 0, 0) == 0 assert marcumq(m, 0, b) == uppergamma(m, b**2/2)/gamma(m) assert marcumq(2, 0, 5) == 27*exp(Rational(-25, 2))/2 assert marcumq(0, a, 0) == 1 - exp(-a**2/2) assert marcumq(0, pi, 0) == 1 - exp(-pi**2/2) assert marcumq(1, a, a) == S.Half + exp(-a**2)*besseli(0, a**2)/2 assert marcumq(2, a, a) == S.Half + exp(-a**2)*besseli(0, a**2)/2 + exp(-a**2)*besseli(1, a**2) assert diff(marcumq(1, a, 3), a) == a*(-marcumq(1, a, 3) + marcumq(2, a, 3)) assert diff(marcumq(2, 3, b), b) == -b**2*exp(-b**2/2 - Rational(9, 2))*besseli(1, 3*b)/3 x = Symbol('x') assert marcumq(2, 3, 4).rewrite(Integral, x=x) == \ Integral(x**2*exp(-x**2/2 - Rational(9, 2))*besseli(1, 3*x), (x, 4, oo))/3 assert eq([marcumq(5, -2, 3).rewrite(Integral).evalf(10)], [0.7905769565]) k = Symbol('k') assert marcumq(-3, -5, -7).rewrite(Sum, k=k) == \ exp(-37)*Sum((Rational(5, 7))**k*besseli(k, 35), (k, 4, oo)) assert eq([marcumq(1, 3, 1).rewrite(Sum).evalf(10)], [0.9891705502]) assert marcumq(1, a, a, evaluate=False).rewrite(besseli) == S.Half + exp(-a**2)*besseli(0, a**2)/2 assert marcumq(2, a, a, evaluate=False).rewrite(besseli) == S.Half + exp(-a**2)*besseli(0, a**2)/2 + \ exp(-a**2)*besseli(1, a**2) assert marcumq(3, a, a).rewrite(besseli) == (besseli(1, a**2) + besseli(2, a**2))*exp(-a**2) + \ S.Half + exp(-a**2)*besseli(0, a**2)/2 assert marcumq(5, 8, 8).rewrite(besseli) == exp(-64)*besseli(0, 64)/2 + \ (besseli(4, 64) + besseli(3, 64) + besseli(2, 64) + besseli(1, 64))*exp(-64) + S.Half assert marcumq(m, a, a).rewrite(besseli) == marcumq(m, a, a) x = Symbol('x', integer=True) assert marcumq(x, a, a).rewrite(besseli) == marcumq(x, a, a)
01acd960ca30f6ccdbbc2fd67cad747398fe2d0440ce7a3a57558909bb69e0c5
from sympy.core.numbers import (I, Rational, oo, pi, zoo) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol) from sympy.functions.elementary.hyperbolic import atanh from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (sin, tan) from sympy.functions.special.gamma_functions import gamma from sympy.functions.special.hyper import (hyper, meijerg) from sympy.integrals.integrals import Integral from sympy.series.order import O from sympy.functions.special.elliptic_integrals import (elliptic_k as K, elliptic_f as F, elliptic_e as E, elliptic_pi as P) from sympy.core.random import (test_derivative_numerically as td, random_complex_number as randcplx, verify_numerically as tn) from sympy.abc import z, m, n i = Symbol('i', integer=True) j = Symbol('k', integer=True, positive=True) t = Dummy('t') def test_K(): assert K(0) == pi/2 assert K(S.Half) == 8*pi**Rational(3, 2)/gamma(Rational(-1, 4))**2 assert K(1) is zoo assert K(-1) == gamma(Rational(1, 4))**2/(4*sqrt(2*pi)) assert K(oo) == 0 assert K(-oo) == 0 assert K(I*oo) == 0 assert K(-I*oo) == 0 assert K(zoo) == 0 assert K(z).diff(z) == (E(z) - (1 - z)*K(z))/(2*z*(1 - z)) assert td(K(z), z) zi = Symbol('z', real=False) assert K(zi).conjugate() == K(zi.conjugate()) zr = Symbol('z', negative=True) assert K(zr).conjugate() == K(zr) assert K(z).rewrite(hyper) == \ (pi/2)*hyper((S.Half, S.Half), (S.One,), z) assert tn(K(z), (pi/2)*hyper((S.Half, S.Half), (S.One,), z)) assert K(z).rewrite(meijerg) == \ meijerg(((S.Half, S.Half), []), ((S.Zero,), (S.Zero,)), -z)/2 assert tn(K(z), meijerg(((S.Half, S.Half), []), ((S.Zero,), (S.Zero,)), -z)/2) assert K(z).series(z) == pi/2 + pi*z/8 + 9*pi*z**2/128 + \ 25*pi*z**3/512 + 1225*pi*z**4/32768 + 3969*pi*z**5/131072 + O(z**6) assert K(m).rewrite(Integral).dummy_eq( Integral(1/sqrt(1 - m*sin(t)**2), (t, 0, pi/2))) def test_F(): assert F(z, 0) == z assert F(0, m) == 0 assert F(pi*i/2, m) == i*K(m) assert F(z, oo) == 0 assert F(z, -oo) == 0 assert F(-z, m) == -F(z, m) assert F(z, m).diff(z) == 1/sqrt(1 - m*sin(z)**2) assert F(z, m).diff(m) == E(z, m)/(2*m*(1 - m)) - F(z, m)/(2*m) - \ sin(2*z)/(4*(1 - m)*sqrt(1 - m*sin(z)**2)) r = randcplx() assert td(F(z, r), z) assert td(F(r, m), m) mi = Symbol('m', real=False) assert F(z, mi).conjugate() == F(z.conjugate(), mi.conjugate()) mr = Symbol('m', negative=True) assert F(z, mr).conjugate() == F(z.conjugate(), mr) assert F(z, m).series(z) == \ z + z**5*(3*m**2/40 - m/30) + m*z**3/6 + O(z**6) assert F(z, m).rewrite(Integral).dummy_eq( Integral(1/sqrt(1 - m*sin(t)**2), (t, 0, z))) def test_E(): assert E(z, 0) == z assert E(0, m) == 0 assert E(i*pi/2, m) == i*E(m) assert E(z, oo) is zoo assert E(z, -oo) is zoo assert E(0) == pi/2 assert E(1) == 1 assert E(oo) == I*oo assert E(-oo) is oo assert E(zoo) is zoo assert E(-z, m) == -E(z, m) assert E(z, m).diff(z) == sqrt(1 - m*sin(z)**2) assert E(z, m).diff(m) == (E(z, m) - F(z, m))/(2*m) assert E(z).diff(z) == (E(z) - K(z))/(2*z) r = randcplx() assert td(E(r, m), m) assert td(E(z, r), z) assert td(E(z), z) mi = Symbol('m', real=False) assert E(z, mi).conjugate() == E(z.conjugate(), mi.conjugate()) assert E(mi).conjugate() == E(mi.conjugate()) mr = Symbol('m', negative=True) assert E(z, mr).conjugate() == E(z.conjugate(), mr) assert E(mr).conjugate() == E(mr) assert E(z).rewrite(hyper) == (pi/2)*hyper((Rational(-1, 2), S.Half), (S.One,), z) assert tn(E(z), (pi/2)*hyper((Rational(-1, 2), S.Half), (S.One,), z)) assert E(z).rewrite(meijerg) == \ -meijerg(((S.Half, Rational(3, 2)), []), ((S.Zero,), (S.Zero,)), -z)/4 assert tn(E(z), -meijerg(((S.Half, Rational(3, 2)), []), ((S.Zero,), (S.Zero,)), -z)/4) assert E(z, m).series(z) == \ z + z**5*(-m**2/40 + m/30) - m*z**3/6 + O(z**6) assert E(z).series(z) == pi/2 - pi*z/8 - 3*pi*z**2/128 - \ 5*pi*z**3/512 - 175*pi*z**4/32768 - 441*pi*z**5/131072 + O(z**6) assert E(z, m).rewrite(Integral).dummy_eq( Integral(sqrt(1 - m*sin(t)**2), (t, 0, z))) assert E(m).rewrite(Integral).dummy_eq( Integral(sqrt(1 - m*sin(t)**2), (t, 0, pi/2))) def test_P(): assert P(0, z, m) == F(z, m) assert P(1, z, m) == F(z, m) + \ (sqrt(1 - m*sin(z)**2)*tan(z) - E(z, m))/(1 - m) assert P(n, i*pi/2, m) == i*P(n, m) assert P(n, z, 0) == atanh(sqrt(n - 1)*tan(z))/sqrt(n - 1) assert P(n, z, n) == F(z, n) - P(1, z, n) + tan(z)/sqrt(1 - n*sin(z)**2) assert P(oo, z, m) == 0 assert P(-oo, z, m) == 0 assert P(n, z, oo) == 0 assert P(n, z, -oo) == 0 assert P(0, m) == K(m) assert P(1, m) is zoo assert P(n, 0) == pi/(2*sqrt(1 - n)) assert P(2, 1) is -oo assert P(-1, 1) is oo assert P(n, n) == E(n)/(1 - n) assert P(n, -z, m) == -P(n, z, m) ni, mi = Symbol('n', real=False), Symbol('m', real=False) assert P(ni, z, mi).conjugate() == \ P(ni.conjugate(), z.conjugate(), mi.conjugate()) nr, mr = Symbol('n', negative=True), \ Symbol('m', negative=True) assert P(nr, z, mr).conjugate() == P(nr, z.conjugate(), mr) assert P(n, m).conjugate() == P(n.conjugate(), m.conjugate()) assert P(n, z, m).diff(n) == (E(z, m) + (m - n)*F(z, m)/n + (n**2 - m)*P(n, z, m)/n - n*sqrt(1 - m*sin(z)**2)*sin(2*z)/(2*(1 - n*sin(z)**2)))/(2*(m - n)*(n - 1)) assert P(n, z, m).diff(z) == 1/(sqrt(1 - m*sin(z)**2)*(1 - n*sin(z)**2)) assert P(n, z, m).diff(m) == (E(z, m)/(m - 1) + P(n, z, m) - m*sin(2*z)/(2*(m - 1)*sqrt(1 - m*sin(z)**2)))/(2*(n - m)) assert P(n, m).diff(n) == (E(m) + (m - n)*K(m)/n + (n**2 - m)*P(n, m)/n)/(2*(m - n)*(n - 1)) assert P(n, m).diff(m) == (E(m)/(m - 1) + P(n, m))/(2*(n - m)) # These tests fail due to # https://github.com/fredrik-johansson/mpmath/issues/571#issuecomment-777201962 # https://github.com/sympy/sympy/issues/20933#issuecomment-777080385 # # rx, ry = randcplx(), randcplx() # assert td(P(n, rx, ry), n) # assert td(P(rx, z, ry), z) # assert td(P(rx, ry, m), m) assert P(n, z, m).series(z) == z + z**3*(m/6 + n/3) + \ z**5*(3*m**2/40 + m*n/10 - m/30 + n**2/5 - n/15) + O(z**6) assert P(n, z, m).rewrite(Integral).dummy_eq( Integral(1/((1 - n*sin(t)**2)*sqrt(1 - m*sin(t)**2)), (t, 0, z))) assert P(n, m).rewrite(Integral).dummy_eq( Integral(1/((1 - n*sin(t)**2)*sqrt(1 - m*sin(t)**2)), (t, 0, pi/2)))
4112a5e058d71068c33798815a6154a73b9bbc743af101fae23c43b3d597581f
from sympy.core.function import expand_func from sympy.core import EulerGamma from sympy.core.numbers import (I, Rational, nan, oo, pi, zoo) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol) from sympy.functions.combinatorial.factorials import factorial from sympy.functions.combinatorial.numbers import harmonic from sympy.functions.elementary.complexes import (Abs, conjugate, im, re) from sympy.functions.elementary.exponential import (exp, exp_polar, log) from sympy.functions.elementary.hyperbolic import tanh from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.error_functions import (Ei, erf, erfc) from sympy.functions.special.gamma_functions import (digamma, gamma, loggamma, lowergamma, multigamma, polygamma, trigamma, uppergamma) from sympy.functions.special.zeta_functions import zeta from sympy.series.order import O from sympy.core.expr import unchanged from sympy.core.function import ArgumentIndexError from sympy.testing.pytest import raises from sympy.core.random import (test_derivative_numerically as td, random_complex_number as randcplx, verify_numerically as tn) x = Symbol('x') y = Symbol('y') n = Symbol('n', integer=True) w = Symbol('w', real=True) def test_gamma(): assert gamma(nan) is nan assert gamma(oo) is oo assert gamma(-100) is zoo assert gamma(0) is zoo assert gamma(-100.0) is zoo assert gamma(1) == 1 assert gamma(2) == 1 assert gamma(3) == 2 assert gamma(102) == factorial(101) assert gamma(S.Half) == sqrt(pi) assert gamma(Rational(3, 2)) == sqrt(pi)*S.Half assert gamma(Rational(5, 2)) == sqrt(pi)*Rational(3, 4) assert gamma(Rational(7, 2)) == sqrt(pi)*Rational(15, 8) assert gamma(Rational(-1, 2)) == -2*sqrt(pi) assert gamma(Rational(-3, 2)) == sqrt(pi)*Rational(4, 3) assert gamma(Rational(-5, 2)) == sqrt(pi)*Rational(-8, 15) assert gamma(Rational(-15, 2)) == sqrt(pi)*Rational(256, 2027025) assert gamma(Rational( -11, 8)).expand(func=True) == Rational(64, 33)*gamma(Rational(5, 8)) assert gamma(Rational( -10, 3)).expand(func=True) == Rational(81, 280)*gamma(Rational(2, 3)) assert gamma(Rational( 14, 3)).expand(func=True) == Rational(880, 81)*gamma(Rational(2, 3)) assert gamma(Rational( 17, 7)).expand(func=True) == Rational(30, 49)*gamma(Rational(3, 7)) assert gamma(Rational( 19, 8)).expand(func=True) == Rational(33, 64)*gamma(Rational(3, 8)) assert gamma(x).diff(x) == gamma(x)*polygamma(0, x) assert gamma(x - 1).expand(func=True) == gamma(x)/(x - 1) assert gamma(x + 2).expand(func=True, mul=False) == x*(x + 1)*gamma(x) assert conjugate(gamma(x)) == gamma(conjugate(x)) assert expand_func(gamma(x + Rational(3, 2))) == \ (x + S.Half)*gamma(x + S.Half) assert expand_func(gamma(x - S.Half)) == \ gamma(S.Half + x)/(x - S.Half) # Test a bug: assert expand_func(gamma(x + Rational(3, 4))) == gamma(x + Rational(3, 4)) # XXX: Not sure about these tests. I can fix them by defining e.g. # exp_polar.is_integer but I'm not sure if that makes sense. assert gamma(3*exp_polar(I*pi)/4).is_nonnegative is False assert gamma(3*exp_polar(I*pi)/4).is_extended_nonpositive is True y = Symbol('y', nonpositive=True, integer=True) assert gamma(y).is_real == False y = Symbol('y', positive=True, noninteger=True) assert gamma(y).is_real == True assert gamma(-1.0, evaluate=False).is_real == False assert gamma(0, evaluate=False).is_real == False assert gamma(-2, evaluate=False).is_real == False def test_gamma_rewrite(): assert gamma(n).rewrite(factorial) == factorial(n - 1) def test_gamma_series(): assert gamma(x + 1).series(x, 0, 3) == \ 1 - EulerGamma*x + x**2*(EulerGamma**2/2 + pi**2/12) + O(x**3) assert gamma(x).series(x, -1, 3) == \ -1/(x + 1) + EulerGamma - 1 + (x + 1)*(-1 - pi**2/12 - EulerGamma**2/2 + \ EulerGamma) + (x + 1)**2*(-1 - pi**2/12 - EulerGamma**2/2 + EulerGamma**3/6 - \ polygamma(2, 1)/6 + EulerGamma*pi**2/12 + EulerGamma) + O((x + 1)**3, (x, -1)) def tn_branch(s, func): from sympy.core.random import uniform c = uniform(1, 5) expr = func(s, c*exp_polar(I*pi)) - func(s, c*exp_polar(-I*pi)) eps = 1e-15 expr2 = func(s + eps, -c + eps*I) - func(s + eps, -c - eps*I) return abs(expr.n() - expr2.n()).n() < 1e-10 def test_lowergamma(): from sympy.functions.special.error_functions import expint from sympy.functions.special.hyper import meijerg assert lowergamma(x, 0) == 0 assert lowergamma(x, y).diff(y) == y**(x - 1)*exp(-y) assert td(lowergamma(randcplx(), y), y) assert td(lowergamma(x, randcplx()), x) assert lowergamma(x, y).diff(x) == \ gamma(x)*digamma(x) - uppergamma(x, y)*log(y) \ - meijerg([], [1, 1], [0, 0, x], [], y) assert lowergamma(S.Half, x) == sqrt(pi)*erf(sqrt(x)) assert not lowergamma(S.Half - 3, x).has(lowergamma) assert not lowergamma(S.Half + 3, x).has(lowergamma) assert lowergamma(S.Half, x, evaluate=False).has(lowergamma) assert tn(lowergamma(S.Half + 3, x, evaluate=False), lowergamma(S.Half + 3, x), x) assert tn(lowergamma(S.Half - 3, x, evaluate=False), lowergamma(S.Half - 3, x), x) assert tn_branch(-3, lowergamma) assert tn_branch(-4, lowergamma) assert tn_branch(Rational(1, 3), lowergamma) assert tn_branch(pi, lowergamma) assert lowergamma(3, exp_polar(4*pi*I)*x) == lowergamma(3, x) assert lowergamma(y, exp_polar(5*pi*I)*x) == \ exp(4*I*pi*y)*lowergamma(y, x*exp_polar(pi*I)) assert lowergamma(-2, exp_polar(5*pi*I)*x) == \ lowergamma(-2, x*exp_polar(I*pi)) + 2*pi*I assert conjugate(lowergamma(x, y)) == lowergamma(conjugate(x), conjugate(y)) assert conjugate(lowergamma(x, 0)) == 0 assert unchanged(conjugate, lowergamma(x, -oo)) assert lowergamma(0, x)._eval_is_meromorphic(x, 0) == False assert lowergamma(S(1)/3, x)._eval_is_meromorphic(x, 0) == False assert lowergamma(1, x, evaluate=False)._eval_is_meromorphic(x, 0) == True assert lowergamma(x, x)._eval_is_meromorphic(x, 0) == False assert lowergamma(x + 1, x)._eval_is_meromorphic(x, 0) == False assert lowergamma(1/x, x)._eval_is_meromorphic(x, 0) == False assert lowergamma(0, x + 1)._eval_is_meromorphic(x, 0) == False assert lowergamma(S(1)/3, x + 1)._eval_is_meromorphic(x, 0) == True assert lowergamma(1, x + 1, evaluate=False)._eval_is_meromorphic(x, 0) == True assert lowergamma(x, x + 1)._eval_is_meromorphic(x, 0) == True assert lowergamma(x + 1, x + 1)._eval_is_meromorphic(x, 0) == True assert lowergamma(1/x, x + 1)._eval_is_meromorphic(x, 0) == False assert lowergamma(0, 1/x)._eval_is_meromorphic(x, 0) == False assert lowergamma(S(1)/3, 1/x)._eval_is_meromorphic(x, 0) == False assert lowergamma(1, 1/x, evaluate=False)._eval_is_meromorphic(x, 0) == False assert lowergamma(x, 1/x)._eval_is_meromorphic(x, 0) == False assert lowergamma(x + 1, 1/x)._eval_is_meromorphic(x, 0) == False assert lowergamma(1/x, 1/x)._eval_is_meromorphic(x, 0) == False assert lowergamma(x, 2).series(x, oo, 3) == \ 2**x*(1 + 2/(x + 1))*exp(-2)/x + O(exp(x*log(2))/x**3, (x, oo)) assert lowergamma( x, y).rewrite(expint) == -y**x*expint(-x + 1, y) + gamma(x) k = Symbol('k', integer=True) assert lowergamma( k, y).rewrite(expint) == -y**k*expint(-k + 1, y) + gamma(k) k = Symbol('k', integer=True, positive=False) assert lowergamma(k, y).rewrite(expint) == lowergamma(k, y) assert lowergamma(x, y).rewrite(uppergamma) == gamma(x) - uppergamma(x, y) assert lowergamma(70, 6) == factorial(69) - 69035724522603011058660187038367026272747334489677105069435923032634389419656200387949342530805432320 * exp(-6) assert (lowergamma(S(77) / 2, 6) - lowergamma(S(77) / 2, 6, evaluate=False)).evalf() < 1e-16 assert (lowergamma(-S(77) / 2, 6) - lowergamma(-S(77) / 2, 6, evaluate=False)).evalf() < 1e-16 def test_uppergamma(): from sympy.functions.special.error_functions import expint from sympy.functions.special.hyper import meijerg assert uppergamma(4, 0) == 6 assert uppergamma(x, y).diff(y) == -y**(x - 1)*exp(-y) assert td(uppergamma(randcplx(), y), y) assert uppergamma(x, y).diff(x) == \ uppergamma(x, y)*log(y) + meijerg([], [1, 1], [0, 0, x], [], y) assert td(uppergamma(x, randcplx()), x) p = Symbol('p', positive=True) assert uppergamma(0, p) == -Ei(-p) assert uppergamma(p, 0) == gamma(p) assert uppergamma(S.Half, x) == sqrt(pi)*erfc(sqrt(x)) assert not uppergamma(S.Half - 3, x).has(uppergamma) assert not uppergamma(S.Half + 3, x).has(uppergamma) assert uppergamma(S.Half, x, evaluate=False).has(uppergamma) assert tn(uppergamma(S.Half + 3, x, evaluate=False), uppergamma(S.Half + 3, x), x) assert tn(uppergamma(S.Half - 3, x, evaluate=False), uppergamma(S.Half - 3, x), x) assert unchanged(uppergamma, x, -oo) assert unchanged(uppergamma, x, 0) assert tn_branch(-3, uppergamma) assert tn_branch(-4, uppergamma) assert tn_branch(Rational(1, 3), uppergamma) assert tn_branch(pi, uppergamma) assert uppergamma(3, exp_polar(4*pi*I)*x) == uppergamma(3, x) assert uppergamma(y, exp_polar(5*pi*I)*x) == \ exp(4*I*pi*y)*uppergamma(y, x*exp_polar(pi*I)) + \ gamma(y)*(1 - exp(4*pi*I*y)) assert uppergamma(-2, exp_polar(5*pi*I)*x) == \ uppergamma(-2, x*exp_polar(I*pi)) - 2*pi*I assert uppergamma(-2, x) == expint(3, x)/x**2 assert conjugate(uppergamma(x, y)) == uppergamma(conjugate(x), conjugate(y)) assert unchanged(conjugate, uppergamma(x, -oo)) assert uppergamma(x, y).rewrite(expint) == y**x*expint(-x + 1, y) assert uppergamma(x, y).rewrite(lowergamma) == gamma(x) - lowergamma(x, y) assert uppergamma(70, 6) == 69035724522603011058660187038367026272747334489677105069435923032634389419656200387949342530805432320*exp(-6) assert (uppergamma(S(77) / 2, 6) - uppergamma(S(77) / 2, 6, evaluate=False)).evalf() < 1e-16 assert (uppergamma(-S(77) / 2, 6) - uppergamma(-S(77) / 2, 6, evaluate=False)).evalf() < 1e-16 def test_polygamma(): assert polygamma(n, nan) is nan assert polygamma(0, oo) is oo assert polygamma(0, -oo) is oo assert polygamma(0, I*oo) is oo assert polygamma(0, -I*oo) is oo assert polygamma(1, oo) == 0 assert polygamma(5, oo) == 0 assert polygamma(0, -9) is zoo assert polygamma(0, -9) is zoo assert polygamma(0, -1) is zoo assert polygamma(0, 0) is zoo assert polygamma(0, 1) == -EulerGamma assert polygamma(0, 7) == Rational(49, 20) - EulerGamma assert polygamma(1, 1) == pi**2/6 assert polygamma(1, 2) == pi**2/6 - 1 assert polygamma(1, 3) == pi**2/6 - Rational(5, 4) assert polygamma(3, 1) == pi**4 / 15 assert polygamma(3, 5) == 6*(Rational(-22369, 20736) + pi**4/90) assert polygamma(5, 1) == 8 * pi**6 / 63 assert polygamma(1, S.Half) == pi**2 / 2 assert polygamma(2, S.Half) == -14*zeta(3) assert polygamma(11, S.Half) == 176896*pi**12 def t(m, n): x = S(m)/n r = polygamma(0, x) if r.has(polygamma): return False return abs(polygamma(0, x.n()).n() - r.n()).n() < 1e-10 assert t(1, 2) assert t(3, 2) assert t(-1, 2) assert t(1, 4) assert t(-3, 4) assert t(1, 3) assert t(4, 3) assert t(3, 4) assert t(2, 3) assert t(123, 5) assert polygamma(0, x).rewrite(zeta) == polygamma(0, x) assert polygamma(1, x).rewrite(zeta) == zeta(2, x) assert polygamma(2, x).rewrite(zeta) == -2*zeta(3, x) assert polygamma(I, 2).rewrite(zeta) == polygamma(I, 2) n1 = Symbol('n1') n2 = Symbol('n2', real=True) n3 = Symbol('n3', integer=True) n4 = Symbol('n4', positive=True) n5 = Symbol('n5', positive=True, integer=True) assert polygamma(n1, x).rewrite(zeta) == polygamma(n1, x) assert polygamma(n2, x).rewrite(zeta) == polygamma(n2, x) assert polygamma(n3, x).rewrite(zeta) == polygamma(n3, x) assert polygamma(n4, x).rewrite(zeta) == polygamma(n4, x) assert polygamma(n5, x).rewrite(zeta) == (-1)**(n5 + 1) * factorial(n5) * zeta(n5 + 1, x) assert polygamma(3, 7*x).diff(x) == 7*polygamma(4, 7*x) assert polygamma(0, x).rewrite(harmonic) == harmonic(x - 1) - EulerGamma assert polygamma(2, x).rewrite(harmonic) == 2*harmonic(x - 1, 3) - 2*zeta(3) ni = Symbol("n", integer=True) assert polygamma(ni, x).rewrite(harmonic) == (-1)**(ni + 1)*(-harmonic(x - 1, ni + 1) + zeta(ni + 1))*factorial(ni) # Polygamma of non-negative integer order is unbranched: k = Symbol('n', integer=True, nonnegative=True) assert polygamma(k, exp_polar(2*I*pi)*x) == polygamma(k, x) # but negative integers are branched! k = Symbol('n', integer=True) assert polygamma(k, exp_polar(2*I*pi)*x).args == (k, exp_polar(2*I*pi)*x) # Polygamma of order -1 is loggamma: assert polygamma(-1, x) == loggamma(x) # But smaller orders are iterated integrals and don't have a special name assert polygamma(-2, x).func is polygamma # Test a bug assert polygamma(0, -x).expand(func=True) == polygamma(0, -x) assert polygamma(2, 2.5).is_positive == False assert polygamma(2, -2.5).is_positive == False assert polygamma(3, 2.5).is_positive == True assert polygamma(3, -2.5).is_positive is True assert polygamma(-2, -2.5).is_positive is None assert polygamma(-3, -2.5).is_positive is None assert polygamma(2, 2.5).is_negative == True assert polygamma(3, 2.5).is_negative == False assert polygamma(3, -2.5).is_negative == False assert polygamma(2, -2.5).is_negative is True assert polygamma(-2, -2.5).is_negative is None assert polygamma(-3, -2.5).is_negative is None assert polygamma(I, 2).is_positive is None assert polygamma(I, 3).is_negative is None # issue 17350 assert polygamma(pi, 3).evalf() == polygamma(pi, 3) assert (I*polygamma(I, pi)).as_real_imag() == \ (-im(polygamma(I, pi)), re(polygamma(I, pi))) assert (tanh(polygamma(I, 1))).rewrite(exp) == \ (exp(polygamma(I, 1)) - exp(-polygamma(I, 1)))/(exp(polygamma(I, 1)) + exp(-polygamma(I, 1))) assert (I / polygamma(I, 4)).rewrite(exp) == \ I*sqrt(re(polygamma(I, 4))**2 + im(polygamma(I, 4))**2)\ /((re(polygamma(I, 4)) + I*im(polygamma(I, 4)))*Abs(polygamma(I, 4))) assert unchanged(polygamma, 2.3, 1.0) # issue 12569 assert unchanged(im, polygamma(0, I)) assert polygamma(Symbol('a', positive=True), Symbol('b', positive=True)).is_real is True assert polygamma(0, I).is_real is None def test_polygamma_expand_func(): assert polygamma(0, x).expand(func=True) == polygamma(0, x) assert polygamma(0, 2*x).expand(func=True) == \ polygamma(0, x)/2 + polygamma(0, S.Half + x)/2 + log(2) assert polygamma(1, 2*x).expand(func=True) == \ polygamma(1, x)/4 + polygamma(1, S.Half + x)/4 assert polygamma(2, x).expand(func=True) == \ polygamma(2, x) assert polygamma(0, -1 + x).expand(func=True) == \ polygamma(0, x) - 1/(x - 1) assert polygamma(0, 1 + x).expand(func=True) == \ 1/x + polygamma(0, x ) assert polygamma(0, 2 + x).expand(func=True) == \ 1/x + 1/(1 + x) + polygamma(0, x) assert polygamma(0, 3 + x).expand(func=True) == \ polygamma(0, x) + 1/x + 1/(1 + x) + 1/(2 + x) assert polygamma(0, 4 + x).expand(func=True) == \ polygamma(0, x) + 1/x + 1/(1 + x) + 1/(2 + x) + 1/(3 + x) assert polygamma(1, 1 + x).expand(func=True) == \ polygamma(1, x) - 1/x**2 assert polygamma(1, 2 + x).expand(func=True, multinomial=False) == \ polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 assert polygamma(1, 3 + x).expand(func=True, multinomial=False) == \ polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 - 1/(2 + x)**2 assert polygamma(1, 4 + x).expand(func=True, multinomial=False) == \ polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 - \ 1/(2 + x)**2 - 1/(3 + x)**2 assert polygamma(0, x + y).expand(func=True) == \ polygamma(0, x + y) assert polygamma(1, x + y).expand(func=True) == \ polygamma(1, x + y) assert polygamma(1, 3 + 4*x + y).expand(func=True, multinomial=False) == \ polygamma(1, y + 4*x) - 1/(y + 4*x)**2 - \ 1/(1 + y + 4*x)**2 - 1/(2 + y + 4*x)**2 assert polygamma(3, 3 + 4*x + y).expand(func=True, multinomial=False) == \ polygamma(3, y + 4*x) - 6/(y + 4*x)**4 - \ 6/(1 + y + 4*x)**4 - 6/(2 + y + 4*x)**4 assert polygamma(3, 4*x + y + 1).expand(func=True, multinomial=False) == \ polygamma(3, y + 4*x) - 6/(y + 4*x)**4 e = polygamma(3, 4*x + y + Rational(3, 2)) assert e.expand(func=True) == e e = polygamma(3, x + y + Rational(3, 4)) assert e.expand(func=True, basic=False) == e def test_digamma(): assert digamma(nan) == nan assert digamma(oo) == oo assert digamma(-oo) == oo assert digamma(I*oo) == oo assert digamma(-I*oo) == oo assert digamma(-9) == zoo assert digamma(-9) == zoo assert digamma(-1) == zoo assert digamma(0) == zoo assert digamma(1) == -EulerGamma assert digamma(7) == Rational(49, 20) - EulerGamma def t(m, n): x = S(m)/n r = digamma(x) if r.has(digamma): return False return abs(digamma(x.n()).n() - r.n()).n() < 1e-10 assert t(1, 2) assert t(3, 2) assert t(-1, 2) assert t(1, 4) assert t(-3, 4) assert t(1, 3) assert t(4, 3) assert t(3, 4) assert t(2, 3) assert t(123, 5) assert digamma(x).rewrite(zeta) == polygamma(0, x) assert digamma(x).rewrite(harmonic) == harmonic(x - 1) - EulerGamma assert digamma(I).is_real is None assert digamma(x,evaluate=False).fdiff() == polygamma(1, x) assert digamma(x,evaluate=False).is_real is None assert digamma(x,evaluate=False).is_positive is None assert digamma(x,evaluate=False).is_negative is None assert digamma(x,evaluate=False).rewrite(polygamma) == polygamma(0, x) def test_digamma_expand_func(): assert digamma(x).expand(func=True) == polygamma(0, x) assert digamma(2*x).expand(func=True) == \ polygamma(0, x)/2 + polygamma(0, Rational(1, 2) + x)/2 + log(2) assert digamma(-1 + x).expand(func=True) == \ polygamma(0, x) - 1/(x - 1) assert digamma(1 + x).expand(func=True) == \ 1/x + polygamma(0, x ) assert digamma(2 + x).expand(func=True) == \ 1/x + 1/(1 + x) + polygamma(0, x) assert digamma(3 + x).expand(func=True) == \ polygamma(0, x) + 1/x + 1/(1 + x) + 1/(2 + x) assert digamma(4 + x).expand(func=True) == \ polygamma(0, x) + 1/x + 1/(1 + x) + 1/(2 + x) + 1/(3 + x) assert digamma(x + y).expand(func=True) == \ polygamma(0, x + y) def test_trigamma(): assert trigamma(nan) == nan assert trigamma(oo) == 0 assert trigamma(1) == pi**2/6 assert trigamma(2) == pi**2/6 - 1 assert trigamma(3) == pi**2/6 - Rational(5, 4) assert trigamma(x, evaluate=False).rewrite(zeta) == zeta(2, x) assert trigamma(x, evaluate=False).rewrite(harmonic) == \ trigamma(x).rewrite(polygamma).rewrite(harmonic) assert trigamma(x,evaluate=False).fdiff() == polygamma(2, x) assert trigamma(x,evaluate=False).is_real is None assert trigamma(x,evaluate=False).is_positive is None assert trigamma(x,evaluate=False).is_negative is None assert trigamma(x,evaluate=False).rewrite(polygamma) == polygamma(1, x) def test_trigamma_expand_func(): assert trigamma(2*x).expand(func=True) == \ polygamma(1, x)/4 + polygamma(1, Rational(1, 2) + x)/4 assert trigamma(1 + x).expand(func=True) == \ polygamma(1, x) - 1/x**2 assert trigamma(2 + x).expand(func=True, multinomial=False) == \ polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 assert trigamma(3 + x).expand(func=True, multinomial=False) == \ polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 - 1/(2 + x)**2 assert trigamma(4 + x).expand(func=True, multinomial=False) == \ polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 - \ 1/(2 + x)**2 - 1/(3 + x)**2 assert trigamma(x + y).expand(func=True) == \ polygamma(1, x + y) assert trigamma(3 + 4*x + y).expand(func=True, multinomial=False) == \ polygamma(1, y + 4*x) - 1/(y + 4*x)**2 - \ 1/(1 + y + 4*x)**2 - 1/(2 + y + 4*x)**2 def test_loggamma(): raises(TypeError, lambda: loggamma(2, 3)) raises(ArgumentIndexError, lambda: loggamma(x).fdiff(2)) assert loggamma(-1) is oo assert loggamma(-2) is oo assert loggamma(0) is oo assert loggamma(1) == 0 assert loggamma(2) == 0 assert loggamma(3) == log(2) assert loggamma(4) == log(6) n = Symbol("n", integer=True, positive=True) assert loggamma(n) == log(gamma(n)) assert loggamma(-n) is oo assert loggamma(n/2) == log(2**(-n + 1)*sqrt(pi)*gamma(n)/gamma(n/2 + S.Half)) assert loggamma(oo) is oo assert loggamma(-oo) is zoo assert loggamma(I*oo) is zoo assert loggamma(-I*oo) is zoo assert loggamma(zoo) is zoo assert loggamma(nan) is nan L = loggamma(Rational(16, 3)) E = -5*log(3) + loggamma(Rational(1, 3)) + log(4) + log(7) + log(10) + log(13) assert expand_func(L).doit() == E assert L.n() == E.n() L = loggamma(Rational(19, 4)) E = -4*log(4) + loggamma(Rational(3, 4)) + log(3) + log(7) + log(11) + log(15) assert expand_func(L).doit() == E assert L.n() == E.n() L = loggamma(Rational(23, 7)) E = -3*log(7) + log(2) + loggamma(Rational(2, 7)) + log(9) + log(16) assert expand_func(L).doit() == E assert L.n() == E.n() L = loggamma(Rational(19, 4) - 7) E = -log(9) - log(5) + loggamma(Rational(3, 4)) + 3*log(4) - 3*I*pi assert expand_func(L).doit() == E assert L.n() == E.n() L = loggamma(Rational(23, 7) - 6) E = -log(19) - log(12) - log(5) + loggamma(Rational(2, 7)) + 3*log(7) - 3*I*pi assert expand_func(L).doit() == E assert L.n() == E.n() assert loggamma(x).diff(x) == polygamma(0, x) s1 = loggamma(1/(x + sin(x)) + cos(x)).nseries(x, n=4) s2 = (-log(2*x) - 1)/(2*x) - log(x/pi)/2 + (4 - log(2*x))*x/24 + O(x**2) + \ log(x)*x**2/2 assert (s1 - s2).expand(force=True).removeO() == 0 s1 = loggamma(1/x).series(x) s2 = (1/x - S.Half)*log(1/x) - 1/x + log(2*pi)/2 + \ x/12 - x**3/360 + x**5/1260 + O(x**7) assert ((s1 - s2).expand(force=True)).removeO() == 0 assert loggamma(x).rewrite('intractable') == log(gamma(x)) s1 = loggamma(x).series(x).cancel() assert s1 == -log(x) - EulerGamma*x + pi**2*x**2/12 + x**3*polygamma(2, 1)/6 + \ pi**4*x**4/360 + x**5*polygamma(4, 1)/120 + O(x**6) assert s1 == loggamma(x).rewrite('intractable').series(x).cancel() assert conjugate(loggamma(x)) == loggamma(conjugate(x)) assert conjugate(loggamma(0)) is oo assert conjugate(loggamma(1)) == loggamma(conjugate(1)) assert conjugate(loggamma(-oo)) == conjugate(zoo) assert loggamma(Symbol('v', positive=True)).is_real is True assert loggamma(Symbol('v', zero=True)).is_real is False assert loggamma(Symbol('v', negative=True)).is_real is False assert loggamma(Symbol('v', nonpositive=True)).is_real is False assert loggamma(Symbol('v', nonnegative=True)).is_real is None assert loggamma(Symbol('v', imaginary=True)).is_real is None assert loggamma(Symbol('v', real=True)).is_real is None assert loggamma(Symbol('v')).is_real is None assert loggamma(S.Half).is_real is True assert loggamma(0).is_real is False assert loggamma(Rational(-1, 2)).is_real is False assert loggamma(I).is_real is None assert loggamma(2 + 3*I).is_real is None def tN(N, M): assert loggamma(1/x)._eval_nseries(x, n=N).getn() == M tN(0, 0) tN(1, 1) tN(2, 2) tN(3, 3) tN(4, 4) tN(5, 5) def test_polygamma_expansion(): # A. & S., pa. 259 and 260 assert polygamma(0, 1/x).nseries(x, n=3) == \ -log(x) - x/2 - x**2/12 + O(x**3) assert polygamma(1, 1/x).series(x, n=5) == \ x + x**2/2 + x**3/6 + O(x**5) assert polygamma(3, 1/x).nseries(x, n=11) == \ 2*x**3 + 3*x**4 + 2*x**5 - x**7 + 4*x**9/3 + O(x**11) def test_issue_8657(): n = Symbol('n', negative=True, integer=True) m = Symbol('m', integer=True) o = Symbol('o', positive=True) p = Symbol('p', negative=True, integer=False) assert gamma(n).is_real is False assert gamma(m).is_real is None assert gamma(o).is_real is True assert gamma(p).is_real is True assert gamma(w).is_real is None def test_issue_8524(): x = Symbol('x', positive=True) y = Symbol('y', negative=True) z = Symbol('z', positive=False) p = Symbol('p', negative=False) q = Symbol('q', integer=True) r = Symbol('r', integer=False) e = Symbol('e', even=True, negative=True) assert gamma(x).is_positive is True assert gamma(y).is_positive is None assert gamma(z).is_positive is None assert gamma(p).is_positive is None assert gamma(q).is_positive is None assert gamma(r).is_positive is None assert gamma(e + S.Half).is_positive is True assert gamma(e - S.Half).is_positive is False def test_issue_14450(): assert uppergamma(Rational(3, 8), x).evalf() == uppergamma(Rational(3, 8), x) assert lowergamma(x, Rational(3, 8)).evalf() == lowergamma(x, Rational(3, 8)) # some values from Wolfram Alpha for comparison assert abs(uppergamma(Rational(3, 8), 2).evalf() - 0.07105675881) < 1e-9 assert abs(lowergamma(Rational(3, 8), 2).evalf() - 2.2993794256) < 1e-9 def test_issue_14528(): k = Symbol('k', integer=True, nonpositive=True) assert isinstance(gamma(k), gamma) def test_multigamma(): from sympy.concrete.products import Product p = Symbol('p') _k = Dummy('_k') assert multigamma(x, p).dummy_eq(pi**(p*(p - 1)/4)*\ Product(gamma(x + (1 - _k)/2), (_k, 1, p))) assert conjugate(multigamma(x, p)).dummy_eq(pi**((conjugate(p) - 1)*\ conjugate(p)/4)*Product(gamma(conjugate(x) + (1-conjugate(_k))/2), (_k, 1, p))) assert conjugate(multigamma(x, 1)) == gamma(conjugate(x)) p = Symbol('p', positive=True) assert conjugate(multigamma(x, p)).dummy_eq(pi**((p - 1)*p/4)*\ Product(gamma(conjugate(x) + (1-conjugate(_k))/2), (_k, 1, p))) assert multigamma(nan, 1) is nan assert multigamma(oo, 1).doit() is oo assert multigamma(1, 1) == 1 assert multigamma(2, 1) == 1 assert multigamma(3, 1) == 2 assert multigamma(102, 1) == factorial(101) assert multigamma(S.Half, 1) == sqrt(pi) assert multigamma(1, 2) == pi assert multigamma(2, 2) == pi/2 assert multigamma(1, 3) is zoo assert multigamma(2, 3) == pi**2/2 assert multigamma(3, 3) == 3*pi**2/2 assert multigamma(x, 1).diff(x) == gamma(x)*polygamma(0, x) assert multigamma(x, 2).diff(x) == sqrt(pi)*gamma(x)*gamma(x - S.Half)*\ polygamma(0, x) + sqrt(pi)*gamma(x)*gamma(x - S.Half)*polygamma(0, x - S.Half) assert multigamma(x - 1, 1).expand(func=True) == gamma(x)/(x - 1) assert multigamma(x + 2, 1).expand(func=True, mul=False) == x*(x + 1)*\ gamma(x) assert multigamma(x - 1, 2).expand(func=True) == sqrt(pi)*gamma(x)*\ gamma(x + S.Half)/(x**3 - 3*x**2 + x*Rational(11, 4) - Rational(3, 4)) assert multigamma(x - 1, 3).expand(func=True) == pi**Rational(3, 2)*gamma(x)**2*\ gamma(x + S.Half)/(x**5 - 6*x**4 + 55*x**3/4 - 15*x**2 + x*Rational(31, 4) - Rational(3, 2)) assert multigamma(n, 1).rewrite(factorial) == factorial(n - 1) assert multigamma(n, 2).rewrite(factorial) == sqrt(pi)*\ factorial(n - Rational(3, 2))*factorial(n - 1) assert multigamma(n, 3).rewrite(factorial) == pi**Rational(3, 2)*\ factorial(n - 2)*factorial(n - Rational(3, 2))*factorial(n - 1) assert multigamma(Rational(-1, 2), 3, evaluate=False).is_real == False assert multigamma(S.Half, 3, evaluate=False).is_real == False assert multigamma(0, 1, evaluate=False).is_real == False assert multigamma(1, 3, evaluate=False).is_real == False assert multigamma(-1.0, 3, evaluate=False).is_real == False assert multigamma(0.7, 3, evaluate=False).is_real == True assert multigamma(3, 3, evaluate=False).is_real == True def test_gamma_as_leading_term(): assert gamma(x).as_leading_term(x) == 1/x assert gamma(2 + x).as_leading_term(x) == S(1) assert gamma(cos(x)).as_leading_term(x) == S(1) assert gamma(sin(x)).as_leading_term(x) == 1/x
e41b29b9183fcbaab8e2f884ecf8420b0766e81bfcdd1ff5cf8f03e792102ccd
from sympy.core.function import (diff, expand, expand_func) from sympy.core import EulerGamma from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import (conjugate, im, polar_lift, re) from sympy.functions.elementary.exponential import (exp, exp_polar, log) from sympy.functions.elementary.hyperbolic import (cosh, sinh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin, sinc) from sympy.functions.special.error_functions import (Chi, Ci, E1, Ei, Li, Shi, Si, erf, erf2, erf2inv, erfc, erfcinv, erfi, erfinv, expint, fresnelc, fresnels, li) from sympy.functions.special.gamma_functions import (gamma, uppergamma) from sympy.functions.special.hyper import (hyper, meijerg) from sympy.integrals.integrals import (Integral, integrate) from sympy.series.gruntz import gruntz from sympy.series.limits import limit from sympy.series.order import O from sympy.core.expr import unchanged from sympy.core.function import ArgumentIndexError from sympy.functions.special.error_functions import _erfs, _eis from sympy.testing.pytest import raises x, y, z = symbols('x,y,z') w = Symbol("w", real=True) n = Symbol("n", integer=True) def test_erf(): assert erf(nan) is nan assert erf(oo) == 1 assert erf(-oo) == -1 assert erf(0) is S.Zero assert erf(I*oo) == oo*I assert erf(-I*oo) == -oo*I assert erf(-2) == -erf(2) assert erf(-x*y) == -erf(x*y) assert erf(-x - y) == -erf(x + y) assert erf(erfinv(x)) == x assert erf(erfcinv(x)) == 1 - x assert erf(erf2inv(0, x)) == x assert erf(erf2inv(0, x, evaluate=False)) == x # To cover code in erf assert erf(erf2inv(0, erf(erfcinv(1 - erf(erfinv(x)))))) == x assert erf(I).is_real is False assert erf(0, evaluate=False).is_real assert erf(0, evaluate=False).is_zero assert conjugate(erf(z)) == erf(conjugate(z)) assert erf(x).as_leading_term(x) == 2*x/sqrt(pi) assert erf(x*y).as_leading_term(y) == 2*x*y/sqrt(pi) assert (erf(x*y)/erf(y)).as_leading_term(y) == x assert erf(1/x).as_leading_term(x) == S.One assert erf(z).rewrite('uppergamma') == sqrt(z**2)*(1 - erfc(sqrt(z**2)))/z assert erf(z).rewrite('erfc') == S.One - erfc(z) assert erf(z).rewrite('erfi') == -I*erfi(I*z) assert erf(z).rewrite('fresnels') == (1 + I)*(fresnelc(z*(1 - I)/sqrt(pi)) - I*fresnels(z*(1 - I)/sqrt(pi))) assert erf(z).rewrite('fresnelc') == (1 + I)*(fresnelc(z*(1 - I)/sqrt(pi)) - I*fresnels(z*(1 - I)/sqrt(pi))) assert erf(z).rewrite('hyper') == 2*z*hyper([S.Half], [3*S.Half], -z**2)/sqrt(pi) assert erf(z).rewrite('meijerg') == z*meijerg([S.Half], [], [0], [Rational(-1, 2)], z**2)/sqrt(pi) assert erf(z).rewrite('expint') == sqrt(z**2)/z - z*expint(S.Half, z**2)/sqrt(S.Pi) assert limit(exp(x)*exp(x**2)*(erf(x + 1/exp(x)) - erf(x)), x, oo) == \ 2/sqrt(pi) assert limit((1 - erf(z))*exp(z**2)*z, z, oo) == 1/sqrt(pi) assert limit((1 - erf(x))*exp(x**2)*sqrt(pi)*x, x, oo) == 1 assert limit(((1 - erf(x))*exp(x**2)*sqrt(pi)*x - 1)*2*x**2, x, oo) == -1 assert limit(erf(x)/x, x, 0) == 2/sqrt(pi) assert limit(x**(-4) - sqrt(pi)*erf(x**2) / (2*x**6), x, 0) == S(1)/3 assert erf(x).as_real_imag() == \ (erf(re(x) - I*im(x))/2 + erf(re(x) + I*im(x))/2, -I*(-erf(re(x) - I*im(x)) + erf(re(x) + I*im(x)))/2) assert erf(x).as_real_imag(deep=False) == \ (erf(re(x) - I*im(x))/2 + erf(re(x) + I*im(x))/2, -I*(-erf(re(x) - I*im(x)) + erf(re(x) + I*im(x)))/2) assert erf(w).as_real_imag() == (erf(w), 0) assert erf(w).as_real_imag(deep=False) == (erf(w), 0) # issue 13575 assert erf(I).as_real_imag() == (0, -I*erf(I)) raises(ArgumentIndexError, lambda: erf(x).fdiff(2)) assert erf(x).inverse() == erfinv def test_erf_series(): assert erf(x).series(x, 0, 7) == 2*x/sqrt(pi) - \ 2*x**3/3/sqrt(pi) + x**5/5/sqrt(pi) + O(x**7) assert erf(x).series(x, oo) == \ -exp(-x**2)*(3/(4*x**5) - 1/(2*x**3) + 1/x + O(x**(-6), (x, oo)))/sqrt(pi) + 1 assert erf(x**2).series(x, oo, n=8) == \ (-1/(2*x**6) + x**(-2) + O(x**(-8), (x, oo)))*exp(-x**4)/sqrt(pi)*-1 + 1 assert erf(sqrt(x)).series(x, oo, n=3) == (sqrt(1/x) - (1/x)**(S(3)/2)/2\ + 3*(1/x)**(S(5)/2)/4 + O(x**(-3), (x, oo)))*exp(-x)/sqrt(pi)*-1 + 1 def test_erf_evalf(): assert abs( erf(Float(2.0)) - 0.995322265 ) < 1E-8 # XXX def test__erfs(): assert _erfs(z).diff(z) == -2/sqrt(S.Pi) + 2*z*_erfs(z) assert _erfs(1/z).series(z) == \ z/sqrt(pi) - z**3/(2*sqrt(pi)) + 3*z**5/(4*sqrt(pi)) + O(z**6) assert expand(erf(z).rewrite('tractable').diff(z).rewrite('intractable')) \ == erf(z).diff(z) assert _erfs(z).rewrite("intractable") == (-erf(z) + 1)*exp(z**2) raises(ArgumentIndexError, lambda: _erfs(z).fdiff(2)) def test_erfc(): assert erfc(nan) is nan assert erfc(oo) is S.Zero assert erfc(-oo) == 2 assert erfc(0) == 1 assert erfc(I*oo) == -oo*I assert erfc(-I*oo) == oo*I assert erfc(-x) == S(2) - erfc(x) assert erfc(erfcinv(x)) == x assert erfc(I).is_real is False assert erfc(0, evaluate=False).is_real assert erfc(0, evaluate=False).is_zero is False assert erfc(erfinv(x)) == 1 - x assert conjugate(erfc(z)) == erfc(conjugate(z)) assert erfc(x).as_leading_term(x) is S.One assert erfc(1/x).as_leading_term(x) == S.Zero assert erfc(z).rewrite('erf') == 1 - erf(z) assert erfc(z).rewrite('erfi') == 1 + I*erfi(I*z) assert erfc(z).rewrite('fresnels') == 1 - (1 + I)*(fresnelc(z*(1 - I)/sqrt(pi)) - I*fresnels(z*(1 - I)/sqrt(pi))) assert erfc(z).rewrite('fresnelc') == 1 - (1 + I)*(fresnelc(z*(1 - I)/sqrt(pi)) - I*fresnels(z*(1 - I)/sqrt(pi))) assert erfc(z).rewrite('hyper') == 1 - 2*z*hyper([S.Half], [3*S.Half], -z**2)/sqrt(pi) assert erfc(z).rewrite('meijerg') == 1 - z*meijerg([S.Half], [], [0], [Rational(-1, 2)], z**2)/sqrt(pi) assert erfc(z).rewrite('uppergamma') == 1 - sqrt(z**2)*(1 - erfc(sqrt(z**2)))/z assert erfc(z).rewrite('expint') == S.One - sqrt(z**2)/z + z*expint(S.Half, z**2)/sqrt(S.Pi) assert erfc(z).rewrite('tractable') == _erfs(z)*exp(-z**2) assert expand_func(erf(x) + erfc(x)) is S.One assert erfc(x).as_real_imag() == \ (erfc(re(x) - I*im(x))/2 + erfc(re(x) + I*im(x))/2, -I*(-erfc(re(x) - I*im(x)) + erfc(re(x) + I*im(x)))/2) assert erfc(x).as_real_imag(deep=False) == \ (erfc(re(x) - I*im(x))/2 + erfc(re(x) + I*im(x))/2, -I*(-erfc(re(x) - I*im(x)) + erfc(re(x) + I*im(x)))/2) assert erfc(w).as_real_imag() == (erfc(w), 0) assert erfc(w).as_real_imag(deep=False) == (erfc(w), 0) raises(ArgumentIndexError, lambda: erfc(x).fdiff(2)) assert erfc(x).inverse() == erfcinv def test_erfc_series(): assert erfc(x).series(x, 0, 7) == 1 - 2*x/sqrt(pi) + \ 2*x**3/3/sqrt(pi) - x**5/5/sqrt(pi) + O(x**7) assert erfc(x).series(x, oo) == \ (3/(4*x**5) - 1/(2*x**3) + 1/x + O(x**(-6), (x, oo)))*exp(-x**2)/sqrt(pi) def test_erfc_evalf(): assert abs( erfc(Float(2.0)) - 0.00467773 ) < 1E-8 # XXX def test_erfi(): assert erfi(nan) is nan assert erfi(oo) is S.Infinity assert erfi(-oo) is S.NegativeInfinity assert erfi(0) is S.Zero assert erfi(I*oo) == I assert erfi(-I*oo) == -I assert erfi(-x) == -erfi(x) assert erfi(I*erfinv(x)) == I*x assert erfi(I*erfcinv(x)) == I*(1 - x) assert erfi(I*erf2inv(0, x)) == I*x assert erfi(I*erf2inv(0, x, evaluate=False)) == I*x # To cover code in erfi assert erfi(I).is_real is False assert erfi(0, evaluate=False).is_real assert erfi(0, evaluate=False).is_zero assert conjugate(erfi(z)) == erfi(conjugate(z)) assert erfi(x).as_leading_term(x) == 2*x/sqrt(pi) assert erfi(x*y).as_leading_term(y) == 2*x*y/sqrt(pi) assert (erfi(x*y)/erfi(y)).as_leading_term(y) == x assert erfi(1/x).as_leading_term(x) == erfi(1/x) assert erfi(z).rewrite('erf') == -I*erf(I*z) assert erfi(z).rewrite('erfc') == I*erfc(I*z) - I assert erfi(z).rewrite('fresnels') == (1 - I)*(fresnelc(z*(1 + I)/sqrt(pi)) - I*fresnels(z*(1 + I)/sqrt(pi))) assert erfi(z).rewrite('fresnelc') == (1 - I)*(fresnelc(z*(1 + I)/sqrt(pi)) - I*fresnels(z*(1 + I)/sqrt(pi))) assert erfi(z).rewrite('hyper') == 2*z*hyper([S.Half], [3*S.Half], z**2)/sqrt(pi) assert erfi(z).rewrite('meijerg') == z*meijerg([S.Half], [], [0], [Rational(-1, 2)], -z**2)/sqrt(pi) assert erfi(z).rewrite('uppergamma') == (sqrt(-z**2)/z*(uppergamma(S.Half, -z**2)/sqrt(S.Pi) - S.One)) assert erfi(z).rewrite('expint') == sqrt(-z**2)/z - z*expint(S.Half, -z**2)/sqrt(S.Pi) assert erfi(z).rewrite('tractable') == -I*(-_erfs(I*z)*exp(z**2) + 1) assert expand_func(erfi(I*z)) == I*erf(z) assert erfi(x).as_real_imag() == \ (erfi(re(x) - I*im(x))/2 + erfi(re(x) + I*im(x))/2, -I*(-erfi(re(x) - I*im(x)) + erfi(re(x) + I*im(x)))/2) assert erfi(x).as_real_imag(deep=False) == \ (erfi(re(x) - I*im(x))/2 + erfi(re(x) + I*im(x))/2, -I*(-erfi(re(x) - I*im(x)) + erfi(re(x) + I*im(x)))/2) assert erfi(w).as_real_imag() == (erfi(w), 0) assert erfi(w).as_real_imag(deep=False) == (erfi(w), 0) raises(ArgumentIndexError, lambda: erfi(x).fdiff(2)) def test_erfi_series(): assert erfi(x).series(x, 0, 7) == 2*x/sqrt(pi) + \ 2*x**3/3/sqrt(pi) + x**5/5/sqrt(pi) + O(x**7) assert erfi(x).series(x, oo) == \ (3/(4*x**5) + 1/(2*x**3) + 1/x + O(x**(-6), (x, oo)))*exp(x**2)/sqrt(pi) - I def test_erfi_evalf(): assert abs( erfi(Float(2.0)) - 18.5648024145756 ) < 1E-13 # XXX def test_erf2(): assert erf2(0, 0) is S.Zero assert erf2(x, x) is S.Zero assert erf2(nan, 0) is nan assert erf2(-oo, y) == erf(y) + 1 assert erf2( oo, y) == erf(y) - 1 assert erf2( x, oo) == 1 - erf(x) assert erf2( x,-oo) == -1 - erf(x) assert erf2(x, erf2inv(x, y)) == y assert erf2(-x, -y) == -erf2(x,y) assert erf2(-x, y) == erf(y) + erf(x) assert erf2( x, -y) == -erf(y) - erf(x) assert erf2(x, y).rewrite('fresnels') == erf(y).rewrite(fresnels)-erf(x).rewrite(fresnels) assert erf2(x, y).rewrite('fresnelc') == erf(y).rewrite(fresnelc)-erf(x).rewrite(fresnelc) assert erf2(x, y).rewrite('hyper') == erf(y).rewrite(hyper)-erf(x).rewrite(hyper) assert erf2(x, y).rewrite('meijerg') == erf(y).rewrite(meijerg)-erf(x).rewrite(meijerg) assert erf2(x, y).rewrite('uppergamma') == erf(y).rewrite(uppergamma) - erf(x).rewrite(uppergamma) assert erf2(x, y).rewrite('expint') == erf(y).rewrite(expint)-erf(x).rewrite(expint) assert erf2(I, 0).is_real is False assert erf2(0, 0, evaluate=False).is_real assert erf2(0, 0, evaluate=False).is_zero assert erf2(x, x, evaluate=False).is_zero assert erf2(x, y).is_zero is None assert expand_func(erf(x) + erf2(x, y)) == erf(y) assert conjugate(erf2(x, y)) == erf2(conjugate(x), conjugate(y)) assert erf2(x, y).rewrite('erf') == erf(y) - erf(x) assert erf2(x, y).rewrite('erfc') == erfc(x) - erfc(y) assert erf2(x, y).rewrite('erfi') == I*(erfi(I*x) - erfi(I*y)) assert erf2(x, y).diff(x) == erf2(x, y).fdiff(1) assert erf2(x, y).diff(y) == erf2(x, y).fdiff(2) assert erf2(x, y).diff(x) == -2*exp(-x**2)/sqrt(pi) assert erf2(x, y).diff(y) == 2*exp(-y**2)/sqrt(pi) raises(ArgumentIndexError, lambda: erf2(x, y).fdiff(3)) assert erf2(x, y).is_extended_real is None xr, yr = symbols('xr yr', extended_real=True) assert erf2(xr, yr).is_extended_real is True def test_erfinv(): assert erfinv(0) is S.Zero assert erfinv(1) is S.Infinity assert erfinv(nan) is S.NaN assert erfinv(-1) is S.NegativeInfinity assert erfinv(erf(w)) == w assert erfinv(erf(-w)) == -w assert erfinv(x).diff() == sqrt(pi)*exp(erfinv(x)**2)/2 raises(ArgumentIndexError, lambda: erfinv(x).fdiff(2)) assert erfinv(z).rewrite('erfcinv') == erfcinv(1-z) assert erfinv(z).inverse() == erf def test_erfinv_evalf(): assert abs( erfinv(Float(0.2)) - 0.179143454621292 ) < 1E-13 def test_erfcinv(): assert erfcinv(1) is S.Zero assert erfcinv(0) is S.Infinity assert erfcinv(nan) is S.NaN assert erfcinv(x).diff() == -sqrt(pi)*exp(erfcinv(x)**2)/2 raises(ArgumentIndexError, lambda: erfcinv(x).fdiff(2)) assert erfcinv(z).rewrite('erfinv') == erfinv(1-z) assert erfcinv(z).inverse() == erfc def test_erf2inv(): assert erf2inv(0, 0) is S.Zero assert erf2inv(0, 1) is S.Infinity assert erf2inv(1, 0) is S.One assert erf2inv(0, y) == erfinv(y) assert erf2inv(oo, y) == erfcinv(-y) assert erf2inv(x, 0) == x assert erf2inv(x, oo) == erfinv(x) assert erf2inv(nan, 0) is nan assert erf2inv(0, nan) is nan assert erf2inv(x, y).diff(x) == exp(-x**2 + erf2inv(x, y)**2) assert erf2inv(x, y).diff(y) == sqrt(pi)*exp(erf2inv(x, y)**2)/2 raises(ArgumentIndexError, lambda: erf2inv(x, y).fdiff(3)) # NOTE we multiply by exp_polar(I*pi) and need this to be on the principal # branch, hence take x in the lower half plane (d=0). def mytn(expr1, expr2, expr3, x, d=0): from sympy.core.random import verify_numerically, random_complex_number subs = {} for a in expr1.free_symbols: if a != x: subs[a] = random_complex_number() return expr2 == expr3 and verify_numerically(expr1.subs(subs), expr2.subs(subs), x, d=d) def mytd(expr1, expr2, x): from sympy.core.random import test_derivative_numerically, \ random_complex_number subs = {} for a in expr1.free_symbols: if a != x: subs[a] = random_complex_number() return expr1.diff(x) == expr2 and test_derivative_numerically(expr1.subs(subs), x) def tn_branch(func, s=None): from sympy.core.random import uniform def fn(x): if s is None: return func(x) return func(s, x) c = uniform(1, 5) expr = fn(c*exp_polar(I*pi)) - fn(c*exp_polar(-I*pi)) eps = 1e-15 expr2 = fn(-c + eps*I) - fn(-c - eps*I) return abs(expr.n() - expr2.n()).n() < 1e-10 def test_ei(): assert Ei(0) is S.NegativeInfinity assert Ei(oo) is S.Infinity assert Ei(-oo) is S.Zero assert tn_branch(Ei) assert mytd(Ei(x), exp(x)/x, x) assert mytn(Ei(x), Ei(x).rewrite(uppergamma), -uppergamma(0, x*polar_lift(-1)) - I*pi, x) assert mytn(Ei(x), Ei(x).rewrite(expint), -expint(1, x*polar_lift(-1)) - I*pi, x) assert Ei(x).rewrite(expint).rewrite(Ei) == Ei(x) assert Ei(x*exp_polar(2*I*pi)) == Ei(x) + 2*I*pi assert Ei(x*exp_polar(-2*I*pi)) == Ei(x) - 2*I*pi assert mytn(Ei(x), Ei(x).rewrite(Shi), Chi(x) + Shi(x), x) assert mytn(Ei(x*polar_lift(I)), Ei(x*polar_lift(I)).rewrite(Si), Ci(x) + I*Si(x) + I*pi/2, x) assert Ei(log(x)).rewrite(li) == li(x) assert Ei(2*log(x)).rewrite(li) == li(x**2) assert gruntz(Ei(x+exp(-x))*exp(-x)*x, x, oo) == 1 assert Ei(x).series(x) == EulerGamma + log(x) + x + x**2/4 + \ x**3/18 + x**4/96 + x**5/600 + O(x**6) assert Ei(x).series(x, 1, 3) == Ei(1) + E*(x - 1) + O((x - 1)**3, (x, 1)) assert Ei(x).series(x, oo) == \ (120/x**5 + 24/x**4 + 6/x**3 + 2/x**2 + 1/x + 1 + O(x**(-6), (x, oo)))*exp(x)/x assert str(Ei(cos(2)).evalf(n=10)) == '-0.6760647401' raises(ArgumentIndexError, lambda: Ei(x).fdiff(2)) def test_expint(): assert mytn(expint(x, y), expint(x, y).rewrite(uppergamma), y**(x - 1)*uppergamma(1 - x, y), x) assert mytd( expint(x, y), -y**(x - 1)*meijerg([], [1, 1], [0, 0, 1 - x], [], y), x) assert mytd(expint(x, y), -expint(x - 1, y), y) assert mytn(expint(1, x), expint(1, x).rewrite(Ei), -Ei(x*polar_lift(-1)) + I*pi, x) assert expint(-4, x) == exp(-x)/x + 4*exp(-x)/x**2 + 12*exp(-x)/x**3 \ + 24*exp(-x)/x**4 + 24*exp(-x)/x**5 assert expint(Rational(-3, 2), x) == \ exp(-x)/x + 3*exp(-x)/(2*x**2) + 3*sqrt(pi)*erfc(sqrt(x))/(4*x**S('5/2')) assert tn_branch(expint, 1) assert tn_branch(expint, 2) assert tn_branch(expint, 3) assert tn_branch(expint, 1.7) assert tn_branch(expint, pi) assert expint(y, x*exp_polar(2*I*pi)) == \ x**(y - 1)*(exp(2*I*pi*y) - 1)*gamma(-y + 1) + expint(y, x) assert expint(y, x*exp_polar(-2*I*pi)) == \ x**(y - 1)*(exp(-2*I*pi*y) - 1)*gamma(-y + 1) + expint(y, x) assert expint(2, x*exp_polar(2*I*pi)) == 2*I*pi*x + expint(2, x) assert expint(2, x*exp_polar(-2*I*pi)) == -2*I*pi*x + expint(2, x) assert expint(1, x).rewrite(Ei).rewrite(expint) == expint(1, x) assert expint(x, y).rewrite(Ei) == expint(x, y) assert expint(x, y).rewrite(Ci) == expint(x, y) assert mytn(E1(x), E1(x).rewrite(Shi), Shi(x) - Chi(x), x) assert mytn(E1(polar_lift(I)*x), E1(polar_lift(I)*x).rewrite(Si), -Ci(x) + I*Si(x) - I*pi/2, x) assert mytn(expint(2, x), expint(2, x).rewrite(Ei).rewrite(expint), -x*E1(x) + exp(-x), x) assert mytn(expint(3, x), expint(3, x).rewrite(Ei).rewrite(expint), x**2*E1(x)/2 + (1 - x)*exp(-x)/2, x) assert expint(Rational(3, 2), z).nseries(z) == \ 2 + 2*z - z**2/3 + z**3/15 - z**4/84 + z**5/540 - \ 2*sqrt(pi)*sqrt(z) + O(z**6) assert E1(z).series(z) == -EulerGamma - log(z) + z - \ z**2/4 + z**3/18 - z**4/96 + z**5/600 + O(z**6) assert expint(4, z).series(z) == Rational(1, 3) - z/2 + z**2/2 + \ z**3*(log(z)/6 - Rational(11, 36) + EulerGamma/6 - I*pi/6) - z**4/24 + \ z**5/240 + O(z**6) assert expint(n, x).series(x, oo, n=3) == \ (n*(n + 1)/x**2 - n/x + 1 + O(x**(-3), (x, oo)))*exp(-x)/x assert expint(z, y).series(z, 0, 2) == exp(-y)/y - z*meijerg(((), (1, 1)), ((0, 0, 1), ()), y)/y + O(z**2) raises(ArgumentIndexError, lambda: expint(x, y).fdiff(3)) neg = Symbol('neg', negative=True) assert Ei(neg).rewrite(Si) == Shi(neg) + Chi(neg) - I*pi def test__eis(): assert _eis(z).diff(z) == -_eis(z) + 1/z assert _eis(1/z).series(z) == \ z + z**2 + 2*z**3 + 6*z**4 + 24*z**5 + O(z**6) assert Ei(z).rewrite('tractable') == exp(z)*_eis(z) assert li(z).rewrite('tractable') == z*_eis(log(z)) assert _eis(z).rewrite('intractable') == exp(-z)*Ei(z) assert expand(li(z).rewrite('tractable').diff(z).rewrite('intractable')) \ == li(z).diff(z) assert expand(Ei(z).rewrite('tractable').diff(z).rewrite('intractable')) \ == Ei(z).diff(z) assert _eis(z).series(z, n=3) == EulerGamma + log(z) + z*(-log(z) - \ EulerGamma + 1) + z**2*(log(z)/2 - Rational(3, 4) + EulerGamma/2)\ + O(z**3*log(z)) raises(ArgumentIndexError, lambda: _eis(z).fdiff(2)) def tn_arg(func): def test(arg, e1, e2): from sympy.core.random import uniform v = uniform(1, 5) v1 = func(arg*x).subs(x, v).n() v2 = func(e1*v + e2*1e-15).n() return abs(v1 - v2).n() < 1e-10 return test(exp_polar(I*pi/2), I, 1) and \ test(exp_polar(-I*pi/2), -I, 1) and \ test(exp_polar(I*pi), -1, I) and \ test(exp_polar(-I*pi), -1, -I) def test_li(): z = Symbol("z") zr = Symbol("z", real=True) zp = Symbol("z", positive=True) zn = Symbol("z", negative=True) assert li(0) is S.Zero assert li(1) is -oo assert li(oo) is oo assert isinstance(li(z), li) assert unchanged(li, -zp) assert unchanged(li, zn) assert diff(li(z), z) == 1/log(z) assert conjugate(li(z)) == li(conjugate(z)) assert conjugate(li(-zr)) == li(-zr) assert unchanged(conjugate, li(-zp)) assert unchanged(conjugate, li(zn)) assert li(z).rewrite(Li) == Li(z) + li(2) assert li(z).rewrite(Ei) == Ei(log(z)) assert li(z).rewrite(uppergamma) == (-log(1/log(z))/2 - log(-log(z)) + log(log(z))/2 - expint(1, -log(z))) assert li(z).rewrite(Si) == (-log(I*log(z)) - log(1/log(z))/2 + log(log(z))/2 + Ci(I*log(z)) + Shi(log(z))) assert li(z).rewrite(Ci) == (-log(I*log(z)) - log(1/log(z))/2 + log(log(z))/2 + Ci(I*log(z)) + Shi(log(z))) assert li(z).rewrite(Shi) == (-log(1/log(z))/2 + log(log(z))/2 + Chi(log(z)) - Shi(log(z))) assert li(z).rewrite(Chi) == (-log(1/log(z))/2 + log(log(z))/2 + Chi(log(z)) - Shi(log(z))) assert li(z).rewrite(hyper) ==(log(z)*hyper((1, 1), (2, 2), log(z)) - log(1/log(z))/2 + log(log(z))/2 + EulerGamma) assert li(z).rewrite(meijerg) == (-log(1/log(z))/2 - log(-log(z)) + log(log(z))/2 - meijerg(((), (1,)), ((0, 0), ()), -log(z))) assert gruntz(1/li(z), z, oo) is S.Zero assert li(z).series(z) == log(z)**5/600 + log(z)**4/96 + log(z)**3/18 + log(z)**2/4 + \ log(z) + log(log(z)) + EulerGamma raises(ArgumentIndexError, lambda: li(z).fdiff(2)) def test_Li(): assert Li(2) is S.Zero assert Li(oo) is oo assert isinstance(Li(z), Li) assert diff(Li(z), z) == 1/log(z) assert gruntz(1/Li(z), z, oo) is S.Zero assert Li(z).rewrite(li) == li(z) - li(2) assert Li(z).series(z) == \ log(z)**5/600 + log(z)**4/96 + log(z)**3/18 + log(z)**2/4 + log(z) + log(log(z)) - li(2) + EulerGamma raises(ArgumentIndexError, lambda: Li(z).fdiff(2)) def test_si(): assert Si(I*x) == I*Shi(x) assert Shi(I*x) == I*Si(x) assert Si(-I*x) == -I*Shi(x) assert Shi(-I*x) == -I*Si(x) assert Si(-x) == -Si(x) assert Shi(-x) == -Shi(x) assert Si(exp_polar(2*pi*I)*x) == Si(x) assert Si(exp_polar(-2*pi*I)*x) == Si(x) assert Shi(exp_polar(2*pi*I)*x) == Shi(x) assert Shi(exp_polar(-2*pi*I)*x) == Shi(x) assert Si(oo) == pi/2 assert Si(-oo) == -pi/2 assert Shi(oo) is oo assert Shi(-oo) is -oo assert mytd(Si(x), sin(x)/x, x) assert mytd(Shi(x), sinh(x)/x, x) assert mytn(Si(x), Si(x).rewrite(Ei), -I*(-Ei(x*exp_polar(-I*pi/2))/2 + Ei(x*exp_polar(I*pi/2))/2 - I*pi) + pi/2, x) assert mytn(Si(x), Si(x).rewrite(expint), -I*(-expint(1, x*exp_polar(-I*pi/2))/2 + expint(1, x*exp_polar(I*pi/2))/2) + pi/2, x) assert mytn(Shi(x), Shi(x).rewrite(Ei), Ei(x)/2 - Ei(x*exp_polar(I*pi))/2 + I*pi/2, x) assert mytn(Shi(x), Shi(x).rewrite(expint), expint(1, x)/2 - expint(1, x*exp_polar(I*pi))/2 - I*pi/2, x) assert tn_arg(Si) assert tn_arg(Shi) assert Si(x).nseries(x, n=8) == \ x - x**3/18 + x**5/600 - x**7/35280 + O(x**9) assert Shi(x).nseries(x, n=8) == \ x + x**3/18 + x**5/600 + x**7/35280 + O(x**9) assert Si(sin(x)).nseries(x, n=5) == x - 2*x**3/9 + 17*x**5/450 + O(x**6) assert Si(x).nseries(x, 1, n=3) == \ Si(1) + (x - 1)*sin(1) + (x - 1)**2*(-sin(1)/2 + cos(1)/2) + O((x - 1)**3, (x, 1)) assert Si(x).series(x, oo) == pi/2 - (- 6/x**3 + 1/x \ + O(x**(-7), (x, oo)))*sin(x)/x - (24/x**4 - 2/x**2 + 1 \ + O(x**(-7), (x, oo)))*cos(x)/x t = Symbol('t', Dummy=True) assert Si(x).rewrite(sinc) == Integral(sinc(t), (t, 0, x)) assert limit(Shi(x), x, S.NegativeInfinity) == -I*pi/2 def test_ci(): m1 = exp_polar(I*pi) m1_ = exp_polar(-I*pi) pI = exp_polar(I*pi/2) mI = exp_polar(-I*pi/2) assert Ci(m1*x) == Ci(x) + I*pi assert Ci(m1_*x) == Ci(x) - I*pi assert Ci(pI*x) == Chi(x) + I*pi/2 assert Ci(mI*x) == Chi(x) - I*pi/2 assert Chi(m1*x) == Chi(x) + I*pi assert Chi(m1_*x) == Chi(x) - I*pi assert Chi(pI*x) == Ci(x) + I*pi/2 assert Chi(mI*x) == Ci(x) - I*pi/2 assert Ci(exp_polar(2*I*pi)*x) == Ci(x) + 2*I*pi assert Chi(exp_polar(-2*I*pi)*x) == Chi(x) - 2*I*pi assert Chi(exp_polar(2*I*pi)*x) == Chi(x) + 2*I*pi assert Ci(exp_polar(-2*I*pi)*x) == Ci(x) - 2*I*pi assert Ci(oo) is S.Zero assert Ci(-oo) == I*pi assert Chi(oo) is oo assert Chi(-oo) is oo assert mytd(Ci(x), cos(x)/x, x) assert mytd(Chi(x), cosh(x)/x, x) assert mytn(Ci(x), Ci(x).rewrite(Ei), Ei(x*exp_polar(-I*pi/2))/2 + Ei(x*exp_polar(I*pi/2))/2, x) assert mytn(Chi(x), Chi(x).rewrite(Ei), Ei(x)/2 + Ei(x*exp_polar(I*pi))/2 - I*pi/2, x) assert tn_arg(Ci) assert tn_arg(Chi) assert Ci(x).nseries(x, n=4) == \ EulerGamma + log(x) - x**2/4 + x**4/96 + O(x**5) assert Chi(x).nseries(x, n=4) == \ EulerGamma + log(x) + x**2/4 + x**4/96 + O(x**5) assert Ci(x).series(x, oo) == -cos(x)*(-6/x**3 + 1/x \ + O(x**(-7), (x, oo)))/x + (24/x**4 - 2/x**2 + 1 \ + O(x**(-7), (x, oo)))*sin(x)/x assert limit(log(x) - Ci(2*x), x, 0) == -log(2) - EulerGamma assert Ci(x).rewrite(uppergamma) == -expint(1, x*exp_polar(-I*pi/2))/2 -\ expint(1, x*exp_polar(I*pi/2))/2 assert Ci(x).rewrite(expint) == -expint(1, x*exp_polar(-I*pi/2))/2 -\ expint(1, x*exp_polar(I*pi/2))/2 raises(ArgumentIndexError, lambda: Ci(x).fdiff(2)) def test_fresnel(): assert fresnels(0) is S.Zero assert fresnels(oo) is S.Half assert fresnels(-oo) == Rational(-1, 2) assert fresnels(I*oo) == -I*S.Half assert unchanged(fresnels, z) assert fresnels(-z) == -fresnels(z) assert fresnels(I*z) == -I*fresnels(z) assert fresnels(-I*z) == I*fresnels(z) assert conjugate(fresnels(z)) == fresnels(conjugate(z)) assert fresnels(z).diff(z) == sin(pi*z**2/2) assert fresnels(z).rewrite(erf) == (S.One + I)/4 * ( erf((S.One + I)/2*sqrt(pi)*z) - I*erf((S.One - I)/2*sqrt(pi)*z)) assert fresnels(z).rewrite(hyper) == \ pi*z**3/6 * hyper([Rational(3, 4)], [Rational(3, 2), Rational(7, 4)], -pi**2*z**4/16) assert fresnels(z).series(z, n=15) == \ pi*z**3/6 - pi**3*z**7/336 + pi**5*z**11/42240 + O(z**15) assert fresnels(w).is_extended_real is True assert fresnels(w).is_finite is True assert fresnels(z).is_extended_real is None assert fresnels(z).is_finite is None assert fresnels(z).as_real_imag() == (fresnels(re(z) - I*im(z))/2 + fresnels(re(z) + I*im(z))/2, -I*(-fresnels(re(z) - I*im(z)) + fresnels(re(z) + I*im(z)))/2) assert fresnels(z).as_real_imag(deep=False) == (fresnels(re(z) - I*im(z))/2 + fresnels(re(z) + I*im(z))/2, -I*(-fresnels(re(z) - I*im(z)) + fresnels(re(z) + I*im(z)))/2) assert fresnels(w).as_real_imag() == (fresnels(w), 0) assert fresnels(w).as_real_imag(deep=True) == (fresnels(w), 0) assert fresnels(2 + 3*I).as_real_imag() == ( fresnels(2 + 3*I)/2 + fresnels(2 - 3*I)/2, -I*(fresnels(2 + 3*I) - fresnels(2 - 3*I))/2 ) assert expand_func(integrate(fresnels(z), z)) == \ z*fresnels(z) + cos(pi*z**2/2)/pi assert fresnels(z).rewrite(meijerg) == sqrt(2)*pi*z**Rational(9, 4) * \ meijerg(((), (1,)), ((Rational(3, 4),), (Rational(1, 4), 0)), -pi**2*z**4/16)/(2*(-z)**Rational(3, 4)*(z**2)**Rational(3, 4)) assert fresnelc(0) is S.Zero assert fresnelc(oo) == S.Half assert fresnelc(-oo) == Rational(-1, 2) assert fresnelc(I*oo) == I*S.Half assert unchanged(fresnelc, z) assert fresnelc(-z) == -fresnelc(z) assert fresnelc(I*z) == I*fresnelc(z) assert fresnelc(-I*z) == -I*fresnelc(z) assert conjugate(fresnelc(z)) == fresnelc(conjugate(z)) assert fresnelc(z).diff(z) == cos(pi*z**2/2) assert fresnelc(z).rewrite(erf) == (S.One - I)/4 * ( erf((S.One + I)/2*sqrt(pi)*z) + I*erf((S.One - I)/2*sqrt(pi)*z)) assert fresnelc(z).rewrite(hyper) == \ z * hyper([Rational(1, 4)], [S.Half, Rational(5, 4)], -pi**2*z**4/16) assert fresnelc(w).is_extended_real is True assert fresnelc(z).as_real_imag() == \ (fresnelc(re(z) - I*im(z))/2 + fresnelc(re(z) + I*im(z))/2, -I*(-fresnelc(re(z) - I*im(z)) + fresnelc(re(z) + I*im(z)))/2) assert fresnelc(z).as_real_imag(deep=False) == \ (fresnelc(re(z) - I*im(z))/2 + fresnelc(re(z) + I*im(z))/2, -I*(-fresnelc(re(z) - I*im(z)) + fresnelc(re(z) + I*im(z)))/2) assert fresnelc(2 + 3*I).as_real_imag() == ( fresnelc(2 - 3*I)/2 + fresnelc(2 + 3*I)/2, -I*(fresnelc(2 + 3*I) - fresnelc(2 - 3*I))/2 ) assert expand_func(integrate(fresnelc(z), z)) == \ z*fresnelc(z) - sin(pi*z**2/2)/pi assert fresnelc(z).rewrite(meijerg) == sqrt(2)*pi*z**Rational(3, 4) * \ meijerg(((), (1,)), ((Rational(1, 4),), (Rational(3, 4), 0)), -pi**2*z**4/16)/(2*(-z)**Rational(1, 4)*(z**2)**Rational(1, 4)) from sympy.core.random import verify_numerically verify_numerically(re(fresnels(z)), fresnels(z).as_real_imag()[0], z) verify_numerically(im(fresnels(z)), fresnels(z).as_real_imag()[1], z) verify_numerically(fresnels(z), fresnels(z).rewrite(hyper), z) verify_numerically(fresnels(z), fresnels(z).rewrite(meijerg), z) verify_numerically(re(fresnelc(z)), fresnelc(z).as_real_imag()[0], z) verify_numerically(im(fresnelc(z)), fresnelc(z).as_real_imag()[1], z) verify_numerically(fresnelc(z), fresnelc(z).rewrite(hyper), z) verify_numerically(fresnelc(z), fresnelc(z).rewrite(meijerg), z) raises(ArgumentIndexError, lambda: fresnels(z).fdiff(2)) raises(ArgumentIndexError, lambda: fresnelc(z).fdiff(2)) assert fresnels(x).taylor_term(-1, x) is S.Zero assert fresnelc(x).taylor_term(-1, x) is S.Zero assert fresnelc(x).taylor_term(1, x) == -pi**2*x**5/40 def test_fresnel_series(): assert fresnelc(z).series(z, n=15) == \ z - pi**2*z**5/40 + pi**4*z**9/3456 - pi**6*z**13/599040 + O(z**15) # issues 6510, 10102 fs = (S.Half - sin(pi*z**2/2)/(pi**2*z**3) + (-1/(pi*z) + 3/(pi**3*z**5))*cos(pi*z**2/2)) fc = (S.Half - cos(pi*z**2/2)/(pi**2*z**3) + (1/(pi*z) - 3/(pi**3*z**5))*sin(pi*z**2/2)) assert fresnels(z).series(z, oo) == fs + O(z**(-6), (z, oo)) assert fresnelc(z).series(z, oo) == fc + O(z**(-6), (z, oo)) assert (fresnels(z).series(z, -oo) + fs.subs(z, -z)).expand().is_Order assert (fresnelc(z).series(z, -oo) + fc.subs(z, -z)).expand().is_Order assert (fresnels(1/z).series(z) - fs.subs(z, 1/z)).expand().is_Order assert (fresnelc(1/z).series(z) - fc.subs(z, 1/z)).expand().is_Order assert ((2*fresnels(3*z)).series(z, oo) - 2*fs.subs(z, 3*z)).expand().is_Order assert ((3*fresnelc(2*z)).series(z, oo) - 3*fc.subs(z, 2*z)).expand().is_Order
952ac802db94e1f1e599ef6b88381e421c3fafccb744e20c5cd71d42484e30c4
r""" This module contains :py:meth:`~sympy.solvers.ode.dsolve` and different helper functions that it uses. :py:meth:`~sympy.solvers.ode.dsolve` solves ordinary differential equations. See the docstring on the various functions for their uses. Note that partial differential equations support is in ``pde.py``. Note that hint functions have docstrings describing their various methods, but they are intended for internal use. Use ``dsolve(ode, func, hint=hint)`` to solve an ODE using a specific hint. See also the docstring on :py:meth:`~sympy.solvers.ode.dsolve`. **Functions in this module** These are the user functions in this module: - :py:meth:`~sympy.solvers.ode.dsolve` - Solves ODEs. - :py:meth:`~sympy.solvers.ode.classify_ode` - Classifies ODEs into possible hints for :py:meth:`~sympy.solvers.ode.dsolve`. - :py:meth:`~sympy.solvers.ode.checkodesol` - Checks if an equation is the solution to an ODE. - :py:meth:`~sympy.solvers.ode.homogeneous_order` - Returns the homogeneous order of an expression. - :py:meth:`~sympy.solvers.ode.infinitesimals` - Returns the infinitesimals of the Lie group of point transformations of an ODE, such that it is invariant. - :py:meth:`~sympy.solvers.ode.checkinfsol` - Checks if the given infinitesimals are the actual infinitesimals of a first order ODE. These are the non-solver helper functions that are for internal use. The user should use the various options to :py:meth:`~sympy.solvers.ode.dsolve` to obtain the functionality provided by these functions: - :py:meth:`~sympy.solvers.ode.ode.odesimp` - Does all forms of ODE simplification. - :py:meth:`~sympy.solvers.ode.ode.ode_sol_simplicity` - A key function for comparing solutions by simplicity. - :py:meth:`~sympy.solvers.ode.constantsimp` - Simplifies arbitrary constants. - :py:meth:`~sympy.solvers.ode.ode.constant_renumber` - Renumber arbitrary constants. - :py:meth:`~sympy.solvers.ode.ode._handle_Integral` - Evaluate unevaluated Integrals. See also the docstrings of these functions. **Currently implemented solver methods** The following methods are implemented for solving ordinary differential equations. See the docstrings of the various hint functions for more information on each (run ``help(ode)``): - 1st order separable differential equations. - 1st order differential equations whose coefficients or `dx` and `dy` are functions homogeneous of the same order. - 1st order exact differential equations. - 1st order linear differential equations. - 1st order Bernoulli differential equations. - Power series solutions for first order differential equations. - Lie Group method of solving first order differential equations. - 2nd order Liouville differential equations. - Power series solutions for second order differential equations at ordinary and regular singular points. - `n`\th order differential equation that can be solved with algebraic rearrangement and integration. - `n`\th order linear homogeneous differential equation with constant coefficients. - `n`\th order linear inhomogeneous differential equation with constant coefficients using the method of undetermined coefficients. - `n`\th order linear inhomogeneous differential equation with constant coefficients using the method of variation of parameters. **Philosophy behind this module** This module is designed to make it easy to add new ODE solving methods without having to mess with the solving code for other methods. The idea is that there is a :py:meth:`~sympy.solvers.ode.classify_ode` function, which takes in an ODE and tells you what hints, if any, will solve the ODE. It does this without attempting to solve the ODE, so it is fast. Each solving method is a hint, and it has its own function, named ``ode_<hint>``. That function takes in the ODE and any match expression gathered by :py:meth:`~sympy.solvers.ode.classify_ode` and returns a solved result. If this result has any integrals in it, the hint function will return an unevaluated :py:class:`~sympy.integrals.integrals.Integral` class. :py:meth:`~sympy.solvers.ode.dsolve`, which is the user wrapper function around all of this, will then call :py:meth:`~sympy.solvers.ode.ode.odesimp` on the result, which, among other things, will attempt to solve the equation for the dependent variable (the function we are solving for), simplify the arbitrary constants in the expression, and evaluate any integrals, if the hint allows it. **How to add new solution methods** If you have an ODE that you want :py:meth:`~sympy.solvers.ode.dsolve` to be able to solve, try to avoid adding special case code here. Instead, try finding a general method that will solve your ODE, as well as others. This way, the :py:mod:`~sympy.solvers.ode` module will become more robust, and unhindered by special case hacks. WolphramAlpha and Maple's DETools[odeadvisor] function are two resources you can use to classify a specific ODE. It is also better for a method to work with an `n`\th order ODE instead of only with specific orders, if possible. To add a new method, there are a few things that you need to do. First, you need a hint name for your method. Try to name your hint so that it is unambiguous with all other methods, including ones that may not be implemented yet. If your method uses integrals, also include a ``hint_Integral`` hint. If there is more than one way to solve ODEs with your method, include a hint for each one, as well as a ``<hint>_best`` hint. Your ``ode_<hint>_best()`` function should choose the best using min with ``ode_sol_simplicity`` as the key argument. See :obj:`~sympy.solvers.ode.single.HomogeneousCoeffBest`, for example. The function that uses your method will be called ``ode_<hint>()``, so the hint must only use characters that are allowed in a Python function name (alphanumeric characters and the underscore '``_``' character). Include a function for every hint, except for ``_Integral`` hints (:py:meth:`~sympy.solvers.ode.dsolve` takes care of those automatically). Hint names should be all lowercase, unless a word is commonly capitalized (such as Integral or Bernoulli). If you have a hint that you do not want to run with ``all_Integral`` that doesn't have an ``_Integral`` counterpart (such as a best hint that would defeat the purpose of ``all_Integral``), you will need to remove it manually in the :py:meth:`~sympy.solvers.ode.dsolve` code. See also the :py:meth:`~sympy.solvers.ode.classify_ode` docstring for guidelines on writing a hint name. Determine *in general* how the solutions returned by your method compare with other methods that can potentially solve the same ODEs. Then, put your hints in the :py:data:`~sympy.solvers.ode.allhints` tuple in the order that they should be called. The ordering of this tuple determines which hints are default. Note that exceptions are ok, because it is easy for the user to choose individual hints with :py:meth:`~sympy.solvers.ode.dsolve`. In general, ``_Integral`` variants should go at the end of the list, and ``_best`` variants should go before the various hints they apply to. For example, the ``undetermined_coefficients`` hint comes before the ``variation_of_parameters`` hint because, even though variation of parameters is more general than undetermined coefficients, undetermined coefficients generally returns cleaner results for the ODEs that it can solve than variation of parameters does, and it does not require integration, so it is much faster. Next, you need to have a match expression or a function that matches the type of the ODE, which you should put in :py:meth:`~sympy.solvers.ode.classify_ode` (if the match function is more than just a few lines. It should match the ODE without solving for it as much as possible, so that :py:meth:`~sympy.solvers.ode.classify_ode` remains fast and is not hindered by bugs in solving code. Be sure to consider corner cases. For example, if your solution method involves dividing by something, make sure you exclude the case where that division will be 0. In most cases, the matching of the ODE will also give you the various parts that you need to solve it. You should put that in a dictionary (``.match()`` will do this for you), and add that as ``matching_hints['hint'] = matchdict`` in the relevant part of :py:meth:`~sympy.solvers.ode.classify_ode`. :py:meth:`~sympy.solvers.ode.classify_ode` will then send this to :py:meth:`~sympy.solvers.ode.dsolve`, which will send it to your function as the ``match`` argument. Your function should be named ``ode_<hint>(eq, func, order, match)`. If you need to send more information, put it in the ``match`` dictionary. For example, if you had to substitute in a dummy variable in :py:meth:`~sympy.solvers.ode.classify_ode` to match the ODE, you will need to pass it to your function using the `match` dict to access it. You can access the independent variable using ``func.args[0]``, and the dependent variable (the function you are trying to solve for) as ``func.func``. If, while trying to solve the ODE, you find that you cannot, raise ``NotImplementedError``. :py:meth:`~sympy.solvers.ode.dsolve` will catch this error with the ``all`` meta-hint, rather than causing the whole routine to fail. Add a docstring to your function that describes the method employed. Like with anything else in SymPy, you will need to add a doctest to the docstring, in addition to real tests in ``test_ode.py``. Try to maintain consistency with the other hint functions' docstrings. Add your method to the list at the top of this docstring. Also, add your method to ``ode.rst`` in the ``docs/src`` directory, so that the Sphinx docs will pull its docstring into the main SymPy documentation. Be sure to make the Sphinx documentation by running ``make html`` from within the doc directory to verify that the docstring formats correctly. If your solution method involves integrating, use :py:obj:`~.Integral` instead of :py:meth:`~sympy.core.expr.Expr.integrate`. This allows the user to bypass hard/slow integration by using the ``_Integral`` variant of your hint. In most cases, calling :py:meth:`sympy.core.basic.Basic.doit` will integrate your solution. If this is not the case, you will need to write special code in :py:meth:`~sympy.solvers.ode.ode._handle_Integral`. Arbitrary constants should be symbols named ``C1``, ``C2``, and so on. All solution methods should return an equality instance. If you need an arbitrary number of arbitrary constants, you can use ``constants = numbered_symbols(prefix='C', cls=Symbol, start=1)``. If it is possible to solve for the dependent function in a general way, do so. Otherwise, do as best as you can, but do not call solve in your ``ode_<hint>()`` function. :py:meth:`~sympy.solvers.ode.ode.odesimp` will attempt to solve the solution for you, so you do not need to do that. Lastly, if your ODE has a common simplification that can be applied to your solutions, you can add a special case in :py:meth:`~sympy.solvers.ode.ode.odesimp` for it. For example, solutions returned from the ``1st_homogeneous_coeff`` hints often have many :obj:`~sympy.functions.elementary.exponential.log` terms, so :py:meth:`~sympy.solvers.ode.ode.odesimp` calls :py:meth:`~sympy.simplify.simplify.logcombine` on them (it also helps to write the arbitrary constant as ``log(C1)`` instead of ``C1`` in this case). Also consider common ways that you can rearrange your solution to have :py:meth:`~sympy.solvers.ode.constantsimp` take better advantage of it. It is better to put simplification in :py:meth:`~sympy.solvers.ode.ode.odesimp` than in your method, because it can then be turned off with the simplify flag in :py:meth:`~sympy.solvers.ode.dsolve`. If you have any extraneous simplification in your function, be sure to only run it using ``if match.get('simplify', True):``, especially if it can be slow or if it can reduce the domain of the solution. Finally, as with every contribution to SymPy, your method will need to be tested. Add a test for each method in ``test_ode.py``. Follow the conventions there, i.e., test the solver using ``dsolve(eq, f(x), hint=your_hint)``, and also test the solution using :py:meth:`~sympy.solvers.ode.checkodesol` (you can put these in a separate tests and skip/XFAIL if it runs too slow/doesn't work). Be sure to call your hint specifically in :py:meth:`~sympy.solvers.ode.dsolve`, that way the test will not be broken simply by the introduction of another matching hint. If your method works for higher order (>1) ODEs, you will need to run ``sol = constant_renumber(sol, 'C', 1, order)`` for each solution, where ``order`` is the order of the ODE. This is because ``constant_renumber`` renumbers the arbitrary constants by printing order, which is platform dependent. Try to test every corner case of your solver, including a range of orders if it is a `n`\th order solver, but if your solver is slow, such as if it involves hard integration, try to keep the test run time down. Feel free to refactor existing hints to avoid duplicating code or creating inconsistencies. If you can show that your method exactly duplicates an existing method, including in the simplicity and speed of obtaining the solutions, then you can remove the old, less general method. The existing code is tested extensively in ``test_ode.py``, so if anything is broken, one of those tests will surely fail. """ from sympy.core import Add, S, Mul, Pow, oo from sympy.core.containers import Tuple from sympy.core.expr import AtomicExpr, Expr from sympy.core.function import (Function, Derivative, AppliedUndef, diff, expand, expand_mul, Subs) from sympy.core.multidimensional import vectorize from sympy.core.numbers import nan, zoo, Number from sympy.core.relational import Equality, Eq from sympy.core.sorting import default_sort_key, ordered from sympy.core.symbol import Symbol, Wild, Dummy, symbols from sympy.core.sympify import sympify from sympy.core.traversal import preorder_traversal from sympy.logic.boolalg import (BooleanAtom, BooleanTrue, BooleanFalse) from sympy.functions import exp, log, sqrt from sympy.functions.combinatorial.factorials import factorial from sympy.integrals.integrals import Integral from sympy.polys import (Poly, terms_gcd, PolynomialError, lcm) from sympy.polys.polytools import cancel from sympy.series import Order from sympy.series.series import series from sympy.simplify import (collect, logcombine, powsimp, # type: ignore separatevars, simplify, cse) from sympy.simplify.radsimp import collect_const from sympy.solvers import checksol, solve from sympy.utilities import numbered_symbols from sympy.utilities.iterables import uniq, sift, iterable from sympy.solvers.deutils import _preprocess, ode_order, _desolve #: This is a list of hints in the order that they should be preferred by #: :py:meth:`~sympy.solvers.ode.classify_ode`. In general, hints earlier in the #: list should produce simpler solutions than those later in the list (for #: ODEs that fit both). For now, the order of this list is based on empirical #: observations by the developers of SymPy. #: #: The hint used by :py:meth:`~sympy.solvers.ode.dsolve` for a specific ODE #: can be overridden (see the docstring). #: #: In general, ``_Integral`` hints are grouped at the end of the list, unless #: there is a method that returns an unevaluable integral most of the time #: (which go near the end of the list anyway). ``default``, ``all``, #: ``best``, and ``all_Integral`` meta-hints should not be included in this #: list, but ``_best`` and ``_Integral`` hints should be included. allhints = ( "factorable", "nth_algebraic", "separable", "1st_exact", "1st_linear", "Bernoulli", "1st_rational_riccati", "Riccati_special_minus2", "1st_homogeneous_coeff_best", "1st_homogeneous_coeff_subs_indep_div_dep", "1st_homogeneous_coeff_subs_dep_div_indep", "almost_linear", "linear_coefficients", "separable_reduced", "1st_power_series", "lie_group", "nth_linear_constant_coeff_homogeneous", "nth_linear_euler_eq_homogeneous", "nth_linear_constant_coeff_undetermined_coefficients", "nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients", "nth_linear_constant_coeff_variation_of_parameters", "nth_linear_euler_eq_nonhomogeneous_variation_of_parameters", "Liouville", "2nd_linear_airy", "2nd_linear_bessel", "2nd_hypergeometric", "2nd_hypergeometric_Integral", "nth_order_reducible", "2nd_power_series_ordinary", "2nd_power_series_regular", "nth_algebraic_Integral", "separable_Integral", "1st_exact_Integral", "1st_linear_Integral", "Bernoulli_Integral", "1st_homogeneous_coeff_subs_indep_div_dep_Integral", "1st_homogeneous_coeff_subs_dep_div_indep_Integral", "almost_linear_Integral", "linear_coefficients_Integral", "separable_reduced_Integral", "nth_linear_constant_coeff_variation_of_parameters_Integral", "nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral", "Liouville_Integral", "2nd_nonlinear_autonomous_conserved", "2nd_nonlinear_autonomous_conserved_Integral", ) def get_numbered_constants(eq, num=1, start=1, prefix='C'): """ Returns a list of constants that do not occur in eq already. """ ncs = iter_numbered_constants(eq, start, prefix) Cs = [next(ncs) for i in range(num)] return (Cs[0] if num == 1 else tuple(Cs)) def iter_numbered_constants(eq, start=1, prefix='C'): """ Returns an iterator of constants that do not occur in eq already. """ if isinstance(eq, (Expr, Eq)): eq = [eq] elif not iterable(eq): raise ValueError("Expected Expr or iterable but got %s" % eq) atom_set = set().union(*[i.free_symbols for i in eq]) func_set = set().union(*[i.atoms(Function) for i in eq]) if func_set: atom_set |= {Symbol(str(f.func)) for f in func_set} return numbered_symbols(start=start, prefix=prefix, exclude=atom_set) def dsolve(eq, func=None, hint="default", simplify=True, ics= None, xi=None, eta=None, x0=0, n=6, **kwargs): r""" Solves any (supported) kind of ordinary differential equation and system of ordinary differential equations. For single ordinary differential equation ========================================= It is classified under this when number of equation in ``eq`` is one. **Usage** ``dsolve(eq, f(x), hint)`` -> Solve ordinary differential equation ``eq`` for function ``f(x)``, using method ``hint``. **Details** ``eq`` can be any supported ordinary differential equation (see the :py:mod:`~sympy.solvers.ode` docstring for supported methods). This can either be an :py:class:`~sympy.core.relational.Equality`, or an expression, which is assumed to be equal to ``0``. ``f(x)`` is a function of one variable whose derivatives in that variable make up the ordinary differential equation ``eq``. In many cases it is not necessary to provide this; it will be autodetected (and an error raised if it couldn't be detected). ``hint`` is the solving method that you want dsolve to use. Use ``classify_ode(eq, f(x))`` to get all of the possible hints for an ODE. The default hint, ``default``, will use whatever hint is returned first by :py:meth:`~sympy.solvers.ode.classify_ode`. See Hints below for more options that you can use for hint. ``simplify`` enables simplification by :py:meth:`~sympy.solvers.ode.ode.odesimp`. See its docstring for more information. Turn this off, for example, to disable solving of solutions for ``func`` or simplification of arbitrary constants. It will still integrate with this hint. Note that the solution may contain more arbitrary constants than the order of the ODE with this option enabled. ``xi`` and ``eta`` are the infinitesimal functions of an ordinary differential equation. They are the infinitesimals of the Lie group of point transformations for which the differential equation is invariant. The user can specify values for the infinitesimals. If nothing is specified, ``xi`` and ``eta`` are calculated using :py:meth:`~sympy.solvers.ode.infinitesimals` with the help of various heuristics. ``ics`` is the set of initial/boundary conditions for the differential equation. It should be given in the form of ``{f(x0): x1, f(x).diff(x).subs(x, x2): x3}`` and so on. For power series solutions, if no initial conditions are specified ``f(0)`` is assumed to be ``C0`` and the power series solution is calculated about 0. ``x0`` is the point about which the power series solution of a differential equation is to be evaluated. ``n`` gives the exponent of the dependent variable up to which the power series solution of a differential equation is to be evaluated. **Hints** Aside from the various solving methods, there are also some meta-hints that you can pass to :py:meth:`~sympy.solvers.ode.dsolve`: ``default``: This uses whatever hint is returned first by :py:meth:`~sympy.solvers.ode.classify_ode`. This is the default argument to :py:meth:`~sympy.solvers.ode.dsolve`. ``all``: To make :py:meth:`~sympy.solvers.ode.dsolve` apply all relevant classification hints, use ``dsolve(ODE, func, hint="all")``. This will return a dictionary of ``hint:solution`` terms. If a hint causes dsolve to raise the ``NotImplementedError``, value of that hint's key will be the exception object raised. The dictionary will also include some special keys: - ``order``: The order of the ODE. See also :py:meth:`~sympy.solvers.deutils.ode_order` in ``deutils.py``. - ``best``: The simplest hint; what would be returned by ``best`` below. - ``best_hint``: The hint that would produce the solution given by ``best``. If more than one hint produces the best solution, the first one in the tuple returned by :py:meth:`~sympy.solvers.ode.classify_ode` is chosen. - ``default``: The solution that would be returned by default. This is the one produced by the hint that appears first in the tuple returned by :py:meth:`~sympy.solvers.ode.classify_ode`. ``all_Integral``: This is the same as ``all``, except if a hint also has a corresponding ``_Integral`` hint, it only returns the ``_Integral`` hint. This is useful if ``all`` causes :py:meth:`~sympy.solvers.ode.dsolve` to hang because of a difficult or impossible integral. This meta-hint will also be much faster than ``all``, because :py:meth:`~sympy.core.expr.Expr.integrate` is an expensive routine. ``best``: To have :py:meth:`~sympy.solvers.ode.dsolve` try all methods and return the simplest one. This takes into account whether the solution is solvable in the function, whether it contains any Integral classes (i.e. unevaluatable integrals), and which one is the shortest in size. See also the :py:meth:`~sympy.solvers.ode.classify_ode` docstring for more info on hints, and the :py:mod:`~sympy.solvers.ode` docstring for a list of all supported hints. **Tips** - You can declare the derivative of an unknown function this way: >>> from sympy import Function, Derivative >>> from sympy.abc import x # x is the independent variable >>> f = Function("f")(x) # f is a function of x >>> # f_ will be the derivative of f with respect to x >>> f_ = Derivative(f, x) - See ``test_ode.py`` for many tests, which serves also as a set of examples for how to use :py:meth:`~sympy.solvers.ode.dsolve`. - :py:meth:`~sympy.solvers.ode.dsolve` always returns an :py:class:`~sympy.core.relational.Equality` class (except for the case when the hint is ``all`` or ``all_Integral``). If possible, it solves the solution explicitly for the function being solved for. Otherwise, it returns an implicit solution. - Arbitrary constants are symbols named ``C1``, ``C2``, and so on. - Because all solutions should be mathematically equivalent, some hints may return the exact same result for an ODE. Often, though, two different hints will return the same solution formatted differently. The two should be equivalent. Also note that sometimes the values of the arbitrary constants in two different solutions may not be the same, because one constant may have "absorbed" other constants into it. - Do ``help(ode.ode_<hintname>)`` to get help more information on a specific hint, where ``<hintname>`` is the name of a hint without ``_Integral``. For system of ordinary differential equations ============================================= **Usage** ``dsolve(eq, func)`` -> Solve a system of ordinary differential equations ``eq`` for ``func`` being list of functions including `x(t)`, `y(t)`, `z(t)` where number of functions in the list depends upon the number of equations provided in ``eq``. **Details** ``eq`` can be any supported system of ordinary differential equations This can either be an :py:class:`~sympy.core.relational.Equality`, or an expression, which is assumed to be equal to ``0``. ``func`` holds ``x(t)`` and ``y(t)`` being functions of one variable which together with some of their derivatives make up the system of ordinary differential equation ``eq``. It is not necessary to provide this; it will be autodetected (and an error raised if it couldn't be detected). **Hints** The hints are formed by parameters returned by classify_sysode, combining them give hints name used later for forming method name. Examples ======== >>> from sympy import Function, dsolve, Eq, Derivative, sin, cos, symbols >>> from sympy.abc import x >>> f = Function('f') >>> dsolve(Derivative(f(x), x, x) + 9*f(x), f(x)) Eq(f(x), C1*sin(3*x) + C2*cos(3*x)) >>> eq = sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x) >>> dsolve(eq, hint='1st_exact') [Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))] >>> dsolve(eq, hint='almost_linear') [Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))] >>> t = symbols('t') >>> x, y = symbols('x, y', cls=Function) >>> eq = (Eq(Derivative(x(t),t), 12*t*x(t) + 8*y(t)), Eq(Derivative(y(t),t), 21*x(t) + 7*t*y(t))) >>> dsolve(eq) [Eq(x(t), C1*x0(t) + C2*x0(t)*Integral(8*exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)**2, t)), Eq(y(t), C1*y0(t) + C2*(y0(t)*Integral(8*exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)**2, t) + exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)))] >>> eq = (Eq(Derivative(x(t),t),x(t)*y(t)*sin(t)), Eq(Derivative(y(t),t),y(t)**2*sin(t))) >>> dsolve(eq) {Eq(x(t), -exp(C1)/(C2*exp(C1) - cos(t))), Eq(y(t), -1/(C1 - cos(t)))} """ if iterable(eq): from sympy.solvers.ode.systems import dsolve_system # This may have to be changed in future # when we have weakly and strongly # connected components. This have to # changed to show the systems that haven't # been solved. try: sol = dsolve_system(eq, funcs=func, ics=ics, doit=True) return sol[0] if len(sol) == 1 else sol except NotImplementedError: pass match = classify_sysode(eq, func) eq = match['eq'] order = match['order'] func = match['func'] t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] # keep highest order term coefficient positive for i in range(len(eq)): for func_ in func: if isinstance(func_, list): pass else: if eq[i].coeff(diff(func[i],t,ode_order(eq[i], func[i]))).is_negative: eq[i] = -eq[i] match['eq'] = eq if len(set(order.values()))!=1: raise ValueError("It solves only those systems of equations whose orders are equal") match['order'] = list(order.values())[0] def recur_len(l): return sum(recur_len(item) if isinstance(item,list) else 1 for item in l) if recur_len(func) != len(eq): raise ValueError("dsolve() and classify_sysode() work with " "number of functions being equal to number of equations") if match['type_of_equation'] is None: raise NotImplementedError else: if match['is_linear'] == True: solvefunc = globals()['sysode_linear_%(no_of_equation)seq_order%(order)s' % match] else: solvefunc = globals()['sysode_nonlinear_%(no_of_equation)seq_order%(order)s' % match] sols = solvefunc(match) if ics: constants = Tuple(*sols).free_symbols - Tuple(*eq).free_symbols solved_constants = solve_ics(sols, func, constants, ics) return [sol.subs(solved_constants) for sol in sols] return sols else: given_hint = hint # hint given by the user # See the docstring of _desolve for more details. hints = _desolve(eq, func=func, hint=hint, simplify=True, xi=xi, eta=eta, type='ode', ics=ics, x0=x0, n=n, **kwargs) eq = hints.pop('eq', eq) all_ = hints.pop('all', False) if all_: retdict = {} failed_hints = {} gethints = classify_ode(eq, dict=True, hint='all') orderedhints = gethints['ordered_hints'] for hint in hints: try: rv = _helper_simplify(eq, hint, hints[hint], simplify) except NotImplementedError as detail: failed_hints[hint] = detail else: retdict[hint] = rv func = hints[hint]['func'] retdict['best'] = min(list(retdict.values()), key=lambda x: ode_sol_simplicity(x, func, trysolving=not simplify)) if given_hint == 'best': return retdict['best'] for i in orderedhints: if retdict['best'] == retdict.get(i, None): retdict['best_hint'] = i break retdict['default'] = gethints['default'] retdict['order'] = gethints['order'] retdict.update(failed_hints) return retdict else: # The key 'hint' stores the hint needed to be solved for. hint = hints['hint'] return _helper_simplify(eq, hint, hints, simplify, ics=ics) def _helper_simplify(eq, hint, match, simplify=True, ics=None, **kwargs): r""" Helper function of dsolve that calls the respective :py:mod:`~sympy.solvers.ode` functions to solve for the ordinary differential equations. This minimizes the computation in calling :py:meth:`~sympy.solvers.deutils._desolve` multiple times. """ r = match func = r['func'] order = r['order'] match = r[hint] if isinstance(match, SingleODESolver): solvefunc = match elif hint.endswith('_Integral'): solvefunc = globals()['ode_' + hint[:-len('_Integral')]] else: solvefunc = globals()['ode_' + hint] free = eq.free_symbols cons = lambda s: s.free_symbols.difference(free) if simplify: # odesimp() will attempt to integrate, if necessary, apply constantsimp(), # attempt to solve for func, and apply any other hint specific # simplifications if isinstance(solvefunc, SingleODESolver): sols = solvefunc.get_general_solution() else: sols = solvefunc(eq, func, order, match) if iterable(sols): rv = [odesimp(eq, s, func, hint) for s in sols] else: rv = odesimp(eq, sols, func, hint) else: # We still want to integrate (you can disable it separately with the hint) if isinstance(solvefunc, SingleODESolver): exprs = solvefunc.get_general_solution(simplify=False) else: match['simplify'] = False # Some hints can take advantage of this option exprs = solvefunc(eq, func, order, match) if isinstance(exprs, list): rv = [_handle_Integral(expr, func, hint) for expr in exprs] else: rv = _handle_Integral(exprs, func, hint) if isinstance(rv, list): if simplify: rv = _remove_redundant_solutions(eq, rv, order, func.args[0]) if len(rv) == 1: rv = rv[0] if ics and 'power_series' not in hint: if isinstance(rv, (Expr, Eq)): solved_constants = solve_ics([rv], [r['func']], cons(rv), ics) rv = rv.subs(solved_constants) else: rv1 = [] for s in rv: try: solved_constants = solve_ics([s], [r['func']], cons(s), ics) except ValueError: continue rv1.append(s.subs(solved_constants)) if len(rv1) == 1: return rv1[0] rv = rv1 return rv def solve_ics(sols, funcs, constants, ics): """ Solve for the constants given initial conditions ``sols`` is a list of solutions. ``funcs`` is a list of functions. ``constants`` is a list of constants. ``ics`` is the set of initial/boundary conditions for the differential equation. It should be given in the form of ``{f(x0): x1, f(x).diff(x).subs(x, x2): x3}`` and so on. Returns a dictionary mapping constants to values. ``solution.subs(constants)`` will replace the constants in ``solution``. Example ======= >>> # From dsolve(f(x).diff(x) - f(x), f(x)) >>> from sympy import symbols, Eq, exp, Function >>> from sympy.solvers.ode.ode import solve_ics >>> f = Function('f') >>> x, C1 = symbols('x C1') >>> sols = [Eq(f(x), C1*exp(x))] >>> funcs = [f(x)] >>> constants = [C1] >>> ics = {f(0): 2} >>> solved_constants = solve_ics(sols, funcs, constants, ics) >>> solved_constants {C1: 2} >>> sols[0].subs(solved_constants) Eq(f(x), 2*exp(x)) """ # Assume ics are of the form f(x0): value or Subs(diff(f(x), x, n), (x, # x0)): value (currently checked by classify_ode). To solve, replace x # with x0, f(x0) with value, then solve for constants. For f^(n)(x0), # differentiate the solution n times, so that f^(n)(x) appears. x = funcs[0].args[0] diff_sols = [] subs_sols = [] diff_variables = set() for funcarg, value in ics.items(): if isinstance(funcarg, AppliedUndef): x0 = funcarg.args[0] matching_func = [f for f in funcs if f.func == funcarg.func][0] S = sols elif isinstance(funcarg, (Subs, Derivative)): if isinstance(funcarg, Subs): # Make sure it stays a subs. Otherwise subs below will produce # a different looking term. funcarg = funcarg.doit() if isinstance(funcarg, Subs): deriv = funcarg.expr x0 = funcarg.point[0] variables = funcarg.expr.variables matching_func = deriv elif isinstance(funcarg, Derivative): deriv = funcarg x0 = funcarg.variables[0] variables = (x,)*len(funcarg.variables) matching_func = deriv.subs(x0, x) for sol in sols: if sol.has(deriv.expr.func): diff_sols.append(Eq(sol.lhs.diff(*variables), sol.rhs.diff(*variables))) diff_variables.add(variables) S = diff_sols else: raise NotImplementedError("Unrecognized initial condition") for sol in S: if sol.has(matching_func): sol2 = sol sol2 = sol2.subs(x, x0) sol2 = sol2.subs(funcarg, value) # This check is necessary because of issue #15724 if not isinstance(sol2, BooleanAtom) or not subs_sols: subs_sols = [s for s in subs_sols if not isinstance(s, BooleanAtom)] subs_sols.append(sol2) # TODO: Use solveset here try: solved_constants = solve(subs_sols, constants, dict=True) except NotImplementedError: solved_constants = [] # XXX: We can't differentiate between the solution not existing because of # invalid initial conditions, and not existing because solve is not smart # enough. If we could use solveset, this might be improvable, but for now, # we use NotImplementedError in this case. if not solved_constants: raise ValueError("Couldn't solve for initial conditions") if solved_constants == True: raise ValueError("Initial conditions did not produce any solutions for constants. Perhaps they are degenerate.") if len(solved_constants) > 1: raise NotImplementedError("Initial conditions produced too many solutions for constants") return solved_constants[0] def classify_ode(eq, func=None, dict=False, ics=None, *, prep=True, xi=None, eta=None, n=None, **kwargs): r""" Returns a tuple of possible :py:meth:`~sympy.solvers.ode.dsolve` classifications for an ODE. The tuple is ordered so that first item is the classification that :py:meth:`~sympy.solvers.ode.dsolve` uses to solve the ODE by default. In general, classifications at the near the beginning of the list will produce better solutions faster than those near the end, thought there are always exceptions. To make :py:meth:`~sympy.solvers.ode.dsolve` use a different classification, use ``dsolve(ODE, func, hint=<classification>)``. See also the :py:meth:`~sympy.solvers.ode.dsolve` docstring for different meta-hints you can use. If ``dict`` is true, :py:meth:`~sympy.solvers.ode.classify_ode` will return a dictionary of ``hint:match`` expression terms. This is intended for internal use by :py:meth:`~sympy.solvers.ode.dsolve`. Note that because dictionaries are ordered arbitrarily, this will most likely not be in the same order as the tuple. You can get help on different hints by executing ``help(ode.ode_hintname)``, where ``hintname`` is the name of the hint without ``_Integral``. See :py:data:`~sympy.solvers.ode.allhints` or the :py:mod:`~sympy.solvers.ode` docstring for a list of all supported hints that can be returned from :py:meth:`~sympy.solvers.ode.classify_ode`. Notes ===== These are remarks on hint names. ``_Integral`` If a classification has ``_Integral`` at the end, it will return the expression with an unevaluated :py:class:`~.Integral` class in it. Note that a hint may do this anyway if :py:meth:`~sympy.core.expr.Expr.integrate` cannot do the integral, though just using an ``_Integral`` will do so much faster. Indeed, an ``_Integral`` hint will always be faster than its corresponding hint without ``_Integral`` because :py:meth:`~sympy.core.expr.Expr.integrate` is an expensive routine. If :py:meth:`~sympy.solvers.ode.dsolve` hangs, it is probably because :py:meth:`~sympy.core.expr.Expr.integrate` is hanging on a tough or impossible integral. Try using an ``_Integral`` hint or ``all_Integral`` to get it return something. Note that some hints do not have ``_Integral`` counterparts. This is because :py:func:`~sympy.integrals.integrals.integrate` is not used in solving the ODE for those method. For example, `n`\th order linear homogeneous ODEs with constant coefficients do not require integration to solve, so there is no ``nth_linear_homogeneous_constant_coeff_Integrate`` hint. You can easily evaluate any unevaluated :py:class:`~sympy.integrals.integrals.Integral`\s in an expression by doing ``expr.doit()``. Ordinals Some hints contain an ordinal such as ``1st_linear``. This is to help differentiate them from other hints, as well as from other methods that may not be implemented yet. If a hint has ``nth`` in it, such as the ``nth_linear`` hints, this means that the method used to applies to ODEs of any order. ``indep`` and ``dep`` Some hints contain the words ``indep`` or ``dep``. These reference the independent variable and the dependent function, respectively. For example, if an ODE is in terms of `f(x)`, then ``indep`` will refer to `x` and ``dep`` will refer to `f`. ``subs`` If a hints has the word ``subs`` in it, it means that the ODE is solved by substituting the expression given after the word ``subs`` for a single dummy variable. This is usually in terms of ``indep`` and ``dep`` as above. The substituted expression will be written only in characters allowed for names of Python objects, meaning operators will be spelled out. For example, ``indep``/``dep`` will be written as ``indep_div_dep``. ``coeff`` The word ``coeff`` in a hint refers to the coefficients of something in the ODE, usually of the derivative terms. See the docstring for the individual methods for more info (``help(ode)``). This is contrast to ``coefficients``, as in ``undetermined_coefficients``, which refers to the common name of a method. ``_best`` Methods that have more than one fundamental way to solve will have a hint for each sub-method and a ``_best`` meta-classification. This will evaluate all hints and return the best, using the same considerations as the normal ``best`` meta-hint. Examples ======== >>> from sympy import Function, classify_ode, Eq >>> from sympy.abc import x >>> f = Function('f') >>> classify_ode(Eq(f(x).diff(x), 0), f(x)) ('nth_algebraic', 'separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_homogeneous', 'nth_linear_euler_eq_homogeneous', 'nth_algebraic_Integral', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral') >>> classify_ode(f(x).diff(x, 2) + 3*f(x).diff(x) + 2*f(x) - 4) ('factorable', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', 'nth_linear_constant_coeff_variation_of_parameters_Integral') """ ics = sympify(ics) if func and len(func.args) != 1: raise ValueError("dsolve() and classify_ode() only " "work with functions of one variable, not %s" % func) if isinstance(eq, Equality): eq = eq.lhs - eq.rhs # Some methods want the unprocessed equation eq_orig = eq if prep or func is None: eq, func_ = _preprocess(eq, func) if func is None: func = func_ x = func.args[0] f = func.func y = Dummy('y') terms = 5 if n is None else n order = ode_order(eq, f(x)) # hint:matchdict or hint:(tuple of matchdicts) # Also will contain "default":<default hint> and "order":order items. matching_hints = {"order": order} df = f(x).diff(x) a = Wild('a', exclude=[f(x)]) d = Wild('d', exclude=[df, f(x).diff(x, 2)]) e = Wild('e', exclude=[df]) n = Wild('n', exclude=[x, f(x), df]) c1 = Wild('c1', exclude=[x]) a3 = Wild('a3', exclude=[f(x), df, f(x).diff(x, 2)]) b3 = Wild('b3', exclude=[f(x), df, f(x).diff(x, 2)]) c3 = Wild('c3', exclude=[f(x), df, f(x).diff(x, 2)]) boundary = {} # Used to extract initial conditions C1 = Symbol("C1") # Preprocessing to get the initial conditions out if ics is not None: for funcarg in ics: # Separating derivatives if isinstance(funcarg, (Subs, Derivative)): # f(x).diff(x).subs(x, 0) is a Subs, but f(x).diff(x).subs(x, # y) is a Derivative if isinstance(funcarg, Subs): deriv = funcarg.expr old = funcarg.variables[0] new = funcarg.point[0] elif isinstance(funcarg, Derivative): deriv = funcarg # No information on this. Just assume it was x old = x new = funcarg.variables[0] if (isinstance(deriv, Derivative) and isinstance(deriv.args[0], AppliedUndef) and deriv.args[0].func == f and len(deriv.args[0].args) == 1 and old == x and not new.has(x) and all(i == deriv.variables[0] for i in deriv.variables) and not ics[funcarg].has(f)): dorder = ode_order(deriv, x) temp = 'f' + str(dorder) boundary.update({temp: new, temp + 'val': ics[funcarg]}) else: raise ValueError("Enter valid boundary conditions for Derivatives") # Separating functions elif isinstance(funcarg, AppliedUndef): if (funcarg.func == f and len(funcarg.args) == 1 and not funcarg.args[0].has(x) and not ics[funcarg].has(f)): boundary.update({'f0': funcarg.args[0], 'f0val': ics[funcarg]}) else: raise ValueError("Enter valid boundary conditions for Function") else: raise ValueError("Enter boundary conditions of the form ics={f(point): value, f(x).diff(x, order).subs(x, point): value}") ode = SingleODEProblem(eq_orig, func, x, prep=prep, xi=xi, eta=eta) user_hint = kwargs.get('hint', 'default') # Used when dsolve is called without an explicit hint. # We exit early to return the first valid match early_exit = (user_hint=='default') if user_hint.endswith('_Integral'): user_hint = user_hint[:-len('_Integral')] user_map = solver_map # An explicit hint has been given to dsolve # Skip matching code for other hints if user_hint not in ['default', 'all', 'all_Integral', 'best'] and user_hint in solver_map: user_map = {user_hint: solver_map[user_hint]} for hint in user_map: solver = user_map[hint](ode) if solver.matches(): matching_hints[hint] = solver if user_map[hint].has_integral: matching_hints[hint + "_Integral"] = solver if dict and early_exit: matching_hints["default"] = hint return matching_hints eq = expand(eq) # Precondition to try remove f(x) from highest order derivative reduced_eq = None if eq.is_Add: deriv_coef = eq.coeff(f(x).diff(x, order)) if deriv_coef not in (1, 0): r = deriv_coef.match(a*f(x)**c1) if r and r[c1]: den = f(x)**r[c1] reduced_eq = Add(*[arg/den for arg in eq.args]) if not reduced_eq: reduced_eq = eq if order == 1: # NON-REDUCED FORM OF EQUATION matches r = collect(eq, df, exact=True).match(d + e * df) if r: r['d'] = d r['e'] = e r['y'] = y r[d] = r[d].subs(f(x), y) r[e] = r[e].subs(f(x), y) # FIRST ORDER POWER SERIES WHICH NEEDS INITIAL CONDITIONS # TODO: Hint first order series should match only if d/e is analytic. # For now, only d/e and (d/e).diff(arg) is checked for existence at # at a given point. # This is currently done internally in ode_1st_power_series. point = boundary.get('f0', 0) value = boundary.get('f0val', C1) check = cancel(r[d]/r[e]) check1 = check.subs({x: point, y: value}) if not check1.has(oo) and not check1.has(zoo) and \ not check1.has(nan) and not check1.has(-oo): check2 = (check1.diff(x)).subs({x: point, y: value}) if not check2.has(oo) and not check2.has(zoo) and \ not check2.has(nan) and not check2.has(-oo): rseries = r.copy() rseries.update({'terms': terms, 'f0': point, 'f0val': value}) matching_hints["1st_power_series"] = rseries elif order == 2: # Homogeneous second order differential equation of the form # a3*f(x).diff(x, 2) + b3*f(x).diff(x) + c3 # It has a definite power series solution at point x0 if, b3/a3 and c3/a3 # are analytic at x0. deq = a3*(f(x).diff(x, 2)) + b3*df + c3*f(x) r = collect(reduced_eq, [f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq) ordinary = False if r: if not all(r[key].is_polynomial() for key in r): n, d = reduced_eq.as_numer_denom() reduced_eq = expand(n) r = collect(reduced_eq, [f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq) if r and r[a3] != 0: p = cancel(r[b3]/r[a3]) # Used below q = cancel(r[c3]/r[a3]) # Used below point = kwargs.get('x0', 0) check = p.subs(x, point) if not check.has(oo, nan, zoo, -oo): check = q.subs(x, point) if not check.has(oo, nan, zoo, -oo): ordinary = True r.update({'a3': a3, 'b3': b3, 'c3': c3, 'x0': point, 'terms': terms}) matching_hints["2nd_power_series_ordinary"] = r # Checking if the differential equation has a regular singular point # at x0. It has a regular singular point at x0, if (b3/a3)*(x - x0) # and (c3/a3)*((x - x0)**2) are analytic at x0. if not ordinary: p = cancel((x - point)*p) check = p.subs(x, point) if not check.has(oo, nan, zoo, -oo): q = cancel(((x - point)**2)*q) check = q.subs(x, point) if not check.has(oo, nan, zoo, -oo): coeff_dict = {'p': p, 'q': q, 'x0': point, 'terms': terms} matching_hints["2nd_power_series_regular"] = coeff_dict # Order keys based on allhints. retlist = [i for i in allhints if i in matching_hints] if dict: # Dictionaries are ordered arbitrarily, so make note of which # hint would come first for dsolve(). Use an ordered dict in Py 3. matching_hints["default"] = retlist[0] if retlist else None matching_hints["ordered_hints"] = tuple(retlist) return matching_hints else: return tuple(retlist) def classify_sysode(eq, funcs=None, **kwargs): r""" Returns a dictionary of parameter names and values that define the system of ordinary differential equations in ``eq``. The parameters are further used in :py:meth:`~sympy.solvers.ode.dsolve` for solving that system. Some parameter names and values are: 'is_linear' (boolean), which tells whether the given system is linear. Note that "linear" here refers to the operator: terms such as ``x*diff(x,t)`` are nonlinear, whereas terms like ``sin(t)*diff(x,t)`` are still linear operators. 'func' (list) contains the :py:class:`~sympy.core.function.Function`s that appear with a derivative in the ODE, i.e. those that we are trying to solve the ODE for. 'order' (dict) with the maximum derivative for each element of the 'func' parameter. 'func_coeff' (dict or Matrix) with the coefficient for each triple ``(equation number, function, order)```. The coefficients are those subexpressions that do not appear in 'func', and hence can be considered constant for purposes of ODE solving. The value of this parameter can also be a Matrix if the system of ODEs are linear first order of the form X' = AX where X is the vector of dependent variables. Here, this function returns the coefficient matrix A. 'eq' (list) with the equations from ``eq``, sympified and transformed into expressions (we are solving for these expressions to be zero). 'no_of_equations' (int) is the number of equations (same as ``len(eq)``). 'type_of_equation' (string) is an internal classification of the type of ODE. 'is_constant' (boolean), which tells if the system of ODEs is constant coefficient or not. This key is temporary addition for now and is in the match dict only when the system of ODEs is linear first order constant coefficient homogeneous. So, this key's value is True for now if it is available else it doesn't exist. 'is_homogeneous' (boolean), which tells if the system of ODEs is homogeneous. Like the key 'is_constant', this key is a temporary addition and it is True since this key value is available only when the system is linear first order constant coefficient homogeneous. References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode-toc1.htm -A. D. Polyanin and A. V. Manzhirov, Handbook of Mathematics for Engineers and Scientists Examples ======== >>> from sympy import Function, Eq, symbols, diff >>> from sympy.solvers.ode.ode import classify_sysode >>> from sympy.abc import t >>> f, x, y = symbols('f, x, y', cls=Function) >>> k, l, m, n = symbols('k, l, m, n', Integer=True) >>> x1 = diff(x(t), t) ; y1 = diff(y(t), t) >>> x2 = diff(x(t), t, t) ; y2 = diff(y(t), t, t) >>> eq = (Eq(x1, 12*x(t) - 6*y(t)), Eq(y1, 11*x(t) + 3*y(t))) >>> classify_sysode(eq) {'eq': [-12*x(t) + 6*y(t) + Derivative(x(t), t), -11*x(t) - 3*y(t) + Derivative(y(t), t)], 'func': [x(t), y(t)], 'func_coeff': {(0, x(t), 0): -12, (0, x(t), 1): 1, (0, y(t), 0): 6, (0, y(t), 1): 0, (1, x(t), 0): -11, (1, x(t), 1): 0, (1, y(t), 0): -3, (1, y(t), 1): 1}, 'is_linear': True, 'no_of_equation': 2, 'order': {x(t): 1, y(t): 1}, 'type_of_equation': None} >>> eq = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t) + 2), Eq(diff(y(t),t), -t**2*x(t) + 5*t*y(t))) >>> classify_sysode(eq) {'eq': [-t**2*y(t) - 5*t*x(t) + Derivative(x(t), t) - 2, t**2*x(t) - 5*t*y(t) + Derivative(y(t), t)], 'func': [x(t), y(t)], 'func_coeff': {(0, x(t), 0): -5*t, (0, x(t), 1): 1, (0, y(t), 0): -t**2, (0, y(t), 1): 0, (1, x(t), 0): t**2, (1, x(t), 1): 0, (1, y(t), 0): -5*t, (1, y(t), 1): 1}, 'is_linear': True, 'no_of_equation': 2, 'order': {x(t): 1, y(t): 1}, 'type_of_equation': None} """ # Sympify equations and convert iterables of equations into # a list of equations def _sympify(eq): return list(map(sympify, eq if iterable(eq) else [eq])) eq, funcs = (_sympify(w) for w in [eq, funcs]) for i, fi in enumerate(eq): if isinstance(fi, Equality): eq[i] = fi.lhs - fi.rhs t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] matching_hints = {"no_of_equation":i+1} matching_hints['eq'] = eq if i==0: raise ValueError("classify_sysode() works for systems of ODEs. " "For scalar ODEs, classify_ode should be used") # find all the functions if not given order = dict() if funcs==[None]: funcs = _extract_funcs(eq) funcs = list(set(funcs)) if len(funcs) != len(eq): raise ValueError("Number of functions given is not equal to the number of equations %s" % funcs) # This logic of list of lists in funcs to # be replaced later. func_dict = dict() for func in funcs: if not order.get(func, False): max_order = 0 for i, eqs_ in enumerate(eq): order_ = ode_order(eqs_,func) if max_order < order_: max_order = order_ eq_no = i if eq_no in func_dict: func_dict[eq_no] = [func_dict[eq_no], func] else: func_dict[eq_no] = func order[func] = max_order funcs = [func_dict[i] for i in range(len(func_dict))] matching_hints['func'] = funcs for func in funcs: if isinstance(func, list): for func_elem in func: if len(func_elem.args) != 1: raise ValueError("dsolve() and classify_sysode() work with " "functions of one variable only, not %s" % func) else: if func and len(func.args) != 1: raise ValueError("dsolve() and classify_sysode() work with " "functions of one variable only, not %s" % func) # find the order of all equation in system of odes matching_hints["order"] = order # find coefficients of terms f(t), diff(f(t),t) and higher derivatives # and similarly for other functions g(t), diff(g(t),t) in all equations. # Here j denotes the equation number, funcs[l] denotes the function about # which we are talking about and k denotes the order of function funcs[l] # whose coefficient we are calculating. def linearity_check(eqs, j, func, is_linear_): for k in range(order[func] + 1): func_coef[j, func, k] = collect(eqs.expand(), [diff(func, t, k)]).coeff(diff(func, t, k)) if is_linear_ == True: if func_coef[j, func, k] == 0: if k == 0: coef = eqs.as_independent(func, as_Add=True)[1] for xr in range(1, ode_order(eqs,func) + 1): coef -= eqs.as_independent(diff(func, t, xr), as_Add=True)[1] if coef != 0: is_linear_ = False else: if eqs.as_independent(diff(func, t, k), as_Add=True)[1]: is_linear_ = False else: for func_ in funcs: if isinstance(func_, list): for elem_func_ in func_: dep = func_coef[j, func, k].as_independent(elem_func_, as_Add=True)[1] if dep != 0: is_linear_ = False else: dep = func_coef[j, func, k].as_independent(func_, as_Add=True)[1] if dep != 0: is_linear_ = False return is_linear_ func_coef = {} is_linear = True for j, eqs in enumerate(eq): for func in funcs: if isinstance(func, list): for func_elem in func: is_linear = linearity_check(eqs, j, func_elem, is_linear) else: is_linear = linearity_check(eqs, j, func, is_linear) matching_hints['func_coeff'] = func_coef matching_hints['is_linear'] = is_linear if len(set(order.values())) == 1: order_eq = list(matching_hints['order'].values())[0] if matching_hints['is_linear'] == True: if matching_hints['no_of_equation'] == 2: if order_eq == 1: type_of_equation = check_linear_2eq_order1(eq, funcs, func_coef) else: type_of_equation = None # If the equation doesn't match up with any of the # general case solvers in systems.py and the number # of equations is greater than 2, then NotImplementedError # should be raised. else: type_of_equation = None else: if matching_hints['no_of_equation'] == 2: if order_eq == 1: type_of_equation = check_nonlinear_2eq_order1(eq, funcs, func_coef) else: type_of_equation = None elif matching_hints['no_of_equation'] == 3: if order_eq == 1: type_of_equation = check_nonlinear_3eq_order1(eq, funcs, func_coef) else: type_of_equation = None else: type_of_equation = None else: type_of_equation = None matching_hints['type_of_equation'] = type_of_equation return matching_hints def check_linear_2eq_order1(eq, func, func_coef): x = func[0].func y = func[1].func fc = func_coef t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] r = dict() # for equations Eq(a1*diff(x(t),t), b1*x(t) + c1*y(t) + d1) # and Eq(a2*diff(y(t),t), b2*x(t) + c2*y(t) + d2) r['a1'] = fc[0,x(t),1] ; r['a2'] = fc[1,y(t),1] r['b1'] = -fc[0,x(t),0]/fc[0,x(t),1] ; r['b2'] = -fc[1,x(t),0]/fc[1,y(t),1] r['c1'] = -fc[0,y(t),0]/fc[0,x(t),1] ; r['c2'] = -fc[1,y(t),0]/fc[1,y(t),1] forcing = [S.Zero,S.Zero] for i in range(2): for j in Add.make_args(eq[i]): if not j.has(x(t), y(t)): forcing[i] += j if not (forcing[0].has(t) or forcing[1].has(t)): # We can handle homogeneous case and simple constant forcings r['d1'] = forcing[0] r['d2'] = forcing[1] else: # Issue #9244: nonhomogeneous linear systems are not supported return None # Conditions to check for type 6 whose equations are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and # Eq(diff(y(t),t), a*[f(t) + a*h(t)]x(t) + a*[g(t) - h(t)]*y(t)) p = 0 q = 0 p1 = cancel(r['b2']/(cancel(r['b2']/r['c2']).as_numer_denom()[0])) p2 = cancel(r['b1']/(cancel(r['b1']/r['c1']).as_numer_denom()[0])) for n, i in enumerate([p1, p2]): for j in Mul.make_args(collect_const(i)): if not j.has(t): q = j if q and n==0: if ((r['b2']/j - r['b1'])/(r['c1'] - r['c2']/j)) == j: p = 1 elif q and n==1: if ((r['b1']/j - r['b2'])/(r['c2'] - r['c1']/j)) == j: p = 2 # End of condition for type 6 if r['d1']!=0 or r['d2']!=0: return None else: if not any(r[k].has(t) for k in 'a1 a2 b1 b2 c1 c2'.split()): return None else: r['b1'] = r['b1']/r['a1'] ; r['b2'] = r['b2']/r['a2'] r['c1'] = r['c1']/r['a1'] ; r['c2'] = r['c2']/r['a2'] if p: return "type6" else: # Equations for type 7 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), h(t)*x(t) + p(t)*y(t)) return "type7" def check_nonlinear_2eq_order1(eq, func, func_coef): t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] f = Wild('f') g = Wild('g') u, v = symbols('u, v', cls=Dummy) def check_type(x, y): r1 = eq[0].match(t*diff(x(t),t) - x(t) + f) r2 = eq[1].match(t*diff(y(t),t) - y(t) + g) if not (r1 and r2): r1 = eq[0].match(diff(x(t),t) - x(t)/t + f/t) r2 = eq[1].match(diff(y(t),t) - y(t)/t + g/t) if not (r1 and r2): r1 = (-eq[0]).match(t*diff(x(t),t) - x(t) + f) r2 = (-eq[1]).match(t*diff(y(t),t) - y(t) + g) if not (r1 and r2): r1 = (-eq[0]).match(diff(x(t),t) - x(t)/t + f/t) r2 = (-eq[1]).match(diff(y(t),t) - y(t)/t + g/t) if r1 and r2 and not (r1[f].subs(diff(x(t),t),u).subs(diff(y(t),t),v).has(t) \ or r2[g].subs(diff(x(t),t),u).subs(diff(y(t),t),v).has(t)): return 'type5' else: return None for func_ in func: if isinstance(func_, list): x = func[0][0].func y = func[0][1].func eq_type = check_type(x, y) if not eq_type: eq_type = check_type(y, x) return eq_type x = func[0].func y = func[1].func fc = func_coef n = Wild('n', exclude=[x(t),y(t)]) f1 = Wild('f1', exclude=[v,t]) f2 = Wild('f2', exclude=[v,t]) g1 = Wild('g1', exclude=[u,t]) g2 = Wild('g2', exclude=[u,t]) for i in range(2): eqs = 0 for terms in Add.make_args(eq[i]): eqs += terms/fc[i,func[i],1] eq[i] = eqs r = eq[0].match(diff(x(t),t) - x(t)**n*f) if r: g = (diff(y(t),t) - eq[1])/r[f] if r and not (g.has(x(t)) or g.subs(y(t),v).has(t) or r[f].subs(x(t),u).subs(y(t),v).has(t)): return 'type1' r = eq[0].match(diff(x(t),t) - exp(n*x(t))*f) if r: g = (diff(y(t),t) - eq[1])/r[f] if r and not (g.has(x(t)) or g.subs(y(t),v).has(t) or r[f].subs(x(t),u).subs(y(t),v).has(t)): return 'type2' g = Wild('g') r1 = eq[0].match(diff(x(t),t) - f) r2 = eq[1].match(diff(y(t),t) - g) if r1 and r2 and not (r1[f].subs(x(t),u).subs(y(t),v).has(t) or \ r2[g].subs(x(t),u).subs(y(t),v).has(t)): return 'type3' r1 = eq[0].match(diff(x(t),t) - f) r2 = eq[1].match(diff(y(t),t) - g) num, den = ( (r1[f].subs(x(t),u).subs(y(t),v))/ (r2[g].subs(x(t),u).subs(y(t),v))).as_numer_denom() R1 = num.match(f1*g1) R2 = den.match(f2*g2) # phi = (r1[f].subs(x(t),u).subs(y(t),v))/num if R1 and R2: return 'type4' return None def check_nonlinear_2eq_order2(eq, func, func_coef): return None def check_nonlinear_3eq_order1(eq, func, func_coef): x = func[0].func y = func[1].func z = func[2].func fc = func_coef t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] u, v, w = symbols('u, v, w', cls=Dummy) a = Wild('a', exclude=[x(t), y(t), z(t), t]) b = Wild('b', exclude=[x(t), y(t), z(t), t]) c = Wild('c', exclude=[x(t), y(t), z(t), t]) f = Wild('f') F1 = Wild('F1') F2 = Wild('F2') F3 = Wild('F3') for i in range(3): eqs = 0 for terms in Add.make_args(eq[i]): eqs += terms/fc[i,func[i],1] eq[i] = eqs r1 = eq[0].match(diff(x(t),t) - a*y(t)*z(t)) r2 = eq[1].match(diff(y(t),t) - b*z(t)*x(t)) r3 = eq[2].match(diff(z(t),t) - c*x(t)*y(t)) if r1 and r2 and r3: num1, den1 = r1[a].as_numer_denom() num2, den2 = r2[b].as_numer_denom() num3, den3 = r3[c].as_numer_denom() if solve([num1*u-den1*(v-w), num2*v-den2*(w-u), num3*w-den3*(u-v)],[u, v]): return 'type1' r = eq[0].match(diff(x(t),t) - y(t)*z(t)*f) if r: r1 = collect_const(r[f]).match(a*f) r2 = ((diff(y(t),t) - eq[1])/r1[f]).match(b*z(t)*x(t)) r3 = ((diff(z(t),t) - eq[2])/r1[f]).match(c*x(t)*y(t)) if r1 and r2 and r3: num1, den1 = r1[a].as_numer_denom() num2, den2 = r2[b].as_numer_denom() num3, den3 = r3[c].as_numer_denom() if solve([num1*u-den1*(v-w), num2*v-den2*(w-u), num3*w-den3*(u-v)],[u, v]): return 'type2' r = eq[0].match(diff(x(t),t) - (F2-F3)) if r: r1 = collect_const(r[F2]).match(c*F2) r1.update(collect_const(r[F3]).match(b*F3)) if r1: if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]): r1[F2], r1[F3] = r1[F3], r1[F2] r1[c], r1[b] = -r1[b], -r1[c] r2 = eq[1].match(diff(y(t),t) - a*r1[F3] + r1[c]*F1) if r2: r3 = (eq[2] == diff(z(t),t) - r1[b]*r2[F1] + r2[a]*r1[F2]) if r1 and r2 and r3: return 'type3' r = eq[0].match(diff(x(t),t) - z(t)*F2 + y(t)*F3) if r: r1 = collect_const(r[F2]).match(c*F2) r1.update(collect_const(r[F3]).match(b*F3)) if r1: if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]): r1[F2], r1[F3] = r1[F3], r1[F2] r1[c], r1[b] = -r1[b], -r1[c] r2 = (diff(y(t),t) - eq[1]).match(a*x(t)*r1[F3] - r1[c]*z(t)*F1) if r2: r3 = (diff(z(t),t) - eq[2] == r1[b]*y(t)*r2[F1] - r2[a]*x(t)*r1[F2]) if r1 and r2 and r3: return 'type4' r = (diff(x(t),t) - eq[0]).match(x(t)*(F2 - F3)) if r: r1 = collect_const(r[F2]).match(c*F2) r1.update(collect_const(r[F3]).match(b*F3)) if r1: if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]): r1[F2], r1[F3] = r1[F3], r1[F2] r1[c], r1[b] = -r1[b], -r1[c] r2 = (diff(y(t),t) - eq[1]).match(y(t)*(a*r1[F3] - r1[c]*F1)) if r2: r3 = (diff(z(t),t) - eq[2] == z(t)*(r1[b]*r2[F1] - r2[a]*r1[F2])) if r1 and r2 and r3: return 'type5' return None def check_nonlinear_3eq_order2(eq, func, func_coef): return None @vectorize(0) def odesimp(ode, eq, func, hint): r""" Simplifies solutions of ODEs, including trying to solve for ``func`` and running :py:meth:`~sympy.solvers.ode.constantsimp`. It may use knowledge of the type of solution that the hint returns to apply additional simplifications. It also attempts to integrate any :py:class:`~sympy.integrals.integrals.Integral`\s in the expression, if the hint is not an ``_Integral`` hint. This function should have no effect on expressions returned by :py:meth:`~sympy.solvers.ode.dsolve`, as :py:meth:`~sympy.solvers.ode.dsolve` already calls :py:meth:`~sympy.solvers.ode.ode.odesimp`, but the individual hint functions do not call :py:meth:`~sympy.solvers.ode.ode.odesimp` (because the :py:meth:`~sympy.solvers.ode.dsolve` wrapper does). Therefore, this function is designed for mainly internal use. Examples ======== >>> from sympy import sin, symbols, dsolve, pprint, Function >>> from sympy.solvers.ode.ode import odesimp >>> x, u2, C1= symbols('x,u2,C1') >>> f = Function('f') >>> eq = dsolve(x*f(x).diff(x) - f(x) - x*sin(f(x)/x), f(x), ... hint='1st_homogeneous_coeff_subs_indep_div_dep_Integral', ... simplify=False) >>> pprint(eq, wrap_line=False) x ---- f(x) / | | / 1 \ | -|u1 + -------| | | /1 \| | | sin|--|| | \ \u1// log(f(x)) = log(C1) + | ---------------- d(u1) | 2 | u1 | / >>> pprint(odesimp(eq, f(x), 1, {C1}, ... hint='1st_homogeneous_coeff_subs_indep_div_dep' ... )) #doctest: +SKIP x --------- = C1 /f(x)\ tan|----| \2*x / """ x = func.args[0] f = func.func C1 = get_numbered_constants(eq, num=1) constants = eq.free_symbols - ode.free_symbols # First, integrate if the hint allows it. eq = _handle_Integral(eq, func, hint) if hint.startswith("nth_linear_euler_eq_nonhomogeneous"): eq = simplify(eq) if not isinstance(eq, Equality): raise TypeError("eq should be an instance of Equality") # Second, clean up the arbitrary constants. # Right now, nth linear hints can put as many as 2*order constants in an # expression. If that number grows with another hint, the third argument # here should be raised accordingly, or constantsimp() rewritten to handle # an arbitrary number of constants. eq = constantsimp(eq, constants) # Lastly, now that we have cleaned up the expression, try solving for func. # When CRootOf is implemented in solve(), we will want to return a CRootOf # every time instead of an Equality. # Get the f(x) on the left if possible. if eq.rhs == func and not eq.lhs.has(func): eq = [Eq(eq.rhs, eq.lhs)] # make sure we are working with lists of solutions in simplified form. if eq.lhs == func and not eq.rhs.has(func): # The solution is already solved eq = [eq] else: # The solution is not solved, so try to solve it try: floats = any(i.is_Float for i in eq.atoms(Number)) eqsol = solve(eq, func, force=True, rational=False if floats else None) if not eqsol: raise NotImplementedError except (NotImplementedError, PolynomialError): eq = [eq] else: def _expand(expr): numer, denom = expr.as_numer_denom() if denom.is_Add: return expr else: return powsimp(expr.expand(), combine='exp', deep=True) # XXX: the rest of odesimp() expects each ``t`` to be in a # specific normal form: rational expression with numerator # expanded, but with combined exponential functions (at # least in this setup all tests pass). eq = [Eq(f(x), _expand(t)) for t in eqsol] # special simplification of the lhs. if hint.startswith("1st_homogeneous_coeff"): for j, eqi in enumerate(eq): newi = logcombine(eqi, force=True) if isinstance(newi.lhs, log) and newi.rhs == 0: newi = Eq(newi.lhs.args[0]/C1, C1) eq[j] = newi # We cleaned up the constants before solving to help the solve engine with # a simpler expression, but the solved expression could have introduced # things like -C1, so rerun constantsimp() one last time before returning. for i, eqi in enumerate(eq): eq[i] = constantsimp(eqi, constants) eq[i] = constant_renumber(eq[i], ode.free_symbols) # If there is only 1 solution, return it; # otherwise return the list of solutions. if len(eq) == 1: eq = eq[0] return eq def ode_sol_simplicity(sol, func, trysolving=True): r""" Returns an extended integer representing how simple a solution to an ODE is. The following things are considered, in order from most simple to least: - ``sol`` is solved for ``func``. - ``sol`` is not solved for ``func``, but can be if passed to solve (e.g., a solution returned by ``dsolve(ode, func, simplify=False``). - If ``sol`` is not solved for ``func``, then base the result on the length of ``sol``, as computed by ``len(str(sol))``. - If ``sol`` has any unevaluated :py:class:`~sympy.integrals.integrals.Integral`\s, this will automatically be considered less simple than any of the above. This function returns an integer such that if solution A is simpler than solution B by above metric, then ``ode_sol_simplicity(sola, func) < ode_sol_simplicity(solb, func)``. Currently, the following are the numbers returned, but if the heuristic is ever improved, this may change. Only the ordering is guaranteed. +----------------------------------------------+-------------------+ | Simplicity | Return | +==============================================+===================+ | ``sol`` solved for ``func`` | ``-2`` | +----------------------------------------------+-------------------+ | ``sol`` not solved for ``func`` but can be | ``-1`` | +----------------------------------------------+-------------------+ | ``sol`` is not solved nor solvable for | ``len(str(sol))`` | | ``func`` | | +----------------------------------------------+-------------------+ | ``sol`` contains an | ``oo`` | | :obj:`~sympy.integrals.integrals.Integral` | | +----------------------------------------------+-------------------+ ``oo`` here means the SymPy infinity, which should compare greater than any integer. If you already know :py:meth:`~sympy.solvers.solvers.solve` cannot solve ``sol``, you can use ``trysolving=False`` to skip that step, which is the only potentially slow step. For example, :py:meth:`~sympy.solvers.ode.dsolve` with the ``simplify=False`` flag should do this. If ``sol`` is a list of solutions, if the worst solution in the list returns ``oo`` it returns that, otherwise it returns ``len(str(sol))``, that is, the length of the string representation of the whole list. Examples ======== This function is designed to be passed to ``min`` as the key argument, such as ``min(listofsolutions, key=lambda i: ode_sol_simplicity(i, f(x)))``. >>> from sympy import symbols, Function, Eq, tan, Integral >>> from sympy.solvers.ode.ode import ode_sol_simplicity >>> x, C1, C2 = symbols('x, C1, C2') >>> f = Function('f') >>> ode_sol_simplicity(Eq(f(x), C1*x**2), f(x)) -2 >>> ode_sol_simplicity(Eq(x**2 + f(x), C1), f(x)) -1 >>> ode_sol_simplicity(Eq(f(x), C1*Integral(2*x, x)), f(x)) oo >>> eq1 = Eq(f(x)/tan(f(x)/(2*x)), C1) >>> eq2 = Eq(f(x)/tan(f(x)/(2*x) + f(x)), C2) >>> [ode_sol_simplicity(eq, f(x)) for eq in [eq1, eq2]] [28, 35] >>> min([eq1, eq2], key=lambda i: ode_sol_simplicity(i, f(x))) Eq(f(x)/tan(f(x)/(2*x)), C1) """ # TODO: if two solutions are solved for f(x), we still want to be # able to get the simpler of the two # See the docstring for the coercion rules. We check easier (faster) # things here first, to save time. if iterable(sol): # See if there are Integrals for i in sol: if ode_sol_simplicity(i, func, trysolving=trysolving) == oo: return oo return len(str(sol)) if sol.has(Integral): return oo # Next, try to solve for func. This code will change slightly when CRootOf # is implemented in solve(). Probably a CRootOf solution should fall # somewhere between a normal solution and an unsolvable expression. # First, see if they are already solved if sol.lhs == func and not sol.rhs.has(func) or \ sol.rhs == func and not sol.lhs.has(func): return -2 # We are not so lucky, try solving manually if trysolving: try: sols = solve(sol, func) if not sols: raise NotImplementedError except NotImplementedError: pass else: return -1 # Finally, a naive computation based on the length of the string version # of the expression. This may favor combined fractions because they # will not have duplicate denominators, and may slightly favor expressions # with fewer additions and subtractions, as those are separated by spaces # by the printer. # Additional ideas for simplicity heuristics are welcome, like maybe # checking if a equation has a larger domain, or if constantsimp has # introduced arbitrary constants numbered higher than the order of a # given ODE that sol is a solution of. return len(str(sol)) def _extract_funcs(eqs): funcs = [] for eq in eqs: derivs = [node for node in preorder_traversal(eq) if isinstance(node, Derivative)] func = [] for d in derivs: func += list(d.atoms(AppliedUndef)) for func_ in func: funcs.append(func_) funcs = list(uniq(funcs)) return funcs def _get_constant_subexpressions(expr, Cs): Cs = set(Cs) Ces = [] def _recursive_walk(expr): expr_syms = expr.free_symbols if expr_syms and expr_syms.issubset(Cs): Ces.append(expr) else: if expr.func == exp: expr = expr.expand(mul=True) if expr.func in (Add, Mul): d = sift(expr.args, lambda i : i.free_symbols.issubset(Cs)) if len(d[True]) > 1: x = expr.func(*d[True]) if not x.is_number: Ces.append(x) elif isinstance(expr, Integral): if expr.free_symbols.issubset(Cs) and \ all(len(x) == 3 for x in expr.limits): Ces.append(expr) for i in expr.args: _recursive_walk(i) return _recursive_walk(expr) return Ces def __remove_linear_redundancies(expr, Cs): cnts = {i: expr.count(i) for i in Cs} Cs = [i for i in Cs if cnts[i] > 0] def _linear(expr): if isinstance(expr, Add): xs = [i for i in Cs if expr.count(i)==cnts[i] \ and 0 == expr.diff(i, 2)] d = {} for x in xs: y = expr.diff(x) if y not in d: d[y]=[] d[y].append(x) for y in d: if len(d[y]) > 1: d[y].sort(key=str) for x in d[y][1:]: expr = expr.subs(x, 0) return expr def _recursive_walk(expr): if len(expr.args) != 0: expr = expr.func(*[_recursive_walk(i) for i in expr.args]) expr = _linear(expr) return expr if isinstance(expr, Equality): lhs, rhs = [_recursive_walk(i) for i in expr.args] f = lambda i: isinstance(i, Number) or i in Cs if isinstance(lhs, Symbol) and lhs in Cs: rhs, lhs = lhs, rhs if lhs.func in (Add, Symbol) and rhs.func in (Add, Symbol): dlhs = sift([lhs] if isinstance(lhs, AtomicExpr) else lhs.args, f) drhs = sift([rhs] if isinstance(rhs, AtomicExpr) else rhs.args, f) for i in [True, False]: for hs in [dlhs, drhs]: if i not in hs: hs[i] = [0] # this calculation can be simplified lhs = Add(*dlhs[False]) - Add(*drhs[False]) rhs = Add(*drhs[True]) - Add(*dlhs[True]) elif lhs.func in (Mul, Symbol) and rhs.func in (Mul, Symbol): dlhs = sift([lhs] if isinstance(lhs, AtomicExpr) else lhs.args, f) if True in dlhs: if False not in dlhs: dlhs[False] = [1] lhs = Mul(*dlhs[False]) rhs = rhs/Mul(*dlhs[True]) return Eq(lhs, rhs) else: return _recursive_walk(expr) @vectorize(0) def constantsimp(expr, constants): r""" Simplifies an expression with arbitrary constants in it. This function is written specifically to work with :py:meth:`~sympy.solvers.ode.dsolve`, and is not intended for general use. Simplification is done by "absorbing" the arbitrary constants into other arbitrary constants, numbers, and symbols that they are not independent of. The symbols must all have the same name with numbers after it, for example, ``C1``, ``C2``, ``C3``. The ``symbolname`` here would be '``C``', the ``startnumber`` would be 1, and the ``endnumber`` would be 3. If the arbitrary constants are independent of the variable ``x``, then the independent symbol would be ``x``. There is no need to specify the dependent function, such as ``f(x)``, because it already has the independent symbol, ``x``, in it. Because terms are "absorbed" into arbitrary constants and because constants are renumbered after simplifying, the arbitrary constants in expr are not necessarily equal to the ones of the same name in the returned result. If two or more arbitrary constants are added, multiplied, or raised to the power of each other, they are first absorbed together into a single arbitrary constant. Then the new constant is combined into other terms if necessary. Absorption of constants is done with limited assistance: 1. terms of :py:class:`~sympy.core.add.Add`\s are collected to try join constants so `e^x (C_1 \cos(x) + C_2 \cos(x))` will simplify to `e^x C_1 \cos(x)`; 2. powers with exponents that are :py:class:`~sympy.core.add.Add`\s are expanded so `e^{C_1 + x}` will be simplified to `C_1 e^x`. Use :py:meth:`~sympy.solvers.ode.ode.constant_renumber` to renumber constants after simplification or else arbitrary numbers on constants may appear, e.g. `C_1 + C_3 x`. In rare cases, a single constant can be "simplified" into two constants. Every differential equation solution should have as many arbitrary constants as the order of the differential equation. The result here will be technically correct, but it may, for example, have `C_1` and `C_2` in an expression, when `C_1` is actually equal to `C_2`. Use your discretion in such situations, and also take advantage of the ability to use hints in :py:meth:`~sympy.solvers.ode.dsolve`. Examples ======== >>> from sympy import symbols >>> from sympy.solvers.ode.ode import constantsimp >>> C1, C2, C3, x, y = symbols('C1, C2, C3, x, y') >>> constantsimp(2*C1*x, {C1, C2, C3}) C1*x >>> constantsimp(C1 + 2 + x, {C1, C2, C3}) C1 + x >>> constantsimp(C1*C2 + 2 + C2 + C3*x, {C1, C2, C3}) C1 + C3*x """ # This function works recursively. The idea is that, for Mul, # Add, Pow, and Function, if the class has a constant in it, then # we can simplify it, which we do by recursing down and # simplifying up. Otherwise, we can skip that part of the # expression. Cs = constants orig_expr = expr constant_subexprs = _get_constant_subexpressions(expr, Cs) for xe in constant_subexprs: xes = list(xe.free_symbols) if not xes: continue if all(expr.count(c) == xe.count(c) for c in xes): xes.sort(key=str) expr = expr.subs(xe, xes[0]) # try to perform common sub-expression elimination of constant terms try: commons, rexpr = cse(expr) commons.reverse() rexpr = rexpr[0] for s in commons: cs = list(s[1].atoms(Symbol)) if len(cs) == 1 and cs[0] in Cs and \ cs[0] not in rexpr.atoms(Symbol) and \ not any(cs[0] in ex for ex in commons if ex != s): rexpr = rexpr.subs(s[0], cs[0]) else: rexpr = rexpr.subs(*s) expr = rexpr except IndexError: pass expr = __remove_linear_redundancies(expr, Cs) def _conditional_term_factoring(expr): new_expr = terms_gcd(expr, clear=False, deep=True, expand=False) # we do not want to factor exponentials, so handle this separately if new_expr.is_Mul: infac = False asfac = False for m in new_expr.args: if isinstance(m, exp): asfac = True elif m.is_Add: infac = any(isinstance(fi, exp) for t in m.args for fi in Mul.make_args(t)) if asfac and infac: new_expr = expr break return new_expr expr = _conditional_term_factoring(expr) # call recursively if more simplification is possible if orig_expr != expr: return constantsimp(expr, Cs) return expr def constant_renumber(expr, variables=None, newconstants=None): r""" Renumber arbitrary constants in ``expr`` to use the symbol names as given in ``newconstants``. In the process, this reorders expression terms in a standard way. If ``newconstants`` is not provided then the new constant names will be ``C1``, ``C2`` etc. Otherwise ``newconstants`` should be an iterable giving the new symbols to use for the constants in order. The ``variables`` argument is a list of non-constant symbols. All other free symbols found in ``expr`` are assumed to be constants and will be renumbered. If ``variables`` is not given then any numbered symbol beginning with ``C`` (e.g. ``C1``) is assumed to be a constant. Symbols are renumbered based on ``.sort_key()``, so they should be numbered roughly in the order that they appear in the final, printed expression. Note that this ordering is based in part on hashes, so it can produce different results on different machines. The structure of this function is very similar to that of :py:meth:`~sympy.solvers.ode.constantsimp`. Examples ======== >>> from sympy import symbols >>> from sympy.solvers.ode.ode import constant_renumber >>> x, C1, C2, C3 = symbols('x,C1:4') >>> expr = C3 + C2*x + C1*x**2 >>> expr C1*x**2 + C2*x + C3 >>> constant_renumber(expr) C1 + C2*x + C3*x**2 The ``variables`` argument specifies which are constants so that the other symbols will not be renumbered: >>> constant_renumber(expr, [C1, x]) C1*x**2 + C2 + C3*x The ``newconstants`` argument is used to specify what symbols to use when replacing the constants: >>> constant_renumber(expr, [x], newconstants=symbols('E1:4')) E1 + E2*x + E3*x**2 """ # System of expressions if isinstance(expr, (set, list, tuple)): return type(expr)(constant_renumber(Tuple(*expr), variables=variables, newconstants=newconstants)) # Symbols in solution but not ODE are constants if variables is not None: variables = set(variables) free_symbols = expr.free_symbols constantsymbols = list(free_symbols - variables) # Any Cn is a constant... else: variables = set() isconstant = lambda s: s.startswith('C') and s[1:].isdigit() constantsymbols = [sym for sym in expr.free_symbols if isconstant(sym.name)] # Find new constants checking that they aren't already in the ODE if newconstants is None: iter_constants = numbered_symbols(start=1, prefix='C', exclude=variables) else: iter_constants = (sym for sym in newconstants if sym not in variables) constants_found = [] # make a mapping to send all constantsymbols to S.One and use # that to make sure that term ordering is not dependent on # the indexed value of C C_1 = [(ci, S.One) for ci in constantsymbols] sort_key=lambda arg: default_sort_key(arg.subs(C_1)) def _constant_renumber(expr): r""" We need to have an internal recursive function """ # For system of expressions if isinstance(expr, Tuple): renumbered = [_constant_renumber(e) for e in expr] return Tuple(*renumbered) if isinstance(expr, Equality): return Eq( _constant_renumber(expr.lhs), _constant_renumber(expr.rhs)) if type(expr) not in (Mul, Add, Pow) and not expr.is_Function and \ not expr.has(*constantsymbols): # Base case, as above. Hope there aren't constants inside # of some other class, because they won't be renumbered. return expr elif expr.is_Piecewise: return expr elif expr in constantsymbols: if expr not in constants_found: constants_found.append(expr) return expr elif expr.is_Function or expr.is_Pow: return expr.func( *[_constant_renumber(x) for x in expr.args]) else: sortedargs = list(expr.args) sortedargs.sort(key=sort_key) return expr.func(*[_constant_renumber(x) for x in sortedargs]) expr = _constant_renumber(expr) # Don't renumber symbols present in the ODE. constants_found = [c for c in constants_found if c not in variables] # Renumbering happens here subs_dict = {var: cons for var, cons in zip(constants_found, iter_constants)} expr = expr.subs(subs_dict, simultaneous=True) return expr def _handle_Integral(expr, func, hint): r""" Converts a solution with Integrals in it into an actual solution. For most hints, this simply runs ``expr.doit()``. """ if hint == "nth_linear_constant_coeff_homogeneous": sol = expr elif not hint.endswith("_Integral"): sol = expr.doit() else: sol = expr return sol # XXX: Should this function maybe go somewhere else? def homogeneous_order(eq, *symbols): r""" Returns the order `n` if `g` is homogeneous and ``None`` if it is not homogeneous. Determines if a function is homogeneous and if so of what order. A function `f(x, y, \cdots)` is homogeneous of order `n` if `f(t x, t y, \cdots) = t^n f(x, y, \cdots)`. If the function is of two variables, `F(x, y)`, then `f` being homogeneous of any order is equivalent to being able to rewrite `F(x, y)` as `G(x/y)` or `H(y/x)`. This fact is used to solve 1st order ordinary differential equations whose coefficients are homogeneous of the same order (see the docstrings of :obj:`~sympy.solvers.ode.single.HomogeneousCoeffSubsDepDivIndep` and :obj:`~sympy.solvers.ode.single.HomogeneousCoeffSubsIndepDivDep`). Symbols can be functions, but every argument of the function must be a symbol, and the arguments of the function that appear in the expression must match those given in the list of symbols. If a declared function appears with different arguments than given in the list of symbols, ``None`` is returned. Examples ======== >>> from sympy import Function, homogeneous_order, sqrt >>> from sympy.abc import x, y >>> f = Function('f') >>> homogeneous_order(f(x), f(x)) is None True >>> homogeneous_order(f(x,y), f(y, x), x, y) is None True >>> homogeneous_order(f(x), f(x), x) 1 >>> homogeneous_order(x**2*f(x)/sqrt(x**2+f(x)**2), x, f(x)) 2 >>> homogeneous_order(x**2+f(x), x, f(x)) is None True """ if not symbols: raise ValueError("homogeneous_order: no symbols were given.") symset = set(symbols) eq = sympify(eq) # The following are not supported if eq.has(Order, Derivative): return None # These are all constants if (eq.is_Number or eq.is_NumberSymbol or eq.is_number ): return S.Zero # Replace all functions with dummy variables dum = numbered_symbols(prefix='d', cls=Dummy) newsyms = set() for i in [j for j in symset if getattr(j, 'is_Function')]: iargs = set(i.args) if iargs.difference(symset): return None else: dummyvar = next(dum) eq = eq.subs(i, dummyvar) symset.remove(i) newsyms.add(dummyvar) symset.update(newsyms) if not eq.free_symbols & symset: return None # assuming order of a nested function can only be equal to zero if isinstance(eq, Function): return None if homogeneous_order( eq.args[0], *tuple(symset)) != 0 else S.Zero # make the replacement of x with x*t and see if t can be factored out t = Dummy('t', positive=True) # It is sufficient that t > 0 eqs = separatevars(eq.subs([(i, t*i) for i in symset]), [t], dict=True)[t] if eqs is S.One: return S.Zero # there was no term with only t i, d = eqs.as_independent(t, as_Add=False) b, e = d.as_base_exp() if b == t: return e def ode_2nd_power_series_ordinary(eq, func, order, match): r""" Gives a power series solution to a second order homogeneous differential equation with polynomial coefficients at an ordinary point. A homogeneous differential equation is of the form .. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) y(x) = 0 For simplicity it is assumed that `P(x)`, `Q(x)` and `R(x)` are polynomials, it is sufficient that `\frac{Q(x)}{P(x)}` and `\frac{R(x)}{P(x)}` exists at `x_{0}`. A recurrence relation is obtained by substituting `y` as `\sum_{n=0}^\infty a_{n}x^{n}`, in the differential equation, and equating the nth term. Using this relation various terms can be generated. Examples ======== >>> from sympy import dsolve, Function, pprint >>> from sympy.abc import x >>> f = Function("f") >>> eq = f(x).diff(x, 2) + f(x) >>> pprint(dsolve(eq, hint='2nd_power_series_ordinary')) / 4 2 \ / 2\ |x x | | x | / 6\ f(x) = C2*|-- - -- + 1| + C1*x*|1 - --| + O\x / \24 2 / \ 6 / References ========== - http://tutorial.math.lamar.edu/Classes/DE/SeriesSolutions.aspx - George E. Simmons, "Differential Equations with Applications and Historical Notes", p.p 176 - 184 """ x = func.args[0] f = func.func C0, C1 = get_numbered_constants(eq, num=2) n = Dummy("n", integer=True) s = Wild("s") k = Wild("k", exclude=[x]) x0 = match['x0'] terms = match['terms'] p = match[match['a3']] q = match[match['b3']] r = match[match['c3']] seriesdict = {} recurr = Function("r") # Generating the recurrence relation which works this way: # for the second order term the summation begins at n = 2. The coefficients # p is multiplied with an*(n - 1)*(n - 2)*x**n-2 and a substitution is made such that # the exponent of x becomes n. # For example, if p is x, then the second degree recurrence term is # an*(n - 1)*(n - 2)*x**n-1, substituting (n - 1) as n, it transforms to # an+1*n*(n - 1)*x**n. # A similar process is done with the first order and zeroth order term. coefflist = [(recurr(n), r), (n*recurr(n), q), (n*(n - 1)*recurr(n), p)] for index, coeff in enumerate(coefflist): if coeff[1]: f2 = powsimp(expand((coeff[1]*(x - x0)**(n - index)).subs(x, x + x0))) if f2.is_Add: addargs = f2.args else: addargs = [f2] for arg in addargs: powm = arg.match(s*x**k) term = coeff[0]*powm[s] if not powm[k].is_Symbol: term = term.subs(n, n - powm[k].as_independent(n)[0]) startind = powm[k].subs(n, index) # Seeing if the startterm can be reduced further. # If it vanishes for n lesser than startind, it is # equal to summation from n. if startind: for i in reversed(range(startind)): if not term.subs(n, i): seriesdict[term] = i else: seriesdict[term] = i + 1 break else: seriesdict[term] = S.Zero # Stripping of terms so that the sum starts with the same number. teq = S.Zero suminit = seriesdict.values() rkeys = seriesdict.keys() req = Add(*rkeys) if any(suminit): maxval = max(suminit) for term in seriesdict: val = seriesdict[term] if val != maxval: for i in range(val, maxval): teq += term.subs(n, val) finaldict = {} if teq: fargs = teq.atoms(AppliedUndef) if len(fargs) == 1: finaldict[fargs.pop()] = 0 else: maxf = max(fargs, key = lambda x: x.args[0]) sol = solve(teq, maxf) if isinstance(sol, list): sol = sol[0] finaldict[maxf] = sol # Finding the recurrence relation in terms of the largest term. fargs = req.atoms(AppliedUndef) maxf = max(fargs, key = lambda x: x.args[0]) minf = min(fargs, key = lambda x: x.args[0]) if minf.args[0].is_Symbol: startiter = 0 else: startiter = -minf.args[0].as_independent(n)[0] lhs = maxf rhs = solve(req, maxf) if isinstance(rhs, list): rhs = rhs[0] # Checking how many values are already present tcounter = len([t for t in finaldict.values() if t]) for _ in range(tcounter, terms - 3): # Assuming c0 and c1 to be arbitrary check = rhs.subs(n, startiter) nlhs = lhs.subs(n, startiter) nrhs = check.subs(finaldict) finaldict[nlhs] = nrhs startiter += 1 # Post processing series = C0 + C1*(x - x0) for term in finaldict: if finaldict[term]: fact = term.args[0] series += (finaldict[term].subs([(recurr(0), C0), (recurr(1), C1)])*( x - x0)**fact) series = collect(expand_mul(series), [C0, C1]) + Order(x**terms) return Eq(f(x), series) def ode_2nd_power_series_regular(eq, func, order, match): r""" Gives a power series solution to a second order homogeneous differential equation with polynomial coefficients at a regular point. A second order homogeneous differential equation is of the form .. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) y(x) = 0 A point is said to regular singular at `x0` if `x - x0\frac{Q(x)}{P(x)}` and `(x - x0)^{2}\frac{R(x)}{P(x)}` are analytic at `x0`. For simplicity `P(x)`, `Q(x)` and `R(x)` are assumed to be polynomials. The algorithm for finding the power series solutions is: 1. Try expressing `(x - x0)P(x)` and `((x - x0)^{2})Q(x)` as power series solutions about x0. Find `p0` and `q0` which are the constants of the power series expansions. 2. Solve the indicial equation `f(m) = m(m - 1) + m*p0 + q0`, to obtain the roots `m1` and `m2` of the indicial equation. 3. If `m1 - m2` is a non integer there exists two series solutions. If `m1 = m2`, there exists only one solution. If `m1 - m2` is an integer, then the existence of one solution is confirmed. The other solution may or may not exist. The power series solution is of the form `x^{m}\sum_{n=0}^\infty a_{n}x^{n}`. The coefficients are determined by the following recurrence relation. `a_{n} = -\frac{\sum_{k=0}^{n-1} q_{n-k} + (m + k)p_{n-k}}{f(m + n)}`. For the case in which `m1 - m2` is an integer, it can be seen from the recurrence relation that for the lower root `m`, when `n` equals the difference of both the roots, the denominator becomes zero. So if the numerator is not equal to zero, a second series solution exists. Examples ======== >>> from sympy import dsolve, Function, pprint >>> from sympy.abc import x >>> f = Function("f") >>> eq = x*(f(x).diff(x, 2)) + 2*(f(x).diff(x)) + x*f(x) >>> pprint(dsolve(eq, hint='2nd_power_series_regular')) / 6 4 2 \ | x x x | / 4 2 \ C1*|- --- + -- - -- + 1| | x x | \ 720 24 2 / / 6\ f(x) = C2*|--- - -- + 1| + ------------------------ + O\x / \120 6 / x References ========== - George E. Simmons, "Differential Equations with Applications and Historical Notes", p.p 176 - 184 """ x = func.args[0] f = func.func C0, C1 = get_numbered_constants(eq, num=2) m = Dummy("m") # for solving the indicial equation x0 = match['x0'] terms = match['terms'] p = match['p'] q = match['q'] # Generating the indicial equation indicial = [] for term in [p, q]: if not term.has(x): indicial.append(term) else: term = series(term, x=x, n=1, x0=x0) if isinstance(term, Order): indicial.append(S.Zero) else: for arg in term.args: if not arg.has(x): indicial.append(arg) break p0, q0 = indicial sollist = solve(m*(m - 1) + m*p0 + q0, m) if sollist and isinstance(sollist, list) and all( sol.is_real for sol in sollist): serdict1 = {} serdict2 = {} if len(sollist) == 1: # Only one series solution exists in this case. m1 = m2 = sollist.pop() if terms-m1-1 <= 0: return Eq(f(x), Order(terms)) serdict1 = _frobenius(terms-m1-1, m1, p0, q0, p, q, x0, x, C0) else: m1 = sollist[0] m2 = sollist[1] if m1 < m2: m1, m2 = m2, m1 # Irrespective of whether m1 - m2 is an integer or not, one # Frobenius series solution exists. serdict1 = _frobenius(terms-m1-1, m1, p0, q0, p, q, x0, x, C0) if not (m1 - m2).is_integer: # Second frobenius series solution exists. serdict2 = _frobenius(terms-m2-1, m2, p0, q0, p, q, x0, x, C1) else: # Check if second frobenius series solution exists. serdict2 = _frobenius(terms-m2-1, m2, p0, q0, p, q, x0, x, C1, check=m1) if serdict1: finalseries1 = C0 for key in serdict1: power = int(key.name[1:]) finalseries1 += serdict1[key]*(x - x0)**power finalseries1 = (x - x0)**m1*finalseries1 finalseries2 = S.Zero if serdict2: for key in serdict2: power = int(key.name[1:]) finalseries2 += serdict2[key]*(x - x0)**power finalseries2 += C1 finalseries2 = (x - x0)**m2*finalseries2 return Eq(f(x), collect(finalseries1 + finalseries2, [C0, C1]) + Order(x**terms)) def _frobenius(n, m, p0, q0, p, q, x0, x, c, check=None): r""" Returns a dict with keys as coefficients and values as their values in terms of C0 """ n = int(n) # In cases where m1 - m2 is not an integer m2 = check d = Dummy("d") numsyms = numbered_symbols("C", start=0) numsyms = [next(numsyms) for i in range(n + 1)] serlist = [] for ser in [p, q]: # Order term not present if ser.is_polynomial(x) and Poly(ser, x).degree() <= n: if x0: ser = ser.subs(x, x + x0) dict_ = Poly(ser, x).as_dict() # Order term present else: tseries = series(ser, x=x0, n=n+1) # Removing order dict_ = Poly(list(ordered(tseries.args))[: -1], x).as_dict() # Fill in with zeros, if coefficients are zero. for i in range(n + 1): if (i,) not in dict_: dict_[(i,)] = S.Zero serlist.append(dict_) pseries = serlist[0] qseries = serlist[1] indicial = d*(d - 1) + d*p0 + q0 frobdict = {} for i in range(1, n + 1): num = c*(m*pseries[(i,)] + qseries[(i,)]) for j in range(1, i): sym = Symbol("C" + str(j)) num += frobdict[sym]*((m + j)*pseries[(i - j,)] + qseries[(i - j,)]) # Checking for cases when m1 - m2 is an integer. If num equals zero # then a second Frobenius series solution cannot be found. If num is not zero # then set constant as zero and proceed. if m2 is not None and i == m2 - m: if num: return False else: frobdict[numsyms[i]] = S.Zero else: frobdict[numsyms[i]] = -num/(indicial.subs(d, m+i)) return frobdict def _remove_redundant_solutions(eq, solns, order, var): r""" Remove redundant solutions from the set of solutions. This function is needed because otherwise dsolve can return redundant solutions. As an example consider: eq = Eq((f(x).diff(x, 2))*f(x).diff(x), 0) There are two ways to find solutions to eq. The first is to solve f(x).diff(x, 2) = 0 leading to solution f(x)=C1 + C2*x. The second is to solve the equation f(x).diff(x) = 0 leading to the solution f(x) = C1. In this particular case we then see that the second solution is a special case of the first and we do not want to return it. This does not always happen. If we have eq = Eq((f(x)**2-4)*(f(x).diff(x)-4), 0) then we get the algebraic solution f(x) = [-2, 2] and the integral solution f(x) = x + C1 and in this case the two solutions are not equivalent wrt initial conditions so both should be returned. """ def is_special_case_of(soln1, soln2): return _is_special_case_of(soln1, soln2, eq, order, var) unique_solns = [] for soln1 in solns: for soln2 in unique_solns[:]: if is_special_case_of(soln1, soln2): break elif is_special_case_of(soln2, soln1): unique_solns.remove(soln2) else: unique_solns.append(soln1) return unique_solns def _is_special_case_of(soln1, soln2, eq, order, var): r""" True if soln1 is found to be a special case of soln2 wrt some value of the constants that appear in soln2. False otherwise. """ # The solutions returned by dsolve may be given explicitly or implicitly. # We will equate the sol1=(soln1.rhs - soln1.lhs), sol2=(soln2.rhs - soln2.lhs) # of the two solutions. # # Since this is supposed to hold for all x it also holds for derivatives. # For an order n ode we should be able to differentiate # each solution n times to get n+1 equations. # # We then try to solve those n+1 equations for the integrations constants # in sol2. If we can find a solution that doesn't depend on x then it # means that some value of the constants in sol1 is a special case of # sol2 corresponding to a particular choice of the integration constants. # In case the solution is in implicit form we subtract the sides soln1 = soln1.rhs - soln1.lhs soln2 = soln2.rhs - soln2.lhs # Work for the series solution if soln1.has(Order) and soln2.has(Order): if soln1.getO() == soln2.getO(): soln1 = soln1.removeO() soln2 = soln2.removeO() else: return False elif soln1.has(Order) or soln2.has(Order): return False constants1 = soln1.free_symbols.difference(eq.free_symbols) constants2 = soln2.free_symbols.difference(eq.free_symbols) constants1_new = get_numbered_constants(Tuple(soln1, soln2), len(constants1)) if len(constants1) == 1: constants1_new = {constants1_new} for c_old, c_new in zip(constants1, constants1_new): soln1 = soln1.subs(c_old, c_new) # n equations for sol1 = sol2, sol1'=sol2', ... lhs = soln1 rhs = soln2 eqns = [Eq(lhs, rhs)] for n in range(1, order): lhs = lhs.diff(var) rhs = rhs.diff(var) eq = Eq(lhs, rhs) eqns.append(eq) # BooleanTrue/False awkwardly show up for trivial equations if any(isinstance(eq, BooleanFalse) for eq in eqns): return False eqns = [eq for eq in eqns if not isinstance(eq, BooleanTrue)] try: constant_solns = solve(eqns, constants2) except NotImplementedError: return False # Sometimes returns a dict and sometimes a list of dicts if isinstance(constant_solns, dict): constant_solns = [constant_solns] # after solving the issue 17418, maybe we don't need the following checksol code. for constant_soln in constant_solns: for eq in eqns: eq=eq.rhs-eq.lhs if checksol(eq, constant_soln) is not True: return False # If any solution gives all constants as expressions that don't depend on # x then there exists constants for soln2 that give soln1 for constant_soln in constant_solns: if not any(c.has(var) for c in constant_soln.values()): return True return False def ode_1st_power_series(eq, func, order, match): r""" The power series solution is a method which gives the Taylor series expansion to the solution of a differential equation. For a first order differential equation `\frac{dy}{dx} = h(x, y)`, a power series solution exists at a point `x = x_{0}` if `h(x, y)` is analytic at `x_{0}`. The solution is given by .. math:: y(x) = y(x_{0}) + \sum_{n = 1}^{\infty} \frac{F_{n}(x_{0},b)(x - x_{0})^n}{n!}, where `y(x_{0}) = b` is the value of y at the initial value of `x_{0}`. To compute the values of the `F_{n}(x_{0},b)` the following algorithm is followed, until the required number of terms are generated. 1. `F_1 = h(x_{0}, b)` 2. `F_{n+1} = \frac{\partial F_{n}}{\partial x} + \frac{\partial F_{n}}{\partial y}F_{1}` Examples ======== >>> from sympy import Function, pprint, exp >>> from sympy.solvers.ode.ode import dsolve >>> from sympy.abc import x >>> f = Function('f') >>> eq = exp(x)*(f(x).diff(x)) - f(x) >>> pprint(dsolve(eq, hint='1st_power_series')) 3 4 5 C1*x C1*x C1*x / 6\ f(x) = C1 + C1*x - ----- + ----- + ----- + O\x / 6 24 60 References ========== - Travis W. Walker, Analytic power series technique for solving first-order differential equations, p.p 17, 18 """ x = func.args[0] y = match['y'] f = func.func h = -match[match['d']]/match[match['e']] point = match['f0'] value = match['f0val'] terms = match['terms'] # First term F = h if not h: return Eq(f(x), value) # Initialization series = value if terms > 1: hc = h.subs({x: point, y: value}) if hc.has(oo) or hc.has(nan) or hc.has(zoo): # Derivative does not exist, not analytic return Eq(f(x), oo) elif hc: series += hc*(x - point) for factcount in range(2, terms): Fnew = F.diff(x) + F.diff(y)*h Fnewc = Fnew.subs({x: point, y: value}) # Same logic as above if Fnewc.has(oo) or Fnewc.has(nan) or Fnewc.has(-oo) or Fnewc.has(zoo): return Eq(f(x), oo) series += Fnewc*((x - point)**factcount)/factorial(factcount) F = Fnew series += Order(x**terms) return Eq(f(x), series) def checkinfsol(eq, infinitesimals, func=None, order=None): r""" This function is used to check if the given infinitesimals are the actual infinitesimals of the given first order differential equation. This method is specific to the Lie Group Solver of ODEs. As of now, it simply checks, by substituting the infinitesimals in the partial differential equation. .. math:: \frac{\partial \eta}{\partial x} + \left(\frac{\partial \eta}{\partial y} - \frac{\partial \xi}{\partial x}\right)*h - \frac{\partial \xi}{\partial y}*h^{2} - \xi\frac{\partial h}{\partial x} - \eta\frac{\partial h}{\partial y} = 0 where `\eta`, and `\xi` are the infinitesimals and `h(x,y) = \frac{dy}{dx}` The infinitesimals should be given in the form of a list of dicts ``[{xi(x, y): inf, eta(x, y): inf}]``, corresponding to the output of the function infinitesimals. It returns a list of values of the form ``[(True/False, sol)]`` where ``sol`` is the value obtained after substituting the infinitesimals in the PDE. If it is ``True``, then ``sol`` would be 0. """ if isinstance(eq, Equality): eq = eq.lhs - eq.rhs if not func: eq, func = _preprocess(eq) variables = func.args if len(variables) != 1: raise ValueError("ODE's have only one independent variable") else: x = variables[0] if not order: order = ode_order(eq, func) if order != 1: raise NotImplementedError("Lie groups solver has been implemented " "only for first order differential equations") else: df = func.diff(x) a = Wild('a', exclude = [df]) b = Wild('b', exclude = [df]) match = collect(expand(eq), df).match(a*df + b) if match: h = -simplify(match[b]/match[a]) else: try: sol = solve(eq, df) except NotImplementedError: raise NotImplementedError("Infinitesimals for the " "first order ODE could not be found") else: h = sol[0] # Find infinitesimals for one solution y = Dummy('y') h = h.subs(func, y) xi = Function('xi')(x, y) eta = Function('eta')(x, y) dxi = Function('xi')(x, func) deta = Function('eta')(x, func) pde = (eta.diff(x) + (eta.diff(y) - xi.diff(x))*h - (xi.diff(y))*h**2 - xi*(h.diff(x)) - eta*(h.diff(y))) soltup = [] for sol in infinitesimals: tsol = {xi: S(sol[dxi]).subs(func, y), eta: S(sol[deta]).subs(func, y)} sol = simplify(pde.subs(tsol).doit()) if sol: soltup.append((False, sol.subs(y, func))) else: soltup.append((True, 0)) return soltup def sysode_linear_2eq_order1(match_): x = match_['func'][0].func y = match_['func'][1].func func = match_['func'] fc = match_['func_coeff'] eq = match_['eq'] r = dict() t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] for i in range(2): eqs = 0 for terms in Add.make_args(eq[i]): eqs += terms/fc[i,func[i],1] eq[i] = eqs # for equations Eq(a1*diff(x(t),t), a*x(t) + b*y(t) + k1) # and Eq(a2*diff(x(t),t), c*x(t) + d*y(t) + k2) r['a'] = -fc[0,x(t),0]/fc[0,x(t),1] r['c'] = -fc[1,x(t),0]/fc[1,y(t),1] r['b'] = -fc[0,y(t),0]/fc[0,x(t),1] r['d'] = -fc[1,y(t),0]/fc[1,y(t),1] forcing = [S.Zero,S.Zero] for i in range(2): for j in Add.make_args(eq[i]): if not j.has(x(t), y(t)): forcing[i] += j if not (forcing[0].has(t) or forcing[1].has(t)): r['k1'] = forcing[0] r['k2'] = forcing[1] else: raise NotImplementedError("Only homogeneous problems are supported" + " (and constant inhomogeneity)") if match_['type_of_equation'] == 'type6': sol = _linear_2eq_order1_type6(x, y, t, r, eq) if match_['type_of_equation'] == 'type7': sol = _linear_2eq_order1_type7(x, y, t, r, eq) return sol def _linear_2eq_order1_type6(x, y, t, r, eq): r""" The equations of this type of ode are . .. math:: x' = f(t) x + g(t) y .. math:: y' = a [f(t) + a h(t)] x + a [g(t) - h(t)] y This is solved by first multiplying the first equation by `-a` and adding it to the second equation to obtain .. math:: y' - a x' = -a h(t) (y - a x) Setting `U = y - ax` and integrating the equation we arrive at .. math:: y - ax = C_1 e^{-a \int h(t) \,dt} and on substituting the value of y in first equation give rise to first order ODEs. After solving for `x`, we can obtain `y` by substituting the value of `x` in second equation. """ C1, C2, C3, C4 = get_numbered_constants(eq, num=4) p = 0 q = 0 p1 = cancel(r['c']/cancel(r['c']/r['d']).as_numer_denom()[0]) p2 = cancel(r['a']/cancel(r['a']/r['b']).as_numer_denom()[0]) for n, i in enumerate([p1, p2]): for j in Mul.make_args(collect_const(i)): if not j.has(t): q = j if q!=0 and n==0: if ((r['c']/j - r['a'])/(r['b'] - r['d']/j)) == j: p = 1 s = j break if q!=0 and n==1: if ((r['a']/j - r['c'])/(r['d'] - r['b']/j)) == j: p = 2 s = j break if p == 1: equ = diff(x(t),t) - r['a']*x(t) - r['b']*(s*x(t) + C1*exp(-s*Integral(r['b'] - r['d']/s, t))) hint1 = classify_ode(equ)[1] sol1 = dsolve(equ, hint=hint1+'_Integral').rhs sol2 = s*sol1 + C1*exp(-s*Integral(r['b'] - r['d']/s, t)) elif p ==2: equ = diff(y(t),t) - r['c']*y(t) - r['d']*s*y(t) + C1*exp(-s*Integral(r['d'] - r['b']/s, t)) hint1 = classify_ode(equ)[1] sol2 = dsolve(equ, hint=hint1+'_Integral').rhs sol1 = s*sol2 + C1*exp(-s*Integral(r['d'] - r['b']/s, t)) return [Eq(x(t), sol1), Eq(y(t), sol2)] def _linear_2eq_order1_type7(x, y, t, r, eq): r""" The equations of this type of ode are . .. math:: x' = f(t) x + g(t) y .. math:: y' = h(t) x + p(t) y Differentiating the first equation and substituting the value of `y` from second equation will give a second-order linear equation .. math:: g x'' - (fg + gp + g') x' + (fgp - g^{2} h + f g' - f' g) x = 0 This above equation can be easily integrated if following conditions are satisfied. 1. `fgp - g^{2} h + f g' - f' g = 0` 2. `fgp - g^{2} h + f g' - f' g = ag, fg + gp + g' = bg` If first condition is satisfied then it is solved by current dsolve solver and in second case it becomes a constant coefficient differential equation which is also solved by current solver. Otherwise if the above condition fails then, a particular solution is assumed as `x = x_0(t)` and `y = y_0(t)` Then the general solution is expressed as .. math:: x = C_1 x_0(t) + C_2 x_0(t) \int \frac{g(t) F(t) P(t)}{x_0^{2}(t)} \,dt .. math:: y = C_1 y_0(t) + C_2 [\frac{F(t) P(t)}{x_0(t)} + y_0(t) \int \frac{g(t) F(t) P(t)}{x_0^{2}(t)} \,dt] where C1 and C2 are arbitrary constants and .. math:: F(t) = e^{\int f(t) \,dt}, P(t) = e^{\int p(t) \,dt} """ C1, C2, C3, C4 = get_numbered_constants(eq, num=4) e1 = r['a']*r['b']*r['c'] - r['b']**2*r['c'] + r['a']*diff(r['b'],t) - diff(r['a'],t)*r['b'] e2 = r['a']*r['c']*r['d'] - r['b']*r['c']**2 + diff(r['c'],t)*r['d'] - r['c']*diff(r['d'],t) m1 = r['a']*r['b'] + r['b']*r['d'] + diff(r['b'],t) m2 = r['a']*r['c'] + r['c']*r['d'] + diff(r['c'],t) if e1 == 0: sol1 = dsolve(r['b']*diff(x(t),t,t) - m1*diff(x(t),t)).rhs sol2 = dsolve(diff(y(t),t) - r['c']*sol1 - r['d']*y(t)).rhs elif e2 == 0: sol2 = dsolve(r['c']*diff(y(t),t,t) - m2*diff(y(t),t)).rhs sol1 = dsolve(diff(x(t),t) - r['a']*x(t) - r['b']*sol2).rhs elif not (e1/r['b']).has(t) and not (m1/r['b']).has(t): sol1 = dsolve(diff(x(t),t,t) - (m1/r['b'])*diff(x(t),t) - (e1/r['b'])*x(t)).rhs sol2 = dsolve(diff(y(t),t) - r['c']*sol1 - r['d']*y(t)).rhs elif not (e2/r['c']).has(t) and not (m2/r['c']).has(t): sol2 = dsolve(diff(y(t),t,t) - (m2/r['c'])*diff(y(t),t) - (e2/r['c'])*y(t)).rhs sol1 = dsolve(diff(x(t),t) - r['a']*x(t) - r['b']*sol2).rhs else: x0 = Function('x0')(t) # x0 and y0 being particular solutions y0 = Function('y0')(t) F = exp(Integral(r['a'],t)) P = exp(Integral(r['d'],t)) sol1 = C1*x0 + C2*x0*Integral(r['b']*F*P/x0**2, t) sol2 = C1*y0 + C2*(F*P/x0 + y0*Integral(r['b']*F*P/x0**2, t)) return [Eq(x(t), sol1), Eq(y(t), sol2)] def sysode_nonlinear_2eq_order1(match_): func = match_['func'] eq = match_['eq'] fc = match_['func_coeff'] t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] if match_['type_of_equation'] == 'type5': sol = _nonlinear_2eq_order1_type5(func, t, eq) return sol x = func[0].func y = func[1].func for i in range(2): eqs = 0 for terms in Add.make_args(eq[i]): eqs += terms/fc[i,func[i],1] eq[i] = eqs if match_['type_of_equation'] == 'type1': sol = _nonlinear_2eq_order1_type1(x, y, t, eq) elif match_['type_of_equation'] == 'type2': sol = _nonlinear_2eq_order1_type2(x, y, t, eq) elif match_['type_of_equation'] == 'type3': sol = _nonlinear_2eq_order1_type3(x, y, t, eq) elif match_['type_of_equation'] == 'type4': sol = _nonlinear_2eq_order1_type4(x, y, t, eq) return sol def _nonlinear_2eq_order1_type1(x, y, t, eq): r""" Equations: .. math:: x' = x^n F(x,y) .. math:: y' = g(y) F(x,y) Solution: .. math:: x = \varphi(y), \int \frac{1}{g(y) F(\varphi(y),y)} \,dy = t + C_2 where if `n \neq 1` .. math:: \varphi = [C_1 + (1-n) \int \frac{1}{g(y)} \,dy]^{\frac{1}{1-n}} if `n = 1` .. math:: \varphi = C_1 e^{\int \frac{1}{g(y)} \,dy} where `C_1` and `C_2` are arbitrary constants. """ C1, C2 = get_numbered_constants(eq, num=2) n = Wild('n', exclude=[x(t),y(t)]) f = Wild('f') u, v = symbols('u, v') r = eq[0].match(diff(x(t),t) - x(t)**n*f) g = ((diff(y(t),t) - eq[1])/r[f]).subs(y(t),v) F = r[f].subs(x(t),u).subs(y(t),v) n = r[n] if n!=1: phi = (C1 + (1-n)*Integral(1/g, v))**(1/(1-n)) else: phi = C1*exp(Integral(1/g, v)) phi = phi.doit() sol2 = solve(Integral(1/(g*F.subs(u,phi)), v).doit() - t - C2, v) sol = [] for sols in sol2: sol.append(Eq(x(t),phi.subs(v, sols))) sol.append(Eq(y(t), sols)) return sol def _nonlinear_2eq_order1_type2(x, y, t, eq): r""" Equations: .. math:: x' = e^{\lambda x} F(x,y) .. math:: y' = g(y) F(x,y) Solution: .. math:: x = \varphi(y), \int \frac{1}{g(y) F(\varphi(y),y)} \,dy = t + C_2 where if `\lambda \neq 0` .. math:: \varphi = -\frac{1}{\lambda} log(C_1 - \lambda \int \frac{1}{g(y)} \,dy) if `\lambda = 0` .. math:: \varphi = C_1 + \int \frac{1}{g(y)} \,dy where `C_1` and `C_2` are arbitrary constants. """ C1, C2 = get_numbered_constants(eq, num=2) n = Wild('n', exclude=[x(t),y(t)]) f = Wild('f') u, v = symbols('u, v') r = eq[0].match(diff(x(t),t) - exp(n*x(t))*f) g = ((diff(y(t),t) - eq[1])/r[f]).subs(y(t),v) F = r[f].subs(x(t),u).subs(y(t),v) n = r[n] if n: phi = -1/n*log(C1 - n*Integral(1/g, v)) else: phi = C1 + Integral(1/g, v) phi = phi.doit() sol2 = solve(Integral(1/(g*F.subs(u,phi)), v).doit() - t - C2, v) sol = [] for sols in sol2: sol.append(Eq(x(t),phi.subs(v, sols))) sol.append(Eq(y(t), sols)) return sol def _nonlinear_2eq_order1_type3(x, y, t, eq): r""" Autonomous system of general form .. math:: x' = F(x,y) .. math:: y' = G(x,y) Assuming `y = y(x, C_1)` where `C_1` is an arbitrary constant is the general solution of the first-order equation .. math:: F(x,y) y'_x = G(x,y) Then the general solution of the original system of equations has the form .. math:: \int \frac{1}{F(x,y(x,C_1))} \,dx = t + C_1 """ C1, C2, C3, C4 = get_numbered_constants(eq, num=4) v = Function('v') u = Symbol('u') f = Wild('f') g = Wild('g') r1 = eq[0].match(diff(x(t),t) - f) r2 = eq[1].match(diff(y(t),t) - g) F = r1[f].subs(x(t), u).subs(y(t), v(u)) G = r2[g].subs(x(t), u).subs(y(t), v(u)) sol2r = dsolve(Eq(diff(v(u), u), G/F)) if isinstance(sol2r, Equality): sol2r = [sol2r] for sol2s in sol2r: sol1 = solve(Integral(1/F.subs(v(u), sol2s.rhs), u).doit() - t - C2, u) sol = [] for sols in sol1: sol.append(Eq(x(t), sols)) sol.append(Eq(y(t), (sol2s.rhs).subs(u, sols))) return sol def _nonlinear_2eq_order1_type4(x, y, t, eq): r""" Equation: .. math:: x' = f_1(x) g_1(y) \phi(x,y,t) .. math:: y' = f_2(x) g_2(y) \phi(x,y,t) First integral: .. math:: \int \frac{f_2(x)}{f_1(x)} \,dx - \int \frac{g_1(y)}{g_2(y)} \,dy = C where `C` is an arbitrary constant. On solving the first integral for `x` (resp., `y` ) and on substituting the resulting expression into either equation of the original solution, one arrives at a first-order equation for determining `y` (resp., `x` ). """ C1, C2 = get_numbered_constants(eq, num=2) u, v = symbols('u, v') U, V = symbols('U, V', cls=Function) f = Wild('f') g = Wild('g') f1 = Wild('f1', exclude=[v,t]) f2 = Wild('f2', exclude=[v,t]) g1 = Wild('g1', exclude=[u,t]) g2 = Wild('g2', exclude=[u,t]) r1 = eq[0].match(diff(x(t),t) - f) r2 = eq[1].match(diff(y(t),t) - g) num, den = ( (r1[f].subs(x(t),u).subs(y(t),v))/ (r2[g].subs(x(t),u).subs(y(t),v))).as_numer_denom() R1 = num.match(f1*g1) R2 = den.match(f2*g2) phi = (r1[f].subs(x(t),u).subs(y(t),v))/num F1 = R1[f1]; F2 = R2[f2] G1 = R1[g1]; G2 = R2[g2] sol1r = solve(Integral(F2/F1, u).doit() - Integral(G1/G2,v).doit() - C1, u) sol2r = solve(Integral(F2/F1, u).doit() - Integral(G1/G2,v).doit() - C1, v) sol = [] for sols in sol1r: sol.append(Eq(y(t), dsolve(diff(V(t),t) - F2.subs(u,sols).subs(v,V(t))*G2.subs(v,V(t))*phi.subs(u,sols).subs(v,V(t))).rhs)) for sols in sol2r: sol.append(Eq(x(t), dsolve(diff(U(t),t) - F1.subs(u,U(t))*G1.subs(v,sols).subs(u,U(t))*phi.subs(v,sols).subs(u,U(t))).rhs)) return set(sol) def _nonlinear_2eq_order1_type5(func, t, eq): r""" Clairaut system of ODEs .. math:: x = t x' + F(x',y') .. math:: y = t y' + G(x',y') The following are solutions of the system `(i)` straight lines: .. math:: x = C_1 t + F(C_1, C_2), y = C_2 t + G(C_1, C_2) where `C_1` and `C_2` are arbitrary constants; `(ii)` envelopes of the above lines; `(iii)` continuously differentiable lines made up from segments of the lines `(i)` and `(ii)`. """ C1, C2 = get_numbered_constants(eq, num=2) f = Wild('f') g = Wild('g') def check_type(x, y): r1 = eq[0].match(t*diff(x(t),t) - x(t) + f) r2 = eq[1].match(t*diff(y(t),t) - y(t) + g) if not (r1 and r2): r1 = eq[0].match(diff(x(t),t) - x(t)/t + f/t) r2 = eq[1].match(diff(y(t),t) - y(t)/t + g/t) if not (r1 and r2): r1 = (-eq[0]).match(t*diff(x(t),t) - x(t) + f) r2 = (-eq[1]).match(t*diff(y(t),t) - y(t) + g) if not (r1 and r2): r1 = (-eq[0]).match(diff(x(t),t) - x(t)/t + f/t) r2 = (-eq[1]).match(diff(y(t),t) - y(t)/t + g/t) return [r1, r2] for func_ in func: if isinstance(func_, list): x = func[0][0].func y = func[0][1].func [r1, r2] = check_type(x, y) if not (r1 and r2): [r1, r2] = check_type(y, x) x, y = y, x x1 = diff(x(t),t); y1 = diff(y(t),t) return {Eq(x(t), C1*t + r1[f].subs(x1,C1).subs(y1,C2)), Eq(y(t), C2*t + r2[g].subs(x1,C1).subs(y1,C2))} def sysode_nonlinear_3eq_order1(match_): x = match_['func'][0].func y = match_['func'][1].func z = match_['func'][2].func eq = match_['eq'] t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] if match_['type_of_equation'] == 'type1': sol = _nonlinear_3eq_order1_type1(x, y, z, t, eq) if match_['type_of_equation'] == 'type2': sol = _nonlinear_3eq_order1_type2(x, y, z, t, eq) if match_['type_of_equation'] == 'type3': sol = _nonlinear_3eq_order1_type3(x, y, z, t, eq) if match_['type_of_equation'] == 'type4': sol = _nonlinear_3eq_order1_type4(x, y, z, t, eq) if match_['type_of_equation'] == 'type5': sol = _nonlinear_3eq_order1_type5(x, y, z, t, eq) return sol def _nonlinear_3eq_order1_type1(x, y, z, t, eq): r""" Equations: .. math:: a x' = (b - c) y z, \enspace b y' = (c - a) z x, \enspace c z' = (a - b) x y First Integrals: .. math:: a x^{2} + b y^{2} + c z^{2} = C_1 .. math:: a^{2} x^{2} + b^{2} y^{2} + c^{2} z^{2} = C_2 where `C_1` and `C_2` are arbitrary constants. On solving the integrals for `y` and `z` and on substituting the resulting expressions into the first equation of the system, we arrives at a separable first-order equation on `x`. Similarly doing that for other two equations, we will arrive at first order equation on `y` and `z` too. References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0401.pdf """ C1, C2 = get_numbered_constants(eq, num=2) u, v, w = symbols('u, v, w') p = Wild('p', exclude=[x(t), y(t), z(t), t]) q = Wild('q', exclude=[x(t), y(t), z(t), t]) s = Wild('s', exclude=[x(t), y(t), z(t), t]) r = (diff(x(t),t) - eq[0]).match(p*y(t)*z(t)) r.update((diff(y(t),t) - eq[1]).match(q*z(t)*x(t))) r.update((diff(z(t),t) - eq[2]).match(s*x(t)*y(t))) n1, d1 = r[p].as_numer_denom() n2, d2 = r[q].as_numer_denom() n3, d3 = r[s].as_numer_denom() val = solve([n1*u-d1*v+d1*w, d2*u+n2*v-d2*w, d3*u-d3*v-n3*w],[u,v]) vals = [val[v], val[u]] c = lcm(vals[0].as_numer_denom()[1], vals[1].as_numer_denom()[1]) b = vals[0].subs(w, c) a = vals[1].subs(w, c) y_x = sqrt(((c*C1-C2) - a*(c-a)*x(t)**2)/(b*(c-b))) z_x = sqrt(((b*C1-C2) - a*(b-a)*x(t)**2)/(c*(b-c))) z_y = sqrt(((a*C1-C2) - b*(a-b)*y(t)**2)/(c*(a-c))) x_y = sqrt(((c*C1-C2) - b*(c-b)*y(t)**2)/(a*(c-a))) x_z = sqrt(((b*C1-C2) - c*(b-c)*z(t)**2)/(a*(b-a))) y_z = sqrt(((a*C1-C2) - c*(a-c)*z(t)**2)/(b*(a-b))) sol1 = dsolve(a*diff(x(t),t) - (b-c)*y_x*z_x) sol2 = dsolve(b*diff(y(t),t) - (c-a)*z_y*x_y) sol3 = dsolve(c*diff(z(t),t) - (a-b)*x_z*y_z) return [sol1, sol2, sol3] def _nonlinear_3eq_order1_type2(x, y, z, t, eq): r""" Equations: .. math:: a x' = (b - c) y z f(x, y, z, t) .. math:: b y' = (c - a) z x f(x, y, z, t) .. math:: c z' = (a - b) x y f(x, y, z, t) First Integrals: .. math:: a x^{2} + b y^{2} + c z^{2} = C_1 .. math:: a^{2} x^{2} + b^{2} y^{2} + c^{2} z^{2} = C_2 where `C_1` and `C_2` are arbitrary constants. On solving the integrals for `y` and `z` and on substituting the resulting expressions into the first equation of the system, we arrives at a first-order differential equations on `x`. Similarly doing that for other two equations we will arrive at first order equation on `y` and `z`. References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0402.pdf """ C1, C2 = get_numbered_constants(eq, num=2) u, v, w = symbols('u, v, w') p = Wild('p', exclude=[x(t), y(t), z(t), t]) q = Wild('q', exclude=[x(t), y(t), z(t), t]) s = Wild('s', exclude=[x(t), y(t), z(t), t]) f = Wild('f') r1 = (diff(x(t),t) - eq[0]).match(y(t)*z(t)*f) r = collect_const(r1[f]).match(p*f) r.update(((diff(y(t),t) - eq[1])/r[f]).match(q*z(t)*x(t))) r.update(((diff(z(t),t) - eq[2])/r[f]).match(s*x(t)*y(t))) n1, d1 = r[p].as_numer_denom() n2, d2 = r[q].as_numer_denom() n3, d3 = r[s].as_numer_denom() val = solve([n1*u-d1*v+d1*w, d2*u+n2*v-d2*w, -d3*u+d3*v+n3*w],[u,v]) vals = [val[v], val[u]] c = lcm(vals[0].as_numer_denom()[1], vals[1].as_numer_denom()[1]) a = vals[0].subs(w, c) b = vals[1].subs(w, c) y_x = sqrt(((c*C1-C2) - a*(c-a)*x(t)**2)/(b*(c-b))) z_x = sqrt(((b*C1-C2) - a*(b-a)*x(t)**2)/(c*(b-c))) z_y = sqrt(((a*C1-C2) - b*(a-b)*y(t)**2)/(c*(a-c))) x_y = sqrt(((c*C1-C2) - b*(c-b)*y(t)**2)/(a*(c-a))) x_z = sqrt(((b*C1-C2) - c*(b-c)*z(t)**2)/(a*(b-a))) y_z = sqrt(((a*C1-C2) - c*(a-c)*z(t)**2)/(b*(a-b))) sol1 = dsolve(a*diff(x(t),t) - (b-c)*y_x*z_x*r[f]) sol2 = dsolve(b*diff(y(t),t) - (c-a)*z_y*x_y*r[f]) sol3 = dsolve(c*diff(z(t),t) - (a-b)*x_z*y_z*r[f]) return [sol1, sol2, sol3] def _nonlinear_3eq_order1_type3(x, y, z, t, eq): r""" Equations: .. math:: x' = c F_2 - b F_3, \enspace y' = a F_3 - c F_1, \enspace z' = b F_1 - a F_2 where `F_n = F_n(x, y, z, t)`. 1. First Integral: .. math:: a x + b y + c z = C_1, where C is an arbitrary constant. 2. If we assume function `F_n` to be independent of `t`,i.e, `F_n` = `F_n (x, y, z)` Then, on eliminating `t` and `z` from the first two equation of the system, one arrives at the first-order equation .. math:: \frac{dy}{dx} = \frac{a F_3 (x, y, z) - c F_1 (x, y, z)}{c F_2 (x, y, z) - b F_3 (x, y, z)} where `z = \frac{1}{c} (C_1 - a x - b y)` References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0404.pdf """ C1 = get_numbered_constants(eq, num=1) u, v, w = symbols('u, v, w') fu, fv, fw = symbols('u, v, w', cls=Function) p = Wild('p', exclude=[x(t), y(t), z(t), t]) q = Wild('q', exclude=[x(t), y(t), z(t), t]) s = Wild('s', exclude=[x(t), y(t), z(t), t]) F1, F2, F3 = symbols('F1, F2, F3', cls=Wild) r1 = (diff(x(t), t) - eq[0]).match(F2-F3) r = collect_const(r1[F2]).match(s*F2) r.update(collect_const(r1[F3]).match(q*F3)) if eq[1].has(r[F2]) and not eq[1].has(r[F3]): r[F2], r[F3] = r[F3], r[F2] r[s], r[q] = -r[q], -r[s] r.update((diff(y(t), t) - eq[1]).match(p*r[F3] - r[s]*F1)) a = r[p]; b = r[q]; c = r[s] F1 = r[F1].subs(x(t), u).subs(y(t),v).subs(z(t), w) F2 = r[F2].subs(x(t), u).subs(y(t),v).subs(z(t), w) F3 = r[F3].subs(x(t), u).subs(y(t),v).subs(z(t), w) z_xy = (C1-a*u-b*v)/c y_zx = (C1-a*u-c*w)/b x_yz = (C1-b*v-c*w)/a y_x = dsolve(diff(fv(u),u) - ((a*F3-c*F1)/(c*F2-b*F3)).subs(w,z_xy).subs(v,fv(u))).rhs z_x = dsolve(diff(fw(u),u) - ((b*F1-a*F2)/(c*F2-b*F3)).subs(v,y_zx).subs(w,fw(u))).rhs z_y = dsolve(diff(fw(v),v) - ((b*F1-a*F2)/(a*F3-c*F1)).subs(u,x_yz).subs(w,fw(v))).rhs x_y = dsolve(diff(fu(v),v) - ((c*F2-b*F3)/(a*F3-c*F1)).subs(w,z_xy).subs(u,fu(v))).rhs y_z = dsolve(diff(fv(w),w) - ((a*F3-c*F1)/(b*F1-a*F2)).subs(u,x_yz).subs(v,fv(w))).rhs x_z = dsolve(diff(fu(w),w) - ((c*F2-b*F3)/(b*F1-a*F2)).subs(v,y_zx).subs(u,fu(w))).rhs sol1 = dsolve(diff(fu(t),t) - (c*F2 - b*F3).subs(v,y_x).subs(w,z_x).subs(u,fu(t))).rhs sol2 = dsolve(diff(fv(t),t) - (a*F3 - c*F1).subs(u,x_y).subs(w,z_y).subs(v,fv(t))).rhs sol3 = dsolve(diff(fw(t),t) - (b*F1 - a*F2).subs(u,x_z).subs(v,y_z).subs(w,fw(t))).rhs return [sol1, sol2, sol3] def _nonlinear_3eq_order1_type4(x, y, z, t, eq): r""" Equations: .. math:: x' = c z F_2 - b y F_3, \enspace y' = a x F_3 - c z F_1, \enspace z' = b y F_1 - a x F_2 where `F_n = F_n (x, y, z, t)` 1. First integral: .. math:: a x^{2} + b y^{2} + c z^{2} = C_1 where `C` is an arbitrary constant. 2. Assuming the function `F_n` is independent of `t`: `F_n = F_n (x, y, z)`. Then on eliminating `t` and `z` from the first two equations of the system, one arrives at the first-order equation .. math:: \frac{dy}{dx} = \frac{a x F_3 (x, y, z) - c z F_1 (x, y, z)} {c z F_2 (x, y, z) - b y F_3 (x, y, z)} where `z = \pm \sqrt{\frac{1}{c} (C_1 - a x^{2} - b y^{2})}` References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0405.pdf """ C1 = get_numbered_constants(eq, num=1) u, v, w = symbols('u, v, w') p = Wild('p', exclude=[x(t), y(t), z(t), t]) q = Wild('q', exclude=[x(t), y(t), z(t), t]) s = Wild('s', exclude=[x(t), y(t), z(t), t]) F1, F2, F3 = symbols('F1, F2, F3', cls=Wild) r1 = eq[0].match(diff(x(t),t) - z(t)*F2 + y(t)*F3) r = collect_const(r1[F2]).match(s*F2) r.update(collect_const(r1[F3]).match(q*F3)) if eq[1].has(r[F2]) and not eq[1].has(r[F3]): r[F2], r[F3] = r[F3], r[F2] r[s], r[q] = -r[q], -r[s] r.update((diff(y(t),t) - eq[1]).match(p*x(t)*r[F3] - r[s]*z(t)*F1)) a = r[p]; b = r[q]; c = r[s] F1 = r[F1].subs(x(t),u).subs(y(t),v).subs(z(t),w) F2 = r[F2].subs(x(t),u).subs(y(t),v).subs(z(t),w) F3 = r[F3].subs(x(t),u).subs(y(t),v).subs(z(t),w) x_yz = sqrt((C1 - b*v**2 - c*w**2)/a) y_zx = sqrt((C1 - c*w**2 - a*u**2)/b) z_xy = sqrt((C1 - a*u**2 - b*v**2)/c) y_x = dsolve(diff(v(u),u) - ((a*u*F3-c*w*F1)/(c*w*F2-b*v*F3)).subs(w,z_xy).subs(v,v(u))).rhs z_x = dsolve(diff(w(u),u) - ((b*v*F1-a*u*F2)/(c*w*F2-b*v*F3)).subs(v,y_zx).subs(w,w(u))).rhs z_y = dsolve(diff(w(v),v) - ((b*v*F1-a*u*F2)/(a*u*F3-c*w*F1)).subs(u,x_yz).subs(w,w(v))).rhs x_y = dsolve(diff(u(v),v) - ((c*w*F2-b*v*F3)/(a*u*F3-c*w*F1)).subs(w,z_xy).subs(u,u(v))).rhs y_z = dsolve(diff(v(w),w) - ((a*u*F3-c*w*F1)/(b*v*F1-a*u*F2)).subs(u,x_yz).subs(v,v(w))).rhs x_z = dsolve(diff(u(w),w) - ((c*w*F2-b*v*F3)/(b*v*F1-a*u*F2)).subs(v,y_zx).subs(u,u(w))).rhs sol1 = dsolve(diff(u(t),t) - (c*w*F2 - b*v*F3).subs(v,y_x).subs(w,z_x).subs(u,u(t))).rhs sol2 = dsolve(diff(v(t),t) - (a*u*F3 - c*w*F1).subs(u,x_y).subs(w,z_y).subs(v,v(t))).rhs sol3 = dsolve(diff(w(t),t) - (b*v*F1 - a*u*F2).subs(u,x_z).subs(v,y_z).subs(w,w(t))).rhs return [sol1, sol2, sol3] def _nonlinear_3eq_order1_type5(x, y, z, t, eq): r""" .. math:: x' = x (c F_2 - b F_3), \enspace y' = y (a F_3 - c F_1), \enspace z' = z (b F_1 - a F_2) where `F_n = F_n (x, y, z, t)` and are arbitrary functions. First Integral: .. math:: \left|x\right|^{a} \left|y\right|^{b} \left|z\right|^{c} = C_1 where `C` is an arbitrary constant. If the function `F_n` is independent of `t`, then, by eliminating `t` and `z` from the first two equations of the system, one arrives at a first-order equation. References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0406.pdf """ C1 = get_numbered_constants(eq, num=1) u, v, w = symbols('u, v, w') fu, fv, fw = symbols('u, v, w', cls=Function) p = Wild('p', exclude=[x(t), y(t), z(t), t]) q = Wild('q', exclude=[x(t), y(t), z(t), t]) s = Wild('s', exclude=[x(t), y(t), z(t), t]) F1, F2, F3 = symbols('F1, F2, F3', cls=Wild) r1 = eq[0].match(diff(x(t), t) - x(t)*F2 + x(t)*F3) r = collect_const(r1[F2]).match(s*F2) r.update(collect_const(r1[F3]).match(q*F3)) if eq[1].has(r[F2]) and not eq[1].has(r[F3]): r[F2], r[F3] = r[F3], r[F2] r[s], r[q] = -r[q], -r[s] r.update((diff(y(t), t) - eq[1]).match(y(t)*(p*r[F3] - r[s]*F1))) a = r[p]; b = r[q]; c = r[s] F1 = r[F1].subs(x(t), u).subs(y(t), v).subs(z(t), w) F2 = r[F2].subs(x(t), u).subs(y(t), v).subs(z(t), w) F3 = r[F3].subs(x(t), u).subs(y(t), v).subs(z(t), w) x_yz = (C1*v**-b*w**-c)**-a y_zx = (C1*w**-c*u**-a)**-b z_xy = (C1*u**-a*v**-b)**-c y_x = dsolve(diff(fv(u), u) - ((v*(a*F3 - c*F1))/(u*(c*F2 - b*F3))).subs(w, z_xy).subs(v, fv(u))).rhs z_x = dsolve(diff(fw(u), u) - ((w*(b*F1 - a*F2))/(u*(c*F2 - b*F3))).subs(v, y_zx).subs(w, fw(u))).rhs z_y = dsolve(diff(fw(v), v) - ((w*(b*F1 - a*F2))/(v*(a*F3 - c*F1))).subs(u, x_yz).subs(w, fw(v))).rhs x_y = dsolve(diff(fu(v), v) - ((u*(c*F2 - b*F3))/(v*(a*F3 - c*F1))).subs(w, z_xy).subs(u, fu(v))).rhs y_z = dsolve(diff(fv(w), w) - ((v*(a*F3 - c*F1))/(w*(b*F1 - a*F2))).subs(u, x_yz).subs(v, fv(w))).rhs x_z = dsolve(diff(fu(w), w) - ((u*(c*F2 - b*F3))/(w*(b*F1 - a*F2))).subs(v, y_zx).subs(u, fu(w))).rhs sol1 = dsolve(diff(fu(t), t) - (u*(c*F2 - b*F3)).subs(v, y_x).subs(w, z_x).subs(u, fu(t))).rhs sol2 = dsolve(diff(fv(t), t) - (v*(a*F3 - c*F1)).subs(u, x_y).subs(w, z_y).subs(v, fv(t))).rhs sol3 = dsolve(diff(fw(t), t) - (w*(b*F1 - a*F2)).subs(u, x_z).subs(v, y_z).subs(w, fw(t))).rhs return [sol1, sol2, sol3] #This import is written at the bottom to avoid circular imports. from .single import SingleODEProblem, SingleODESolver, solver_map
64d6d141422975add6de9d507bb55bafc81e777994c67c19e25bf9b72cdd5c29
from sympy.core import Add, Mul, S from sympy.core.containers import Tuple from sympy.core.exprtools import factor_terms from sympy.core.numbers import I from sympy.core.relational import Eq, Equality from sympy.core.sorting import default_sort_key, ordered from sympy.core.symbol import Dummy, Symbol from sympy.core.function import (expand_mul, expand, Derivative, AppliedUndef, Function, Subs) from sympy.functions import (exp, im, cos, sin, re, Piecewise, piecewise_fold, sqrt, log) from sympy.functions.combinatorial.factorials import factorial from sympy.matrices import zeros, Matrix, NonSquareMatrixError, MatrixBase, eye from sympy.polys import Poly, together from sympy.simplify import collect, radsimp, signsimp # type: ignore from sympy.simplify.powsimp import powdenest, powsimp from sympy.simplify.ratsimp import ratsimp from sympy.simplify.simplify import simplify from sympy.sets.sets import FiniteSet from sympy.solvers.deutils import ode_order from sympy.solvers.solveset import NonlinearError, solveset from sympy.utilities.iterables import (connected_components, iterable, strongly_connected_components) from sympy.utilities.misc import filldedent from sympy.integrals.integrals import Integral, integrate def _get_func_order(eqs, funcs): return {func: max(ode_order(eq, func) for eq in eqs) for func in funcs} class ODEOrderError(ValueError): """Raised by linear_ode_to_matrix if the system has the wrong order""" pass class ODENonlinearError(NonlinearError): """Raised by linear_ode_to_matrix if the system is nonlinear""" pass def _simpsol(soleq): lhs = soleq.lhs sol = soleq.rhs sol = powsimp(sol) gens = list(sol.atoms(exp)) p = Poly(sol, *gens, expand=False) gens = [factor_terms(g) for g in gens] if not gens: gens = p.gens syms = [Symbol('C1'), Symbol('C2')] terms = [] for coeff, monom in zip(p.coeffs(), p.monoms()): coeff = piecewise_fold(coeff) if type(coeff) is Piecewise: coeff = Piecewise(*((ratsimp(coef).collect(syms), cond) for coef, cond in coeff.args)) else: coeff = ratsimp(coeff).collect(syms) monom = Mul(*(g ** i for g, i in zip(gens, monom))) terms.append(coeff * monom) return Eq(lhs, Add(*terms)) def _solsimp(e, t): no_t, has_t = powsimp(expand_mul(e)).as_independent(t) no_t = ratsimp(no_t) has_t = has_t.replace(exp, lambda a: exp(factor_terms(a))) return no_t + has_t def simpsol(sol, wrt1, wrt2, doit=True): """Simplify solutions from dsolve_system.""" # The parameter sol is the solution as returned by dsolve (list of Eq). # # The parameters wrt1 and wrt2 are lists of symbols to be collected for # with those in wrt1 being collected for first. This allows for collecting # on any factors involving the independent variable before collecting on # the integration constants or vice versa using e.g.: # # sol = simpsol(sol, [t], [C1, C2]) # t first, constants after # sol = simpsol(sol, [C1, C2], [t]) # constants first, t after # # If doit=True (default) then simpsol will begin by evaluating any # unevaluated integrals. Since many integrals will appear multiple times # in the solutions this is done intelligently by computing each integral # only once. # # The strategy is to first perform simple cancellation with factor_terms # and then multiply out all brackets with expand_mul. This gives an Add # with many terms. # # We split each term into two multiplicative factors dep and coeff where # all factors that involve wrt1 are in dep and any constant factors are in # coeff e.g. # sqrt(2)*C1*exp(t) -> ( exp(t), sqrt(2)*C1 ) # # The dep factors are simplified using powsimp to combine expanded # exponential factors e.g. # exp(a*t)*exp(b*t) -> exp(t*(a+b)) # # We then collect coefficients for all terms having the same (simplified) # dep. The coefficients are then simplified using together and ratsimp and # lastly by recursively applying the same transformation to the # coefficients to collect on wrt2. # # Finally the result is recombined into an Add and signsimp is used to # normalise any minus signs. def simprhs(rhs, rep, wrt1, wrt2): """Simplify the rhs of an ODE solution""" if rep: rhs = rhs.subs(rep) rhs = factor_terms(rhs) rhs = simp_coeff_dep(rhs, wrt1, wrt2) rhs = signsimp(rhs) return rhs def simp_coeff_dep(expr, wrt1, wrt2=None): """Split rhs into terms, split terms into dep and coeff and collect on dep""" add_dep_terms = lambda e: e.is_Add and e.has(*wrt1) expandable = lambda e: e.is_Mul and any(map(add_dep_terms, e.args)) expand_func = lambda e: expand_mul(e, deep=False) expand_mul_mod = lambda e: e.replace(expandable, expand_func) terms = Add.make_args(expand_mul_mod(expr)) dc = {} for term in terms: coeff, dep = term.as_independent(*wrt1, as_Add=False) # Collect together the coefficients for terms that have the same # dependence on wrt1 (after dep is normalised using simpdep). dep = simpdep(dep, wrt1) # See if the dependence on t cancels out... if dep is not S.One: dep2 = factor_terms(dep) if not dep2.has(*wrt1): coeff *= dep2 dep = S.One if dep not in dc: dc[dep] = coeff else: dc[dep] += coeff # Apply the method recursively to the coefficients but this time # collecting on wrt2 rather than wrt2. termpairs = ((simpcoeff(c, wrt2), d) for d, c in dc.items()) if wrt2 is not None: termpairs = ((simp_coeff_dep(c, wrt2), d) for c, d in termpairs) return Add(*(c * d for c, d in termpairs)) def simpdep(term, wrt1): """Normalise factors involving t with powsimp and recombine exp""" def canonicalise(a): # Using factor_terms here isn't quite right because it leads to things # like exp(t*(1+t)) that we don't want. We do want to cancel factors # and pull out a common denominator but ideally the numerator would be # expressed as a standard form polynomial in t so we expand_mul # and collect afterwards. a = factor_terms(a) num, den = a.as_numer_denom() num = expand_mul(num) num = collect(num, wrt1) return num / den term = powsimp(term) rep = {e: exp(canonicalise(e.args[0])) for e in term.atoms(exp)} term = term.subs(rep) return term def simpcoeff(coeff, wrt2): """Bring to a common fraction and cancel with ratsimp""" coeff = together(coeff) if coeff.is_polynomial(): # Calling ratsimp can be expensive. The main reason is to simplify # sums of terms with irrational denominators so we limit ourselves # to the case where the expression is polynomial in any symbols. # Maybe there's a better approach... coeff = ratsimp(radsimp(coeff)) # collect on secondary variables first and any remaining symbols after if wrt2 is not None: syms = list(wrt2) + list(ordered(coeff.free_symbols - set(wrt2))) else: syms = list(ordered(coeff.free_symbols)) coeff = collect(coeff, syms) coeff = together(coeff) return coeff # There are often repeated integrals. Collect unique integrals and # evaluate each once and then substitute into the final result to replace # all occurrences in each of the solution equations. if doit: integrals = set().union(*(s.atoms(Integral) for s in sol)) rep = {i: factor_terms(i).doit() for i in integrals} else: rep = {} sol = [Eq(s.lhs, simprhs(s.rhs, rep, wrt1, wrt2)) for s in sol] return sol def linodesolve_type(A, t, b=None): r""" Helper function that determines the type of the system of ODEs for solving with :obj:`sympy.solvers.ode.systems.linodesolve()` Explanation =========== This function takes in the coefficient matrix and/or the non-homogeneous term and returns the type of the equation that can be solved by :obj:`sympy.solvers.ode.systems.linodesolve()`. If the system is constant coefficient homogeneous, then "type1" is returned If the system is constant coefficient non-homogeneous, then "type2" is returned If the system is non-constant coefficient homogeneous, then "type3" is returned If the system is non-constant coefficient non-homogeneous, then "type4" is returned If the system has a non-constant coefficient matrix which can be factorized into constant coefficient matrix, then "type5" or "type6" is returned for when the system is homogeneous or non-homogeneous respectively. Note that, if the system of ODEs is of "type3" or "type4", then along with the type, the commutative antiderivative of the coefficient matrix is also returned. If the system cannot be solved by :obj:`sympy.solvers.ode.systems.linodesolve()`, then NotImplementedError is raised. Parameters ========== A : Matrix Coefficient matrix of the system of ODEs b : Matrix or None Non-homogeneous term of the system. The default value is None. If this argument is None, then the system is assumed to be homogeneous. Examples ======== >>> from sympy import symbols, Matrix >>> from sympy.solvers.ode.systems import linodesolve_type >>> t = symbols("t") >>> A = Matrix([[1, 1], [2, 3]]) >>> b = Matrix([t, 1]) >>> linodesolve_type(A, t) {'antiderivative': None, 'type_of_equation': 'type1'} >>> linodesolve_type(A, t, b=b) {'antiderivative': None, 'type_of_equation': 'type2'} >>> A_t = Matrix([[1, t], [-t, 1]]) >>> linodesolve_type(A_t, t) {'antiderivative': Matrix([ [ t, t**2/2], [-t**2/2, t]]), 'type_of_equation': 'type3'} >>> linodesolve_type(A_t, t, b=b) {'antiderivative': Matrix([ [ t, t**2/2], [-t**2/2, t]]), 'type_of_equation': 'type4'} >>> A_non_commutative = Matrix([[1, t], [t, -1]]) >>> linodesolve_type(A_non_commutative, t) Traceback (most recent call last): ... NotImplementedError: The system does not have a commutative antiderivative, it cannot be solved by linodesolve. Returns ======= Dict Raises ====== NotImplementedError When the coefficient matrix doesn't have a commutative antiderivative See Also ======== linodesolve: Function for which linodesolve_type gets the information """ match = {} is_non_constant = not _matrix_is_constant(A, t) is_non_homogeneous = not (b is None or b.is_zero_matrix) type = "type{}".format(int("{}{}".format(int(is_non_constant), int(is_non_homogeneous)), 2) + 1) B = None match.update({"type_of_equation": type, "antiderivative": B}) if is_non_constant: B, is_commuting = _is_commutative_anti_derivative(A, t) if not is_commuting: raise NotImplementedError(filldedent(''' The system does not have a commutative antiderivative, it cannot be solved by linodesolve. ''')) match['antiderivative'] = B match.update(_first_order_type5_6_subs(A, t, b=b)) return match def _first_order_type5_6_subs(A, t, b=None): match = {} factor_terms = _factor_matrix(A, t) is_homogeneous = b is None or b.is_zero_matrix if factor_terms is not None: t_ = Symbol("{}_".format(t)) F_t = integrate(factor_terms[0], t) inverse = solveset(Eq(t_, F_t), t) # Note: A simple way to check if a function is invertible # or not. if isinstance(inverse, FiniteSet) and not inverse.has(Piecewise)\ and len(inverse) == 1: A = factor_terms[1] if not is_homogeneous: b = b / factor_terms[0] b = b.subs(t, list(inverse)[0]) type = "type{}".format(5 + (not is_homogeneous)) match.update({'func_coeff': A, 'tau': F_t, 't_': t_, 'type_of_equation': type, 'rhs': b}) return match def linear_ode_to_matrix(eqs, funcs, t, order): r""" Convert a linear system of ODEs to matrix form Explanation =========== Express a system of linear ordinary differential equations as a single matrix differential equation [1]. For example the system $x' = x + y + 1$ and $y' = x - y$ can be represented as .. math:: A_1 X' = A_0 X + b where $A_1$ and $A_0$ are $2 \times 2$ matrices and $b$, $X$ and $X'$ are $2 \times 1$ matrices with $X = [x, y]^T$. Higher-order systems are represented with additional matrices e.g. a second-order system would look like .. math:: A_2 X'' = A_1 X' + A_0 X + b Examples ======== >>> from sympy import Function, Symbol, Matrix, Eq >>> from sympy.solvers.ode.systems import linear_ode_to_matrix >>> t = Symbol('t') >>> x = Function('x') >>> y = Function('y') We can create a system of linear ODEs like >>> eqs = [ ... Eq(x(t).diff(t), x(t) + y(t) + 1), ... Eq(y(t).diff(t), x(t) - y(t)), ... ] >>> funcs = [x(t), y(t)] >>> order = 1 # 1st order system Now ``linear_ode_to_matrix`` can represent this as a matrix differential equation. >>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, t, order) >>> A1 Matrix([ [1, 0], [0, 1]]) >>> A0 Matrix([ [1, 1], [1, -1]]) >>> b Matrix([ [1], [0]]) The original equations can be recovered from these matrices: >>> eqs_mat = Matrix([eq.lhs - eq.rhs for eq in eqs]) >>> X = Matrix(funcs) >>> A1 * X.diff(t) - A0 * X - b == eqs_mat True If the system of equations has a maximum order greater than the order of the system specified, a ODEOrderError exception is raised. >>> eqs = [Eq(x(t).diff(t, 2), x(t).diff(t) + x(t)), Eq(y(t).diff(t), y(t) + x(t))] >>> linear_ode_to_matrix(eqs, funcs, t, 1) Traceback (most recent call last): ... ODEOrderError: Cannot represent system in 1-order form If the system of equations is nonlinear, then ODENonlinearError is raised. >>> eqs = [Eq(x(t).diff(t), x(t) + y(t)), Eq(y(t).diff(t), y(t)**2 + x(t))] >>> linear_ode_to_matrix(eqs, funcs, t, 1) Traceback (most recent call last): ... ODENonlinearError: The system of ODEs is nonlinear. Parameters ========== eqs : list of SymPy expressions or equalities The equations as expressions (assumed equal to zero). funcs : list of applied functions The dependent variables of the system of ODEs. t : symbol The independent variable. order : int The order of the system of ODEs. Returns ======= The tuple ``(As, b)`` where ``As`` is a tuple of matrices and ``b`` is the the matrix representing the rhs of the matrix equation. Raises ====== ODEOrderError When the system of ODEs have an order greater than what was specified ODENonlinearError When the system of ODEs is nonlinear See Also ======== linear_eq_to_matrix: for systems of linear algebraic equations. References ========== .. [1] https://en.wikipedia.org/wiki/Matrix_differential_equation """ from sympy.solvers.solveset import linear_eq_to_matrix if any(ode_order(eq, func) > order for eq in eqs for func in funcs): msg = "Cannot represent system in {}-order form" raise ODEOrderError(msg.format(order)) As = [] for o in range(order, -1, -1): # Work from the highest derivative down funcs_deriv = [func.diff(t, o) for func in funcs] # linear_eq_to_matrix expects a proper symbol so substitute e.g. # Derivative(x(t), t) for a Dummy. rep = {func_deriv: Dummy() for func_deriv in funcs_deriv} eqs = [eq.subs(rep) for eq in eqs] syms = [rep[func_deriv] for func_deriv in funcs_deriv] # Ai is the matrix for X(t).diff(t, o) # eqs is minus the remainder of the equations. try: Ai, b = linear_eq_to_matrix(eqs, syms) except NonlinearError: raise ODENonlinearError("The system of ODEs is nonlinear.") Ai = Ai.applyfunc(expand_mul) As.append(Ai if o == order else -Ai) if o: eqs = [-eq for eq in b] else: rhs = b return As, rhs def matrix_exp(A, t): r""" Matrix exponential $\exp(A*t)$ for the matrix ``A`` and scalar ``t``. Explanation =========== This functions returns the $\exp(A*t)$ by doing a simple matrix multiplication: .. math:: \exp(A*t) = P * expJ * P^{-1} where $expJ$ is $\exp(J*t)$. $J$ is the Jordan normal form of $A$ and $P$ is matrix such that: .. math:: A = P * J * P^{-1} The matrix exponential $\exp(A*t)$ appears in the solution of linear differential equations. For example if $x$ is a vector and $A$ is a matrix then the initial value problem .. math:: \frac{dx(t)}{dt} = A \times x(t), x(0) = x0 has the unique solution .. math:: x(t) = \exp(A t) x0 Examples ======== >>> from sympy import Symbol, Matrix, pprint >>> from sympy.solvers.ode.systems import matrix_exp >>> t = Symbol('t') We will consider a 2x2 matrix for comupting the exponential >>> A = Matrix([[2, -5], [2, -4]]) >>> pprint(A) [2 -5] [ ] [2 -4] Now, exp(A*t) is given as follows: >>> pprint(matrix_exp(A, t)) [ -t -t -t ] [3*e *sin(t) + e *cos(t) -5*e *sin(t) ] [ ] [ -t -t -t ] [ 2*e *sin(t) - 3*e *sin(t) + e *cos(t)] Parameters ========== A : Matrix The matrix $A$ in the expression $\exp(A*t)$ t : Symbol The independent variable See Also ======== matrix_exp_jordan_form: For exponential of Jordan normal form References ========== .. [1] https://en.wikipedia.org/wiki/Jordan_normal_form .. [2] https://en.wikipedia.org/wiki/Matrix_exponential """ P, expJ = matrix_exp_jordan_form(A, t) return P * expJ * P.inv() def matrix_exp_jordan_form(A, t): r""" Matrix exponential $\exp(A*t)$ for the matrix *A* and scalar *t*. Explanation =========== Returns the Jordan form of the $\exp(A*t)$ along with the matrix $P$ such that: .. math:: \exp(A*t) = P * expJ * P^{-1} Examples ======== >>> from sympy import Matrix, Symbol >>> from sympy.solvers.ode.systems import matrix_exp, matrix_exp_jordan_form >>> t = Symbol('t') We will consider a 2x2 defective matrix. This shows that our method works even for defective matrices. >>> A = Matrix([[1, 1], [0, 1]]) It can be observed that this function gives us the Jordan normal form and the required invertible matrix P. >>> P, expJ = matrix_exp_jordan_form(A, t) Here, it is shown that P and expJ returned by this function is correct as they satisfy the formula: P * expJ * P_inverse = exp(A*t). >>> P * expJ * P.inv() == matrix_exp(A, t) True Parameters ========== A : Matrix The matrix $A$ in the expression $\exp(A*t)$ t : Symbol The independent variable References ========== .. [1] https://en.wikipedia.org/wiki/Defective_matrix .. [2] https://en.wikipedia.org/wiki/Jordan_matrix .. [3] https://en.wikipedia.org/wiki/Jordan_normal_form """ N, M = A.shape if N != M: raise ValueError('Needed square matrix but got shape (%s, %s)' % (N, M)) elif A.has(t): raise ValueError('Matrix A should not depend on t') def jordan_chains(A): '''Chains from Jordan normal form analogous to M.eigenvects(). Returns a dict with eignevalues as keys like: {e1: [[v111,v112,...], [v121, v122,...]], e2:...} where vijk is the kth vector in the jth chain for eigenvalue i. ''' P, blocks = A.jordan_cells() basis = [P[:,i] for i in range(P.shape[1])] n = 0 chains = {} for b in blocks: eigval = b[0, 0] size = b.shape[0] if eigval not in chains: chains[eigval] = [] chains[eigval].append(basis[n:n+size]) n += size return chains eigenchains = jordan_chains(A) # Needed for consistency across Python versions eigenchains_iter = sorted(eigenchains.items(), key=default_sort_key) isreal = not A.has(I) blocks = [] vectors = [] seen_conjugate = set() for e, chains in eigenchains_iter: for chain in chains: n = len(chain) if isreal and e != e.conjugate() and e.conjugate() in eigenchains: if e in seen_conjugate: continue seen_conjugate.add(e.conjugate()) exprt = exp(re(e) * t) imrt = im(e) * t imblock = Matrix([[cos(imrt), sin(imrt)], [-sin(imrt), cos(imrt)]]) expJblock2 = Matrix(n, n, lambda i,j: imblock * t**(j-i) / factorial(j-i) if j >= i else zeros(2, 2)) expJblock = Matrix(2*n, 2*n, lambda i,j: expJblock2[i//2,j//2][i%2,j%2]) blocks.append(exprt * expJblock) for i in range(n): vectors.append(re(chain[i])) vectors.append(im(chain[i])) else: vectors.extend(chain) fun = lambda i,j: t**(j-i)/factorial(j-i) if j >= i else 0 expJblock = Matrix(n, n, fun) blocks.append(exp(e * t) * expJblock) expJ = Matrix.diag(*blocks) P = Matrix(N, N, lambda i,j: vectors[j][i]) return P, expJ # Note: To add a docstring example with tau def linodesolve(A, t, b=None, B=None, type="auto", doit=False, tau=None): r""" System of n equations linear first-order differential equations Explanation =========== This solver solves the system of ODEs of the follwing form: .. math:: X'(t) = A(t) X(t) + b(t) Here, $A(t)$ is the coefficient matrix, $X(t)$ is the vector of n independent variables, $b(t)$ is the non-homogeneous term and $X'(t)$ is the derivative of $X(t)$ Depending on the properties of $A(t)$ and $b(t)$, this solver evaluates the solution differently. When $A(t)$ is constant coefficient matrix and $b(t)$ is zero vector i.e. system is homogeneous, the system is "type1". The solution is: .. math:: X(t) = \exp(A t) C Here, $C$ is a vector of constants and $A$ is the constant coefficient matrix. When $A(t)$ is constant coefficient matrix and $b(t)$ is non-zero i.e. system is non-homogeneous, the system is "type2". The solution is: .. math:: X(t) = e^{A t} ( \int e^{- A t} b \,dt + C) When $A(t)$ is coefficient matrix such that its commutative with its antiderivative $B(t)$ and $b(t)$ is a zero vector i.e. system is homogeneous, the system is "type3". The solution is: .. math:: X(t) = \exp(B(t)) C When $A(t)$ is commutative with its antiderivative $B(t)$ and $b(t)$ is non-zero i.e. system is non-homogeneous, the system is "type4". The solution is: .. math:: X(t) = e^{B(t)} ( \int e^{-B(t)} b(t) \,dt + C) When $A(t)$ is a coefficient matrix such that it can be factorized into a scalar and a constant coefficient matrix: .. math:: A(t) = f(t) * A Where $f(t)$ is a scalar expression in the independent variable $t$ and $A$ is a constant matrix, then we can do the following substitutions: .. math:: tau = \int f(t) dt, X(t) = Y(tau), b(t) = b(f^{-1}(tau)) Here, the substitution for the non-homogeneous term is done only when its non-zero. Using these substitutions, our original system becomes: .. math:: Y'(tau) = A * Y(tau) + b(tau)/f(tau) The above system can be easily solved using the solution for "type1" or "type2" depending on the homogeneity of the system. After we get the solution for $Y(tau)$, we substitute the solution for $tau$ as $t$ to get back $X(t)$ .. math:: X(t) = Y(tau) Systems of "type5" and "type6" have a commutative antiderivative but we use this solution because its faster to compute. The final solution is the general solution for all the four equations since a constant coefficient matrix is always commutative with its antidervative. An additional feature of this function is, if someone wants to substitute for value of the independent variable, they can pass the substitution `tau` and the solution will have the independent variable substituted with the passed expression(`tau`). Parameters ========== A : Matrix Coefficient matrix of the system of linear first order ODEs. t : Symbol Independent variable in the system of ODEs. b : Matrix or None Non-homogeneous term in the system of ODEs. If None is passed, a homogeneous system of ODEs is assumed. B : Matrix or None Antiderivative of the coefficient matrix. If the antiderivative is not passed and the solution requires the term, then the solver would compute it internally. type : String Type of the system of ODEs passed. Depending on the type, the solution is evaluated. The type values allowed and the corresponding system it solves are: "type1" for constant coefficient homogeneous "type2" for constant coefficient non-homogeneous, "type3" for non-constant coefficient homogeneous, "type4" for non-constant coefficient non-homogeneous, "type5" and "type6" for non-constant coefficient homogeneous and non-homogeneous systems respectively where the coefficient matrix can be factorized to a constant coefficient matrix. The default value is "auto" which will let the solver decide the correct type of the system passed. doit : Boolean Evaluate the solution if True, default value is False tau: Expression Used to substitute for the value of `t` after we get the solution of the system. Examples ======== To solve the system of ODEs using this function directly, several things must be done in the right order. Wrong inputs to the function will lead to incorrect results. >>> from sympy import symbols, Function, Eq >>> from sympy.solvers.ode.systems import canonical_odes, linear_ode_to_matrix, linodesolve, linodesolve_type >>> from sympy.solvers.ode.subscheck import checkodesol >>> f, g = symbols("f, g", cls=Function) >>> x, a = symbols("x, a") >>> funcs = [f(x), g(x)] >>> eqs = [Eq(f(x).diff(x) - f(x), a*g(x) + 1), Eq(g(x).diff(x) + g(x), a*f(x))] Here, it is important to note that before we derive the coefficient matrix, it is important to get the system of ODEs into the desired form. For that we will use :obj:`sympy.solvers.ode.systems.canonical_odes()`. >>> eqs = canonical_odes(eqs, funcs, x) >>> eqs [[Eq(Derivative(f(x), x), a*g(x) + f(x) + 1), Eq(Derivative(g(x), x), a*f(x) - g(x))]] Now, we will use :obj:`sympy.solvers.ode.systems.linear_ode_to_matrix()` to get the coefficient matrix and the non-homogeneous term if it is there. >>> eqs = eqs[0] >>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, x, 1) >>> A = A0 We have the coefficient matrices and the non-homogeneous term ready. Now, we can use :obj:`sympy.solvers.ode.systems.linodesolve_type()` to get the information for the system of ODEs to finally pass it to the solver. >>> system_info = linodesolve_type(A, x, b=b) >>> sol_vector = linodesolve(A, x, b=b, B=system_info['antiderivative'], type=system_info['type_of_equation']) Now, we can prove if the solution is correct or not by using :obj:`sympy.solvers.ode.checkodesol()` >>> sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)] >>> checkodesol(eqs, sol) (True, [0, 0]) We can also use the doit method to evaluate the solutions passed by the function. >>> sol_vector_evaluated = linodesolve(A, x, b=b, type="type2", doit=True) Now, we will look at a system of ODEs which is non-constant. >>> eqs = [Eq(f(x).diff(x), f(x) + x*g(x)), Eq(g(x).diff(x), -x*f(x) + g(x))] The system defined above is already in the desired form, so we do not have to convert it. >>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, x, 1) >>> A = A0 A user can also pass the commutative antiderivative required for type3 and type4 system of ODEs. Passing an incorrect one will lead to incorrect results. If the coefficient matrix is not commutative with its antiderivative, then :obj:`sympy.solvers.ode.systems.linodesolve_type()` raises a NotImplementedError. If it does have a commutative antiderivative, then the function just returns the information about the system. >>> system_info = linodesolve_type(A, x, b=b) Now, we can pass the antiderivative as an argument to get the solution. If the system information is not passed, then the solver will compute the required arguments internally. >>> sol_vector = linodesolve(A, x, b=b) Once again, we can verify the solution obtained. >>> sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)] >>> checkodesol(eqs, sol) (True, [0, 0]) Returns ======= List Raises ====== ValueError This error is raised when the coefficient matrix, non-homogeneous term or the antiderivative, if passed, aren't a matrix or do not have correct dimensions NonSquareMatrixError When the coefficient matrix or its antiderivative, if passed isn't a square matrix NotImplementedError If the coefficient matrix doesn't have a commutative antiderivative See Also ======== linear_ode_to_matrix: Coefficient matrix computation function canonical_odes: System of ODEs representation change linodesolve_type: Getting information about systems of ODEs to pass in this solver """ if not isinstance(A, MatrixBase): raise ValueError(filldedent('''\ The coefficients of the system of ODEs should be of type Matrix ''')) if not A.is_square: raise NonSquareMatrixError(filldedent('''\ The coefficient matrix must be a square ''')) if b is not None: if not isinstance(b, MatrixBase): raise ValueError(filldedent('''\ The non-homogeneous terms of the system of ODEs should be of type Matrix ''')) if A.rows != b.rows: raise ValueError(filldedent('''\ The system of ODEs should have the same number of non-homogeneous terms and the number of equations ''')) if B is not None: if not isinstance(B, MatrixBase): raise ValueError(filldedent('''\ The antiderivative of coefficients of the system of ODEs should be of type Matrix ''')) if not B.is_square: raise NonSquareMatrixError(filldedent('''\ The antiderivative of the coefficient matrix must be a square ''')) if A.rows != B.rows: raise ValueError(filldedent('''\ The coefficient matrix and its antiderivative should have same dimensions ''')) if not any(type == "type{}".format(i) for i in range(1, 7)) and not type == "auto": raise ValueError(filldedent('''\ The input type should be a valid one ''')) n = A.rows # constants = numbered_symbols(prefix='C', cls=Dummy, start=const_idx+1) Cvect = Matrix(list(Dummy() for _ in range(n))) if any(type == typ for typ in ["type2", "type4", "type6"]) and b is None: b = zeros(n, 1) is_transformed = tau is not None passed_type = type if type == "auto": system_info = linodesolve_type(A, t, b=b) type = system_info["type_of_equation"] B = system_info["antiderivative"] if type in ("type5", "type6"): is_transformed = True if passed_type != "auto": if tau is None: system_info = _first_order_type5_6_subs(A, t, b=b) if not system_info: raise ValueError(filldedent(''' The system passed isn't {}. '''.format(type))) tau = system_info['tau'] t = system_info['t_'] A = system_info['A'] b = system_info['b'] if type in ("type1", "type2", "type5", "type6"): P, J = matrix_exp_jordan_form(A, t) P = simplify(P) if type in ("type1", "type5"): sol_vector = P * (J * Cvect) else: sol_vector = P * J * ((J.inv() * P.inv() * b).applyfunc(lambda x: Integral(x, t)) + Cvect) else: if B is None: B, _ = _is_commutative_anti_derivative(A, t) if type == "type3": sol_vector = B.exp() * Cvect else: sol_vector = B.exp() * (((-B).exp() * b).applyfunc(lambda x: Integral(x, t)) + Cvect) if is_transformed: sol_vector = sol_vector.subs(t, tau) gens = sol_vector.atoms(exp) if type != "type1": sol_vector = [expand_mul(s) for s in sol_vector] sol_vector = [collect(s, ordered(gens), exact=True) for s in sol_vector] if doit: sol_vector = [s.doit() for s in sol_vector] return sol_vector def _matrix_is_constant(M, t): """Checks if the matrix M is independent of t or not.""" return all(coef.as_independent(t, as_Add=True)[1] == 0 for coef in M) def canonical_odes(eqs, funcs, t): r""" Function that solves for highest order derivatives in a system Explanation =========== This function inputs a system of ODEs and based on the system, the dependent variables and their highest order, returns the system in the following form: .. math:: X'(t) = A(t) X(t) + b(t) Here, $X(t)$ is the vector of dependent variables of lower order, $A(t)$ is the coefficient matrix, $b(t)$ is the non-homogeneous term and $X'(t)$ is the vector of dependent variables in their respective highest order. We use the term canonical form to imply the system of ODEs which is of the above form. If the system passed has a non-linear term with multiple solutions, then a list of systems is returned in its canonical form. Parameters ========== eqs : List List of the ODEs funcs : List List of dependent variables t : Symbol Independent variable Examples ======== >>> from sympy import symbols, Function, Eq, Derivative >>> from sympy.solvers.ode.systems import canonical_odes >>> f, g = symbols("f g", cls=Function) >>> x, y = symbols("x y") >>> funcs = [f(x), g(x)] >>> eqs = [Eq(f(x).diff(x) - 7*f(x), 12*g(x)), Eq(g(x).diff(x) + g(x), 20*f(x))] >>> canonical_eqs = canonical_odes(eqs, funcs, x) >>> canonical_eqs [[Eq(Derivative(f(x), x), 7*f(x) + 12*g(x)), Eq(Derivative(g(x), x), 20*f(x) - g(x))]] >>> system = [Eq(Derivative(f(x), x)**2 - 2*Derivative(f(x), x) + 1, 4), Eq(-y*f(x) + Derivative(g(x), x), 0)] >>> canonical_system = canonical_odes(system, funcs, x) >>> canonical_system [[Eq(Derivative(f(x), x), -1), Eq(Derivative(g(x), x), y*f(x))], [Eq(Derivative(f(x), x), 3), Eq(Derivative(g(x), x), y*f(x))]] Returns ======= List """ from sympy.solvers.solvers import solve order = _get_func_order(eqs, funcs) canon_eqs = solve(eqs, *[func.diff(t, order[func]) for func in funcs], dict=True) systems = [] for eq in canon_eqs: system = [Eq(func.diff(t, order[func]), eq[func.diff(t, order[func])]) for func in funcs] systems.append(system) return systems def _is_commutative_anti_derivative(A, t): r""" Helper function for determining if the Matrix passed is commutative with its antiderivative Explanation =========== This function checks if the Matrix $A$ passed is commutative with its antiderivative with respect to the independent variable $t$. .. math:: B(t) = \int A(t) dt The function outputs two values, first one being the antiderivative $B(t)$, second one being a boolean value, if True, then the matrix $A(t)$ passed is commutative with $B(t)$, else the matrix passed isn't commutative with $B(t)$. Parameters ========== A : Matrix The matrix which has to be checked t : Symbol Independent variable Examples ======== >>> from sympy import symbols, Matrix >>> from sympy.solvers.ode.systems import _is_commutative_anti_derivative >>> t = symbols("t") >>> A = Matrix([[1, t], [-t, 1]]) >>> B, is_commuting = _is_commutative_anti_derivative(A, t) >>> is_commuting True Returns ======= Matrix, Boolean """ B = integrate(A, t) is_commuting = (B*A - A*B).applyfunc(expand).applyfunc(factor_terms).is_zero_matrix is_commuting = False if is_commuting is None else is_commuting return B, is_commuting def _factor_matrix(A, t): term = None for element in A: temp_term = element.as_independent(t)[1] if temp_term.has(t): term = temp_term break if term is not None: A_factored = (A/term).applyfunc(ratsimp) can_factor = _matrix_is_constant(A_factored, t) term = (term, A_factored) if can_factor else None return term def _is_second_order_type2(A, t): term = _factor_matrix(A, t) is_type2 = False if term is not None: term = 1/term[0] is_type2 = term.is_polynomial() if is_type2: poly = Poly(term.expand(), t) monoms = poly.monoms() if monoms[0][0] in (2, 4): cs = _get_poly_coeffs(poly, 4) a, b, c, d, e = cs a1 = powdenest(sqrt(a), force=True) c1 = powdenest(sqrt(e), force=True) b1 = powdenest(sqrt(c - 2*a1*c1), force=True) is_type2 = (b == 2*a1*b1) and (d == 2*b1*c1) term = a1*t**2 + b1*t + c1 else: is_type2 = False return is_type2, term def _get_poly_coeffs(poly, order): cs = [0 for _ in range(order+1)] for c, m in zip(poly.coeffs(), poly.monoms()): cs[-1-m[0]] = c return cs def _match_second_order_type(A1, A0, t, b=None): r""" Works only for second order system in its canonical form. Type 0: Constant coefficient matrix, can be simply solved by introducing dummy variables. Type 1: When the substitution: $U = t*X' - X$ works for reducing the second order system to first order system. Type 2: When the system is of the form: $poly * X'' = A*X$ where $poly$ is square of a quadratic polynomial with respect to *t* and $A$ is a constant coefficient matrix. """ match = {"type_of_equation": "type0"} n = A1.shape[0] if _matrix_is_constant(A1, t) and _matrix_is_constant(A0, t): return match if (A1 + A0*t).applyfunc(expand_mul).is_zero_matrix: match.update({"type_of_equation": "type1", "A1": A1}) elif A1.is_zero_matrix and (b is None or b.is_zero_matrix): is_type2, term = _is_second_order_type2(A0, t) if is_type2: a, b, c = _get_poly_coeffs(Poly(term, t), 2) A = (A0*(term**2).expand()).applyfunc(ratsimp) + (b**2/4 - a*c)*eye(n, n) tau = integrate(1/term, t) t_ = Symbol("{}_".format(t)) match.update({"type_of_equation": "type2", "A0": A, "g(t)": sqrt(term), "tau": tau, "is_transformed": True, "t_": t_}) return match def _second_order_subs_type1(A, b, funcs, t): r""" For a linear, second order system of ODEs, a particular substitution. A system of the below form can be reduced to a linear first order system of ODEs: .. math:: X'' = A(t) * (t*X' - X) + b(t) By substituting: .. math:: U = t*X' - X To get the system: .. math:: U' = t*(A(t)*U + b(t)) Where $U$ is the vector of dependent variables, $X$ is the vector of dependent variables in `funcs` and $X'$ is the first order derivative of $X$ with respect to $t$. It may or may not reduce the system into linear first order system of ODEs. Then a check is made to determine if the system passed can be reduced or not, if this substitution works, then the system is reduced and its solved for the new substitution. After we get the solution for $U$: .. math:: U = a(t) We substitute and return the reduced system: .. math:: a(t) = t*X' - X Parameters ========== A: Matrix Coefficient matrix($A(t)*t$) of the second order system of this form. b: Matrix Non-homogeneous term($b(t)$) of the system of ODEs. funcs: List List of dependent variables t: Symbol Independent variable of the system of ODEs. Returns ======= List """ U = Matrix([t*func.diff(t) - func for func in funcs]) sol = linodesolve(A, t, t*b) reduced_eqs = [Eq(u, s) for s, u in zip(sol, U)] reduced_eqs = canonical_odes(reduced_eqs, funcs, t)[0] return reduced_eqs def _second_order_subs_type2(A, funcs, t_): r""" Returns a second order system based on the coefficient matrix passed. Explanation =========== This function returns a system of second order ODE of the following form: .. math:: X'' = A * X Here, $X$ is the vector of dependent variables, but a bit modified, $A$ is the coefficient matrix passed. Along with returning the second order system, this function also returns the new dependent variables with the new independent variable `t_` passed. Parameters ========== A: Matrix Coefficient matrix of the system funcs: List List of old dependent variables t_: Symbol New independent variable Returns ======= List, List """ func_names = [func.func.__name__ for func in funcs] new_funcs = [Function(Dummy("{}_".format(name)))(t_) for name in func_names] rhss = A * Matrix(new_funcs) new_eqs = [Eq(func.diff(t_, 2), rhs) for func, rhs in zip(new_funcs, rhss)] return new_eqs, new_funcs def _is_euler_system(As, t): return all(_matrix_is_constant((A*t**i).applyfunc(ratsimp), t) for i, A in enumerate(As)) def _classify_linear_system(eqs, funcs, t, is_canon=False): r""" Returns a dictionary with details of the eqs if the system passed is linear and can be classified by this function else returns None Explanation =========== This function takes the eqs, converts it into a form Ax = b where x is a vector of terms containing dependent variables and their derivatives till their maximum order. If it is possible to convert eqs into Ax = b, then all the equations in eqs are linear otherwise they are non-linear. To check if the equations are constant coefficient, we need to check if all the terms in A obtained above are constant or not. To check if the equations are homogeneous or not, we need to check if b is a zero matrix or not. Parameters ========== eqs: List List of ODEs funcs: List List of dependent variables t: Symbol Independent variable of the equations in eqs is_canon: Boolean If True, then this function will not try to get the system in canonical form. Default value is False Returns ======= match = { 'no_of_equation': len(eqs), 'eq': eqs, 'func': funcs, 'order': order, 'is_linear': is_linear, 'is_constant': is_constant, 'is_homogeneous': is_homogeneous, } Dict or list of Dicts or None Dict with values for keys: 1. no_of_equation: Number of equations 2. eq: The set of equations 3. func: List of dependent variables 4. order: A dictionary that gives the order of the dependent variable in eqs 5. is_linear: Boolean value indicating if the set of equations are linear or not. 6. is_constant: Boolean value indicating if the set of equations have constant coefficients or not. 7. is_homogeneous: Boolean value indicating if the set of equations are homogeneous or not. 8. commutative_antiderivative: Antiderivative of the coefficient matrix if the coefficient matrix is non-constant and commutative with its antiderivative. This key may or may not exist. 9. is_general: Boolean value indicating if the system of ODEs is solvable using one of the general case solvers or not. 10. rhs: rhs of the non-homogeneous system of ODEs in Matrix form. This key may or may not exist. 11. is_higher_order: True if the system passed has an order greater than 1. This key may or may not exist. 12. is_second_order: True if the system passed is a second order ODE. This key may or may not exist. This Dict is the answer returned if the eqs are linear and constant coefficient. Otherwise, None is returned. """ # Error for i == 0 can be added but isn't for now # Check for len(funcs) == len(eqs) if len(funcs) != len(eqs): raise ValueError("Number of functions given is not equal to the number of equations %s" % funcs) # ValueError when functions have more than one arguments for func in funcs: if len(func.args) != 1: raise ValueError("dsolve() and classify_sysode() work with " "functions of one variable only, not %s" % func) # Getting the func_dict and order using the helper # function order = _get_func_order(eqs, funcs) system_order = max(order[func] for func in funcs) is_higher_order = system_order > 1 is_second_order = system_order == 2 and all(order[func] == 2 for func in funcs) # Not adding the check if the len(func.args) for # every func in funcs is 1 # Linearity check try: canon_eqs = canonical_odes(eqs, funcs, t) if not is_canon else [eqs] if len(canon_eqs) == 1: As, b = linear_ode_to_matrix(canon_eqs[0], funcs, t, system_order) else: match = { 'is_implicit': True, 'canon_eqs': canon_eqs } return match # When the system of ODEs is non-linear, an ODENonlinearError is raised. # This function catches the error and None is returned. except ODENonlinearError: return None is_linear = True # Homogeneous check is_homogeneous = True if b.is_zero_matrix else False # Is general key is used to identify if the system of ODEs can be solved by # one of the general case solvers or not. match = { 'no_of_equation': len(eqs), 'eq': eqs, 'func': funcs, 'order': order, 'is_linear': is_linear, 'is_homogeneous': is_homogeneous, 'is_general': True } if not is_homogeneous: match['rhs'] = b is_constant = all(_matrix_is_constant(A_, t) for A_ in As) # The match['is_linear'] check will be added in the future when this # function becomes ready to deal with non-linear systems of ODEs if not is_higher_order: A = As[1] match['func_coeff'] = A # Constant coefficient check is_constant = _matrix_is_constant(A, t) match['is_constant'] = is_constant try: system_info = linodesolve_type(A, t, b=b) except NotImplementedError: return None match.update(system_info) antiderivative = match.pop("antiderivative") if not is_constant: match['commutative_antiderivative'] = antiderivative return match else: match['type_of_equation'] = "type0" if is_second_order: A1, A0 = As[1:] match_second_order = _match_second_order_type(A1, A0, t) match.update(match_second_order) match['is_second_order'] = True # If system is constant, then no need to check if its in euler # form or not. It will be easier and faster to directly proceed # to solve it. if match['type_of_equation'] == "type0" and not is_constant: is_euler = _is_euler_system(As, t) if is_euler: t_ = Symbol('{}_'.format(t)) match.update({'is_transformed': True, 'type_of_equation': 'type1', 't_': t_}) else: is_jordan = lambda M: M == Matrix.jordan_block(M.shape[0], M[0, 0]) terms = _factor_matrix(As[-1], t) if all(A.is_zero_matrix for A in As[1:-1]) and terms is not None and not is_jordan(terms[1]): P, J = terms[1].jordan_form() match.update({'type_of_equation': 'type2', 'J': J, 'f(t)': terms[0], 'P': P, 'is_transformed': True}) if match['type_of_equation'] != 'type0' and is_second_order: match.pop('is_second_order', None) match['is_higher_order'] = is_higher_order return match def _preprocess_eqs(eqs): processed_eqs = [] for eq in eqs: processed_eqs.append(eq if isinstance(eq, Equality) else Eq(eq, 0)) return processed_eqs def _eqs2dict(eqs, funcs): eqsorig = {} eqsmap = {} funcset = set(funcs) for eq in eqs: f1, = eq.lhs.atoms(AppliedUndef) f2s = (eq.rhs.atoms(AppliedUndef) - {f1}) & funcset eqsmap[f1] = f2s eqsorig[f1] = eq return eqsmap, eqsorig def _dict2graph(d): nodes = list(d) edges = [(f1, f2) for f1, f2s in d.items() for f2 in f2s] G = (nodes, edges) return G def _is_type1(scc, t): eqs, funcs = scc try: (A1, A0), b = linear_ode_to_matrix(eqs, funcs, t, 1) except (ODENonlinearError, ODEOrderError): return False if _matrix_is_constant(A0, t) and b.is_zero_matrix: return True return False def _combine_type1_subsystems(subsystem, funcs, t): indices = [i for i, sys in enumerate(zip(subsystem, funcs)) if _is_type1(sys, t)] remove = set() for ip, i in enumerate(indices): for j in indices[ip+1:]: if any(eq2.has(funcs[i]) for eq2 in subsystem[j]): subsystem[j] = subsystem[i] + subsystem[j] remove.add(i) subsystem = [sys for i, sys in enumerate(subsystem) if i not in remove] return subsystem def _component_division(eqs, funcs, t): # Assuming that each eq in eqs is in canonical form, # that is, [f(x).diff(x) = .., g(x).diff(x) = .., etc] # and that the system passed is in its first order eqsmap, eqsorig = _eqs2dict(eqs, funcs) subsystems = [] for cc in connected_components(_dict2graph(eqsmap)): eqsmap_c = {f: eqsmap[f] for f in cc} sccs = strongly_connected_components(_dict2graph(eqsmap_c)) subsystem = [[eqsorig[f] for f in scc] for scc in sccs] subsystem = _combine_type1_subsystems(subsystem, sccs, t) subsystems.append(subsystem) return subsystems # Returns: List of equations def _linear_ode_solver(match): t = match['t'] funcs = match['func'] rhs = match.get('rhs', None) tau = match.get('tau', None) t = match['t_'] if 't_' in match else t A = match['func_coeff'] # Note: To make B None when the matrix has constant # coefficient B = match.get('commutative_antiderivative', None) type = match['type_of_equation'] sol_vector = linodesolve(A, t, b=rhs, B=B, type=type, tau=tau) sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)] return sol def _select_equations(eqs, funcs, key=lambda x: x): eq_dict = {e.lhs: e.rhs for e in eqs} return [Eq(f, eq_dict[key(f)]) for f in funcs] def _higher_order_ode_solver(match): eqs = match["eq"] funcs = match["func"] t = match["t"] sysorder = match['order'] type = match.get('type_of_equation', "type0") is_second_order = match.get('is_second_order', False) is_transformed = match.get('is_transformed', False) is_euler = is_transformed and type == "type1" is_higher_order_type2 = is_transformed and type == "type2" and 'P' in match if is_second_order: new_eqs, new_funcs = _second_order_to_first_order(eqs, funcs, t, A1=match.get("A1", None), A0=match.get("A0", None), b=match.get("rhs", None), type=type, t_=match.get("t_", None)) else: new_eqs, new_funcs = _higher_order_to_first_order(eqs, sysorder, t, funcs=funcs, type=type, J=match.get('J', None), f_t=match.get('f(t)', None), P=match.get('P', None), b=match.get('rhs', None)) if is_transformed: t = match.get('t_', t) if not is_higher_order_type2: new_eqs = _select_equations(new_eqs, [f.diff(t) for f in new_funcs]) sol = None # NotImplementedError may be raised when the system may be actually # solvable if it can be just divided into sub-systems try: if not is_higher_order_type2: sol = _strong_component_solver(new_eqs, new_funcs, t) except NotImplementedError: sol = None # Dividing the system only when it becomes essential if sol is None: try: sol = _component_solver(new_eqs, new_funcs, t) except NotImplementedError: sol = None if sol is None: return sol is_second_order_type2 = is_second_order and type == "type2" underscores = '__' if is_transformed else '_' sol = _select_equations(sol, funcs, key=lambda x: Function(Dummy('{}{}0'.format(x.func.__name__, underscores)))(t)) if match.get("is_transformed", False): if is_second_order_type2: g_t = match["g(t)"] tau = match["tau"] sol = [Eq(s.lhs, s.rhs.subs(t, tau) * g_t) for s in sol] elif is_euler: t = match['t'] tau = match['t_'] sol = [s.subs(tau, log(t)) for s in sol] elif is_higher_order_type2: P = match['P'] sol_vector = P * Matrix([s.rhs for s in sol]) sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)] return sol # Returns: List of equations or None # If None is returned by this solver, then the system # of ODEs cannot be solved directly by dsolve_system. def _strong_component_solver(eqs, funcs, t): from sympy.solvers.ode.ode import dsolve, constant_renumber match = _classify_linear_system(eqs, funcs, t, is_canon=True) sol = None # Assuming that we can't get an implicit system # since we are already canonical equations from # dsolve_system if match: match['t'] = t if match.get('is_higher_order', False): sol = _higher_order_ode_solver(match) elif match.get('is_linear', False): sol = _linear_ode_solver(match) # Note: For now, only linear systems are handled by this function # hence, the match condition is added. This can be removed later. if sol is None and len(eqs) == 1: sol = dsolve(eqs[0], func=funcs[0]) variables = Tuple(eqs[0]).free_symbols new_constants = [Dummy() for _ in range(ode_order(eqs[0], funcs[0]))] sol = constant_renumber(sol, variables=variables, newconstants=new_constants) sol = [sol] # To add non-linear case here in future return sol def _get_funcs_from_canon(eqs): return [eq.lhs.args[0] for eq in eqs] # Returns: List of Equations(a solution) def _weak_component_solver(wcc, t): # We will divide the systems into sccs # only when the wcc cannot be solved as # a whole eqs = [] for scc in wcc: eqs += scc funcs = _get_funcs_from_canon(eqs) sol = _strong_component_solver(eqs, funcs, t) if sol: return sol sol = [] for j, scc in enumerate(wcc): eqs = scc funcs = _get_funcs_from_canon(eqs) # Substituting solutions for the dependent # variables solved in previous SCC, if any solved. comp_eqs = [eq.subs({s.lhs: s.rhs for s in sol}) for eq in eqs] scc_sol = _strong_component_solver(comp_eqs, funcs, t) if scc_sol is None: raise NotImplementedError(filldedent(''' The system of ODEs passed cannot be solved by dsolve_system. ''')) # scc_sol: List of equations # scc_sol is a solution sol += scc_sol return sol # Returns: List of Equations(a solution) def _component_solver(eqs, funcs, t): components = _component_division(eqs, funcs, t) sol = [] for wcc in components: # wcc_sol: List of Equations sol += _weak_component_solver(wcc, t) # sol: List of Equations return sol def _second_order_to_first_order(eqs, funcs, t, type="auto", A1=None, A0=None, b=None, t_=None): r""" Expects the system to be in second order and in canonical form Explanation =========== Reduces a second order system into a first order one depending on the type of second order system. 1. "type0": If this is passed, then the system will be reduced to first order by introducing dummy variables. 2. "type1": If this is passed, then a particular substitution will be used to reduce the the system into first order. 3. "type2": If this is passed, then the system will be transformed with new dependent variables and independent variables. This transformation is a part of solving the corresponding system of ODEs. `A1` and `A0` are the coefficient matrices from the system and it is assumed that the second order system has the form given below: .. math:: A2 * X'' = A1 * X' + A0 * X + b Here, $A2$ is the coefficient matrix for the vector $X''$ and $b$ is the non-homogeneous term. Default value for `b` is None but if `A1` and `A0` are passed and `b` isn't passed, then the system will be assumed homogeneous. """ is_a1 = A1 is None is_a0 = A0 is None if (type == "type1" and is_a1) or (type == "type2" and is_a0)\ or (type == "auto" and (is_a1 or is_a0)): (A2, A1, A0), b = linear_ode_to_matrix(eqs, funcs, t, 2) if not A2.is_Identity: raise ValueError(filldedent(''' The system must be in its canonical form. ''')) if type == "auto": match = _match_second_order_type(A1, A0, t) type = match["type_of_equation"] A1 = match.get("A1", None) A0 = match.get("A0", None) sys_order = {func: 2 for func in funcs} if type == "type1": if b is None: b = zeros(len(eqs)) eqs = _second_order_subs_type1(A1, b, funcs, t) sys_order = {func: 1 for func in funcs} if type == "type2": if t_ is None: t_ = Symbol("{}_".format(t)) t = t_ eqs, funcs = _second_order_subs_type2(A0, funcs, t_) sys_order = {func: 2 for func in funcs} return _higher_order_to_first_order(eqs, sys_order, t, funcs=funcs) def _higher_order_type2_to_sub_systems(J, f_t, funcs, t, max_order, b=None, P=None): # Note: To add a test for this ValueError if J is None or f_t is None or not _matrix_is_constant(J, t): raise ValueError(filldedent(''' Correctly input for args 'A' and 'f_t' for Linear, Higher Order, Type 2 ''')) if P is None and b is not None and not b.is_zero_matrix: raise ValueError(filldedent(''' Provide the keyword 'P' for matrix P in A = P * J * P-1. ''')) new_funcs = Matrix([Function(Dummy('{}__0'.format(f.func.__name__)))(t) for f in funcs]) new_eqs = new_funcs.diff(t, max_order) - f_t * J * new_funcs if b is not None and not b.is_zero_matrix: new_eqs -= P.inv() * b new_eqs = canonical_odes(new_eqs, new_funcs, t)[0] return new_eqs, new_funcs def _higher_order_to_first_order(eqs, sys_order, t, funcs=None, type="type0", **kwargs): if funcs is None: funcs = sys_order.keys() # Standard Cauchy Euler system if type == "type1": t_ = Symbol('{}_'.format(t)) new_funcs = [Function(Dummy('{}_'.format(f.func.__name__)))(t_) for f in funcs] max_order = max(sys_order[func] for func in funcs) subs_dict = {func: new_func for func, new_func in zip(funcs, new_funcs)} subs_dict[t] = exp(t_) free_function = Function(Dummy()) def _get_coeffs_from_subs_expression(expr): if isinstance(expr, Subs): free_symbol = expr.args[1][0] term = expr.args[0] return {ode_order(term, free_symbol): 1} if isinstance(expr, Mul): coeff = expr.args[0] order = list(_get_coeffs_from_subs_expression(expr.args[1]).keys())[0] return {order: coeff} if isinstance(expr, Add): coeffs = {} for arg in expr.args: if isinstance(arg, Mul): coeffs.update(_get_coeffs_from_subs_expression(arg)) else: order = list(_get_coeffs_from_subs_expression(arg).keys())[0] coeffs[order] = 1 return coeffs for o in range(1, max_order + 1): expr = free_function(log(t_)).diff(t_, o)*t_**o coeff_dict = _get_coeffs_from_subs_expression(expr) coeffs = [coeff_dict[order] if order in coeff_dict else 0 for order in range(o + 1)] expr_to_subs = sum(free_function(t_).diff(t_, i) * c for i, c in enumerate(coeffs)) / t**o subs_dict.update({f.diff(t, o): expr_to_subs.subs(free_function(t_), nf) for f, nf in zip(funcs, new_funcs)}) new_eqs = [eq.subs(subs_dict) for eq in eqs] new_sys_order = {nf: sys_order[f] for f, nf in zip(funcs, new_funcs)} new_eqs = canonical_odes(new_eqs, new_funcs, t_)[0] return _higher_order_to_first_order(new_eqs, new_sys_order, t_, funcs=new_funcs) # Systems of the form: X(n)(t) = f(t)*A*X + b # where X(n)(t) is the nth derivative of the vector of dependent variables # with respect to the independent variable and A is a constant matrix. if type == "type2": J = kwargs.get('J', None) f_t = kwargs.get('f_t', None) b = kwargs.get('b', None) P = kwargs.get('P', None) max_order = max(sys_order[func] for func in funcs) return _higher_order_type2_to_sub_systems(J, f_t, funcs, t, max_order, P=P, b=b) # Note: To be changed to this after doit option is disabled for default cases # new_sysorder = _get_func_order(new_eqs, new_funcs) # # return _higher_order_to_first_order(new_eqs, new_sysorder, t, funcs=new_funcs) new_funcs = [] for prev_func in funcs: func_name = prev_func.func.__name__ func = Function(Dummy('{}_0'.format(func_name)))(t) new_funcs.append(func) subs_dict = {prev_func: func} new_eqs = [] for i in range(1, sys_order[prev_func]): new_func = Function(Dummy('{}_{}'.format(func_name, i)))(t) subs_dict[prev_func.diff(t, i)] = new_func new_funcs.append(new_func) prev_f = subs_dict[prev_func.diff(t, i-1)] new_eq = Eq(prev_f.diff(t), new_func) new_eqs.append(new_eq) eqs = [eq.subs(subs_dict) for eq in eqs] + new_eqs return eqs, new_funcs def dsolve_system(eqs, funcs=None, t=None, ics=None, doit=False, simplify=True): r""" Solves any(supported) system of Ordinary Differential Equations Explanation =========== This function takes a system of ODEs as an input, determines if the it is solvable by this function, and returns the solution if found any. This function can handle: 1. Linear, First Order, Constant coefficient homogeneous system of ODEs 2. Linear, First Order, Constant coefficient non-homogeneous system of ODEs 3. Linear, First Order, non-constant coefficient homogeneous system of ODEs 4. Linear, First Order, non-constant coefficient non-homogeneous system of ODEs 5. Any implicit system which can be divided into system of ODEs which is of the above 4 forms 6. Any higher order linear system of ODEs that can be reduced to one of the 5 forms of systems described above. The types of systems described above aren't limited by the number of equations, i.e. this function can solve the above types irrespective of the number of equations in the system passed. But, the bigger the system, the more time it will take to solve the system. This function returns a list of solutions. Each solution is a list of equations where LHS is the dependent variable and RHS is an expression in terms of the independent variable. Among the non constant coefficient types, not all the systems are solvable by this function. Only those which have either a coefficient matrix with a commutative antiderivative or those systems which may be divided further so that the divided systems may have coefficient matrix with commutative antiderivative. Parameters ========== eqs : List system of ODEs to be solved funcs : List or None List of dependent variables that make up the system of ODEs t : Symbol or None Independent variable in the system of ODEs ics : Dict or None Set of initial boundary/conditions for the system of ODEs doit : Boolean Evaluate the solutions if True. Default value is True. Can be set to false if the integral evaluation takes too much time and/or isn't required. simplify: Boolean Simplify the solutions for the systems. Default value is True. Can be set to false if simplification takes too much time and/or isn't required. Examples ======== >>> from sympy import symbols, Eq, Function >>> from sympy.solvers.ode.systems import dsolve_system >>> f, g = symbols("f g", cls=Function) >>> x = symbols("x") >>> eqs = [Eq(f(x).diff(x), g(x)), Eq(g(x).diff(x), f(x))] >>> dsolve_system(eqs) [[Eq(f(x), -C1*exp(-x) + C2*exp(x)), Eq(g(x), C1*exp(-x) + C2*exp(x))]] You can also pass the initial conditions for the system of ODEs: >>> dsolve_system(eqs, ics={f(0): 1, g(0): 0}) [[Eq(f(x), exp(x)/2 + exp(-x)/2), Eq(g(x), exp(x)/2 - exp(-x)/2)]] Optionally, you can pass the dependent variables and the independent variable for which the system is to be solved: >>> funcs = [f(x), g(x)] >>> dsolve_system(eqs, funcs=funcs, t=x) [[Eq(f(x), -C1*exp(-x) + C2*exp(x)), Eq(g(x), C1*exp(-x) + C2*exp(x))]] Lets look at an implicit system of ODEs: >>> eqs = [Eq(f(x).diff(x)**2, g(x)**2), Eq(g(x).diff(x), g(x))] >>> dsolve_system(eqs) [[Eq(f(x), C1 - C2*exp(x)), Eq(g(x), C2*exp(x))], [Eq(f(x), C1 + C2*exp(x)), Eq(g(x), C2*exp(x))]] Returns ======= List of List of Equations Raises ====== NotImplementedError When the system of ODEs is not solvable by this function. ValueError When the parameters passed aren't in the required form. """ from sympy.solvers.ode.ode import solve_ics, _extract_funcs, constant_renumber if not iterable(eqs): raise ValueError(filldedent(''' List of equations should be passed. The input is not valid. ''')) eqs = _preprocess_eqs(eqs) if funcs is not None and not isinstance(funcs, list): raise ValueError(filldedent(''' Input to the funcs should be a list of functions. ''')) if funcs is None: funcs = _extract_funcs(eqs) if any(len(func.args) != 1 for func in funcs): raise ValueError(filldedent(''' dsolve_system can solve a system of ODEs with only one independent variable. ''')) if len(eqs) != len(funcs): raise ValueError(filldedent(''' Number of equations and number of functions do not match ''')) if t is not None and not isinstance(t, Symbol): raise ValueError(filldedent(''' The indepedent variable must be of type Symbol ''')) if t is None: t = list(list(eqs[0].atoms(Derivative))[0].atoms(Symbol))[0] sols = [] canon_eqs = canonical_odes(eqs, funcs, t) for canon_eq in canon_eqs: try: sol = _strong_component_solver(canon_eq, funcs, t) except NotImplementedError: sol = None if sol is None: sol = _component_solver(canon_eq, funcs, t) sols.append(sol) if sols: final_sols = [] variables = Tuple(*eqs).free_symbols for sol in sols: sol = _select_equations(sol, funcs) sol = constant_renumber(sol, variables=variables) if ics: constants = Tuple(*sol).free_symbols - variables solved_constants = solve_ics(sol, funcs, constants, ics) sol = [s.subs(solved_constants) for s in sol] if simplify: constants = Tuple(*sol).free_symbols - variables sol = simpsol(sol, [t], constants, doit=doit) final_sols.append(sol) sols = final_sols return sols
5ad791984388f2306a0e2e3fd663a0c7dae9949d40d17c0dba1938871bdb4ea8
from sympy.core.containers import Tuple from sympy.core.function import (Function, Lambda, nfloat, diff) from sympy.core.mod import Mod from sympy.core.numbers import (E, I, Rational, oo, pi, Integer) from sympy.core.relational import (Eq, Gt, Ne, Ge) from sympy.core.singleton import S from sympy.core.sorting import ordered from sympy.core.symbol import (Dummy, Symbol, symbols) from sympy.functions.elementary.complexes import (Abs, arg, im, re, sign, conjugate) from sympy.functions.elementary.exponential import (LambertW, exp, log) from sympy.functions.elementary.hyperbolic import (HyperbolicFunction, sinh, tanh, cosh, sech, coth) from sympy.functions.elementary.miscellaneous import sqrt, Min, Max from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import ( TrigonometricFunction, acos, acot, acsc, asec, asin, atan, atan2, cos, cot, csc, sec, sin, tan) from sympy.functions.special.error_functions import (erf, erfc, erfcinv, erfinv) from sympy.logic.boolalg import And from sympy.matrices.dense import MutableDenseMatrix as Matrix from sympy.matrices.immutable import ImmutableDenseMatrix from sympy.polys.polytools import Poly from sympy.polys.rootoftools import CRootOf from sympy.sets.contains import Contains from sympy.sets.conditionset import ConditionSet from sympy.sets.fancysets import ImageSet, Range from sympy.sets.sets import (Complement, FiniteSet, Intersection, Interval, Union, imageset, ProductSet) from sympy.simplify import simplify from sympy.tensor.indexed import Indexed from sympy.utilities.iterables import numbered_symbols from sympy.testing.pytest import (XFAIL, raises, skip, slow, SKIP, _both_exp_pow) from sympy.core.random import verify_numerically as tn from sympy.physics.units import cm from sympy.solvers import solve from sympy.solvers.solveset import ( solveset_real, domain_check, solveset_complex, linear_eq_to_matrix, linsolve, _is_function_class_equation, invert_real, invert_complex, solveset, solve_decomposition, substitution, nonlinsolve, solvify, _is_finite_with_finite_vars, _transolve, _is_exponential, _solve_exponential, _is_logarithmic, _is_lambert, _solve_logarithm, _term_factors, _is_modular, NonlinearError) from sympy.abc import (a, b, c, d, e, f, g, h, i, j, k, l, m, n, q, r, t, w, x, y, z) def dumeq(i, j): if type(i) in (list, tuple): return all(dumeq(i, j) for i, j in zip(i, j)) return i == j or i.dummy_eq(j) @_both_exp_pow def test_invert_real(): x = Symbol('x', real=True) def ireal(x, s=S.Reals): return Intersection(s, x) assert invert_real(exp(x), z, x) == (x, ireal(FiniteSet(log(z)))) y = Symbol('y', positive=True) n = Symbol('n', real=True) assert invert_real(x + 3, y, x) == (x, FiniteSet(y - 3)) assert invert_real(x*3, y, x) == (x, FiniteSet(y / 3)) assert invert_real(exp(x), y, x) == (x, FiniteSet(log(y))) assert invert_real(exp(3*x), y, x) == (x, FiniteSet(log(y) / 3)) assert invert_real(exp(x + 3), y, x) == (x, FiniteSet(log(y) - 3)) assert invert_real(exp(x) + 3, y, x) == (x, ireal(FiniteSet(log(y - 3)))) assert invert_real(exp(x)*3, y, x) == (x, FiniteSet(log(y / 3))) assert invert_real(log(x), y, x) == (x, FiniteSet(exp(y))) assert invert_real(log(3*x), y, x) == (x, FiniteSet(exp(y) / 3)) assert invert_real(log(x + 3), y, x) == (x, FiniteSet(exp(y) - 3)) assert invert_real(Abs(x), y, x) == (x, FiniteSet(y, -y)) assert invert_real(2**x, y, x) == (x, FiniteSet(log(y)/log(2))) assert invert_real(2**exp(x), y, x) == (x, ireal(FiniteSet(log(log(y)/log(2))))) assert invert_real(x**2, y, x) == (x, FiniteSet(sqrt(y), -sqrt(y))) assert invert_real(x**S.Half, y, x) == (x, FiniteSet(y**2)) raises(ValueError, lambda: invert_real(x, x, x)) # issue 21236 assert invert_real(x**pi, y, x) == (x, FiniteSet(y**(1/pi))) assert invert_real(x**pi, -E, x) == (x, S.EmptySet) assert invert_real(x**Rational(3/2), 1000, x) == (x, FiniteSet(100)) assert invert_real(x**1.0, 1, x) == (x**1.0, FiniteSet(1)) raises(ValueError, lambda: invert_real(S.One, y, x)) assert invert_real(x**31 + x, y, x) == (x**31 + x, FiniteSet(y)) lhs = x**31 + x base_values = FiniteSet(y - 1, -y - 1) assert invert_real(Abs(x**31 + x + 1), y, x) == (lhs, base_values) assert dumeq(invert_real(sin(x), y, x), (x, imageset(Lambda(n, n*pi + (-1)**n*asin(y)), S.Integers))) assert dumeq(invert_real(sin(exp(x)), y, x), (x, imageset(Lambda(n, log((-1)**n*asin(y) + n*pi)), S.Integers))) assert dumeq(invert_real(csc(x), y, x), (x, imageset(Lambda(n, n*pi + (-1)**n*acsc(y)), S.Integers))) assert dumeq(invert_real(csc(exp(x)), y, x), (x, imageset(Lambda(n, log((-1)**n*acsc(y) + n*pi)), S.Integers))) assert dumeq(invert_real(cos(x), y, x), (x, Union(imageset(Lambda(n, 2*n*pi + acos(y)), S.Integers), \ imageset(Lambda(n, 2*n*pi - acos(y)), S.Integers)))) assert dumeq(invert_real(cos(exp(x)), y, x), (x, Union(imageset(Lambda(n, log(2*n*pi + acos(y))), S.Integers), \ imageset(Lambda(n, log(2*n*pi - acos(y))), S.Integers)))) assert dumeq(invert_real(sec(x), y, x), (x, Union(imageset(Lambda(n, 2*n*pi + asec(y)), S.Integers), \ imageset(Lambda(n, 2*n*pi - asec(y)), S.Integers)))) assert dumeq(invert_real(sec(exp(x)), y, x), (x, Union(imageset(Lambda(n, log(2*n*pi + asec(y))), S.Integers), \ imageset(Lambda(n, log(2*n*pi - asec(y))), S.Integers)))) assert dumeq(invert_real(tan(x), y, x), (x, imageset(Lambda(n, n*pi + atan(y)), S.Integers))) assert dumeq(invert_real(tan(exp(x)), y, x), (x, imageset(Lambda(n, log(n*pi + atan(y))), S.Integers))) assert dumeq(invert_real(cot(x), y, x), (x, imageset(Lambda(n, n*pi + acot(y)), S.Integers))) assert dumeq(invert_real(cot(exp(x)), y, x), (x, imageset(Lambda(n, log(n*pi + acot(y))), S.Integers))) assert dumeq(invert_real(tan(tan(x)), y, x), (tan(x), imageset(Lambda(n, n*pi + atan(y)), S.Integers))) x = Symbol('x', positive=True) assert invert_real(x**pi, y, x) == (x, FiniteSet(y**(1/pi))) def test_invert_complex(): assert invert_complex(x + 3, y, x) == (x, FiniteSet(y - 3)) assert invert_complex(x*3, y, x) == (x, FiniteSet(y / 3)) assert invert_complex((x - 1)**3, 0, x) == (x, FiniteSet(1)) assert dumeq(invert_complex(exp(x), y, x), (x, imageset(Lambda(n, I*(2*pi*n + arg(y)) + log(Abs(y))), S.Integers))) assert invert_complex(log(x), y, x) == (x, FiniteSet(exp(y))) raises(ValueError, lambda: invert_real(1, y, x)) raises(ValueError, lambda: invert_complex(x, x, x)) raises(ValueError, lambda: invert_complex(x, x, 1)) # https://github.com/skirpichev/omg/issues/16 assert invert_complex(sinh(x), 0, x) != (x, FiniteSet(0)) def test_domain_check(): assert domain_check(1/(1 + (1/(x+1))**2), x, -1) is False assert domain_check(x**2, x, 0) is True assert domain_check(x, x, oo) is False assert domain_check(0, x, oo) is False def test_issue_11536(): assert solveset(0**x - 100, x, S.Reals) == S.EmptySet assert solveset(0**x - 1, x, S.Reals) == FiniteSet(0) def test_issue_17479(): f = (x**2 + y**2)**2 + (x**2 + z**2)**2 - 2*(2*x**2 + y**2 + z**2) fx = f.diff(x) fy = f.diff(y) fz = f.diff(z) sol = nonlinsolve([fx, fy, fz], [x, y, z]) assert len(sol) >= 4 and len(sol) <= 20 # nonlinsolve has been giving a varying number of solutions # (originally 18, then 20, now 19) due to various internal changes. # Unfortunately not all the solutions are actually valid and some are # redundant. Since the original issue was that an exception was raised, # this first test only checks that nonlinsolve returns a "plausible" # solution set. The next test checks the result for correctness. @XFAIL def test_issue_18449(): x, y, z = symbols("x, y, z") f = (x**2 + y**2)**2 + (x**2 + z**2)**2 - 2*(2*x**2 + y**2 + z**2) fx = diff(f, x) fy = diff(f, y) fz = diff(f, z) sol = nonlinsolve([fx, fy, fz], [x, y, z]) for (xs, ys, zs) in sol: d = {x: xs, y: ys, z: zs} assert tuple(_.subs(d).simplify() for _ in (fx, fy, fz)) == (0, 0, 0) # After simplification and removal of duplicate elements, there should # only be 4 parametric solutions left: # simplifiedsolutions = FiniteSet((sqrt(1 - z**2), z, z), # (-sqrt(1 - z**2), z, z), # (sqrt(1 - z**2), -z, z), # (-sqrt(1 - z**2), -z, z)) # TODO: Is the above solution set definitely complete? def test_issue_21047(): f = (2 - x)**2 + (sqrt(x - 1) - 1)**6 assert solveset(f, x, S.Reals) == FiniteSet(2) f = (sqrt(x)-1)**2 + (sqrt(x)+1)**2 -2*x**2 + sqrt(2) assert solveset(f, x, S.Reals) == FiniteSet( S.Half - sqrt(2*sqrt(2) + 5)/2, S.Half + sqrt(2*sqrt(2) + 5)/2) def test_is_function_class_equation(): assert _is_function_class_equation(TrigonometricFunction, tan(x), x) is True assert _is_function_class_equation(TrigonometricFunction, tan(x) - 1, x) is True assert _is_function_class_equation(TrigonometricFunction, tan(x) + sin(x), x) is True assert _is_function_class_equation(TrigonometricFunction, tan(x) + sin(x) - a, x) is True assert _is_function_class_equation(TrigonometricFunction, sin(x)*tan(x) + sin(x), x) is True assert _is_function_class_equation(TrigonometricFunction, sin(x)*tan(x + a) + sin(x), x) is True assert _is_function_class_equation(TrigonometricFunction, sin(x)*tan(x*a) + sin(x), x) is True assert _is_function_class_equation(TrigonometricFunction, a*tan(x) - 1, x) is True assert _is_function_class_equation(TrigonometricFunction, tan(x)**2 + sin(x) - 1, x) is True assert _is_function_class_equation(TrigonometricFunction, tan(x) + x, x) is False assert _is_function_class_equation(TrigonometricFunction, tan(x**2), x) is False assert _is_function_class_equation(TrigonometricFunction, tan(x**2) + sin(x), x) is False assert _is_function_class_equation(TrigonometricFunction, tan(x)**sin(x), x) is False assert _is_function_class_equation(TrigonometricFunction, tan(sin(x)) + sin(x), x) is False assert _is_function_class_equation(HyperbolicFunction, tanh(x), x) is True assert _is_function_class_equation(HyperbolicFunction, tanh(x) - 1, x) is True assert _is_function_class_equation(HyperbolicFunction, tanh(x) + sinh(x), x) is True assert _is_function_class_equation(HyperbolicFunction, tanh(x) + sinh(x) - a, x) is True assert _is_function_class_equation(HyperbolicFunction, sinh(x)*tanh(x) + sinh(x), x) is True assert _is_function_class_equation(HyperbolicFunction, sinh(x)*tanh(x + a) + sinh(x), x) is True assert _is_function_class_equation(HyperbolicFunction, sinh(x)*tanh(x*a) + sinh(x), x) is True assert _is_function_class_equation(HyperbolicFunction, a*tanh(x) - 1, x) is True assert _is_function_class_equation(HyperbolicFunction, tanh(x)**2 + sinh(x) - 1, x) is True assert _is_function_class_equation(HyperbolicFunction, tanh(x) + x, x) is False assert _is_function_class_equation(HyperbolicFunction, tanh(x**2), x) is False assert _is_function_class_equation(HyperbolicFunction, tanh(x**2) + sinh(x), x) is False assert _is_function_class_equation(HyperbolicFunction, tanh(x)**sinh(x), x) is False assert _is_function_class_equation(HyperbolicFunction, tanh(sinh(x)) + sinh(x), x) is False def test_garbage_input(): raises(ValueError, lambda: solveset_real([y], y)) x = Symbol('x', real=True) assert solveset_real(x, 1) == S.EmptySet assert solveset_real(x - 1, 1) == FiniteSet(x) assert solveset_real(x, pi) == S.EmptySet assert solveset_real(x, x**2) == S.EmptySet raises(ValueError, lambda: solveset_complex([x], x)) assert solveset_complex(x, pi) == S.EmptySet raises(ValueError, lambda: solveset((x, y), x)) raises(ValueError, lambda: solveset(x + 1, S.Reals)) raises(ValueError, lambda: solveset(x + 1, x, 2)) def test_solve_mul(): assert solveset_real((a*x + b)*(exp(x) - 3), x) == \ Union({log(3)}, Intersection({-b/a}, S.Reals)) anz = Symbol('anz', nonzero=True) bb = Symbol('bb', real=True) assert solveset_real((anz*x + bb)*(exp(x) - 3), x) == \ FiniteSet(-bb/anz, log(3)) assert solveset_real((2*x + 8)*(8 + exp(x)), x) == FiniteSet(S(-4)) assert solveset_real(x/log(x), x) is S.EmptySet def test_solve_invert(): assert solveset_real(exp(x) - 3, x) == FiniteSet(log(3)) assert solveset_real(log(x) - 3, x) == FiniteSet(exp(3)) assert solveset_real(3**(x + 2), x) == FiniteSet() assert solveset_real(3**(2 - x), x) == FiniteSet() assert solveset_real(y - b*exp(a/x), x) == Intersection( S.Reals, FiniteSet(a/log(y/b))) # issue 4504 assert solveset_real(2**x - 10, x) == FiniteSet(1 + log(5)/log(2)) def test_errorinverses(): assert solveset_real(erf(x) - S.Half, x) == \ FiniteSet(erfinv(S.Half)) assert solveset_real(erfinv(x) - 2, x) == \ FiniteSet(erf(2)) assert solveset_real(erfc(x) - S.One, x) == \ FiniteSet(erfcinv(S.One)) assert solveset_real(erfcinv(x) - 2, x) == FiniteSet(erfc(2)) def test_solve_polynomial(): x = Symbol('x', real=True) y = Symbol('y', real=True) assert solveset_real(3*x - 2, x) == FiniteSet(Rational(2, 3)) assert solveset_real(x**2 - 1, x) == FiniteSet(-S.One, S.One) assert solveset_real(x - y**3, x) == FiniteSet(y ** 3) assert solveset_real(x**3 - 15*x - 4, x) == FiniteSet( -2 + 3 ** S.Half, S(4), -2 - 3 ** S.Half) assert solveset_real(sqrt(x) - 1, x) == FiniteSet(1) assert solveset_real(sqrt(x) - 2, x) == FiniteSet(4) assert solveset_real(x**Rational(1, 4) - 2, x) == FiniteSet(16) assert solveset_real(x**Rational(1, 3) - 3, x) == FiniteSet(27) assert len(solveset_real(x**5 + x**3 + 1, x)) == 1 assert len(solveset_real(-2*x**3 + 4*x**2 - 2*x + 6, x)) > 0 assert solveset_real(x**6 + x**4 + I, x) is S.EmptySet def test_return_root_of(): f = x**5 - 15*x**3 - 5*x**2 + 10*x + 20 s = list(solveset_complex(f, x)) for root in s: assert root.func == CRootOf # if one uses solve to get the roots of a polynomial that has a CRootOf # solution, make sure that the use of nfloat during the solve process # doesn't fail. Note: if you want numerical solutions to a polynomial # it is *much* faster to use nroots to get them than to solve the # equation only to get CRootOf solutions which are then numerically # evaluated. So for eq = x**5 + 3*x + 7 do Poly(eq).nroots() rather # than [i.n() for i in solve(eq)] to get the numerical roots of eq. assert nfloat(list(solveset_complex(x**5 + 3*x**3 + 7, x))[0], exponent=False) == CRootOf(x**5 + 3*x**3 + 7, 0).n() sol = list(solveset_complex(x**6 - 2*x + 2, x)) assert all(isinstance(i, CRootOf) for i in sol) and len(sol) == 6 f = x**5 - 15*x**3 - 5*x**2 + 10*x + 20 s = list(solveset_complex(f, x)) for root in s: assert root.func == CRootOf s = x**5 + 4*x**3 + 3*x**2 + Rational(7, 4) assert solveset_complex(s, x) == \ FiniteSet(*Poly(s*4, domain='ZZ').all_roots()) # Refer issue #7876 eq = x*(x - 1)**2*(x + 1)*(x**6 - x + 1) assert solveset_complex(eq, x) == \ FiniteSet(-1, 0, 1, CRootOf(x**6 - x + 1, 0), CRootOf(x**6 - x + 1, 1), CRootOf(x**6 - x + 1, 2), CRootOf(x**6 - x + 1, 3), CRootOf(x**6 - x + 1, 4), CRootOf(x**6 - x + 1, 5)) def test_solveset_sqrt_1(): assert solveset_real(sqrt(5*x + 6) - 2 - x, x) == \ FiniteSet(-S.One, S(2)) assert solveset_real(sqrt(x - 1) - x + 7, x) == FiniteSet(10) assert solveset_real(sqrt(x - 2) - 5, x) == FiniteSet(27) assert solveset_real(sqrt(x) - 2 - 5, x) == FiniteSet(49) assert solveset_real(sqrt(x**3), x) == FiniteSet(0) assert solveset_real(sqrt(x - 1), x) == FiniteSet(1) def test_solveset_sqrt_2(): x = Symbol('x', real=True) y = Symbol('y', real=True) # http://tutorial.math.lamar.edu/Classes/Alg/SolveRadicalEqns.aspx#Solve_Rad_Ex2_a assert solveset_real(sqrt(2*x - 1) - sqrt(x - 4) - 2, x) == \ FiniteSet(S(5), S(13)) assert solveset_real(sqrt(x + 7) + 2 - sqrt(3 - x), x) == \ FiniteSet(-6) # http://www.purplemath.com/modules/solverad.htm assert solveset_real(sqrt(17*x - sqrt(x**2 - 5)) - 7, x) == \ FiniteSet(3) eq = x + 1 - (x**4 + 4*x**3 - x)**Rational(1, 4) assert solveset_real(eq, x) == FiniteSet(Rational(-1, 2), Rational(-1, 3)) eq = sqrt(2*x + 9) - sqrt(x + 1) - sqrt(x + 4) assert solveset_real(eq, x) == FiniteSet(0) eq = sqrt(x + 4) + sqrt(2*x - 1) - 3*sqrt(x - 1) assert solveset_real(eq, x) == FiniteSet(5) eq = sqrt(x)*sqrt(x - 7) - 12 assert solveset_real(eq, x) == FiniteSet(16) eq = sqrt(x - 3) + sqrt(x) - 3 assert solveset_real(eq, x) == FiniteSet(4) eq = sqrt(2*x**2 - 7) - (3 - x) assert solveset_real(eq, x) == FiniteSet(-S(8), S(2)) # others eq = sqrt(9*x**2 + 4) - (3*x + 2) assert solveset_real(eq, x) == FiniteSet(0) assert solveset_real(sqrt(x - 3) - sqrt(x) - 3, x) == FiniteSet() eq = (2*x - 5)**Rational(1, 3) - 3 assert solveset_real(eq, x) == FiniteSet(16) assert solveset_real(sqrt(x) + sqrt(sqrt(x)) - 4, x) == \ FiniteSet((Rational(-1, 2) + sqrt(17)/2)**4) eq = sqrt(x) - sqrt(x - 1) + sqrt(sqrt(x)) assert solveset_real(eq, x) == FiniteSet() eq = (x - 4)**2 + (sqrt(x) - 2)**4 assert solveset_real(eq, x) == FiniteSet(-4, 4) eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6*sqrt(5)/5) ans = solveset_real(eq, x) ra = S('''-1484/375 - 4*(-1/2 + sqrt(3)*I/2)*(-12459439/52734375 + 114*sqrt(12657)/78125)**(1/3) - 172564/(140625*(-1/2 + sqrt(3)*I/2)*(-12459439/52734375 + 114*sqrt(12657)/78125)**(1/3))''') rb = Rational(4, 5) assert all(abs(eq.subs(x, i).n()) < 1e-10 for i in (ra, rb)) and \ len(ans) == 2 and \ {i.n(chop=True) for i in ans} == \ {i.n(chop=True) for i in (ra, rb)} assert solveset_real(sqrt(x) + x**Rational(1, 3) + x**Rational(1, 4), x) == FiniteSet(0) assert solveset_real(x/sqrt(x**2 + 1), x) == FiniteSet(0) eq = (x - y**3)/((y**2)*sqrt(1 - y**2)) assert solveset_real(eq, x) == FiniteSet(y**3) # issue 4497 assert solveset_real(1/(5 + x)**Rational(1, 5) - 9, x) == \ FiniteSet(Rational(-295244, 59049)) @XFAIL def test_solve_sqrt_fail(): # this only works if we check real_root(eq.subs(x, Rational(1, 3))) # but checksol doesn't work like that eq = (x**3 - 3*x**2)**Rational(1, 3) + 1 - x assert solveset_real(eq, x) == FiniteSet(Rational(1, 3)) @slow def test_solve_sqrt_3(): R = Symbol('R') eq = sqrt(2)*R*sqrt(1/(R + 1)) + (R + 1)*(sqrt(2)*sqrt(1/(R + 1)) - 1) sol = solveset_complex(eq, R) fset = [Rational(5, 3) + 4*sqrt(10)*cos(atan(3*sqrt(111)/251)/3)/3, -sqrt(10)*cos(atan(3*sqrt(111)/251)/3)/3 + 40*re(1/((Rational(-1, 2) - sqrt(3)*I/2)*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3)))/9 + sqrt(30)*sin(atan(3*sqrt(111)/251)/3)/3 + Rational(5, 3) + I*(-sqrt(30)*cos(atan(3*sqrt(111)/251)/3)/3 - sqrt(10)*sin(atan(3*sqrt(111)/251)/3)/3 + 40*im(1/((Rational(-1, 2) - sqrt(3)*I/2)*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3)))/9)] cset = [40*re(1/((Rational(-1, 2) + sqrt(3)*I/2)*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3)))/9 - sqrt(10)*cos(atan(3*sqrt(111)/251)/3)/3 - sqrt(30)*sin(atan(3*sqrt(111)/251)/3)/3 + Rational(5, 3) + I*(40*im(1/((Rational(-1, 2) + sqrt(3)*I/2)*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3)))/9 - sqrt(10)*sin(atan(3*sqrt(111)/251)/3)/3 + sqrt(30)*cos(atan(3*sqrt(111)/251)/3)/3)] assert sol._args[0] == FiniteSet(*fset) assert sol._args[1] == ConditionSet( R, Eq(sqrt(2)*R*sqrt(1/(R + 1)) + (R + 1)*(sqrt(2)*sqrt(1/(R + 1)) - 1), 0), FiniteSet(*cset)) # the number of real roots will depend on the value of m: for m=1 there are 4 # and for m=-1 there are none. eq = -sqrt((m - q)**2 + (-m/(2*q) + S.Half)**2) + sqrt((-m**2/2 - sqrt( 4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2 + (m**2/2 - m - sqrt( 4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2) unsolved_object = ConditionSet(q, Eq(sqrt((m - q)**2 + (-m/(2*q) + S.Half)**2) - sqrt((-m**2/2 - sqrt(4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2 + (m**2/2 - m - sqrt(4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2), 0), S.Reals) assert solveset_real(eq, q) == unsolved_object def test_solve_polynomial_symbolic_param(): assert solveset_complex((x**2 - 1)**2 - a, x) == \ FiniteSet(sqrt(1 + sqrt(a)), -sqrt(1 + sqrt(a)), sqrt(1 - sqrt(a)), -sqrt(1 - sqrt(a))) # issue 4507 assert solveset_complex(y - b/(1 + a*x), x) == \ FiniteSet((b/y - 1)/a) - FiniteSet(-1/a) # issue 4508 assert solveset_complex(y - b*x/(a + x), x) == \ FiniteSet(-a*y/(y - b)) - FiniteSet(-a) def test_solve_rational(): assert solveset_real(1/x + 1, x) == FiniteSet(-S.One) assert solveset_real(1/exp(x) - 1, x) == FiniteSet(0) assert solveset_real(x*(1 - 5/x), x) == FiniteSet(5) assert solveset_real(2*x/(x + 2) - 1, x) == FiniteSet(2) assert solveset_real((x**2/(7 - x)).diff(x), x) == \ FiniteSet(S.Zero, S(14)) def test_solveset_real_gen_is_pow(): assert solveset_real(sqrt(1) + 1, x) is S.EmptySet def test_no_sol(): assert solveset(1 - oo*x) is S.EmptySet assert solveset(oo*x, x) is S.EmptySet assert solveset(oo*x - oo, x) is S.EmptySet assert solveset_real(4, x) is S.EmptySet assert solveset_real(exp(x), x) is S.EmptySet assert solveset_real(x**2 + 1, x) is S.EmptySet assert solveset_real(-3*a/sqrt(x), x) is S.EmptySet assert solveset_real(1/x, x) is S.EmptySet assert solveset_real(-(1 + x)/(2 + x)**2 + 1/(2 + x), x ) is S.EmptySet def test_sol_zero_real(): assert solveset_real(0, x) == S.Reals assert solveset(0, x, Interval(1, 2)) == Interval(1, 2) assert solveset_real(-x**2 - 2*x + (x + 1)**2 - 1, x) == S.Reals def test_no_sol_rational_extragenous(): assert solveset_real((x/(x + 1) + 3)**(-2), x) is S.EmptySet assert solveset_real((x - 1)/(1 + 1/(x - 1)), x) is S.EmptySet def test_solve_polynomial_cv_1a(): """ Test for solving on equations that can be converted to a polynomial equation using the change of variable y -> x**Rational(p, q) """ assert solveset_real(sqrt(x) - 1, x) == FiniteSet(1) assert solveset_real(sqrt(x) - 2, x) == FiniteSet(4) assert solveset_real(x**Rational(1, 4) - 2, x) == FiniteSet(16) assert solveset_real(x**Rational(1, 3) - 3, x) == FiniteSet(27) assert solveset_real(x*(x**(S.One / 3) - 3), x) == \ FiniteSet(S.Zero, S(27)) def test_solveset_real_rational(): """Test solveset_real for rational functions""" x = Symbol('x', real=True) y = Symbol('y', real=True) assert solveset_real((x - y**3) / ((y**2)*sqrt(1 - y**2)), x) \ == FiniteSet(y**3) # issue 4486 assert solveset_real(2*x/(x + 2) - 1, x) == FiniteSet(2) def test_solveset_real_log(): assert solveset_real(log((x-1)*(x+1)), x) == \ FiniteSet(sqrt(2), -sqrt(2)) def test_poly_gens(): assert solveset_real(4**(2*(x**2) + 2*x) - 8, x) == \ FiniteSet(Rational(-3, 2), S.Half) def test_solve_abs(): n = Dummy('n') raises(ValueError, lambda: solveset(Abs(x) - 1, x)) assert solveset(Abs(x) - n, x, S.Reals).dummy_eq( ConditionSet(x, Contains(n, Interval(0, oo)), {-n, n})) assert solveset_real(Abs(x) - 2, x) == FiniteSet(-2, 2) assert solveset_real(Abs(x) + 2, x) is S.EmptySet assert solveset_real(Abs(x + 3) - 2*Abs(x - 3), x) == \ FiniteSet(1, 9) assert solveset_real(2*Abs(x) - Abs(x - 1), x) == \ FiniteSet(-1, Rational(1, 3)) sol = ConditionSet( x, And( Contains(b, Interval(0, oo)), Contains(a + b, Interval(0, oo)), Contains(a - b, Interval(0, oo))), FiniteSet(-a - b - 3, -a + b - 3, a - b - 3, a + b - 3)) eq = Abs(Abs(x + 3) - a) - b assert invert_real(eq, 0, x)[1] == sol reps = {a: 3, b: 1} eqab = eq.subs(reps) for si in sol.subs(reps): assert not eqab.subs(x, si) assert dumeq(solveset(Eq(sin(Abs(x)), 1), x, domain=S.Reals), Union( Intersection(Interval(0, oo), ImageSet(Lambda(n, (-1)**n*pi/2 + n*pi), S.Integers)), Intersection(Interval(-oo, 0), ImageSet(Lambda(n, n*pi - (-1)**(-n)*pi/2), S.Integers)))) def test_issue_9824(): assert dumeq(solveset(sin(x)**2 - 2*sin(x) + 1, x), ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers)) assert dumeq(solveset(cos(x)**2 - 2*cos(x) + 1, x), ImageSet(Lambda(n, 2*n*pi), S.Integers)) def test_issue_9565(): assert solveset_real(Abs((x - 1)/(x - 5)) <= Rational(1, 3), x) == Interval(-1, 2) def test_issue_10069(): eq = abs(1/(x - 1)) - 1 > 0 assert solveset_real(eq, x) == Union( Interval.open(0, 1), Interval.open(1, 2)) def test_real_imag_splitting(): a, b = symbols('a b', real=True) assert solveset_real(sqrt(a**2 - b**2) - 3, a) == \ FiniteSet(-sqrt(b**2 + 9), sqrt(b**2 + 9)) assert solveset_real(sqrt(a**2 + b**2) - 3, a) != \ S.EmptySet def test_units(): assert solveset_real(1/x - 1/(2*cm), x) == FiniteSet(2*cm) def test_solve_only_exp_1(): y = Symbol('y', positive=True) assert solveset_real(exp(x) - y, x) == FiniteSet(log(y)) assert solveset_real(exp(x) + exp(-x) - 4, x) == \ FiniteSet(log(-sqrt(3) + 2), log(sqrt(3) + 2)) assert solveset_real(exp(x) + exp(-x) - y, x) != S.EmptySet def test_atan2(): # The .inverse() method on atan2 works only if x.is_real is True and the # second argument is a real constant assert solveset_real(atan2(x, 2) - pi/3, x) == FiniteSet(2*sqrt(3)) def test_piecewise_solveset(): eq = Piecewise((x - 2, Gt(x, 2)), (2 - x, True)) - 3 assert set(solveset_real(eq, x)) == set(FiniteSet(-1, 5)) absxm3 = Piecewise( (x - 3, 0 <= x - 3), (3 - x, 0 > x - 3)) y = Symbol('y', positive=True) assert solveset_real(absxm3 - y, x) == FiniteSet(-y + 3, y + 3) f = Piecewise(((x - 2)**2, x >= 0), (0, True)) assert solveset(f, x, domain=S.Reals) == Union(FiniteSet(2), Interval(-oo, 0, True, True)) assert solveset( Piecewise((x + 1, x > 0), (I, True)) - I, x, S.Reals ) == Interval(-oo, 0) assert solveset(Piecewise((x - 1, Ne(x, I)), (x, True)), x) == FiniteSet(1) # issue 19718 g = Piecewise((1, x > 10), (0, True)) assert solveset(g > 0, x, S.Reals) == Interval.open(10, oo) from sympy.logic.boolalg import BooleanTrue f = BooleanTrue() assert solveset(f, x, domain=Interval(-3, 10)) == Interval(-3, 10) # issue 20552 f = Piecewise((0, Eq(x, 0)), (x**2/Abs(x), True)) g = Piecewise((0, Eq(x, pi)), ((x - pi)/sin(x), True)) assert solveset(f, x, domain=S.Reals) == FiniteSet(0) assert solveset(g) == FiniteSet(pi) def test_solveset_complex_polynomial(): assert solveset_complex(a*x**2 + b*x + c, x) == \ FiniteSet(-b/(2*a) - sqrt(-4*a*c + b**2)/(2*a), -b/(2*a) + sqrt(-4*a*c + b**2)/(2*a)) assert solveset_complex(x - y**3, y) == FiniteSet( (-x**Rational(1, 3))/2 + I*sqrt(3)*x**Rational(1, 3)/2, x**Rational(1, 3), (-x**Rational(1, 3))/2 - I*sqrt(3)*x**Rational(1, 3)/2) assert solveset_complex(x + 1/x - 1, x) == \ FiniteSet(S.Half + I*sqrt(3)/2, S.Half - I*sqrt(3)/2) def test_sol_zero_complex(): assert solveset_complex(0, x) is S.Complexes def test_solveset_complex_rational(): assert solveset_complex((x - 1)*(x - I)/(x - 3), x) == \ FiniteSet(1, I) assert solveset_complex((x - y**3)/((y**2)*sqrt(1 - y**2)), x) == \ FiniteSet(y**3) assert solveset_complex(-x**2 - I, x) == \ FiniteSet(-sqrt(2)/2 + sqrt(2)*I/2, sqrt(2)/2 - sqrt(2)*I/2) def test_solve_quintics(): skip("This test is too slow") f = x**5 - 110*x**3 - 55*x**2 + 2310*x + 979 s = solveset_complex(f, x) for root in s: res = f.subs(x, root.n()).n() assert tn(res, 0) f = x**5 + 15*x + 12 s = solveset_complex(f, x) for root in s: res = f.subs(x, root.n()).n() assert tn(res, 0) def test_solveset_complex_exp(): assert dumeq(solveset_complex(exp(x) - 1, x), imageset(Lambda(n, I*2*n*pi), S.Integers)) assert dumeq(solveset_complex(exp(x) - I, x), imageset(Lambda(n, I*(2*n*pi + pi/2)), S.Integers)) assert solveset_complex(1/exp(x), x) == S.EmptySet assert dumeq(solveset_complex(sinh(x).rewrite(exp), x), imageset(Lambda(n, n*pi*I), S.Integers)) def test_solveset_real_exp(): assert solveset(Eq((-2)**x, 4), x, S.Reals) == FiniteSet(2) assert solveset(Eq(-2**x, 4), x, S.Reals) == S.EmptySet assert solveset(Eq((-3)**x, 27), x, S.Reals) == S.EmptySet assert solveset(Eq((-5)**(x+1), 625), x, S.Reals) == FiniteSet(3) assert solveset(Eq(2**(x-3), -16), x, S.Reals) == S.EmptySet assert solveset(Eq((-3)**(x - 3), -3**39), x, S.Reals) == FiniteSet(42) assert solveset(Eq(2**x, y), x, S.Reals) == Intersection(S.Reals, FiniteSet(log(y)/log(2))) assert invert_real((-2)**(2*x) - 16, 0, x) == (x, FiniteSet(2)) def test_solve_complex_log(): assert solveset_complex(log(x), x) == FiniteSet(1) assert solveset_complex(1 - log(a + 4*x**2), x) == \ FiniteSet(-sqrt(-a + E)/2, sqrt(-a + E)/2) def test_solve_complex_sqrt(): assert solveset_complex(sqrt(5*x + 6) - 2 - x, x) == \ FiniteSet(-S.One, S(2)) assert solveset_complex(sqrt(5*x + 6) - (2 + 2*I) - x, x) == \ FiniteSet(-S(2), 3 - 4*I) assert solveset_complex(4*x*(1 - a * sqrt(x)), x) == \ FiniteSet(S.Zero, 1 / a ** 2) def test_solveset_complex_tan(): s = solveset_complex(tan(x).rewrite(exp), x) assert dumeq(s, imageset(Lambda(n, pi*n), S.Integers) - \ imageset(Lambda(n, pi*n + pi/2), S.Integers)) @_both_exp_pow def test_solve_trig(): assert dumeq(solveset_real(sin(x), x), Union(imageset(Lambda(n, 2*pi*n), S.Integers), imageset(Lambda(n, 2*pi*n + pi), S.Integers))) assert dumeq(solveset_real(sin(x) - 1, x), imageset(Lambda(n, 2*pi*n + pi/2), S.Integers)) assert dumeq(solveset_real(cos(x), x), Union(imageset(Lambda(n, 2*pi*n + pi/2), S.Integers), imageset(Lambda(n, 2*pi*n + pi*Rational(3, 2)), S.Integers))) assert dumeq(solveset_real(sin(x) + cos(x), x), Union(imageset(Lambda(n, 2*n*pi + pi*Rational(3, 4)), S.Integers), imageset(Lambda(n, 2*n*pi + pi*Rational(7, 4)), S.Integers))) assert solveset_real(sin(x)**2 + cos(x)**2, x) == S.EmptySet assert dumeq(solveset_complex(cos(x) - S.Half, x), Union(imageset(Lambda(n, 2*n*pi + pi*Rational(5, 3)), S.Integers), imageset(Lambda(n, 2*n*pi + pi/3), S.Integers))) assert dumeq(solveset(sin(y + a) - sin(y), a, domain=S.Reals), Union(ImageSet(Lambda(n, 2*n*pi), S.Integers), Intersection(ImageSet(Lambda(n, -I*(I*( 2*n*pi + arg(-exp(-2*I*y))) + 2*im(y))), S.Integers), S.Reals))) assert dumeq(solveset_real(sin(2*x)*cos(x) + cos(2*x)*sin(x)-1, x), ImageSet(Lambda(n, n*pi*Rational(2, 3) + pi/6), S.Integers)) assert dumeq(solveset_real(2*tan(x)*sin(x) + 1, x), Union( ImageSet(Lambda(n, 2*n*pi + atan(sqrt(2)*sqrt(-1 + sqrt(17))/ (1 - sqrt(17))) + pi), S.Integers), ImageSet(Lambda(n, 2*n*pi - atan(sqrt(2)*sqrt(-1 + sqrt(17))/ (1 - sqrt(17))) + pi), S.Integers))) assert dumeq(solveset_real(cos(2*x)*cos(4*x) - 1, x), ImageSet(Lambda(n, n*pi), S.Integers)) assert dumeq(solveset(sin(x/10) + Rational(3, 4)), Union( ImageSet(Lambda(n, 20*n*pi + 10*atan(3*sqrt(7)/7) + 10*pi), S.Integers), ImageSet(Lambda(n, 20*n*pi - 10*atan(3*sqrt(7)/7) + 20*pi), S.Integers))) assert dumeq(solveset(cos(x/15) + cos(x/5)), Union( ImageSet(Lambda(n, 30*n*pi + 15*pi/2), S.Integers), ImageSet(Lambda(n, 30*n*pi + 45*pi/2), S.Integers), ImageSet(Lambda(n, 30*n*pi + 75*pi/4), S.Integers), ImageSet(Lambda(n, 30*n*pi + 45*pi/4), S.Integers), ImageSet(Lambda(n, 30*n*pi + 105*pi/4), S.Integers), ImageSet(Lambda(n, 30*n*pi + 15*pi/4), S.Integers))) assert dumeq(solveset(sec(sqrt(2)*x/3) + 5), Union( ImageSet(Lambda(n, 3*sqrt(2)*(2*n*pi - pi + atan(2*sqrt(6)))/2), S.Integers), ImageSet(Lambda(n, 3*sqrt(2)*(2*n*pi - atan(2*sqrt(6)) + pi)/2), S.Integers))) assert dumeq(simplify(solveset(tan(pi*x) - cot(pi/2*x))), Union( ImageSet(Lambda(n, 4*n + 1), S.Integers), ImageSet(Lambda(n, 4*n + 3), S.Integers), ImageSet(Lambda(n, 4*n + Rational(7, 3)), S.Integers), ImageSet(Lambda(n, 4*n + Rational(5, 3)), S.Integers), ImageSet(Lambda(n, 4*n + Rational(11, 3)), S.Integers), ImageSet(Lambda(n, 4*n + Rational(1, 3)), S.Integers))) assert dumeq(solveset(cos(9*x)), Union( ImageSet(Lambda(n, 2*n*pi/9 + pi/18), S.Integers), ImageSet(Lambda(n, 2*n*pi/9 + pi/6), S.Integers))) assert dumeq(solveset(sin(8*x) + cot(12*x), x, S.Reals), Union( ImageSet(Lambda(n, n*pi/2 + pi/8), S.Integers), ImageSet(Lambda(n, n*pi/2 + 3*pi/8), S.Integers), ImageSet(Lambda(n, n*pi/2 + 5*pi/16), S.Integers), ImageSet(Lambda(n, n*pi/2 + 3*pi/16), S.Integers), ImageSet(Lambda(n, n*pi/2 + 7*pi/16), S.Integers), ImageSet(Lambda(n, n*pi/2 + pi/16), S.Integers))) # This is the only remaining solveset test that actually ends up being solved # by _solve_trig2(). All others are handled by the improved _solve_trig1. assert dumeq(solveset_real(2*cos(x)*cos(2*x) - 1, x), Union(ImageSet(Lambda(n, 2*n*pi + 2*atan(sqrt(-2*2**Rational(1, 3)*(67 + 9*sqrt(57))**Rational(2, 3) + 8*2**Rational(2, 3) + 11*(67 + 9*sqrt(57))**Rational(1, 3))/(3*(67 + 9*sqrt(57))**Rational(1, 6)))), S.Integers), ImageSet(Lambda(n, 2*n*pi - 2*atan(sqrt(-2*2**Rational(1, 3)*(67 + 9*sqrt(57))**Rational(2, 3) + 8*2**Rational(2, 3) + 11*(67 + 9*sqrt(57))**Rational(1, 3))/(3*(67 + 9*sqrt(57))**Rational(1, 6))) + 2*pi), S.Integers))) # issue #16870 assert dumeq(simplify(solveset(sin(x/180*pi) - S.Half, x, S.Reals)), Union( ImageSet(Lambda(n, 360*n + 150), S.Integers), ImageSet(Lambda(n, 360*n + 30), S.Integers))) def test_solve_hyperbolic(): # actual solver: _solve_trig1 n = Dummy('n') assert solveset(sinh(x) + cosh(x), x) == S.EmptySet assert solveset(sinh(x) + cos(x), x) == ConditionSet(x, Eq(cos(x) + sinh(x), 0), S.Complexes) assert solveset_real(sinh(x) + sech(x), x) == FiniteSet( log(sqrt(sqrt(5) - 2))) assert solveset_real(3*cosh(2*x) - 5, x) == FiniteSet( -log(3)/2, log(3)/2) assert solveset_real(sinh(x - 3) - 2, x) == FiniteSet( log((2 + sqrt(5))*exp(3))) assert solveset_real(cosh(2*x) + 2*sinh(x) - 5, x) == FiniteSet( log(-2 + sqrt(5)), log(1 + sqrt(2))) assert solveset_real((coth(x) + sinh(2*x))/cosh(x) - 3, x) == FiniteSet( log(S.Half + sqrt(5)/2), log(1 + sqrt(2))) assert solveset_real(cosh(x)*sinh(x) - 2, x) == FiniteSet( log(4 + sqrt(17))/2) assert solveset_real(sinh(x) + tanh(x) - 1, x) == FiniteSet( log(sqrt(2)/2 + sqrt(-S(1)/2 + sqrt(2)))) assert dumeq(solveset_complex(sinh(x) - I/2, x), Union( ImageSet(Lambda(n, I*(2*n*pi + 5*pi/6)), S.Integers), ImageSet(Lambda(n, I*(2*n*pi + pi/6)), S.Integers))) assert dumeq(solveset_complex(sinh(x) + sech(x), x), Union( ImageSet(Lambda(n, 2*n*I*pi + log(sqrt(-2 + sqrt(5)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi + pi/2) + log(sqrt(2 + sqrt(5)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi + pi) + log(sqrt(-2 + sqrt(5)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi - pi/2) + log(sqrt(2 + sqrt(5)))), S.Integers))) assert dumeq(solveset(sinh(x/10) + Rational(3, 4)), Union( ImageSet(Lambda(n, 10*I*(2*n*pi + pi) + 10*log(2)), S.Integers), ImageSet(Lambda(n, 20*n*I*pi - 10*log(2)), S.Integers))) assert dumeq(solveset(cosh(x/15) + cosh(x/5)), Union( ImageSet(Lambda(n, 15*I*(2*n*pi + pi/2)), S.Integers), ImageSet(Lambda(n, 15*I*(2*n*pi - pi/2)), S.Integers), ImageSet(Lambda(n, 15*I*(2*n*pi - 3*pi/4)), S.Integers), ImageSet(Lambda(n, 15*I*(2*n*pi + 3*pi/4)), S.Integers), ImageSet(Lambda(n, 15*I*(2*n*pi - pi/4)), S.Integers), ImageSet(Lambda(n, 15*I*(2*n*pi + pi/4)), S.Integers))) assert dumeq(solveset(sech(sqrt(2)*x/3) + 5), Union( ImageSet(Lambda(n, 3*sqrt(2)*I*(2*n*pi - pi + atan(2*sqrt(6)))/2), S.Integers), ImageSet(Lambda(n, 3*sqrt(2)*I*(2*n*pi - atan(2*sqrt(6)) + pi)/2), S.Integers))) assert dumeq(solveset(tanh(pi*x) - coth(pi/2*x)), Union( ImageSet(Lambda(n, 2*I*(2*n*pi + pi/2)/pi), S.Integers), ImageSet(Lambda(n, 2*I*(2*n*pi - pi/2)/pi), S.Integers))) assert dumeq(solveset(cosh(9*x)), Union( ImageSet(Lambda(n, I*(2*n*pi + pi/2)/9), S.Integers), ImageSet(Lambda(n, I*(2*n*pi - pi/2)/9), S.Integers))) # issues #9606 / #9531: assert solveset(sinh(x), x, S.Reals) == FiniteSet(0) assert dumeq(solveset(sinh(x), x, S.Complexes), Union( ImageSet(Lambda(n, I*(2*n*pi + pi)), S.Integers), ImageSet(Lambda(n, 2*n*I*pi), S.Integers))) # issues #11218 / #18427 assert dumeq(solveset(sin(pi*x), x, S.Reals), Union( ImageSet(Lambda(n, (2*n*pi + pi)/pi), S.Integers), ImageSet(Lambda(n, 2*n), S.Integers))) assert dumeq(solveset(sin(pi*x), x), Union( ImageSet(Lambda(n, (2*n*pi + pi)/pi), S.Integers), ImageSet(Lambda(n, 2*n), S.Integers))) # issue #17543 assert dumeq(simplify(solveset(I*cot(8*x - 8*E), x)), Union( ImageSet(Lambda(n, n*pi/4 - 13*pi/16 + E), S.Integers), ImageSet(Lambda(n, n*pi/4 - 11*pi/16 + E), S.Integers))) # issues #18490 / #19489 assert solveset(cosh(x) + cosh(3*x) - cosh(5*x), x, S.Reals ).dummy_eq(ConditionSet(x, Eq(cosh(x) + cosh(3*x) - cosh(5*x), 0), S.Reals)) assert solveset(sinh(8*x) + coth(12*x)).dummy_eq( ConditionSet(x, Eq(sinh(8*x) + coth(12*x), 0), S.Complexes)) def test_solve_trig_hyp_symbolic(): # actual solver: _solve_trig1 assert dumeq(solveset(sin(a*x), x), ConditionSet(x, Ne(a, 0), Union( ImageSet(Lambda(n, (2*n*pi + pi)/a), S.Integers), ImageSet(Lambda(n, 2*n*pi/a), S.Integers)))) assert dumeq(solveset(cosh(x/a), x), ConditionSet(x, Ne(a, 0), Union( ImageSet(Lambda(n, I*a*(2*n*pi + pi/2)), S.Integers), ImageSet(Lambda(n, I*a*(2*n*pi - pi/2)), S.Integers)))) assert dumeq(solveset(sin(2*sqrt(3)/3*a**2/(b*pi)*x) + cos(4*sqrt(3)/3*a**2/(b*pi)*x), x), ConditionSet(x, Ne(b, 0) & Ne(a**2, 0), Union( ImageSet(Lambda(n, sqrt(3)*pi*b*(2*n*pi + pi/2)/(2*a**2)), S.Integers), ImageSet(Lambda(n, sqrt(3)*pi*b*(2*n*pi - 5*pi/6)/(2*a**2)), S.Integers), ImageSet(Lambda(n, sqrt(3)*pi*b*(2*n*pi - pi/6)/(2*a**2)), S.Integers)))) assert dumeq(simplify(solveset(cot((1 + I)*x) - cot((3 + 3*I)*x), x)), Union( ImageSet(Lambda(n, pi*(1 - I)*(4*n + 1)/4), S.Integers), ImageSet(Lambda(n, pi*(1 - I)*(4*n - 1)/4), S.Integers))) assert dumeq(solveset(cosh((a**2 + 1)*x) - 3, x), ConditionSet(x, Ne(a**2 + 1, 0), Union( ImageSet(Lambda(n, (2*n*I*pi + log(3 - 2*sqrt(2)))/(a**2 + 1)), S.Integers), ImageSet(Lambda(n, (2*n*I*pi + log(2*sqrt(2) + 3))/(a**2 + 1)), S.Integers)))) ar = Symbol('ar', real=True) assert solveset(cosh((ar**2 + 1)*x) - 2, x, S.Reals) == FiniteSet( log(sqrt(3) + 2)/(ar**2 + 1), log(2 - sqrt(3))/(ar**2 + 1)) def test_issue_9616(): assert dumeq(solveset(sinh(x) + tanh(x) - 1, x), Union( ImageSet(Lambda(n, 2*n*I*pi + log(sqrt(2)/2 + sqrt(-S.Half + sqrt(2)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi - atan(sqrt(2)*sqrt(S.Half + sqrt(2))) + pi) + log(sqrt(1 + sqrt(2)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi + pi) + log(-sqrt(2)/2 + sqrt(-S.Half + sqrt(2)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi - pi + atan(sqrt(2)*sqrt(S.Half + sqrt(2)))) + log(sqrt(1 + sqrt(2)))), S.Integers))) f1 = (sinh(x)).rewrite(exp) f2 = (tanh(x)).rewrite(exp) assert dumeq(solveset(f1 + f2 - 1, x), Union( Complement(ImageSet( Lambda(n, I*(2*n*pi + pi) + log(-sqrt(2)/2 + sqrt(-S.Half + sqrt(2)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi + pi)/2), S.Integers)), Complement(ImageSet(Lambda(n, I*(2*n*pi - pi + atan(sqrt(2)*sqrt(S.Half + sqrt(2)))) + log(sqrt(1 + sqrt(2)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi + pi)/2), S.Integers)), Complement(ImageSet(Lambda(n, I*(2*n*pi - atan(sqrt(2)*sqrt(S.Half + sqrt(2))) + pi) + log(sqrt(1 + sqrt(2)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi + pi)/2), S.Integers)), Complement( ImageSet(Lambda(n, 2*n*I*pi + log(sqrt(2)/2 + sqrt(-S.Half + sqrt(2)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi + pi)/2), S.Integers)))) def test_solve_invalid_sol(): assert 0 not in solveset_real(sin(x)/x, x) assert 0 not in solveset_complex((exp(x) - 1)/x, x) @XFAIL def test_solve_trig_simplified(): n = Dummy('n') assert dumeq(solveset_real(sin(x), x), imageset(Lambda(n, n*pi), S.Integers)) assert dumeq(solveset_real(cos(x), x), imageset(Lambda(n, n*pi + pi/2), S.Integers)) assert dumeq(solveset_real(cos(x) + sin(x), x), imageset(Lambda(n, n*pi - pi/4), S.Integers)) @XFAIL def test_solve_lambert(): assert solveset_real(x*exp(x) - 1, x) == FiniteSet(LambertW(1)) assert solveset_real(exp(x) + x, x) == FiniteSet(-LambertW(1)) assert solveset_real(x + 2**x, x) == \ FiniteSet(-LambertW(log(2))/log(2)) # issue 4739 ans = solveset_real(3*x + 5 + 2**(-5*x + 3), x) assert ans == FiniteSet(Rational(-5, 3) + LambertW(-10240*2**Rational(1, 3)*log(2)/3)/(5*log(2))) eq = 2*(3*x + 4)**5 - 6*7**(3*x + 9) result = solveset_real(eq, x) ans = FiniteSet((log(2401) + 5*LambertW(-log(7**(7*3**Rational(1, 5)/5))))/(3*log(7))/-1) assert result == ans assert solveset_real(eq.expand(), x) == result assert solveset_real(5*x - 1 + 3*exp(2 - 7*x), x) == \ FiniteSet(Rational(1, 5) + LambertW(-21*exp(Rational(3, 5))/5)/7) assert solveset_real(2*x + 5 + log(3*x - 2), x) == \ FiniteSet(Rational(2, 3) + LambertW(2*exp(Rational(-19, 3))/3)/2) assert solveset_real(3*x + log(4*x), x) == \ FiniteSet(LambertW(Rational(3, 4))/3) assert solveset_real(x**x - 2) == FiniteSet(exp(LambertW(log(2)))) a = Symbol('a') assert solveset_real(-a*x + 2*x*log(x), x) == FiniteSet(exp(a/2)) a = Symbol('a', real=True) assert solveset_real(a/x + exp(x/2), x) == \ FiniteSet(2*LambertW(-a/2)) assert solveset_real((a/x + exp(x/2)).diff(x), x) == \ FiniteSet(4*LambertW(sqrt(2)*sqrt(a)/4)) # coverage test assert solveset_real(tanh(x + 3)*tanh(x - 3) - 1, x) is S.EmptySet assert solveset_real((x**2 - 2*x + 1).subs(x, log(x) + 3*x), x) == \ FiniteSet(LambertW(3*S.Exp1)/3) assert solveset_real((x**2 - 2*x + 1).subs(x, (log(x) + 3*x)**2 - 1), x) == \ FiniteSet(LambertW(3*exp(-sqrt(2)))/3, LambertW(3*exp(sqrt(2)))/3) assert solveset_real((x**2 - 2*x - 2).subs(x, log(x) + 3*x), x) == \ FiniteSet(LambertW(3*exp(1 + sqrt(3)))/3, LambertW(3*exp(-sqrt(3) + 1))/3) assert solveset_real(x*log(x) + 3*x + 1, x) == \ FiniteSet(exp(-3 + LambertW(-exp(3)))) eq = (x*exp(x) - 3).subs(x, x*exp(x)) assert solveset_real(eq, x) == \ FiniteSet(LambertW(3*exp(-LambertW(3)))) assert solveset_real(3*log(a**(3*x + 5)) + a**(3*x + 5), x) == \ FiniteSet(-((log(a**5) + LambertW(Rational(1, 3)))/(3*log(a)))) p = symbols('p', positive=True) assert solveset_real(3*log(p**(3*x + 5)) + p**(3*x + 5), x) == \ FiniteSet( log((-3**Rational(1, 3) - 3**Rational(5, 6)*I)*LambertW(Rational(1, 3))**Rational(1, 3)/(2*p**Rational(5, 3)))/log(p), log((-3**Rational(1, 3) + 3**Rational(5, 6)*I)*LambertW(Rational(1, 3))**Rational(1, 3)/(2*p**Rational(5, 3)))/log(p), log((3*LambertW(Rational(1, 3))/p**5)**(1/(3*log(p)))),) # checked numerically # check collection b = Symbol('b') eq = 3*log(a**(3*x + 5)) + b*log(a**(3*x + 5)) + a**(3*x + 5) assert solveset_real(eq, x) == FiniteSet( -((log(a**5) + LambertW(1/(b + 3)))/(3*log(a)))) # issue 4271 assert solveset_real((a/x + exp(x/2)).diff(x, 2), x) == FiniteSet( 6*LambertW((-1)**Rational(1, 3)*a**Rational(1, 3)/3)) assert solveset_real(x**3 - 3**x, x) == \ FiniteSet(-3/log(3)*LambertW(-log(3)/3)) assert solveset_real(3**cos(x) - cos(x)**3) == FiniteSet( acos(-3*LambertW(-log(3)/3)/log(3))) assert solveset_real(x**2 - 2**x, x) == \ solveset_real(-x**2 + 2**x, x) assert solveset_real(3*log(x) - x*log(3)) == FiniteSet( -3*LambertW(-log(3)/3)/log(3), -3*LambertW(-log(3)/3, -1)/log(3)) assert solveset_real(LambertW(2*x) - y) == FiniteSet( y*exp(y)/2) @XFAIL def test_other_lambert(): a = Rational(6, 5) assert solveset_real(x**a - a**x, x) == FiniteSet( a, -a*LambertW(-log(a)/a)/log(a)) @_both_exp_pow def test_solveset(): f = Function('f') raises(ValueError, lambda: solveset(x + y)) assert solveset(x, 1) == S.EmptySet assert solveset(f(1)**2 + y + 1, f(1) ) == FiniteSet(-sqrt(-y - 1), sqrt(-y - 1)) assert solveset(f(1)**2 - 1, f(1), S.Reals) == FiniteSet(-1, 1) assert solveset(f(1)**2 + 1, f(1)) == FiniteSet(-I, I) assert solveset(x - 1, 1) == FiniteSet(x) assert solveset(sin(x) - cos(x), sin(x)) == FiniteSet(cos(x)) assert solveset(0, domain=S.Reals) == S.Reals assert solveset(1) == S.EmptySet assert solveset(True, domain=S.Reals) == S.Reals # issue 10197 assert solveset(False, domain=S.Reals) == S.EmptySet assert solveset(exp(x) - 1, domain=S.Reals) == FiniteSet(0) assert solveset(exp(x) - 1, x, S.Reals) == FiniteSet(0) assert solveset(Eq(exp(x), 1), x, S.Reals) == FiniteSet(0) assert solveset(exp(x) - 1, exp(x), S.Reals) == FiniteSet(1) A = Indexed('A', x) assert solveset(A - 1, A, S.Reals) == FiniteSet(1) assert solveset(x - 1 >= 0, x, S.Reals) == Interval(1, oo) assert solveset(exp(x) - 1 >= 0, x, S.Reals) == Interval(0, oo) assert dumeq(solveset(exp(x) - 1, x), imageset(Lambda(n, 2*I*pi*n), S.Integers)) assert dumeq(solveset(Eq(exp(x), 1), x), imageset(Lambda(n, 2*I*pi*n), S.Integers)) # issue 13825 assert solveset(x**2 + f(0) + 1, x) == {-sqrt(-f(0) - 1), sqrt(-f(0) - 1)} # issue 19977 assert solveset(atan(log(x)) > 0, x, domain=Interval.open(0, oo)) == Interval.open(1, oo) @_both_exp_pow def test_multi_exp(): k1, k2, k3 = symbols('k1, k2, k3') assert dumeq(solveset(exp(exp(x)) - 5, x),\ imageset(Lambda(((k1, n),), I*(2*k1*pi + arg(2*n*I*pi + log(5))) + log(Abs(2*n*I*pi + log(5)))),\ ProductSet(S.Integers, S.Integers))) assert dumeq(solveset((d*exp(exp(a*x + b)) + c), x),\ imageset(Lambda(x, (-b + x)/a), ImageSet(Lambda(((k1, n),), \ I*(2*k1*pi + arg(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))) + log(Abs(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d))))), \ ProductSet(S.Integers, S.Integers)))) assert dumeq(solveset((d*exp(exp(exp(a*x + b))) + c), x),\ imageset(Lambda(x, (-b + x)/a), ImageSet(Lambda(((k2, k1, n),), \ I*(2*k2*pi + arg(I*(2*k1*pi + arg(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))) + \ log(Abs(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))))) + log(Abs(I*(2*k1*pi + arg(I*(2*n*pi + arg(-c/d)) + \ log(Abs(c/d)))) + log(Abs(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d))))))), \ ProductSet(S.Integers, S.Integers, S.Integers)))) assert dumeq(solveset((d*exp(exp(exp(exp(a*x + b)))) + c), x),\ ImageSet(Lambda(x, (-b + x)/a), ImageSet(Lambda(((k3, k2, k1, n),), \ I*(2*k3*pi + arg(I*(2*k2*pi + arg(I*(2*k1*pi + arg(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))) + \ log(Abs(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))))) + log(Abs(I*(2*k1*pi + arg(I*(2*n*pi + arg(-c/d)) + \ log(Abs(c/d)))) + log(Abs(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))))))) + log(Abs(I*(2*k2*pi + \ arg(I*(2*k1*pi + arg(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))) + log(Abs(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))))) + \ log(Abs(I*(2*k1*pi + arg(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))) + log(Abs(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d))))))))), \ ProductSet(S.Integers, S.Integers, S.Integers, S.Integers)))) def test__solveset_multi(): from sympy.solvers.solveset import _solveset_multi from sympy.sets import Reals # Basic univariate case: assert _solveset_multi([x**2-1], [x], [S.Reals]) == FiniteSet((1,), (-1,)) # Linear systems of two equations assert _solveset_multi([x+y, x+1], [x, y], [Reals, Reals]) == FiniteSet((-1, 1)) assert _solveset_multi([x+y, x+1], [y, x], [Reals, Reals]) == FiniteSet((1, -1)) assert _solveset_multi([x+y, x-y-1], [x, y], [Reals, Reals]) == FiniteSet((S(1)/2, -S(1)/2)) assert _solveset_multi([x-1, y-2], [x, y], [Reals, Reals]) == FiniteSet((1, 2)) # assert dumeq(_solveset_multi([x+y], [x, y], [Reals, Reals]), ImageSet(Lambda(x, (x, -x)), Reals)) assert dumeq(_solveset_multi([x+y], [x, y], [Reals, Reals]), Union( ImageSet(Lambda(((x,),), (x, -x)), ProductSet(Reals)), ImageSet(Lambda(((y,),), (-y, y)), ProductSet(Reals)))) assert _solveset_multi([x+y, x+y+1], [x, y], [Reals, Reals]) == S.EmptySet assert _solveset_multi([x+y, x-y, x-1], [x, y], [Reals, Reals]) == S.EmptySet assert _solveset_multi([x+y, x-y, x-1], [y, x], [Reals, Reals]) == S.EmptySet # Systems of three equations: assert _solveset_multi([x+y+z-1, x+y-z-2, x-y-z-3], [x, y, z], [Reals, Reals, Reals]) == FiniteSet((2, -S.Half, -S.Half)) # Nonlinear systems: from sympy.abc import theta assert _solveset_multi([x**2+y**2-2, x+y], [x, y], [Reals, Reals]) == FiniteSet((-1, 1), (1, -1)) assert _solveset_multi([x**2-1, y], [x, y], [Reals, Reals]) == FiniteSet((1, 0), (-1, 0)) #assert _solveset_multi([x**2-y**2], [x, y], [Reals, Reals]) == Union( # ImageSet(Lambda(x, (x, -x)), Reals), ImageSet(Lambda(x, (x, x)), Reals)) assert dumeq(_solveset_multi([x**2-y**2], [x, y], [Reals, Reals]), Union( ImageSet(Lambda(((x,),), (x, -Abs(x))), ProductSet(Reals)), ImageSet(Lambda(((x,),), (x, Abs(x))), ProductSet(Reals)), ImageSet(Lambda(((y,),), (-Abs(y), y)), ProductSet(Reals)), ImageSet(Lambda(((y,),), (Abs(y), y)), ProductSet(Reals)))) assert _solveset_multi([r*cos(theta)-1, r*sin(theta)], [theta, r], [Interval(0, pi), Interval(-1, 1)]) == FiniteSet((0, 1), (pi, -1)) assert _solveset_multi([r*cos(theta)-1, r*sin(theta)], [r, theta], [Interval(0, 1), Interval(0, pi)]) == FiniteSet((1, 0)) #assert _solveset_multi([r*cos(theta)-r, r*sin(theta)], [r, theta], # [Interval(0, 1), Interval(0, pi)]) == ? assert dumeq(_solveset_multi([r*cos(theta)-r, r*sin(theta)], [r, theta], [Interval(0, 1), Interval(0, pi)]), Union( ImageSet(Lambda(((r,),), (r, 0)), ImageSet(Lambda(r, (r,)), Interval(0, 1))), ImageSet(Lambda(((theta,),), (0, theta)), ImageSet(Lambda(theta, (theta,)), Interval(0, pi))))) def test_conditionset(): assert solveset(Eq(sin(x)**2 + cos(x)**2, 1), x, domain=S.Reals ) is S.Reals assert solveset(Eq(x**2 + x*sin(x), 1), x, domain=S.Reals ).dummy_eq(ConditionSet(x, Eq(x**2 + x*sin(x) - 1, 0), S.Reals)) assert dumeq(solveset(Eq(-I*(exp(I*x) - exp(-I*x))/2, 1), x ), imageset(Lambda(n, 2*n*pi + pi/2), S.Integers)) assert solveset(x + sin(x) > 1, x, domain=S.Reals ).dummy_eq(ConditionSet(x, x + sin(x) > 1, S.Reals)) assert solveset(Eq(sin(Abs(x)), x), x, domain=S.Reals ).dummy_eq(ConditionSet(x, Eq(-x + sin(Abs(x)), 0), S.Reals)) assert solveset(y**x-z, x, S.Reals ).dummy_eq(ConditionSet(x, Eq(y**x - z, 0), S.Reals)) @XFAIL def test_conditionset_equality(): ''' Checking equality of different representations of ConditionSet''' assert solveset(Eq(tan(x), y), x) == ConditionSet(x, Eq(tan(x), y), S.Complexes) def test_solveset_domain(): assert solveset(x**2 - x - 6, x, Interval(0, oo)) == FiniteSet(3) assert solveset(x**2 - 1, x, Interval(0, oo)) == FiniteSet(1) assert solveset(x**4 - 16, x, Interval(0, 10)) == FiniteSet(2) def test_improve_coverage(): solution = solveset(exp(x) + sin(x), x, S.Reals) unsolved_object = ConditionSet(x, Eq(exp(x) + sin(x), 0), S.Reals) assert solution.dummy_eq(unsolved_object) def test_issue_9522(): expr1 = Eq(1/(x**2 - 4) + x, 1/(x**2 - 4) + 2) expr2 = Eq(1/x + x, 1/x) assert solveset(expr1, x, S.Reals) is S.EmptySet assert solveset(expr2, x, S.Reals) is S.EmptySet def test_solvify(): assert solvify(x**2 + 10, x, S.Reals) == [] assert solvify(x**3 + 1, x, S.Complexes) == [-1, S.Half - sqrt(3)*I/2, S.Half + sqrt(3)*I/2] assert solvify(log(x), x, S.Reals) == [1] assert solvify(cos(x), x, S.Reals) == [pi/2, pi*Rational(3, 2)] assert solvify(sin(x) + 1, x, S.Reals) == [pi*Rational(3, 2)] raises(NotImplementedError, lambda: solvify(sin(exp(x)), x, S.Complexes)) def test_solvify_piecewise(): p1 = Piecewise((0, x < -1), (x**2, x <= 1), (log(x), True)) p2 = Piecewise((0, x < -10), (x**2 + 5*x - 6, x >= -9)) p3 = Piecewise((0, Eq(x, 0)), (x**2/Abs(x), True)) p4 = Piecewise((0, Eq(x, pi)), ((x - pi)/sin(x), True)) # issue 21079 assert solvify(p1, x, S.Reals) == [0] assert solvify(p2, x, S.Reals) == [-6, 1] assert solvify(p3, x, S.Reals) == [0] assert solvify(p4, x, S.Reals) == [pi] def test_abs_invert_solvify(): x = Symbol('x',positive=True) assert solvify(sin(Abs(x)), x, S.Reals) == [0, pi] x = Symbol('x') assert solvify(sin(Abs(x)), x, S.Reals) is None def test_linear_eq_to_matrix(): eqns1 = [2*x + y - 2*z - 3, x - y - z, x + y + 3*z - 12] eqns2 = [Eq(3*x + 2*y - z, 1), Eq(2*x - 2*y + 4*z, -2), -2*x + y - 2*z] A, B = linear_eq_to_matrix(eqns1, x, y, z) assert A == Matrix([[2, 1, -2], [1, -1, -1], [1, 1, 3]]) assert B == Matrix([[3], [0], [12]]) A, B = linear_eq_to_matrix(eqns2, x, y, z) assert A == Matrix([[3, 2, -1], [2, -2, 4], [-2, 1, -2]]) assert B == Matrix([[1], [-2], [0]]) # Pure symbolic coefficients eqns3 = [a*b*x + b*y + c*z - d, e*x + d*x + f*y + g*z - h, i*x + j*y + k*z - l] A, B = linear_eq_to_matrix(eqns3, x, y, z) assert A == Matrix([[a*b, b, c], [d + e, f, g], [i, j, k]]) assert B == Matrix([[d], [h], [l]]) # raise ValueError if # 1) no symbols are given raises(ValueError, lambda: linear_eq_to_matrix(eqns3)) # 2) there are duplicates raises(ValueError, lambda: linear_eq_to_matrix(eqns3, [x, x, y])) # 3) there are non-symbols raises(ValueError, lambda: linear_eq_to_matrix(eqns3, [x, 1/a, y])) # 4) a nonlinear term is detected in the original expression raises(NonlinearError, lambda: linear_eq_to_matrix(Eq(1/x + x, 1/x), [x])) assert linear_eq_to_matrix(1, x) == (Matrix([[0]]), Matrix([[-1]])) # issue 15195 assert linear_eq_to_matrix(x + y*(z*(3*x + 2) + 3), x) == ( Matrix([[3*y*z + 1]]), Matrix([[-y*(2*z + 3)]])) assert linear_eq_to_matrix(Matrix( [[a*x + b*y - 7], [5*x + 6*y - c]]), x, y) == ( Matrix([[a, b], [5, 6]]), Matrix([[7], [c]])) # issue 15312 assert linear_eq_to_matrix(Eq(x + 2, 1), x) == ( Matrix([[1]]), Matrix([[-1]])) def test_issue_16577(): assert linear_eq_to_matrix(Eq(a*(2*x + 3*y) + 4*y, 5), x, y) == ( Matrix([[2*a, 3*a + 4]]), Matrix([[5]])) def test_issue_10085(): assert invert_real(exp(x),0,x) == (x, S.EmptySet) def test_linsolve(): x1, x2, x3, x4 = symbols('x1, x2, x3, x4') # Test for different input forms M = Matrix([[1, 2, 1, 1, 7], [1, 2, 2, -1, 12], [2, 4, 0, 6, 4]]) system1 = A, B = M[:, :-1], M[:, -1] Eqns = [x1 + 2*x2 + x3 + x4 - 7, x1 + 2*x2 + 2*x3 - x4 - 12, 2*x1 + 4*x2 + 6*x4 - 4] sol = FiniteSet((-2*x2 - 3*x4 + 2, x2, 2*x4 + 5, x4)) assert linsolve(Eqns, (x1, x2, x3, x4)) == sol assert linsolve(Eqns, *(x1, x2, x3, x4)) == sol assert linsolve(system1, (x1, x2, x3, x4)) == sol assert linsolve(system1, *(x1, x2, x3, x4)) == sol # issue 9667 - symbols can be Dummy symbols x1, x2, x3, x4 = symbols('x:4', cls=Dummy) assert linsolve(system1, x1, x2, x3, x4) == FiniteSet( (-2*x2 - 3*x4 + 2, x2, 2*x4 + 5, x4)) # raise ValueError for garbage value raises(ValueError, lambda: linsolve(Eqns)) raises(ValueError, lambda: linsolve(x1)) raises(ValueError, lambda: linsolve(x1, x2)) raises(ValueError, lambda: linsolve((A,), x1, x2)) raises(ValueError, lambda: linsolve(A, B, x1, x2)) #raise ValueError if equations are non-linear in given variables raises(NonlinearError, lambda: linsolve([x + y - 1, x ** 2 + y - 3], [x, y])) raises(NonlinearError, lambda: linsolve([cos(x) + y, x + y], [x, y])) assert linsolve([x + z - 1, x ** 2 + y - 3], [z, y]) == {(-x + 1, -x**2 + 3)} # Fully symbolic test A = Matrix([[a, b], [c, d]]) B = Matrix([[e], [g]]) system2 = (A, B) sol = FiniteSet(((-b*g + d*e)/(a*d - b*c), (a*g - c*e)/(a*d - b*c))) assert linsolve(system2, [x, y]) == sol # No solution A = Matrix([[1, 2, 3], [2, 4, 6], [3, 6, 9]]) B = Matrix([0, 0, 1]) assert linsolve((A, B), (x, y, z)) is S.EmptySet # Issue #10056 A, B, J1, J2 = symbols('A B J1 J2') Augmatrix = Matrix([ [2*I*J1, 2*I*J2, -2/J1], [-2*I*J2, -2*I*J1, 2/J2], [0, 2, 2*I/(J1*J2)], [2, 0, 0], ]) assert linsolve(Augmatrix, A, B) == FiniteSet((0, I/(J1*J2))) # Issue #10121 - Assignment of free variables Augmatrix = Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]]) assert linsolve(Augmatrix, a, b, c, d, e) == FiniteSet((a, 0, c, 0, e)) #raises(IndexError, lambda: linsolve(Augmatrix, a, b, c)) x0, x1, x2, _x0 = symbols('tau0 tau1 tau2 _tau0') assert linsolve(Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, _x0]]) ) == FiniteSet((x0, 0, x1, _x0, x2)) x0, x1, x2, _x0 = symbols('tau00 tau01 tau02 tau0') assert linsolve(Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, _x0]]) ) == FiniteSet((x0, 0, x1, _x0, x2)) x0, x1, x2, _x0 = symbols('tau00 tau01 tau02 tau1') assert linsolve(Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, _x0]]) ) == FiniteSet((x0, 0, x1, _x0, x2)) # symbols can be given as generators x0, x2, x4 = symbols('x0, x2, x4') assert linsolve(Augmatrix, numbered_symbols('x') ) == FiniteSet((x0, 0, x2, 0, x4)) Augmatrix[-1, -1] = x0 # use Dummy to avoid clash; the names may clash but the symbols # will not Augmatrix[-1, -1] = symbols('_x0') assert len(linsolve( Augmatrix, numbered_symbols('x', cls=Dummy)).free_symbols) == 4 # Issue #12604 f = Function('f') assert linsolve([f(x) - 5], f(x)) == FiniteSet((5,)) # Issue #14860 from sympy.physics.units import meter, newton, kilo kN = kilo*newton Eqns = [8*kN + x + y, 28*kN*meter + 3*x*meter] assert linsolve(Eqns, x, y) == { (kilo*newton*Rational(-28, 3), kN*Rational(4, 3))} # linsolve fully expands expressions, so removable singularities # and other nonlinearity does not raise an error assert linsolve([Eq(x, x + y)], [x, y]) == {(x, 0)} assert linsolve([Eq(1/x, 1/x + y)], [x, y]) == {(x, 0)} assert linsolve([Eq(y/x, y/x + y)], [x, y]) == {(x, 0)} assert linsolve([Eq(x*(x + 1), x**2 + y)], [x, y]) == {(y, y)} # corner cases # # XXX: The case below should give the same as for [0] # assert linsolve([], [x]) == {(x,)} assert linsolve([], [x]) is S.EmptySet assert linsolve([0], [x]) == {(x,)} assert linsolve([x], [x, y]) == {(0, y)} assert linsolve([x, 0], [x, y]) == {(0, y)} def test_linsolve_large_sparse(): # # This is mainly a performance test # def _mk_eqs_sol(n): xs = symbols('x:{}'.format(n)) ys = symbols('y:{}'.format(n)) syms = xs + ys eqs = [] sol = (-S.Half,) * n + (S.Half,) * n for xi, yi in zip(xs, ys): eqs.extend([xi + yi, xi - yi + 1]) return eqs, syms, FiniteSet(sol) n = 500 eqs, syms, sol = _mk_eqs_sol(n) assert linsolve(eqs, syms) == sol def test_linsolve_immutable(): A = ImmutableDenseMatrix([[1, 1, 2], [0, 1, 2], [0, 0, 1]]) B = ImmutableDenseMatrix([2, 1, -1]) assert linsolve([A, B], (x, y, z)) == FiniteSet((1, 3, -1)) A = ImmutableDenseMatrix([[1, 1, 7], [1, -1, 3]]) assert linsolve(A) == FiniteSet((5, 2)) def test_solve_decomposition(): n = Dummy('n') f1 = exp(3*x) - 6*exp(2*x) + 11*exp(x) - 6 f2 = sin(x)**2 - 2*sin(x) + 1 f3 = sin(x)**2 - sin(x) f4 = sin(x + 1) f5 = exp(x + 2) - 1 f6 = 1/log(x) f7 = 1/x s1 = ImageSet(Lambda(n, 2*n*pi), S.Integers) s2 = ImageSet(Lambda(n, 2*n*pi + pi), S.Integers) s3 = ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers) s4 = ImageSet(Lambda(n, 2*n*pi - 1), S.Integers) s5 = ImageSet(Lambda(n, 2*n*pi - 1 + pi), S.Integers) assert solve_decomposition(f1, x, S.Reals) == FiniteSet(0, log(2), log(3)) assert dumeq(solve_decomposition(f2, x, S.Reals), s3) assert dumeq(solve_decomposition(f3, x, S.Reals), Union(s1, s2, s3)) assert dumeq(solve_decomposition(f4, x, S.Reals), Union(s4, s5)) assert solve_decomposition(f5, x, S.Reals) == FiniteSet(-2) assert solve_decomposition(f6, x, S.Reals) == S.EmptySet assert solve_decomposition(f7, x, S.Reals) == S.EmptySet assert solve_decomposition(x, x, Interval(1, 2)) == S.EmptySet # nonlinsolve testcases def test_nonlinsolve_basic(): assert nonlinsolve([],[]) == S.EmptySet assert nonlinsolve([],[x, y]) == S.EmptySet system = [x, y - x - 5] assert nonlinsolve([x],[x, y]) == FiniteSet((0, y)) assert nonlinsolve(system, [y]) == FiniteSet((x + 5,)) soln = (ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers),) assert dumeq(nonlinsolve([sin(x) - 1], [x]), FiniteSet(tuple(soln))) assert nonlinsolve([x**2 - 1], [x]) == FiniteSet((-1,), (1,)) soln = FiniteSet((y, y)) assert nonlinsolve([x - y, 0], x, y) == soln assert nonlinsolve([0, x - y], x, y) == soln assert nonlinsolve([x - y, x - y], x, y) == soln assert nonlinsolve([x, 0], x, y) == FiniteSet((0, y)) f = Function('f') assert nonlinsolve([f(x), 0], f(x), y) == FiniteSet((0, y)) assert nonlinsolve([f(x), 0], f(x), f(y)) == FiniteSet((0, f(y))) A = Indexed('A', x) assert nonlinsolve([A, 0], A, y) == FiniteSet((0, y)) assert nonlinsolve([x**2 -1], [sin(x)]) == FiniteSet((S.EmptySet,)) assert nonlinsolve([x**2 -1], sin(x)) == FiniteSet((S.EmptySet,)) assert nonlinsolve([x**2 -1], 1) == FiniteSet((x**2,)) assert nonlinsolve([x**2 -1], x + y) == FiniteSet((S.EmptySet,)) assert nonlinsolve([Eq(1, x + y), Eq(1, -x + y - 1), Eq(1, -x + y - 1)], x, y) == FiniteSet( (-S.Half, 3*S.Half)) def test_nonlinsolve_abs(): soln = FiniteSet((y, y), (-y, y)) assert nonlinsolve([Abs(x) - y], x, y) == soln def test_raise_exception_nonlinsolve(): raises(IndexError, lambda: nonlinsolve([x**2 -1], [])) raises(ValueError, lambda: nonlinsolve([x**2 -1])) raises(NotImplementedError, lambda: nonlinsolve([(x+y)**2 - 9, x**2 - y**2 - 0.75], (x, y))) def test_trig_system(): # TODO: add more simple testcases when solveset returns # simplified soln for Trig eq assert nonlinsolve([sin(x) - 1, cos(x) -1 ], x) == S.EmptySet soln1 = (ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers),) soln = FiniteSet(soln1) assert dumeq(nonlinsolve([sin(x) - 1, cos(x)], x), soln) @XFAIL def test_trig_system_fail(): # fails because solveset trig solver is not much smart. sys = [x + y - pi/2, sin(x) + sin(y) - 1] # solveset returns conditionset for sin(x) + sin(y) - 1 soln_1 = (ImageSet(Lambda(n, n*pi + pi/2), S.Integers), ImageSet(Lambda(n, n*pi), S.Integers)) soln_1 = FiniteSet(soln_1) soln_2 = (ImageSet(Lambda(n, n*pi), S.Integers), ImageSet(Lambda(n, n*pi+ pi/2), S.Integers)) soln_2 = FiniteSet(soln_2) soln = soln_1 + soln_2 assert dumeq(nonlinsolve(sys, [x, y]), soln) # Add more cases from here # http://www.vitutor.com/geometry/trigonometry/equations_systems.html#uno sys = [sin(x) + sin(y) - (sqrt(3)+1)/2, sin(x) - sin(y) - (sqrt(3) - 1)/2] soln_x = Union(ImageSet(Lambda(n, 2*n*pi + pi/3), S.Integers), ImageSet(Lambda(n, 2*n*pi + pi*Rational(2, 3)), S.Integers)) soln_y = Union(ImageSet(Lambda(n, 2*n*pi + pi/6), S.Integers), ImageSet(Lambda(n, 2*n*pi + pi*Rational(5, 6)), S.Integers)) assert dumeq(nonlinsolve(sys, [x, y]), FiniteSet((soln_x, soln_y))) def test_nonlinsolve_positive_dimensional(): x, y, a, b, c, d = symbols('x, y, a, b, c, d', extended_real=True) assert nonlinsolve([x*y, x*y - x], [x, y]) == FiniteSet((0, y)) system = [a**2 + a*c, a - b] assert nonlinsolve(system, [a, b]) == FiniteSet((0, 0), (-c, -c)) # here (a= 0, b = 0) is independent soln so both is printed. # if symbols = [a, b, c] then only {a : -c ,b : -c} eq1 = a + b + c + d eq2 = a*b + b*c + c*d + d*a eq3 = a*b*c + b*c*d + c*d*a + d*a*b eq4 = a*b*c*d - 1 system = [eq1, eq2, eq3, eq4] sol1 = (-1/d, -d, 1/d, FiniteSet(d) - FiniteSet(0)) sol2 = (1/d, -d, -1/d, FiniteSet(d) - FiniteSet(0)) soln = FiniteSet(sol1, sol2) assert nonlinsolve(system, [a, b, c, d]) == soln def test_nonlinsolve_polysys(): x, y = symbols('x, y', real=True) assert nonlinsolve([x**2 + y - 2, x**2 + y], [x, y]) == S.EmptySet s = (-y + 2, y) assert nonlinsolve([(x + y)**2 - 4, x + y - 2], [x, y]) == FiniteSet(s) system = [x**2 - y**2] soln_real = FiniteSet((-y, y), (y, y)) soln_complex = FiniteSet((-Abs(y), y), (Abs(y), y)) soln =soln_real + soln_complex assert nonlinsolve(system, [x, y]) == soln system = [x**2 - y**2] soln_real= FiniteSet((y, -y), (y, y)) soln_complex = FiniteSet((y, -Abs(y)), (y, Abs(y))) soln = soln_real + soln_complex assert nonlinsolve(system, [y, x]) == soln system = [x**2 + y - 3, x - y - 4] assert nonlinsolve(system, (x, y)) != nonlinsolve(system, (y, x)) def test_nonlinsolve_using_substitution(): x, y, z, n = symbols('x, y, z, n', real = True) system = [(x + y)*n - y**2 + 2] s_x = (n*y - y**2 + 2)/n soln = (-s_x, y) assert nonlinsolve(system, [x, y]) == FiniteSet(soln) system = [z**2*x**2 - z**2*y**2/exp(x)] soln_real_1 = (y, x, 0) soln_real_2 = (-exp(x/2)*Abs(x), x, z) soln_real_3 = (exp(x/2)*Abs(x), x, z) soln_complex_1 = (-x*exp(x/2), x, z) soln_complex_2 = (x*exp(x/2), x, z) syms = [y, x, z] soln = FiniteSet(soln_real_1, soln_complex_1, soln_complex_2,\ soln_real_2, soln_real_3) assert nonlinsolve(system,syms) == soln def test_nonlinsolve_complex(): n = Dummy('n') assert dumeq(nonlinsolve([exp(x) - sin(y), 1/y - 3], [x, y]), { (ImageSet(Lambda(n, 2*n*I*pi + log(sin(Rational(1, 3)))), S.Integers), Rational(1, 3))}) system = [exp(x) - sin(y), 1/exp(y) - 3] assert dumeq(nonlinsolve(system, [x, y]), { (ImageSet(Lambda(n, I*(2*n*pi + pi) + log(sin(log(3)))), S.Integers), -log(3)), (ImageSet(Lambda(n, I*(2*n*pi + arg(sin(2*n*I*pi - log(3)))) + log(Abs(sin(2*n*I*pi - log(3))))), S.Integers), ImageSet(Lambda(n, 2*n*I*pi - log(3)), S.Integers))}) system = [exp(x) - sin(y), y**2 - 4] assert dumeq(nonlinsolve(system, [x, y]), { (ImageSet(Lambda(n, I*(2*n*pi + pi) + log(sin(2))), S.Integers), -2), (ImageSet(Lambda(n, 2*n*I*pi + log(sin(2))), S.Integers), 2)}) @XFAIL def test_solve_nonlinear_trans(): # After the transcendental equation solver these will work x, y = symbols('x, y', real=True) soln1 = FiniteSet((2*LambertW(y/2), y)) soln2 = FiniteSet((-x*sqrt(exp(x)), y), (x*sqrt(exp(x)), y)) soln3 = FiniteSet((x*exp(x/2), x)) soln4 = FiniteSet(2*LambertW(y/2), y) assert nonlinsolve([x**2 - y**2/exp(x)], [x, y]) == soln1 assert nonlinsolve([x**2 - y**2/exp(x)], [y, x]) == soln2 assert nonlinsolve([x**2 - y**2/exp(x)], [y, x]) == soln3 assert nonlinsolve([x**2 - y**2/exp(x)], [x, y]) == soln4 def test_issue_14642(): x = Symbol('x') n1 = 0.5*x**3+x**2+0.5+I #add I in the Polynomials solution = solveset(n1, x) assert abs(solution.args[0] - (-2.28267560928153 - 0.312325580497716*I)) <= 1e-9 assert abs(solution.args[1] - (-0.297354141679308 + 1.01904778618762*I)) <= 1e-9 assert abs(solution.args[2] - (0.580029750960839 - 0.706722205689907*I)) <= 1e-9 # Symbolic n1 = S.Half*x**3+x**2+S.Half+I res = FiniteSet(-((3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49) /2)/2)**2)**(S(1)/6)*cos(atan((27 + 3*sqrt(3)*31985**(S(1)/4)* cos(atan(S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan( S(172)/49)/2)/2 + S(43)/2))/3)/3 - S(2)/3 - 4*cos(atan((27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/2)/2)/(3*sqrt(3)* 31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2))/3)/(3*((3* sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/2)/2)**2)**(S(1)/ 6)) + I*(-((3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/ 2)/2)**2)**(S(1)/6)*sin(atan((27 + 3*sqrt(3)*31985**(S(1)/4)*cos( atan(S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49) /2)/2 + S(43)/2))/3)/3 + 4*sin(atan((27 + 3*sqrt(3)*31985**(S(1)/4)* cos(atan(S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172) /49)/2)/2 + S(43)/2))/3)/(3*((3*sqrt(3)*31985**(S(1)/4)*sin(atan( S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)* cos(atan(S(172)/49)/2)/2)**2)**(S(1)/6))), -S(2)/3 - sqrt(3)*((3* sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/2)/2)**2)**(S(1) /6)*sin(atan((27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/2) /2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2)) /3)/6 - 4*re(1/((-S(1)/2 - sqrt(3)*I/2)*(S(43)/2 + 27*I + sqrt(-256 + (43 + 54*I)**2)/2)**(S(1)/3)))/3 + ((3*sqrt(3)*31985**(S(1)/4)*sin( atan(S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)* cos(atan(S(172)/49)/2)/2)**2)**(S(1)/6)*cos(atan((27 + 3*sqrt(3)* 31985**(S(1)/4)*cos(atan(S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)* sin(atan(S(172)/49)/2)/2 + S(43)/2))/3)/6 + I*(-4*im(1/((-S(1)/2 - sqrt(3)*I/2)*(S(43)/2 + 27*I + sqrt(-256 + (43 + 54*I)**2)/2)**(S(1)/ 3)))/3 + ((3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/2) /2)**2)**(S(1)/6)*sin(atan((27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan( S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2))/3)/6 + sqrt(3)*((3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/ 49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan( S(172)/49)/2)/2)**2)**(S(1)/6)*cos(atan((27 + 3*sqrt(3)*31985**(S(1)/ 4)*cos(atan(S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan( S(172)/49)/2)/2 + S(43)/2))/3)/6), -S(2)/3 - 4*re(1/((-S(1)/2 + sqrt(3)*I/2)*(S(43)/2 + 27*I + sqrt(-256 + (43 + 54*I)**2)/2)**(S(1) /3)))/3 + sqrt(3)*((3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/2) /2)**2)**(S(1)/6)*sin(atan((27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan( S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2))/3)/6 + ((3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/2) /2)**2)**(S(1)/6)*cos(atan((27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan( S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2))/3)/6 + I*(-sqrt(3)*((3*sqrt(3)*31985**(S(1)/4)*sin(atan( S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos( atan(S(172)/49)/2)/2)**2)**(S(1)/6)*cos(atan((27 + 3*sqrt(3)*31985**( S(1)/4)*cos(atan(S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin( atan(S(172)/49)/2)/2 + S(43)/2))/3)/6 + ((3*sqrt(3)*31985**(S(1)/4)* sin(atan(S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)* cos(atan(S(172)/49)/2)/2)**2)**(S(1)/6)*sin(atan((27 + 3*sqrt(3)*31985**( S(1)/4)*cos(atan(S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin( atan(S(172)/49)/2)/2 + S(43)/2))/3)/6 - 4*im(1/((-S(1)/2 + sqrt(3)*I/2)* (S(43)/2 + 27*I + sqrt(-256 + (43 + 54*I)**2)/2)**(S(1)/3)))/3)) assert solveset(n1, x) == res def test_issue_13961(): V = (ax, bx, cx, gx, jx, lx, mx, nx, q) = symbols('ax bx cx gx jx lx mx nx q') S = (ax*q - lx*q - mx, ax - gx*q - lx, bx*q**2 + cx*q - jx*q - nx, q*(-ax*q + lx*q + mx), q*(-ax + gx*q + lx)) sol = FiniteSet((lx + mx/q, (-cx*q + jx*q + nx)/q**2, cx, mx/q**2, jx, lx, mx, nx, q), (lx + mx/q, (cx*q - jx*q - nx)/q**2*-1, cx, mx/q**2, jx, lx, mx, nx, q)) assert nonlinsolve(S, *V) == sol # The two solutions are in fact identical, so even better if only one is returned def test_issue_14541(): solutions = solveset(sqrt(-x**2 - 2.0), x) assert abs(solutions.args[0]+1.4142135623731*I) <= 1e-9 assert abs(solutions.args[1]-1.4142135623731*I) <= 1e-9 def test_issue_13396(): expr = -2*y*exp(-x**2 - y**2)*Abs(x) sol = FiniteSet(0) assert solveset(expr, y, domain=S.Reals) == sol # Related type of equation also solved here assert solveset(atan(x**2 - y**2)-pi/2, y, S.Reals) is S.EmptySet def test_issue_12032(): sol = FiniteSet(-sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) + 2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)))/2 + sqrt(Abs(-2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)) + 2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) + 2/sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) + 2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)))))/2, -sqrt(Abs(-2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)) + 2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) + 2/sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) + 2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)))))/2 - sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) + 2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)))/2, sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) + 2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)))/2 - I*sqrt(Abs(-2/sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) + 2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) - 2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)) + 2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)))))/2, sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) + 2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)))/2 + I*sqrt(Abs(-2/sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) + 2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) - 2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)) + 2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1,3)))))/2) assert solveset(x**4 + x - 1, x) == sol def test_issue_10876(): assert solveset(1/sqrt(x), x) == S.EmptySet def test_issue_19050(): # test_issue_19050 --> TypeError removed assert dumeq(nonlinsolve([x + y, sin(y)], [x, y]), FiniteSet((ImageSet(Lambda(n, -2*n*pi), S.Integers), ImageSet(Lambda(n, 2*n*pi), S.Integers)),\ (ImageSet(Lambda(n, -2*n*pi - pi), S.Integers), ImageSet(Lambda(n, 2*n*pi + pi), S.Integers)))) assert dumeq(nonlinsolve([x + y, sin(y) + cos(y)], [x, y]), FiniteSet((ImageSet(Lambda(n, -2*n*pi - 3*pi/4), S.Integers), ImageSet(Lambda(n, 2*n*pi + 3*pi/4), S.Integers)), \ (ImageSet(Lambda(n, -2*n*pi - 7*pi/4), S.Integers), ImageSet(Lambda(n, 2*n*pi + 7*pi/4), S.Integers)))) def test_issue_16618(): # AttributeError is removed ! eqn = [sin(x)*sin(y), cos(x)*cos(y) - 1] ans = FiniteSet((x, 2*n*pi), (2*n*pi, y), (x, 2*n*pi + pi), (2*n*pi + pi, y)) sol = nonlinsolve(eqn, [x, y]) for i0, j0 in zip(ordered(sol), ordered(ans)): assert len(i0) == len(j0) == 2 assert all(a.dummy_eq(b) for a, b in zip(i0, j0)) assert len(sol) == len(ans) def test_issue_17566(): assert nonlinsolve([32*(2**x)/2**(-y) - 4**y, 27*(3**x) - 1/3**y], x, y) ==\ FiniteSet((-log(81)/log(3), 1)) def test_issue_16643(): n = Dummy('n') assert solveset(x**2*sin(x), x).dummy_eq(Union(ImageSet(Lambda(n, 2*n*pi + pi), S.Integers), ImageSet(Lambda(n, 2*n*pi), S.Integers))) def test_issue_19587(): n,m = symbols('n m') assert nonlinsolve([32*2**m*2**n - 4**n, 27*3**m - 3**(-n)], m, n) ==\ FiniteSet((-log(81)/log(3), 1)) def test_issue_5132_1(): system = [sqrt(x**2 + y**2) - sqrt(10), x + y - 4] assert nonlinsolve(system, [x, y]) == FiniteSet((1, 3), (3, 1)) n = Dummy('n') eqs = [exp(x)**2 - sin(y) + z**2, 1/exp(y) - 3] s_real_y = -log(3) s_real_z = sqrt(-exp(2*x) - sin(log(3))) soln_real = FiniteSet((s_real_y, s_real_z), (s_real_y, -s_real_z)) lam = Lambda(n, 2*n*I*pi + -log(3)) s_complex_y = ImageSet(lam, S.Integers) lam = Lambda(n, sqrt(-exp(2*x) + sin(2*n*I*pi + -log(3)))) s_complex_z_1 = ImageSet(lam, S.Integers) lam = Lambda(n, -sqrt(-exp(2*x) + sin(2*n*I*pi + -log(3)))) s_complex_z_2 = ImageSet(lam, S.Integers) soln_complex = FiniteSet( (s_complex_y, s_complex_z_1), (s_complex_y, s_complex_z_2) ) soln = soln_real + soln_complex assert dumeq(nonlinsolve(eqs, [y, z]), soln) def test_issue_5132_2(): x, y = symbols('x, y', real=True) eqs = [exp(x)**2 - sin(y) + z**2, 1/exp(y) - 3] n = Dummy('n') soln_real = (log(-z**2 + sin(y))/2, z) lam = Lambda( n, I*(2*n*pi + arg(-z**2 + sin(y)))/2 + log(Abs(z**2 - sin(y)))/2) img = ImageSet(lam, S.Integers) # not sure about the complex soln. But it looks correct. soln_complex = (img, z) soln = FiniteSet(soln_real, soln_complex) assert dumeq(nonlinsolve(eqs, [x, z]), soln) system = [r - x**2 - y**2, tan(t) - y/x] s_x = sqrt(r/(tan(t)**2 + 1)) s_y = sqrt(r/(tan(t)**2 + 1))*tan(t) soln = FiniteSet((s_x, s_y), (-s_x, -s_y)) assert nonlinsolve(system, [x, y]) == soln def test_issue_6752(): a, b = symbols('a, b', real=True) assert nonlinsolve([a**2 + a, a - b], [a, b]) == {(-1, -1), (0, 0)} @SKIP("slow") def test_issue_5114_solveset(): # slow testcase from sympy.abc import o, p # there is no 'a' in the equation set but this is how the # problem was originally posed syms = [a, b, c, f, h, k, n] eqs = [b + r/d - c/d, c*(1/d + 1/e + 1/g) - f/g - r/d, f*(1/g + 1/i + 1/j) - c/g - h/i, h*(1/i + 1/l + 1/m) - f/i - k/m, k*(1/m + 1/o + 1/p) - h/m - n/p, n*(1/p + 1/q) - k/p] assert len(nonlinsolve(eqs, syms)) == 1 @SKIP("Hangs") def _test_issue_5335(): # Not able to check zero dimensional system. # is_zero_dimensional Hangs lam, a0, conc = symbols('lam a0 conc') eqs = [lam + 2*y - a0*(1 - x/2)*x - 0.005*x/2*x, a0*(1 - x/2)*x - 1*y - 0.743436700916726*y, x + y - conc] sym = [x, y, a0] # there are 4 solutions but only two are valid assert len(nonlinsolve(eqs, sym)) == 2 # float eqs = [lam + 2*y - a0*(1 - x/2)*x - 0.005*x/2*x, a0*(1 - x/2)*x - 1*y - 0.743436700916726*y, x + y - conc] sym = [x, y, a0] assert len(nonlinsolve(eqs, sym)) == 2 def test_issue_2777(): # the equations represent two circles x, y = symbols('x y', real=True) e1, e2 = sqrt(x**2 + y**2) - 10, sqrt(y**2 + (-x + 10)**2) - 3 a, b = Rational(191, 20), 3*sqrt(391)/20 ans = {(a, -b), (a, b)} assert nonlinsolve((e1, e2), (x, y)) == ans assert nonlinsolve((e1, e2/(x - a)), (x, y)) == S.EmptySet # make the 2nd circle's radius be -3 e2 += 6 assert nonlinsolve((e1, e2), (x, y)) == S.EmptySet def test_issue_8828(): x1 = 0 y1 = -620 r1 = 920 x2 = 126 y2 = 276 x3 = 51 y3 = 205 r3 = 104 v = [x, y, z] f1 = (x - x1)**2 + (y - y1)**2 - (r1 - z)**2 f2 = (x2 - x)**2 + (y2 - y)**2 - z**2 f3 = (x - x3)**2 + (y - y3)**2 - (r3 - z)**2 F = [f1, f2, f3] g1 = sqrt((x - x1)**2 + (y - y1)**2) + z - r1 g2 = f2 g3 = sqrt((x - x3)**2 + (y - y3)**2) + z - r3 G = [g1, g2, g3] # both soln same A = nonlinsolve(F, v) B = nonlinsolve(G, v) assert A == B def test_nonlinsolve_conditionset(): # when solveset failed to solve all the eq # return conditionset f = Function('f') f1 = f(x) - pi/2 f2 = f(y) - pi*Rational(3, 2) intermediate_system = Eq(2*f(x) - pi, 0) & Eq(2*f(y) - 3*pi, 0) syms = Tuple(x, y) soln = ConditionSet( syms, intermediate_system, S.Complexes**2) assert nonlinsolve([f1, f2], [x, y]) == soln def test_substitution_basic(): assert substitution([], [x, y]) == S.EmptySet assert substitution([], []) == S.EmptySet system = [2*x**2 + 3*y**2 - 30, 3*x**2 - 2*y**2 - 19] soln = FiniteSet((-3, -2), (-3, 2), (3, -2), (3, 2)) assert substitution(system, [x, y]) == soln soln = FiniteSet((-1, 1)) assert substitution([x + y], [x], [{y: 1}], [y], set(), [x, y]) == soln assert substitution( [x + y], [x], [{y: 1}], [y], {x + 1}, [y, x]) == S.EmptySet def test_issue_5132_substitution(): x, y, z, r, t = symbols('x, y, z, r, t', real=True) system = [r - x**2 - y**2, tan(t) - y/x] s_x_1 = Complement(FiniteSet(-sqrt(r/(tan(t)**2 + 1))), FiniteSet(0)) s_x_2 = Complement(FiniteSet(sqrt(r/(tan(t)**2 + 1))), FiniteSet(0)) s_y = sqrt(r/(tan(t)**2 + 1))*tan(t) soln = FiniteSet((s_x_2, s_y)) + FiniteSet((s_x_1, -s_y)) assert substitution(system, [x, y]) == soln n = Dummy('n') eqs = [exp(x)**2 - sin(y) + z**2, 1/exp(y) - 3] s_real_y = -log(3) s_real_z = sqrt(-exp(2*x) - sin(log(3))) soln_real = FiniteSet((s_real_y, s_real_z), (s_real_y, -s_real_z)) lam = Lambda(n, 2*n*I*pi + -log(3)) s_complex_y = ImageSet(lam, S.Integers) lam = Lambda(n, sqrt(-exp(2*x) + sin(2*n*I*pi + -log(3)))) s_complex_z_1 = ImageSet(lam, S.Integers) lam = Lambda(n, -sqrt(-exp(2*x) + sin(2*n*I*pi + -log(3)))) s_complex_z_2 = ImageSet(lam, S.Integers) soln_complex = FiniteSet( (s_complex_y, s_complex_z_1), (s_complex_y, s_complex_z_2)) soln = soln_real + soln_complex assert dumeq(substitution(eqs, [y, z]), soln) def test_raises_substitution(): raises(ValueError, lambda: substitution([x**2 -1], [])) raises(TypeError, lambda: substitution([x**2 -1])) raises(ValueError, lambda: substitution([x**2 -1], [sin(x)])) raises(TypeError, lambda: substitution([x**2 -1], x)) raises(TypeError, lambda: substitution([x**2 -1], 1)) def test_issue_21022(): from sympy.core.sympify import sympify eqs = [ 'k-16', 'p-8', 'y*y+z*z-x*x', 'd - x + p', 'd*d+k*k-y*y', 'z*z-p*p-k*k', 'abc-efg', ] efg = Symbol('efg') eqs = [sympify(x) for x in eqs] syb = list(ordered(set.union(*[x.free_symbols for x in eqs]))) res = nonlinsolve(eqs, syb) ans = FiniteSet( (efg, sqrt(-16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16)*sqrt(16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16), efg, 16, 8, 8 + sqrt(-16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16)*sqrt(16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16), sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16, -8*sqrt(5)), (efg, sqrt(-16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16)*sqrt(16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16), efg, 16, 8, 8 + sqrt(-16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16)*sqrt(16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16), sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16, 8*sqrt(5)), (efg, -sqrt(-16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16)*sqrt(16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16), efg, 16, 8, -sqrt(-16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16)*sqrt(16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16) + 8, sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16, -8*sqrt(5)), (efg, -sqrt(-16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16)*sqrt(16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16), efg, 16, 8, -sqrt(-16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16)*sqrt(16 + sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16) + 8, sqrt(640 - 128*sqrt(5))*sqrt(128*sqrt(5) + 640)/16, 8*sqrt(5)) ) assert len(res) == len(ans) == 4 assert res == ans for result in res.args: assert len(result) == 8 def test_issue_17940(): n = Dummy('n') k1 = Dummy('k1') sol = ImageSet(Lambda(((k1, n),), I*(2*k1*pi + arg(2*n*I*pi + log(5))) + log(Abs(2*n*I*pi + log(5)))), ProductSet(S.Integers, S.Integers)) assert solveset(exp(exp(x)) - 5, x).dummy_eq(sol) def test_issue_17906(): assert solveset(7**(x**2 - 80) - 49**x, x) == FiniteSet(-8, 10) def test_issue_17933(): eq1 = x*sin(45) - y*cos(q) eq2 = x*cos(45) - y*sin(q) eq3 = 9*x*sin(45)/10 + y*cos(q) eq4 = 9*x*cos(45)/10 + y*sin(z) - z assert nonlinsolve([eq1, eq2, eq3, eq4], x, y, z, q) ==\ FiniteSet((0, 0, 0, q)) def test_issue_14565(): # removed redundancy assert dumeq(nonlinsolve([k + m, k + m*exp(-2*pi*k)], [k, m]) , FiniteSet((-n*I, ImageSet(Lambda(n, n*I), S.Integers)))) # end of tests for nonlinsolve def test_issue_9556(): b = Symbol('b', positive=True) assert solveset(Abs(x) + 1, x, S.Reals) is S.EmptySet assert solveset(Abs(x) + b, x, S.Reals) is S.EmptySet assert solveset(Eq(b, -1), b, S.Reals) is S.EmptySet def test_issue_9611(): assert solveset(Eq(x - x + a, a), x, S.Reals) == S.Reals assert solveset(Eq(y - y + a, a), y) == S.Complexes def test_issue_9557(): assert solveset(x**2 + a, x, S.Reals) == Intersection(S.Reals, FiniteSet(-sqrt(-a), sqrt(-a))) def test_issue_9778(): x = Symbol('x', real=True) y = Symbol('y', real=True) assert solveset(x**3 + 1, x, S.Reals) == FiniteSet(-1) assert solveset(x**Rational(3, 5) + 1, x, S.Reals) == S.EmptySet assert solveset(x**3 + y, x, S.Reals) == \ FiniteSet(-Abs(y)**Rational(1, 3)*sign(y)) def test_issue_10214(): assert solveset(x**Rational(3, 2) + 4, x, S.Reals) == S.EmptySet assert solveset(x**(Rational(-3, 2)) + 4, x, S.Reals) == S.EmptySet ans = FiniteSet(-2**Rational(2, 3)) assert solveset(x**(S(3)) + 4, x, S.Reals) == ans assert (x**(S(3)) + 4).subs(x,list(ans)[0]) == 0 # substituting ans and verifying the result. assert (x**(S(3)) + 4).subs(x,-(-2)**Rational(2, 3)) == 0 def test_issue_9849(): assert solveset(Abs(sin(x)) + 1, x, S.Reals) == S.EmptySet def test_issue_9953(): assert linsolve([ ], x) == S.EmptySet def test_issue_9913(): assert solveset(2*x + 1/(x - 10)**2, x, S.Reals) == \ FiniteSet(-(3*sqrt(24081)/4 + Rational(4027, 4))**Rational(1, 3)/3 - 100/ (3*(3*sqrt(24081)/4 + Rational(4027, 4))**Rational(1, 3)) + Rational(20, 3)) def test_issue_10397(): assert solveset(sqrt(x), x, S.Complexes) == FiniteSet(0) def test_issue_14987(): raises(ValueError, lambda: linear_eq_to_matrix( [x**2], x)) raises(ValueError, lambda: linear_eq_to_matrix( [x*(-3/x + 1) + 2*y - a], [x, y])) raises(ValueError, lambda: linear_eq_to_matrix( [(x**2 - 3*x)/(x - 3) - 3], x)) raises(ValueError, lambda: linear_eq_to_matrix( [(x + 1)**3 - x**3 - 3*x**2 + 7], x)) raises(ValueError, lambda: linear_eq_to_matrix( [x*(1/x + 1) + y], [x, y])) raises(ValueError, lambda: linear_eq_to_matrix( [(x + 1)*y], [x, y])) raises(ValueError, lambda: linear_eq_to_matrix( [Eq(1/x, 1/x + y)], [x, y])) raises(ValueError, lambda: linear_eq_to_matrix( [Eq(y/x, y/x + y)], [x, y])) raises(ValueError, lambda: linear_eq_to_matrix( [Eq(x*(x + 1), x**2 + y)], [x, y])) def test_simplification(): eq = x + (a - b)/(-2*a + 2*b) assert solveset(eq, x) == FiniteSet(S.Half) assert solveset(eq, x, S.Reals) == Intersection({-((a - b)/(-2*a + 2*b))}, S.Reals) # So that ap - bn is not zero: ap = Symbol('ap', positive=True) bn = Symbol('bn', negative=True) eq = x + (ap - bn)/(-2*ap + 2*bn) assert solveset(eq, x) == FiniteSet(S.Half) assert solveset(eq, x, S.Reals) == FiniteSet(S.Half) def test_integer_domain_relational(): eq1 = 2*x + 3 > 0 eq2 = x**2 + 3*x - 2 >= 0 eq3 = x + 1/x > -2 + 1/x eq4 = x + sqrt(x**2 - 5) > 0 eq = x + 1/x > -2 + 1/x eq5 = eq.subs(x,log(x)) eq6 = log(x)/x <= 0 eq7 = log(x)/x < 0 eq8 = x/(x-3) < 3 eq9 = x/(x**2-3) < 3 assert solveset(eq1, x, S.Integers) == Range(-1, oo, 1) assert solveset(eq2, x, S.Integers) == Union(Range(-oo, -3, 1), Range(1, oo, 1)) assert solveset(eq3, x, S.Integers) == Union(Range(-1, 0, 1), Range(1, oo, 1)) assert solveset(eq4, x, S.Integers) == Range(3, oo, 1) assert solveset(eq5, x, S.Integers) == Range(2, oo, 1) assert solveset(eq6, x, S.Integers) == Range(1, 2, 1) assert solveset(eq7, x, S.Integers) == S.EmptySet assert solveset(eq8, x, domain=Range(0,5)) == Range(0, 3, 1) assert solveset(eq9, x, domain=Range(0,5)) == Union(Range(0, 2, 1), Range(2, 5, 1)) # test_issue_19794 assert solveset(x + 2 < 0, x, S.Integers) == Range(-oo, -2, 1) def test_issue_10555(): f = Function('f') g = Function('g') assert solveset(f(x) - pi/2, x, S.Reals).dummy_eq( ConditionSet(x, Eq(f(x) - pi/2, 0), S.Reals)) assert solveset(f(g(x)) - pi/2, g(x), S.Reals).dummy_eq( ConditionSet(g(x), Eq(f(g(x)) - pi/2, 0), S.Reals)) def test_issue_8715(): eq = x + 1/x > -2 + 1/x assert solveset(eq, x, S.Reals) == \ (Interval.open(-2, oo) - FiniteSet(0)) assert solveset(eq.subs(x,log(x)), x, S.Reals) == \ Interval.open(exp(-2), oo) - FiniteSet(1) def test_issue_11174(): eq = z**2 + exp(2*x) - sin(y) soln = Intersection(S.Reals, FiniteSet(log(-z**2 + sin(y))/2)) assert solveset(eq, x, S.Reals) == soln eq = sqrt(r)*Abs(tan(t))/sqrt(tan(t)**2 + 1) + x*tan(t) s = -sqrt(r)*Abs(tan(t))/(sqrt(tan(t)**2 + 1)*tan(t)) soln = Intersection(S.Reals, FiniteSet(s)) assert solveset(eq, x, S.Reals) == soln def test_issue_11534(): # eq and eq2 should give the same solution as a Complement x = Symbol('x', real=True) y = Symbol('y', real=True) eq = -y + x/sqrt(-x**2 + 1) eq2 = -y**2 + x**2/(-x**2 + 1) soln = Complement(FiniteSet(-y/sqrt(y**2 + 1), y/sqrt(y**2 + 1)), FiniteSet(-1, 1)) assert solveset(eq, x, S.Reals) == soln assert solveset(eq2, x, S.Reals) == soln def test_issue_10477(): assert solveset((x**2 + 4*x - 3)/x < 2, x, S.Reals) == \ Union(Interval.open(-oo, -3), Interval.open(0, 1)) def test_issue_10671(): assert solveset(sin(y), y, Interval(0, pi)) == FiniteSet(0, pi) i = Interval(1, 10) assert solveset((1/x).diff(x) < 0, x, i) == i def test_issue_11064(): eq = x + sqrt(x**2 - 5) assert solveset(eq > 0, x, S.Reals) == \ Interval(sqrt(5), oo) assert solveset(eq < 0, x, S.Reals) == \ Interval(-oo, -sqrt(5)) assert solveset(eq > sqrt(5), x, S.Reals) == \ Interval.Lopen(sqrt(5), oo) def test_issue_12478(): eq = sqrt(x - 2) + 2 soln = solveset_real(eq, x) assert soln is S.EmptySet assert solveset(eq < 0, x, S.Reals) is S.EmptySet assert solveset(eq > 0, x, S.Reals) == Interval(2, oo) def test_issue_12429(): eq = solveset(log(x)/x <= 0, x, S.Reals) sol = Interval.Lopen(0, 1) assert eq == sol def test_issue_19506(): eq = arg(x + I) C = Dummy('C') assert solveset(eq).dummy_eq(Intersection(ConditionSet(C, Eq(im(C) + 1, 0), S.Complexes), ConditionSet(C, re(C) > 0, S.Complexes))) def test_solveset_arg(): assert solveset(arg(x), x, S.Reals) == Interval.open(0, oo) assert solveset(arg(4*x -3), x, S.Reals) == Interval.open(Rational(3, 4), oo) def test__is_finite_with_finite_vars(): f = _is_finite_with_finite_vars # issue 12482 assert all(f(1/x) is None for x in ( Dummy(), Dummy(real=True), Dummy(complex=True))) assert f(1/Dummy(real=False)) is True # b/c it's finite but not 0 def test_issue_13550(): assert solveset(x**2 - 2*x - 15, symbol = x, domain = Interval(-oo, 0)) == FiniteSet(-3) def test_issue_13849(): assert nonlinsolve((t*(sqrt(5) + sqrt(2)) - sqrt(2), t), t) is S.EmptySet def test_issue_14223(): assert solveset((Abs(x + Min(x, 2)) - 2).rewrite(Piecewise), x, S.Reals) == FiniteSet(-1, 1) assert solveset((Abs(x + Min(x, 2)) - 2).rewrite(Piecewise), x, Interval(0, 2)) == FiniteSet(1) assert solveset(x, x, FiniteSet(1, 2)) is S.EmptySet def test_issue_10158(): dom = S.Reals assert solveset(x*Max(x, 15) - 10, x, dom) == FiniteSet(Rational(2, 3)) assert solveset(x*Min(x, 15) - 10, x, dom) == FiniteSet(-sqrt(10), sqrt(10)) assert solveset(Max(Abs(x - 3) - 1, x + 2) - 3, x, dom) == FiniteSet(-1, 1) assert solveset(Abs(x - 1) - Abs(y), x, dom) == FiniteSet(-Abs(y) + 1, Abs(y) + 1) assert solveset(Abs(x + 4*Abs(x + 1)), x, dom) == FiniteSet(Rational(-4, 3), Rational(-4, 5)) assert solveset(2*Abs(x + Abs(x + Max(3, x))) - 2, x, S.Reals) == FiniteSet(-1, -2) dom = S.Complexes raises(ValueError, lambda: solveset(x*Max(x, 15) - 10, x, dom)) raises(ValueError, lambda: solveset(x*Min(x, 15) - 10, x, dom)) raises(ValueError, lambda: solveset(Max(Abs(x - 3) - 1, x + 2) - 3, x, dom)) raises(ValueError, lambda: solveset(Abs(x - 1) - Abs(y), x, dom)) raises(ValueError, lambda: solveset(Abs(x + 4*Abs(x + 1)), x, dom)) def test_issue_14300(): f = 1 - exp(-18000000*x) - y a1 = FiniteSet(-log(-y + 1)/18000000) assert solveset(f, x, S.Reals) == \ Intersection(S.Reals, a1) assert dumeq(solveset(f, x), ImageSet(Lambda(n, -I*(2*n*pi + arg(-y + 1))/18000000 - log(Abs(y - 1))/18000000), S.Integers)) def test_issue_14454(): number = CRootOf(x**4 + x - 1, 2) raises(ValueError, lambda: invert_real(number, 0, x)) assert invert_real(x**2, number, x) # no error def test_issue_17882(): assert solveset(-8*x**2/(9*(x**2 - 1)**(S(4)/3)) + 4/(3*(x**2 - 1)**(S(1)/3)), x, S.Complexes) == \ FiniteSet(sqrt(3), -sqrt(3)) def test_term_factors(): assert list(_term_factors(3**x - 2)) == [-2, 3**x] expr = 4**(x + 1) + 4**(x + 2) + 4**(x - 1) - 3**(x + 2) - 3**(x + 3) assert set(_term_factors(expr)) == { 3**(x + 2), 4**(x + 2), 3**(x + 3), 4**(x - 1), -1, 4**(x + 1)} #################### tests for transolve and its helpers ############### def test_transolve(): assert _transolve(3**x, x, S.Reals) == S.EmptySet assert _transolve(3**x - 9**(x + 5), x, S.Reals) == FiniteSet(-10) def test_issue_21276(): eq = (2*x*(y - z) - y*erf(y - z) - y + z*erf(y - z) + z)**2 assert solveset(eq.expand(), y) == FiniteSet(z, z + erfinv(2*x - 1)) # exponential tests def test_exponential_real(): from sympy.abc import y e1 = 3**(2*x) - 2**(x + 3) e2 = 4**(5 - 9*x) - 8**(2 - x) e3 = 2**x + 4**x e4 = exp(log(5)*x) - 2**x e5 = exp(x/y)*exp(-z/y) - 2 e6 = 5**(x/2) - 2**(x/3) e7 = 4**(x + 1) + 4**(x + 2) + 4**(x - 1) - 3**(x + 2) - 3**(x + 3) e8 = -9*exp(-2*x + 5) + 4*exp(3*x + 1) e9 = 2**x + 4**x + 8**x - 84 e10 = 29*2**(x + 1)*615**(x) - 123*2726**(x) assert solveset(e1, x, S.Reals) == FiniteSet( -3*log(2)/(-2*log(3) + log(2))) assert solveset(e2, x, S.Reals) == FiniteSet(Rational(4, 15)) assert solveset(e3, x, S.Reals) == S.EmptySet assert solveset(e4, x, S.Reals) == FiniteSet(0) assert solveset(e5, x, S.Reals) == Intersection( S.Reals, FiniteSet(y*log(2*exp(z/y)))) assert solveset(e6, x, S.Reals) == FiniteSet(0) assert solveset(e7, x, S.Reals) == FiniteSet(2) assert solveset(e8, x, S.Reals) == FiniteSet(-2*log(2)/5 + 2*log(3)/5 + Rational(4, 5)) assert solveset(e9, x, S.Reals) == FiniteSet(2) assert solveset(e10,x, S.Reals) == FiniteSet((-log(29) - log(2) + log(123))/(-log(2726) + log(2) + log(615))) assert solveset_real(-9*exp(-2*x + 5) + 2**(x + 1), x) == FiniteSet( -((-5 - 2*log(3) + log(2))/(log(2) + 2))) assert solveset_real(4**(x/2) - 2**(x/3), x) == FiniteSet(0) b = sqrt(6)*sqrt(log(2))/sqrt(log(5)) assert solveset_real(5**(x/2) - 2**(3/x), x) == FiniteSet(-b, b) # coverage test C1, C2 = symbols('C1 C2') f = Function('f') assert solveset_real(C1 + C2/x**2 - exp(-f(x)), f(x)) == Intersection( S.Reals, FiniteSet(-log(C1 + C2/x**2))) y = symbols('y', positive=True) assert solveset_real(x**2 - y**2/exp(x), y) == Intersection( S.Reals, FiniteSet(-sqrt(x**2*exp(x)), sqrt(x**2*exp(x)))) p = Symbol('p', positive=True) assert solveset_real((1/p + 1)**(p + 1), p).dummy_eq( ConditionSet(x, Eq((1 + 1/x)**(x + 1), 0), S.Reals)) @XFAIL def test_exponential_complex(): n = Dummy('n') assert dumeq(solveset_complex(2**x + 4**x, x),imageset( Lambda(n, I*(2*n*pi + pi)/log(2)), S.Integers)) assert solveset_complex(x**z*y**z - 2, z) == FiniteSet( log(2)/(log(x) + log(y))) assert dumeq(solveset_complex(4**(x/2) - 2**(x/3), x), imageset( Lambda(n, 3*n*I*pi/log(2)), S.Integers)) assert dumeq(solveset(2**x + 32, x), imageset( Lambda(n, (I*(2*n*pi + pi) + 5*log(2))/log(2)), S.Integers)) eq = (2**exp(y**2/x) + 2)/(x**2 + 15) a = sqrt(x)*sqrt(-log(log(2)) + log(log(2) + 2*n*I*pi)) assert solveset_complex(eq, y) == FiniteSet(-a, a) union1 = imageset(Lambda(n, I*(2*n*pi - pi*Rational(2, 3))/log(2)), S.Integers) union2 = imageset(Lambda(n, I*(2*n*pi + pi*Rational(2, 3))/log(2)), S.Integers) assert dumeq(solveset(2**x + 4**x + 8**x, x), Union(union1, union2)) eq = 4**(x + 1) + 4**(x + 2) + 4**(x - 1) - 3**(x + 2) - 3**(x + 3) res = solveset(eq, x) num = 2*n*I*pi - 4*log(2) + 2*log(3) den = -2*log(2) + log(3) ans = imageset(Lambda(n, num/den), S.Integers) assert dumeq(res, ans) def test_expo_conditionset(): f1 = (exp(x) + 1)**x - 2 f2 = (x + 2)**y*x - 3 f3 = 2**x - exp(x) - 3 f4 = log(x) - exp(x) f5 = 2**x + 3**x - 5**x assert solveset(f1, x, S.Reals).dummy_eq(ConditionSet( x, Eq((exp(x) + 1)**x - 2, 0), S.Reals)) assert solveset(f2, x, S.Reals).dummy_eq(ConditionSet( x, Eq(x*(x + 2)**y - 3, 0), S.Reals)) assert solveset(f3, x, S.Reals).dummy_eq(ConditionSet( x, Eq(2**x - exp(x) - 3, 0), S.Reals)) assert solveset(f4, x, S.Reals).dummy_eq(ConditionSet( x, Eq(-exp(x) + log(x), 0), S.Reals)) assert solveset(f5, x, S.Reals).dummy_eq(ConditionSet( x, Eq(2**x + 3**x - 5**x, 0), S.Reals)) def test_exponential_symbols(): x, y, z = symbols('x y z', positive=True) xr, zr = symbols('xr, zr', real=True) assert solveset(z**x - y, x, S.Reals) == Intersection( S.Reals, FiniteSet(log(y)/log(z))) f1 = 2*x**w - 4*y**w f2 = (x/y)**w - 2 sol1 = Intersection({log(2)/(log(x) - log(y))}, S.Reals) sol2 = Intersection({log(2)/log(x/y)}, S.Reals) assert solveset(f1, w, S.Reals) == sol1, solveset(f1, w, S.Reals) assert solveset(f2, w, S.Reals) == sol2, solveset(f2, w, S.Reals) assert solveset(x**x, x, Interval.Lopen(0,oo)).dummy_eq( ConditionSet(w, Eq(w**w, 0), Interval.open(0, oo))) assert solveset(x**y - 1, y, S.Reals) == FiniteSet(0) assert solveset(exp(x/y)*exp(-z/y) - 2, y, S.Reals) == \ Complement(ConditionSet(y, Eq(im(x)/y, 0) & Eq(im(z)/y, 0), \ Complement(Intersection(FiniteSet((x - z)/log(2)), S.Reals), FiniteSet(0))), FiniteSet(0)) assert solveset(exp(xr/y)*exp(-zr/y) - 2, y, S.Reals) == \ Complement(FiniteSet((xr - zr)/log(2)), FiniteSet(0)) assert solveset(a**x - b**x, x).dummy_eq(ConditionSet( w, Ne(a, 0) & Ne(b, 0), FiniteSet(0))) def test_ignore_assumptions(): # make sure assumptions are ignored xpos = symbols('x', positive=True) x = symbols('x') assert solveset_complex(xpos**2 - 4, xpos ) == solveset_complex(x**2 - 4, x) @XFAIL def test_issue_10864(): assert solveset(x**(y*z) - x, x, S.Reals) == FiniteSet(1) @XFAIL def test_solve_only_exp_2(): assert solveset_real(sqrt(exp(x)) + sqrt(exp(-x)) - 4, x) == \ FiniteSet(2*log(-sqrt(3) + 2), 2*log(sqrt(3) + 2)) def test_is_exponential(): assert _is_exponential(y, x) is False assert _is_exponential(3**x - 2, x) is True assert _is_exponential(5**x - 7**(2 - x), x) is True assert _is_exponential(sin(2**x) - 4*x, x) is False assert _is_exponential(x**y - z, y) is True assert _is_exponential(x**y - z, x) is False assert _is_exponential(2**x + 4**x - 1, x) is True assert _is_exponential(x**(y*z) - x, x) is False assert _is_exponential(x**(2*x) - 3**x, x) is False assert _is_exponential(x**y - y*z, y) is False assert _is_exponential(x**y - x*z, y) is True def test_solve_exponential(): assert _solve_exponential(3**(2*x) - 2**(x + 3), 0, x, S.Reals) == \ FiniteSet(-3*log(2)/(-2*log(3) + log(2))) assert _solve_exponential(2**y + 4**y, 1, y, S.Reals) == \ FiniteSet(log(Rational(-1, 2) + sqrt(5)/2)/log(2)) assert _solve_exponential(2**y + 4**y, 0, y, S.Reals) == \ S.EmptySet assert _solve_exponential(2**x + 3**x - 5**x, 0, x, S.Reals) == \ ConditionSet(x, Eq(2**x + 3**x - 5**x, 0), S.Reals) # end of exponential tests # logarithmic tests def test_logarithmic(): assert solveset_real(log(x - 3) + log(x + 3), x) == FiniteSet( -sqrt(10), sqrt(10)) assert solveset_real(log(x + 1) - log(2*x - 1), x) == FiniteSet(2) assert solveset_real(log(x + 3) + log(1 + 3/x) - 3, x) == FiniteSet( -3 + sqrt(-12 + exp(3))*exp(Rational(3, 2))/2 + exp(3)/2, -sqrt(-12 + exp(3))*exp(Rational(3, 2))/2 - 3 + exp(3)/2) eq = z - log(x) + log(y/(x*(-1 + y**2/x**2))) assert solveset_real(eq, x) == \ Intersection(S.Reals, FiniteSet(-sqrt(y**2 - y*exp(z)), sqrt(y**2 - y*exp(z)))) - \ Intersection(S.Reals, FiniteSet(-sqrt(y**2), sqrt(y**2))) assert solveset_real( log(3*x) - log(-x + 1) - log(4*x + 1), x) == FiniteSet(Rational(-1, 2), S.Half) assert solveset(log(x**y) - y*log(x), x, S.Reals) == S.Reals @XFAIL def test_uselogcombine_2(): eq = log(exp(2*x) + 1) + log(-tanh(x) + 1) - log(2) assert solveset_real(eq, x) is S.EmptySet eq = log(8*x) - log(sqrt(x) + 1) - 2 assert solveset_real(eq, x) is S.EmptySet def test_is_logarithmic(): assert _is_logarithmic(y, x) is False assert _is_logarithmic(log(x), x) is True assert _is_logarithmic(log(x) - 3, x) is True assert _is_logarithmic(log(x)*log(y), x) is True assert _is_logarithmic(log(x)**2, x) is False assert _is_logarithmic(log(x - 3) + log(x + 3), x) is True assert _is_logarithmic(log(x**y) - y*log(x), x) is True assert _is_logarithmic(sin(log(x)), x) is False assert _is_logarithmic(x + y, x) is False assert _is_logarithmic(log(3*x) - log(1 - x) + 4, x) is True assert _is_logarithmic(log(x) + log(y) + x, x) is False assert _is_logarithmic(log(log(x - 3)) + log(x - 3), x) is True assert _is_logarithmic(log(log(3) + x) + log(x), x) is True assert _is_logarithmic(log(x)*(y + 3) + log(x), y) is False def test_solve_logarithm(): y = Symbol('y') assert _solve_logarithm(log(x**y) - y*log(x), 0, x, S.Reals) == S.Reals y = Symbol('y', positive=True) assert _solve_logarithm(log(x)*log(y), 0, x, S.Reals) == FiniteSet(1) # end of logarithmic tests # lambert tests def test_is_lambert(): a, b, c = symbols('a,b,c') assert _is_lambert(x**2, x) is False assert _is_lambert(a**x**2+b*x+c, x) is True assert _is_lambert(E**2, x) is False assert _is_lambert(x*E**2, x) is False assert _is_lambert(3*log(x) - x*log(3), x) is True assert _is_lambert(log(log(x - 3)) + log(x-3), x) is True assert _is_lambert(5*x - 1 + 3*exp(2 - 7*x), x) is True assert _is_lambert((a/x + exp(x/2)).diff(x, 2), x) is True assert _is_lambert((x**2 - 2*x + 1).subs(x, (log(x) + 3*x)**2 - 1), x) is True assert _is_lambert(x*sinh(x) - 1, x) is True assert _is_lambert(x*cos(x) - 5, x) is True assert _is_lambert(tanh(x) - 5*x, x) is True assert _is_lambert(cosh(x) - sinh(x), x) is False # end of lambert tests def test_linear_coeffs(): from sympy.solvers.solveset import linear_coeffs assert linear_coeffs(0, x) == [0, 0] assert all(i is S.Zero for i in linear_coeffs(0, x)) assert linear_coeffs(x + 2*y + 3, x, y) == [1, 2, 3] assert linear_coeffs(x + 2*y + 3, y, x) == [2, 1, 3] assert linear_coeffs(x + 2*x**2 + 3, x, x**2) == [1, 2, 3] raises(ValueError, lambda: linear_coeffs(x + 2*x**2 + x**3, x, x**2)) raises(ValueError, lambda: linear_coeffs(1/x*(x - 1) + 1/x, x)) raises(ValueError, lambda: linear_coeffs(x, x, x)) assert linear_coeffs(a*(x + y), x, y) == [a, a, 0] assert linear_coeffs(1.0, x, y) == [0, 0, 1.0] # modular tests def test_is_modular(): assert _is_modular(y, x) is False assert _is_modular(Mod(x, 3) - 1, x) is True assert _is_modular(Mod(x**3 - 3*x**2 - x + 1, 3) - 1, x) is True assert _is_modular(Mod(exp(x + y), 3) - 2, x) is True assert _is_modular(Mod(exp(x + y), 3) - log(x), x) is True assert _is_modular(Mod(x, 3) - 1, y) is False assert _is_modular(Mod(x, 3)**2 - 5, x) is False assert _is_modular(Mod(x, 3)**2 - y, x) is False assert _is_modular(exp(Mod(x, 3)) - 1, x) is False assert _is_modular(Mod(3, y) - 1, y) is False def test_invert_modular(): n = Dummy('n', integer=True) from sympy.solvers.solveset import _invert_modular as invert_modular # non invertible cases assert invert_modular(Mod(sin(x), 7), S(5), n, x) == (Mod(sin(x), 7), 5) assert invert_modular(Mod(exp(x), 7), S(5), n, x) == (Mod(exp(x), 7), 5) assert invert_modular(Mod(log(x), 7), S(5), n, x) == (Mod(log(x), 7), 5) # a is symbol assert dumeq(invert_modular(Mod(x, 7), S(5), n, x), (x, ImageSet(Lambda(n, 7*n + 5), S.Integers))) # a.is_Add assert dumeq(invert_modular(Mod(x + 8, 7), S(5), n, x), (x, ImageSet(Lambda(n, 7*n + 4), S.Integers))) assert invert_modular(Mod(x**2 + x, 7), S(5), n, x) == \ (Mod(x**2 + x, 7), 5) # a.is_Mul assert dumeq(invert_modular(Mod(3*x, 7), S(5), n, x), (x, ImageSet(Lambda(n, 7*n + 4), S.Integers))) assert invert_modular(Mod((x + 1)*(x + 2), 7), S(5), n, x) == \ (Mod((x + 1)*(x + 2), 7), 5) # a.is_Pow assert invert_modular(Mod(x**4, 7), S(5), n, x) == \ (x, S.EmptySet) assert dumeq(invert_modular(Mod(3**x, 4), S(3), n, x), (x, ImageSet(Lambda(n, 2*n + 1), S.Naturals0))) assert dumeq(invert_modular(Mod(2**(x**2 + x + 1), 7), S(2), n, x), (x**2 + x + 1, ImageSet(Lambda(n, 3*n + 1), S.Naturals0))) assert invert_modular(Mod(sin(x)**4, 7), S(5), n, x) == (x, S.EmptySet) def test_solve_modular(): n = Dummy('n', integer=True) # if rhs has symbol (need to be implemented in future). assert solveset(Mod(x, 4) - x, x, S.Integers ).dummy_eq( ConditionSet(x, Eq(-x + Mod(x, 4), 0), S.Integers)) # when _invert_modular fails to invert assert solveset(3 - Mod(sin(x), 7), x, S.Integers ).dummy_eq( ConditionSet(x, Eq(Mod(sin(x), 7) - 3, 0), S.Integers)) assert solveset(3 - Mod(log(x), 7), x, S.Integers ).dummy_eq( ConditionSet(x, Eq(Mod(log(x), 7) - 3, 0), S.Integers)) assert solveset(3 - Mod(exp(x), 7), x, S.Integers ).dummy_eq(ConditionSet(x, Eq(Mod(exp(x), 7) - 3, 0), S.Integers)) # EmptySet solution definitely assert solveset(7 - Mod(x, 5), x, S.Integers) is S.EmptySet assert solveset(5 - Mod(x, 5), x, S.Integers) is S.EmptySet # Negative m assert dumeq(solveset(2 + Mod(x, -3), x, S.Integers), ImageSet(Lambda(n, -3*n - 2), S.Integers)) assert solveset(4 + Mod(x, -3), x, S.Integers) is S.EmptySet # linear expression in Mod assert dumeq(solveset(3 - Mod(x, 5), x, S.Integers), ImageSet(Lambda(n, 5*n + 3), S.Integers)) assert dumeq(solveset(3 - Mod(5*x - 8, 7), x, S.Integers), ImageSet(Lambda(n, 7*n + 5), S.Integers)) assert dumeq(solveset(3 - Mod(5*x, 7), x, S.Integers), ImageSet(Lambda(n, 7*n + 2), S.Integers)) # higher degree expression in Mod assert dumeq(solveset(Mod(x**2, 160) - 9, x, S.Integers), Union(ImageSet(Lambda(n, 160*n + 3), S.Integers), ImageSet(Lambda(n, 160*n + 13), S.Integers), ImageSet(Lambda(n, 160*n + 67), S.Integers), ImageSet(Lambda(n, 160*n + 77), S.Integers), ImageSet(Lambda(n, 160*n + 83), S.Integers), ImageSet(Lambda(n, 160*n + 93), S.Integers), ImageSet(Lambda(n, 160*n + 147), S.Integers), ImageSet(Lambda(n, 160*n + 157), S.Integers))) assert solveset(3 - Mod(x**4, 7), x, S.Integers) is S.EmptySet assert dumeq(solveset(Mod(x**4, 17) - 13, x, S.Integers), Union(ImageSet(Lambda(n, 17*n + 3), S.Integers), ImageSet(Lambda(n, 17*n + 5), S.Integers), ImageSet(Lambda(n, 17*n + 12), S.Integers), ImageSet(Lambda(n, 17*n + 14), S.Integers))) # a.is_Pow tests assert dumeq(solveset(Mod(7**x, 41) - 15, x, S.Integers), ImageSet(Lambda(n, 40*n + 3), S.Naturals0)) assert dumeq(solveset(Mod(12**x, 21) - 18, x, S.Integers), ImageSet(Lambda(n, 6*n + 2), S.Naturals0)) assert dumeq(solveset(Mod(3**x, 4) - 3, x, S.Integers), ImageSet(Lambda(n, 2*n + 1), S.Naturals0)) assert dumeq(solveset(Mod(2**x, 7) - 2 , x, S.Integers), ImageSet(Lambda(n, 3*n + 1), S.Naturals0)) assert dumeq(solveset(Mod(3**(3**x), 4) - 3, x, S.Integers), Intersection(ImageSet(Lambda(n, Intersection({log(2*n + 1)/log(3)}, S.Integers)), S.Naturals0), S.Integers)) # Implemented for m without primitive root assert solveset(Mod(x**3, 7) - 2, x, S.Integers) is S.EmptySet assert dumeq(solveset(Mod(x**3, 8) - 1, x, S.Integers), ImageSet(Lambda(n, 8*n + 1), S.Integers)) assert dumeq(solveset(Mod(x**4, 9) - 4, x, S.Integers), Union(ImageSet(Lambda(n, 9*n + 4), S.Integers), ImageSet(Lambda(n, 9*n + 5), S.Integers))) # domain intersection assert dumeq(solveset(3 - Mod(5*x - 8, 7), x, S.Naturals0), Intersection(ImageSet(Lambda(n, 7*n + 5), S.Integers), S.Naturals0)) # Complex args assert solveset(Mod(x, 3) - I, x, S.Integers) == \ S.EmptySet assert solveset(Mod(I*x, 3) - 2, x, S.Integers ).dummy_eq( ConditionSet(x, Eq(Mod(I*x, 3) - 2, 0), S.Integers)) assert solveset(Mod(I + x, 3) - 2, x, S.Integers ).dummy_eq( ConditionSet(x, Eq(Mod(x + I, 3) - 2, 0), S.Integers)) # issue 17373 (https://github.com/sympy/sympy/issues/17373) assert dumeq(solveset(Mod(x**4, 14) - 11, x, S.Integers), Union(ImageSet(Lambda(n, 14*n + 3), S.Integers), ImageSet(Lambda(n, 14*n + 11), S.Integers))) assert dumeq(solveset(Mod(x**31, 74) - 43, x, S.Integers), ImageSet(Lambda(n, 74*n + 31), S.Integers)) # issue 13178 n = symbols('n', integer=True) a = 742938285 b = 1898888478 m = 2**31 - 1 c = 20170816 assert dumeq(solveset(c - Mod(a**n*b, m), n, S.Integers), ImageSet(Lambda(n, 2147483646*n + 100), S.Naturals0)) assert dumeq(solveset(c - Mod(a**n*b, m), n, S.Naturals0), Intersection(ImageSet(Lambda(n, 2147483646*n + 100), S.Naturals0), S.Naturals0)) assert dumeq(solveset(c - Mod(a**(2*n)*b, m), n, S.Integers), Intersection(ImageSet(Lambda(n, 1073741823*n + 50), S.Naturals0), S.Integers)) assert solveset(c - Mod(a**(2*n + 7)*b, m), n, S.Integers) is S.EmptySet assert dumeq(solveset(c - Mod(a**(n - 4)*b, m), n, S.Integers), Intersection(ImageSet(Lambda(n, 2147483646*n + 104), S.Naturals0), S.Integers)) # end of modular tests def test_issue_17276(): assert nonlinsolve([Eq(x, 5**(S(1)/5)), Eq(x*y, 25*sqrt(5))], x, y) == \ FiniteSet((5**(S(1)/5), 25*5**(S(3)/10))) def test_issue_10426(): x = Dummy('x') a = Symbol('a') n = Dummy('n') assert (solveset(sin(x + a) - sin(x), a)).dummy_eq(Dummy('x')) == (Union( ImageSet(Lambda(n, 2*n*pi), S.Integers), Intersection(S.Complexes, ImageSet(Lambda(n, -I*(I*(2*n*pi + arg(-exp(-2*I*x))) + 2*im(x))), S.Integers)))).dummy_eq(Dummy('x,n')) def test_solveset_conjugate(): """Test solveset for simple conjugate functions""" assert solveset(conjugate(x) -3 + I) == FiniteSet(3 + I) def test_issue_18208(): variables = symbols('x0:16') + symbols('y0:12') x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15,\ y0, y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11 = variables eqs = [x0 + x1 + x2 + x3 - 51, x0 + x1 + x4 + x5 - 46, x2 + x3 + x6 + x7 - 39, x0 + x3 + x4 + x7 - 50, x1 + x2 + x5 + x6 - 35, x4 + x5 + x6 + x7 - 34, x4 + x5 + x8 + x9 - 46, x10 + x11 + x6 + x7 - 23, x11 + x4 + x7 + x8 - 25, x10 + x5 + x6 + x9 - 44, x10 + x11 + x8 + x9 - 35, x12 + x13 + x8 + x9 - 35, x10 + x11 + x14 + x15 - 29, x11 + x12 + x15 + x8 - 35, x10 + x13 + x14 + x9 - 29, x12 + x13 + x14 + x15 - 29, y0 + y1 + y2 + y3 - 55, y0 + y1 + y4 + y5 - 53, y2 + y3 + y6 + y7 - 56, y0 + y3 + y4 + y7 - 57, y1 + y2 + y5 + y6 - 52, y4 + y5 + y6 + y7 - 54, y4 + y5 + y8 + y9 - 48, y10 + y11 + y6 + y7 - 60, y11 + y4 + y7 + y8 - 51, y10 + y5 + y6 + y9 - 57, y10 + y11 + y8 + y9 - 54, x10 - 2, x11 - 5, x12 - 1, x13 - 6, x14 - 1, x15 - 21, y0 - 12, y1 - 20] expected = [38 - x3, x3 - 10, 23 - x3, x3, 12 - x7, x7 + 6, 16 - x7, x7, 8, 20, 2, 5, 1, 6, 1, 21, 12, 20, -y11 + y9 + 2, y11 - y9 + 21, -y11 - y7 + y9 + 24, y11 + y7 - y9 - 3, 33 - y7, y7, 27 - y9, y9, 27 - y11, y11] A, b = linear_eq_to_matrix(eqs, variables) # solve solve_expected = {v:eq for v, eq in zip(variables, expected) if v != eq} assert solve(eqs, variables) == solve_expected # linsolve linsolve_expected = FiniteSet(Tuple(*expected)) assert linsolve(eqs, variables) == linsolve_expected assert linsolve((A, b), variables) == linsolve_expected # gauss_jordan_solve gj_solve, new_vars = A.gauss_jordan_solve(b) gj_solve = [i for i in gj_solve] gj_expected = linsolve_expected.subs(zip([x3, x7, y7, y9, y11], new_vars)) assert FiniteSet(Tuple(*gj_solve)) == gj_expected # nonlinsolve # The solution set of nonlinsolve is currently equivalent to linsolve and is # also correct. However, we would prefer to use the same symbols as parameters # for the solution to the underdetermined system in all cases if possible. # We want a solution that is not just equivalent but also given in the same form. # This test may be changed should nonlinsolve be modified in this way. nonlinsolve_expected = FiniteSet((38 - x3, x3 - 10, 23 - x3, x3, 12 - x7, x7 + 6, 16 - x7, x7, 8, 20, 2, 5, 1, 6, 1, 21, 12, 20, -y5 + y7 - 1, y5 - y7 + 24, 21 - y5, y5, 33 - y7, y7, 27 - y9, y9, -y5 + y7 - y9 + 24, y5 - y7 + y9 + 3)) assert nonlinsolve(eqs, variables) == nonlinsolve_expected @XFAIL def test_substitution_with_infeasible_solution(): a00, a01, a10, a11, l0, l1, l2, l3, m0, m1, m2, m3, m4, m5, m6, m7, c00, c01, c10, c11, p00, p01, p10, p11 = symbols( 'a00, a01, a10, a11, l0, l1, l2, l3, m0, m1, m2, m3, m4, m5, m6, m7, c00, c01, c10, c11, p00, p01, p10, p11' ) solvefor = [p00, p01, p10, p11, c00, c01, c10, c11, m0, m1, m3, l0, l1, l2, l3] system = [ -l0 * c00 - l1 * c01 + m0 + c00 + c01, -l0 * c10 - l1 * c11 + m1, -l2 * c00 - l3 * c01 + c00 + c01, -l2 * c10 - l3 * c11 + m3, -l0 * p00 - l2 * p10 + p00 + p10, -l1 * p00 - l3 * p10 + p00 + p10, -l0 * p01 - l2 * p11, -l1 * p01 - l3 * p11, -a00 + c00 * p00 + c10 * p01, -a01 + c01 * p00 + c11 * p01, -a10 + c00 * p10 + c10 * p11, -a11 + c01 * p10 + c11 * p11, -m0 * p00, -m1 * p01, -m2 * p10, -m3 * p11, -m4 * c00, -m5 * c01, -m6 * c10, -m7 * c11, m2, m4, m5, m6, m7 ] sol = FiniteSet( (0, Complement(FiniteSet(p01), FiniteSet(0)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, l2, l3), (p00, Complement(FiniteSet(p01), FiniteSet(0)), 0, p11, 0, 0, 0, 0, 0, 0, 0, 1, 1, -p01/p11, -p01/p11), (0, Complement(FiniteSet(p01), FiniteSet(0)), 0, p11, 0, 0, 0, 0, 0, 0, 0, 1, -l3*p11/p01, -p01/p11, l3), (0, Complement(FiniteSet(p01), FiniteSet(0)), 0, p11, 0, 0, 0, 0, 0, 0, 0, -l2*p11/p01, -l3*p11/p01, l2, l3), ) assert sol != nonlinsolve(system, solvefor) def test_issue_20097(): assert solveset(1/sqrt(x)) is S.EmptySet def test_issue_15350(): assert solveset(diff(sqrt(1/x+x))) == FiniteSet(-1, 1) def test_issue_18359(): c1 = Piecewise((0, x < 0), (Min(1, x)/2 - Min(2, x)/2 + Min(3, x)/2, True)) c2 = Piecewise((Piecewise((0, x < 0), (Min(1, x)/2 - Min(2, x)/2 + Min(3, x)/2, True)), x >= 0), (0, True)) correct_result = Interval(1, 2) result1 = solveset(c1 - Rational(1, 2), x, Interval(0, 3)) result2 = solveset(c2 - Rational(1, 2), x, Interval(0, 3)) assert result1 == correct_result assert result2 == correct_result def test_issue_17604(): lhs = -2**(3*x/11)*exp(x/11) + pi**(x/11) assert _is_exponential(lhs, x) assert _solve_exponential(lhs, 0, x, S.Complexes) == FiniteSet(0) def test_issue_17580(): assert solveset(1/(1 - x**3)**2, x, S.Reals) is S.EmptySet def test_issue_17566_actual(): sys = [2**x + 2**y - 3, 4**x + 9**y - 5] # Not clear this is the correct result, but at least no recursion error assert nonlinsolve(sys, x, y) == FiniteSet((log(3 - 2**y)/log(2), y)) def test_issue_17565(): eq = Ge(2*(x - 2)**2/(3*(x + 1)**(Integer(1)/3)) + 2*(x - 2)*(x + 1)**(Integer(2)/3), 0) res = Union(Interval.Lopen(-1, -Rational(1, 4)), Interval(2, oo)) assert solveset(eq, x, S.Reals) == res def test_issue_15024(): function = (x + 5)/sqrt(-x**2 - 10*x) assert solveset(function, x, S.Reals) == FiniteSet(Integer(-5)) def test_issue_16877(): assert dumeq(nonlinsolve([x - 1, sin(y)], x, y), FiniteSet((FiniteSet(1), ImageSet(Lambda(n, 2*n*pi), S.Integers)), (FiniteSet(1), ImageSet(Lambda(n, 2*n*pi + pi), S.Integers)))) # Even better if (FiniteSet(1), ImageSet(Lambda(n, n*pi), S.Integers)) is obtained def test_issue_16876(): assert dumeq(nonlinsolve([sin(x), 2*x - 4*y], x, y), FiniteSet((ImageSet(Lambda(n, 2*n*pi), S.Integers), ImageSet(Lambda(n, n*pi), S.Integers)), (ImageSet(Lambda(n, 2*n*pi + pi), S.Integers), ImageSet(Lambda(n, n*pi + pi/2), S.Integers)))) # Even better if (ImageSet(Lambda(n, n*pi), S.Integers), # ImageSet(Lambda(n, n*pi/2), S.Integers)) is obtained def test_issue_21236(): x, z = symbols("x z") y = symbols('y', rational=True) assert solveset(x**y - z, x, S.Reals) == ConditionSet(x, Eq(x**y - z, 0), S.Reals) e1, e2 = symbols('e1 e2', even=True) y = e1/e2 # don't know if num or den will be odd and the other even assert solveset(x**y - z, x, S.Reals) == ConditionSet(x, Eq(x**y - z, 0), S.Reals) def test_issue_21908(): assert nonlinsolve([(x**2 + 2*x - y**2)*exp(x), -2*y*exp(x)], x, y ) == {(-2, 0), (0, 0)} def test_issue_19144(): # test case 1 expr1 = [x + y - 1, y**2 + 1] eq1 = [Eq(i, 0) for i in expr1] soln1 = {(1 - I, I), (1 + I, -I)} soln_expr1 = nonlinsolve(expr1, [x, y]) soln_eq1 = nonlinsolve(eq1, [x, y]) assert soln_eq1 == soln_expr1 == soln1 # test case 2 - with denoms expr2 = [x/y - 1, y**2 + 1] eq2 = [Eq(i, 0) for i in expr2] soln2 = {(-I, -I), (I, I)} soln_expr2 = nonlinsolve(expr2, [x, y]) soln_eq2 = nonlinsolve(eq2, [x, y]) assert soln_eq2 == soln_expr2 == soln2 # denominators that cancel in expression assert nonlinsolve([Eq(x + 1/x, 1/x)], [x]) == FiniteSet((S.EmptySet,)) def test_issue_22413(): res = nonlinsolve((4*y*(2*x + 2*exp(y) + 1)*exp(2*x), 4*x*exp(2*x) + 4*y*exp(2*x + y) + 4*exp(2*x + y) + 1), x, y) # First solution is not correct, but the issue was an exception sols = FiniteSet((x, S.Zero), (-exp(y) - S.Half, y)) assert res == sols def test_issue_19814(): assert nonlinsolve([ 2**m - 2**(2*n), 4*2**m - 2**(4*n)], m, n ) == FiniteSet((log(2**(2*n))/log(2), S.Complexes)) def test_issue_22058(): sol = solveset(-sqrt(t)*x**2 + 2*x + sqrt(t), x, S.Reals) # doesn't fail (and following numerical check) assert sol.xreplace({t: 1}) == {1 - sqrt(2), 1 + sqrt(2)}, sol.xreplace({t: 1}) def test_issue_11184(): assert solveset(20*sqrt(y**2 + (sqrt(-(y - 10)*(y + 10)) + 10)**2) - 60, y, S.Reals) is S.EmptySet def test_issue_21890(): e = S(2)/3 assert nonlinsolve([4*x**3*y**4 - 2*y, 4*x**4*y**3 - 2*x], x, y) == { (2**e/(2*y), y), ((-2**e/4 - 2**e*sqrt(3)*I/4)/y, y), ((-2**e/4 + 2**e*sqrt(3)*I/4)/y, y)} assert nonlinsolve([(1 - 4*x**2)*exp(-2*x**2 - 2*y**2), -4*x*y*exp(-2*x**2)*exp(-2*y**2)], x, y) == {(-S(1)/2, 0), (S(1)/2, 0)} rx, ry = symbols('x y', real=True) sol = nonlinsolve([4*rx**3*ry**4 - 2*ry, 4*rx**4*ry**3 - 2*rx], rx, ry) ans = {(2**(S(2)/3)/(2*ry), ry), ((-2**(S(2)/3)/4 - 2**(S(2)/3)*sqrt(3)*I/4)/ry, ry), ((-2**(S(2)/3)/4 + 2**(S(2)/3)*sqrt(3)*I/4)/ry, ry)} assert sol == ans
5f2c9edcf9001e3d28a3fdfd2efdd51ba1b13704d9f03278687e45cf6f2d2ace
from sympy.assumptions.ask import (Q, ask) from sympy.core.add import Add from sympy.core.containers import Tuple from sympy.core.function import (Derivative, Function, diff) from sympy.core.mul import Mul from sympy.core import (GoldenRatio, TribonacciConstant) from sympy.core.numbers import (E, Float, I, Rational, oo, pi) from sympy.core.relational import (Eq, Gt, Lt, Ne) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, Wild, symbols) from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import binomial from sympy.functions.elementary.complexes import (Abs, arg, conjugate, im, re) from sympy.functions.elementary.exponential import (LambertW, exp, log) from sympy.functions.elementary.hyperbolic import (atanh, cosh, sinh, tanh) from sympy.functions.elementary.miscellaneous import (cbrt, root, sqrt) from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (acos, asin, atan, atan2, cos, sec, sin, tan) from sympy.functions.special.error_functions import (erf, erfc, erfcinv, erfinv) from sympy.integrals.integrals import Integral from sympy.logic.boolalg import (And, Or) from sympy.matrices.dense import Matrix from sympy.matrices import SparseMatrix from sympy.polys.polytools import Poly from sympy.printing.str import sstr from sympy.simplify.radsimp import denom from sympy.solvers.solvers import (nsolve, solve, solve_linear) from sympy.core.function import nfloat from sympy.solvers import solve_linear_system, solve_linear_system_LU, \ solve_undetermined_coeffs from sympy.solvers.bivariate import _filtered_gens, _solve_lambert, _lambert from sympy.solvers.solvers import _invert, unrad, checksol, posify, _ispow, \ det_quick, det_perm, det_minor, _simple_dens, denoms from sympy.physics.units import cm from sympy.polys.rootoftools import CRootOf from sympy.testing.pytest import slow, XFAIL, SKIP, raises from sympy.core.random import verify_numerically as tn from sympy.abc import a, b, c, d, e, k, h, p, x, y, z, t, q, m, R def NS(e, n=15, **options): return sstr(sympify(e).evalf(n, **options), full_prec=True) def test_swap_back(): f, g = map(Function, 'fg') fx, gx = f(x), g(x) assert solve([fx + y - 2, fx - gx - 5], fx, y, gx) == \ {fx: gx + 5, y: -gx - 3} assert solve(fx + gx*x - 2, [fx, gx], dict=True)[0] == {fx: 2, gx: 0} assert solve(fx + gx**2*x - y, [fx, gx], dict=True) == [{fx: y - gx**2*x}] assert solve([f(1) - 2, x + 2], dict=True) == [{x: -2, f(1): 2}] def guess_solve_strategy(eq, symbol): try: solve(eq, symbol) return True except (TypeError, NotImplementedError): return False def test_guess_poly(): # polynomial equations assert guess_solve_strategy( S(4), x ) # == GS_POLY assert guess_solve_strategy( x, x ) # == GS_POLY assert guess_solve_strategy( x + a, x ) # == GS_POLY assert guess_solve_strategy( 2*x, x ) # == GS_POLY assert guess_solve_strategy( x + sqrt(2), x) # == GS_POLY assert guess_solve_strategy( x + 2**Rational(1, 4), x) # == GS_POLY assert guess_solve_strategy( x**2 + 1, x ) # == GS_POLY assert guess_solve_strategy( x**2 - 1, x ) # == GS_POLY assert guess_solve_strategy( x*y + y, x ) # == GS_POLY assert guess_solve_strategy( x*exp(y) + y, x) # == GS_POLY assert guess_solve_strategy( (x - y**3)/(y**2*sqrt(1 - y**2)), x) # == GS_POLY def test_guess_poly_cv(): # polynomial equations via a change of variable assert guess_solve_strategy( sqrt(x) + 1, x ) # == GS_POLY_CV_1 assert guess_solve_strategy( x**Rational(1, 3) + sqrt(x) + 1, x ) # == GS_POLY_CV_1 assert guess_solve_strategy( 4*x*(1 - sqrt(x)), x ) # == GS_POLY_CV_1 # polynomial equation multiplying both sides by x**n assert guess_solve_strategy( x + 1/x + y, x ) # == GS_POLY_CV_2 def test_guess_rational_cv(): # rational functions assert guess_solve_strategy( (x + 1)/(x**2 + 2), x) # == GS_RATIONAL assert guess_solve_strategy( (x - y**3)/(y**2*sqrt(1 - y**2)), y) # == GS_RATIONAL_CV_1 # rational functions via the change of variable y -> x**n assert guess_solve_strategy( (sqrt(x) + 1)/(x**Rational(1, 3) + sqrt(x) + 1), x ) \ #== GS_RATIONAL_CV_1 def test_guess_transcendental(): #transcendental functions assert guess_solve_strategy( exp(x) + 1, x ) # == GS_TRANSCENDENTAL assert guess_solve_strategy( 2*cos(x) - y, x ) # == GS_TRANSCENDENTAL assert guess_solve_strategy( exp(x) + exp(-x) - y, x ) # == GS_TRANSCENDENTAL assert guess_solve_strategy(3**x - 10, x) # == GS_TRANSCENDENTAL assert guess_solve_strategy(-3**x + 10, x) # == GS_TRANSCENDENTAL assert guess_solve_strategy(a*x**b - y, x) # == GS_TRANSCENDENTAL def test_solve_args(): # equation container, issue 5113 ans = {x: -3, y: 1} eqs = (x + 5*y - 2, -3*x + 6*y - 15) assert all(solve(container(eqs), x, y) == ans for container in (tuple, list, set, frozenset)) assert solve(Tuple(*eqs), x, y) == ans # implicit symbol to solve for assert set(solve(x**2 - 4)) == {S(2), -S(2)} assert solve([x + y - 3, x - y - 5]) == {x: 4, y: -1} assert solve(x - exp(x), x, implicit=True) == [exp(x)] # no symbol to solve for assert solve(42) == solve(42, x) == [] assert solve([1, 2]) == [] assert solve([sqrt(2)],[x]) == [] # duplicate symbols removed assert solve((x - 3, y + 2), x, y, x) == {x: 3, y: -2} # unordered symbols # only 1 assert solve(y - 3, {y}) == [3] # more than 1 assert solve(y - 3, {x, y}) == [{y: 3}] # multiple symbols: take the first linear solution+ # - return as tuple with values for all requested symbols assert solve(x + y - 3, [x, y]) == [(3 - y, y)] # - unless dict is True assert solve(x + y - 3, [x, y], dict=True) == [{x: 3 - y}] # - or no symbols are given assert solve(x + y - 3) == [{x: 3 - y}] # multiple symbols might represent an undetermined coefficients system assert solve(a + b*x - 2, [a, b]) == {a: 2, b: 0} args = (a + b)*x - b**2 + 2, a, b assert solve(*args) == \ [(-sqrt(2), sqrt(2)), (sqrt(2), -sqrt(2))] assert solve(*args, set=True) == \ ([a, b], {(-sqrt(2), sqrt(2)), (sqrt(2), -sqrt(2))}) assert solve(*args, dict=True) == \ [{b: sqrt(2), a: -sqrt(2)}, {b: -sqrt(2), a: sqrt(2)}] eq = a*x**2 + b*x + c - ((x - h)**2 + 4*p*k)/4/p flags = dict(dict=True) assert solve(eq, [h, p, k], exclude=[a, b, c], **flags) == \ [{k: c - b**2/(4*a), h: -b/(2*a), p: 1/(4*a)}] flags.update(dict(simplify=False)) assert solve(eq, [h, p, k], exclude=[a, b, c], **flags) == \ [{k: (4*a*c - b**2)/(4*a), h: -b/(2*a), p: 1/(4*a)}] # failing undetermined system assert solve(a*x + b**2/(x + 4) - 3*x - 4/x, a, b, dict=True) == \ [{a: (-b**2*x + 3*x**3 + 12*x**2 + 4*x + 16)/(x**2*(x + 4))}] # failed single equation assert solve(1/(1/x - y + exp(y))) == [] raises( NotImplementedError, lambda: solve(exp(x) + sin(x) + exp(y) + sin(y))) # failed system # -- when no symbols given, 1 fails assert solve([y, exp(x) + x]) == {x: -LambertW(1), y: 0} # both fail assert solve( (exp(x) - x, exp(y) - y)) == {x: -LambertW(-1), y: -LambertW(-1)} # -- when symbols given assert solve([y, exp(x) + x], x, y) == {y: 0, x: -LambertW(1)} # symbol is a number assert solve(x**2 - pi, pi) == [x**2] # no equations assert solve([], [x]) == [] # overdetermined system # - nonlinear assert solve([(x + y)**2 - 4, x + y - 2]) == [{x: -y + 2}] # - linear assert solve((x + y - 2, 2*x + 2*y - 4)) == {x: -y + 2} # When one or more args are Boolean assert solve(Eq(x**2, 0.0)) == [0] # issue 19048 assert solve([True, Eq(x, 0)], [x], dict=True) == [{x: 0}] assert solve([Eq(x, x), Eq(x, 0), Eq(x, x+1)], [x], dict=True) == [] assert not solve([Eq(x, x+1), x < 2], x) assert solve([Eq(x, 0), x+1<2]) == Eq(x, 0) assert solve([Eq(x, x), Eq(x, x+1)], x) == [] assert solve(True, x) == [] assert solve([x - 1, False], [x], set=True) == ([], set()) def test_solve_polynomial1(): assert solve(3*x - 2, x) == [Rational(2, 3)] assert solve(Eq(3*x, 2), x) == [Rational(2, 3)] assert set(solve(x**2 - 1, x)) == {-S.One, S.One} assert set(solve(Eq(x**2, 1), x)) == {-S.One, S.One} assert solve(x - y**3, x) == [y**3] rx = root(x, 3) assert solve(x - y**3, y) == [ rx, -rx/2 - sqrt(3)*I*rx/2, -rx/2 + sqrt(3)*I*rx/2] a11, a12, a21, a22, b1, b2 = symbols('a11,a12,a21,a22,b1,b2') assert solve([a11*x + a12*y - b1, a21*x + a22*y - b2], x, y) == \ { x: (a22*b1 - a12*b2)/(a11*a22 - a12*a21), y: (a11*b2 - a21*b1)/(a11*a22 - a12*a21), } solution = {y: S.Zero, x: S.Zero} assert solve((x - y, x + y), x, y ) == solution assert solve((x - y, x + y), (x, y)) == solution assert solve((x - y, x + y), [x, y]) == solution assert set(solve(x**3 - 15*x - 4, x)) == { -2 + 3**S.Half, S(4), -2 - 3**S.Half } assert set(solve((x**2 - 1)**2 - a, x)) == \ {sqrt(1 + sqrt(a)), -sqrt(1 + sqrt(a)), sqrt(1 - sqrt(a)), -sqrt(1 - sqrt(a))} def test_solve_polynomial2(): assert solve(4, x) == [] def test_solve_polynomial_cv_1a(): """ Test for solving on equations that can be converted to a polynomial equation using the change of variable y -> x**Rational(p, q) """ assert solve( sqrt(x) - 1, x) == [1] assert solve( sqrt(x) - 2, x) == [4] assert solve( x**Rational(1, 4) - 2, x) == [16] assert solve( x**Rational(1, 3) - 3, x) == [27] assert solve(sqrt(x) + x**Rational(1, 3) + x**Rational(1, 4), x) == [0] def test_solve_polynomial_cv_1b(): assert set(solve(4*x*(1 - a*sqrt(x)), x)) == {S.Zero, 1/a**2} assert set(solve(x*(root(x, 3) - 3), x)) == {S.Zero, S(27)} def test_solve_polynomial_cv_2(): """ Test for solving on equations that can be converted to a polynomial equation multiplying both sides of the equation by x**m """ assert solve(x + 1/x - 1, x) in \ [[ S.Half + I*sqrt(3)/2, S.Half - I*sqrt(3)/2], [ S.Half - I*sqrt(3)/2, S.Half + I*sqrt(3)/2]] def test_quintics_1(): f = x**5 - 110*x**3 - 55*x**2 + 2310*x + 979 s = solve(f, check=False) for r in s: res = f.subs(x, r.n()).n() assert tn(res, 0) f = x**5 - 15*x**3 - 5*x**2 + 10*x + 20 s = solve(f) for r in s: assert r.func == CRootOf # if one uses solve to get the roots of a polynomial that has a CRootOf # solution, make sure that the use of nfloat during the solve process # doesn't fail. Note: if you want numerical solutions to a polynomial # it is *much* faster to use nroots to get them than to solve the # equation only to get RootOf solutions which are then numerically # evaluated. So for eq = x**5 + 3*x + 7 do Poly(eq).nroots() rather # than [i.n() for i in solve(eq)] to get the numerical roots of eq. assert nfloat(solve(x**5 + 3*x**3 + 7)[0], exponent=False) == \ CRootOf(x**5 + 3*x**3 + 7, 0).n() def test_quintics_2(): f = x**5 + 15*x + 12 s = solve(f, check=False) for r in s: res = f.subs(x, r.n()).n() assert tn(res, 0) f = x**5 - 15*x**3 - 5*x**2 + 10*x + 20 s = solve(f) for r in s: assert r.func == CRootOf assert solve(x**5 - 6*x**3 - 6*x**2 + x - 6) == [ CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 0), CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 1), CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 2), CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 3), CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 4)] def test_quintics_3(): y = x**5 + x**3 - 2**Rational(1, 3) assert solve(y) == solve(-y) == [] def test_highorder_poly(): # just testing that the uniq generator is unpacked sol = solve(x**6 - 2*x + 2) assert all(isinstance(i, CRootOf) for i in sol) and len(sol) == 6 def test_solve_rational(): """Test solve for rational functions""" assert solve( ( x - y**3 )/( (y**2)*sqrt(1 - y**2) ), x) == [y**3] def test_solve_conjugate(): """Test solve for simple conjugate functions""" assert solve(conjugate(x) -3 + I) == [3 + I] def test_solve_nonlinear(): assert solve(x**2 - y**2, x, y, dict=True) == [{x: -y}, {x: y}] assert solve(x**2 - y**2/exp(x), y, x, dict=True) == [{y: -x*sqrt(exp(x))}, {y: x*sqrt(exp(x))}] def test_issue_8666(): x = symbols('x') assert solve(Eq(x**2 - 1/(x**2 - 4), 4 - 1/(x**2 - 4)), x) == [] assert solve(Eq(x + 1/x, 1/x), x) == [] def test_issue_7228(): assert solve(4**(2*(x**2) + 2*x) - 8, x) == [Rational(-3, 2), S.Half] def test_issue_7190(): assert solve(log(x-3) + log(x+3), x) == [sqrt(10)] def test_issue_21004(): x = symbols('x') f = x/sqrt(x**2+1) f_diff = f.diff(x) assert solve(f_diff, x) == [] def test_linear_system(): x, y, z, t, n = symbols('x, y, z, t, n') assert solve([x - 1, x - y, x - 2*y, y - 1], [x, y]) == [] assert solve([x - 1, x - y, x - 2*y, x - 1], [x, y]) == [] assert solve([x - 1, x - 1, x - y, x - 2*y], [x, y]) == [] assert solve([x + 5*y - 2, -3*x + 6*y - 15], x, y) == {x: -3, y: 1} M = Matrix([[0, 0, n*(n + 1), (n + 1)**2, 0], [n + 1, n + 1, -2*n - 1, -(n + 1), 0], [-1, 0, 1, 0, 0]]) assert solve_linear_system(M, x, y, z, t) == \ {x: t*(-n-1)/n, z: t*(-n-1)/n, y: 0} assert solve([x + y + z + t, -z - t], x, y, z, t) == {x: -y, z: -t} @XFAIL def test_linear_system_xfail(): # https://github.com/sympy/sympy/issues/6420 M = Matrix([[0, 15.0, 10.0, 700.0], [1, 1, 1, 100.0], [0, 10.0, 5.0, 200.0], [-5.0, 0, 0, 0 ]]) assert solve_linear_system(M, x, y, z) == {x: 0, y: -60.0, z: 160.0} def test_linear_system_function(): a = Function('a') assert solve([a(0, 0) + a(0, 1) + a(1, 0) + a(1, 1), -a(1, 0) - a(1, 1)], a(0, 0), a(0, 1), a(1, 0), a(1, 1)) == {a(1, 0): -a(1, 1), a(0, 0): -a(0, 1)} def test_linear_system_symbols_doesnt_hang_1(): def _mk_eqs(wy): # Equations for fitting a wy*2 - 1 degree polynomial between two points, # at end points derivatives are known up to order: wy - 1 order = 2*wy - 1 x, x0, x1 = symbols('x, x0, x1', real=True) y0s = symbols('y0_:{}'.format(wy), real=True) y1s = symbols('y1_:{}'.format(wy), real=True) c = symbols('c_:{}'.format(order+1), real=True) expr = sum([coeff*x**o for o, coeff in enumerate(c)]) eqs = [] for i in range(wy): eqs.append(expr.diff(x, i).subs({x: x0}) - y0s[i]) eqs.append(expr.diff(x, i).subs({x: x1}) - y1s[i]) return eqs, c # # The purpose of this test is just to see that these calls don't hang. The # expressions returned are complicated so are not included here. Testing # their correctness takes longer than solving the system. # for n in range(1, 7+1): eqs, c = _mk_eqs(n) solve(eqs, c) def test_linear_system_symbols_doesnt_hang_2(): M = Matrix([ [66, 24, 39, 50, 88, 40, 37, 96, 16, 65, 31, 11, 37, 72, 16, 19, 55, 37, 28, 76], [10, 93, 34, 98, 59, 44, 67, 74, 74, 94, 71, 61, 60, 23, 6, 2, 57, 8, 29, 78], [19, 91, 57, 13, 64, 65, 24, 53, 77, 34, 85, 58, 87, 39, 39, 7, 36, 67, 91, 3], [74, 70, 15, 53, 68, 43, 86, 83, 81, 72, 25, 46, 67, 17, 59, 25, 78, 39, 63, 6], [69, 40, 67, 21, 67, 40, 17, 13, 93, 44, 46, 89, 62, 31, 30, 38, 18, 20, 12, 81], [50, 22, 74, 76, 34, 45, 19, 76, 28, 28, 11, 99, 97, 82, 8, 46, 99, 57, 68, 35], [58, 18, 45, 88, 10, 64, 9, 34, 90, 82, 17, 41, 43, 81, 45, 83, 22, 88, 24, 39], [42, 21, 70, 68, 6, 33, 64, 81, 83, 15, 86, 75, 86, 17, 77, 34, 62, 72, 20, 24], [ 7, 8, 2, 72, 71, 52, 96, 5, 32, 51, 31, 36, 79, 88, 25, 77, 29, 26, 33, 13], [19, 31, 30, 85, 81, 39, 63, 28, 19, 12, 16, 49, 37, 66, 38, 13, 3, 71, 61, 51], [29, 82, 80, 49, 26, 85, 1, 37, 2, 74, 54, 82, 26, 47, 54, 9, 35, 0, 99, 40], [15, 49, 82, 91, 93, 57, 45, 25, 45, 97, 15, 98, 48, 52, 66, 24, 62, 54, 97, 37], [62, 23, 73, 53, 52, 86, 28, 38, 0, 74, 92, 38, 97, 70, 71, 29, 26, 90, 67, 45], [ 2, 32, 23, 24, 71, 37, 25, 71, 5, 41, 97, 65, 93, 13, 65, 45, 25, 88, 69, 50], [40, 56, 1, 29, 79, 98, 79, 62, 37, 28, 45, 47, 3, 1, 32, 74, 98, 35, 84, 32], [33, 15, 87, 79, 65, 9, 14, 63, 24, 19, 46, 28, 74, 20, 29, 96, 84, 91, 93, 1], [97, 18, 12, 52, 1, 2, 50, 14, 52, 76, 19, 82, 41, 73, 51, 79, 13, 3, 82, 96], [40, 28, 52, 10, 10, 71, 56, 78, 82, 5, 29, 48, 1, 26, 16, 18, 50, 76, 86, 52], [38, 89, 83, 43, 29, 52, 90, 77, 57, 0, 67, 20, 81, 88, 48, 96, 88, 58, 14, 3]]) syms = x0,x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17,x18 = symbols('x:19') sol = { x0: -S(1967374186044955317099186851240896179)/3166636564687820453598895768302256588, x1: -S(84268280268757263347292368432053826)/791659141171955113399723942075564147, x2: -S(229962957341664730974463872411844965)/1583318282343910226799447884151128294, x3: S(990156781744251750886760432229180537)/6333273129375640907197791536604513176, x4: -S(2169830351210066092046760299593096265)/18999819388126922721593374609813539528, x5: S(4680868883477577389628494526618745355)/9499909694063461360796687304906769764, x6: -S(1590820774344371990683178396480879213)/3166636564687820453598895768302256588, x7: -S(54104723404825537735226491634383072)/339282489073695048599881689460956063, x8: S(3182076494196560075964847771774733847)/6333273129375640907197791536604513176, x9: -S(10870817431029210431989147852497539675)/18999819388126922721593374609813539528, x10: -S(13118019242576506476316318268573312603)/18999819388126922721593374609813539528, x11: -S(5173852969886775824855781403820641259)/4749954847031730680398343652453384882, x12: S(4261112042731942783763341580651820563)/4749954847031730680398343652453384882, x13: -S(821833082694661608993818117038209051)/6333273129375640907197791536604513176, x14: S(906881575107250690508618713632090559)/904753304196520129599684505229216168, x15: -S(732162528717458388995329317371283987)/6333273129375640907197791536604513176, x16: S(4524215476705983545537087360959896817)/9499909694063461360796687304906769764, x17: -S(3898571347562055611881270844646055217)/6333273129375640907197791536604513176, x18: S(7513502486176995632751685137907442269)/18999819388126922721593374609813539528 } eqs = list(M * Matrix(syms + (1,))) assert solve(eqs, syms) == sol y = Symbol('y') eqs = list(y * M * Matrix(syms + (1,))) assert solve(eqs, syms) == sol def test_linear_systemLU(): n = Symbol('n') M = Matrix([[1, 2, 0, 1], [1, 3, 2*n, 1], [4, -1, n**2, 1]]) assert solve_linear_system_LU(M, [x, y, z]) == {z: -3/(n**2 + 18*n), x: 1 - 12*n/(n**2 + 18*n), y: 6*n/(n**2 + 18*n)} # Note: multiple solutions exist for some of these equations, so the tests # should be expected to break if the implementation of the solver changes # in such a way that a different branch is chosen @slow def test_solve_transcendental(): from sympy.abc import a, b assert solve(exp(x) - 3, x) == [log(3)] assert set(solve((a*x + b)*(exp(x) - 3), x)) == {-b/a, log(3)} assert solve(cos(x) - y, x) == [-acos(y) + 2*pi, acos(y)] assert solve(2*cos(x) - y, x) == [-acos(y/2) + 2*pi, acos(y/2)] assert solve(Eq(cos(x), sin(x)), x) == [pi/4] assert set(solve(exp(x) + exp(-x) - y, x)) in [{ log(y/2 - sqrt(y**2 - 4)/2), log(y/2 + sqrt(y**2 - 4)/2), }, { log(y - sqrt(y**2 - 4)) - log(2), log(y + sqrt(y**2 - 4)) - log(2)}, { log(y/2 - sqrt((y - 2)*(y + 2))/2), log(y/2 + sqrt((y - 2)*(y + 2))/2)}] assert solve(exp(x) - 3, x) == [log(3)] assert solve(Eq(exp(x), 3), x) == [log(3)] assert solve(log(x) - 3, x) == [exp(3)] assert solve(sqrt(3*x) - 4, x) == [Rational(16, 3)] assert solve(3**(x + 2), x) == [] assert solve(3**(2 - x), x) == [] assert solve(x + 2**x, x) == [-LambertW(log(2))/log(2)] assert solve(2*x + 5 + log(3*x - 2), x) == \ [Rational(2, 3) + LambertW(2*exp(Rational(-19, 3))/3)/2] assert solve(3*x + log(4*x), x) == [LambertW(Rational(3, 4))/3] assert set(solve((2*x + 8)*(8 + exp(x)), x)) == {S(-4), log(8) + pi*I} eq = 2*exp(3*x + 4) - 3 ans = solve(eq, x) # this generated a failure in flatten assert len(ans) == 3 and all(eq.subs(x, a).n(chop=True) == 0 for a in ans) assert solve(2*log(3*x + 4) - 3, x) == [(exp(Rational(3, 2)) - 4)/3] assert solve(exp(x) + 1, x) == [pi*I] eq = 2*(3*x + 4)**5 - 6*7**(3*x + 9) result = solve(eq, x) x0 = -log(2401) x1 = 3**Rational(1, 5) x2 = log(7**(7*x1/20)) x3 = sqrt(2) x4 = sqrt(5) x5 = x3*sqrt(x4 - 5) x6 = x4 + 1 x7 = 1/(3*log(7)) x8 = -x4 x9 = x3*sqrt(x8 - 5) x10 = x8 + 1 ans = [x7*(x0 - 5*LambertW(x2*(-x5 + x6))), x7*(x0 - 5*LambertW(x2*(x5 + x6))), x7*(x0 - 5*LambertW(x2*(x10 - x9))), x7*(x0 - 5*LambertW(x2*(x10 + x9))), x7*(x0 - 5*LambertW(-log(7**(7*x1/5))))] assert result == ans, result # it works if expanded, too assert solve(eq.expand(), x) == result assert solve(z*cos(x) - y, x) == [-acos(y/z) + 2*pi, acos(y/z)] assert solve(z*cos(2*x) - y, x) == [-acos(y/z)/2 + pi, acos(y/z)/2] assert solve(z*cos(sin(x)) - y, x) == [ pi - asin(acos(y/z)), asin(acos(y/z) - 2*pi) + pi, -asin(acos(y/z) - 2*pi), asin(acos(y/z))] assert solve(z*cos(x), x) == [pi/2, pi*Rational(3, 2)] # issue 4508 assert solve(y - b*x/(a + x), x) in [[-a*y/(y - b)], [a*y/(b - y)]] assert solve(y - b*exp(a/x), x) == [a/log(y/b)] # issue 4507 assert solve(y - b/(1 + a*x), x) in [[(b - y)/(a*y)], [-((y - b)/(a*y))]] # issue 4506 assert solve(y - a*x**b, x) == [(y/a)**(1/b)] # issue 4505 assert solve(z**x - y, x) == [log(y)/log(z)] # issue 4504 assert solve(2**x - 10, x) == [1 + log(5)/log(2)] # issue 6744 assert solve(x*y) == [{x: 0}, {y: 0}] assert solve([x*y]) == [{x: 0}, {y: 0}] assert solve(x**y - 1) == [{x: 1}, {y: 0}] assert solve([x**y - 1]) == [{x: 1}, {y: 0}] assert solve(x*y*(x**2 - y**2)) == [{x: 0}, {x: -y}, {x: y}, {y: 0}] assert solve([x*y*(x**2 - y**2)]) == [{x: 0}, {x: -y}, {x: y}, {y: 0}] # issue 4739 assert solve(exp(log(5)*x) - 2**x, x) == [0] # issue 14791 assert solve(exp(log(5)*x) - exp(log(2)*x), x) == [0] f = Function('f') assert solve(y*f(log(5)*x) - y*f(log(2)*x), x) == [0] assert solve(f(x) - f(0), x) == [0] assert solve(f(x) - f(2 - x), x) == [1] raises(NotImplementedError, lambda: solve(f(x, y) - f(1, 2), x)) raises(NotImplementedError, lambda: solve(f(x, y) - f(2 - x, 2), x)) raises(ValueError, lambda: solve(f(x, y) - f(1 - x), x)) raises(ValueError, lambda: solve(f(x, y) - f(1), x)) # misc # make sure that the right variables is picked up in tsolve # shouldn't generate a GeneratorsNeeded error in _tsolve when the NaN is generated # for eq_down. Actual answers, as determined numerically are approx. +/- 0.83 raises(NotImplementedError, lambda: solve(sinh(x)*sinh(sinh(x)) + cosh(x)*cosh(sinh(x)) - 3)) # watch out for recursive loop in tsolve raises(NotImplementedError, lambda: solve((x + 2)**y*x - 3, x)) # issue 7245 assert solve(sin(sqrt(x))) == [0, pi**2] # issue 7602 a, b = symbols('a, b', real=True, negative=False) assert str(solve(Eq(a, 0.5 - cos(pi*b)/2), b)) == \ '[2.0 - 0.318309886183791*acos(1.0 - 2.0*a), 0.318309886183791*acos(1.0 - 2.0*a)]' # issue 15325 assert solve(y**(1/x) - z, x) == [log(y)/log(z)] def test_solve_for_functions_derivatives(): t = Symbol('t') x = Function('x')(t) y = Function('y')(t) a11, a12, a21, a22, b1, b2 = symbols('a11,a12,a21,a22,b1,b2') soln = solve([a11*x + a12*y - b1, a21*x + a22*y - b2], x, y) assert soln == { x: (a22*b1 - a12*b2)/(a11*a22 - a12*a21), y: (a11*b2 - a21*b1)/(a11*a22 - a12*a21), } assert solve(x - 1, x) == [1] assert solve(3*x - 2, x) == [Rational(2, 3)] soln = solve([a11*x.diff(t) + a12*y.diff(t) - b1, a21*x.diff(t) + a22*y.diff(t) - b2], x.diff(t), y.diff(t)) assert soln == { y.diff(t): (a11*b2 - a21*b1)/(a11*a22 - a12*a21), x.diff(t): (a22*b1 - a12*b2)/(a11*a22 - a12*a21) } assert solve(x.diff(t) - 1, x.diff(t)) == [1] assert solve(3*x.diff(t) - 2, x.diff(t)) == [Rational(2, 3)] eqns = {3*x - 1, 2*y - 4} assert solve(eqns, {x, y}) == { x: Rational(1, 3), y: 2 } x = Symbol('x') f = Function('f') F = x**2 + f(x)**2 - 4*x - 1 assert solve(F.diff(x), diff(f(x), x)) == [(-x + 2)/f(x)] # Mixed cased with a Symbol and a Function x = Symbol('x') y = Function('y')(t) soln = solve([a11*x + a12*y.diff(t) - b1, a21*x + a22*y.diff(t) - b2], x, y.diff(t)) assert soln == { y.diff(t): (a11*b2 - a21*b1)/(a11*a22 - a12*a21), x: (a22*b1 - a12*b2)/(a11*a22 - a12*a21) } # issue 13263 x = Symbol('x') f = Function('f') soln = solve([f(x).diff(x) + f(x).diff(x, 2) - 1, f(x).diff(x) - f(x).diff(x, 2)], f(x).diff(x), f(x).diff(x, 2)) assert soln == { f(x).diff(x, 2): 1/2, f(x).diff(x): 1/2 } soln = solve([f(x).diff(x, 2) + f(x).diff(x, 3) - 1, 1 - f(x).diff(x, 2) - f(x).diff(x, 3), 1 - f(x).diff(x,3)], f(x).diff(x, 2), f(x).diff(x, 3)) assert soln == { f(x).diff(x, 2): 0, f(x).diff(x, 3): 1 } def test_issue_3725(): f = Function('f') F = x**2 + f(x)**2 - 4*x - 1 e = F.diff(x) assert solve(e, f(x).diff(x)) in [[(2 - x)/f(x)], [-((x - 2)/f(x))]] def test_issue_3870(): a, b, c, d = symbols('a b c d') A = Matrix(2, 2, [a, b, c, d]) B = Matrix(2, 2, [0, 2, -3, 0]) C = Matrix(2, 2, [1, 2, 3, 4]) assert solve(A*B - C, [a, b, c, d]) == {a: 1, b: Rational(-1, 3), c: 2, d: -1} assert solve([A*B - C], [a, b, c, d]) == {a: 1, b: Rational(-1, 3), c: 2, d: -1} assert solve(Eq(A*B, C), [a, b, c, d]) == {a: 1, b: Rational(-1, 3), c: 2, d: -1} assert solve([A*B - B*A], [a, b, c, d]) == {a: d, b: Rational(-2, 3)*c} assert solve([A*C - C*A], [a, b, c, d]) == {a: d - c, b: Rational(2, 3)*c} assert solve([A*B - B*A, A*C - C*A], [a, b, c, d]) == {a: d, b: 0, c: 0} assert solve([Eq(A*B, B*A)], [a, b, c, d]) == {a: d, b: Rational(-2, 3)*c} assert solve([Eq(A*C, C*A)], [a, b, c, d]) == {a: d - c, b: Rational(2, 3)*c} assert solve([Eq(A*B, B*A), Eq(A*C, C*A)], [a, b, c, d]) == {a: d, b: 0, c: 0} def test_solve_linear(): w = Wild('w') assert solve_linear(x, x) == (0, 1) assert solve_linear(x, exclude=[x]) == (0, 1) assert solve_linear(x, symbols=[w]) == (0, 1) assert solve_linear(x, y - 2*x) in [(x, y/3), (y, 3*x)] assert solve_linear(x, y - 2*x, exclude=[x]) == (y, 3*x) assert solve_linear(3*x - y, 0) in [(x, y/3), (y, 3*x)] assert solve_linear(3*x - y, 0, [x]) == (x, y/3) assert solve_linear(3*x - y, 0, [y]) == (y, 3*x) assert solve_linear(x**2/y, 1) == (y, x**2) assert solve_linear(w, x) in [(w, x), (x, w)] assert solve_linear(cos(x)**2 + sin(x)**2 + 2 + y) == \ (y, -2 - cos(x)**2 - sin(x)**2) assert solve_linear(cos(x)**2 + sin(x)**2 + 2 + y, symbols=[x]) == (0, 1) assert solve_linear(Eq(x, 3)) == (x, 3) assert solve_linear(1/(1/x - 2)) == (0, 0) assert solve_linear((x + 1)*exp(-x), symbols=[x]) == (x, -1) assert solve_linear((x + 1)*exp(x), symbols=[x]) == ((x + 1)*exp(x), 1) assert solve_linear(x*exp(-x**2), symbols=[x]) == (x, 0) assert solve_linear(0**x - 1) == (0**x - 1, 1) assert solve_linear(1 + 1/(x - 1)) == (x, 0) eq = y*cos(x)**2 + y*sin(x)**2 - y # = y*(1 - 1) = 0 assert solve_linear(eq) == (0, 1) eq = cos(x)**2 + sin(x)**2 # = 1 assert solve_linear(eq) == (0, 1) raises(ValueError, lambda: solve_linear(Eq(x, 3), 3)) def test_solve_undetermined_coeffs(): assert solve_undetermined_coeffs(a*x**2 + b*x**2 + b*x + 2*c*x + c + 1, [a, b, c], x) == \ {a: -2, b: 2, c: -1} # Test that rational functions work assert solve_undetermined_coeffs(a/x + b/(x + 1) - (2*x + 1)/(x**2 + x), [a, b], x) == \ {a: 1, b: 1} # Test cancellation in rational functions assert solve_undetermined_coeffs(((c + 1)*a*x**2 + (c + 1)*b*x**2 + (c + 1)*b*x + (c + 1)*2*c*x + (c + 1)**2)/(c + 1), [a, b, c], x) == \ {a: -2, b: 2, c: -1} def test_solve_inequalities(): x = Symbol('x') sol = And(S.Zero < x, x < oo) assert solve(x + 1 > 1) == sol assert solve([x + 1 > 1]) == sol assert solve([x + 1 > 1], x) == sol assert solve([x + 1 > 1], [x]) == sol system = [Lt(x**2 - 2, 0), Gt(x**2 - 1, 0)] assert solve(system) == \ And(Or(And(Lt(-sqrt(2), x), Lt(x, -1)), And(Lt(1, x), Lt(x, sqrt(2)))), Eq(0, 0)) x = Symbol('x', real=True) system = [Lt(x**2 - 2, 0), Gt(x**2 - 1, 0)] assert solve(system) == \ Or(And(Lt(-sqrt(2), x), Lt(x, -1)), And(Lt(1, x), Lt(x, sqrt(2)))) # issues 6627, 3448 assert solve((x - 3)/(x - 2) < 0, x) == And(Lt(2, x), Lt(x, 3)) assert solve(x/(x + 1) > 1, x) == And(Lt(-oo, x), Lt(x, -1)) assert solve(sin(x) > S.Half) == And(pi/6 < x, x < pi*Rational(5, 6)) assert solve(Eq(False, x < 1)) == (S.One <= x) & (x < oo) assert solve(Eq(True, x < 1)) == (-oo < x) & (x < 1) assert solve(Eq(x < 1, False)) == (S.One <= x) & (x < oo) assert solve(Eq(x < 1, True)) == (-oo < x) & (x < 1) assert solve(Eq(False, x)) == False assert solve(Eq(0, x)) == [0] assert solve(Eq(True, x)) == True assert solve(Eq(1, x)) == [1] assert solve(Eq(False, ~x)) == True assert solve(Eq(True, ~x)) == False assert solve(Ne(True, x)) == False assert solve(Ne(1, x)) == (x > -oo) & (x < oo) & Ne(x, 1) def test_issue_4793(): assert solve(1/x) == [] assert solve(x*(1 - 5/x)) == [5] assert solve(x + sqrt(x) - 2) == [1] assert solve(-(1 + x)/(2 + x)**2 + 1/(2 + x)) == [] assert solve(-x**2 - 2*x + (x + 1)**2 - 1) == [] assert solve((x/(x + 1) + 3)**(-2)) == [] assert solve(x/sqrt(x**2 + 1), x) == [0] assert solve(exp(x) - y, x) == [log(y)] assert solve(exp(x)) == [] assert solve(x**2 + x + sin(y)**2 + cos(y)**2 - 1, x) in [[0, -1], [-1, 0]] eq = 4*3**(5*x + 2) - 7 ans = solve(eq, x) assert len(ans) == 5 and all(eq.subs(x, a).n(chop=True) == 0 for a in ans) assert solve(log(x**2) - y**2/exp(x), x, y, set=True) == ( [x, y], {(x, sqrt(exp(x) * log(x ** 2))), (x, -sqrt(exp(x) * log(x ** 2)))}) assert solve(x**2*z**2 - z**2*y**2) == [{x: -y}, {x: y}, {z: 0}] assert solve((x - 1)/(1 + 1/(x - 1))) == [] assert solve(x**(y*z) - x, x) == [1] raises(NotImplementedError, lambda: solve(log(x) - exp(x), x)) raises(NotImplementedError, lambda: solve(2**x - exp(x) - 3)) def test_PR1964(): # issue 5171 assert solve(sqrt(x)) == solve(sqrt(x**3)) == [0] assert solve(sqrt(x - 1)) == [1] # issue 4462 a = Symbol('a') assert solve(-3*a/sqrt(x), x) == [] # issue 4486 assert solve(2*x/(x + 2) - 1, x) == [2] # issue 4496 assert set(solve((x**2/(7 - x)).diff(x))) == {S.Zero, S(14)} # issue 4695 f = Function('f') assert solve((3 - 5*x/f(x))*f(x), f(x)) == [x*Rational(5, 3)] # issue 4497 assert solve(1/root(5 + x, 5) - 9, x) == [Rational(-295244, 59049)] assert solve(sqrt(x) + sqrt(sqrt(x)) - 4) == [(Rational(-1, 2) + sqrt(17)/2)**4] assert set(solve(Poly(sqrt(exp(x)) + sqrt(exp(-x)) - 4))) in \ [ {log((-sqrt(3) + 2)**2), log((sqrt(3) + 2)**2)}, {2*log(-sqrt(3) + 2), 2*log(sqrt(3) + 2)}, {log(-4*sqrt(3) + 7), log(4*sqrt(3) + 7)}, ] assert set(solve(Poly(exp(x) + exp(-x) - 4))) == \ {log(-sqrt(3) + 2), log(sqrt(3) + 2)} assert set(solve(x**y + x**(2*y) - 1, x)) == \ {(Rational(-1, 2) + sqrt(5)/2)**(1/y), (Rational(-1, 2) - sqrt(5)/2)**(1/y)} assert solve(exp(x/y)*exp(-z/y) - 2, y) == [(x - z)/log(2)] assert solve( x**z*y**z - 2, z) in [[log(2)/(log(x) + log(y))], [log(2)/(log(x*y))]] # if you do inversion too soon then multiple roots (as for the following) # will be missed, e.g. if exp(3*x) = exp(3) -> 3*x = 3 E = S.Exp1 assert solve(exp(3*x) - exp(3), x) in [ [1, log(E*(Rational(-1, 2) - sqrt(3)*I/2)), log(E*(Rational(-1, 2) + sqrt(3)*I/2))], [1, log(-E/2 - sqrt(3)*E*I/2), log(-E/2 + sqrt(3)*E*I/2)], ] # coverage test p = Symbol('p', positive=True) assert solve((1/p + 1)**(p + 1)) == [] def test_issue_5197(): x = Symbol('x', real=True) assert solve(x**2 + 1, x) == [] n = Symbol('n', integer=True, positive=True) assert solve((n - 1)*(n + 2)*(2*n - 1), n) == [1] x = Symbol('x', positive=True) y = Symbol('y') assert solve([x + 5*y - 2, -3*x + 6*y - 15], x, y) == [] # not {x: -3, y: 1} b/c x is positive # The solution following should not contain (-sqrt(2), sqrt(2)) assert solve((x + y)*n - y**2 + 2, x, y) == [(sqrt(2), -sqrt(2))] y = Symbol('y', positive=True) # The solution following should not contain {y: -x*exp(x/2)} assert solve(x**2 - y**2/exp(x), y, x, dict=True) == [{y: x*exp(x/2)}] x, y, z = symbols('x y z', positive=True) assert solve(z**2*x**2 - z**2*y**2/exp(x), y, x, z, dict=True) == [{y: x*exp(x/2)}] def test_checking(): assert set( solve(x*(x - y/x), x, check=False)) == {sqrt(y), S.Zero, -sqrt(y)} assert set(solve(x*(x - y/x), x, check=True)) == {sqrt(y), -sqrt(y)} # {x: 0, y: 4} sets denominator to 0 in the following so system should return None assert solve((1/(1/x + 2), 1/(y - 3) - 1)) == [] # 0 sets denominator of 1/x to zero so None is returned assert solve(1/(1/x + 2)) == [] def test_issue_4671_4463_4467(): assert solve(sqrt(x**2 - 1) - 2) in ([sqrt(5), -sqrt(5)], [-sqrt(5), sqrt(5)]) assert solve((2**exp(y**2/x) + 2)/(x**2 + 15), y) == [ -sqrt(x*log(1 + I*pi/log(2))), sqrt(x*log(1 + I*pi/log(2)))] C1, C2 = symbols('C1 C2') f = Function('f') assert solve(C1 + C2/x**2 - exp(-f(x)), f(x)) == [log(x**2/(C1*x**2 + C2))] a = Symbol('a') E = S.Exp1 assert solve(1 - log(a + 4*x**2), x) in ( [-sqrt(-a + E)/2, sqrt(-a + E)/2], [sqrt(-a + E)/2, -sqrt(-a + E)/2] ) assert solve(log(a**(-3) - x**2)/a, x) in ( [-sqrt(-1 + a**(-3)), sqrt(-1 + a**(-3))], [sqrt(-1 + a**(-3)), -sqrt(-1 + a**(-3))],) assert solve(1 - log(a + 4*x**2), x) in ( [-sqrt(-a + E)/2, sqrt(-a + E)/2], [sqrt(-a + E)/2, -sqrt(-a + E)/2],) assert solve((a**2 + 1)*(sin(a*x) + cos(a*x)), x) == [-pi/(4*a)] assert solve(3 - (sinh(a*x) + cosh(a*x)), x) == [log(3)/a] assert set(solve(3 - (sinh(a*x) + cosh(a*x)**2), x)) == \ {log(-2 + sqrt(5))/a, log(-sqrt(2) + 1)/a, log(-sqrt(5) - 2)/a, log(1 + sqrt(2))/a} assert solve(atan(x) - 1) == [tan(1)] def test_issue_5132(): r, t = symbols('r,t') assert set(solve([r - x**2 - y**2, tan(t) - y/x], [x, y])) == \ {( -sqrt(r*cos(t)**2), -1*sqrt(r*cos(t)**2)*tan(t)), (sqrt(r*cos(t)**2), sqrt(r*cos(t)**2)*tan(t))} assert solve([exp(x) - sin(y), 1/y - 3], [x, y]) == \ [(log(sin(Rational(1, 3))), Rational(1, 3))] assert solve([exp(x) - sin(y), 1/exp(y) - 3], [x, y]) == \ [(log(-sin(log(3))), -log(3))] assert set(solve([exp(x) - sin(y), y**2 - 4], [x, y])) == \ {(log(-sin(2)), -S(2)), (log(sin(2)), S(2))} eqs = [exp(x)**2 - sin(y) + z**2, 1/exp(y) - 3] assert solve(eqs, set=True) == \ ([y, z], { (-log(3), sqrt(-exp(2*x) - sin(log(3)))), (-log(3), -sqrt(-exp(2*x) - sin(log(3))))}) assert solve(eqs, x, z, set=True) == ( [x, z], {(x, sqrt(-exp(2*x) + sin(y))), (x, -sqrt(-exp(2*x) + sin(y)))}) assert set(solve(eqs, x, y)) == \ { (log(-sqrt(-z**2 - sin(log(3)))), -log(3)), (log(-z**2 - sin(log(3)))/2, -log(3))} assert set(solve(eqs, y, z)) == \ { (-log(3), -sqrt(-exp(2*x) - sin(log(3)))), (-log(3), sqrt(-exp(2*x) - sin(log(3))))} eqs = [exp(x)**2 - sin(y) + z, 1/exp(y) - 3] assert solve(eqs, set=True) == ([y, z], { (-log(3), -exp(2*x) - sin(log(3)))}) assert solve(eqs, x, z, set=True) == ( [x, z], {(x, -exp(2*x) + sin(y))}) assert set(solve(eqs, x, y)) == { (log(-sqrt(-z - sin(log(3)))), -log(3)), (log(-z - sin(log(3)))/2, -log(3))} assert solve(eqs, z, y) == \ [(-exp(2*x) - sin(log(3)), -log(3))] assert solve((sqrt(x**2 + y**2) - sqrt(10), x + y - 4), set=True) == ( [x, y], {(S.One, S(3)), (S(3), S.One)}) assert set(solve((sqrt(x**2 + y**2) - sqrt(10), x + y - 4), x, y)) == \ {(S.One, S(3)), (S(3), S.One)} def test_issue_5335(): lam, a0, conc = symbols('lam a0 conc') a = 0.005 b = 0.743436700916726 eqs = [lam + 2*y - a0*(1 - x/2)*x - a*x/2*x, a0*(1 - x/2)*x - 1*y - b*y, x + y - conc] sym = [x, y, a0] # there are 4 solutions obtained manually but only two are valid assert len(solve(eqs, sym, manual=True, minimal=True)) == 2 assert len(solve(eqs, sym)) == 2 # cf below with rational=False @SKIP("Hangs") def _test_issue_5335_float(): # gives ZeroDivisionError: polynomial division lam, a0, conc = symbols('lam a0 conc') a = 0.005 b = 0.743436700916726 eqs = [lam + 2*y - a0*(1 - x/2)*x - a*x/2*x, a0*(1 - x/2)*x - 1*y - b*y, x + y - conc] sym = [x, y, a0] assert len(solve(eqs, sym, rational=False)) == 2 def test_issue_5767(): assert set(solve([x**2 + y + 4], [x])) == \ {(-sqrt(-y - 4),), (sqrt(-y - 4),)} def test_polysys(): assert set(solve([x**2 + 2/y - 2, x + y - 3], [x, y])) == \ {(S.One, S(2)), (1 + sqrt(5), 2 - sqrt(5)), (1 - sqrt(5), 2 + sqrt(5))} assert solve([x**2 + y - 2, x**2 + y]) == [] # the ordering should be whatever the user requested assert solve([x**2 + y - 3, x - y - 4], (x, y)) != solve([x**2 + y - 3, x - y - 4], (y, x)) @slow def test_unrad1(): raises(NotImplementedError, lambda: unrad(sqrt(x) + sqrt(x + 1) + sqrt(1 - sqrt(x)) + 3)) raises(NotImplementedError, lambda: unrad(sqrt(x) + (x + 1)**Rational(1, 3) + 2*sqrt(y))) s = symbols('s', cls=Dummy) # checkers to deal with possibility of answer coming # back with a sign change (cf issue 5203) def check(rv, ans): assert bool(rv[1]) == bool(ans[1]) if ans[1]: return s_check(rv, ans) e = rv[0].expand() a = ans[0].expand() return e in [a, -a] and rv[1] == ans[1] def s_check(rv, ans): # get the dummy rv = list(rv) d = rv[0].atoms(Dummy) reps = list(zip(d, [s]*len(d))) # replace s with this dummy rv = (rv[0].subs(reps).expand(), [rv[1][0].subs(reps), rv[1][1].subs(reps)]) ans = (ans[0].subs(reps).expand(), [ans[1][0].subs(reps), ans[1][1].subs(reps)]) return str(rv[0]) in [str(ans[0]), str(-ans[0])] and \ str(rv[1]) == str(ans[1]) assert unrad(1) is None assert check(unrad(sqrt(x)), (x, [])) assert check(unrad(sqrt(x) + 1), (x - 1, [])) assert check(unrad(sqrt(x) + root(x, 3) + 2), (s**3 + s**2 + 2, [s, s**6 - x])) assert check(unrad(sqrt(x)*root(x, 3) + 2), (x**5 - 64, [])) assert check(unrad(sqrt(x) + (x + 1)**Rational(1, 3)), (x**3 - (x + 1)**2, [])) assert check(unrad(sqrt(x) + sqrt(x + 1) + sqrt(2*x)), (-2*sqrt(2)*x - 2*x + 1, [])) assert check(unrad(sqrt(x) + sqrt(x + 1) + 2), (16*x - 9, [])) assert check(unrad(sqrt(x) + sqrt(x + 1) + sqrt(1 - x)), (5*x**2 - 4*x, [])) assert check(unrad(a*sqrt(x) + b*sqrt(x) + c*sqrt(y) + d*sqrt(y)), ((a*sqrt(x) + b*sqrt(x))**2 - (c*sqrt(y) + d*sqrt(y))**2, [])) assert check(unrad(sqrt(x) + sqrt(1 - x)), (2*x - 1, [])) assert check(unrad(sqrt(x) + sqrt(1 - x) - 3), (x**2 - x + 16, [])) assert check(unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x)), (5*x**2 - 2*x + 1, [])) assert unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x) - 3) in [ (25*x**4 + 376*x**3 + 1256*x**2 - 2272*x + 784, []), (25*x**8 - 476*x**6 + 2534*x**4 - 1468*x**2 + 169, [])] assert unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x) - sqrt(1 - 2*x)) == \ (41*x**4 + 40*x**3 + 232*x**2 - 160*x + 16, []) # orig root at 0.487 assert check(unrad(sqrt(x) + sqrt(x + 1)), (S.One, [])) eq = sqrt(x) + sqrt(x + 1) + sqrt(1 - sqrt(x)) assert check(unrad(eq), (16*x**2 - 9*x, [])) assert set(solve(eq, check=False)) == {S.Zero, Rational(9, 16)} assert solve(eq) == [] # but this one really does have those solutions assert set(solve(sqrt(x) - sqrt(x + 1) + sqrt(1 - sqrt(x)))) == \ {S.Zero, Rational(9, 16)} assert check(unrad(sqrt(x) + root(x + 1, 3) + 2*sqrt(y), y), (S('2*sqrt(x)*(x + 1)**(1/3) + x - 4*y + (x + 1)**(2/3)'), [])) assert check(unrad(sqrt(x/(1 - x)) + (x + 1)**Rational(1, 3)), (x**5 - x**4 - x**3 + 2*x**2 + x - 1, [])) assert check(unrad(sqrt(x/(1 - x)) + 2*sqrt(y), y), (4*x*y + x - 4*y, [])) assert check(unrad(sqrt(x)*sqrt(1 - x) + 2, x), (x**2 - x + 4, [])) # http://tutorial.math.lamar.edu/ # Classes/Alg/SolveRadicalEqns.aspx#Solve_Rad_Ex2_a assert solve(Eq(x, sqrt(x + 6))) == [3] assert solve(Eq(x + sqrt(x - 4), 4)) == [4] assert solve(Eq(1, x + sqrt(2*x - 3))) == [] assert set(solve(Eq(sqrt(5*x + 6) - 2, x))) == {-S.One, S(2)} assert set(solve(Eq(sqrt(2*x - 1) - sqrt(x - 4), 2))) == {S(5), S(13)} assert solve(Eq(sqrt(x + 7) + 2, sqrt(3 - x))) == [-6] # http://www.purplemath.com/modules/solverad.htm assert solve((2*x - 5)**Rational(1, 3) - 3) == [16] assert set(solve(x + 1 - root(x**4 + 4*x**3 - x, 4))) == \ {Rational(-1, 2), Rational(-1, 3)} assert set(solve(sqrt(2*x**2 - 7) - (3 - x))) == {-S(8), S(2)} assert solve(sqrt(2*x + 9) - sqrt(x + 1) - sqrt(x + 4)) == [0] assert solve(sqrt(x + 4) + sqrt(2*x - 1) - 3*sqrt(x - 1)) == [5] assert solve(sqrt(x)*sqrt(x - 7) - 12) == [16] assert solve(sqrt(x - 3) + sqrt(x) - 3) == [4] assert solve(sqrt(9*x**2 + 4) - (3*x + 2)) == [0] assert solve(sqrt(x) - 2 - 5) == [49] assert solve(sqrt(x - 3) - sqrt(x) - 3) == [] assert solve(sqrt(x - 1) - x + 7) == [10] assert solve(sqrt(x - 2) - 5) == [27] assert solve(sqrt(17*x - sqrt(x**2 - 5)) - 7) == [3] assert solve(sqrt(x) - sqrt(x - 1) + sqrt(sqrt(x))) == [] # don't posify the expression in unrad and do use _mexpand z = sqrt(2*x + 1)/sqrt(x) - sqrt(2 + 1/x) p = posify(z)[0] assert solve(p) == [] assert solve(z) == [] assert solve(z + 6*I) == [Rational(-1, 11)] assert solve(p + 6*I) == [] # issue 8622 assert unrad(root(x + 1, 5) - root(x, 3)) == ( -(x**5 - x**3 - 3*x**2 - 3*x - 1), []) # issue #8679 assert check(unrad(x + root(x, 3) + root(x, 3)**2 + sqrt(y), x), (s**3 + s**2 + s + sqrt(y), [s, s**3 - x])) # for coverage assert check(unrad(sqrt(x) + root(x, 3) + y), (s**3 + s**2 + y, [s, s**6 - x])) assert solve(sqrt(x) + root(x, 3) - 2) == [1] raises(NotImplementedError, lambda: solve(sqrt(x) + root(x, 3) + root(x + 1, 5) - 2)) # fails through a different code path raises(NotImplementedError, lambda: solve(-sqrt(2) + cosh(x)/x)) # unrad some assert solve(sqrt(x + root(x, 3))+root(x - y, 5), y) == [ x + (x**Rational(1, 3) + x)**Rational(5, 2)] assert check(unrad(sqrt(x) - root(x + 1, 3)*sqrt(x + 2) + 2), (s**10 + 8*s**8 + 24*s**6 - 12*s**5 - 22*s**4 - 160*s**3 - 212*s**2 - 192*s - 56, [s, s**2 - x])) e = root(x + 1, 3) + root(x, 3) assert unrad(e) == (2*x + 1, []) eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6*sqrt(5)/5) assert check(unrad(eq), (15625*x**4 + 173000*x**3 + 355600*x**2 - 817920*x + 331776, [])) assert check(unrad(root(x, 4) + root(x, 4)**3 - 1), (s**3 + s - 1, [s, s**4 - x])) assert check(unrad(root(x, 2) + root(x, 2)**3 - 1), (x**3 + 2*x**2 + x - 1, [])) assert unrad(x**0.5) is None assert check(unrad(t + root(x + y, 5) + root(x + y, 5)**3), (s**3 + s + t, [s, s**5 - x - y])) assert check(unrad(x + root(x + y, 5) + root(x + y, 5)**3, y), (s**3 + s + x, [s, s**5 - x - y])) assert check(unrad(x + root(x + y, 5) + root(x + y, 5)**3, x), (s**5 + s**3 + s - y, [s, s**5 - x - y])) assert check(unrad(root(x - 1, 3) + root(x + 1, 5) + root(2, 5)), (s**5 + 5*2**Rational(1, 5)*s**4 + s**3 + 10*2**Rational(2, 5)*s**3 + 10*2**Rational(3, 5)*s**2 + 5*2**Rational(4, 5)*s + 4, [s, s**3 - x + 1])) raises(NotImplementedError, lambda: unrad((root(x, 2) + root(x, 3) + root(x, 4)).subs(x, x**5 - x + 1))) # the simplify flag should be reset to False for unrad results; # if it's not then this next test will take a long time assert solve(root(x, 3) + root(x, 5) - 2) == [1] eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6*sqrt(5)/5) assert check(unrad(eq), ((5*x - 4)*(3125*x**3 + 37100*x**2 + 100800*x - 82944), [])) ans = S(''' [4/5, -1484/375 + 172564/(140625*(114*sqrt(12657)/78125 + 12459439/52734375)**(1/3)) + 4*(114*sqrt(12657)/78125 + 12459439/52734375)**(1/3)]''') assert solve(eq) == ans # duplicate radical handling assert check(unrad(sqrt(x + root(x + 1, 3)) - root(x + 1, 3) - 2), (s**3 - s**2 - 3*s - 5, [s, s**3 - x - 1])) # cov post-processing e = root(x**2 + 1, 3) - root(x**2 - 1, 5) - 2 assert check(unrad(e), (s**5 - 10*s**4 + 39*s**3 - 80*s**2 + 80*s - 30, [s, s**3 - x**2 - 1])) e = sqrt(x + root(x + 1, 2)) - root(x + 1, 3) - 2 assert check(unrad(e), (s**6 - 2*s**5 - 7*s**4 - 3*s**3 + 26*s**2 + 40*s + 25, [s, s**3 - x - 1])) assert check(unrad(e, _reverse=True), (s**6 - 14*s**5 + 73*s**4 - 187*s**3 + 276*s**2 - 228*s + 89, [s, s**2 - x - sqrt(x + 1)])) # this one needs r0, r1 reversal to work assert check(unrad(sqrt(x + sqrt(root(x, 3) - 1)) - root(x, 6) - 2), (s**12 - 2*s**8 - 8*s**7 - 8*s**6 + s**4 + 8*s**3 + 23*s**2 + 32*s + 17, [s, s**6 - x])) # why does this pass assert unrad(root(cosh(x), 3)/x*root(x + 1, 5) - 1) == ( -(x**15 - x**3*cosh(x)**5 - 3*x**2*cosh(x)**5 - 3*x*cosh(x)**5 - cosh(x)**5), []) # and this fail? #assert unrad(sqrt(cosh(x)/x) + root(x + 1, 3)*sqrt(x) - 1) == ( # -s**6 + 6*s**5 - 15*s**4 + 20*s**3 - 15*s**2 + 6*s + x**5 + # 2*x**4 + x**3 - 1, [s, s**2 - cosh(x)/x]) # watch for symbols in exponents assert unrad(S('(x+y)**(2*y/3) + (x+y)**(1/3) + 1')) is None assert check(unrad(S('(x+y)**(2*y/3) + (x+y)**(1/3) + 1'), x), (s**(2*y) + s + 1, [s, s**3 - x - y])) # should _Q be so lenient? assert unrad(x**(S.Half/y) + y, x) == (x**(1/y) - y**2, []) # This tests two things: that if full unrad is attempted and fails # the solution should still be found; also it tests that the use of # composite assert len(solve(sqrt(y)*x + x**3 - 1, x)) == 3 assert len(solve(-512*y**3 + 1344*(x + 2)**Rational(1, 3)*y**2 - 1176*(x + 2)**Rational(2, 3)*y - 169*x + 686, y, _unrad=False)) == 3 # watch out for when the cov doesn't involve the symbol of interest eq = S('-x + (7*y/8 - (27*x/2 + 27*sqrt(x**2)/2)**(1/3)/3)**3 - 1') assert solve(eq, y) == [ 2**(S(2)/3)*(27*x + 27*sqrt(x**2))**(S(1)/3)*S(4)/21 + (512*x/343 + S(512)/343)**(S(1)/3)*(-S(1)/2 - sqrt(3)*I/2), 2**(S(2)/3)*(27*x + 27*sqrt(x**2))**(S(1)/3)*S(4)/21 + (512*x/343 + S(512)/343)**(S(1)/3)*(-S(1)/2 + sqrt(3)*I/2), 2**(S(2)/3)*(27*x + 27*sqrt(x**2))**(S(1)/3)*S(4)/21 + (512*x/343 + S(512)/343)**(S(1)/3)] eq = root(x + 1, 3) - (root(x, 3) + root(x, 5)) assert check(unrad(eq), (3*s**13 + 3*s**11 + s**9 - 1, [s, s**15 - x])) assert check(unrad(eq - 2), (3*s**13 + 3*s**11 + 6*s**10 + s**9 + 12*s**8 + 6*s**6 + 12*s**5 + 12*s**3 + 7, [s, s**15 - x])) assert check(unrad(root(x, 3) - root(x + 1, 4)/2 + root(x + 2, 3)), (s*(4096*s**9 + 960*s**8 + 48*s**7 - s**6 - 1728), [s, s**4 - x - 1])) # orig expr has two real roots: -1, -.389 assert check(unrad(root(x, 3) + root(x + 1, 4) - root(x + 2, 3)/2), (343*s**13 + 2904*s**12 + 1344*s**11 + 512*s**10 - 1323*s**9 - 3024*s**8 - 1728*s**7 + 1701*s**5 + 216*s**4 - 729*s, [s, s**4 - x - 1])) # orig expr has one real root: -0.048 assert check(unrad(root(x, 3)/2 - root(x + 1, 4) + root(x + 2, 3)), (729*s**13 - 216*s**12 + 1728*s**11 - 512*s**10 + 1701*s**9 - 3024*s**8 + 1344*s**7 + 1323*s**5 - 2904*s**4 + 343*s, [s, s**4 - x - 1])) # orig expr has 2 real roots: -0.91, -0.15 assert check(unrad(root(x, 3)/2 - root(x + 1, 4) + root(x + 2, 3) - 2), (729*s**13 + 1242*s**12 + 18496*s**10 + 129701*s**9 + 388602*s**8 + 453312*s**7 - 612864*s**6 - 3337173*s**5 - 6332418*s**4 - 7134912*s**3 - 5064768*s**2 - 2111913*s - 398034, [s, s**4 - x - 1])) # orig expr has 1 real root: 19.53 ans = solve(sqrt(x) + sqrt(x + 1) - sqrt(1 - x) - sqrt(2 + x)) assert len(ans) == 1 and NS(ans[0])[:4] == '0.73' # the fence optimization problem # https://github.com/sympy/sympy/issues/4793#issuecomment-36994519 F = Symbol('F') eq = F - (2*x + 2*y + sqrt(x**2 + y**2)) ans = F*Rational(2, 7) - sqrt(2)*F/14 X = solve(eq, x, check=False) for xi in reversed(X): # reverse since currently, ans is the 2nd one Y = solve((x*y).subs(x, xi).diff(y), y, simplify=False, check=False) if any((a - ans).expand().is_zero for a in Y): break else: assert None # no answer was found assert solve(sqrt(x + 1) + root(x, 3) - 2) == S(''' [(-11/(9*(47/54 + sqrt(93)/6)**(1/3)) + 1/3 + (47/54 + sqrt(93)/6)**(1/3))**3]''') assert solve(sqrt(sqrt(x + 1)) + x**Rational(1, 3) - 2) == S(''' [(-sqrt(-2*(-1/16 + sqrt(6913)/16)**(1/3) + 6/(-1/16 + sqrt(6913)/16)**(1/3) + 17/2 + 121/(4*sqrt(-6/(-1/16 + sqrt(6913)/16)**(1/3) + 2*(-1/16 + sqrt(6913)/16)**(1/3) + 17/4)))/2 + sqrt(-6/(-1/16 + sqrt(6913)/16)**(1/3) + 2*(-1/16 + sqrt(6913)/16)**(1/3) + 17/4)/2 + 9/4)**3]''') assert solve(sqrt(x) + root(sqrt(x) + 1, 3) - 2) == S(''' [(-(81/2 + 3*sqrt(741)/2)**(1/3)/3 + (81/2 + 3*sqrt(741)/2)**(-1/3) + 2)**2]''') eq = S(''' -x + (1/2 - sqrt(3)*I/2)*(3*x**3/2 - x*(3*x**2 - 34)/2 + sqrt((-3*x**3 + x*(3*x**2 - 34) + 90)**2/4 - 39304/27) - 45)**(1/3) + 34/(3*(1/2 - sqrt(3)*I/2)*(3*x**3/2 - x*(3*x**2 - 34)/2 + sqrt((-3*x**3 + x*(3*x**2 - 34) + 90)**2/4 - 39304/27) - 45)**(1/3))''') assert check(unrad(eq), (s*-(-s**6 + sqrt(3)*s**6*I - 153*2**Rational(2, 3)*3**Rational(1, 3)*s**4 + 51*12**Rational(1, 3)*s**4 - 102*2**Rational(2, 3)*3**Rational(5, 6)*s**4*I - 1620*s**3 + 1620*sqrt(3)*s**3*I + 13872*18**Rational(1, 3)*s**2 - 471648 + 471648*sqrt(3)*I), [s, s**3 - 306*x - sqrt(3)*sqrt(31212*x**2 - 165240*x + 61484) + 810])) assert solve(eq) == [] # not other code errors eq = root(x, 3) - root(y, 3) + root(x, 5) assert check(unrad(eq), (s**15 + 3*s**13 + 3*s**11 + s**9 - y, [s, s**15 - x])) eq = root(x, 3) + root(y, 3) + root(x*y, 4) assert check(unrad(eq), (s*y*(-s**12 - 3*s**11*y - 3*s**10*y**2 - s**9*y**3 - 3*s**8*y**2 + 21*s**7*y**3 - 3*s**6*y**4 - 3*s**4*y**4 - 3*s**3*y**5 - y**6), [s, s**4 - x*y])) raises(NotImplementedError, lambda: unrad(root(x, 3) + root(y, 3) + root(x*y, 5))) # Test unrad with an Equality eq = Eq(-x**(S(1)/5) + x**(S(1)/3), -3**(S(1)/3) - (-1)**(S(3)/5)*3**(S(1)/5)) assert check(unrad(eq), (-s**5 + s**3 - 3**(S(1)/3) - (-1)**(S(3)/5)*3**(S(1)/5), [s, s**15 - x])) # make sure buried radicals are exposed s = sqrt(x) - 1 assert unrad(s**2 - s**3) == (x**3 - 6*x**2 + 9*x - 4, []) # make sure numerators which are already polynomial are rejected assert unrad((x/(x + 1) + 3)**(-2), x) is None @slow def test_unrad_slow(): # this has roots with multiplicity > 1; there should be no # repeats in roots obtained, however eq = (sqrt(1 + sqrt(1 - 4*x**2)) - x*(1 + sqrt(1 + 2*sqrt(1 - 4*x**2)))) assert solve(eq) == [S.Half] @XFAIL def test_unrad_fail(): # this only works if we check real_root(eq.subs(x, Rational(1, 3))) # but checksol doesn't work like that assert solve(root(x**3 - 3*x**2, 3) + 1 - x) == [Rational(1, 3)] assert solve(root(x + 1, 3) + root(x**2 - 2, 5) + 1) == [ -1, -1 + CRootOf(x**5 + x**4 + 5*x**3 + 8*x**2 + 10*x + 5, 0)**3] def test_checksol(): x, y, r, t = symbols('x, y, r, t') eq = r - x**2 - y**2 dict_var_soln = {y: - sqrt(r) / sqrt(tan(t)**2 + 1), x: -sqrt(r)*tan(t)/sqrt(tan(t)**2 + 1)} assert checksol(eq, dict_var_soln) == True assert checksol(Eq(x, False), {x: False}) is True assert checksol(Ne(x, False), {x: False}) is False assert checksol(Eq(x < 1, True), {x: 0}) is True assert checksol(Eq(x < 1, True), {x: 1}) is False assert checksol(Eq(x < 1, False), {x: 1}) is True assert checksol(Eq(x < 1, False), {x: 0}) is False assert checksol(Eq(x + 1, x**2 + 1), {x: 1}) is True assert checksol([x - 1, x**2 - 1], x, 1) is True assert checksol([x - 1, x**2 - 2], x, 1) is False assert checksol(Poly(x**2 - 1), x, 1) is True raises(ValueError, lambda: checksol(x, 1)) raises(ValueError, lambda: checksol([], x, 1)) def test__invert(): assert _invert(x - 2) == (2, x) assert _invert(2) == (2, 0) assert _invert(exp(1/x) - 3, x) == (1/log(3), x) assert _invert(exp(1/x + a/x) - 3, x) == ((a + 1)/log(3), x) assert _invert(a, x) == (a, 0) def test_issue_4463(): assert solve(-a*x + 2*x*log(x), x) == [exp(a/2)] assert solve(x**x) == [] assert solve(x**x - 2) == [exp(LambertW(log(2)))] assert solve(((x - 3)*(x - 2))**((x - 3)*(x - 4))) == [2] @slow def test_issue_5114_solvers(): a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r = symbols('a:r') # there is no 'a' in the equation set but this is how the # problem was originally posed syms = a, b, c, f, h, k, n eqs = [b + r/d - c/d, c*(1/d + 1/e + 1/g) - f/g - r/d, f*(1/g + 1/i + 1/j) - c/g - h/i, h*(1/i + 1/l + 1/m) - f/i - k/m, k*(1/m + 1/o + 1/p) - h/m - n/p, n*(1/p + 1/q) - k/p] assert len(solve(eqs, syms, manual=True, check=False, simplify=False)) == 1 def test_issue_5849(): # # XXX: This system does not have a solution for most values of the # parameters. Generally solve returns the empty set for systems that are # generically inconsistent. # I1, I2, I3, I4, I5, I6 = symbols('I1:7') dI1, dI4, dQ2, dQ4, Q2, Q4 = symbols('dI1,dI4,dQ2,dQ4,Q2,Q4') e = ( I1 - I2 - I3, I3 - I4 - I5, I4 + I5 - I6, -I1 + I2 + I6, -2*I1 - 2*I3 - 2*I5 - 3*I6 - dI1/2 + 12, -I4 + dQ4, -I2 + dQ2, 2*I3 + 2*I5 + 3*I6 - Q2, I4 - 2*I5 + 2*Q4 + dI4 ) ans = [{ I1: I2 + I3, dI1: -4*I2 - 8*I3 - 4*I5 - 6*I6 + 24, I4: I3 - I5, dQ4: I3 - I5, Q4: -I3/2 + 3*I5/2 - dI4/2, dQ2: I2, Q2: 2*I3 + 2*I5 + 3*I6}] v = I1, I4, Q2, Q4, dI1, dI4, dQ2, dQ4 assert solve(e, *v, manual=True, check=False, dict=True) == ans assert solve(e, *v, manual=True, check=False) == ans[0] assert solve(e, *v, manual=True) == [] assert solve(e, *v) == [] # the matrix solver (tested below) doesn't like this because it produces # a zero row in the matrix. Is this related to issue 4551? assert [ei.subs( ans[0]) for ei in e] == [0, 0, I3 - I6, -I3 + I6, 0, 0, 0, 0, 0] def test_issue_5849_matrix(): '''Same as test_issue_5849 but solved with the matrix solver. A solution only exists if I3 == I6 which is not generically true, but `solve` does not return conditions under which the solution is valid, only a solution that is canonical and consistent with the input. ''' # a simple example with the same issue # assert solve([x+y+z, x+y], [x, y]) == {x: y} # the longer example I1, I2, I3, I4, I5, I6 = symbols('I1:7') dI1, dI4, dQ2, dQ4, Q2, Q4 = symbols('dI1,dI4,dQ2,dQ4,Q2,Q4') e = ( I1 - I2 - I3, I3 - I4 - I5, I4 + I5 - I6, -I1 + I2 + I6, -2*I1 - 2*I3 - 2*I5 - 3*I6 - dI1/2 + 12, -I4 + dQ4, -I2 + dQ2, 2*I3 + 2*I5 + 3*I6 - Q2, I4 - 2*I5 + 2*Q4 + dI4 ) assert solve(e, I1, I4, Q2, Q4, dI1, dI4, dQ2, dQ4) == [] def test_issue_21882(): a, b, c, d, f, g, k = unknowns = symbols('a, b, c, d, f, g, k') equations = [ -k*a + b + 5*f/6 + 2*c/9 + 5*d/6 + 4*a/3, -k*f + 4*f/3 + d/2, -k*d + f/6 + d, 13*b/18 + 13*c/18 + 13*a/18, -k*c + b/2 + 20*c/9 + a, -k*b + b + c/18 + a/6, 5*b/3 + c/3 + a, 2*b/3 + 2*c + 4*a/3, -g, ] answer = [ {a: 0, f: 0, b: 0, d: 0, c: 0, g: 0}, {a: 0, f: -d, b: 0, k: S(5)/6, c: 0, g: 0}, {a: -2*c, f: 0, b: c, d: 0, k: S(13)/18, g: 0}, ] assert solve(equations, unknowns, dict=True) == answer def test_issue_5901(): f, g, h = map(Function, 'fgh') a = Symbol('a') D = Derivative(f(x), x) G = Derivative(g(a), a) assert solve(f(x) + f(x).diff(x), f(x)) == \ [-D] assert solve(f(x) - 3, f(x)) == \ [3] assert solve(f(x) - 3*f(x).diff(x), f(x)) == \ [3*D] assert solve([f(x) - 3*f(x).diff(x)], f(x)) == \ {f(x): 3*D} assert solve([f(x) - 3*f(x).diff(x), f(x)**2 - y + 4], f(x), y) == \ [{f(x): 3*D, y: 9*D**2 + 4}] assert solve(-f(a)**2*g(a)**2 + f(a)**2*h(a)**2 + g(a).diff(a), h(a), g(a), set=True) == \ ([g(a)], { (-sqrt(h(a)**2*f(a)**2 + G)/f(a),), (sqrt(h(a)**2*f(a)**2+ G)/f(a),)}) args = [f(x).diff(x, 2)*(f(x) + g(x)) - g(x)**2 + 2, f(x), g(x)] assert set(solve(*args)) == \ {(-sqrt(2), sqrt(2)), (sqrt(2), -sqrt(2))} eqs = [f(x)**2 + g(x) - 2*f(x).diff(x), g(x)**2 - 4] assert solve(eqs, f(x), g(x), set=True) == \ ([f(x), g(x)], { (-sqrt(2*D - 2), S(2)), (sqrt(2*D - 2), S(2)), (-sqrt(2*D + 2), -S(2)), (sqrt(2*D + 2), -S(2))}) # the underlying problem was in solve_linear that was not masking off # anything but a Mul or Add; it now raises an error if it gets anything # but a symbol and solve handles the substitutions necessary so solve_linear # won't make this error raises( ValueError, lambda: solve_linear(f(x) + f(x).diff(x), symbols=[f(x)])) assert solve_linear(f(x) + f(x).diff(x), symbols=[x]) == \ (f(x) + Derivative(f(x), x), 1) assert solve_linear(f(x) + Integral(x, (x, y)), symbols=[x]) == \ (f(x) + Integral(x, (x, y)), 1) assert solve_linear(f(x) + Integral(x, (x, y)) + x, symbols=[x]) == \ (x + f(x) + Integral(x, (x, y)), 1) assert solve_linear(f(y) + Integral(x, (x, y)) + x, symbols=[x]) == \ (x, -f(y) - Integral(x, (x, y))) assert solve_linear(x - f(x)/a + (f(x) - 1)/a, symbols=[x]) == \ (x, 1/a) assert solve_linear(x + Derivative(2*x, x)) == \ (x, -2) assert solve_linear(x + Integral(x, y), symbols=[x]) == \ (x, 0) assert solve_linear(x + Integral(x, y) - 2, symbols=[x]) == \ (x, 2/(y + 1)) assert set(solve(x + exp(x)**2, exp(x))) == \ {-sqrt(-x), sqrt(-x)} assert solve(x + exp(x), x, implicit=True) == \ [-exp(x)] assert solve(cos(x) - sin(x), x, implicit=True) == [] assert solve(x - sin(x), x, implicit=True) == \ [sin(x)] assert solve(x**2 + x - 3, x, implicit=True) == \ [-x**2 + 3] assert solve(x**2 + x - 3, x**2, implicit=True) == \ [-x + 3] def test_issue_5912(): assert set(solve(x**2 - x - 0.1, rational=True)) == \ {S.Half + sqrt(35)/10, -sqrt(35)/10 + S.Half} ans = solve(x**2 - x - 0.1, rational=False) assert len(ans) == 2 and all(a.is_Number for a in ans) ans = solve(x**2 - x - 0.1) assert len(ans) == 2 and all(a.is_Number for a in ans) def test_float_handling(): def test(e1, e2): return len(e1.atoms(Float)) == len(e2.atoms(Float)) assert solve(x - 0.5, rational=True)[0].is_Rational assert solve(x - 0.5, rational=False)[0].is_Float assert solve(x - S.Half, rational=False)[0].is_Rational assert solve(x - 0.5, rational=None)[0].is_Float assert solve(x - S.Half, rational=None)[0].is_Rational assert test(nfloat(1 + 2*x), 1.0 + 2.0*x) for contain in [list, tuple, set]: ans = nfloat(contain([1 + 2*x])) assert type(ans) is contain and test(list(ans)[0], 1.0 + 2.0*x) k, v = list(nfloat({2*x: [1 + 2*x]}).items())[0] assert test(k, 2*x) and test(v[0], 1.0 + 2.0*x) assert test(nfloat(cos(2*x)), cos(2.0*x)) assert test(nfloat(3*x**2), 3.0*x**2) assert test(nfloat(3*x**2, exponent=True), 3.0*x**2.0) assert test(nfloat(exp(2*x)), exp(2.0*x)) assert test(nfloat(x/3), x/3.0) assert test(nfloat(x**4 + 2*x + cos(Rational(1, 3)) + 1), x**4 + 2.0*x + 1.94495694631474) # don't call nfloat if there is no solution tot = 100 + c + z + t assert solve(((.7 + c)/tot - .6, (.2 + z)/tot - .3, t/tot - .1)) == [] def test_check_assumptions(): x = symbols('x', positive=True) assert solve(x**2 - 1) == [1] def test_issue_6056(): assert solve(tanh(x + 3)*tanh(x - 3) - 1) == [] assert solve(tanh(x - 1)*tanh(x + 1) + 1) == \ [I*pi*Rational(-3, 4), -I*pi/4, I*pi/4, I*pi*Rational(3, 4)] assert solve((tanh(x + 3)*tanh(x - 3) + 1)**2) == \ [I*pi*Rational(-3, 4), -I*pi/4, I*pi/4, I*pi*Rational(3, 4)] def test_issue_5673(): eq = -x + exp(exp(LambertW(log(x)))*LambertW(log(x))) assert checksol(eq, x, 2) is True assert checksol(eq, x, 2, numerical=False) is None def test_exclude(): R, C, Ri, Vout, V1, Vminus, Vplus, s = \ symbols('R, C, Ri, Vout, V1, Vminus, Vplus, s') Rf = symbols('Rf', positive=True) # to eliminate Rf = 0 soln eqs = [C*V1*s + Vplus*(-2*C*s - 1/R), Vminus*(-1/Ri - 1/Rf) + Vout/Rf, C*Vplus*s + V1*(-C*s - 1/R) + Vout/R, -Vminus + Vplus] assert solve(eqs, exclude=s*C*R) == [ { Rf: Ri*(C*R*s + 1)**2/(C*R*s), Vminus: Vplus, V1: 2*Vplus + Vplus/(C*R*s), Vout: C*R*Vplus*s + 3*Vplus + Vplus/(C*R*s)}, { Vplus: 0, Vminus: 0, V1: 0, Vout: 0}, ] # TODO: Investigate why currently solution [0] is preferred over [1]. assert solve(eqs, exclude=[Vplus, s, C]) in [[{ Vminus: Vplus, V1: Vout/2 + Vplus/2 + sqrt((Vout - 5*Vplus)*(Vout - Vplus))/2, R: (Vout - 3*Vplus - sqrt(Vout**2 - 6*Vout*Vplus + 5*Vplus**2))/(2*C*Vplus*s), Rf: Ri*(Vout - Vplus)/Vplus, }, { Vminus: Vplus, V1: Vout/2 + Vplus/2 - sqrt((Vout - 5*Vplus)*(Vout - Vplus))/2, R: (Vout - 3*Vplus + sqrt(Vout**2 - 6*Vout*Vplus + 5*Vplus**2))/(2*C*Vplus*s), Rf: Ri*(Vout - Vplus)/Vplus, }], [{ Vminus: Vplus, Vout: (V1**2 - V1*Vplus - Vplus**2)/(V1 - 2*Vplus), Rf: Ri*(V1 - Vplus)**2/(Vplus*(V1 - 2*Vplus)), R: Vplus/(C*s*(V1 - 2*Vplus)), }]] def test_high_order_roots(): s = x**5 + 4*x**3 + 3*x**2 + Rational(7, 4) assert set(solve(s)) == set(Poly(s*4, domain='ZZ').all_roots()) def test_minsolve_linear_system(): def count(dic): return len([x for x in dic.values() if x == 0]) assert count(solve([x + y + z, y + z + a + t], particular=True, quick=True)) \ == 3 assert count(solve([x + y + z, y + z + a + t], particular=True, quick=False)) \ == 3 assert count(solve([x + y + z, y + z + a], particular=True, quick=True)) == 1 assert count(solve([x + y + z, y + z + a], particular=True, quick=False)) == 2 def test_real_roots(): # cf. issue 6650 x = Symbol('x', real=True) assert len(solve(x**5 + x**3 + 1)) == 1 def test_issue_6528(): eqs = [ 327600995*x**2 - 37869137*x + 1809975124*y**2 - 9998905626, 895613949*x**2 - 273830224*x*y + 530506983*y**2 - 10000000000] # two expressions encountered are > 1400 ops long so if this hangs # it is likely because simplification is being done assert len(solve(eqs, y, x, check=False)) == 4 def test_overdetermined(): x = symbols('x', real=True) eqs = [Abs(4*x - 7) - 5, Abs(3 - 8*x) - 1] assert solve(eqs, x) == [(S.Half,)] assert solve(eqs, x, manual=True) == [(S.Half,)] assert solve(eqs, x, manual=True, check=False) == [(S.Half,), (S(3),)] def test_issue_6605(): x = symbols('x') assert solve(4**(x/2) - 2**(x/3)) == [0, 3*I*pi/log(2)] # while the first one passed, this one failed x = symbols('x', real=True) assert solve(5**(x/2) - 2**(x/3)) == [0] b = sqrt(6)*sqrt(log(2))/sqrt(log(5)) assert solve(5**(x/2) - 2**(3/x)) == [-b, b] def test__ispow(): assert _ispow(x**2) assert not _ispow(x) assert not _ispow(True) def test_issue_6644(): eq = -sqrt((m - q)**2 + (-m/(2*q) + S.Half)**2) + sqrt((-m**2/2 - sqrt( 4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2 + (m**2/2 - m - sqrt( 4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2) sol = solve(eq, q, simplify=False, check=False) assert len(sol) == 5 def test_issue_6752(): assert solve([a**2 + a, a - b], [a, b]) == [(-1, -1), (0, 0)] assert solve([a**2 + a*c, a - b], [a, b]) == [(0, 0), (-c, -c)] def test_issue_6792(): assert solve(x*(x - 1)**2*(x + 1)*(x**6 - x + 1)) == [ -1, 0, 1, CRootOf(x**6 - x + 1, 0), CRootOf(x**6 - x + 1, 1), CRootOf(x**6 - x + 1, 2), CRootOf(x**6 - x + 1, 3), CRootOf(x**6 - x + 1, 4), CRootOf(x**6 - x + 1, 5)] def test_issues_6819_6820_6821_6248_8692(): # issue 6821 x, y = symbols('x y', real=True) assert solve(abs(x + 3) - 2*abs(x - 3)) == [1, 9] assert solve([abs(x) - 2, arg(x) - pi], x) == [(-2,)] assert set(solve(abs(x - 7) - 8)) == {-S.One, S(15)} # issue 8692 assert solve(Eq(Abs(x + 1) + Abs(x**2 - 7), 9), x) == [ Rational(-1, 2) + sqrt(61)/2, -sqrt(69)/2 + S.Half] # issue 7145 assert solve(2*abs(x) - abs(x - 1)) == [-1, Rational(1, 3)] x = symbols('x') assert solve([re(x) - 1, im(x) - 2], x) == [ {re(x): 1, x: 1 + 2*I, im(x): 2}] # check for 'dict' handling of solution eq = sqrt(re(x)**2 + im(x)**2) - 3 assert solve(eq) == solve(eq, x) i = symbols('i', imaginary=True) assert solve(abs(i) - 3) == [-3*I, 3*I] raises(NotImplementedError, lambda: solve(abs(x) - 3)) w = symbols('w', integer=True) assert solve(2*x**w - 4*y**w, w) == solve((x/y)**w - 2, w) x, y = symbols('x y', real=True) assert solve(x + y*I + 3) == {y: 0, x: -3} # issue 2642 assert solve(x*(1 + I)) == [0] x, y = symbols('x y', imaginary=True) assert solve(x + y*I + 3 + 2*I) == {x: -2*I, y: 3*I} x = symbols('x', real=True) assert solve(x + y + 3 + 2*I) == {x: -3, y: -2*I} # issue 6248 f = Function('f') assert solve(f(x + 1) - f(2*x - 1)) == [2] assert solve(log(x + 1) - log(2*x - 1)) == [2] x = symbols('x') assert solve(2**x + 4**x) == [I*pi/log(2)] def test_issue_14607(): # issue 14607 s, tau_c, tau_1, tau_2, phi, K = symbols( 's, tau_c, tau_1, tau_2, phi, K') target = (s**2*tau_1*tau_2 + s*tau_1 + s*tau_2 + 1)/(K*s*(-phi + tau_c)) K_C, tau_I, tau_D = symbols('K_C, tau_I, tau_D', positive=True, nonzero=True) PID = K_C*(1 + 1/(tau_I*s) + tau_D*s) eq = (target - PID).together() eq *= denom(eq).simplify() eq = Poly(eq, s) c = eq.coeffs() vars = [K_C, tau_I, tau_D] s = solve(c, vars, dict=True) assert len(s) == 1 knownsolution = {K_C: -(tau_1 + tau_2)/(K*(phi - tau_c)), tau_I: tau_1 + tau_2, tau_D: tau_1*tau_2/(tau_1 + tau_2)} for var in vars: assert s[0][var].simplify() == knownsolution[var].simplify() def test_lambert_multivariate(): from sympy.abc import x, y assert _filtered_gens(Poly(x + 1/x + exp(x) + y), x) == {x, exp(x)} assert _lambert(x, x) == [] assert solve((x**2 - 2*x + 1).subs(x, log(x) + 3*x)) == [LambertW(3*S.Exp1)/3] assert solve((x**2 - 2*x + 1).subs(x, (log(x) + 3*x)**2 - 1)) == \ [LambertW(3*exp(-sqrt(2)))/3, LambertW(3*exp(sqrt(2)))/3] assert solve((x**2 - 2*x - 2).subs(x, log(x) + 3*x)) == \ [LambertW(3*exp(1 - sqrt(3)))/3, LambertW(3*exp(1 + sqrt(3)))/3] eq = (x*exp(x) - 3).subs(x, x*exp(x)) assert solve(eq) == [LambertW(3*exp(-LambertW(3)))] # coverage test raises(NotImplementedError, lambda: solve(x - sin(x)*log(y - x), x)) ans = [3, -3*LambertW(-log(3)/3)/log(3)] # 3 and 2.478... assert solve(x**3 - 3**x, x) == ans assert set(solve(3*log(x) - x*log(3))) == set(ans) assert solve(LambertW(2*x) - y, x) == [y*exp(y)/2] @XFAIL def test_other_lambert(): assert solve(3*sin(x) - x*sin(3), x) == [3] assert set(solve(x**a - a**x), x) == { a, -a*LambertW(-log(a)/a)/log(a)} @slow def test_lambert_bivariate(): # tests passing current implementation assert solve((x**2 + x)*exp(x**2 + x) - 1) == [ Rational(-1, 2) + sqrt(1 + 4*LambertW(1))/2, Rational(-1, 2) - sqrt(1 + 4*LambertW(1))/2] assert solve((x**2 + x)*exp((x**2 + x)*2) - 1) == [ Rational(-1, 2) + sqrt(1 + 2*LambertW(2))/2, Rational(-1, 2) - sqrt(1 + 2*LambertW(2))/2] assert solve(a/x + exp(x/2), x) == [2*LambertW(-a/2)] assert solve((a/x + exp(x/2)).diff(x), x) == \ [4*LambertW(-sqrt(2)*sqrt(a)/4), 4*LambertW(sqrt(2)*sqrt(a)/4)] assert solve((1/x + exp(x/2)).diff(x), x) == \ [4*LambertW(-sqrt(2)/4), 4*LambertW(sqrt(2)/4), # nsimplifies as 2*2**(141/299)*3**(206/299)*5**(205/299)*7**(37/299)/21 4*LambertW(-sqrt(2)/4, -1)] assert solve(x*log(x) + 3*x + 1, x) == \ [exp(-3 + LambertW(-exp(3)))] assert solve(-x**2 + 2**x, x) == [2, 4, -2*LambertW(log(2)/2)/log(2)] assert solve(x**2 - 2**x, x) == [2, 4, -2*LambertW(log(2)/2)/log(2)] ans = solve(3*x + 5 + 2**(-5*x + 3), x) assert len(ans) == 1 and ans[0].expand() == \ Rational(-5, 3) + LambertW(-10240*root(2, 3)*log(2)/3)/(5*log(2)) assert solve(5*x - 1 + 3*exp(2 - 7*x), x) == \ [Rational(1, 5) + LambertW(-21*exp(Rational(3, 5))/5)/7] assert solve((log(x) + x).subs(x, x**2 + 1)) == [ -I*sqrt(-LambertW(1) + 1), sqrt(-1 + LambertW(1))] # check collection ax = a**(3*x + 5) ans = solve(3*log(ax) + b*log(ax) + ax, x) x0 = 1/log(a) x1 = sqrt(3)*I x2 = b + 3 x3 = x2*LambertW(1/x2)/a**5 x4 = x3**Rational(1, 3)/2 assert ans == [ x0*log(x4*(-x1 - 1)), x0*log(x4*(x1 - 1)), x0*log(x3)/3] x1 = LambertW(Rational(1, 3)) x2 = a**(-5) x3 = -3**Rational(1, 3) x4 = 3**Rational(5, 6)*I x5 = x1**Rational(1, 3)*x2**Rational(1, 3)/2 ans = solve(3*log(ax) + ax, x) assert ans == [ x0*log(3*x1*x2)/3, x0*log(x5*(x3 - x4)), x0*log(x5*(x3 + x4))] # coverage p = symbols('p', positive=True) eq = 4*2**(2*p + 3) - 2*p - 3 assert _solve_lambert(eq, p, _filtered_gens(Poly(eq), p)) == [ Rational(-3, 2) - LambertW(-4*log(2))/(2*log(2))] assert set(solve(3**cos(x) - cos(x)**3)) == { acos(3), acos(-3*LambertW(-log(3)/3)/log(3))} # should give only one solution after using `uniq` assert solve(2*log(x) - 2*log(z) + log(z + log(x) + log(z)), x) == [ exp(-z + LambertW(2*z**4*exp(2*z))/2)/z] # cases when p != S.One # issue 4271 ans = solve((a/x + exp(x/2)).diff(x, 2), x) x0 = (-a)**Rational(1, 3) x1 = sqrt(3)*I x2 = x0/6 assert ans == [ 6*LambertW(x0/3), 6*LambertW(x2*(-x1 - 1)), 6*LambertW(x2*(x1 - 1))] assert solve((1/x + exp(x/2)).diff(x, 2), x) == \ [6*LambertW(Rational(-1, 3)), 6*LambertW(Rational(1, 6) - sqrt(3)*I/6), \ 6*LambertW(Rational(1, 6) + sqrt(3)*I/6), 6*LambertW(Rational(-1, 3), -1)] assert solve(x**2 - y**2/exp(x), x, y, dict=True) == \ [{x: 2*LambertW(-y/2)}, {x: 2*LambertW(y/2)}] # this is slow but not exceedingly slow assert solve((x**3)**(x/2) + pi/2, x) == [ exp(LambertW(-2*log(2)/3 + 2*log(pi)/3 + I*pi*Rational(2, 3)))] def test_rewrite_trig(): assert solve(sin(x) + tan(x)) == [0, -pi, pi, 2*pi] assert solve(sin(x) + sec(x)) == [ -2*atan(Rational(-1, 2) + sqrt(2)*sqrt(1 - sqrt(3)*I)/2 + sqrt(3)*I/2), 2*atan(S.Half - sqrt(2)*sqrt(1 + sqrt(3)*I)/2 + sqrt(3)*I/2), 2*atan(S.Half + sqrt(2)*sqrt(1 + sqrt(3)*I)/2 + sqrt(3)*I/2), 2*atan(S.Half - sqrt(3)*I/2 + sqrt(2)*sqrt(1 - sqrt(3)*I)/2)] assert solve(sinh(x) + tanh(x)) == [0, I*pi] # issue 6157 assert solve(2*sin(x) - cos(x), x) == [atan(S.Half)] @XFAIL def test_rewrite_trigh(): # if this import passes then the test below should also pass from sympy.functions.elementary.hyperbolic import sech assert solve(sinh(x) + sech(x)) == [ 2*atanh(Rational(-1, 2) + sqrt(5)/2 - sqrt(-2*sqrt(5) + 2)/2), 2*atanh(Rational(-1, 2) + sqrt(5)/2 + sqrt(-2*sqrt(5) + 2)/2), 2*atanh(-sqrt(5)/2 - S.Half + sqrt(2 + 2*sqrt(5))/2), 2*atanh(-sqrt(2 + 2*sqrt(5))/2 - sqrt(5)/2 - S.Half)] def test_uselogcombine(): eq = z - log(x) + log(y/(x*(-1 + y**2/x**2))) assert solve(eq, x, force=True) == [-sqrt(y*(y - exp(z))), sqrt(y*(y - exp(z)))] assert solve(log(x + 3) + log(1 + 3/x) - 3) in [ [-3 + sqrt(-12 + exp(3))*exp(Rational(3, 2))/2 + exp(3)/2, -sqrt(-12 + exp(3))*exp(Rational(3, 2))/2 - 3 + exp(3)/2], [-3 + sqrt(-36 + (-exp(3) + 6)**2)/2 + exp(3)/2, -3 - sqrt(-36 + (-exp(3) + 6)**2)/2 + exp(3)/2], ] assert solve(log(exp(2*x) + 1) + log(-tanh(x) + 1) - log(2)) == [] def test_atan2(): assert solve(atan2(x, 2) - pi/3, x) == [2*sqrt(3)] def test_errorinverses(): assert solve(erf(x) - y, x) == [erfinv(y)] assert solve(erfinv(x) - y, x) == [erf(y)] assert solve(erfc(x) - y, x) == [erfcinv(y)] assert solve(erfcinv(x) - y, x) == [erfc(y)] def test_issue_2725(): R = Symbol('R') eq = sqrt(2)*R*sqrt(1/(R + 1)) + (R + 1)*(sqrt(2)*sqrt(1/(R + 1)) - 1) sol = solve(eq, R, set=True)[1] assert sol == {(Rational(5, 3) + (Rational(-1, 2) - sqrt(3)*I/2)*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3) + 40/(9*((Rational(-1, 2) - sqrt(3)*I/2)*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3))),), (Rational(5, 3) + 40/(9*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3)) + (Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3),)} def test_issue_5114_6611(): # See that it doesn't hang; this solves in about 2 seconds. # Also check that the solution is relatively small. # Note: the system in issue 6611 solves in about 5 seconds and has # an op-count of 138336 (with simplify=False). b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r = symbols('b:r') eqs = Matrix([ [b - c/d + r/d], [c*(1/g + 1/e + 1/d) - f/g - r/d], [-c/g + f*(1/j + 1/i + 1/g) - h/i], [-f/i + h*(1/m + 1/l + 1/i) - k/m], [-h/m + k*(1/p + 1/o + 1/m) - n/p], [-k/p + n*(1/q + 1/p)]]) v = Matrix([f, h, k, n, b, c]) ans = solve(list(eqs), list(v), simplify=False) # If time is taken to simplify then then 2617 below becomes # 1168 and the time is about 50 seconds instead of 2. assert sum([s.count_ops() for s in ans.values()]) <= 3270 def test_det_quick(): m = Matrix(3, 3, symbols('a:9')) assert m.det() == det_quick(m) # calls det_perm m[0, 0] = 1 assert m.det() == det_quick(m) # calls det_minor m = Matrix(3, 3, list(range(9))) assert m.det() == det_quick(m) # defaults to .det() # make sure they work with Sparse s = SparseMatrix(2, 2, (1, 2, 1, 4)) assert det_perm(s) == det_minor(s) == s.det() def test_real_imag_splitting(): a, b = symbols('a b', real=True) assert solve(sqrt(a**2 + b**2) - 3, a) == \ [-sqrt(-b**2 + 9), sqrt(-b**2 + 9)] a, b = symbols('a b', imaginary=True) assert solve(sqrt(a**2 + b**2) - 3, a) == [] def test_issue_7110(): y = -2*x**3 + 4*x**2 - 2*x + 5 assert any(ask(Q.real(i)) for i in solve(y)) def test_units(): assert solve(1/x - 1/(2*cm)) == [2*cm] def test_issue_7547(): A, B, V = symbols('A,B,V') eq1 = Eq(630.26*(V - 39.0)*V*(V + 39) - A + B, 0) eq2 = Eq(B, 1.36*10**8*(V - 39)) eq3 = Eq(A, 5.75*10**5*V*(V + 39.0)) sol = Matrix(nsolve(Tuple(eq1, eq2, eq3), [A, B, V], (0, 0, 0))) assert str(sol) == str(Matrix( [['4442890172.68209'], ['4289299466.1432'], ['70.5389666628177']])) def test_issue_7895(): r = symbols('r', real=True) assert solve(sqrt(r) - 2) == [4] def test_issue_2777(): # the equations represent two circles x, y = symbols('x y', real=True) e1, e2 = sqrt(x**2 + y**2) - 10, sqrt(y**2 + (-x + 10)**2) - 3 a, b = Rational(191, 20), 3*sqrt(391)/20 ans = [(a, -b), (a, b)] assert solve((e1, e2), (x, y)) == ans assert solve((e1, e2/(x - a)), (x, y)) == [] # make the 2nd circle's radius be -3 e2 += 6 assert solve((e1, e2), (x, y)) == [] assert solve((e1, e2), (x, y), check=False) == ans def test_issue_7322(): number = 5.62527e-35 assert solve(x - number, x)[0] == number def test_nsolve(): raises(ValueError, lambda: nsolve(x, (-1, 1), method='bisect')) raises(TypeError, lambda: nsolve((x - y + 3,x + y,z - y),(x,y,z),(-50,50))) raises(TypeError, lambda: nsolve((x + y, x - y), (0, 1))) @slow def test_high_order_multivariate(): assert len(solve(a*x**3 - x + 1, x)) == 3 assert len(solve(a*x**4 - x + 1, x)) == 4 assert solve(a*x**5 - x + 1, x) == [] # incomplete solution allowed raises(NotImplementedError, lambda: solve(a*x**5 - x + 1, x, incomplete=False)) # result checking must always consider the denominator and CRootOf # must be checked, too d = x**5 - x + 1 assert solve(d*(1 + 1/d)) == [CRootOf(d + 1, i) for i in range(5)] d = x - 1 assert solve(d*(2 + 1/d)) == [S.Half] def test_base_0_exp_0(): assert solve(0**x - 1) == [0] assert solve(0**(x - 2) - 1) == [2] assert solve(S('x*(1/x**0 - x)', evaluate=False)) == \ [0, 1] def test__simple_dens(): assert _simple_dens(1/x**0, [x]) == set() assert _simple_dens(1/x**y, [x]) == {x**y} assert _simple_dens(1/root(x, 3), [x]) == {x} def test_issue_8755(): # This tests two things: that if full unrad is attempted and fails # the solution should still be found; also it tests the use of # keyword `composite`. assert len(solve(sqrt(y)*x + x**3 - 1, x)) == 3 assert len(solve(-512*y**3 + 1344*(x + 2)**Rational(1, 3)*y**2 - 1176*(x + 2)**Rational(2, 3)*y - 169*x + 686, y, _unrad=False)) == 3 @slow def test_issue_8828(): x1 = 0 y1 = -620 r1 = 920 x2 = 126 y2 = 276 x3 = 51 y3 = 205 r3 = 104 v = x, y, z f1 = (x - x1)**2 + (y - y1)**2 - (r1 - z)**2 f2 = (x2 - x)**2 + (y2 - y)**2 - z**2 f3 = (x - x3)**2 + (y - y3)**2 - (r3 - z)**2 F = f1,f2,f3 g1 = sqrt((x - x1)**2 + (y - y1)**2) + z - r1 g2 = f2 g3 = sqrt((x - x3)**2 + (y - y3)**2) + z - r3 G = g1,g2,g3 A = solve(F, v) B = solve(G, v) C = solve(G, v, manual=True) p, q, r = [{tuple(i.evalf(2) for i in j) for j in R} for R in [A, B, C]] assert p == q == r @slow def test_issue_2840_8155(): assert solve(sin(3*x) + sin(6*x)) == [ 0, pi*Rational(-5, 3), pi*Rational(-4, 3), -pi, pi*Rational(-2, 3), pi*Rational(-4, 9), -pi/3, pi*Rational(-2, 9), pi*Rational(2, 9), pi/3, pi*Rational(4, 9), pi*Rational(2, 3), pi, pi*Rational(4, 3), pi*Rational(14, 9), pi*Rational(5, 3), pi*Rational(16, 9), 2*pi, -2*I*log(-(-1)**Rational(1, 9)), -2*I*log(-(-1)**Rational(2, 9)), -2*I*log(-sin(pi/18) - I*cos(pi/18)), -2*I*log(-sin(pi/18) + I*cos(pi/18)), -2*I*log(sin(pi/18) - I*cos(pi/18)), -2*I*log(sin(pi/18) + I*cos(pi/18))] assert solve(2*sin(x) - 2*sin(2*x)) == [ 0, pi*Rational(-5, 3), -pi, -pi/3, pi/3, pi, pi*Rational(5, 3)] def test_issue_9567(): assert solve(1 + 1/(x - 1)) == [0] def test_issue_11538(): assert solve(x + E) == [-E] assert solve(x**2 + E) == [-I*sqrt(E), I*sqrt(E)] assert solve(x**3 + 2*E) == [ -cbrt(2 * E), cbrt(2)*cbrt(E)/2 - cbrt(2)*sqrt(3)*I*cbrt(E)/2, cbrt(2)*cbrt(E)/2 + cbrt(2)*sqrt(3)*I*cbrt(E)/2] assert solve([x + 4, y + E], x, y) == {x: -4, y: -E} assert solve([x**2 + 4, y + E], x, y) == [ (-2*I, -E), (2*I, -E)] e1 = x - y**3 + 4 e2 = x + y + 4 + 4 * E assert len(solve([e1, e2], x, y)) == 3 @slow def test_issue_12114(): a, b, c, d, e, f, g = symbols('a,b,c,d,e,f,g') terms = [1 + a*b + d*e, 1 + a*c + d*f, 1 + b*c + e*f, g - a**2 - d**2, g - b**2 - e**2, g - c**2 - f**2] s = solve(terms, [a, b, c, d, e, f, g], dict=True) assert s == [{a: -sqrt(-f**2 - 1), b: -sqrt(-f**2 - 1), c: -sqrt(-f**2 - 1), d: f, e: f, g: -1}, {a: sqrt(-f**2 - 1), b: sqrt(-f**2 - 1), c: sqrt(-f**2 - 1), d: f, e: f, g: -1}, {a: -sqrt(3)*f/2 - sqrt(-f**2 + 2)/2, b: sqrt(3)*f/2 - sqrt(-f**2 + 2)/2, c: sqrt(-f**2 + 2), d: -f/2 + sqrt(-3*f**2 + 6)/2, e: -f/2 - sqrt(3)*sqrt(-f**2 + 2)/2, g: 2}, {a: -sqrt(3)*f/2 + sqrt(-f**2 + 2)/2, b: sqrt(3)*f/2 + sqrt(-f**2 + 2)/2, c: -sqrt(-f**2 + 2), d: -f/2 - sqrt(-3*f**2 + 6)/2, e: -f/2 + sqrt(3)*sqrt(-f**2 + 2)/2, g: 2}, {a: sqrt(3)*f/2 - sqrt(-f**2 + 2)/2, b: -sqrt(3)*f/2 - sqrt(-f**2 + 2)/2, c: sqrt(-f**2 + 2), d: -f/2 - sqrt(-3*f**2 + 6)/2, e: -f/2 + sqrt(3)*sqrt(-f**2 + 2)/2, g: 2}, {a: sqrt(3)*f/2 + sqrt(-f**2 + 2)/2, b: -sqrt(3)*f/2 + sqrt(-f**2 + 2)/2, c: -sqrt(-f**2 + 2), d: -f/2 + sqrt(-3*f**2 + 6)/2, e: -f/2 - sqrt(3)*sqrt(-f**2 + 2)/2, g: 2}] def test_inf(): assert solve(1 - oo*x) == [] assert solve(oo*x, x) == [] assert solve(oo*x - oo, x) == [] def test_issue_12448(): f = Function('f') fun = [f(i) for i in range(15)] sym = symbols('x:15') reps = dict(zip(fun, sym)) (x, y, z), c = sym[:3], sym[3:] ssym = solve([c[4*i]*x + c[4*i + 1]*y + c[4*i + 2]*z + c[4*i + 3] for i in range(3)], (x, y, z)) (x, y, z), c = fun[:3], fun[3:] sfun = solve([c[4*i]*x + c[4*i + 1]*y + c[4*i + 2]*z + c[4*i + 3] for i in range(3)], (x, y, z)) assert sfun[fun[0]].xreplace(reps).count_ops() == \ ssym[sym[0]].count_ops() def test_denoms(): assert denoms(x/2 + 1/y) == {2, y} assert denoms(x/2 + 1/y, y) == {y} assert denoms(x/2 + 1/y, [y]) == {y} assert denoms(1/x + 1/y + 1/z, [x, y]) == {x, y} assert denoms(1/x + 1/y + 1/z, x, y) == {x, y} assert denoms(1/x + 1/y + 1/z, {x, y}) == {x, y} def test_issue_12476(): x0, x1, x2, x3, x4, x5 = symbols('x0 x1 x2 x3 x4 x5') eqns = [x0**2 - x0, x0*x1 - x1, x0*x2 - x2, x0*x3 - x3, x0*x4 - x4, x0*x5 - x5, x0*x1 - x1, -x0/3 + x1**2 - 2*x2/3, x1*x2 - x1/3 - x2/3 - x3/3, x1*x3 - x2/3 - x3/3 - x4/3, x1*x4 - 2*x3/3 - x5/3, x1*x5 - x4, x0*x2 - x2, x1*x2 - x1/3 - x2/3 - x3/3, -x0/6 - x1/6 + x2**2 - x2/6 - x3/3 - x4/6, -x1/6 + x2*x3 - x2/3 - x3/6 - x4/6 - x5/6, x2*x4 - x2/3 - x3/3 - x4/3, x2*x5 - x3, x0*x3 - x3, x1*x3 - x2/3 - x3/3 - x4/3, -x1/6 + x2*x3 - x2/3 - x3/6 - x4/6 - x5/6, -x0/6 - x1/6 - x2/6 + x3**2 - x3/3 - x4/6, -x1/3 - x2/3 + x3*x4 - x3/3, -x2 + x3*x5, x0*x4 - x4, x1*x4 - 2*x3/3 - x5/3, x2*x4 - x2/3 - x3/3 - x4/3, -x1/3 - x2/3 + x3*x4 - x3/3, -x0/3 - 2*x2/3 + x4**2, -x1 + x4*x5, x0*x5 - x5, x1*x5 - x4, x2*x5 - x3, -x2 + x3*x5, -x1 + x4*x5, -x0 + x5**2, x0 - 1] sols = [{x0: 1, x3: Rational(1, 6), x2: Rational(1, 6), x4: Rational(-2, 3), x1: Rational(-2, 3), x5: 1}, {x0: 1, x3: S.Half, x2: Rational(-1, 2), x4: 0, x1: 0, x5: -1}, {x0: 1, x3: Rational(-1, 3), x2: Rational(-1, 3), x4: Rational(1, 3), x1: Rational(1, 3), x5: 1}, {x0: 1, x3: 1, x2: 1, x4: 1, x1: 1, x5: 1}, {x0: 1, x3: Rational(-1, 3), x2: Rational(1, 3), x4: sqrt(5)/3, x1: -sqrt(5)/3, x5: -1}, {x0: 1, x3: Rational(-1, 3), x2: Rational(1, 3), x4: -sqrt(5)/3, x1: sqrt(5)/3, x5: -1}] assert solve(eqns) == sols def test_issue_13849(): t = symbols('t') assert solve((t*(sqrt(5) + sqrt(2)) - sqrt(2), t), t) == [] def test_issue_14860(): from sympy.physics.units import newton, kilo assert solve(8*kilo*newton + x + y, x) == [-8000*newton - y] def test_issue_14721(): k, h, a, b = symbols(':4') assert solve([ -1 + (-k + 1)**2/b**2 + (-h - 1)**2/a**2, -1 + (-k + 1)**2/b**2 + (-h + 1)**2/a**2, h, k + 2], h, k, a, b) == [ (0, -2, -b*sqrt(1/(b**2 - 9)), b), (0, -2, b*sqrt(1/(b**2 - 9)), b)] assert solve([ h, h/a + 1/b**2 - 2, -h/2 + 1/b**2 - 2], a, h, b) == [ (a, 0, -sqrt(2)/2), (a, 0, sqrt(2)/2)] assert solve((a + b**2 - 1, a + b**2 - 2)) == [] def test_issue_14779(): x = symbols('x', real=True) assert solve(sqrt(x**4 - 130*x**2 + 1089) + sqrt(x**4 - 130*x**2 + 3969) - 96*Abs(x)/x,x) == [sqrt(130)] def test_issue_15307(): assert solve((y - 2, Mul(x + 3,x - 2, evaluate=False))) == \ [{x: -3, y: 2}, {x: 2, y: 2}] assert solve((y - 2, Mul(3, x - 2, evaluate=False))) == \ {x: 2, y: 2} assert solve((y - 2, Add(x + 4, x - 2, evaluate=False))) == \ {x: -1, y: 2} eq1 = Eq(12513*x + 2*y - 219093, -5726*x - y) eq2 = Eq(-2*x + 8, 2*x - 40) assert solve([eq1, eq2]) == {x:12, y:75} def test_issue_15415(): assert solve(x - 3, x) == [3] assert solve([x - 3], x) == {x:3} assert solve(Eq(y + 3*x**2/2, y + 3*x), y) == [] assert solve([Eq(y + 3*x**2/2, y + 3*x)], y) == [] assert solve([Eq(y + 3*x**2/2, y + 3*x), Eq(x, 1)], y) == [] @slow def test_issue_15731(): # f(x)**g(x)=c assert solve(Eq((x**2 - 7*x + 11)**(x**2 - 13*x + 42), 1)) == [2, 3, 4, 5, 6, 7] assert solve((x)**(x + 4) - 4) == [-2] assert solve((-x)**(-x + 4) - 4) == [2] assert solve((x**2 - 6)**(x**2 - 2) - 4) == [-2, 2] assert solve((x**2 - 2*x - 1)**(x**2 - 3) - 1/(1 - 2*sqrt(2))) == [sqrt(2)] assert solve(x**(x + S.Half) - 4*sqrt(2)) == [S(2)] assert solve((x**2 + 1)**x - 25) == [2] assert solve(x**(2/x) - 2) == [2, 4] assert solve((x/2)**(2/x) - sqrt(2)) == [4, 8] assert solve(x**(x + S.Half) - Rational(9, 4)) == [Rational(3, 2)] # a**g(x)=c assert solve((-sqrt(sqrt(2)))**x - 2) == [4, log(2)/(log(2**Rational(1, 4)) + I*pi)] assert solve((sqrt(2))**x - sqrt(sqrt(2))) == [S.Half] assert solve((-sqrt(2))**x + 2*(sqrt(2))) == [3, (3*log(2)**2 + 4*pi**2 - 4*I*pi*log(2))/(log(2)**2 + 4*pi**2)] assert solve((sqrt(2))**x - 2*(sqrt(2))) == [3] assert solve(I**x + 1) == [2] assert solve((1 + I)**x - 2*I) == [2] assert solve((sqrt(2) + sqrt(3))**x - (2*sqrt(6) + 5)**Rational(1, 3)) == [Rational(2, 3)] # bases of both sides are equal b = Symbol('b') assert solve(b**x - b**2, x) == [2] assert solve(b**x - 1/b, x) == [-1] assert solve(b**x - b, x) == [1] b = Symbol('b', positive=True) assert solve(b**x - b**2, x) == [2] assert solve(b**x - 1/b, x) == [-1] def test_issue_10933(): assert solve(x**4 + y*(x + 0.1), x) # doesn't fail assert solve(I*x**4 + x**3 + x**2 + 1.) # doesn't fail def test_Abs_handling(): x = symbols('x', real=True) assert solve(abs(x/y), x) == [0] def test_issue_7982(): x = Symbol('x') # Test that no exception happens assert solve([2*x**2 + 5*x + 20 <= 0, x >= 1.5], x) is S.false # From #8040 assert solve([x**3 - 8.08*x**2 - 56.48*x/5 - 106 >= 0, x - 1 <= 0], [x]) is S.false def test_issue_14645(): x, y = symbols('x y') assert solve([x*y - x - y, x*y - x - y], [x, y]) == [(y/(y - 1), y)] def test_issue_12024(): x, y = symbols('x y') assert solve(Piecewise((0.0, x < 0.1), (x, x >= 0.1)) - y) == \ [{y: Piecewise((0.0, x < 0.1), (x, True))}] def test_issue_17452(): assert solve((7**x)**x + pi, x) == [-sqrt(log(pi) + I*pi)/sqrt(log(7)), sqrt(log(pi) + I*pi)/sqrt(log(7))] assert solve(x**(x/11) + pi/11, x) == [exp(LambertW(-11*log(11) + 11*log(pi) + 11*I*pi))] def test_issue_17799(): assert solve(-erf(x**(S(1)/3))**pi + I, x) == [] def test_issue_17650(): x = Symbol('x', real=True) assert solve(abs(abs(x**2 - 1) - x) - x) == [1, -1 + sqrt(2), 1 + sqrt(2)] def test_issue_17882(): eq = -8*x**2/(9*(x**2 - 1)**(S(4)/3)) + 4/(3*(x**2 - 1)**(S(1)/3)) assert unrad(eq) is None def test_issue_17949(): assert solve(exp(+x+x**2), x) == [] assert solve(exp(-x+x**2), x) == [] assert solve(exp(+x-x**2), x) == [] assert solve(exp(-x-x**2), x) == [] def test_issue_10993(): assert solve(Eq(binomial(x, 2), 3)) == [-2, 3] assert solve(Eq(pow(x, 2) + binomial(x, 3), x)) == [-4, 0, 1] assert solve(Eq(binomial(x, 2), 0)) == [0, 1] assert solve(a+binomial(x, 3), a) == [-binomial(x, 3)] assert solve(x-binomial(a, 3) + binomial(y, 2) + sin(a), x) == [-sin(a) + binomial(a, 3) - binomial(y, 2)] assert solve((x+1)-binomial(x+1, 3), x) == [-2, -1, 3] def test_issue_11553(): eq1 = x + y + 1 eq2 = x + GoldenRatio assert solve([eq1, eq2], x, y) == {x: -GoldenRatio, y: -1 + GoldenRatio} eq3 = x + 2 + TribonacciConstant assert solve([eq1, eq3], x, y) == {x: -2 - TribonacciConstant, y: 1 + TribonacciConstant} def test_issue_19113_19102(): t = S(1)/3 solve(cos(x)**5-sin(x)**5) assert solve(4*cos(x)**3 - 2*sin(x)**3) == [ atan(2**(t)), -atan(2**(t)*(1 - sqrt(3)*I)/2), -atan(2**(t)*(1 + sqrt(3)*I)/2)] h = S.Half assert solve(cos(x)**2 + sin(x)) == [ 2*atan(-h + sqrt(5)/2 + sqrt(2)*sqrt(1 - sqrt(5))/2), -2*atan(h + sqrt(5)/2 + sqrt(2)*sqrt(1 + sqrt(5))/2), -2*atan(-sqrt(5)/2 + h + sqrt(2)*sqrt(1 - sqrt(5))/2), -2*atan(-sqrt(2)*sqrt(1 + sqrt(5))/2 + h + sqrt(5)/2)] assert solve(3*cos(x) - sin(x)) == [atan(3)] def test_issue_19509(): a = S(3)/4 b = S(5)/8 c = sqrt(5)/8 d = sqrt(5)/4 assert solve(1/(x -1)**5 - 1) == [2, -d + a - sqrt(-b + c), -d + a + sqrt(-b + c), d + a - sqrt(-b - c), d + a + sqrt(-b - c)] def test_issue_20747(): THT, HT, DBH, dib, c0, c1, c2, c3, c4 = symbols('THT HT DBH dib c0 c1 c2 c3 c4') f = DBH*c3 + THT*c4 + c2 rhs = 1 - ((HT - 1)/(THT - 1))**c1*(1 - exp(c0/f)) eq = dib - DBH*(c0 - f*log(rhs)) term = ((1 - exp((DBH*c0 - dib)/(DBH*(DBH*c3 + THT*c4 + c2)))) / (1 - exp(c0/(DBH*c3 + THT*c4 + c2)))) sol = [THT*term**(1/c1) - term**(1/c1) + 1] assert solve(eq, HT) == sol def test_issue_20902(): f = (t / ((1 + t) ** 2)) assert solve(f.subs({t: 3 * x + 2}).diff(x) > 0, x) == (S(-1) < x) & (x < S(-1)/3) assert solve(f.subs({t: 3 * x + 3}).diff(x) > 0, x) == (S(-4)/3 < x) & (x < S(-2)/3) assert solve(f.subs({t: 3 * x + 4}).diff(x) > 0, x) == (S(-5)/3 < x) & (x < S(-1)) assert solve(f.subs({t: 3 * x + 2}).diff(x) > 0, x) == (S(-1) < x) & (x < S(-1)/3) def test_issue_21034(): a = symbols('a', real=True) system = [x - cosh(cos(4)), y - sinh(cos(a)), z - tanh(x)] assert solve(system, x, y, z) == {x: cosh(cos(4)), z: tanh(cosh(cos(4))), y: sinh(cos(a))} #Constants inside hyperbolic functions should not be rewritten in terms of exp newsystem = [(exp(x) - exp(-x)) - tanh(x)*(exp(x) + exp(-x)) + x - 5] assert solve(newsystem, x) == {x: 5} #If the variable of interest is present in hyperbolic function, only then # it shouuld be rewritten in terms of exp and solved further def test_issue_4886(): z = a*sqrt(R**2*a**2 + R**2*b**2 - c**2)/(a**2 + b**2) t = b*c/(a**2 + b**2) sol = [((b*(t - z) - c)/(-a), t - z), ((b*(t + z) - c)/(-a), t + z)] assert solve([x**2 + y**2 - R**2, a*x + b*y - c], x, y) == sol def test_issue_6819(): a, b, c, d = symbols('a b c d', positive=True) assert solve(a*b**x - c*d**x, x) == [log(c/a)/log(b/d)] def test_issue_17454(): x = Symbol('x') assert solve((1 - x - I)**4, x) == [1 - I] def test_issue_21852(): solution = [21 - 21*sqrt(2)/2] assert solve(2*x + sqrt(2*x**2) - 21) == solution def test_issue_21942(): eq = -d + (a*c**(1 - e) + b**(1 - e)*(1 - a))**(1/(1 - e)) sol = solve(eq, c, simplify=False, check=False) assert sol == [(b/b**e - b/(a*b**e) + d**(1 - e)/a)**(1/(1 - e))] def test_solver_flags(): root = solve(x**5 + x**2 - x - 1, cubics=False) rad = solve(x**5 + x**2 - x - 1, cubics=True) assert root != rad
167448c0ce98f23c14231f78ebea29c9a6fc4fd8747324311e401c03fd64b81e
from sympy.core.function import (Function, Lambda, expand) from sympy.core.numbers import (I, Rational) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.combinatorial.factorials import (rf, binomial, factorial) from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.polys.polytools import factor from sympy.solvers.recurr import rsolve, rsolve_hyper, rsolve_poly, rsolve_ratio from sympy.testing.pytest import raises, slow from sympy.abc import a, b y = Function('y') n, k = symbols('n,k', integer=True) C0, C1, C2 = symbols('C0,C1,C2') def test_rsolve_poly(): assert rsolve_poly([-1, -1, 1], 0, n) == 0 assert rsolve_poly([-1, -1, 1], 1, n) == -1 assert rsolve_poly([-1, n + 1], n, n) == 1 assert rsolve_poly([-1, 1], n, n) == C0 + (n**2 - n)/2 assert rsolve_poly([-n - 1, n], 1, n) == C1*n - 1 assert rsolve_poly([-4*n - 2, 1], 4*n + 1, n) == -1 assert rsolve_poly([-1, 1], n**5 + n**3, n) == \ C0 - n**3 / 2 - n**5 / 2 + n**2 / 6 + n**6 / 6 + 2*n**4 / 3 def test_rsolve_ratio(): solution = rsolve_ratio([-2*n**3 + n**2 + 2*n - 1, 2*n**3 + n**2 - 6*n, -2*n**3 - 11*n**2 - 18*n - 9, 2*n**3 + 13*n**2 + 22*n + 8], 0, n) assert solution in [ C1*((-2*n + 3)/(n**2 - 1))/3, (S.Half)*(C1*(-3 + 2*n)/(-1 + n**2)), (S.Half)*(C1*( 3 - 2*n)/( 1 - n**2)), (S.Half)*(C2*(-3 + 2*n)/(-1 + n**2)), (S.Half)*(C2*( 3 - 2*n)/( 1 - n**2)), ] def test_rsolve_hyper(): assert rsolve_hyper([-1, -1, 1], 0, n) in [ C0*(S.Half - S.Half*sqrt(5))**n + C1*(S.Half + S.Half*sqrt(5))**n, C1*(S.Half - S.Half*sqrt(5))**n + C0*(S.Half + S.Half*sqrt(5))**n, ] assert rsolve_hyper([n**2 - 2, -2*n - 1, 1], 0, n) in [ C0*rf(sqrt(2), n) + C1*rf(-sqrt(2), n), C1*rf(sqrt(2), n) + C0*rf(-sqrt(2), n), ] assert rsolve_hyper([n**2 - k, -2*n - 1, 1], 0, n) in [ C0*rf(sqrt(k), n) + C1*rf(-sqrt(k), n), C1*rf(sqrt(k), n) + C0*rf(-sqrt(k), n), ] assert rsolve_hyper( [2*n*(n + 1), -n**2 - 3*n + 2, n - 1], 0, n) == C1*factorial(n) + C0*2**n assert rsolve_hyper( [n + 2, -(2*n + 3)*(17*n**2 + 51*n + 39), n + 1], 0, n) == None assert rsolve_hyper([-n - 1, -1, 1], 0, n) == None assert rsolve_hyper([-1, 1], n, n).expand() == C0 + n**2/2 - n/2 assert rsolve_hyper([-1, 1], 1 + n, n).expand() == C0 + n**2/2 + n/2 assert rsolve_hyper([-1, 1], 3*(n + n**2), n).expand() == C0 + n**3 - n assert rsolve_hyper([-a, 1],0,n).expand() == C0*a**n assert rsolve_hyper([-a, 0, 1], 0, n).expand() == (-1)**n*C1*a**(n/2) + C0*a**(n/2) assert rsolve_hyper([1, 1, 1], 0, n).expand() == \ C0*(Rational(-1, 2) - sqrt(3)*I/2)**n + C1*(Rational(-1, 2) + sqrt(3)*I/2)**n assert rsolve_hyper([1, -2*n/a - 2/a, 1], 0, n) is None def recurrence_term(c, f): """Compute RHS of recurrence in f(n) with coefficients in c.""" return sum(c[i]*f.subs(n, n + i) for i in range(len(c))) def test_rsolve_bulk(): """Some bulk-generated tests.""" funcs = [ n, n + 1, n**2, n**3, n**4, n + n**2, 27*n + 52*n**2 - 3* n**3 + 12*n**4 - 52*n**5 ] coeffs = [ [-2, 1], [-2, -1, 1], [-1, 1, 1, -1, 1], [-n, 1], [n**2 - n + 12, 1] ] for p in funcs: # compute difference for c in coeffs: q = recurrence_term(c, p) if p.is_polynomial(n): assert rsolve_poly(c, q, n) == p # See issue 3956: #if p.is_hypergeometric(n): # assert rsolve_hyper(c, q, n) == p def test_rsolve(): f = y(n + 2) - y(n + 1) - y(n) h = sqrt(5)*(S.Half + S.Half*sqrt(5))**n \ - sqrt(5)*(S.Half - S.Half*sqrt(5))**n assert rsolve(f, y(n)) in [ C0*(S.Half - S.Half*sqrt(5))**n + C1*(S.Half + S.Half*sqrt(5))**n, C1*(S.Half - S.Half*sqrt(5))**n + C0*(S.Half + S.Half*sqrt(5))**n, ] assert rsolve(f, y(n), [0, 5]) == h assert rsolve(f, y(n), {0: 0, 1: 5}) == h assert rsolve(f, y(n), {y(0): 0, y(1): 5}) == h assert rsolve(y(n) - y(n - 1) - y(n - 2), y(n), [0, 5]) == h assert rsolve(Eq(y(n), y(n - 1) + y(n - 2)), y(n), [0, 5]) == h assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0 f = (n - 1)*y(n + 2) - (n**2 + 3*n - 2)*y(n + 1) + 2*n*(n + 1)*y(n) g = C1*factorial(n) + C0*2**n h = -3*factorial(n) + 3*2**n assert rsolve(f, y(n)) == g assert rsolve(f, y(n), []) == g assert rsolve(f, y(n), {}) == g assert rsolve(f, y(n), [0, 3]) == h assert rsolve(f, y(n), {0: 0, 1: 3}) == h assert rsolve(f, y(n), {y(0): 0, y(1): 3}) == h assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0 f = y(n) - y(n - 1) - 2 assert rsolve(f, y(n), {y(0): 0}) == 2*n assert rsolve(f, y(n), {y(0): 1}) == 2*n + 1 assert rsolve(f, y(n), {y(0): 0, y(1): 1}) is None assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0 f = 3*y(n - 1) - y(n) - 1 assert rsolve(f, y(n), {y(0): 0}) == -3**n/2 + S.Half assert rsolve(f, y(n), {y(0): 1}) == 3**n/2 + S.Half assert rsolve(f, y(n), {y(0): 2}) == 3*3**n/2 + S.Half assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0 f = y(n) - 1/n*y(n - 1) assert rsolve(f, y(n)) == C0/factorial(n) assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0 f = y(n) - 1/n*y(n - 1) - 1 assert rsolve(f, y(n)) is None f = 2*y(n - 1) + (1 - n)*y(n)/n assert rsolve(f, y(n), {y(1): 1}) == 2**(n - 1)*n assert rsolve(f, y(n), {y(1): 2}) == 2**(n - 1)*n*2 assert rsolve(f, y(n), {y(1): 3}) == 2**(n - 1)*n*3 assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0 f = (n - 1)*(n - 2)*y(n + 2) - (n + 1)*(n + 2)*y(n) assert rsolve(f, y(n), {y(3): 6, y(4): 24}) == n*(n - 1)*(n - 2) assert rsolve( f, y(n), {y(3): 6, y(4): -24}) == -n*(n - 1)*(n - 2)*(-1)**(n) assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0 assert rsolve(Eq(y(n + 1), a*y(n)), y(n), {y(1): a}).simplify() == a**n assert rsolve(y(n) - a*y(n-2),y(n), \ {y(1): sqrt(a)*(a + b), y(2): a*(a - b)}).simplify() == \ a**(n/2)*(-(-1)**n*b + a) f = (-16*n**2 + 32*n - 12)*y(n - 1) + (4*n**2 - 12*n + 9)*y(n) yn = rsolve(f, y(n), {y(1): binomial(2*n + 1, 3)}) sol = 2**(2*n)*n*(2*n - 1)**2*(2*n + 1)/12 assert factor(expand(yn, func=True)) == sol sol = rsolve(y(n) + a*(y(n + 1) + y(n - 1))/2, y(n)) Y = lambda i: sol.subs(n, i) assert (Y(n) + a*(Y(n + 1) + Y(n - 1))/2).expand().cancel() == 0 assert rsolve((k + 1)*y(k), y(k)) is None assert (rsolve((k + 1)*y(k) + (k + 3)*y(k + 1) + (k + 5)*y(k + 2), y(k)) is None) assert rsolve(y(n) + y(n + 1) + 2**n + 3**n, y(n)) == (-1)**n*C0 - 2**n/3 - 3**n/4 def test_rsolve_raises(): x = Function('x') raises(ValueError, lambda: rsolve(y(n) - y(k + 1), y(n))) raises(ValueError, lambda: rsolve(y(n) - y(n + 1), x(n))) raises(ValueError, lambda: rsolve(y(n) - x(n + 1), y(n))) raises(ValueError, lambda: rsolve(y(n) - sqrt(n)*y(n + 1), y(n))) raises(ValueError, lambda: rsolve(y(n) - y(n + 1), y(n), {x(0): 0})) raises(ValueError, lambda: rsolve(y(n) + y(n + 1) + 2**n + cos(n), y(n))) def test_issue_6844(): f = y(n + 2) - y(n + 1) + y(n)/4 assert rsolve(f, y(n)) == 2**(-n)*(C0 + C1*n) assert rsolve(f, y(n), {y(0): 0, y(1): 1}) == 2*2**(-n)*n def test_issue_18751(): r = Symbol('r', positive=True) theta = Symbol('theta', real=True) f = y(n) - 2 * r * cos(theta) * y(n - 1) + r**2 * y(n - 2) assert rsolve(f, y(n)) == \ C0*(r*(cos(theta) - I*Abs(sin(theta))))**n + C1*(r*(cos(theta) + I*Abs(sin(theta))))**n def test_constant_naming(): #issue 8697 assert rsolve(y(n+3) - y(n+2) - y(n+1) + y(n), y(n)) == (-1)**n*C0+C1+C2*n assert rsolve(y(n+3)+3*y(n+2)+3*y(n+1)+y(n), y(n)).expand() == C0*(-1)**n + (-1)**n*C1*n + (-1)**n*C2*n**2 assert rsolve(y(n) - 2*y(n - 3) + 5*y(n - 2) - 4*y(n - 1),y(n),[1,3,8]) == 3*2**n - n - 2 #issue 19630 assert rsolve(y(n+3) - 3*y(n+1) + 2*y(n), y(n), {y(1):0, y(2):8, y(3):-2}) == (-2)**n + 2*n @slow def test_issue_15751(): f = y(n) + 21*y(n + 1) - 273*y(n + 2) - 1092*y(n + 3) + 1820*y(n + 4) + 1092*y(n + 5) - 273*y(n + 6) - 21*y(n + 7) + y(n + 8) assert rsolve(f, y(n)) is not None def test_issue_17990(): f = -10*y(n) + 4*y(n + 1) + 6*y(n + 2) + 46*y(n + 3) sol = rsolve(f, y(n)) expected = C0*((86*18**(S(1)/3)/69 + (-12 + (-1 + sqrt(3)*I)*(290412 + 3036*sqrt(9165))**(S(1)/3))*(1 - sqrt(3)*I)*(24201 + 253*sqrt(9165))** (S(1)/3)/276)/((1 - sqrt(3)*I)*(24201 + 253*sqrt(9165))**(S(1)/3)) )**n + C1*((86*18**(S(1)/3)/69 + (-12 + (-1 - sqrt(3)*I)*(290412 + 3036 *sqrt(9165))**(S(1)/3))*(1 + sqrt(3)*I)*(24201 + 253*sqrt(9165))** (S(1)/3)/276)/((1 + sqrt(3)*I)*(24201 + 253*sqrt(9165))**(S(1)/3)) )**n + C2*(-43*18**(S(1)/3)/(69*(24201 + 253*sqrt(9165))**(S(1)/3)) - S(1)/23 + (290412 + 3036*sqrt(9165))**(S(1)/3)/138)**n assert sol == expected e = sol.subs({C0: 1, C1: 1, C2: 1, n: 1}).evalf() assert abs(e + 0.130434782608696) < 1e-13
6b1d9fd3998509db93bb48f7c06f646b5dcd29c00d345ecafd15f6bd74a5ff2b
from sympy.core.add import Add from sympy.core.mul import Mul from sympy.core.numbers import (Rational, oo, pi) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.matrices.dense import Matrix from sympy.ntheory.factor_ import factorint from sympy.simplify.powsimp import powsimp from sympy.core.function import _mexpand from sympy.core.sorting import default_sort_key, ordered from sympy.functions.elementary.trigonometric import sin from sympy.solvers.diophantine import diophantine from sympy.solvers.diophantine.diophantine import (diop_DN, diop_solve, diop_ternary_quadratic_normal, diop_general_pythagorean, diop_ternary_quadratic, diop_linear, diop_quadratic, diop_general_sum_of_squares, diop_general_sum_of_even_powers, descent, diop_bf_DN, divisible, equivalent, find_DN, ldescent, length, reconstruct, partition, power_representation, prime_as_sum_of_two_squares, square_factor, sum_of_four_squares, sum_of_three_squares, transformation_to_DN, transformation_to_normal, classify_diop, base_solution_linear, cornacchia, sqf_normal, gaussian_reduce, holzer, check_param, parametrize_ternary_quadratic, sum_of_powers, sum_of_squares, _diop_ternary_quadratic_normal, _nint_or_floor, _odd, _even, _remove_gcd, _can_do_sum_of_squares, DiophantineSolutionSet, GeneralPythagorean, BinaryQuadratic) from sympy.testing.pytest import slow, raises, XFAIL from sympy.utilities.iterables import ( signed_permutations) a, b, c, d, p, q, x, y, z, w, t, u, v, X, Y, Z = symbols( "a, b, c, d, p, q, x, y, z, w, t, u, v, X, Y, Z", integer=True) t_0, t_1, t_2, t_3, t_4, t_5, t_6 = symbols("t_:7", integer=True) m1, m2, m3 = symbols('m1:4', integer=True) n1 = symbols('n1', integer=True) def diop_simplify(eq): return _mexpand(powsimp(_mexpand(eq))) def test_input_format(): raises(TypeError, lambda: diophantine(sin(x))) raises(TypeError, lambda: diophantine(x/pi - 3)) def test_nosols(): # diophantine should sympify eq so that these are equivalent assert diophantine(3) == set() assert diophantine(S(3)) == set() def test_univariate(): assert diop_solve((x - 1)*(x - 2)**2) == {(1,), (2,)} assert diop_solve((x - 1)*(x - 2)) == {(1,), (2,)} def test_classify_diop(): raises(TypeError, lambda: classify_diop(x**2/3 - 1)) raises(ValueError, lambda: classify_diop(1)) raises(NotImplementedError, lambda: classify_diop(w*x*y*z - 1)) raises(NotImplementedError, lambda: classify_diop(x**3 + y**3 + z**4 - 90)) assert classify_diop(14*x**2 + 15*x - 42) == ( [x], {1: -42, x: 15, x**2: 14}, 'univariate') assert classify_diop(x*y + z) == ( [x, y, z], {x*y: 1, z: 1}, 'inhomogeneous_ternary_quadratic') assert classify_diop(x*y + z + w + x**2) == ( [w, x, y, z], {x*y: 1, w: 1, x**2: 1, z: 1}, 'inhomogeneous_general_quadratic') assert classify_diop(x*y + x*z + x**2 + 1) == ( [x, y, z], {x*y: 1, x*z: 1, x**2: 1, 1: 1}, 'inhomogeneous_general_quadratic') assert classify_diop(x*y + z + w + 42) == ( [w, x, y, z], {x*y: 1, w: 1, 1: 42, z: 1}, 'inhomogeneous_general_quadratic') assert classify_diop(x*y + z*w) == ( [w, x, y, z], {x*y: 1, w*z: 1}, 'homogeneous_general_quadratic') assert classify_diop(x*y**2 + 1) == ( [x, y], {x*y**2: 1, 1: 1}, 'cubic_thue') assert classify_diop(x**4 + y**4 + z**4 - (1 + 16 + 81)) == ( [x, y, z], {1: -98, x**4: 1, z**4: 1, y**4: 1}, 'general_sum_of_even_powers') assert classify_diop(x**2 + y**2 + z**2) == ( [x, y, z], {x**2: 1, y**2: 1, z**2: 1}, 'homogeneous_ternary_quadratic_normal') def test_linear(): assert diop_solve(x) == (0,) assert diop_solve(1*x) == (0,) assert diop_solve(3*x) == (0,) assert diop_solve(x + 1) == (-1,) assert diop_solve(2*x + 1) == (None,) assert diop_solve(2*x + 4) == (-2,) assert diop_solve(y + x) == (t_0, -t_0) assert diop_solve(y + x + 0) == (t_0, -t_0) assert diop_solve(y + x - 0) == (t_0, -t_0) assert diop_solve(0*x - y - 5) == (-5,) assert diop_solve(3*y + 2*x - 5) == (3*t_0 - 5, -2*t_0 + 5) assert diop_solve(2*x - 3*y - 5) == (3*t_0 - 5, 2*t_0 - 5) assert diop_solve(-2*x - 3*y - 5) == (3*t_0 + 5, -2*t_0 - 5) assert diop_solve(7*x + 5*y) == (5*t_0, -7*t_0) assert diop_solve(2*x + 4*y) == (2*t_0, -t_0) assert diop_solve(4*x + 6*y - 4) == (3*t_0 - 2, -2*t_0 + 2) assert diop_solve(4*x + 6*y - 3) == (None, None) assert diop_solve(0*x + 3*y - 4*z + 5) == (4*t_0 + 5, 3*t_0 + 5) assert diop_solve(4*x + 3*y - 4*z + 5) == (t_0, 8*t_0 + 4*t_1 + 5, 7*t_0 + 3*t_1 + 5) assert diop_solve(4*x + 3*y - 4*z + 5, None) == (0, 5, 5) assert diop_solve(4*x + 2*y + 8*z - 5) == (None, None, None) assert diop_solve(5*x + 7*y - 2*z - 6) == (t_0, -3*t_0 + 2*t_1 + 6, -8*t_0 + 7*t_1 + 18) assert diop_solve(3*x - 6*y + 12*z - 9) == (2*t_0 + 3, t_0 + 2*t_1, t_1) assert diop_solve(6*w + 9*x + 20*y - z) == (t_0, t_1, t_1 + t_2, 6*t_0 + 29*t_1 + 20*t_2) # to ignore constant factors, use diophantine raises(TypeError, lambda: diop_solve(x/2)) def test_quadratic_simple_hyperbolic_case(): # Simple Hyperbolic case: A = C = 0 and B != 0 assert diop_solve(3*x*y + 34*x - 12*y + 1) == \ {(-133, -11), (5, -57)} assert diop_solve(6*x*y + 2*x + 3*y + 1) == set() assert diop_solve(-13*x*y + 2*x - 4*y - 54) == {(27, 0)} assert diop_solve(-27*x*y - 30*x - 12*y - 54) == {(-14, -1)} assert diop_solve(2*x*y + 5*x + 56*y + 7) == {(-161, -3), (-47, -6), (-35, -12), (-29, -69), (-27, 64), (-21, 7), (-9, 1), (105, -2)} assert diop_solve(6*x*y + 9*x + 2*y + 3) == set() assert diop_solve(x*y + x + y + 1) == {(-1, t), (t, -1)} assert diophantine(48*x*y) def test_quadratic_elliptical_case(): # Elliptical case: B**2 - 4AC < 0 assert diop_solve(42*x**2 + 8*x*y + 15*y**2 + 23*x + 17*y - 4915) == {(-11, -1)} assert diop_solve(4*x**2 + 3*y**2 + 5*x - 11*y + 12) == set() assert diop_solve(x**2 + y**2 + 2*x + 2*y + 2) == {(-1, -1)} assert diop_solve(15*x**2 - 9*x*y + 14*y**2 - 23*x - 14*y - 4950) == {(-15, 6)} assert diop_solve(10*x**2 + 12*x*y + 12*y**2 - 34) == \ {(-1, -1), (-1, 2), (1, -2), (1, 1)} def test_quadratic_parabolic_case(): # Parabolic case: B**2 - 4AC = 0 assert check_solutions(8*x**2 - 24*x*y + 18*y**2 + 5*x + 7*y + 16) assert check_solutions(8*x**2 - 24*x*y + 18*y**2 + 6*x + 12*y - 6) assert check_solutions(8*x**2 + 24*x*y + 18*y**2 + 4*x + 6*y - 7) assert check_solutions(-4*x**2 + 4*x*y - y**2 + 2*x - 3) assert check_solutions(x**2 + 2*x*y + y**2 + 2*x + 2*y + 1) assert check_solutions(x**2 - 2*x*y + y**2 + 2*x + 2*y + 1) assert check_solutions(y**2 - 41*x + 40) def test_quadratic_perfect_square(): # B**2 - 4*A*C > 0 # B**2 - 4*A*C is a perfect square assert check_solutions(48*x*y) assert check_solutions(4*x**2 - 5*x*y + y**2 + 2) assert check_solutions(-2*x**2 - 3*x*y + 2*y**2 -2*x - 17*y + 25) assert check_solutions(12*x**2 + 13*x*y + 3*y**2 - 2*x + 3*y - 12) assert check_solutions(8*x**2 + 10*x*y + 2*y**2 - 32*x - 13*y - 23) assert check_solutions(4*x**2 - 4*x*y - 3*y- 8*x - 3) assert check_solutions(- 4*x*y - 4*y**2 - 3*y- 5*x - 10) assert check_solutions(x**2 - y**2 - 2*x - 2*y) assert check_solutions(x**2 - 9*y**2 - 2*x - 6*y) assert check_solutions(4*x**2 - 9*y**2 - 4*x - 12*y - 3) def test_quadratic_non_perfect_square(): # B**2 - 4*A*C is not a perfect square # Used check_solutions() since the solutions are complex expressions involving # square roots and exponents assert check_solutions(x**2 - 2*x - 5*y**2) assert check_solutions(3*x**2 - 2*y**2 - 2*x - 2*y) assert check_solutions(x**2 - x*y - y**2 - 3*y) assert check_solutions(x**2 - 9*y**2 - 2*x - 6*y) assert BinaryQuadratic(x**2 + y**2 + 2*x + 2*y + 2).solve() == {(-1, -1)} def test_issue_9106(): eq = -48 - 2*x*(3*x - 1) + y*(3*y - 1) v = (x, y) for sol in diophantine(eq): assert not diop_simplify(eq.xreplace(dict(zip(v, sol)))) def test_issue_18138(): eq = x**2 - x - y**2 v = (x, y) for sol in diophantine(eq): assert not diop_simplify(eq.xreplace(dict(zip(v, sol)))) @slow def test_quadratic_non_perfect_slow(): assert check_solutions(8*x**2 + 10*x*y - 2*y**2 - 32*x - 13*y - 23) # This leads to very large numbers. # assert check_solutions(5*x**2 - 13*x*y + y**2 - 4*x - 4*y - 15) assert check_solutions(-3*x**2 - 2*x*y + 7*y**2 - 5*x - 7) assert check_solutions(-4 - x + 4*x**2 - y - 3*x*y - 4*y**2) assert check_solutions(1 + 2*x + 2*x**2 + 2*y + x*y - 2*y**2) def test_DN(): # Most of the test cases were adapted from, # Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson, July 31, 2004. # https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf # others are verified using Wolfram Alpha. # Covers cases where D <= 0 or D > 0 and D is a square or N = 0 # Solutions are straightforward in these cases. assert diop_DN(3, 0) == [(0, 0)] assert diop_DN(-17, -5) == [] assert diop_DN(-19, 23) == [(2, 1)] assert diop_DN(-13, 17) == [(2, 1)] assert diop_DN(-15, 13) == [] assert diop_DN(0, 5) == [] assert diop_DN(0, 9) == [(3, t)] assert diop_DN(9, 0) == [(3*t, t)] assert diop_DN(16, 24) == [] assert diop_DN(9, 180) == [(18, 4)] assert diop_DN(9, -180) == [(12, 6)] assert diop_DN(7, 0) == [(0, 0)] # When equation is x**2 + y**2 = N # Solutions are interchangeable assert diop_DN(-1, 5) == [(2, 1), (1, 2)] assert diop_DN(-1, 169) == [(12, 5), (5, 12), (13, 0), (0, 13)] # D > 0 and D is not a square # N = 1 assert diop_DN(13, 1) == [(649, 180)] assert diop_DN(980, 1) == [(51841, 1656)] assert diop_DN(981, 1) == [(158070671986249, 5046808151700)] assert diop_DN(986, 1) == [(49299, 1570)] assert diop_DN(991, 1) == [(379516400906811930638014896080, 12055735790331359447442538767)] assert diop_DN(17, 1) == [(33, 8)] assert diop_DN(19, 1) == [(170, 39)] # N = -1 assert diop_DN(13, -1) == [(18, 5)] assert diop_DN(991, -1) == [] assert diop_DN(41, -1) == [(32, 5)] assert diop_DN(290, -1) == [(17, 1)] assert diop_DN(21257, -1) == [(13913102721304, 95427381109)] assert diop_DN(32, -1) == [] # |N| > 1 # Some tests were created using calculator at # http://www.numbertheory.org/php/patz.html assert diop_DN(13, -4) == [(3, 1), (393, 109), (36, 10)] # Source I referred returned (3, 1), (393, 109) and (-3, 1) as fundamental solutions # So (-3, 1) and (393, 109) should be in the same equivalent class assert equivalent(-3, 1, 393, 109, 13, -4) == True assert diop_DN(13, 27) == [(220, 61), (40, 11), (768, 213), (12, 3)] assert set(diop_DN(157, 12)) == {(13, 1), (10663, 851), (579160, 46222), (483790960, 38610722), (26277068347, 2097138361), (21950079635497, 1751807067011)} assert diop_DN(13, 25) == [(3245, 900)] assert diop_DN(192, 18) == [] assert diop_DN(23, 13) == [(-6, 1), (6, 1)] assert diop_DN(167, 2) == [(13, 1)] assert diop_DN(167, -2) == [] assert diop_DN(123, -2) == [(11, 1)] # One calculator returned [(11, 1), (-11, 1)] but both of these are in # the same equivalence class assert equivalent(11, 1, -11, 1, 123, -2) assert diop_DN(123, -23) == [(-10, 1), (10, 1)] assert diop_DN(0, 0, t) == [(0, t)] assert diop_DN(0, -1, t) == [] def test_bf_pell(): assert diop_bf_DN(13, -4) == [(3, 1), (-3, 1), (36, 10)] assert diop_bf_DN(13, 27) == [(12, 3), (-12, 3), (40, 11), (-40, 11)] assert diop_bf_DN(167, -2) == [] assert diop_bf_DN(1729, 1) == [(44611924489705, 1072885712316)] assert diop_bf_DN(89, -8) == [(9, 1), (-9, 1)] assert diop_bf_DN(21257, -1) == [(13913102721304, 95427381109)] assert diop_bf_DN(340, -4) == [(756, 41)] assert diop_bf_DN(-1, 0, t) == [(0, 0)] assert diop_bf_DN(0, 0, t) == [(0, t)] assert diop_bf_DN(4, 0, t) == [(2*t, t), (-2*t, t)] assert diop_bf_DN(3, 0, t) == [(0, 0)] assert diop_bf_DN(1, -2, t) == [] def test_length(): assert length(2, 1, 0) == 1 assert length(-2, 4, 5) == 3 assert length(-5, 4, 17) == 4 assert length(0, 4, 13) == 6 assert length(7, 13, 11) == 23 assert length(1, 6, 4) == 2 def is_pell_transformation_ok(eq): """ Test whether X*Y, X, or Y terms are present in the equation after transforming the equation using the transformation returned by transformation_to_pell(). If they are not present we are good. Moreover, coefficient of X**2 should be a divisor of coefficient of Y**2 and the constant term. """ A, B = transformation_to_DN(eq) u = (A*Matrix([X, Y]) + B)[0] v = (A*Matrix([X, Y]) + B)[1] simplified = diop_simplify(eq.subs(zip((x, y), (u, v)))) coeff = dict([reversed(t.as_independent(*[X, Y])) for t in simplified.args]) for term in [X*Y, X, Y]: if term in coeff.keys(): return False for term in [X**2, Y**2, 1]: if term not in coeff.keys(): coeff[term] = 0 if coeff[X**2] != 0: return divisible(coeff[Y**2], coeff[X**2]) and \ divisible(coeff[1], coeff[X**2]) return True def test_transformation_to_pell(): assert is_pell_transformation_ok(-13*x**2 - 7*x*y + y**2 + 2*x - 2*y - 14) assert is_pell_transformation_ok(-17*x**2 + 19*x*y - 7*y**2 - 5*x - 13*y - 23) assert is_pell_transformation_ok(x**2 - y**2 + 17) assert is_pell_transformation_ok(-x**2 + 7*y**2 - 23) assert is_pell_transformation_ok(25*x**2 - 45*x*y + 5*y**2 - 5*x - 10*y + 5) assert is_pell_transformation_ok(190*x**2 + 30*x*y + y**2 - 3*y - 170*x - 130) assert is_pell_transformation_ok(x**2 - 2*x*y -190*y**2 - 7*y - 23*x - 89) assert is_pell_transformation_ok(15*x**2 - 9*x*y + 14*y**2 - 23*x - 14*y - 4950) def test_find_DN(): assert find_DN(x**2 - 2*x - y**2) == (1, 1) assert find_DN(x**2 - 3*y**2 - 5) == (3, 5) assert find_DN(x**2 - 2*x*y - 4*y**2 - 7) == (5, 7) assert find_DN(4*x**2 - 8*x*y - y**2 - 9) == (20, 36) assert find_DN(7*x**2 - 2*x*y - y**2 - 12) == (8, 84) assert find_DN(-3*x**2 + 4*x*y -y**2) == (1, 0) assert find_DN(-13*x**2 - 7*x*y + y**2 + 2*x - 2*y -14) == (101, -7825480) def test_ldescent(): # Equations which have solutions u = ([(13, 23), (3, -11), (41, -113), (4, -7), (-7, 4), (91, -3), (1, 1), (1, -1), (4, 32), (17, 13), (123689, 1), (19, -570)]) for a, b in u: w, x, y = ldescent(a, b) assert a*x**2 + b*y**2 == w**2 assert ldescent(-1, -1) is None def test_diop_ternary_quadratic_normal(): assert check_solutions(234*x**2 - 65601*y**2 - z**2) assert check_solutions(23*x**2 + 616*y**2 - z**2) assert check_solutions(5*x**2 + 4*y**2 - z**2) assert check_solutions(3*x**2 + 6*y**2 - 3*z**2) assert check_solutions(x**2 + 3*y**2 - z**2) assert check_solutions(4*x**2 + 5*y**2 - z**2) assert check_solutions(x**2 + y**2 - z**2) assert check_solutions(16*x**2 + y**2 - 25*z**2) assert check_solutions(6*x**2 - y**2 + 10*z**2) assert check_solutions(213*x**2 + 12*y**2 - 9*z**2) assert check_solutions(34*x**2 - 3*y**2 - 301*z**2) assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2) def is_normal_transformation_ok(eq): A = transformation_to_normal(eq) X, Y, Z = A*Matrix([x, y, z]) simplified = diop_simplify(eq.subs(zip((x, y, z), (X, Y, Z)))) coeff = dict([reversed(t.as_independent(*[X, Y, Z])) for t in simplified.args]) for term in [X*Y, Y*Z, X*Z]: if term in coeff.keys(): return False return True def test_transformation_to_normal(): assert is_normal_transformation_ok(x**2 + 3*y**2 + z**2 - 13*x*y - 16*y*z + 12*x*z) assert is_normal_transformation_ok(x**2 + 3*y**2 - 100*z**2) assert is_normal_transformation_ok(x**2 + 23*y*z) assert is_normal_transformation_ok(3*y**2 - 100*z**2 - 12*x*y) assert is_normal_transformation_ok(x**2 + 23*x*y - 34*y*z + 12*x*z) assert is_normal_transformation_ok(z**2 + 34*x*y - 23*y*z + x*z) assert is_normal_transformation_ok(x**2 + y**2 + z**2 - x*y - y*z - x*z) assert is_normal_transformation_ok(x**2 + 2*y*z + 3*z**2) assert is_normal_transformation_ok(x*y + 2*x*z + 3*y*z) assert is_normal_transformation_ok(2*x*z + 3*y*z) def test_diop_ternary_quadratic(): assert check_solutions(2*x**2 + z**2 + y**2 - 4*x*y) assert check_solutions(x**2 - y**2 - z**2 - x*y - y*z) assert check_solutions(3*x**2 - x*y - y*z - x*z) assert check_solutions(x**2 - y*z - x*z) assert check_solutions(5*x**2 - 3*x*y - x*z) assert check_solutions(4*x**2 - 5*y**2 - x*z) assert check_solutions(3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z) assert check_solutions(8*x**2 - 12*y*z) assert check_solutions(45*x**2 - 7*y**2 - 8*x*y - z**2) assert check_solutions(x**2 - 49*y**2 - z**2 + 13*z*y -8*x*y) assert check_solutions(90*x**2 + 3*y**2 + 5*x*y + 2*z*y + 5*x*z) assert check_solutions(x**2 + 3*y**2 + z**2 - x*y - 17*y*z) assert check_solutions(x**2 + 3*y**2 + z**2 - x*y - 16*y*z + 12*x*z) assert check_solutions(x**2 + 3*y**2 + z**2 - 13*x*y - 16*y*z + 12*x*z) assert check_solutions(x*y - 7*y*z + 13*x*z) assert diop_ternary_quadratic_normal(x**2 + y**2 + z**2) == (None, None, None) assert diop_ternary_quadratic_normal(x**2 + y**2) is None raises(ValueError, lambda: _diop_ternary_quadratic_normal((x, y, z), {x*y: 1, x**2: 2, y**2: 3, z**2: 0})) eq = -2*x*y - 6*x*z + 7*y**2 - 3*y*z + 4*z**2 assert diop_ternary_quadratic(eq) == (7, 2, 0) assert diop_ternary_quadratic_normal(4*x**2 + 5*y**2 - z**2) == \ (1, 0, 2) assert diop_ternary_quadratic(x*y + 2*y*z) == \ (-2, 0, n1) eq = -5*x*y - 8*x*z - 3*y*z + 8*z**2 assert parametrize_ternary_quadratic(eq) == \ (8*p**2 - 3*p*q, -8*p*q + 8*q**2, 5*p*q) # this cannot be tested with diophantine because it will # factor into a product assert diop_solve(x*y + 2*y*z) == (-2*p*q, -n1*p**2 + p**2, p*q) def test_square_factor(): assert square_factor(1) == square_factor(-1) == 1 assert square_factor(0) == 1 assert square_factor(5) == square_factor(-5) == 1 assert square_factor(4) == square_factor(-4) == 2 assert square_factor(12) == square_factor(-12) == 2 assert square_factor(6) == 1 assert square_factor(18) == 3 assert square_factor(52) == 2 assert square_factor(49) == 7 assert square_factor(392) == 14 assert square_factor(factorint(-12)) == 2 def test_parametrize_ternary_quadratic(): assert check_solutions(x**2 + y**2 - z**2) assert check_solutions(x**2 + 2*x*y + z**2) assert check_solutions(234*x**2 - 65601*y**2 - z**2) assert check_solutions(3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z) assert check_solutions(x**2 - y**2 - z**2) assert check_solutions(x**2 - 49*y**2 - z**2 + 13*z*y - 8*x*y) assert check_solutions(8*x*y + z**2) assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2) assert check_solutions(236*x**2 - 225*y**2 - 11*x*y - 13*y*z - 17*x*z) assert check_solutions(90*x**2 + 3*y**2 + 5*x*y + 2*z*y + 5*x*z) assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2) def test_no_square_ternary_quadratic(): assert check_solutions(2*x*y + y*z - 3*x*z) assert check_solutions(189*x*y - 345*y*z - 12*x*z) assert check_solutions(23*x*y + 34*y*z) assert check_solutions(x*y + y*z + z*x) assert check_solutions(23*x*y + 23*y*z + 23*x*z) def test_descent(): u = ([(13, 23), (3, -11), (41, -113), (91, -3), (1, 1), (1, -1), (17, 13), (123689, 1), (19, -570)]) for a, b in u: w, x, y = descent(a, b) assert a*x**2 + b*y**2 == w**2 # the docstring warns against bad input, so these are expected results # - can't both be negative raises(TypeError, lambda: descent(-1, -3)) # A can't be zero unless B != 1 raises(ZeroDivisionError, lambda: descent(0, 3)) # supposed to be square-free raises(TypeError, lambda: descent(4, 3)) def test_diophantine(): assert check_solutions((x - y)*(y - z)*(z - x)) assert check_solutions((x - y)*(x**2 + y**2 - z**2)) assert check_solutions((x - 3*y + 7*z)*(x**2 + y**2 - z**2)) assert check_solutions(x**2 - 3*y**2 - 1) assert check_solutions(y**2 + 7*x*y) assert check_solutions(x**2 - 3*x*y + y**2) assert check_solutions(z*(x**2 - y**2 - 15)) assert check_solutions(x*(2*y - 2*z + 5)) assert check_solutions((x**2 - 3*y**2 - 1)*(x**2 - y**2 - 15)) assert check_solutions((x**2 - 3*y**2 - 1)*(y - 7*z)) assert check_solutions((x**2 + y**2 - z**2)*(x - 7*y - 3*z + 4*w)) # Following test case caused problems in parametric representation # But this can be solved by factoring out y. # No need to use methods for ternary quadratic equations. assert check_solutions(y**2 - 7*x*y + 4*y*z) assert check_solutions(x**2 - 2*x + 1) assert diophantine(x - y) == diophantine(Eq(x, y)) # 18196 eq = x**4 + y**4 - 97 assert diophantine(eq, permute=True) == diophantine(-eq, permute=True) assert diophantine(3*x*pi - 2*y*pi) == {(2*t_0, 3*t_0)} eq = x**2 + y**2 + z**2 - 14 base_sol = {(1, 2, 3)} assert diophantine(eq) == base_sol complete_soln = set(signed_permutations(base_sol.pop())) assert diophantine(eq, permute=True) == complete_soln assert diophantine(x**2 + x*Rational(15, 14) - 3) == set() # test issue 11049 eq = 92*x**2 - 99*y**2 - z**2 coeff = eq.as_coefficients_dict() assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \ {(9, 7, 51)} assert diophantine(eq) == {( 891*p**2 + 9*q**2, -693*p**2 - 102*p*q + 7*q**2, 5049*p**2 - 1386*p*q - 51*q**2)} eq = 2*x**2 + 2*y**2 - z**2 coeff = eq.as_coefficients_dict() assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \ {(1, 1, 2)} assert diophantine(eq) == {( 2*p**2 - q**2, -2*p**2 + 4*p*q - q**2, 4*p**2 - 4*p*q + 2*q**2)} eq = 411*x**2+57*y**2-221*z**2 coeff = eq.as_coefficients_dict() assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \ {(2021, 2645, 3066)} assert diophantine(eq) == \ {(115197*p**2 - 446641*q**2, -150765*p**2 + 1355172*p*q - 584545*q**2, 174762*p**2 - 301530*p*q + 677586*q**2)} eq = 573*x**2+267*y**2-984*z**2 coeff = eq.as_coefficients_dict() assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \ {(49, 233, 127)} assert diophantine(eq) == \ {(4361*p**2 - 16072*q**2, -20737*p**2 + 83312*p*q - 76424*q**2, 11303*p**2 - 41474*p*q + 41656*q**2)} # this produces factors during reconstruction eq = x**2 + 3*y**2 - 12*z**2 coeff = eq.as_coefficients_dict() assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \ {(0, 2, 1)} assert diophantine(eq) == \ {(24*p*q, 2*p**2 - 24*q**2, p**2 + 12*q**2)} # solvers have not been written for every type raises(NotImplementedError, lambda: diophantine(x*y**2 + 1)) # rational expressions assert diophantine(1/x) == set() assert diophantine(1/x + 1/y - S.Half) == {(6, 3), (-2, 1), (4, 4), (1, -2), (3, 6)} assert diophantine(x**2 + y**2 +3*x- 5, permute=True) == \ {(-1, 1), (-4, -1), (1, -1), (1, 1), (-4, 1), (-1, -1), (4, 1), (4, -1)} #test issue 18186 assert diophantine(y**4 + x**4 - 2**4 - 3**4, syms=(x, y), permute=True) == \ {(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)} assert diophantine(y**4 + x**4 - 2**4 - 3**4, syms=(y, x), permute=True) == \ {(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)} # issue 18122 assert check_solutions(x**2-y) assert check_solutions(y**2-x) assert diophantine((x**2-y), t) == {(t, t**2)} assert diophantine((y**2-x), t) == {(t**2, -t)} def test_general_pythagorean(): from sympy.abc import a, b, c, d, e assert check_solutions(a**2 + b**2 + c**2 - d**2) assert check_solutions(a**2 + 4*b**2 + 4*c**2 - d**2) assert check_solutions(9*a**2 + 4*b**2 + 4*c**2 - d**2) assert check_solutions(9*a**2 + 4*b**2 - 25*d**2 + 4*c**2 ) assert check_solutions(9*a**2 - 16*d**2 + 4*b**2 + 4*c**2) assert check_solutions(-e**2 + 9*a**2 + 4*b**2 + 4*c**2 + 25*d**2) assert check_solutions(16*a**2 - b**2 + 9*c**2 + d**2 + 25*e**2) assert GeneralPythagorean(a**2 + b**2 + c**2 - d**2).solve(parameters=[x, y, z]) == \ {(x**2 + y**2 - z**2, 2*x*z, 2*y*z, x**2 + y**2 + z**2)} def test_diop_general_sum_of_squares_quick(): for i in range(3, 10): assert check_solutions(sum(i**2 for i in symbols(':%i' % i)) - i) assert diop_general_sum_of_squares(x**2 + y**2 - 2) is None assert diop_general_sum_of_squares(x**2 + y**2 + z**2 + 2) == set() eq = x**2 + y**2 + z**2 - (1 + 4 + 9) assert diop_general_sum_of_squares(eq) == \ {(1, 2, 3)} eq = u**2 + v**2 + x**2 + y**2 + z**2 - 1313 assert len(diop_general_sum_of_squares(eq, 3)) == 3 # issue 11016 var = symbols(':5') + (symbols('6', negative=True),) eq = Add(*[i**2 for i in var]) - 112 base_soln = {(0, 1, 1, 5, 6, -7), (1, 1, 1, 3, 6, -8), (2, 3, 3, 4, 5, -7), (0, 1, 1, 1, 3, -10), (0, 0, 4, 4, 4, -8), (1, 2, 3, 3, 5, -8), (0, 1, 2, 3, 7, -7), (2, 2, 4, 4, 6, -6), (1, 1, 3, 4, 6, -7), (0, 2, 3, 3, 3, -9), (0, 0, 2, 2, 2, -10), (1, 1, 2, 3, 4, -9), (0, 1, 1, 2, 5, -9), (0, 0, 2, 6, 6, -6), (1, 3, 4, 5, 5, -6), (0, 2, 2, 2, 6, -8), (0, 3, 3, 3, 6, -7), (0, 2, 3, 5, 5, -7), (0, 1, 5, 5, 5, -6)} assert diophantine(eq) == base_soln assert len(diophantine(eq, permute=True)) == 196800 # handle negated squares with signsimp assert diophantine(12 - x**2 - y**2 - z**2) == {(2, 2, 2)} # diophantine handles simplification, so classify_diop should # not have to look for additional patterns that are removed # by diophantine eq = a**2 + b**2 + c**2 + d**2 - 4 raises(NotImplementedError, lambda: classify_diop(-eq)) def test_diop_partition(): for n in [8, 10]: for k in range(1, 8): for p in partition(n, k): assert len(p) == k assert [p for p in partition(3, 5)] == [] assert [list(p) for p in partition(3, 5, 1)] == [ [0, 0, 0, 0, 3], [0, 0, 0, 1, 2], [0, 0, 1, 1, 1]] assert list(partition(0)) == [()] assert list(partition(1, 0)) == [()] assert [list(i) for i in partition(3)] == [[1, 1, 1], [1, 2], [3]] def test_prime_as_sum_of_two_squares(): for i in [5, 13, 17, 29, 37, 41, 2341, 3557, 34841, 64601]: a, b = prime_as_sum_of_two_squares(i) assert a**2 + b**2 == i assert prime_as_sum_of_two_squares(7) is None ans = prime_as_sum_of_two_squares(800029) assert ans == (450, 773) and type(ans[0]) is int def test_sum_of_three_squares(): for i in [0, 1, 2, 34, 123, 34304595905, 34304595905394941, 343045959052344, 800, 801, 802, 803, 804, 805, 806]: a, b, c = sum_of_three_squares(i) assert a**2 + b**2 + c**2 == i assert sum_of_three_squares(7) is None assert sum_of_three_squares((4**5)*15) is None assert sum_of_three_squares(25) == (5, 0, 0) assert sum_of_three_squares(4) == (0, 0, 2) def test_sum_of_four_squares(): from sympy.core.random import randint # this should never fail n = randint(1, 100000000000000) assert sum(i**2 for i in sum_of_four_squares(n)) == n assert sum_of_four_squares(0) == (0, 0, 0, 0) assert sum_of_four_squares(14) == (0, 1, 2, 3) assert sum_of_four_squares(15) == (1, 1, 2, 3) assert sum_of_four_squares(18) == (1, 2, 2, 3) assert sum_of_four_squares(19) == (0, 1, 3, 3) assert sum_of_four_squares(48) == (0, 4, 4, 4) def test_power_representation(): tests = [(1729, 3, 2), (234, 2, 4), (2, 1, 2), (3, 1, 3), (5, 2, 2), (12352, 2, 4), (32760, 2, 3)] for test in tests: n, p, k = test f = power_representation(n, p, k) while True: try: l = next(f) assert len(l) == k chk_sum = 0 for l_i in l: chk_sum = chk_sum + l_i**p assert chk_sum == n except StopIteration: break assert list(power_representation(20, 2, 4, True)) == \ [(1, 1, 3, 3), (0, 0, 2, 4)] raises(ValueError, lambda: list(power_representation(1.2, 2, 2))) raises(ValueError, lambda: list(power_representation(2, 0, 2))) raises(ValueError, lambda: list(power_representation(2, 2, 0))) assert list(power_representation(-1, 2, 2)) == [] assert list(power_representation(1, 1, 1)) == [(1,)] assert list(power_representation(3, 2, 1)) == [] assert list(power_representation(4, 2, 1)) == [(2,)] assert list(power_representation(3**4, 4, 6, zeros=True)) == \ [(1, 2, 2, 2, 2, 2), (0, 0, 0, 0, 0, 3)] assert list(power_representation(3**4, 4, 5, zeros=False)) == [] assert list(power_representation(-2, 3, 2)) == [(-1, -1)] assert list(power_representation(-2, 4, 2)) == [] assert list(power_representation(0, 3, 2, True)) == [(0, 0)] assert list(power_representation(0, 3, 2, False)) == [] # when we are dealing with squares, do feasibility checks assert len(list(power_representation(4**10*(8*10 + 7), 2, 3))) == 0 # there will be a recursion error if these aren't recognized big = 2**30 for i in [13, 10, 7, 5, 4, 2, 1]: assert list(sum_of_powers(big, 2, big - i)) == [] def test_assumptions(): """ Test whether diophantine respects the assumptions. """ #Test case taken from the below so question regarding assumptions in diophantine module #https://stackoverflow.com/questions/23301941/how-can-i-declare-natural-symbols-with-sympy m, n = symbols('m n', integer=True, positive=True) diof = diophantine(n**2 + m*n - 500) assert diof == {(5, 20), (40, 10), (95, 5), (121, 4), (248, 2), (499, 1)} a, b = symbols('a b', integer=True, positive=False) diof = diophantine(a*b + 2*a + 3*b - 6) assert diof == {(-15, -3), (-9, -4), (-7, -5), (-6, -6), (-5, -8), (-4, -14)} def check_solutions(eq): """ Determines whether solutions returned by diophantine() satisfy the original equation. Hope to generalize this so we can remove functions like check_ternay_quadratic, check_solutions_normal, check_solutions() """ s = diophantine(eq) factors = Mul.make_args(eq) var = list(eq.free_symbols) var.sort(key=default_sort_key) while s: solution = s.pop() for f in factors: if diop_simplify(f.subs(zip(var, solution))) == 0: break else: return False return True def test_diopcoverage(): eq = (2*x + y + 1)**2 assert diop_solve(eq) == {(t_0, -2*t_0 - 1)} eq = 2*x**2 + 6*x*y + 12*x + 4*y**2 + 18*y + 18 assert diop_solve(eq) == {(t, -t - 3), (2*t - 3, -t)} assert diop_quadratic(x + y**2 - 3) == {(-t**2 + 3, -t)} assert diop_linear(x + y - 3) == (t_0, 3 - t_0) assert base_solution_linear(0, 1, 2, t=None) == (0, 0) ans = (3*t - 1, -2*t + 1) assert base_solution_linear(4, 8, 12, t) == ans assert base_solution_linear(4, 8, 12, t=None) == tuple(_.subs(t, 0) for _ in ans) assert cornacchia(1, 1, 20) is None assert cornacchia(1, 1, 5) == {(2, 1)} assert cornacchia(1, 2, 17) == {(3, 2)} raises(ValueError, lambda: reconstruct(4, 20, 1)) assert gaussian_reduce(4, 1, 3) == (1, 1) eq = -w**2 - x**2 - y**2 + z**2 assert diop_general_pythagorean(eq) == \ diop_general_pythagorean(-eq) == \ (m1**2 + m2**2 - m3**2, 2*m1*m3, 2*m2*m3, m1**2 + m2**2 + m3**2) assert len(check_param(S(3) + x/3, S(4) + x/2, S(2), [x])) == 0 assert len(check_param(Rational(3, 2), S(4) + x, S(2), [x])) == 0 assert len(check_param(S(4) + x, Rational(3, 2), S(2), [x])) == 0 assert _nint_or_floor(16, 10) == 2 assert _odd(1) == (not _even(1)) == True assert _odd(0) == (not _even(0)) == False assert _remove_gcd(2, 4, 6) == (1, 2, 3) raises(TypeError, lambda: _remove_gcd((2, 4, 6))) assert sqf_normal(2*3**2*5, 2*5*11, 2*7**2*11) == \ (11, 1, 5) # it's ok if these pass some day when the solvers are implemented raises(NotImplementedError, lambda: diophantine(x**2 + y**2 + x*y + 2*y*z - 12)) raises(NotImplementedError, lambda: diophantine(x**3 + y**2)) assert diop_quadratic(x**2 + y**2 - 1**2 - 3**4) == \ {(-9, -1), (-9, 1), (-1, -9), (-1, 9), (1, -9), (1, 9), (9, -1), (9, 1)} def test_holzer(): # if the input is good, don't let it diverge in holzer() # (but see test_fail_holzer below) assert holzer(2, 7, 13, 4, 79, 23) == (2, 7, 13) # None in uv condition met; solution is not Holzer reduced # so this will hopefully change but is here for coverage assert holzer(2, 6, 2, 1, 1, 10) == (2, 6, 2) raises(ValueError, lambda: holzer(2, 7, 14, 4, 79, 23)) @XFAIL def test_fail_holzer(): eq = lambda x, y, z: a*x**2 + b*y**2 - c*z**2 a, b, c = 4, 79, 23 x, y, z = xyz = 26, 1, 11 X, Y, Z = ans = 2, 7, 13 assert eq(*xyz) == 0 assert eq(*ans) == 0 assert max(a*x**2, b*y**2, c*z**2) <= a*b*c assert max(a*X**2, b*Y**2, c*Z**2) <= a*b*c h = holzer(x, y, z, a, b, c) assert h == ans # it would be nice to get the smaller soln def test_issue_9539(): assert diophantine(6*w + 9*y + 20*x - z) == \ {(t_0, t_1, t_1 + t_2, 6*t_0 + 29*t_1 + 9*t_2)} def test_issue_8943(): assert diophantine( 3*(x**2 + y**2 + z**2) - 14*(x*y + y*z + z*x)) == \ {(0, 0, 0)} def test_diop_sum_of_even_powers(): eq = x**4 + y**4 + z**4 - 2673 assert diop_solve(eq) == {(3, 6, 6), (2, 4, 7)} assert diop_general_sum_of_even_powers(eq, 2) == {(3, 6, 6), (2, 4, 7)} raises(NotImplementedError, lambda: diop_general_sum_of_even_powers(-eq, 2)) neg = symbols('neg', negative=True) eq = x**4 + y**4 + neg**4 - 2673 assert diop_general_sum_of_even_powers(eq) == {(-3, 6, 6)} assert diophantine(x**4 + y**4 + 2) == set() assert diop_general_sum_of_even_powers(x**4 + y**4 - 2, limit=0) == set() def test_sum_of_squares_powers(): tru = {(0, 0, 1, 1, 11), (0, 0, 5, 7, 7), (0, 1, 3, 7, 8), (0, 1, 4, 5, 9), (0, 3, 4, 7, 7), (0, 3, 5, 5, 8), (1, 1, 2, 6, 9), (1, 1, 6, 6, 7), (1, 2, 3, 3, 10), (1, 3, 4, 4, 9), (1, 5, 5, 6, 6), (2, 2, 3, 5, 9), (2, 3, 5, 6, 7), (3, 3, 4, 5, 8)} eq = u**2 + v**2 + x**2 + y**2 + z**2 - 123 ans = diop_general_sum_of_squares(eq, oo) # allow oo to be used assert len(ans) == 14 assert ans == tru raises(ValueError, lambda: list(sum_of_squares(10, -1))) assert list(sum_of_squares(-10, 2)) == [] assert list(sum_of_squares(2, 3)) == [] assert list(sum_of_squares(0, 3, True)) == [(0, 0, 0)] assert list(sum_of_squares(0, 3)) == [] assert list(sum_of_squares(4, 1)) == [(2,)] assert list(sum_of_squares(5, 1)) == [] assert list(sum_of_squares(50, 2)) == [(5, 5), (1, 7)] assert list(sum_of_squares(11, 5, True)) == [ (1, 1, 1, 2, 2), (0, 0, 1, 1, 3)] assert list(sum_of_squares(8, 8)) == [(1, 1, 1, 1, 1, 1, 1, 1)] assert [len(list(sum_of_squares(i, 5, True))) for i in range(30)] == [ 1, 1, 1, 1, 2, 2, 1, 1, 2, 2, 2, 2, 2, 3, 2, 1, 3, 3, 3, 3, 4, 3, 3, 2, 2, 4, 4, 4, 4, 5] assert [len(list(sum_of_squares(i, 5))) for i in range(30)] == [ 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 3] for i in range(30): s1 = set(sum_of_squares(i, 5, True)) assert not s1 or all(sum(j**2 for j in t) == i for t in s1) s2 = set(sum_of_squares(i, 5)) assert all(sum(j**2 for j in t) == i for t in s2) raises(ValueError, lambda: list(sum_of_powers(2, -1, 1))) raises(ValueError, lambda: list(sum_of_powers(2, 1, -1))) assert list(sum_of_powers(-2, 3, 2)) == [(-1, -1)] assert list(sum_of_powers(-2, 4, 2)) == [] assert list(sum_of_powers(2, 1, 1)) == [(2,)] assert list(sum_of_powers(2, 1, 3, True)) == [(0, 0, 2), (0, 1, 1)] assert list(sum_of_powers(5, 1, 2, True)) == [(0, 5), (1, 4), (2, 3)] assert list(sum_of_powers(6, 2, 2)) == [] assert list(sum_of_powers(3**5, 3, 1)) == [] assert list(sum_of_powers(3**6, 3, 1)) == [(9,)] and (9**3 == 3**6) assert list(sum_of_powers(2**1000, 5, 2)) == [] def test__can_do_sum_of_squares(): assert _can_do_sum_of_squares(3, -1) is False assert _can_do_sum_of_squares(-3, 1) is False assert _can_do_sum_of_squares(0, 1) assert _can_do_sum_of_squares(4, 1) assert _can_do_sum_of_squares(1, 2) assert _can_do_sum_of_squares(2, 2) assert _can_do_sum_of_squares(3, 2) is False def test_diophantine_permute_sign(): from sympy.abc import a, b, c, d, e eq = a**4 + b**4 - (2**4 + 3**4) base_sol = {(2, 3)} assert diophantine(eq) == base_sol complete_soln = set(signed_permutations(base_sol.pop())) assert diophantine(eq, permute=True) == complete_soln eq = a**2 + b**2 + c**2 + d**2 + e**2 - 234 assert len(diophantine(eq)) == 35 assert len(diophantine(eq, permute=True)) == 62000 soln = {(-1, -1), (-1, 2), (1, -2), (1, 1)} assert diophantine(10*x**2 + 12*x*y + 12*y**2 - 34, permute=True) == soln @XFAIL def test_not_implemented(): eq = x**2 + y**4 - 1**2 - 3**4 assert diophantine(eq, syms=[x, y]) == {(9, 1), (1, 3)} def test_issue_9538(): eq = x - 3*y + 2 assert diophantine(eq, syms=[y,x]) == {(t_0, 3*t_0 - 2)} raises(TypeError, lambda: diophantine(eq, syms={y, x})) def test_ternary_quadratic(): # solution with 3 parameters s = diophantine(2*x**2 + y**2 - 2*z**2) p, q, r = ordered(S(s).free_symbols) assert s == {( p**2 - 2*q**2, -2*p**2 + 4*p*q - 4*p*r - 4*q**2, p**2 - 4*p*q + 2*q**2 - 4*q*r)} # solution with Mul in solution s = diophantine(x**2 + 2*y**2 - 2*z**2) assert s == {(4*p*q, p**2 - 2*q**2, p**2 + 2*q**2)} # solution with no Mul in solution s = diophantine(2*x**2 + 2*y**2 - z**2) assert s == {(2*p**2 - q**2, -2*p**2 + 4*p*q - q**2, 4*p**2 - 4*p*q + 2*q**2)} # reduced form when parametrized s = diophantine(3*x**2 + 72*y**2 - 27*z**2) assert s == {(24*p**2 - 9*q**2, 6*p*q, 8*p**2 + 3*q**2)} assert parametrize_ternary_quadratic( 3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z) == ( 2*p**2 - 2*p*q - q**2, 2*p**2 + 2*p*q - q**2, 2*p**2 - 2*p*q + 3*q**2) assert parametrize_ternary_quadratic( 124*x**2 - 30*y**2 - 7729*z**2) == ( -1410*p**2 - 363263*q**2, 2700*p**2 + 30916*p*q - 695610*q**2, -60*p**2 + 5400*p*q + 15458*q**2) def test_diophantine_solution_set(): s1 = DiophantineSolutionSet([], []) assert set(s1) == set() assert s1.symbols == () assert s1.parameters == () raises(ValueError, lambda: s1.add((x,))) assert list(s1.dict_iterator()) == [] s2 = DiophantineSolutionSet([x, y], [t, u]) assert s2.symbols == (x, y) assert s2.parameters == (t, u) raises(ValueError, lambda: s2.add((1,))) s2.add((3, 4)) assert set(s2) == {(3, 4)} s2.update((3, 4), (-1, u)) assert set(s2) == {(3, 4), (-1, u)} raises(ValueError, lambda: s1.update(s2)) assert list(s2.dict_iterator()) == [{x: -1, y: u}, {x: 3, y: 4}] s3 = DiophantineSolutionSet([x, y, z], [t, u]) assert len(s3.parameters) == 2 s3.add((t**2 + u, t - u, 1)) assert set(s3) == {(t**2 + u, t - u, 1)} assert s3.subs(t, 2) == {(u + 4, 2 - u, 1)} assert s3(2) == {(u + 4, 2 - u, 1)} assert s3.subs({t: 7, u: 8}) == {(57, -1, 1)} assert s3(7, 8) == {(57, -1, 1)} assert s3.subs({t: 5}) == {(u + 25, 5 - u, 1)} assert s3(5) == {(u + 25, 5 - u, 1)} assert s3.subs(u, -3) == {(t**2 - 3, t + 3, 1)} assert s3(None, -3) == {(t**2 - 3, t + 3, 1)} assert s3.subs({t: 2, u: 8}) == {(12, -6, 1)} assert s3(2, 8) == {(12, -6, 1)} assert s3.subs({t: 5, u: -3}) == {(22, 8, 1)} assert s3(5, -3) == {(22, 8, 1)} raises(ValueError, lambda: s3.subs(x=1)) raises(ValueError, lambda: s3.subs(1, 2, 3)) raises(ValueError, lambda: s3.add(())) raises(ValueError, lambda: s3.add((1, 2, 3, 4))) raises(ValueError, lambda: s3.add((1, 2))) raises(ValueError, lambda: s3(1, 2, 3)) raises(TypeError, lambda: s3(t=1)) s4 = DiophantineSolutionSet([x, y], [t, u]) s4.add((t, 11*t)) s4.add((-t, 22*t)) assert s4(0, 0) == {(0, 0)} def test_quadratic_parameter_passing(): eq = -33*x*y + 3*y**2 solution = BinaryQuadratic(eq).solve(parameters=[t, u]) # test that parameters are passed all the way to the final solution assert solution == {(t, 11*t), (-t, 22*t)} assert solution(0, 0) == {(0, 0)}
f24f0c06de0b80893d4585adcd36636ce95e2b0ae97be4dd572519394dc67f56
from sympy.core.random import randint from sympy.core.function import Function from sympy.core.mul import Mul from sympy.core.numbers import (I, Rational, oo) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Dummy, symbols) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.hyperbolic import tanh from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import sin from sympy.polys.polytools import Poly from sympy.simplify.ratsimp import ratsimp from sympy.solvers.ode.subscheck import checkodesol from sympy.testing.pytest import slow from sympy.solvers.ode.riccati import (riccati_normal, riccati_inverse_normal, riccati_reduced, match_riccati, inverse_transform_poly, limit_at_inf, check_necessary_conds, val_at_inf, construct_c_case_1, construct_c_case_2, construct_c_case_3, construct_d_case_4, construct_d_case_5, construct_d_case_6, rational_laurent_series, solve_riccati) f = Function('f') x = symbols('x') # These are the functions used to generate the tests # SHOULD NOT BE USED DIRECTLY IN TESTS def rand_rational(maxint): return Rational(randint(-maxint, maxint), randint(1, maxint)) def rand_poly(x, degree, maxint): return Poly([rand_rational(maxint) for _ in range(degree+1)], x) def rand_rational_function(x, degree, maxint): degnum = randint(1, degree) degden = randint(1, degree) num = rand_poly(x, degnum, maxint) den = rand_poly(x, degden, maxint) while den == Poly(0, x): den = rand_poly(x, degden, maxint) return num / den def find_riccati_ode(ratfunc, x, yf): y = ratfunc yp = y.diff(x) q1 = rand_rational_function(x, 1, 3) q2 = rand_rational_function(x, 1, 3) while q2 == 0: q2 = rand_rational_function(x, 1, 3) q0 = ratsimp(yp - q1*y - q2*y**2) eq = Eq(yf.diff(), q0 + q1*yf + q2*yf**2) sol = Eq(yf, y) assert checkodesol(eq, sol) == (True, 0) return eq, q0, q1, q2 # Testing functions start def test_riccati_transformation(): """ This function tests the transformation of the solution of a Riccati ODE to the solution of its corresponding normal Riccati ODE. Each test case 4 values - 1. w - The solution to be transformed 2. b1 - The coefficient of f(x) in the ODE. 3. b2 - The coefficient of f(x)**2 in the ODE. 4. y - The solution to the normal Riccati ODE. """ tests = [ ( x/(x - 1), (x**2 + 7)/3*x, x, -x**2/(x - 1) - x*(x**2/3 + S(7)/3)/2 - 1/(2*x) ), ( (2*x + 3)/(2*x + 2), (3 - 3*x)/(x + 1), 5*x, -5*x*(2*x + 3)/(2*x + 2) - (3 - 3*x)/(Mul(2, x + 1, evaluate=False)) - 1/(2*x) ), ( -1/(2*x**2 - 1), 0, (2 - x)/(4*x - 2), (2 - x)/((4*x - 2)*(2*x**2 - 1)) - (4*x - 2)*(Mul(-4, 2 - x, evaluate=False)/(4*x - \ 2)**2 - 1/(4*x - 2))/(Mul(2, 2 - x, evaluate=False)) ), ( x, (8*x - 12)/(12*x + 9), x**3/(6*x - 9), -x**4/(6*x - 9) - (8*x - 12)/(Mul(2, 12*x + 9, evaluate=False)) - (6*x - 9)*(-6*x**3/(6*x \ - 9)**2 + 3*x**2/(6*x - 9))/(2*x**3) )] for w, b1, b2, y in tests: assert y == riccati_normal(w, x, b1, b2) assert w == riccati_inverse_normal(y, x, b1, b2).cancel() # Test bp parameter in riccati_inverse_normal tests = [ ( (-2*x - 1)/(2*x**2 + 2*x - 2), -2/x, (-x - 1)/(4*x), 8*x**2*(1/(4*x) + (-x - 1)/(4*x**2))/(-x - 1)**2 + 4/(-x - 1), -2*x*(-1/(4*x) - (-x - 1)/(4*x**2))/(-x - 1) - (-2*x - 1)*(-x - 1)/(4*x*(2*x**2 + 2*x \ - 2)) + 1/x ), ( 3/(2*x**2), -2/x, (-x - 1)/(4*x), 8*x**2*(1/(4*x) + (-x - 1)/(4*x**2))/(-x - 1)**2 + 4/(-x - 1), -2*x*(-1/(4*x) - (-x - 1)/(4*x**2))/(-x - 1) + 1/x - Mul(3, -x - 1, evaluate=False)/(8*x**3) )] for w, b1, b2, bp, y in tests: assert y == riccati_normal(w, x, b1, b2) assert w == riccati_inverse_normal(y, x, b1, b2, bp).cancel() def test_riccati_reduced(): """ This function tests the transformation of a Riccati ODE to its normal Riccati ODE. Each test case 2 values - 1. eq - A Riccati ODE. 2. normal_eq - The normal Riccati ODE of eq. """ tests = [ ( f(x).diff(x) - x**2 - x*f(x) - x*f(x)**2, f(x).diff(x) + f(x)**2 + x**3 - x**2/4 - 3/(4*x**2) ), ( 6*x/(2*x + 9) + f(x).diff(x) - (x + 1)*f(x)**2/x, -3*x**2*(1/x + (-x - 1)/x**2)**2/(4*(-x - 1)**2) + Mul(6, \ -x - 1, evaluate=False)/(2*x + 9) + f(x)**2 + f(x).diff(x) \ - (-1 + (x + 1)/x)/(x*(-x - 1)) ), ( f(x)**2 + f(x).diff(x) - (x - 1)*f(x)/(-x - S(1)/2), -(2*x - 2)**2/(4*(2*x + 1)**2) + (2*x - 2)/(2*x + 1)**2 + \ f(x)**2 + f(x).diff(x) - 1/(2*x + 1) ), ( f(x).diff(x) - f(x)**2/x, f(x)**2 + f(x).diff(x) + 1/(4*x**2) ), ( -3*(-x**2 - x + 1)/(x**2 + 6*x + 1) + f(x).diff(x) + f(x)**2/x, f(x)**2 + f(x).diff(x) + (3*x**2/(x**2 + 6*x + 1) + 3*x/(x**2 \ + 6*x + 1) - 3/(x**2 + 6*x + 1))/x + 1/(4*x**2) ), ( 6*x/(2*x + 9) + f(x).diff(x) - (x + 1)*f(x)/x, False ), ( f(x)*f(x).diff(x) - 1/x + f(x)/3 + f(x)**2/(x**2 - 2), False )] for eq, normal_eq in tests: assert normal_eq == riccati_reduced(eq, f, x) def test_match_riccati(): """ This function tests if an ODE is Riccati or not. Each test case has 5 values - 1. eq - The Riccati ODE. 2. match - Boolean indicating if eq is a Riccati ODE. 3. b0 - 4. b1 - Coefficient of f(x) in eq. 5. b2 - Coefficient of f(x)**2 in eq. """ tests = [ # Test Rational Riccati ODEs ( f(x).diff(x) - (405*x**3 - 882*x**2 - 78*x + 92)/(243*x**4 \ - 945*x**3 + 846*x**2 + 180*x - 72) - 2 - f(x)**2/(3*x + 1) \ - (S(1)/3 - x)*f(x)/(S(1)/3 - 3*x/2), True, 45*x**3/(27*x**4 - 105*x**3 + 94*x**2 + 20*x - 8) - 98*x**2/ \ (27*x**4 - 105*x**3 + 94*x**2 + 20*x - 8) - 26*x/(81*x**4 - \ 315*x**3 + 282*x**2 + 60*x - 24) + 2 + 92/(243*x**4 - 945*x**3 \ + 846*x**2 + 180*x - 72), Mul(-1, 2 - 6*x, evaluate=False)/(9*x - 2), 1/(3*x + 1) ), ( f(x).diff(x) + 4*x/27 - (x/3 - 1)*f(x)**2 - (2*x/3 + \ 1)*f(x)/(3*x + 2) - S(10)/27 - (265*x**2 + 423*x + 162) \ /(324*x**3 + 216*x**2), True, -4*x/27 + S(10)/27 + 3/(6*x**3 + 4*x**2) + 47/(36*x**2 \ + 24*x) + 265/(324*x + 216), Mul(-1, -2*x - 3, evaluate=False)/(9*x + 6), x/3 - 1 ), ( f(x).diff(x) - (304*x**5 - 745*x**4 + 631*x**3 - 876*x**2 \ + 198*x - 108)/(36*x**6 - 216*x**5 + 477*x**4 - 567*x**3 + \ 360*x**2 - 108*x) - S(17)/9 - (x - S(3)/2)*f(x)/(x/2 - \ S(3)/2) - (x/3 - 3)*f(x)**2/(3*x), True, 304*x**4/(36*x**5 - 216*x**4 + 477*x**3 - 567*x**2 + 360*x - \ 108) - 745*x**3/(36*x**5 - 216*x**4 + 477*x**3 - 567*x**2 + \ 360*x - 108) + 631*x**2/(36*x**5 - 216*x**4 + 477*x**3 - 567* \ x**2 + 360*x - 108) - 292*x/(12*x**5 - 72*x**4 + 159*x**3 - \ 189*x**2 + 120*x - 36) + S(17)/9 - 12/(4*x**6 - 24*x**5 + \ 53*x**4 - 63*x**3 + 40*x**2 - 12*x) + 22/(4*x**5 - 24*x**4 \ + 53*x**3 - 63*x**2 + 40*x - 12), Mul(-1, 3 - 2*x, evaluate=False)/(x - 3), Mul(-1, 9 - x, evaluate=False)/(9*x) ), # Test Non-Rational Riccati ODEs ( f(x).diff(x) - x**(S(3)/2)/(x**(S(1)/2) - 2) + x**2*f(x) + \ x*f(x)**2/(x**(S(3)/4)), False, 0, 0, 0 ), ( f(x).diff(x) - sin(x**2) + exp(x)*f(x) + log(x)*f(x)**2, False, 0, 0, 0 ), ( f(x).diff(x) - tanh(x + sqrt(x)) + f(x) + x**4*f(x)**2, False, 0, 0, 0 ), # Test Non-Riccati ODEs ( (1 - x**2)*f(x).diff(x, 2) - 2*x*f(x).diff(x) + 20*f(x), False, 0, 0, 0 ), ( f(x).diff(x) - x**2 + x**3*f(x) + (x**2/(x + 1))*f(x)**3, False, 0, 0, 0 ), ( f(x).diff(x)*f(x)**2 + (x**2 - 1)/(x**3 + 1)*f(x) + 1/(2*x \ + 3) + f(x)**2, False, 0, 0, 0 )] for eq, res, b0, b1, b2 in tests: match, funcs = match_riccati(eq, f, x) assert match == res if res: assert [b0, b1, b2] == funcs def test_val_at_inf(): """ This function tests the valuation of rational function at oo. Each test case has 3 values - 1. num - Numerator of rational function. 2. den - Denominator of rational function. 3. val_inf - Valuation of rational function at oo """ tests = [ # degree(denom) > degree(numer) ( Poly(10*x**3 + 8*x**2 - 13*x + 6, x), Poly(-13*x**10 - x**9 + 5*x**8 + 7*x**7 + 10*x**6 + 6*x**5 - 7*x**4 + 11*x**3 - 8*x**2 + 5*x + 13, x), 7 ), ( Poly(1, x), Poly(-9*x**4 + 3*x**3 + 15*x**2 - 6*x - 14, x), 4 ), # degree(denom) == degree(numer) ( Poly(-6*x**3 - 8*x**2 + 8*x - 6, x), Poly(-5*x**3 + 12*x**2 - 6*x - 9, x), 0 ), # degree(denom) < degree(numer) ( Poly(12*x**8 - 12*x**7 - 11*x**6 + 8*x**5 + 3*x**4 - x**3 + x**2 - 11*x, x), Poly(-14*x**2 + x, x), -6 ), ( Poly(5*x**6 + 9*x**5 - 11*x**4 - 9*x**3 + x**2 - 4*x + 4, x), Poly(15*x**4 + 3*x**3 - 8*x**2 + 15*x + 12, x), -2 )] for num, den, val in tests: assert val_at_inf(num, den, x) == val def test_necessary_conds(): """ This function tests the necessary conditions for a Riccati ODE to have a rational particular solution. """ # Valuation at Infinity is an odd negative integer assert check_necessary_conds(-3, [1, 2, 4]) == False # Valuation at Infinity is a positive integer lesser than 2 assert check_necessary_conds(1, [1, 2, 4]) == False # Multiplicity of a pole is an odd integer greater than 1 assert check_necessary_conds(2, [3, 1, 6]) == False # All values are correct assert check_necessary_conds(-10, [1, 2, 8, 12]) == True def test_inverse_transform_poly(): """ This function tests the substitution x -> 1/x in rational functions represented using Poly. """ fns = [ (15*x**3 - 8*x**2 - 2*x - 6)/(18*x + 6), (180*x**5 + 40*x**4 + 80*x**3 + 30*x**2 - 60*x - 80)/(180*x**3 - 150*x**2 + 75*x + 12), (-15*x**5 - 36*x**4 + 75*x**3 - 60*x**2 - 80*x - 60)/(80*x**4 + 60*x**3 + 60*x**2 + 60*x - 80), (60*x**7 + 24*x**6 - 15*x**5 - 20*x**4 + 30*x**2 + 100*x - 60)/(240*x**2 - 20*x - 30), (30*x**6 - 12*x**5 + 15*x**4 - 15*x**2 + 10*x + 60)/(3*x**10 - 45*x**9 + 15*x**5 + 15*x**4 - 5*x**3 \ + 15*x**2 + 45*x - 15) ] for f in fns: num, den = [Poly(e, x) for e in f.as_numer_denom()] num, den = inverse_transform_poly(num, den, x) assert f.subs(x, 1/x).cancel() == num/den def test_limit_at_inf(): """ This function tests the limit at oo of a rational function. Each test case has 3 values - 1. num - Numerator of rational function. 2. den - Denominator of rational function. 3. limit_at_inf - Limit of rational function at oo """ tests = [ # deg(denom) > deg(numer) ( Poly(-12*x**2 + 20*x + 32, x), Poly(32*x**3 + 72*x**2 + 3*x - 32, x), 0 ), # deg(denom) < deg(numer) ( Poly(1260*x**4 - 1260*x**3 - 700*x**2 - 1260*x + 1400, x), Poly(6300*x**3 - 1575*x**2 + 756*x - 540, x), oo ), # deg(denom) < deg(numer), one of the leading coefficients is negative ( Poly(-735*x**8 - 1400*x**7 + 1680*x**6 - 315*x**5 - 600*x**4 + 840*x**3 - 525*x**2 \ + 630*x + 3780, x), Poly(1008*x**7 - 2940*x**6 - 84*x**5 + 2940*x**4 - 420*x**3 + 1512*x**2 + 105*x + 168, x), -oo ), # deg(denom) == deg(numer) ( Poly(105*x**7 - 960*x**6 + 60*x**5 + 60*x**4 - 80*x**3 + 45*x**2 + 120*x + 15, x), Poly(735*x**7 + 525*x**6 + 720*x**5 + 720*x**4 - 8400*x**3 - 2520*x**2 + 2800*x + 280, x), S(1)/7 ), ( Poly(288*x**4 - 450*x**3 + 280*x**2 - 900*x - 90, x), Poly(607*x**4 + 840*x**3 - 1050*x**2 + 420*x + 420, x), S(288)/607 )] for num, den, lim in tests: assert limit_at_inf(num, den, x) == lim def test_construct_c_case_1(): """ This function tests the Case 1 in the step to calculate coefficients of c-vectors. Each test case has 4 values - 1. num - Numerator of the rational function a(x). 2. den - Denominator of the rational function a(x). 3. pole - Pole of a(x) for which c-vector is being calculated. 4. c - The c-vector for the pole. """ tests = [ ( Poly(-3*x**3 + 3*x**2 + 4*x - 5, x, extension=True), Poly(4*x**8 + 16*x**7 + 9*x**5 + 12*x**4 + 6*x**3 + 12*x**2, x, extension=True), S(0), [[S(1)/2 + sqrt(6)*I/6], [S(1)/2 - sqrt(6)*I/6]] ), ( Poly(1200*x**3 + 1440*x**2 + 816*x + 560, x, extension=True), Poly(128*x**5 - 656*x**4 + 1264*x**3 - 1125*x**2 + 385*x + 49, x, extension=True), S(7)/4, [[S(1)/2 + sqrt(16367978)/634], [S(1)/2 - sqrt(16367978)/634]] ), ( Poly(4*x + 2, x, extension=True), Poly(18*x**4 + (2 - 18*sqrt(3))*x**3 + (14 - 11*sqrt(3))*x**2 + (4 - 6*sqrt(3))*x \ + 8*sqrt(3) + 16, x, domain='QQ<sqrt(3)>'), (S(1) + sqrt(3))/2, [[S(1)/2 + sqrt(Mul(4, 2*sqrt(3) + 4, evaluate=False)/(19*sqrt(3) + 44) + 1)/2], \ [S(1)/2 - sqrt(Mul(4, 2*sqrt(3) + 4, evaluate=False)/(19*sqrt(3) + 44) + 1)/2]] )] for num, den, pole, c in tests: assert construct_c_case_1(num, den, x, pole) == c def test_construct_c_case_2(): """ This function tests the Case 2 in the step to calculate coefficients of c-vectors. Each test case has 5 values - 1. num - Numerator of the rational function a(x). 2. den - Denominator of the rational function a(x). 3. pole - Pole of a(x) for which c-vector is being calculated. 4. mul - The multiplicity of the pole. 5. c - The c-vector for the pole. """ tests = [ # Testing poles with multiplicity 2 ( Poly(1, x, extension=True), Poly((x - 1)**2*(x - 2), x, extension=True), 1, 2, [[-I*(-1 - I)/2], [I*(-1 + I)/2]] ), ( Poly(3*x**5 - 12*x**4 - 7*x**3 + 1, x, extension=True), Poly((3*x - 1)**2*(x + 2)**2, x, extension=True), S(1)/3, 2, [[-S(89)/98], [-S(9)/98]] ), # Testing poles with multiplicity 4 ( Poly(x**3 - x**2 + 4*x, x, extension=True), Poly((x - 2)**4*(x + 5)**2, x, extension=True), 2, 4, [[7*sqrt(3)*(S(60)/343 - 4*sqrt(3)/7)/12, 2*sqrt(3)/7], \ [-7*sqrt(3)*(S(60)/343 + 4*sqrt(3)/7)/12, -2*sqrt(3)/7]] ), ( Poly(3*x**5 + x**4 + 3, x, extension=True), Poly((4*x + 1)**4*(x + 2), x, extension=True), -S(1)/4, 4, [[128*sqrt(439)*(-sqrt(439)/128 - S(55)/14336)/439, sqrt(439)/256], \ [-128*sqrt(439)*(sqrt(439)/128 - S(55)/14336)/439, -sqrt(439)/256]] ), # Testing poles with multiplicity 6 ( Poly(x**3 + 2, x, extension=True), Poly((3*x - 1)**6*(x**2 + 1), x, extension=True), S(1)/3, 6, [[27*sqrt(66)*(-sqrt(66)/54 - S(131)/267300)/22, -2*sqrt(66)/1485, sqrt(66)/162], \ [-27*sqrt(66)*(sqrt(66)/54 - S(131)/267300)/22, 2*sqrt(66)/1485, -sqrt(66)/162]] ), ( Poly(x**2 + 12, x, extension=True), Poly((x - sqrt(2))**6, x, extension=True), sqrt(2), 6, [[sqrt(14)*(S(6)/7 - 3*sqrt(14))/28, sqrt(7)/7, sqrt(14)], \ [-sqrt(14)*(S(6)/7 + 3*sqrt(14))/28, -sqrt(7)/7, -sqrt(14)]] )] for num, den, pole, mul, c in tests: assert construct_c_case_2(num, den, x, pole, mul) == c def test_construct_c_case_3(): """ This function tests the Case 3 in the step to calculate coefficients of c-vectors. """ assert construct_c_case_3() == [[1]] def test_construct_d_case_4(): """ This function tests the Case 4 in the step to calculate coefficients of the d-vector. Each test case has 4 values - 1. num - Numerator of the rational function a(x). 2. den - Denominator of the rational function a(x). 3. mul - Multiplicity of oo as a pole. 4. d - The d-vector. """ tests = [ # Tests with multiplicity at oo = 2 ( Poly(-x**5 - 2*x**4 + 4*x**3 + 2*x + 5, x, extension=True), Poly(9*x**3 - 2*x**2 + 10*x - 2, x, extension=True), 2, [[10*I/27, I/3, -3*I*(S(158)/243 - I/3)/2], \ [-10*I/27, -I/3, 3*I*(S(158)/243 + I/3)/2]] ), ( Poly(-x**6 + 9*x**5 + 5*x**4 + 6*x**3 + 5*x**2 + 6*x + 7, x, extension=True), Poly(x**4 + 3*x**3 + 12*x**2 - x + 7, x, extension=True), 2, [[-6*I, I, -I*(17 - I)/2], [6*I, -I, I*(17 + I)/2]] ), # Tests with multiplicity at oo = 4 ( Poly(-2*x**6 - x**5 - x**4 - 2*x**3 - x**2 - 3*x - 3, x, extension=True), Poly(3*x**2 + 10*x + 7, x, extension=True), 4, [[269*sqrt(6)*I/288, -17*sqrt(6)*I/36, sqrt(6)*I/3, -sqrt(6)*I*(S(16969)/2592 \ - 2*sqrt(6)*I/3)/4], [-269*sqrt(6)*I/288, 17*sqrt(6)*I/36, -sqrt(6)*I/3, \ sqrt(6)*I*(S(16969)/2592 + 2*sqrt(6)*I/3)/4]] ), ( Poly(-3*x**5 - 3*x**4 - 3*x**3 - x**2 - 1, x, extension=True), Poly(12*x - 2, x, extension=True), 4, [[41*I/192, 7*I/24, I/2, -I*(-S(59)/6912 - I)], \ [-41*I/192, -7*I/24, -I/2, I*(-S(59)/6912 + I)]] ), # Tests with multiplicity at oo = 4 ( Poly(-x**7 - x**5 - x**4 - x**2 - x, x, extension=True), Poly(x + 2, x, extension=True), 6, [[-5*I/2, 2*I, -I, I, -I*(-9 - 3*I)/2], [5*I/2, -2*I, I, -I, I*(-9 + 3*I)/2]] ), ( Poly(-x**7 - x**6 - 2*x**5 - 2*x**4 - x**3 - x**2 + 2*x - 2, x, extension=True), Poly(2*x - 2, x, extension=True), 6, [[3*sqrt(2)*I/4, 3*sqrt(2)*I/4, sqrt(2)*I/2, sqrt(2)*I/2, -sqrt(2)*I*(-S(7)/8 - \ 3*sqrt(2)*I/2)/2], [-3*sqrt(2)*I/4, -3*sqrt(2)*I/4, -sqrt(2)*I/2, -sqrt(2)*I/2, \ sqrt(2)*I*(-S(7)/8 + 3*sqrt(2)*I/2)/2]] )] for num, den, mul, d in tests: ser = rational_laurent_series(num, den, x, oo, mul, 1) assert construct_d_case_4(ser, mul//2) == d def test_construct_d_case_5(): """ This function tests the Case 5 in the step to calculate coefficients of the d-vector. Each test case has 3 values - 1. num - Numerator of the rational function a(x). 2. den - Denominator of the rational function a(x). 3. d - The d-vector. """ tests = [ ( Poly(2*x**3 + x**2 + x - 2, x, extension=True), Poly(9*x**3 + 5*x**2 + 2*x - 1, x, extension=True), [[sqrt(2)/3, -sqrt(2)/108], [-sqrt(2)/3, sqrt(2)/108]] ), ( Poly(3*x**5 + x**4 - x**3 + x**2 - 2*x - 2, x, domain='ZZ'), Poly(9*x**5 + 7*x**4 + 3*x**3 + 2*x**2 + 5*x + 7, x, domain='ZZ'), [[sqrt(3)/3, -2*sqrt(3)/27], [-sqrt(3)/3, 2*sqrt(3)/27]] ), ( Poly(x**2 - x + 1, x, domain='ZZ'), Poly(3*x**2 + 7*x + 3, x, domain='ZZ'), [[sqrt(3)/3, -5*sqrt(3)/9], [-sqrt(3)/3, 5*sqrt(3)/9]] )] for num, den, d in tests: # Multiplicity of oo is 0 ser = rational_laurent_series(num, den, x, oo, 0, 1) assert construct_d_case_5(ser) == d def test_construct_d_case_6(): """ This function tests the Case 6 in the step to calculate coefficients of the d-vector. Each test case has 3 values - 1. num - Numerator of the rational function a(x). 2. den - Denominator of the rational function a(x). 3. d - The d-vector. """ tests = [ ( Poly(-2*x**2 - 5, x, domain='ZZ'), Poly(4*x**4 + 2*x**2 + 10*x + 2, x, domain='ZZ'), [[S(1)/2 + I/2], [S(1)/2 - I/2]] ), ( Poly(-2*x**3 - 4*x**2 - 2*x - 5, x, domain='ZZ'), Poly(x**6 - x**5 + 2*x**4 - 4*x**3 - 5*x**2 - 5*x + 9, x, domain='ZZ'), [[1], [0]] ), ( Poly(-5*x**3 + x**2 + 11*x + 12, x, domain='ZZ'), Poly(6*x**8 - 26*x**7 - 27*x**6 - 10*x**5 - 44*x**4 - 46*x**3 - 34*x**2 \ - 27*x - 42, x, domain='ZZ'), [[1], [0]] )] for num, den, d in tests: assert construct_d_case_6(num, den, x) == d def test_rational_laurent_series(): """ This function tests the computation of coefficients of Laurent series of a rational function. Each test case has 5 values - 1. num - Numerator of the rational function. 2. den - Denominator of the rational function. 3. x0 - Point about which Laurent series is to be calculated. 4. mul - Multiplicity of x0 if x0 is a pole of the rational function (0 otherwise). 5. n - Number of terms upto which the series is to be calcuated. """ tests = [ # Laurent series about simple pole (Multiplicity = 1) ( Poly(x**2 - 3*x + 9, x, extension=True), Poly(x**2 - x, x, extension=True), S(1), 1, 6, {1: 7, 0: -8, -1: 9, -2: -9, -3: 9, -4: -9} ), # Laurent series about multiple pole (Multiplicty > 1) ( Poly(64*x**3 - 1728*x + 1216, x, extension=True), Poly(64*x**4 - 80*x**3 - 831*x**2 + 1809*x - 972, x, extension=True), S(9)/8, 2, 3, {0: S(32177152)/46521675, 2: S(1019)/984, -1: S(11947565056)/28610830125, \ 1: S(209149)/75645} ), ( Poly(1, x, extension=True), Poly(x**5 + (-4*sqrt(2) - 1)*x**4 + (4*sqrt(2) + 12)*x**3 + (-12 - 8*sqrt(2))*x**2 \ + (4 + 8*sqrt(2))*x - 4, x, extension=True), sqrt(2), 4, 6, {4: 1 + sqrt(2), 3: -3 - 2*sqrt(2), 2: Mul(-1, -3 - 2*sqrt(2), evaluate=False)/(-1 \ + sqrt(2)), 1: (-3 - 2*sqrt(2))/(-1 + sqrt(2))**2, 0: Mul(-1, -3 - 2*sqrt(2), evaluate=False \ )/(-1 + sqrt(2))**3, -1: (-3 - 2*sqrt(2))/(-1 + sqrt(2))**4} ), # Laurent series about oo ( Poly(x**5 - 4*x**3 + 6*x**2 + 10*x - 13, x, extension=True), Poly(x**2 - 5, x, extension=True), oo, 3, 6, {3: 1, 2: 0, 1: 1, 0: 6, -1: 15, -2: 17} ), # Laurent series at x0 where x0 is not a pole of the function # Using multiplicity as 0 (as x0 will not be a pole) ( Poly(3*x**3 + 6*x**2 - 2*x + 5, x, extension=True), Poly(9*x**4 - x**3 - 3*x**2 + 4*x + 4, x, extension=True), S(2)/5, 0, 1, {0: S(3345)/3304, -1: S(399325)/2729104, -2: S(3926413375)/4508479808, \ -3: S(-5000852751875)/1862002160704, -4: S(-6683640101653125)/6152055138966016} ), ( Poly(-7*x**2 + 2*x - 4, x, extension=True), Poly(7*x**5 + 9*x**4 + 8*x**3 + 3*x**2 + 6*x + 9, x, extension=True), oo, 0, 6, {0: 0, -2: 0, -5: -S(71)/49, -1: 0, -3: -1, -4: S(11)/7} )] for num, den, x0, mul, n, ser in tests: assert ser == rational_laurent_series(num, den, x, x0, mul, n) def check_dummy_sol(eq, solse, dummy_sym): """ Helper function to check if actual solution matches expected solution if actual solution contains dummy symbols. """ if isinstance(eq, Eq): eq = eq.lhs - eq.rhs _, funcs = match_riccati(eq, f, x) sols = solve_riccati(f(x), x, *funcs) C1 = Dummy('C1') sols = [sol.subs(C1, dummy_sym) for sol in sols] assert all([x[0] for x in checkodesol(eq, sols)]) assert all([s1.dummy_eq(s2, dummy_sym) for s1, s2 in zip(sols, solse)]) def test_solve_riccati(): """ This function tests the computation of rational particular solutions for a Riccati ODE. Each test case has 2 values - 1. eq - Riccati ODE to be solved. 2. sol - Expected solution to the equation. Some examples have been taken from the paper - "Statistical Investigation of First-Order Algebraic ODEs and their Rational General Solutions" by Georg Grasegger, N. Thieu Vo, Franz Winkler https://www3.risc.jku.at/publications/download/risc_5197/RISCReport15-19.pdf """ C0 = Dummy('C0') # Type: 1st Order Rational Riccati, dy/dx = a + b*y + c*y**2, # a, b, c are rational functions of x tests = [ # a(x) is a constant ( Eq(f(x).diff(x) + f(x)**2 - 2, 0), [Eq(f(x), sqrt(2)), Eq(f(x), -sqrt(2))] ), # a(x) is a constant ( f(x)**2 + f(x).diff(x) + 4*f(x)/x + 2/x**2, [Eq(f(x), (-2*C0 - x)/(C0*x + x**2))] ), # a(x) is a constant ( 2*x**2*f(x).diff(x) - x*(4*f(x) + f(x).diff(x) - 4) + (f(x) - 1)*f(x), [Eq(f(x), (C0 + 2*x**2)/(C0 + x))] ), # Pole with multiplicity 1 ( Eq(f(x).diff(x), -f(x)**2 - 2/(x**3 - x**2)), [Eq(f(x), 1/(x**2 - x))] ), # One pole of multiplicity 2 ( x**2 - (2*x + 1/x)*f(x) + f(x)**2 + f(x).diff(x), [Eq(f(x), (C0*x + x**3 + 2*x)/(C0 + x**2)), Eq(f(x), x)] ), ( x**4*f(x).diff(x) + x**2 - x*(2*f(x)**2 + f(x).diff(x)) + f(x), [Eq(f(x), (C0*x**2 + x)/(C0 + x**2)), Eq(f(x), x**2)] ), # Multiple poles of multiplicity 2 ( -f(x)**2 + f(x).diff(x) + (15*x**2 - 20*x + 7)/((x - 1)**2*(2*x \ - 1)**2), [Eq(f(x), (9*C0*x - 6*C0 - 15*x**5 + 60*x**4 - 94*x**3 + 72*x**2 \ - 30*x + 6)/(6*C0*x**2 - 9*C0*x + 3*C0 + 6*x**6 - 29*x**5 + \ 57*x**4 - 58*x**3 + 30*x**2 - 6*x)), Eq(f(x), (3*x - 2)/(2*x**2 \ - 3*x + 1))] ), # Regression: Poles with even multiplicity > 2 fixed ( f(x)**2 + f(x).diff(x) - (4*x**6 - 8*x**5 + 12*x**4 + 4*x**3 + \ 7*x**2 - 20*x + 4)/(4*x**4), [Eq(f(x), (2*x**5 - 2*x**4 - x**3 + 4*x**2 + 3*x - 2)/(2*x**4 \ - 2*x**2))] ), # Regression: Poles with even multiplicity > 2 fixed ( Eq(f(x).diff(x), (-x**6 + 15*x**4 - 40*x**3 + 45*x**2 - 24*x + 4)/\ (x**12 - 12*x**11 + 66*x**10 - 220*x**9 + 495*x**8 - 792*x**7 + 924*x**6 - \ 792*x**5 + 495*x**4 - 220*x**3 + 66*x**2 - 12*x + 1) + f(x)**2 + f(x)), [Eq(f(x), 1/(x**6 - 6*x**5 + 15*x**4 - 20*x**3 + 15*x**2 - 6*x + 1))] ), # More than 2 poles with multiplicity 2 # Regression: Fixed mistake in necessary conditions ( Eq(f(x).diff(x), x*f(x) + 2*x + (3*x - 2)*f(x)**2/(4*x + 2) + \ (8*x**2 - 7*x + 26)/(16*x**3 - 24*x**2 + 8) - S(3)/2), [Eq(f(x), (1 - 4*x)/(2*x - 2))] ), # Regression: Fixed mistake in necessary conditions ( Eq(f(x).diff(x), (-12*x**2 - 48*x - 15)/(24*x**3 - 40*x**2 + 8*x + 8) \ + 3*f(x)**2/(6*x + 2)), [Eq(f(x), (2*x + 1)/(2*x - 2))] ), # Imaginary poles ( f(x).diff(x) + (3*x**2 + 1)*f(x)**2/x + (6*x**2 - x + 3)*f(x)/(x*(x \ - 1)) + (3*x**2 - 2*x + 2)/(x*(x - 1)**2), [Eq(f(x), (-C0 - x**3 + x**2 - 2*x)/(C0*x - C0 + x**4 - x**3 + x**2 \ - x)), Eq(f(x), -1/(x - 1))], ), # Imaginary coefficients in equation ( f(x).diff(x) - 2*I*(f(x)**2 + 1)/x, [Eq(f(x), (-I*C0 + I*x**4)/(C0 + x**4)), Eq(f(x), -I)] ), # Regression: linsolve returning empty solution # Large value of m (> 10) ( Eq(f(x).diff(x), x*f(x)/(S(3)/2 - 2*x) + (x/2 - S(1)/3)*f(x)**2/\ (2*x/3 - S(1)/2) - S(5)/4 + (281*x**2 - 1260*x + 756)/(16*x**3 - 12*x**2)), [Eq(f(x), (9 - x)/x), Eq(f(x), (40*x**14 + 28*x**13 + 420*x**12 + 2940*x**11 + \ 18480*x**10 + 103950*x**9 + 519750*x**8 + 2286900*x**7 + 8731800*x**6 + 28378350*\ x**5 + 76403250*x**4 + 163721250*x**3 + 261954000*x**2 + 278326125*x + 147349125)/\ ((24*x**14 + 140*x**13 + 840*x**12 + 4620*x**11 + 23100*x**10 + 103950*x**9 + \ 415800*x**8 + 1455300*x**7 + 4365900*x**6 + 10914750*x**5 + 21829500*x**4 + 32744250\ *x**3 + 32744250*x**2 + 16372125*x)))] ), # Regression: Fixed bug due to a typo in paper ( Eq(f(x).diff(x), 18*x**3 + 18*x**2 + (-x/2 - S(1)/2)*f(x)**2 + 6), [Eq(f(x), 6*x)] ), # Regression: Fixed bug due to a typo in paper ( Eq(f(x).diff(x), -3*x**3/4 + 15*x/2 + (x/3 - S(4)/3)*f(x)**2 \ + 9 + (1 - x)*f(x)/x + 3/x), [Eq(f(x), -3*x/2 - 3)] )] for eq, sol in tests: check_dummy_sol(eq, sol, C0) @slow def test_solve_riccati_slow(): """ This function tests the computation of rational particular solutions for a Riccati ODE. Each test case has 2 values - 1. eq - Riccati ODE to be solved. 2. sol - Expected solution to the equation. """ C0 = Dummy('C0') tests = [ # Very large values of m (989 and 991) ( Eq(f(x).diff(x), (1 - x)*f(x)/(x - 3) + (2 - 12*x)*f(x)**2/(2*x - 9) + \ (54924*x**3 - 405264*x**2 + 1084347*x - 1087533)/(8*x**4 - 132*x**3 + 810*x**2 - \ 2187*x + 2187) + 495), [Eq(f(x), (18*x + 6)/(2*x - 9))] )] for eq, sol in tests: check_dummy_sol(eq, sol, C0)
569c4466ce696cebc1e3f071fe3c8d81d57e96ee0d561cf2df118b2e75e41105
from sympy.core.function import (Derivative, Function, Subs, diff) from sympy.core.numbers import (I, Rational, pi) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import (im, re) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.hyperbolic import acosh from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (atan2, cos, sin, tan) from sympy.integrals.integrals import Integral from sympy.polys.polytools import Poly from sympy.series.order import O from sympy.simplify.radsimp import collect from sympy.solvers.ode import (classify_ode, homogeneous_order, dsolve) from sympy.solvers.ode.subscheck import checkodesol from sympy.solvers.ode.ode import (classify_sysode, constant_renumber, constantsimp, get_numbered_constants, solve_ics) from sympy.solvers.ode.nonhomogeneous import _undetermined_coefficients_match from sympy.solvers.ode.single import LinearCoefficients from sympy.solvers.deutils import ode_order from sympy.testing.pytest import XFAIL, raises, slow from sympy.utilities.misc import filldedent C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10 = symbols('C0:11') u, x, y, z = symbols('u,x:z', real=True) f = Function('f') g = Function('g') h = Function('h') # Note: Examples which were specifically testing Single ODE solver are moved to test_single.py # and all the system of ode examples are moved to test_systems.py # Note: the tests below may fail (but still be correct) if ODE solver, # the integral engine, solve(), or even simplify() changes. Also, in # differently formatted solutions, the arbitrary constants might not be # equal. Using specific hints in tests can help to avoid this. # Tests of order higher than 1 should run the solutions through # constant_renumber because it will normalize it (constant_renumber causes # dsolve() to return different results on different machines) def test_get_numbered_constants(): with raises(ValueError): get_numbered_constants(None) def test_dsolve_all_hint(): eq = f(x).diff(x) output = dsolve(eq, hint='all') # Match the Dummy variables: sol1 = output['separable_Integral'] _y = sol1.lhs.args[1][0] sol1 = output['1st_homogeneous_coeff_subs_dep_div_indep_Integral'] _u1 = sol1.rhs.args[1].args[1][0] expected = {'Bernoulli_Integral': Eq(f(x), C1 + Integral(0, x)), '1st_homogeneous_coeff_best': Eq(f(x), C1), 'Bernoulli': Eq(f(x), C1), 'nth_algebraic': Eq(f(x), C1), 'nth_linear_euler_eq_homogeneous': Eq(f(x), C1), 'nth_linear_constant_coeff_homogeneous': Eq(f(x), C1), 'separable': Eq(f(x), C1), '1st_homogeneous_coeff_subs_indep_div_dep': Eq(f(x), C1), 'nth_algebraic_Integral': Eq(f(x), C1), '1st_linear': Eq(f(x), C1), '1st_linear_Integral': Eq(f(x), C1 + Integral(0, x)), '1st_exact': Eq(f(x), C1), '1st_exact_Integral': Eq(Subs(Integral(0, x) + Integral(1, _y), _y, f(x)), C1), 'lie_group': Eq(f(x), C1), '1st_homogeneous_coeff_subs_dep_div_indep': Eq(f(x), C1), '1st_homogeneous_coeff_subs_dep_div_indep_Integral': Eq(log(x), C1 + Integral(-1/_u1, (_u1, f(x)/x))), '1st_power_series': Eq(f(x), C1), 'separable_Integral': Eq(Integral(1, (_y, f(x))), C1 + Integral(0, x)), '1st_homogeneous_coeff_subs_indep_div_dep_Integral': Eq(f(x), C1), 'best': Eq(f(x), C1), 'best_hint': 'nth_algebraic', 'default': 'nth_algebraic', 'order': 1} assert output == expected assert dsolve(eq, hint='best') == Eq(f(x), C1) def test_dsolve_ics(): # Maybe this should just use one of the solutions instead of raising... with raises(NotImplementedError): dsolve(f(x).diff(x) - sqrt(f(x)), ics={f(1):1}) @slow def test_dsolve_options(): eq = x*f(x).diff(x) + f(x) a = dsolve(eq, hint='all') b = dsolve(eq, hint='all', simplify=False) c = dsolve(eq, hint='all_Integral') keys = ['1st_exact', '1st_exact_Integral', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_homogeneous_coeff_subs_dep_div_indep_Integral', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear', '1st_linear_Integral', 'Bernoulli', 'Bernoulli_Integral', 'almost_linear', 'almost_linear_Integral', 'best', 'best_hint', 'default', 'factorable', 'lie_group', 'nth_linear_euler_eq_homogeneous', 'order', 'separable', 'separable_Integral'] Integral_keys = ['1st_exact_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear_Integral', 'Bernoulli_Integral', 'almost_linear_Integral', 'best', 'best_hint', 'default', 'factorable', 'nth_linear_euler_eq_homogeneous', 'order', 'separable_Integral'] assert sorted(a.keys()) == keys assert a['order'] == ode_order(eq, f(x)) assert a['best'] == Eq(f(x), C1/x) assert dsolve(eq, hint='best') == Eq(f(x), C1/x) assert a['default'] == 'factorable' assert a['best_hint'] == 'factorable' assert not a['1st_exact'].has(Integral) assert not a['separable'].has(Integral) assert not a['1st_homogeneous_coeff_best'].has(Integral) assert not a['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral) assert not a['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral) assert not a['1st_linear'].has(Integral) assert a['1st_linear_Integral'].has(Integral) assert a['1st_exact_Integral'].has(Integral) assert a['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral) assert a['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral) assert a['separable_Integral'].has(Integral) assert sorted(b.keys()) == keys assert b['order'] == ode_order(eq, f(x)) assert b['best'] == Eq(f(x), C1/x) assert dsolve(eq, hint='best', simplify=False) == Eq(f(x), C1/x) assert b['default'] == 'factorable' assert b['best_hint'] == 'factorable' assert a['separable'] != b['separable'] assert a['1st_homogeneous_coeff_subs_dep_div_indep'] != \ b['1st_homogeneous_coeff_subs_dep_div_indep'] assert a['1st_homogeneous_coeff_subs_indep_div_dep'] != \ b['1st_homogeneous_coeff_subs_indep_div_dep'] assert not b['1st_exact'].has(Integral) assert not b['separable'].has(Integral) assert not b['1st_homogeneous_coeff_best'].has(Integral) assert not b['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral) assert not b['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral) assert not b['1st_linear'].has(Integral) assert b['1st_linear_Integral'].has(Integral) assert b['1st_exact_Integral'].has(Integral) assert b['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral) assert b['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral) assert b['separable_Integral'].has(Integral) assert sorted(c.keys()) == Integral_keys raises(ValueError, lambda: dsolve(eq, hint='notarealhint')) raises(ValueError, lambda: dsolve(eq, hint='Liouville')) assert dsolve(f(x).diff(x) - 1/f(x)**2, hint='all')['best'] == \ dsolve(f(x).diff(x) - 1/f(x)**2, hint='best') assert dsolve(f(x) + f(x).diff(x) + sin(x).diff(x) + 1, f(x), hint="1st_linear_Integral") == \ Eq(f(x), (C1 + Integral((-sin(x).diff(x) - 1)* exp(Integral(1, x)), x))*exp(-Integral(1, x))) def test_classify_ode(): assert classify_ode(f(x).diff(x, 2), f(x)) == \ ( 'nth_algebraic', 'nth_linear_constant_coeff_homogeneous', 'nth_linear_euler_eq_homogeneous', 'Liouville', '2nd_power_series_ordinary', 'nth_algebraic_Integral', 'Liouville_Integral', ) assert classify_ode(f(x), f(x)) == ('nth_algebraic', 'nth_algebraic_Integral') assert classify_ode(Eq(f(x).diff(x), 0), f(x)) == ( 'nth_algebraic', 'separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_homogeneous', 'nth_linear_euler_eq_homogeneous', 'nth_algebraic_Integral', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral') assert classify_ode(f(x).diff(x)**2, f(x)) == ('factorable', 'nth_algebraic', 'separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', 'nth_linear_euler_eq_homogeneous', 'nth_algebraic_Integral', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral') # issue 4749: f(x) should be cleared from highest derivative before classifying a = classify_ode(Eq(f(x).diff(x) + f(x), x), f(x)) b = classify_ode(f(x).diff(x)*f(x) + f(x)*f(x) - x*f(x), f(x)) c = classify_ode(f(x).diff(x)/f(x) + f(x)/f(x) - x/f(x), f(x)) assert a == ('1st_exact', '1st_linear', 'Bernoulli', 'almost_linear', '1st_power_series', "lie_group", 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral', 'almost_linear_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral') assert b == ('factorable', '1st_linear', 'Bernoulli', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', '1st_linear_Integral', 'Bernoulli_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral') assert c == ('factorable', '1st_linear', 'Bernoulli', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', '1st_linear_Integral', 'Bernoulli_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral') assert classify_ode( 2*x*f(x)*f(x).diff(x) + (1 + x)*f(x)**2 - exp(x), f(x) ) == ('factorable', '1st_exact', 'Bernoulli', 'almost_linear', 'lie_group', '1st_exact_Integral', 'Bernoulli_Integral', 'almost_linear_Integral') assert 'Riccati_special_minus2' in \ classify_ode(2*f(x).diff(x) + f(x)**2 - f(x)/x + 3*x**(-2), f(x)) raises(ValueError, lambda: classify_ode(x + f(x, y).diff(x).diff( y), f(x, y))) # issue 5176 k = Symbol('k') assert classify_ode(f(x).diff(x)/(k*f(x) + k*x*f(x)) + 2*f(x)/(k*f(x) + k*x*f(x)) + x*f(x).diff(x)/(k*f(x) + k*x*f(x)) + z, f(x)) == \ ('factorable', 'separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_power_series', 'lie_group', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral') # preprocessing ans = ('factorable', 'nth_algebraic', 'separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', 'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters', 'nth_algebraic_Integral', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral', 'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral') # w/o f(x) given assert classify_ode(diff(f(x) + x, x) + diff(f(x), x)) == ans # w/ f(x) and prep=True assert classify_ode(diff(f(x) + x, x) + diff(f(x), x), f(x), prep=True) == ans assert classify_ode(Eq(2*x**3*f(x).diff(x), 0), f(x)) == \ ('factorable', 'nth_algebraic', 'separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_power_series', 'lie_group', 'nth_linear_euler_eq_homogeneous', 'nth_algebraic_Integral', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral') assert classify_ode(Eq(2*f(x)**3*f(x).diff(x), 0), f(x)) == \ ('factorable', 'nth_algebraic', 'separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_power_series', 'lie_group', 'nth_algebraic_Integral', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral') # test issue 13864 assert classify_ode(Eq(diff(f(x), x) - f(x)**x, 0), f(x)) == \ ('1st_power_series', 'lie_group') assert isinstance(classify_ode(Eq(f(x), 5), f(x), dict=True), dict) #This is for new behavior of classify_ode when called internally with default, It should # return the first hint which matches therefore, 'ordered_hints' key will not be there. assert sorted(classify_ode(Eq(f(x).diff(x), 0), f(x), dict=True).keys()) == \ ['default', 'nth_linear_constant_coeff_homogeneous', 'order'] a = classify_ode(2*x*f(x)*f(x).diff(x) + (1 + x)*f(x)**2 - exp(x), f(x), dict=True, hint='Bernoulli') assert sorted(a.keys()) == ['Bernoulli', 'Bernoulli_Integral', 'default', 'order', 'ordered_hints'] # test issue 22155 a = classify_ode(f(x).diff(x) - exp(f(x) - x), f(x)) assert a == ('separable', '1st_exact', '1st_power_series', 'lie_group', 'separable_Integral', '1st_exact_Integral') def test_classify_ode_ics(): # Dummy eq = f(x).diff(x, x) - f(x) # Not f(0) or f'(0) ics = {x: 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) ############################ # f(0) type (AppliedUndef) # ############################ # Wrong function ics = {g(0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Contains x ics = {f(x): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Too many args ics = {f(0, 0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # point contains f # XXX: Should be NotImplementedError ics = {f(0): f(1)} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Does not raise ics = {f(0): 1} classify_ode(eq, f(x), ics=ics) ##################### # f'(0) type (Subs) # ##################### # Wrong function ics = {g(x).diff(x).subs(x, 0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Contains x ics = {f(y).diff(y).subs(y, x): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Wrong variable ics = {f(y).diff(y).subs(y, 0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Too many args ics = {f(x, y).diff(x).subs(x, 0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Derivative wrt wrong vars ics = {Derivative(f(x), x, y).subs(x, 0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # point contains f # XXX: Should be NotImplementedError ics = {f(x).diff(x).subs(x, 0): f(0)} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Does not raise ics = {f(x).diff(x).subs(x, 0): 1} classify_ode(eq, f(x), ics=ics) ########################### # f'(y) type (Derivative) # ########################### # Wrong function ics = {g(x).diff(x).subs(x, y): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Contains x ics = {f(y).diff(y).subs(y, x): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Too many args ics = {f(x, y).diff(x).subs(x, y): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Derivative wrt wrong vars ics = {Derivative(f(x), x, z).subs(x, y): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # point contains f # XXX: Should be NotImplementedError ics = {f(x).diff(x).subs(x, y): f(0)} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Does not raise ics = {f(x).diff(x).subs(x, y): 1} classify_ode(eq, f(x), ics=ics) def test_classify_sysode(): # Here x is assumed to be x(t) and y as y(t) for simplicity. # Similarly diff(x,t) and diff(y,y) is assumed to be x1 and y1 respectively. k, l, m, n = symbols('k, l, m, n', Integer=True) k1, k2, k3, l1, l2, l3, m1, m2, m3 = symbols('k1, k2, k3, l1, l2, l3, m1, m2, m3', Integer=True) P, Q, R, p, q, r = symbols('P, Q, R, p, q, r', cls=Function) P1, P2, P3, Q1, Q2, R1, R2 = symbols('P1, P2, P3, Q1, Q2, R1, R2', cls=Function) x, y, z = symbols('x, y, z', cls=Function) t = symbols('t') x1 = diff(x(t),t) ; y1 = diff(y(t),t) ; eq6 = (Eq(x1, exp(k*x(t))*P(x(t),y(t))), Eq(y1,r(y(t))*P(x(t),y(t)))) sol6 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): 0, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): 0, \ (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): 0, (1, y(t), 1): 1}, 'type_of_equation': 'type2', 'func': \ [x(t), y(t)], 'is_linear': False, 'eq': [-P(x(t), y(t))*exp(k*x(t)) + Derivative(x(t), t), -P(x(t), \ y(t))*r(y(t)) + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq6) == sol6 eq7 = (Eq(x1, x(t)**2+y(t)/x(t)), Eq(y1, x(t)/y(t))) sol7 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): 0, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): 0, \ (1, x(t), 0): -1/y(t), (0, y(t), 1): 0, (0, y(t), 0): -1/x(t), (1, y(t), 1): 1}, 'type_of_equation': 'type3', \ 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)**2 + Derivative(x(t), t) - y(t)/x(t), -x(t)/y(t) + \ Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq7) == sol7 eq8 = (Eq(x1, P1(x(t))*Q1(y(t))*R(x(t),y(t),t)), Eq(y1, P1(x(t))*Q1(y(t))*R(x(t),y(t),t))) sol8 = {'func': [x(t), y(t)], 'is_linear': False, 'type_of_equation': 'type4', 'eq': \ [-P1(x(t))*Q1(y(t))*R(x(t), y(t), t) + Derivative(x(t), t), -P1(x(t))*Q1(y(t))*R(x(t), y(t), t) + \ Derivative(y(t), t)], 'func_coeff': {(0, y(t), 1): 0, (1, y(t), 1): 1, (1, x(t), 1): 0, (0, y(t), 0): 0, \ (1, x(t), 0): 0, (0, x(t), 0): 0, (1, y(t), 0): 0, (0, x(t), 1): 1}, 'order': {y(t): 1, x(t): 1}, 'no_of_equation': 2} assert classify_sysode(eq8) == sol8 eq11 = (Eq(x1,x(t)*y(t)**3), Eq(y1,y(t)**5)) sol11 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -y(t)**3, (1, x(t), 1): 0, (0, x(t), 1): 1, \ (1, y(t), 0): 0, (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): 0, (1, y(t), 1): 1}, 'type_of_equation': \ 'type1', 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)*y(t)**3 + Derivative(x(t), t), \ -y(t)**5 + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq11) == sol11 eq13 = (Eq(x1,x(t)*y(t)*sin(t)**2), Eq(y1,y(t)**2*sin(t)**2)) sol13 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -y(t)*sin(t)**2, (1, x(t), 1): 0, (0, x(t), 1): 1, \ (1, y(t), 0): 0, (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): -x(t)*sin(t)**2, (1, y(t), 1): 1}, \ 'type_of_equation': 'type4', 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)*y(t)*sin(t)**2 + \ Derivative(x(t), t), -y(t)**2*sin(t)**2 + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq13) == sol13 def test_solve_ics(): # Basic tests that things work from dsolve. assert dsolve(f(x).diff(x) - 1/f(x), f(x), ics={f(1): 2}) == \ Eq(f(x), sqrt(2 * x + 2)) assert dsolve(f(x).diff(x) - f(x), f(x), ics={f(0): 1}) == Eq(f(x), exp(x)) assert dsolve(f(x).diff(x) - f(x), f(x), ics={f(x).diff(x).subs(x, 0): 1}) == Eq(f(x), exp(x)) assert dsolve(f(x).diff(x, x) + f(x), f(x), ics={f(0): 1, f(x).diff(x).subs(x, 0): 1}) == Eq(f(x), sin(x) + cos(x)) assert dsolve([f(x).diff(x) - f(x) + g(x), g(x).diff(x) - g(x) - f(x)], [f(x), g(x)], ics={f(0): 1, g(0): 0}) == [Eq(f(x), exp(x)*cos(x)), Eq(g(x), exp(x)*sin(x))] # Test cases where dsolve returns two solutions. eq = (x**2*f(x)**2 - x).diff(x) assert dsolve(eq, f(x), ics={f(1): 0}) == [Eq(f(x), -sqrt(x - 1)/x), Eq(f(x), sqrt(x - 1)/x)] assert dsolve(eq, f(x), ics={f(x).diff(x).subs(x, 1): 0}) == [Eq(f(x), -sqrt(x - S.Half)/x), Eq(f(x), sqrt(x - S.Half)/x)] eq = cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x) assert dsolve(eq, f(x), ics={f(0):1}, hint='1st_exact', simplify=False) == Eq(x*cos(f(x)) + f(x)**3/3, Rational(1, 3)) assert dsolve(eq, f(x), ics={f(0):1}, hint='1st_exact', simplify=True) == Eq(x*cos(f(x)) + f(x)**3/3, Rational(1, 3)) assert solve_ics([Eq(f(x), C1*exp(x))], [f(x)], [C1], {f(0): 1}) == {C1: 1} assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1, f(pi/2): 1}) == {C1: 1, C2: 1} assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1, f(x).diff(x).subs(x, 0): 1}) == {C1: 1, C2: 1} assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1}) == \ {C2: 1} # Some more complicated tests Refer to PR #16098 assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0, f(x).diff(x).subs(x, 1):0})) == \ {Eq(f(x), 0), Eq(f(x), x ** 3 / 6 - x / 2)} assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0})) == \ {Eq(f(x), 0), Eq(f(x), C2*x + x**3/6)} K, r, f0 = symbols('K r f0') sol = Eq(f(x), K*f0*exp(r*x)/((-K + f0)*(f0*exp(r*x)/(-K + f0) - 1))) assert (dsolve(Eq(f(x).diff(x), r * f(x) * (1 - f(x) / K)), f(x), ics={f(0): f0})) == sol #Order dependent issues Refer to PR #16098 assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(x).diff(x).subs(x,0):0, f(0):0})) == \ {Eq(f(x), 0), Eq(f(x), x ** 3 / 6)} assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0, f(x).diff(x).subs(x,0):0})) == \ {Eq(f(x), 0), Eq(f(x), x ** 3 / 6)} # XXX: Ought to be ValueError raises(ValueError, lambda: solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1, f(pi): 1})) # Degenerate case. f'(0) is identically 0. raises(ValueError, lambda: solve_ics([Eq(f(x), sqrt(C1 - x**2))], [f(x)], [C1], {f(x).diff(x).subs(x, 0): 0})) EI, q, L = symbols('EI q L') # eq = Eq(EI*diff(f(x), x, 4), q) sols = [Eq(f(x), C1 + C2*x + C3*x**2 + C4*x**3 + q*x**4/(24*EI))] funcs = [f(x)] constants = [C1, C2, C3, C4] # Test both cases, Derivative (the default from f(x).diff(x).subs(x, L)), # and Subs ics1 = {f(0): 0, f(x).diff(x).subs(x, 0): 0, f(L).diff(L, 2): 0, f(L).diff(L, 3): 0} ics2 = {f(0): 0, f(x).diff(x).subs(x, 0): 0, Subs(f(x).diff(x, 2), x, L): 0, Subs(f(x).diff(x, 3), x, L): 0} solved_constants1 = solve_ics(sols, funcs, constants, ics1) solved_constants2 = solve_ics(sols, funcs, constants, ics2) assert solved_constants1 == solved_constants2 == { C1: 0, C2: 0, C3: L**2*q/(4*EI), C4: -L*q/(6*EI)} def test_ode_order(): f = Function('f') g = Function('g') x = Symbol('x') assert ode_order(3*x*exp(f(x)), f(x)) == 0 assert ode_order(x*diff(f(x), x) + 3*x*f(x) - sin(x)/x, f(x)) == 1 assert ode_order(x**2*f(x).diff(x, x) + x*diff(f(x), x) - f(x), f(x)) == 2 assert ode_order(diff(x*exp(f(x)), x, x), f(x)) == 2 assert ode_order(diff(x*diff(x*exp(f(x)), x, x), x), f(x)) == 3 assert ode_order(diff(f(x), x, x), g(x)) == 0 assert ode_order(diff(f(x), x, x)*diff(g(x), x), f(x)) == 2 assert ode_order(diff(f(x), x, x)*diff(g(x), x), g(x)) == 1 assert ode_order(diff(x*diff(x*exp(f(x)), x, x), x), g(x)) == 0 # issue 5835: ode_order has to also work for unevaluated derivatives # (ie, without using doit()). assert ode_order(Derivative(x*f(x), x), f(x)) == 1 assert ode_order(x*sin(Derivative(x*f(x)**2, x, x)), f(x)) == 2 assert ode_order(Derivative(x*Derivative(x*exp(f(x)), x, x), x), g(x)) == 0 assert ode_order(Derivative(f(x), x, x), g(x)) == 0 assert ode_order(Derivative(x*exp(f(x)), x, x), f(x)) == 2 assert ode_order(Derivative(f(x), x, x)*Derivative(g(x), x), g(x)) == 1 assert ode_order(Derivative(x*Derivative(f(x), x, x), x), f(x)) == 3 assert ode_order( x*sin(Derivative(x*Derivative(f(x), x)**2, x, x)), f(x)) == 3 def test_homogeneous_order(): assert homogeneous_order(exp(y/x) + tan(y/x), x, y) == 0 assert homogeneous_order(x**2 + sin(x)*cos(y), x, y) is None assert homogeneous_order(x - y - x*sin(y/x), x, y) == 1 assert homogeneous_order((x*y + sqrt(x**4 + y**4) + x**2*(log(x) - log(y)))/ (pi*x**Rational(2, 3)*sqrt(y)**3), x, y) == Rational(-1, 6) assert homogeneous_order(y/x*cos(y/x) - x/y*sin(y/x) + cos(y/x), x, y) == 0 assert homogeneous_order(f(x), x, f(x)) == 1 assert homogeneous_order(f(x)**2, x, f(x)) == 2 assert homogeneous_order(x*y*z, x, y) == 2 assert homogeneous_order(x*y*z, x, y, z) == 3 assert homogeneous_order(x**2*f(x)/sqrt(x**2 + f(x)**2), f(x)) is None assert homogeneous_order(f(x, y)**2, x, f(x, y), y) == 2 assert homogeneous_order(f(x, y)**2, x, f(x), y) is None assert homogeneous_order(f(x, y)**2, x, f(x, y)) is None assert homogeneous_order(f(y, x)**2, x, y, f(x, y)) is None assert homogeneous_order(f(y), f(x), x) is None assert homogeneous_order(-f(x)/x + 1/sin(f(x)/ x), f(x), x) == 0 assert homogeneous_order(log(1/y) + log(x**2), x, y) is None assert homogeneous_order(log(1/y) + log(x), x, y) == 0 assert homogeneous_order(log(x/y), x, y) == 0 assert homogeneous_order(2*log(1/y) + 2*log(x), x, y) == 0 a = Symbol('a') assert homogeneous_order(a*log(1/y) + a*log(x), x, y) == 0 assert homogeneous_order(f(x).diff(x), x, y) is None assert homogeneous_order(-f(x).diff(x) + x, x, y) is None assert homogeneous_order(O(x), x, y) is None assert homogeneous_order(x + O(x**2), x, y) is None assert homogeneous_order(x**pi, x) == pi assert homogeneous_order(x**x, x) is None raises(ValueError, lambda: homogeneous_order(x*y)) @XFAIL def test_noncircularized_real_imaginary_parts(): # If this passes, lines numbered 3878-3882 (at the time of this commit) # of sympy/solvers/ode.py for nth_linear_constant_coeff_homogeneous # should be removed. y = sqrt(1+x) i, r = im(y), re(y) assert not (i.has(atan2) and r.has(atan2)) def test_collect_respecting_exponentials(): # If this test passes, lines 1306-1311 (at the time of this commit) # of sympy/solvers/ode.py should be removed. sol = 1 + exp(x/2) assert sol == collect( sol, exp(x/3)) def test_undetermined_coefficients_match(): assert _undetermined_coefficients_match(g(x), x) == {'test': False} assert _undetermined_coefficients_match(sin(2*x + sqrt(5)), x) == \ {'test': True, 'trialset': {cos(2*x + sqrt(5)), sin(2*x + sqrt(5))}} assert _undetermined_coefficients_match(sin(x)*cos(x), x) == \ {'test': False} s = {cos(x), x*cos(x), x**2*cos(x), x**2*sin(x), x*sin(x), sin(x)} assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \ {'test': True, 'trialset': s} assert _undetermined_coefficients_match( sin(x)*x**2 + sin(x)*x + sin(x), x) == {'test': True, 'trialset': s} assert _undetermined_coefficients_match( exp(2*x)*sin(x)*(x**2 + x + 1), x ) == { 'test': True, 'trialset': {exp(2*x)*sin(x), x**2*exp(2*x)*sin(x), cos(x)*exp(2*x), x**2*cos(x)*exp(2*x), x*cos(x)*exp(2*x), x*exp(2*x)*sin(x)}} assert _undetermined_coefficients_match(1/sin(x), x) == {'test': False} assert _undetermined_coefficients_match(log(x), x) == {'test': False} assert _undetermined_coefficients_match(2**(x)*(x**2 + x + 1), x) == \ {'test': True, 'trialset': {2**x, x*2**x, x**2*2**x}} assert _undetermined_coefficients_match(x**y, x) == {'test': False} assert _undetermined_coefficients_match(exp(x)*exp(2*x + 1), x) == \ {'test': True, 'trialset': {exp(1 + 3*x)}} assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \ {'test': True, 'trialset': {x*cos(x), x*sin(x), x**2*cos(x), x**2*sin(x), cos(x), sin(x)}} assert _undetermined_coefficients_match(sin(x)*(x + sin(x)), x) == \ {'test': False} assert _undetermined_coefficients_match(sin(x)*(x + sin(2*x)), x) == \ {'test': False} assert _undetermined_coefficients_match(sin(x)*tan(x), x) == \ {'test': False} assert _undetermined_coefficients_match( x**2*sin(x)*exp(x) + x*sin(x) + x, x ) == { 'test': True, 'trialset': {x**2*cos(x)*exp(x), x, cos(x), S.One, exp(x)*sin(x), sin(x), x*exp(x)*sin(x), x*cos(x), x*cos(x)*exp(x), x*sin(x), cos(x)*exp(x), x**2*exp(x)*sin(x)}} assert _undetermined_coefficients_match(4*x*sin(x - 2), x) == { 'trialset': {x*cos(x - 2), x*sin(x - 2), cos(x - 2), sin(x - 2)}, 'test': True, } assert _undetermined_coefficients_match(2**x*x, x) == \ {'test': True, 'trialset': {2**x, x*2**x}} assert _undetermined_coefficients_match(2**x*exp(2*x), x) == \ {'test': True, 'trialset': {2**x*exp(2*x)}} assert _undetermined_coefficients_match(exp(-x)/x, x) == \ {'test': False} # Below are from Ordinary Differential Equations, # Tenenbaum and Pollard, pg. 231 assert _undetermined_coefficients_match(S(4), x) == \ {'test': True, 'trialset': {S.One}} assert _undetermined_coefficients_match(12*exp(x), x) == \ {'test': True, 'trialset': {exp(x)}} assert _undetermined_coefficients_match(exp(I*x), x) == \ {'test': True, 'trialset': {exp(I*x)}} assert _undetermined_coefficients_match(sin(x), x) == \ {'test': True, 'trialset': {cos(x), sin(x)}} assert _undetermined_coefficients_match(cos(x), x) == \ {'test': True, 'trialset': {cos(x), sin(x)}} assert _undetermined_coefficients_match(8 + 6*exp(x) + 2*sin(x), x) == \ {'test': True, 'trialset': {S.One, cos(x), sin(x), exp(x)}} assert _undetermined_coefficients_match(x**2, x) == \ {'test': True, 'trialset': {S.One, x, x**2}} assert _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x) == \ {'test': True, 'trialset': {x*exp(x), exp(x), exp(-x)}} assert _undetermined_coefficients_match(2*exp(2*x)*sin(x), x) == \ {'test': True, 'trialset': {exp(2*x)*sin(x), cos(x)*exp(2*x)}} assert _undetermined_coefficients_match(x - sin(x), x) == \ {'test': True, 'trialset': {S.One, x, cos(x), sin(x)}} assert _undetermined_coefficients_match(x**2 + 2*x, x) == \ {'test': True, 'trialset': {S.One, x, x**2}} assert _undetermined_coefficients_match(4*x*sin(x), x) == \ {'test': True, 'trialset': {x*cos(x), x*sin(x), cos(x), sin(x)}} assert _undetermined_coefficients_match(x*sin(2*x), x) == \ {'test': True, 'trialset': {x*cos(2*x), x*sin(2*x), cos(2*x), sin(2*x)}} assert _undetermined_coefficients_match(x**2*exp(-x), x) == \ {'test': True, 'trialset': {x*exp(-x), x**2*exp(-x), exp(-x)}} assert _undetermined_coefficients_match(2*exp(-x) - x**2*exp(-x), x) == \ {'test': True, 'trialset': {x*exp(-x), x**2*exp(-x), exp(-x)}} assert _undetermined_coefficients_match(exp(-2*x) + x**2, x) == \ {'test': True, 'trialset': {S.One, x, x**2, exp(-2*x)}} assert _undetermined_coefficients_match(x*exp(-x), x) == \ {'test': True, 'trialset': {x*exp(-x), exp(-x)}} assert _undetermined_coefficients_match(x + exp(2*x), x) == \ {'test': True, 'trialset': {S.One, x, exp(2*x)}} assert _undetermined_coefficients_match(sin(x) + exp(-x), x) == \ {'test': True, 'trialset': {cos(x), sin(x), exp(-x)}} assert _undetermined_coefficients_match(exp(x), x) == \ {'test': True, 'trialset': {exp(x)}} # converted from sin(x)**2 assert _undetermined_coefficients_match(S.Half - cos(2*x)/2, x) == \ {'test': True, 'trialset': {S.One, cos(2*x), sin(2*x)}} # converted from exp(2*x)*sin(x)**2 assert _undetermined_coefficients_match( exp(2*x)*(S.Half + cos(2*x)/2), x ) == { 'test': True, 'trialset': {exp(2*x)*sin(2*x), cos(2*x)*exp(2*x), exp(2*x)}} assert _undetermined_coefficients_match(2*x + sin(x) + cos(x), x) == \ {'test': True, 'trialset': {S.One, x, cos(x), sin(x)}} # converted from sin(2*x)*sin(x) assert _undetermined_coefficients_match(cos(x)/2 - cos(3*x)/2, x) == \ {'test': True, 'trialset': {cos(x), cos(3*x), sin(x), sin(3*x)}} assert _undetermined_coefficients_match(cos(x**2), x) == {'test': False} assert _undetermined_coefficients_match(2**(x**2), x) == {'test': False} def test_issue_4785(): from sympy.abc import A eq = x + A*(x + diff(f(x), x) + f(x)) + diff(f(x), x) + f(x) + 2 assert classify_ode(eq, f(x)) == ('factorable', '1st_exact', '1st_linear', 'almost_linear', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', '1st_exact_Integral', '1st_linear_Integral', 'almost_linear_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral') # issue 4864 eq = (x**2 + f(x)**2)*f(x).diff(x) - 2*x*f(x) assert classify_ode(eq, f(x)) == ('factorable', '1st_exact', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', '1st_exact_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral') def test_issue_4825(): raises(ValueError, lambda: dsolve(f(x, y).diff(x) - y*f(x, y), f(x))) assert classify_ode(f(x, y).diff(x) - y*f(x, y), f(x), dict=True) == \ {'order': 0, 'default': None, 'ordered_hints': ()} # See also issue 3793, test Z13. raises(ValueError, lambda: dsolve(f(x).diff(x), f(y))) assert classify_ode(f(x).diff(x), f(y), dict=True) == \ {'order': 0, 'default': None, 'ordered_hints': ()} def test_constant_renumber_order_issue_5308(): from sympy.utilities.iterables import variations assert constant_renumber(C1*x + C2*y) == \ constant_renumber(C1*y + C2*x) == \ C1*x + C2*y e = C1*(C2 + x)*(C3 + y) for a, b, c in variations([C1, C2, C3], 3): assert constant_renumber(a*(b + x)*(c + y)) == e def test_constant_renumber(): e1, e2, x, y = symbols("e1:3 x y") exprs = [e2*x, e1*x + e2*y] assert constant_renumber(exprs[0]) == e2*x assert constant_renumber(exprs[0], variables=[x]) == C1*x assert constant_renumber(exprs[0], variables=[x], newconstants=[C2]) == C2*x assert constant_renumber(exprs, variables=[x, y]) == [C1*x, C1*y + C2*x] assert constant_renumber(exprs, variables=[x, y], newconstants=symbols("C3:5")) == [C3*x, C3*y + C4*x] def test_issue_5770(): k = Symbol("k", real=True) t = Symbol('t') w = Function('w') sol = dsolve(w(t).diff(t, 6) - k**6*w(t), w(t)) assert len([s for s in sol.free_symbols if s.name.startswith('C')]) == 6 assert constantsimp((C1*cos(x) + C2*cos(x))*exp(x), {C1, C2}) == \ C1*cos(x)*exp(x) assert constantsimp(C1*cos(x) + C2*cos(x) + C3*sin(x), {C1, C2, C3}) == \ C1*cos(x) + C3*sin(x) assert constantsimp(exp(C1 + x), {C1}) == C1*exp(x) assert constantsimp(x + C1 + y, {C1, y}) == C1 + x assert constantsimp(x + C1 + Integral(x, (x, 1, 2)), {C1}) == C1 + x def test_issue_5112_5430(): assert homogeneous_order(-log(x) + acosh(x), x) is None assert homogeneous_order(y - log(x), x, y) is None def test_issue_5095(): f = Function('f') raises(ValueError, lambda: dsolve(f(x).diff(x)**2, f(x), 'fdsjf')) def test_homogeneous_function(): f = Function('f') eq1 = tan(x + f(x)) eq2 = sin((3*x)/(4*f(x))) eq3 = cos(x*f(x)*Rational(3, 4)) eq4 = log((3*x + 4*f(x))/(5*f(x) + 7*x)) eq5 = exp((2*x**2)/(3*f(x)**2)) eq6 = log((3*x + 4*f(x))/(5*f(x) + 7*x) + exp((2*x**2)/(3*f(x)**2))) eq7 = sin((3*x)/(5*f(x) + x**2)) assert homogeneous_order(eq1, x, f(x)) == None assert homogeneous_order(eq2, x, f(x)) == 0 assert homogeneous_order(eq3, x, f(x)) == None assert homogeneous_order(eq4, x, f(x)) == 0 assert homogeneous_order(eq5, x, f(x)) == 0 assert homogeneous_order(eq6, x, f(x)) == 0 assert homogeneous_order(eq7, x, f(x)) == None def test_linear_coeff_match(): n, d = z*(2*x + 3*f(x) + 5), z*(7*x + 9*f(x) + 11) rat = n/d eq1 = sin(rat) + cos(rat.expand()) obj1 = LinearCoefficients(eq1) eq2 = rat obj2 = LinearCoefficients(eq2) eq3 = log(sin(rat)) obj3 = LinearCoefficients(eq3) ans = (4, Rational(-13, 3)) assert obj1._linear_coeff_match(eq1, f(x)) == ans assert obj2._linear_coeff_match(eq2, f(x)) == ans assert obj3._linear_coeff_match(eq3, f(x)) == ans # no c eq4 = (3*x)/f(x) obj4 = LinearCoefficients(eq4) # not x and f(x) eq5 = (3*x + 2)/x obj5 = LinearCoefficients(eq5) # denom will be zero eq6 = (3*x + 2*f(x) + 1)/(3*x + 2*f(x) + 5) obj6 = LinearCoefficients(eq6) # not rational coefficient eq7 = (3*x + 2*f(x) + sqrt(2))/(3*x + 2*f(x) + 5) obj7 = LinearCoefficients(eq7) assert obj4._linear_coeff_match(eq4, f(x)) is None assert obj5._linear_coeff_match(eq5, f(x)) is None assert obj6._linear_coeff_match(eq6, f(x)) is None assert obj7._linear_coeff_match(eq7, f(x)) is None def test_constantsimp_take_problem(): c = exp(C1) + 2 assert len(Poly(constantsimp(exp(C1) + c + c*x, [C1])).gens) == 2 def test_series(): C1 = Symbol("C1") eq = f(x).diff(x) - f(x) sol = Eq(f(x), C1 + C1*x + C1*x**2/2 + C1*x**3/6 + C1*x**4/24 + C1*x**5/120 + O(x**6)) assert dsolve(eq, hint='1st_power_series') == sol assert checkodesol(eq, sol, order=1)[0] eq = f(x).diff(x) - x*f(x) sol = Eq(f(x), C1*x**4/8 + C1*x**2/2 + C1 + O(x**6)) assert dsolve(eq, hint='1st_power_series') == sol assert checkodesol(eq, sol, order=1)[0] eq = f(x).diff(x) - sin(x*f(x)) sol = Eq(f(x), (x - 2)**2*(1+ sin(4))*cos(4) + (x - 2)*sin(4) + 2 + O(x**3)) assert dsolve(eq, hint='1st_power_series', ics={f(2): 2}, n=3) == sol # FIXME: The solution here should be O((x-2)**3) so is incorrect #assert checkodesol(eq, sol, order=1)[0] @slow def test_2nd_power_series_ordinary(): C1, C2 = symbols("C1 C2") eq = f(x).diff(x, 2) - x*f(x) assert classify_ode(eq) == ('2nd_linear_airy', '2nd_power_series_ordinary') sol = Eq(f(x), C2*(x**3/6 + 1) + C1*x*(x**3/12 + 1) + O(x**6)) assert dsolve(eq, hint='2nd_power_series_ordinary') == sol assert checkodesol(eq, sol) == (True, 0) sol = Eq(f(x), C2*((x + 2)**4/6 + (x + 2)**3/6 - (x + 2)**2 + 1) + C1*(x + (x + 2)**4/12 - (x + 2)**3/3 + S(2)) + O(x**6)) assert dsolve(eq, hint='2nd_power_series_ordinary', x0=-2) == sol # FIXME: Solution should be O((x+2)**6) # assert checkodesol(eq, sol) == (True, 0) sol = Eq(f(x), C2*x + C1 + O(x**2)) assert dsolve(eq, hint='2nd_power_series_ordinary', n=2) == sol assert checkodesol(eq, sol) == (True, 0) eq = (1 + x**2)*(f(x).diff(x, 2)) + 2*x*(f(x).diff(x)) -2*f(x) assert classify_ode(eq) == ('factorable', '2nd_hypergeometric', '2nd_hypergeometric_Integral', '2nd_power_series_ordinary') sol = Eq(f(x), C2*(-x**4/3 + x**2 + 1) + C1*x + O(x**6)) assert dsolve(eq, hint='2nd_power_series_ordinary') == sol assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 2) + x*(f(x).diff(x)) + f(x) assert classify_ode(eq) == ('factorable', '2nd_power_series_ordinary',) sol = Eq(f(x), C2*(x**4/8 - x**2/2 + 1) + C1*x*(-x**2/3 + 1) + O(x**6)) assert dsolve(eq) == sol # FIXME: checkodesol fails for this solution... # assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 2) + f(x).diff(x) - x*f(x) assert classify_ode(eq) == ('2nd_power_series_ordinary',) sol = Eq(f(x), C2*(-x**4/24 + x**3/6 + 1) + C1*x*(x**3/24 + x**2/6 - x/2 + 1) + O(x**6)) assert dsolve(eq) == sol # FIXME: checkodesol fails for this solution... # assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 2) + x*f(x) assert classify_ode(eq) == ('2nd_linear_airy', '2nd_power_series_ordinary') sol = Eq(f(x), C2*(x**6/180 - x**3/6 + 1) + C1*x*(-x**3/12 + 1) + O(x**7)) assert dsolve(eq, hint='2nd_power_series_ordinary', n=7) == sol assert checkodesol(eq, sol) == (True, 0) def test_2nd_power_series_regular(): C1, C2, a = symbols("C1 C2 a") eq = x**2*(f(x).diff(x, 2)) - 3*x*(f(x).diff(x)) + (4*x + 4)*f(x) sol = Eq(f(x), C1*x**2*(-16*x**3/9 + 4*x**2 - 4*x + 1) + O(x**6)) assert dsolve(eq, hint='2nd_power_series_regular') == sol assert checkodesol(eq, sol) == (True, 0) eq = 4*x**2*(f(x).diff(x, 2)) -8*x**2*(f(x).diff(x)) + (4*x**2 + 1)*f(x) sol = Eq(f(x), C1*sqrt(x)*(x**4/24 + x**3/6 + x**2/2 + x + 1) + O(x**6)) assert dsolve(eq, hint='2nd_power_series_regular') == sol assert checkodesol(eq, sol) == (True, 0) eq = x**2*(f(x).diff(x, 2)) - x**2*(f(x).diff(x)) + ( x**2 - 2)*f(x) sol = Eq(f(x), C1*(-x**6/720 - 3*x**5/80 - x**4/8 + x**2/2 + x/2 + 1)/x + C2*x**2*(-x**3/60 + x**2/20 + x/2 + 1) + O(x**6)) assert dsolve(eq) == sol assert checkodesol(eq, sol) == (True, 0) eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - Rational(1, 4))*f(x) sol = Eq(f(x), C1*(x**4/24 - x**2/2 + 1)/sqrt(x) + C2*sqrt(x)*(x**4/120 - x**2/6 + 1) + O(x**6)) assert dsolve(eq, hint='2nd_power_series_regular') == sol assert checkodesol(eq, sol) == (True, 0) eq = x*f(x).diff(x, 2) + f(x).diff(x) - a*x*f(x) sol = Eq(f(x), C1*(a**2*x**4/64 + a*x**2/4 + 1) + O(x**6)) assert dsolve(eq, f(x), hint="2nd_power_series_regular") == sol assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 2) + ((1 - x)/x)*f(x).diff(x) + (a/x)*f(x) sol = Eq(f(x), C1*(-a*x**5*(a - 4)*(a - 3)*(a - 2)*(a - 1)/14400 + \ a*x**4*(a - 3)*(a - 2)*(a - 1)/576 - a*x**3*(a - 2)*(a - 1)/36 + \ a*x**2*(a - 1)/4 - a*x + 1) + O(x**6)) assert dsolve(eq, f(x), hint="2nd_power_series_regular") == sol assert checkodesol(eq, sol) == (True, 0) def test_issue_15056(): t = Symbol('t') C3 = Symbol('C3') assert get_numbered_constants(Symbol('C1') * Function('C2')(t)) == C3 def test_issue_15913(): eq = -C1/x - 2*x*f(x) - f(x) + Derivative(f(x), x) sol = C2*exp(x**2 + x) + exp(x**2 + x)*Integral(C1*exp(-x**2 - x)/x, x) assert checkodesol(eq, sol) == (True, 0) sol = C1 + C2*exp(-x*y) eq = Derivative(y*f(x), x) + f(x).diff(x, 2) assert checkodesol(eq, sol, f(x)) == (True, 0) def test_issue_16146(): raises(ValueError, lambda: dsolve([f(x).diff(x), g(x).diff(x)], [f(x), g(x), h(x)])) raises(ValueError, lambda: dsolve([f(x).diff(x), g(x).diff(x)], [f(x)])) def test_dsolve_remove_redundant_solutions(): eq = (f(x)-2)*f(x).diff(x) sol = Eq(f(x), C1) assert dsolve(eq) == sol eq = (f(x)-sin(x))*(f(x).diff(x, 2)) sol = {Eq(f(x), C1 + C2*x), Eq(f(x), sin(x))} assert set(dsolve(eq)) == sol eq = (f(x)**2-2*f(x)+1)*f(x).diff(x, 3) sol = Eq(f(x), C1 + C2*x + C3*x**2) assert dsolve(eq) == sol def test_issue_13060(): A, B = symbols("A B", cls=Function) t = Symbol("t") eq = [Eq(Derivative(A(t), t), A(t)*B(t)), Eq(Derivative(B(t), t), A(t)*B(t))] sol = dsolve(eq) assert checkodesol(eq, sol) == (True, [0, 0]) def test_issue_22523(): N, s = symbols('N s') rho = Function('rho') # intentionally use 4.0 to confirm issue with nfloat # works here eqn = 4.0*N*sqrt(N - 1)*rho(s) + (4*s**2*(N - 1) + (N - 2*s*(N - 1))**2 )*Derivative(rho(s), (s, 2)) match = classify_ode(eqn, dict=True, hint='all') assert match['2nd_power_series_ordinary']['terms'] == 5 C1, C2 = symbols('C1,C2') sol = dsolve(eqn, hint='2nd_power_series_ordinary') # there is no r(2.0) in this result assert filldedent(sol) == filldedent(str(''' Eq(rho(s), C2*(1 - 4.0*s**4*sqrt(N - 1.0)/N + 0.666666666666667*s**4/N - 2.66666666666667*s**3*sqrt(N - 1.0)/N - 2.0*s**2*sqrt(N - 1.0)/N + 9.33333333333333*s**4*sqrt(N - 1.0)/N**2 - 0.666666666666667*s**4/N**2 + 2.66666666666667*s**3*sqrt(N - 1.0)/N**2 - 5.33333333333333*s**4*sqrt(N - 1.0)/N**3) + C1*s*(1.0 - 1.33333333333333*s**3*sqrt(N - 1.0)/N - 0.666666666666667*s**2*sqrt(N - 1.0)/N + 1.33333333333333*s**3*sqrt(N - 1.0)/N**2) + O(s**6))''')) def test_issue_22604(): x1, x2 = symbols('x1, x2', cls = Function) t, k1, k2, m1, m2 = symbols('t k1 k2 m1 m2', real = True) k1, k2, m1, m2 = 1, 1, 1, 1 eq1 = Eq(m1*diff(x1(t), t, 2) + k1*x1(t) - k2*(x2(t) - x1(t)), 0) eq2 = Eq(m2*diff(x2(t), t, 2) + k2*(x2(t) - x1(t)), 0) eqs = [eq1, eq2] [x1sol, x2sol] = dsolve(eqs, [x1(t), x2(t)], ics = {x1(0):0, x1(t).diff().subs(t,0):0, \ x2(0):1, x2(t).diff().subs(t,0):0}) assert x1sol == Eq(x1(t), sqrt(3 - sqrt(5))*(sqrt(10) + 5*sqrt(2))*cos(sqrt(2)*t*sqrt(3 - sqrt(5))/2)/20 + \ (-5*sqrt(2) + sqrt(10))*sqrt(sqrt(5) + 3)*cos(sqrt(2)*t*sqrt(sqrt(5) + 3)/2)/20) assert x2sol == Eq(x2(t), (sqrt(5) + 5)*cos(sqrt(2)*t*sqrt(3 - sqrt(5))/2)/10 + (5 - sqrt(5))*cos(sqrt(2)*t*sqrt(sqrt(5) + 3)/2)/10)
4f38ed33f396976f1e2769b25ac2bc538ac247f6eb6e50eb6d50e14a57f4415f
# # The main tests for the code in single.py are currently located in # sympy/solvers/tests/test_ode.py # r""" This File contains test functions for the individual hints used for solving ODEs. Examples of each solver will be returned by _get_examples_ode_sol_name_of_solver. Examples should have a key 'XFAIL' which stores the list of hints if they are expected to fail for that hint. Functions that are for internal use: 1) _ode_solver_test(ode_examples) - It takes a dictionary of examples returned by _get_examples method and tests them with their respective hints. 2) _test_particular_example(our_hint, example_name) - It tests the ODE example corresponding to the hint provided. 3) _test_all_hints(runxfail=False) - It is used to test all the examples with all the hints currently implemented. It calls _test_all_examples_for_one_hint() which outputs whether the given hint functions properly if it classifies the ODE example. If runxfail flag is set to True then it will only test the examples which are expected to fail. Everytime the ODE of a particular solver is added, _test_all_hints() is to be executed to find the possible failures of different solver hints. 4) _test_all_examples_for_one_hint(our_hint, all_examples) - It takes hint as argument and checks this hint against all the ODE examples and gives output as the number of ODEs matched, number of ODEs which were solved correctly, list of ODEs which gives incorrect solution and list of ODEs which raises exception. """ from sympy.core.function import (Derivative, diff) from sympy.core.mul import Mul from sympy.core.numbers import (E, I, Rational, pi) from sympy.core.relational import (Eq, Ne) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, symbols) from sympy.functions.elementary.complexes import (im, re) from sympy.functions.elementary.exponential import (LambertW, exp, log) from sympy.functions.elementary.hyperbolic import (acosh, asinh, cosh, sinh, tanh) from sympy.functions.elementary.miscellaneous import (cbrt, sqrt) from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sec, sin, tan) from sympy.functions.special.error_functions import (Ei, erfi) from sympy.functions.special.hyper import hyper from sympy.integrals.integrals import (Integral, integrate) from sympy.polys.rootoftools import rootof from sympy.core import Function, Symbol from sympy.functions import airyai, airybi, besselj, bessely, lowergamma from sympy.integrals.risch import NonElementaryIntegral from sympy.solvers.ode import classify_ode, dsolve from sympy.solvers.ode.ode import allhints, _remove_redundant_solutions from sympy.solvers.ode.single import (FirstLinear, ODEMatchError, SingleODEProblem, SingleODESolver, NthOrderReducible) from sympy.solvers.ode.subscheck import checkodesol from sympy.testing.pytest import raises, slow, ON_TRAVIS import traceback x = Symbol('x') u = Symbol('u') _u = Dummy('u') y = Symbol('y') f = Function('f') g = Function('g') C1, C2, C3, C4, C5, C6, C7, C8, C9, C10 = symbols('C1:11') hint_message = """\ Hint did not match the example {example}. The ODE is: {eq}. The expected hint was {our_hint}\ """ expected_sol_message = """\ Different solution found from dsolve for example {example}. The ODE is: {eq} The expected solution was {sol} What dsolve returned is: {dsolve_sol}\ """ checkodesol_msg = """\ solution found is not correct for example {example}. The ODE is: {eq}\ """ dsol_incorrect_msg = """\ solution returned by dsolve is incorrect when using {hint}. The ODE is: {eq} The expected solution was {sol} what dsolve returned is: {dsolve_sol} You can test this with: eq = {eq} sol = dsolve(eq, hint='{hint}') print(sol) print(checkodesol(eq, sol)) """ exception_msg = """\ dsolve raised exception : {e} when using {hint} for the example {example} You can test this with: from sympy.solvers.ode.tests.test_single import _test_an_example _test_an_example('{hint}', example_name = '{example}') The ODE is: {eq} \ """ check_hint_msg = """\ Tested hint was : {hint} Total of {matched} examples matched with this hint. Out of which {solve} gave correct results. Examples which gave incorrect results are {unsolve}. Examples which raised exceptions are {exceptions} \ """ def _add_example_keys(func): def inner(): solver=func() examples=[] for example in solver['examples']: temp={ 'eq': solver['examples'][example]['eq'], 'sol': solver['examples'][example]['sol'], 'XFAIL': solver['examples'][example].get('XFAIL', []), 'func': solver['examples'][example].get('func',solver['func']), 'example_name': example, 'slow': solver['examples'][example].get('slow', False), 'simplify_flag':solver['examples'][example].get('simplify_flag',True), 'checkodesol_XFAIL': solver['examples'][example].get('checkodesol_XFAIL', False), 'dsolve_too_slow':solver['examples'][example].get('dsolve_too_slow',False), 'checkodesol_too_slow':solver['examples'][example].get('checkodesol_too_slow',False), 'hint': solver['hint'] } examples.append(temp) return examples return inner() def _ode_solver_test(ode_examples, run_slow_test=False): for example in ode_examples: if ((not run_slow_test) and example['slow']) or (run_slow_test and (not example['slow'])): continue result = _test_particular_example(example['hint'], example, solver_flag=True) if result['xpass_msg'] != "": print(result['xpass_msg']) def _test_all_hints(runxfail=False): all_hints = list(allhints)+["default"] all_examples = _get_all_examples() for our_hint in all_hints: if our_hint.endswith('_Integral') or 'series' in our_hint: continue _test_all_examples_for_one_hint(our_hint, all_examples, runxfail) def _test_dummy_sol(expected_sol,dsolve_sol): if type(dsolve_sol)==list: return any(expected_sol.dummy_eq(sub_dsol) for sub_dsol in dsolve_sol) else: return expected_sol.dummy_eq(dsolve_sol) def _test_an_example(our_hint, example_name): all_examples = _get_all_examples() for example in all_examples: if example['example_name'] == example_name: _test_particular_example(our_hint, example) def _test_particular_example(our_hint, ode_example, solver_flag=False): eq = ode_example['eq'] expected_sol = ode_example['sol'] example = ode_example['example_name'] xfail = our_hint in ode_example['XFAIL'] func = ode_example['func'] result = {'msg': '', 'xpass_msg': ''} simplify_flag=ode_example['simplify_flag'] checkodesol_XFAIL = ode_example['checkodesol_XFAIL'] dsolve_too_slow = ode_example['dsolve_too_slow'] checkodesol_too_slow = ode_example['checkodesol_too_slow'] xpass = True if solver_flag: if our_hint not in classify_ode(eq, func): message = hint_message.format(example=example, eq=eq, our_hint=our_hint) raise AssertionError(message) if our_hint in classify_ode(eq, func): result['match_list'] = example try: if not (dsolve_too_slow): dsolve_sol = dsolve(eq, func, simplify=simplify_flag,hint=our_hint) else: if len(expected_sol)==1: dsolve_sol = expected_sol[0] else: dsolve_sol = expected_sol except Exception as e: dsolve_sol = [] result['exception_list'] = example if not solver_flag: traceback.print_exc() result['msg'] = exception_msg.format(e=str(e), hint=our_hint, example=example, eq=eq) if solver_flag and not xfail: print(result['msg']) raise xpass = False if solver_flag and dsolve_sol!=[]: expect_sol_check = False if type(dsolve_sol)==list: for sub_sol in expected_sol: if sub_sol.has(Dummy): expect_sol_check = not _test_dummy_sol(sub_sol, dsolve_sol) else: expect_sol_check = sub_sol not in dsolve_sol if expect_sol_check: break else: expect_sol_check = dsolve_sol not in expected_sol for sub_sol in expected_sol: if sub_sol.has(Dummy): expect_sol_check = not _test_dummy_sol(sub_sol, dsolve_sol) if expect_sol_check: message = expected_sol_message.format(example=example, eq=eq, sol=expected_sol, dsolve_sol=dsolve_sol) raise AssertionError(message) expected_checkodesol = [(True, 0) for i in range(len(expected_sol))] if len(expected_sol) == 1: expected_checkodesol = (True, 0) if not (checkodesol_too_slow and ON_TRAVIS): if not checkodesol_XFAIL: if checkodesol(eq, dsolve_sol, func, solve_for_func=False) != expected_checkodesol: result['unsolve_list'] = example xpass = False message = dsol_incorrect_msg.format(hint=our_hint, eq=eq, sol=expected_sol,dsolve_sol=dsolve_sol) if solver_flag: message = checkodesol_msg.format(example=example, eq=eq) raise AssertionError(message) else: result['msg'] = 'AssertionError: ' + message if xpass and xfail: result['xpass_msg'] = example + "is now passing for the hint" + our_hint return result def _test_all_examples_for_one_hint(our_hint, all_examples=[], runxfail=None): if all_examples == []: all_examples = _get_all_examples() match_list, unsolve_list, exception_list = [], [], [] for ode_example in all_examples: xfail = our_hint in ode_example['XFAIL'] if runxfail and not xfail: continue if xfail: continue result = _test_particular_example(our_hint, ode_example) match_list += result.get('match_list',[]) unsolve_list += result.get('unsolve_list',[]) exception_list += result.get('exception_list',[]) if runxfail is not None: msg = result['msg'] if msg!='': print(result['msg']) # print(result.get('xpass_msg','')) if runxfail is None: match_count = len(match_list) solved = len(match_list)-len(unsolve_list)-len(exception_list) msg = check_hint_msg.format(hint=our_hint, matched=match_count, solve=solved, unsolve=unsolve_list, exceptions=exception_list) print(msg) def test_SingleODESolver(): # Test that not implemented methods give NotImplementedError # Subclasses should override these methods. problem = SingleODEProblem(f(x).diff(x), f(x), x) solver = SingleODESolver(problem) raises(NotImplementedError, lambda: solver.matches()) raises(NotImplementedError, lambda: solver.get_general_solution()) raises(NotImplementedError, lambda: solver._matches()) raises(NotImplementedError, lambda: solver._get_general_solution()) # This ODE can not be solved by the FirstLinear solver. Here we test that # it does not match and the asking for a general solution gives # ODEMatchError problem = SingleODEProblem(f(x).diff(x) + f(x)*f(x), f(x), x) solver = FirstLinear(problem) raises(ODEMatchError, lambda: solver.get_general_solution()) solver = FirstLinear(problem) assert solver.matches() is False #These are just test for order of ODE problem = SingleODEProblem(f(x).diff(x) + f(x), f(x), x) assert problem.order == 1 problem = SingleODEProblem(f(x).diff(x,4) + f(x).diff(x,2) - f(x).diff(x,3), f(x), x) assert problem.order == 4 problem = SingleODEProblem(f(x).diff(x, 3) + f(x).diff(x, 2) - f(x)**2, f(x), x) assert problem.is_autonomous == True problem = SingleODEProblem(f(x).diff(x, 3) + x*f(x).diff(x, 2) - f(x)**2, f(x), x) assert problem.is_autonomous == False def test_linear_coefficients(): _ode_solver_test(_get_examples_ode_sol_linear_coefficients) @slow def test_1st_homogeneous_coeff_ode(): #These were marked as test_1st_homogeneous_coeff_corner_case eq1 = f(x).diff(x) - f(x)/x c1 = classify_ode(eq1, f(x)) eq2 = x*f(x).diff(x) - f(x) c2 = classify_ode(eq2, f(x)) sdi = "1st_homogeneous_coeff_subs_dep_div_indep" sid = "1st_homogeneous_coeff_subs_indep_div_dep" assert sid not in c1 and sdi not in c1 assert sid not in c2 and sdi not in c2 _ode_solver_test(_get_examples_ode_sol_1st_homogeneous_coeff_subs_dep_div_indep) _ode_solver_test(_get_examples_ode_sol_1st_homogeneous_coeff_best) @slow def test_slow_examples_1st_homogeneous_coeff_ode(): _ode_solver_test(_get_examples_ode_sol_1st_homogeneous_coeff_subs_dep_div_indep, run_slow_test=True) _ode_solver_test(_get_examples_ode_sol_1st_homogeneous_coeff_best, run_slow_test=True) @slow def test_nth_linear_constant_coeff_homogeneous(): _ode_solver_test(_get_examples_ode_sol_nth_linear_constant_coeff_homogeneous) @slow def test_slow_examples_nth_linear_constant_coeff_homogeneous(): _ode_solver_test(_get_examples_ode_sol_nth_linear_constant_coeff_homogeneous, run_slow_test=True) def test_Airy_equation(): _ode_solver_test(_get_examples_ode_sol_2nd_linear_airy) @slow def test_lie_group(): _ode_solver_test(_get_examples_ode_sol_lie_group) @slow def test_separable_reduced(): df = f(x).diff(x) eq = (x / f(x))*df + tan(x**2*f(x) / (x**2*f(x) - 1)) assert classify_ode(eq) == ('factorable', 'separable_reduced', 'lie_group', 'separable_reduced_Integral') _ode_solver_test(_get_examples_ode_sol_separable_reduced) @slow def test_slow_examples_separable_reduced(): _ode_solver_test(_get_examples_ode_sol_separable_reduced, run_slow_test=True) @slow def test_2nd_2F1_hypergeometric(): _ode_solver_test(_get_examples_ode_sol_2nd_2F1_hypergeometric) def test_2nd_2F1_hypergeometric_integral(): eq = x*(x-1)*f(x).diff(x, 2) + (-1+ S(7)/2*x)*f(x).diff(x) + f(x) sol = Eq(f(x), (C1 + C2*Integral(exp(Integral((1 - x/2)/(x*(x - 1)), x))/(1 - x/2)**2, x))*exp(Integral(1/(x - 1), x)/4)*exp(-Integral(7/(x - 1), x)/4)*hyper((S(1)/2, -1), (1,), x)) assert sol == dsolve(eq, hint='2nd_hypergeometric_Integral') assert checkodesol(eq, sol) == (True, 0) @slow def test_2nd_nonlinear_autonomous_conserved(): _ode_solver_test(_get_examples_ode_sol_2nd_nonlinear_autonomous_conserved) def test_2nd_nonlinear_autonomous_conserved_integral(): eq = f(x).diff(x, 2) + asin(f(x)) actual = [Eq(Integral(1/sqrt(C1 - 2*Integral(asin(_u), _u)), (_u, f(x))), C2 + x), Eq(Integral(1/sqrt(C1 - 2*Integral(asin(_u), _u)), (_u, f(x))), C2 - x)] solved = dsolve(eq, hint='2nd_nonlinear_autonomous_conserved_Integral', simplify=False) for a,s in zip(actual, solved): assert a.dummy_eq(s) # checkodesol unable to simplify solutions with f(x) in an integral equation assert checkodesol(eq, [s.doit() for s in solved]) == [(True, 0), (True, 0)] def test_2nd_linear_bessel_equation(): _ode_solver_test(_get_examples_ode_sol_2nd_linear_bessel) @slow def test_nth_algebraic(): eqn = f(x) + f(x)*f(x).diff(x) solns = [Eq(f(x), exp(x)), Eq(f(x), C1*exp(C2*x))] solns_final = _remove_redundant_solutions(eqn, solns, 2, x) assert solns_final == [Eq(f(x), C1*exp(C2*x))] _ode_solver_test(_get_examples_ode_sol_nth_algebraic) @slow def test_slow_examples_nth_linear_constant_coeff_var_of_parameters(): _ode_solver_test(_get_examples_ode_sol_nth_linear_var_of_parameters, run_slow_test=True) def test_nth_linear_constant_coeff_var_of_parameters(): _ode_solver_test(_get_examples_ode_sol_nth_linear_var_of_parameters) @slow def test_nth_linear_constant_coeff_variation_of_parameters__integral(): # solve_variation_of_parameters shouldn't attempt to simplify the # Wronskian if simplify=False. If wronskian() ever gets good enough # to simplify the result itself, this test might fail. our_hint = 'nth_linear_constant_coeff_variation_of_parameters_Integral' eq = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x) sol_simp = dsolve(eq, f(x), hint=our_hint, simplify=True) sol_nsimp = dsolve(eq, f(x), hint=our_hint, simplify=False) assert sol_simp != sol_nsimp assert checkodesol(eq, sol_simp, order=5, solve_for_func=False) == (True, 0) assert checkodesol(eq, sol_simp, order=5, solve_for_func=False) == (True, 0) @slow def test_slow_examples_1st_exact(): _ode_solver_test(_get_examples_ode_sol_1st_exact, run_slow_test=True) @slow def test_1st_exact(): _ode_solver_test(_get_examples_ode_sol_1st_exact) def test_1st_exact_integral(): eq = cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x) sol_1 = dsolve(eq, f(x), simplify=False, hint='1st_exact_Integral') assert checkodesol(eq, sol_1, order=1, solve_for_func=False) @slow def test_slow_examples_nth_order_reducible(): _ode_solver_test(_get_examples_ode_sol_nth_order_reducible, run_slow_test=True) @slow def test_slow_examples_nth_linear_constant_coeff_undetermined_coefficients(): _ode_solver_test(_get_examples_ode_sol_nth_linear_undetermined_coefficients, run_slow_test=True) @slow def test_slow_examples_separable(): _ode_solver_test(_get_examples_ode_sol_separable, run_slow_test=True) def test_nth_linear_constant_coeff_undetermined_coefficients(): #issue-https://github.com/sympy/sympy/issues/5787 # This test case is to show the classification of imaginary constants under # nth_linear_constant_coeff_undetermined_coefficients eq = Eq(diff(f(x), x), I*f(x) + S.Half - I) our_hint = 'nth_linear_constant_coeff_undetermined_coefficients' assert our_hint in classify_ode(eq) _ode_solver_test(_get_examples_ode_sol_nth_linear_undetermined_coefficients) def test_nth_order_reducible(): F = lambda eq: NthOrderReducible(SingleODEProblem(eq, f(x), x))._matches() D = Derivative assert F(D(y*f(x), x, y) + D(f(x), x)) == False assert F(D(y*f(y), y, y) + D(f(y), y)) == False assert F(f(x)*D(f(x), x) + D(f(x), x, 2))== False assert F(D(x*f(y), y, 2) + D(u*y*f(x), x, 3)) == False # no simplification by design assert F(D(f(y), y, 2) + D(f(y), y, 3) + D(f(x), x, 4)) == False assert F(D(f(x), x, 2) + D(f(x), x, 3)) == True _ode_solver_test(_get_examples_ode_sol_nth_order_reducible) @slow def test_separable(): _ode_solver_test(_get_examples_ode_sol_separable) @slow def test_factorable(): assert integrate(-asin(f(2*x)+pi), x) == -Integral(asin(pi + f(2*x)), x) _ode_solver_test(_get_examples_ode_sol_factorable) @slow def test_slow_examples_factorable(): _ode_solver_test(_get_examples_ode_sol_factorable, run_slow_test=True) def test_Riccati_special_minus2(): _ode_solver_test(_get_examples_ode_sol_riccati) @slow def test_1st_rational_riccati(): _ode_solver_test(_get_examples_ode_sol_1st_rational_riccati) def test_Bernoulli(): _ode_solver_test(_get_examples_ode_sol_bernoulli) def test_1st_linear(): _ode_solver_test(_get_examples_ode_sol_1st_linear) def test_almost_linear(): _ode_solver_test(_get_examples_ode_sol_almost_linear) def test_Liouville_ODE(): hint = 'Liouville' not_Liouville1 = classify_ode(diff(f(x), x)/x + f(x)*diff(f(x), x, x)/2 - diff(f(x), x)**2/2, f(x)) not_Liouville2 = classify_ode(diff(f(x), x)/x + diff(f(x), x, x)/2 - x*diff(f(x), x)**2/2, f(x)) assert hint not in not_Liouville1 assert hint not in not_Liouville2 assert hint + '_Integral' not in not_Liouville1 assert hint + '_Integral' not in not_Liouville2 _ode_solver_test(_get_examples_ode_sol_liouville) def test_nth_order_linear_euler_eq_homogeneous(): x, t, a, b, c = symbols('x t a b c') y = Function('y') our_hint = "nth_linear_euler_eq_homogeneous" eq = diff(f(t), t, 4)*t**4 - 13*diff(f(t), t, 2)*t**2 + 36*f(t) assert our_hint in classify_ode(eq) eq = a*y(t) + b*t*diff(y(t), t) + c*t**2*diff(y(t), t, 2) assert our_hint in classify_ode(eq) _ode_solver_test(_get_examples_ode_sol_euler_homogeneous) def test_nth_order_linear_euler_eq_nonhomogeneous_undetermined_coefficients(): x, t = symbols('x t') a, b, c, d = symbols('a b c d', integer=True) our_hint = "nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients" eq = x**4*diff(f(x), x, 4) - 13*x**2*diff(f(x), x, 2) + 36*f(x) + x assert our_hint in classify_ode(eq, f(x)) eq = a*x**2*diff(f(x), x, 2) + b*x*diff(f(x), x) + c*f(x) + d*log(x) assert our_hint in classify_ode(eq, f(x)) _ode_solver_test(_get_examples_ode_sol_euler_undetermined_coeff) def test_nth_order_linear_euler_eq_nonhomogeneous_variation_of_parameters(): x, t = symbols('x, t') a, b, c, d = symbols('a, b, c, d', integer=True) our_hint = "nth_linear_euler_eq_nonhomogeneous_variation_of_parameters" eq = Eq(x**2*diff(f(x),x,2) - 8*x*diff(f(x),x) + 12*f(x), x**2) assert our_hint in classify_ode(eq, f(x)) eq = Eq(a*x**3*diff(f(x),x,3) + b*x**2*diff(f(x),x,2) + c*x*diff(f(x),x) + d*f(x), x*log(x)) assert our_hint in classify_ode(eq, f(x)) _ode_solver_test(_get_examples_ode_sol_euler_var_para) @_add_example_keys def _get_examples_ode_sol_euler_homogeneous(): r1, r2, r3, r4, r5 = [rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, n) for n in range(5)] return { 'hint': "nth_linear_euler_eq_homogeneous", 'func': f(x), 'examples':{ 'euler_hom_01': { 'eq': Eq(-3*diff(f(x), x)*x + 2*x**2*diff(f(x), x, x), 0), 'sol': [Eq(f(x), C1 + C2*x**Rational(5, 2))], }, 'euler_hom_02': { 'eq': Eq(3*f(x) - 5*diff(f(x), x)*x + 2*x**2*diff(f(x), x, x), 0), 'sol': [Eq(f(x), C1*sqrt(x) + C2*x**3)] }, 'euler_hom_03': { 'eq': Eq(4*f(x) + 5*diff(f(x), x)*x + x**2*diff(f(x), x, x), 0), 'sol': [Eq(f(x), (C1 + C2*log(x))/x**2)] }, 'euler_hom_04': { 'eq': Eq(6*f(x) - 6*diff(f(x), x)*x + 1*x**2*diff(f(x), x, x) + x**3*diff(f(x), x, x, x), 0), 'sol': [Eq(f(x), C1/x**2 + C2*x + C3*x**3)] }, 'euler_hom_05': { 'eq': Eq(-125*f(x) + 61*diff(f(x), x)*x - 12*x**2*diff(f(x), x, x) + x**3*diff(f(x), x, x, x), 0), 'sol': [Eq(f(x), x**5*(C1 + C2*log(x) + C3*log(x)**2))] }, 'euler_hom_06': { 'eq': x**2*diff(f(x), x, 2) + x*diff(f(x), x) - 9*f(x), 'sol': [Eq(f(x), C1*x**-3 + C2*x**3)] }, 'euler_hom_07': { 'eq': sin(x)*x**2*f(x).diff(x, 2) + sin(x)*x*f(x).diff(x) + sin(x)*f(x), 'sol': [Eq(f(x), C1*sin(log(x)) + C2*cos(log(x)))], 'XFAIL': ['2nd_power_series_regular','nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients'] }, 'euler_hom_08': { 'eq': x**6 * f(x).diff(x, 6) - x*f(x).diff(x) + f(x), 'sol': [Eq(f(x), C1*x + C2*x**r1 + C3*x**r2 + C4*x**r3 + C5*x**r4 + C6*x**r5)], 'checkodesol_XFAIL':True }, #This example is from issue: https://github.com/sympy/sympy/issues/15237 #This example is from issue: # https://github.com/sympy/sympy/issues/15237 'euler_hom_09': { 'eq': Derivative(x*f(x), x, x, x), 'sol': [Eq(f(x), C1 + C2/x + C3*x)], }, } } @_add_example_keys def _get_examples_ode_sol_euler_undetermined_coeff(): return { 'hint': "nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients", 'func': f(x), 'examples':{ 'euler_undet_01': { 'eq': Eq(x**2*diff(f(x), x, x) + x*diff(f(x), x), 1), 'sol': [Eq(f(x), C1 + C2*log(x) + log(x)**2/2)] }, 'euler_undet_02': { 'eq': Eq(x**2*diff(f(x), x, x) - 2*x*diff(f(x), x) + 2*f(x), x**3), 'sol': [Eq(f(x), x*(C1 + C2*x + Rational(1, 2)*x**2))] }, 'euler_undet_03': { 'eq': Eq(x**2*diff(f(x), x, x) - x*diff(f(x), x) - 3*f(x), log(x)/x), 'sol': [Eq(f(x), (C1 + C2*x**4 - log(x)**2/8 - log(x)/16)/x)] }, 'euler_undet_04': { 'eq': Eq(x**2*diff(f(x), x, x) + 3*x*diff(f(x), x) - 8*f(x), log(x)**3 - log(x)), 'sol': [Eq(f(x), C1/x**4 + C2*x**2 - Rational(1,8)*log(x)**3 - Rational(3,32)*log(x)**2 - Rational(1,64)*log(x) - Rational(7, 256))] }, 'euler_undet_05': { 'eq': Eq(x**3*diff(f(x), x, x, x) - 3*x**2*diff(f(x), x, x) + 6*x*diff(f(x), x) - 6*f(x), log(x)), 'sol': [Eq(f(x), C1*x + C2*x**2 + C3*x**3 - Rational(1, 6)*log(x) - Rational(11, 36))] }, #Below examples were added for the issue: https://github.com/sympy/sympy/issues/5096 'euler_undet_06': { 'eq': 2*x**2*f(x).diff(x, 2) + f(x) + sqrt(2*x)*sin(log(2*x)/2), 'sol': [Eq(f(x), sqrt(x)*(C1*sin(log(x)/2) + C2*cos(log(x)/2) + sqrt(2)*log(x)*cos(log(2*x)/2)/2))] }, 'euler_undet_07': { 'eq': 2*x**2*f(x).diff(x, 2) + f(x) + sin(log(2*x)/2), 'sol': [Eq(f(x), C1*sqrt(x)*sin(log(x)/2) + C2*sqrt(x)*cos(log(x)/2) - 2*sin(log(2*x)/2)/5 - 4*cos(log(2*x)/2)/5)] }, } } @_add_example_keys def _get_examples_ode_sol_euler_var_para(): return { 'hint': "nth_linear_euler_eq_nonhomogeneous_variation_of_parameters", 'func': f(x), 'examples':{ 'euler_var_01': { 'eq': Eq(x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x), x**4), 'sol': [Eq(f(x), x*(C1 + C2*x + x**3/6))] }, 'euler_var_02': { 'eq': Eq(3*x**2*diff(f(x), x, x) + 6*x*diff(f(x), x) - 6*f(x), x**3*exp(x)), 'sol': [Eq(f(x), C1/x**2 + C2*x + x*exp(x)/3 - 4*exp(x)/3 + 8*exp(x)/(3*x) - 8*exp(x)/(3*x**2))] }, 'euler_var_03': { 'eq': Eq(x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x), x**4*exp(x)), 'sol': [Eq(f(x), x*(C1 + C2*x + x*exp(x) - 2*exp(x)))] }, 'euler_var_04': { 'eq': x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - log(x), 'sol': [Eq(f(x), C1*x + C2*x**2 + log(x)/2 + Rational(3, 4))] }, 'euler_var_05': { 'eq': -exp(x) + (x*Derivative(f(x), (x, 2)) + Derivative(f(x), x))/x, 'sol': [Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))] }, 'euler_var_06': { 'eq': x**2 * f(x).diff(x, 2) + x * f(x).diff(x) + 4 * f(x) - 1/x, 'sol': [Eq(f(x), C1*sin(2*log(x)) + C2*cos(2*log(x)) + 1/(5*x))] }, } } @_add_example_keys def _get_examples_ode_sol_bernoulli(): # Type: Bernoulli, f'(x) + p(x)*f(x) == q(x)*f(x)**n return { 'hint': "Bernoulli", 'func': f(x), 'examples':{ 'bernoulli_01': { 'eq': Eq(x*f(x).diff(x) + f(x) - f(x)**2, 0), 'sol': [Eq(f(x), 1/(C1*x + 1))], 'XFAIL': ['separable_reduced'] }, 'bernoulli_02': { 'eq': f(x).diff(x) - y*f(x), 'sol': [Eq(f(x), C1*exp(x*y))] }, 'bernoulli_03': { 'eq': f(x)*f(x).diff(x) - 1, 'sol': [Eq(f(x), -sqrt(C1 + 2*x)), Eq(f(x), sqrt(C1 + 2*x))] }, } } @_add_example_keys def _get_examples_ode_sol_riccati(): # Type: Riccati special alpha = -2, a*dy/dx + b*y**2 + c*y/x +d/x**2 return { 'hint': "Riccati_special_minus2", 'func': f(x), 'examples':{ 'riccati_01': { 'eq': 2*f(x).diff(x) + f(x)**2 - f(x)/x + 3*x**(-2), 'sol': [Eq(f(x), (-sqrt(3)*tan(C1 + sqrt(3)*log(x)/4) + 3)/(2*x))], }, }, } @_add_example_keys def _get_examples_ode_sol_1st_rational_riccati(): # Type: 1st Order Rational Riccati, dy/dx = a + b*y + c*y**2, # a, b, c are rational functions of x return { 'hint': "1st_rational_riccati", 'func': f(x), 'examples':{ # a(x) is a constant "rational_riccati_01": { "eq": Eq(f(x).diff(x) + f(x)**2 - 2, 0), "sol": [Eq(f(x), sqrt(2)*(-C1 - exp(2*sqrt(2)*x))/(C1 - exp(2*sqrt(2)*x)))] }, # a(x) is a constant "rational_riccati_02": { "eq": f(x)**2 + Derivative(f(x), x) + 4*f(x)/x + 2/x**2, "sol": [Eq(f(x), (-2*C1 - x)/(x*(C1 + x)))] }, # a(x) is a constant "rational_riccati_03": { "eq": 2*x**2*Derivative(f(x), x) - x*(4*f(x) + Derivative(f(x), x) - 4) + (f(x) - 1)*f(x), "sol": [Eq(f(x), (C1 + 2*x**2)/(C1 + x))] }, # Constant coefficients "rational_riccati_04": { "eq": f(x).diff(x) - 6 - 5*f(x) - f(x)**2, "sol": [Eq(f(x), (-2*C1 + 3*exp(x))/(C1 - exp(x)))] }, # One pole of multiplicity 2 "rational_riccati_05": { "eq": x**2 - (2*x + 1/x)*f(x) + f(x)**2 + Derivative(f(x), x), "sol": [Eq(f(x), x*(C1 + x**2 + 1)/(C1 + x**2 - 1))] }, # One pole of multiplicity 2 "rational_riccati_06": { "eq": x**4*Derivative(f(x), x) + x**2 - x*(2*f(x)**2 + Derivative(f(x), x)) + f(x), "sol": [Eq(f(x), x*(C1*x - x + 1)/(C1 + x**2 - 1))] }, # Multiple poles of multiplicity 2 "rational_riccati_07": { "eq": -f(x)**2 + Derivative(f(x), x) + (15*x**2 - 20*x + 7)/((x - 1)**2*(2*x \ - 1)**2), "sol": [Eq(f(x), (9*C1*x - 6*C1 - 15*x**5 + 60*x**4 - 94*x**3 + 72*x**2 - \ 33*x + 8)/(6*C1*x**2 - 9*C1*x + 3*C1 + 6*x**6 - 29*x**5 + 57*x**4 - \ 58*x**3 + 28*x**2 - 3*x - 1))] }, # Imaginary poles "rational_riccati_08": { "eq": Derivative(f(x), x) + (3*x**2 + 1)*f(x)**2/x + (6*x**2 - x + 3)*f(x)/(x*(x \ - 1)) + (3*x**2 - 2*x + 2)/(x*(x - 1)**2), "sol": [Eq(f(x), (-C1 - x**3 + x**2 - 2*x + 1)/(C1*x - C1 + x**4 - x**3 + x**2 - \ 2*x + 1))], }, # Imaginary coefficients in equation "rational_riccati_09": { "eq": Derivative(f(x), x) - 2*I*(f(x)**2 + 1)/x, "sol": [Eq(f(x), (-I*C1 + I*x**4 + I)/(C1 + x**4 - 1))] }, # Regression: linsolve returning empty solution # Large value of m (> 10) "rational_riccati_10": { "eq": Eq(Derivative(f(x), x), x*f(x)/(S(3)/2 - 2*x) + (x/2 - S(1)/3)*f(x)**2/\ (2*x/3 - S(1)/2) - S(5)/4 + (281*x**2 - 1260*x + 756)/(16*x**3 - 12*x**2)), "sol": [Eq(f(x), (40*C1*x**14 + 28*C1*x**13 + 420*C1*x**12 + 2940*C1*x**11 + \ 18480*C1*x**10 + 103950*C1*x**9 + 519750*C1*x**8 + 2286900*C1*x**7 + \ 8731800*C1*x**6 + 28378350*C1*x**5 + 76403250*C1*x**4 + 163721250*C1*x**3 \ + 261954000*C1*x**2 + 278326125*C1*x + 147349125*C1 + x*exp(2*x) - 9*exp(2*x) \ )/(x*(24*C1*x**13 + 140*C1*x**12 + 840*C1*x**11 + 4620*C1*x**10 + 23100*C1*x**9 \ + 103950*C1*x**8 + 415800*C1*x**7 + 1455300*C1*x**6 + 4365900*C1*x**5 + \ 10914750*C1*x**4 + 21829500*C1*x**3 + 32744250*C1*x**2 + 32744250*C1*x + \ 16372125*C1 - exp(2*x))))] } } } @_add_example_keys def _get_examples_ode_sol_1st_linear(): # Type: first order linear form f'(x)+p(x)f(x)=q(x) return { 'hint': "1st_linear", 'func': f(x), 'examples':{ 'linear_01': { 'eq': Eq(f(x).diff(x) + x*f(x), x**2), 'sol': [Eq(f(x), (C1 + x*exp(x**2/2)- sqrt(2)*sqrt(pi)*erfi(sqrt(2)*x/2)/2)*exp(-x**2/2))], }, }, } @_add_example_keys def _get_examples_ode_sol_factorable(): """ some hints are marked as xfail for examples because they missed additional algebraic solution which could be found by Factorable hint. Fact_01 raise exception for nth_linear_constant_coeff_undetermined_coefficients""" y = Dummy('y') a0,a1,a2,a3,a4 = symbols('a0, a1, a2, a3, a4') return { 'hint': "factorable", 'func': f(x), 'examples':{ 'fact_01': { 'eq': f(x) + f(x)*f(x).diff(x), 'sol': [Eq(f(x), 0), Eq(f(x), C1 - x)], 'XFAIL': ['separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', 'lie_group', 'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', 'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters', 'nth_linear_constant_coeff_undetermined_coefficients'] }, 'fact_02': { 'eq': f(x)*(f(x).diff(x)+f(x)*x+2), 'sol': [Eq(f(x), (C1 - sqrt(2)*sqrt(pi)*erfi(sqrt(2)*x/2))*exp(-x**2/2)), Eq(f(x), 0)], 'XFAIL': ['Bernoulli', '1st_linear', 'lie_group'] }, 'fact_03': { 'eq': (f(x).diff(x)+f(x)*x**2)*(f(x).diff(x, 2) + x*f(x)), 'sol': [Eq(f(x), C1*airyai(-x) + C2*airybi(-x)),Eq(f(x), C1*exp(-x**3/3))] }, 'fact_04': { 'eq': (f(x).diff(x)+f(x)*x**2)*(f(x).diff(x, 2) + f(x)), 'sol': [Eq(f(x), C1*exp(-x**3/3)), Eq(f(x), C1*sin(x) + C2*cos(x))] }, 'fact_05': { 'eq': (f(x).diff(x)**2-1)*(f(x).diff(x)**2-4), 'sol': [Eq(f(x), C1 - x), Eq(f(x), C1 + x), Eq(f(x), C1 + 2*x), Eq(f(x), C1 - 2*x)] }, 'fact_06': { 'eq': (f(x).diff(x, 2)-exp(f(x)))*f(x).diff(x), 'sol': [ Eq(f(x), log(C1/(cos(C1*sqrt(-1/C1)*(C2 + x)) - 1))), Eq(f(x), log(C1/(cos(C1*sqrt(-1/C1)*(C2 - x)) - 1))), Eq(f(x), C1) ], 'slow': True, }, 'fact_07': { 'eq': (f(x).diff(x)**2-1)*(f(x)*f(x).diff(x)-1), 'sol': [Eq(f(x), C1 - x), Eq(f(x), -sqrt(C1 + 2*x)),Eq(f(x), sqrt(C1 + 2*x)), Eq(f(x), C1 + x)] }, 'fact_08': { 'eq': Derivative(f(x), x)**4 - 2*Derivative(f(x), x)**2 + 1, 'sol': [Eq(f(x), C1 - x), Eq(f(x), C1 + x)] }, 'fact_09': { 'eq': f(x)**2*Derivative(f(x), x)**6 - 2*f(x)**2*Derivative(f(x), x)**4 + f(x)**2*Derivative(f(x), x)**2 - 2*f(x)*Derivative(f(x), x)**5 + 4*f(x)*Derivative(f(x), x)**3 - 2*f(x)*Derivative(f(x), x) + Derivative(f(x), x)**4 - 2*Derivative(f(x), x)**2 + 1, 'sol': [ Eq(f(x), C1 - x), Eq(f(x), -sqrt(C1 + 2*x)), Eq(f(x), sqrt(C1 + 2*x)), Eq(f(x), C1 + x) ] }, 'fact_10': { 'eq': x**4*f(x)**2 + 2*x**4*f(x)*Derivative(f(x), (x, 2)) + x**4*Derivative(f(x), (x, 2))**2 + 2*x**3*f(x)*Derivative(f(x), x) + 2*x**3*Derivative(f(x), x)*Derivative(f(x), (x, 2)) - 7*x**2*f(x)**2 - 7*x**2*f(x)*Derivative(f(x), (x, 2)) + x**2*Derivative(f(x), x)**2 - 7*x*f(x)*Derivative(f(x), x) + 12*f(x)**2, 'sol': [ Eq(f(x), C1*besselj(2, x) + C2*bessely(2, x)), Eq(f(x), C1*besselj(sqrt(3), x) + C2*bessely(sqrt(3), x)) ], 'slow': True, }, 'fact_11': { 'eq': (f(x).diff(x, 2)-exp(f(x)))*(f(x).diff(x, 2)+exp(f(x))), 'sol': [ Eq(f(x), log(C1/(cos(C1*sqrt(-1/C1)*(C2 + x)) - 1))), Eq(f(x), log(C1/(cos(C1*sqrt(-1/C1)*(C2 - x)) - 1))), Eq(f(x), log(C1/(1 - cos(C1*sqrt(-1/C1)*(C2 + x))))), Eq(f(x), log(C1/(1 - cos(C1*sqrt(-1/C1)*(C2 - x))))) ], 'dsolve_too_slow': True, }, #Below examples were added for the issue: https://github.com/sympy/sympy/issues/15889 'fact_12': { 'eq': exp(f(x).diff(x))-f(x)**2, 'sol': [Eq(NonElementaryIntegral(1/log(y**2), (y, f(x))), C1 + x)], 'XFAIL': ['lie_group'] #It shows not implemented error for lie_group. }, 'fact_13': { 'eq': f(x).diff(x)**2 - f(x)**3, 'sol': [Eq(f(x), 4/(C1**2 - 2*C1*x + x**2))], 'XFAIL': ['lie_group'] #It shows not implemented error for lie_group. }, 'fact_14': { 'eq': f(x).diff(x)**2 - f(x), 'sol': [Eq(f(x), C1**2/4 - C1*x/2 + x**2/4)] }, 'fact_15': { 'eq': f(x).diff(x)**2 - f(x)**2, 'sol': [Eq(f(x), C1*exp(x)), Eq(f(x), C1*exp(-x))] }, 'fact_16': { 'eq': f(x).diff(x)**2 - f(x)**3, 'sol': [Eq(f(x), 4/(C1**2 - 2*C1*x + x**2))], }, # kamke ode 1.1 'fact_17': { 'eq': f(x).diff(x)-(a4*x**4 + a3*x**3 + a2*x**2 + a1*x + a0)**(-1/2), 'sol': [Eq(f(x), C1 + Integral(1/sqrt(a0 + a1*x + a2*x**2 + a3*x**3 + a4*x**4), x))], 'slow': True }, # This is from issue: https://github.com/sympy/sympy/issues/9446 'fact_18':{ 'eq': Eq(f(2 * x), sin(Derivative(f(x)))), 'sol': [Eq(f(x), C1 + Integral(pi - asin(f(2*x)), x)), Eq(f(x), C1 + Integral(asin(f(2*x)), x))], 'checkodesol_XFAIL':True }, # This is from issue: https://github.com/sympy/sympy/issues/7093 'fact_19': { 'eq': Derivative(f(x), x)**2 - x**3, 'sol': [Eq(f(x), C1 - 2*x**Rational(5,2)/5), Eq(f(x), C1 + 2*x**Rational(5,2)/5)], }, 'fact_20': { 'eq': x*f(x).diff(x, 2) - x*f(x), 'sol': [Eq(f(x), C1*exp(-x) + C2*exp(x))], }, } } @_add_example_keys def _get_examples_ode_sol_almost_linear(): from sympy.functions.special.error_functions import Ei A = Symbol('A', positive=True) f = Function('f') d = f(x).diff(x) return { 'hint': "almost_linear", 'func': f(x), 'examples':{ 'almost_lin_01': { 'eq': x**2*f(x)**2*d + f(x)**3 + 1, 'sol': [Eq(f(x), (C1*exp(3/x) - 1)**Rational(1, 3)), Eq(f(x), (-1 - sqrt(3)*I)*(C1*exp(3/x) - 1)**Rational(1, 3)/2), Eq(f(x), (-1 + sqrt(3)*I)*(C1*exp(3/x) - 1)**Rational(1, 3)/2)], }, 'almost_lin_02': { 'eq': x*f(x)*d + 2*x*f(x)**2 + 1, 'sol': [Eq(f(x), -sqrt((C1 - 2*Ei(4*x))*exp(-4*x))), Eq(f(x), sqrt((C1 - 2*Ei(4*x))*exp(-4*x)))] }, 'almost_lin_03': { 'eq': x*d + x*f(x) + 1, 'sol': [Eq(f(x), (C1 - Ei(x))*exp(-x))] }, 'almost_lin_04': { 'eq': x*exp(f(x))*d + exp(f(x)) + 3*x, 'sol': [Eq(f(x), log(C1/x - x*Rational(3, 2)))], }, 'almost_lin_05': { 'eq': x + A*(x + diff(f(x), x) + f(x)) + diff(f(x), x) + f(x) + 2, 'sol': [Eq(f(x), (C1 + Piecewise( (x, Eq(A + 1, 0)), ((-A*x + A - x - 1)*exp(x)/(A + 1), True)))*exp(-x))], }, } } @_add_example_keys def _get_examples_ode_sol_liouville(): n = Symbol('n') _y = Dummy('y') return { 'hint': "Liouville", 'func': f(x), 'examples':{ 'liouville_01': { 'eq': diff(f(x), x)/x + diff(f(x), x, x)/2 - diff(f(x), x)**2/2, 'sol': [Eq(f(x), log(x/(C1 + C2*x)))], }, 'liouville_02': { 'eq': diff(x*exp(-f(x)), x, x), 'sol': [Eq(f(x), log(x/(C1 + C2*x)))] }, 'liouville_03': { 'eq': ((diff(f(x), x)/x + diff(f(x), x, x)/2 - diff(f(x), x)**2/2)*exp(-f(x))/exp(f(x))).expand(), 'sol': [Eq(f(x), log(x/(C1 + C2*x)))] }, 'liouville_04': { 'eq': diff(f(x), x, x) + 1/f(x)*(diff(f(x), x))**2 + 1/x*diff(f(x), x), 'sol': [Eq(f(x), -sqrt(C1 + C2*log(x))), Eq(f(x), sqrt(C1 + C2*log(x)))], }, 'liouville_05': { 'eq': x*diff(f(x), x, x) + x/f(x)*diff(f(x), x)**2 + x*diff(f(x), x), 'sol': [Eq(f(x), -sqrt(C1 + C2*exp(-x))), Eq(f(x), sqrt(C1 + C2*exp(-x)))], }, 'liouville_06': { 'eq': Eq((x*exp(f(x))).diff(x, x), 0), 'sol': [Eq(f(x), log(C1 + C2/x))], }, 'liouville_07': { 'eq': (diff(f(x), x)/x + diff(f(x), x, x)/2 - diff(f(x), x)**2/2)*exp(-f(x))/exp(f(x)), 'sol': [Eq(f(x), log(x/(C1 + C2*x)))], }, 'liouville_08': { 'eq': x**2*diff(f(x),x) + (n*f(x) + f(x)**2)*diff(f(x),x)**2 + diff(f(x), (x, 2)), 'sol': [Eq(C1 + C2*lowergamma(Rational(1,3), x**3/3) + NonElementaryIntegral(exp(_y**3/3)*exp(_y**2*n/2), (_y, f(x))), 0)], }, } } @_add_example_keys def _get_examples_ode_sol_nth_algebraic(): M, m, r, t = symbols('M m r t') phi = Function('phi') k = Symbol('k') # This one needs a substitution f' = g. # 'algeb_12': { # 'eq': -exp(x) + (x*Derivative(f(x), (x, 2)) + Derivative(f(x), x))/x, # 'sol': [Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))], # }, return { 'hint': "nth_algebraic", 'func': f(x), 'examples':{ 'algeb_01': { 'eq': f(x) * f(x).diff(x) * f(x).diff(x, x) * (f(x) - 1) * (f(x).diff(x) - x), 'sol': [Eq(f(x), C1 + x**2/2), Eq(f(x), C1 + C2*x)] }, 'algeb_02': { 'eq': f(x) * f(x).diff(x) * f(x).diff(x, x) * (f(x) - 1), 'sol': [Eq(f(x), C1 + C2*x)] }, 'algeb_03': { 'eq': f(x) * f(x).diff(x) * f(x).diff(x, x), 'sol': [Eq(f(x), C1 + C2*x)] }, 'algeb_04': { 'eq': Eq(-M * phi(t).diff(t), Rational(3, 2) * m * r**2 * phi(t).diff(t) * phi(t).diff(t,t)), 'sol': [Eq(phi(t), C1), Eq(phi(t), C1 + C2*t - M*t**2/(3*m*r**2))], 'func': phi(t) }, 'algeb_05': { 'eq': (1 - sin(f(x))) * f(x).diff(x), 'sol': [Eq(f(x), C1)], 'XFAIL': ['separable'] #It raised exception. }, 'algeb_06': { 'eq': (diff(f(x)) - x)*(diff(f(x)) + x), 'sol': [Eq(f(x), C1 - x**2/2), Eq(f(x), C1 + x**2/2)] }, 'algeb_07': { 'eq': Eq(Derivative(f(x), x), Derivative(g(x), x)), 'sol': [Eq(f(x), C1 + g(x))], }, 'algeb_08': { 'eq': f(x).diff(x) - C1, #this example is from issue 15999 'sol': [Eq(f(x), C1*x + C2)], }, 'algeb_09': { 'eq': f(x)*f(x).diff(x), 'sol': [Eq(f(x), C1)], }, 'algeb_10': { 'eq': (diff(f(x)) - x)*(diff(f(x)) + x), 'sol': [Eq(f(x), C1 - x**2/2), Eq(f(x), C1 + x**2/2)], }, 'algeb_11': { 'eq': f(x) + f(x)*f(x).diff(x), 'sol': [Eq(f(x), 0), Eq(f(x), C1 - x)], 'XFAIL': ['separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', 'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters'] #nth_linear_constant_coeff_undetermined_coefficients raises exception rest all of them misses a solution. }, 'algeb_12': { 'eq': Derivative(x*f(x), x, x, x), 'sol': [Eq(f(x), (C1 + C2*x + C3*x**2) / x)], 'XFAIL': ['nth_algebraic'] # It passes only when prep=False is set in dsolve. }, 'algeb_13': { 'eq': Eq(Derivative(x*Derivative(f(x), x), x)/x, exp(x)), 'sol': [Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))], 'XFAIL': ['nth_algebraic'] # It passes only when prep=False is set in dsolve. }, # These are simple tests from the old ode module example 14-18 'algeb_14': { 'eq': Eq(f(x).diff(x), 0), 'sol': [Eq(f(x), C1)], }, 'algeb_15': { 'eq': Eq(3*f(x).diff(x) - 5, 0), 'sol': [Eq(f(x), C1 + x*Rational(5, 3))], }, 'algeb_16': { 'eq': Eq(3*f(x).diff(x), 5), 'sol': [Eq(f(x), C1 + x*Rational(5, 3))], }, # Type: 2nd order, constant coefficients (two complex roots) 'algeb_17': { 'eq': Eq(3*f(x).diff(x) - 1, 0), 'sol': [Eq(f(x), C1 + x/3)], }, 'algeb_18': { 'eq': Eq(x*f(x).diff(x) - 1, 0), 'sol': [Eq(f(x), C1 + log(x))], }, # https://github.com/sympy/sympy/issues/6989 'algeb_19': { 'eq': f(x).diff(x) - x*exp(-k*x), 'sol': [Eq(f(x), C1 + Piecewise(((-k*x - 1)*exp(-k*x)/k**2, Ne(k**2, 0)),(x**2/2, True)))], }, 'algeb_20': { 'eq': -f(x).diff(x) + x*exp(-k*x), 'sol': [Eq(f(x), C1 + Piecewise(((-k*x - 1)*exp(-k*x)/k**2, Ne(k**2, 0)),(x**2/2, True)))], }, # https://github.com/sympy/sympy/issues/10867 'algeb_21': { 'eq': Eq(g(x).diff(x).diff(x), (x-2)**2 + (x-3)**3), 'sol': [Eq(g(x), C1 + C2*x + x**5/20 - 2*x**4/3 + 23*x**3/6 - 23*x**2/2)], 'func': g(x), }, # https://github.com/sympy/sympy/issues/13691 'algeb_22': { 'eq': f(x).diff(x) - C1*g(x).diff(x), 'sol': [Eq(f(x), C2 + C1*g(x))], 'func': f(x), }, # https://github.com/sympy/sympy/issues/4838 'algeb_23': { 'eq': f(x).diff(x) - 3*C1 - 3*x**2, 'sol': [Eq(f(x), C2 + 3*C1*x + x**3)], }, } } @_add_example_keys def _get_examples_ode_sol_nth_order_reducible(): return { 'hint': "nth_order_reducible", 'func': f(x), 'examples':{ 'reducible_01': { 'eq': Eq(x*Derivative(f(x), x)**2 + Derivative(f(x), x, 2), 0), 'sol': [Eq(f(x),C1 - sqrt(-1/C2)*log(-C2*sqrt(-1/C2) + x) + sqrt(-1/C2)*log(C2*sqrt(-1/C2) + x))], 'slow': True, }, 'reducible_02': { 'eq': -exp(x) + (x*Derivative(f(x), (x, 2)) + Derivative(f(x), x))/x, 'sol': [Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))], 'slow': True, }, 'reducible_03': { 'eq': Eq(sqrt(2) * f(x).diff(x,x,x) + f(x).diff(x), 0), 'sol': [Eq(f(x), C1 + C2*sin(2**Rational(3, 4)*x/2) + C3*cos(2**Rational(3, 4)*x/2))], 'slow': True, }, 'reducible_04': { 'eq': f(x).diff(x, 2) + 2*f(x).diff(x), 'sol': [Eq(f(x), C1 + C2*exp(-2*x))], }, 'reducible_05': { 'eq': f(x).diff(x, 3) + f(x).diff(x, 2) - 6*f(x).diff(x), 'sol': [Eq(f(x), C1 + C2*exp(-3*x) + C3*exp(2*x))], 'slow': True, }, 'reducible_06': { 'eq': f(x).diff(x, 4) - f(x).diff(x, 3) - 4*f(x).diff(x, 2) + \ 4*f(x).diff(x), 'sol': [Eq(f(x), C1 + C2*exp(-2*x) + C3*exp(x) + C4*exp(2*x))], 'slow': True, }, 'reducible_07': { 'eq': f(x).diff(x, 4) + 3*f(x).diff(x, 3), 'sol': [Eq(f(x), C1 + C2*x + C3*x**2 + C4*exp(-3*x))], 'slow': True, }, 'reducible_08': { 'eq': f(x).diff(x, 4) - 2*f(x).diff(x, 2), 'sol': [Eq(f(x), C1 + C2*x + C3*exp(-sqrt(2)*x) + C4*exp(sqrt(2)*x))], 'slow': True, }, 'reducible_09': { 'eq': f(x).diff(x, 4) + 4*f(x).diff(x, 2), 'sol': [Eq(f(x), C1 + C2*x + C3*sin(2*x) + C4*cos(2*x))], 'slow': True, }, 'reducible_10': { 'eq': f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x), 'sol': [Eq(f(x), C1 + C2*x*sin(x) + C2*cos(x) - C3*x*cos(x) + C3*sin(x) + C4*sin(x) + C5*cos(x))], 'slow': True, }, 'reducible_11': { 'eq': f(x).diff(x, 2) - f(x).diff(x)**3, 'sol': [Eq(f(x), C1 - sqrt(2)*sqrt(-1/(C2 + x))*(C2 + x)), Eq(f(x), C1 + sqrt(2)*sqrt(-1/(C2 + x))*(C2 + x))], 'slow': True, }, # Needs to be a way to know how to combine derivatives in the expression 'reducible_12': { 'eq': Derivative(x*f(x), x, x, x) + Derivative(f(x), x, x, x), 'sol': [Eq(f(x), C1 + C3/Mul(2, (x**2 + 2*x + 1), evaluate=False) + x*(C2 + C3/Mul(2, (x**2 + 2*x + 1), evaluate=False)))], # 2-arg Mul! 'slow': True, }, } } @_add_example_keys def _get_examples_ode_sol_nth_linear_undetermined_coefficients(): # examples 3-27 below are from Ordinary Differential Equations, # Tenenbaum and Pollard, pg. 231 g = exp(-x) f2 = f(x).diff(x, 2) c = 3*f(x).diff(x, 3) + 5*f2 + f(x).diff(x) - f(x) - x t = symbols("t") u = symbols("u",cls=Function) R, L, C, E_0, alpha = symbols("R L C E_0 alpha",positive=True) omega = Symbol('omega') return { 'hint': "nth_linear_constant_coeff_undetermined_coefficients", 'func': f(x), 'examples':{ 'undet_01': { 'eq': c - x*g, 'sol': [Eq(f(x), C3*exp(x/3) - x + (C1 + x*(C2 - x**2/24 - 3*x/32))*exp(-x) - 1)], 'slow': True, }, 'undet_02': { 'eq': c - g, 'sol': [Eq(f(x), C3*exp(x/3) - x + (C1 + x*(C2 - x/8))*exp(-x) - 1)], 'slow': True, }, 'undet_03': { 'eq': f2 + 3*f(x).diff(x) + 2*f(x) - 4, 'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 2)], 'slow': True, }, 'undet_04': { 'eq': f2 + 3*f(x).diff(x) + 2*f(x) - 12*exp(x), 'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 2*exp(x))], 'slow': True, }, 'undet_05': { 'eq': f2 + 3*f(x).diff(x) + 2*f(x) - exp(I*x), 'sol': [Eq(f(x), (S(3)/10 + I/10)*(C1*exp(-2*x) + C2*exp(-x) - I*exp(I*x)))], 'slow': True, }, 'undet_06': { 'eq': f2 + 3*f(x).diff(x) + 2*f(x) - sin(x), 'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + sin(x)/10 - 3*cos(x)/10)], 'slow': True, }, 'undet_07': { 'eq': f2 + 3*f(x).diff(x) + 2*f(x) - cos(x), 'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 3*sin(x)/10 + cos(x)/10)], 'slow': True, }, 'undet_08': { 'eq': f2 + 3*f(x).diff(x) + 2*f(x) - (8 + 6*exp(x) + 2*sin(x)), 'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + exp(x) + sin(x)/5 - 3*cos(x)/5 + 4)], 'slow': True, }, 'undet_09': { 'eq': f2 + f(x).diff(x) + f(x) - x**2, 'sol': [Eq(f(x), -2*x + x**2 + (C1*sin(x*sqrt(3)/2) + C2*cos(x*sqrt(3)/2))*exp(-x/2))], 'slow': True, }, 'undet_10': { 'eq': f2 - 2*f(x).diff(x) - 8*f(x) - 9*x*exp(x) - 10*exp(-x), 'sol': [Eq(f(x), -x*exp(x) - 2*exp(-x) + C1*exp(-2*x) + C2*exp(4*x))], 'slow': True, }, 'undet_11': { 'eq': f2 - 3*f(x).diff(x) - 2*exp(2*x)*sin(x), 'sol': [Eq(f(x), C1 + C2*exp(3*x) - 3*exp(2*x)*sin(x)/5 - exp(2*x)*cos(x)/5)], 'slow': True, }, 'undet_12': { 'eq': f(x).diff(x, 4) - 2*f2 + f(x) - x + sin(x), 'sol': [Eq(f(x), x - sin(x)/4 + (C1 + C2*x)*exp(-x) + (C3 + C4*x)*exp(x))], 'slow': True, }, 'undet_13': { 'eq': f2 + f(x).diff(x) - x**2 - 2*x, 'sol': [Eq(f(x), C1 + x**3/3 + C2*exp(-x))], 'slow': True, }, 'undet_14': { 'eq': f2 + f(x).diff(x) - x - sin(2*x), 'sol': [Eq(f(x), C1 - x - sin(2*x)/5 - cos(2*x)/10 + x**2/2 + C2*exp(-x))], 'slow': True, }, 'undet_15': { 'eq': f2 + f(x) - 4*x*sin(x), 'sol': [Eq(f(x), (C1 - x**2)*cos(x) + (C2 + x)*sin(x))], 'slow': True, }, 'undet_16': { 'eq': f2 + 4*f(x) - x*sin(2*x), 'sol': [Eq(f(x), (C1 - x**2/8)*cos(2*x) + (C2 + x/16)*sin(2*x))], 'slow': True, }, 'undet_17': { 'eq': f2 + 2*f(x).diff(x) + f(x) - x**2*exp(-x), 'sol': [Eq(f(x), (C1 + x*(C2 + x**3/12))*exp(-x))], 'slow': True, }, 'undet_18': { 'eq': f(x).diff(x, 3) + 3*f2 + 3*f(x).diff(x) + f(x) - 2*exp(-x) + \ x**2*exp(-x), 'sol': [Eq(f(x), (C1 + x*(C2 + x*(C3 - x**3/60 + x/3)))*exp(-x))], 'slow': True, }, 'undet_19': { 'eq': f2 + 3*f(x).diff(x) + 2*f(x) - exp(-2*x) - x**2, 'sol': [Eq(f(x), C2*exp(-x) + x**2/2 - x*Rational(3,2) + (C1 - x)*exp(-2*x) + Rational(7,4))], 'slow': True, }, 'undet_20': { 'eq': f2 - 3*f(x).diff(x) + 2*f(x) - x*exp(-x), 'sol': [Eq(f(x), C1*exp(x) + C2*exp(2*x) + (6*x + 5)*exp(-x)/36)], 'slow': True, }, 'undet_21': { 'eq': f2 + f(x).diff(x) - 6*f(x) - x - exp(2*x), 'sol': [Eq(f(x), Rational(-1, 36) - x/6 + C2*exp(-3*x) + (C1 + x/5)*exp(2*x))], 'slow': True, }, 'undet_22': { 'eq': f2 + f(x) - sin(x) - exp(-x), 'sol': [Eq(f(x), C2*sin(x) + (C1 - x/2)*cos(x) + exp(-x)/2)], 'slow': True, }, 'undet_23': { 'eq': f(x).diff(x, 3) - 3*f2 + 3*f(x).diff(x) - f(x) - exp(x), 'sol': [Eq(f(x), (C1 + x*(C2 + x*(C3 + x/6)))*exp(x))], 'slow': True, }, 'undet_24': { 'eq': f2 + f(x) - S.Half - cos(2*x)/2, 'sol': [Eq(f(x), S.Half - cos(2*x)/6 + C1*sin(x) + C2*cos(x))], 'slow': True, }, 'undet_25': { 'eq': f(x).diff(x, 3) - f(x).diff(x) - exp(2*x)*(S.Half - cos(2*x)/2), 'sol': [Eq(f(x), C1 + C2*exp(-x) + C3*exp(x) + (-21*sin(2*x) + 27*cos(2*x) + 130)*exp(2*x)/1560)], 'slow': True, }, #Note: 'undet_26' is referred in 'undet_37' 'undet_26': { 'eq': (f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - sin(x) - cos(x)), 'sol': [Eq(f(x), C1 + x**2 + (C2 + x*(C3 - x/8))*sin(x) + (C4 + x*(C5 + x/8))*cos(x))], 'slow': True, }, 'undet_27': { 'eq': f2 + f(x) - cos(x)/2 + cos(3*x)/2, 'sol': [Eq(f(x), cos(3*x)/16 + C2*cos(x) + (C1 + x/4)*sin(x))], 'slow': True, }, 'undet_28': { 'eq': f(x).diff(x) - 1, 'sol': [Eq(f(x), C1 + x)], 'slow': True, }, # https://github.com/sympy/sympy/issues/19358 'undet_29': { 'eq': f2 + f(x).diff(x) + exp(x-C1), 'sol': [Eq(f(x), C2 + C3*exp(-x) - exp(-C1 + x)/2)], 'slow': True, }, # https://github.com/sympy/sympy/issues/18408 'undet_30': { 'eq': f(x).diff(x, 3) - f(x).diff(x) - sinh(x), 'sol': [Eq(f(x), C1 + C2*exp(-x) + C3*exp(x) + x*sinh(x)/2)], }, 'undet_31': { 'eq': f(x).diff(x, 2) - 49*f(x) - sinh(3*x), 'sol': [Eq(f(x), C1*exp(-7*x) + C2*exp(7*x) - sinh(3*x)/40)], }, 'undet_32': { 'eq': f(x).diff(x, 3) - f(x).diff(x) - sinh(x) - exp(x), 'sol': [Eq(f(x), C1 + C3*exp(-x) + x*sinh(x)/2 + (C2 + x/2)*exp(x))], }, # https://github.com/sympy/sympy/issues/5096 'undet_33': { 'eq': f(x).diff(x, x) + f(x) - x*sin(x - 2), 'sol': [Eq(f(x), C1*sin(x) + C2*cos(x) - x**2*cos(x - 2)/4 + x*sin(x - 2)/4)], }, 'undet_34': { 'eq': f(x).diff(x, 2) + f(x) - x**4*sin(x-1), 'sol': [ Eq(f(x), C1*sin(x) + C2*cos(x) - x**5*cos(x - 1)/10 + x**4*sin(x - 1)/4 + x**3*cos(x - 1)/2 - 3*x**2*sin(x - 1)/4 - 3*x*cos(x - 1)/4)], }, 'undet_35': { 'eq': f(x).diff(x, 2) - f(x) - exp(x - 1), 'sol': [Eq(f(x), C2*exp(-x) + (C1 + x*exp(-1)/2)*exp(x))], }, 'undet_36': { 'eq': f(x).diff(x, 2)+f(x)-(sin(x-2)+1), 'sol': [Eq(f(x), C1*sin(x) + C2*cos(x) - x*cos(x - 2)/2 + 1)], }, # Equivalent to example_name 'undet_26'. # This previously failed because the algorithm for undetermined coefficients # didn't know to multiply exp(I*x) by sufficient x because it is linearly # dependent on sin(x) and cos(x). 'undet_37': { 'eq': f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x), 'sol': [Eq(f(x), C1 + x**2*(I*exp(I*x)/8 + 1) + (C2 + C3*x)*sin(x) + (C4 + C5*x)*cos(x))], }, # https://github.com/sympy/sympy/issues/12623 'undet_38': { 'eq': Eq( u(t).diff(t,t) + R /L*u(t).diff(t) + 1/(L*C)*u(t), alpha), 'sol': [Eq(u(t), C*L*alpha + C2*exp(-t*(R + sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L)) + C1*exp(t*(-R + sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L)))], 'func': u(t) }, 'undet_39': { 'eq': Eq( L*C*u(t).diff(t,t) + R*C*u(t).diff(t) + u(t), E_0*exp(I*omega*t) ), 'sol': [Eq(u(t), C2*exp(-t*(R + sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L)) + C1*exp(t*(-R + sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L)) - E_0*exp(I*omega*t)/(C*L*omega**2 - I*C*R*omega - 1))], 'func': u(t), }, # https://github.com/sympy/sympy/issues/6879 'undet_40': { 'eq': Eq(Derivative(f(x), x, 2) - 2*Derivative(f(x), x) + f(x), sin(x)), 'sol': [Eq(f(x), (C1 + C2*x)*exp(x) + cos(x)/2)], }, } } @_add_example_keys def _get_examples_ode_sol_separable(): # test_separable1-5 are from Ordinary Differential Equations, Tenenbaum and # Pollard, pg. 55 t,a = symbols('a,t') m = 96 g = 9.8 k = .2 f1 = g * m v = Function('v') return { 'hint': "separable", 'func': f(x), 'examples':{ 'separable_01': { 'eq': f(x).diff(x) - f(x), 'sol': [Eq(f(x), C1*exp(x))], }, 'separable_02': { 'eq': x*f(x).diff(x) - f(x), 'sol': [Eq(f(x), C1*x)], }, 'separable_03': { 'eq': f(x).diff(x) + sin(x), 'sol': [Eq(f(x), C1 + cos(x))], }, 'separable_04': { 'eq': f(x)**2 + 1 - (x**2 + 1)*f(x).diff(x), 'sol': [Eq(f(x), tan(C1 + atan(x)))], }, 'separable_05': { 'eq': f(x).diff(x)/tan(x) - f(x) - 2, 'sol': [Eq(f(x), C1/cos(x) - 2)], }, 'separable_06': { 'eq': f(x).diff(x) * (1 - sin(f(x))) - 1, 'sol': [Eq(-x + f(x) + cos(f(x)), C1)], }, 'separable_07': { 'eq': f(x)*x**2*f(x).diff(x) - f(x)**3 - 2*x**2*f(x).diff(x), 'sol': [Eq(f(x), (-x - sqrt(x*(4*C1*x + x - 4)))/(C1*x - 1)/2), Eq(f(x), (-x + sqrt(x*(4*C1*x + x - 4)))/(C1*x - 1)/2)], 'slow': True, }, 'separable_08': { 'eq': f(x)**2 - 1 - (2*f(x) + x*f(x))*f(x).diff(x), 'sol': [Eq(f(x), -sqrt(C1*x**2 + 4*C1*x + 4*C1 + 1)), Eq(f(x), sqrt(C1*x**2 + 4*C1*x + 4*C1 + 1))], 'slow': True, }, 'separable_09': { 'eq': x*log(x)*f(x).diff(x) + sqrt(1 + f(x)**2), 'sol': [Eq(f(x), sinh(C1 - log(log(x))))], #One more solution is f(x)=I 'slow': True, 'checkodesol_XFAIL': True, }, 'separable_10': { 'eq': exp(x + 1)*tan(f(x)) + cos(f(x))*f(x).diff(x), 'sol': [Eq(E*exp(x) + log(cos(f(x)) - 1)/2 - log(cos(f(x)) + 1)/2 + cos(f(x)), C1)], 'slow': True, }, 'separable_11': { 'eq': (x*cos(f(x)) + x**2*sin(f(x))*f(x).diff(x) - a**2*sin(f(x))*f(x).diff(x)), 'sol': [ Eq(f(x), -acos(C1*sqrt(-a**2 + x**2)) + 2*pi), Eq(f(x), acos(C1*sqrt(-a**2 + x**2))) ], 'slow': True, }, 'separable_12': { 'eq': f(x).diff(x) - f(x)*tan(x), 'sol': [Eq(f(x), C1/cos(x))], }, 'separable_13': { 'eq': (x - 1)*cos(f(x))*f(x).diff(x) - 2*x*sin(f(x)), 'sol': [ Eq(f(x), pi - asin(C1*(x**2 - 2*x + 1)*exp(2*x))), Eq(f(x), asin(C1*(x**2 - 2*x + 1)*exp(2*x))) ], }, 'separable_14': { 'eq': f(x).diff(x) - f(x)*log(f(x))/tan(x), 'sol': [Eq(f(x), exp(C1*sin(x)))], }, 'separable_15': { 'eq': x*f(x).diff(x) + (1 + f(x)**2)*atan(f(x)), 'sol': [Eq(f(x), tan(C1/x))], #Two more solutions are f(x)=0 and f(x)=I 'slow': True, 'checkodesol_XFAIL': True, }, 'separable_16': { 'eq': f(x).diff(x) + x*(f(x) + 1), 'sol': [Eq(f(x), -1 + C1*exp(-x**2/2))], }, 'separable_17': { 'eq': exp(f(x)**2)*(x**2 + 2*x + 1) + (x*f(x) + f(x))*f(x).diff(x), 'sol': [ Eq(f(x), -sqrt(log(1/(C1 + x**2 + 2*x)))), Eq(f(x), sqrt(log(1/(C1 + x**2 + 2*x)))) ], }, 'separable_18': { 'eq': f(x).diff(x) + f(x), 'sol': [Eq(f(x), C1*exp(-x))], }, 'separable_19': { 'eq': sin(x)*cos(2*f(x)) + cos(x)*sin(2*f(x))*f(x).diff(x), 'sol': [Eq(f(x), pi - acos(C1/cos(x)**2)/2), Eq(f(x), acos(C1/cos(x)**2)/2)], }, 'separable_20': { 'eq': (1 - x)*f(x).diff(x) - x*(f(x) + 1), 'sol': [Eq(f(x), (C1*exp(-x) - x + 1)/(x - 1))], }, 'separable_21': { 'eq': f(x)*diff(f(x), x) + x - 3*x*f(x)**2, 'sol': [Eq(f(x), -sqrt(3)*sqrt(C1*exp(3*x**2) + 1)/3), Eq(f(x), sqrt(3)*sqrt(C1*exp(3*x**2) + 1)/3)], }, 'separable_22': { 'eq': f(x).diff(x) - exp(x + f(x)), 'sol': [Eq(f(x), log(-1/(C1 + exp(x))))], 'XFAIL': ['lie_group'] #It shows 'NoneType' object is not subscriptable for lie_group. }, # https://github.com/sympy/sympy/issues/7081 'separable_23': { 'eq': x*(f(x).diff(x)) + 1 - f(x)**2, 'sol': [Eq(f(x), (-C1 - x**2)/(-C1 + x**2))], }, # https://github.com/sympy/sympy/issues/10379 'separable_24': { 'eq': f(t).diff(t)-(1-51.05*y*f(t)), 'sol': [Eq(f(t), (0.019588638589618023*exp(y*(C1 - 51.049999999999997*t)) + 0.019588638589618023)/y)], 'func': f(t), }, # https://github.com/sympy/sympy/issues/15999 'separable_25': { 'eq': f(x).diff(x) - C1*f(x), 'sol': [Eq(f(x), C2*exp(C1*x))], }, 'separable_26': { 'eq': f1 - k * (v(t) ** 2) - m * Derivative(v(t)), 'sol': [Eq(v(t), -68.585712797928991/tanh(C1 - 0.14288690166235204*t))], 'func': v(t), 'checkodesol_XFAIL': True, }, #https://github.com/sympy/sympy/issues/22155 'separable_27': { 'eq': f(x).diff(x) - exp(f(x) - x), 'sol': [Eq(f(x), log(-exp(x)/(C1*exp(x) - 1)))], } } } @_add_example_keys def _get_examples_ode_sol_1st_exact(): # Type: Exact differential equation, p(x,f) + q(x,f)*f' == 0, # where dp/df == dq/dx ''' Example 7 is an exact equation that fails under the exact engine. It is caught by first order homogeneous albeit with a much contorted solution. The exact engine fails because of a poorly simplified integral of q(0,y)dy, where q is the function multiplying f'. The solutions should be Eq(sqrt(x**2+f(x)**2)**3+y**3, C1). The equation below is equivalent, but it is so complex that checkodesol fails, and takes a long time to do so. ''' return { 'hint': "1st_exact", 'func': f(x), 'examples':{ '1st_exact_01': { 'eq': sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x), 'sol': [Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))], 'slow': True, }, '1st_exact_02': { 'eq': (2*x*f(x) + 1)/f(x) + (f(x) - x)/f(x)**2*f(x).diff(x), 'sol': [Eq(f(x), exp(C1 - x**2 + LambertW(-x*exp(-C1 + x**2))))], 'XFAIL': ['lie_group'], #It shows dsolve raises an exception: List index out of range for lie_group 'slow': True, 'checkodesol_XFAIL':True }, '1st_exact_03': { 'eq': 2*x + f(x)*cos(x) + (2*f(x) + sin(x) - sin(f(x)))*f(x).diff(x), 'sol': [Eq(f(x)*sin(x) + cos(f(x)) + x**2 + f(x)**2, C1)], 'XFAIL': ['lie_group'], #It goes into infinite loop for lie_group. 'slow': True, }, '1st_exact_04': { 'eq': cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x), 'sol': [Eq(x*cos(f(x)) + f(x)**3/3, C1)], 'slow': True, }, '1st_exact_05': { 'eq': 2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), 'sol': [Eq(x**2*f(x) + f(x)**3/3, C1)], 'slow': True, 'simplify_flag':False }, # This was from issue: https://github.com/sympy/sympy/issues/11290 '1st_exact_06': { 'eq': cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x), 'sol': [Eq(x*cos(f(x)) + f(x)**3/3, C1)], 'simplify_flag':False }, '1st_exact_07': { 'eq': x*sqrt(x**2 + f(x)**2) - (x**2*f(x)/(f(x) - sqrt(x**2 + f(x)**2)))*f(x).diff(x), 'sol': [Eq(log(x), C1 - 9*sqrt(1 + f(x)**2/x**2)*asinh(f(x)/x)/(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2)) - 9*sqrt(1 + f(x)**2/x**2)* log(1 - sqrt(1 + f(x)**2/x**2)*f(x)/x + 2*f(x)**2/x**2)/ (-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2)) + 9*asinh(f(x)/x)*f(x)/(x*(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2))) + 9*f(x)*log(1 - sqrt(1 + f(x)**2/x**2)*f(x)/x + 2*f(x)**2/x**2)/ (x*(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2))))], 'slow': True, 'dsolve_too_slow':True }, # Type: a(x)f'(x)+b(x)*f(x)+c(x)=0 '1st_exact_08': { 'eq': Eq(x**2*f(x).diff(x) + 3*x*f(x) - sin(x)/x, 0), 'sol': [Eq(f(x), (C1 - cos(x))/x**3)], }, # these examples are from test_exact_enhancement '1st_exact_09': { 'eq': f(x)/x**2 + ((f(x)*x - 1)/x)*f(x).diff(x), 'sol': [Eq(f(x), (i*sqrt(C1*x**2 + 1) + 1)/x) for i in (-1, 1)], }, '1st_exact_10': { 'eq': (x*f(x) - 1) + f(x).diff(x)*(x**2 - x*f(x)), 'sol': [Eq(f(x), x - sqrt(C1 + x**2 - 2*log(x))), Eq(f(x), x + sqrt(C1 + x**2 - 2*log(x)))], }, '1st_exact_11': { 'eq': (x + 2)*sin(f(x)) + f(x).diff(x)*x*cos(f(x)), 'sol': [Eq(f(x), -asin(C1*exp(-x)/x**2) + pi), Eq(f(x), asin(C1*exp(-x)/x**2))], }, } } @_add_example_keys def _get_examples_ode_sol_nth_linear_var_of_parameters(): g = exp(-x) f2 = f(x).diff(x, 2) c = 3*f(x).diff(x, 3) + 5*f2 + f(x).diff(x) - f(x) - x return { 'hint': "nth_linear_constant_coeff_variation_of_parameters", 'func': f(x), 'examples':{ 'var_of_parameters_01': { 'eq': c - x*g, 'sol': [Eq(f(x), C3*exp(x/3) - x + (C1 + x*(C2 - x**2/24 - 3*x/32))*exp(-x) - 1)], 'slow': True, }, 'var_of_parameters_02': { 'eq': c - g, 'sol': [Eq(f(x), C3*exp(x/3) - x + (C1 + x*(C2 - x/8))*exp(-x) - 1)], 'slow': True, }, 'var_of_parameters_03': { 'eq': f(x).diff(x) - 1, 'sol': [Eq(f(x), C1 + x)], 'slow': True, }, 'var_of_parameters_04': { 'eq': f2 + 3*f(x).diff(x) + 2*f(x) - 4, 'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 2)], 'slow': True, }, 'var_of_parameters_05': { 'eq': f2 + 3*f(x).diff(x) + 2*f(x) - 12*exp(x), 'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 2*exp(x))], 'slow': True, }, 'var_of_parameters_06': { 'eq': f2 - 2*f(x).diff(x) - 8*f(x) - 9*x*exp(x) - 10*exp(-x), 'sol': [Eq(f(x), -x*exp(x) - 2*exp(-x) + C1*exp(-2*x) + C2*exp(4*x))], 'slow': True, }, 'var_of_parameters_07': { 'eq': f2 + 2*f(x).diff(x) + f(x) - x**2*exp(-x), 'sol': [Eq(f(x), (C1 + x*(C2 + x**3/12))*exp(-x))], 'slow': True, }, 'var_of_parameters_08': { 'eq': f2 - 3*f(x).diff(x) + 2*f(x) - x*exp(-x), 'sol': [Eq(f(x), C1*exp(x) + C2*exp(2*x) + (6*x + 5)*exp(-x)/36)], 'slow': True, }, 'var_of_parameters_09': { 'eq': f(x).diff(x, 3) - 3*f2 + 3*f(x).diff(x) - f(x) - exp(x), 'sol': [Eq(f(x), (C1 + x*(C2 + x*(C3 + x/6)))*exp(x))], 'slow': True, }, 'var_of_parameters_10': { 'eq': f2 + 2*f(x).diff(x) + f(x) - exp(-x)/x, 'sol': [Eq(f(x), (C1 + x*(C2 + log(x)))*exp(-x))], 'slow': True, }, 'var_of_parameters_11': { 'eq': f2 + f(x) - 1/sin(x)*1/cos(x), 'sol': [Eq(f(x), (C1 + log(sin(x) - 1)/2 - log(sin(x) + 1)/2 )*cos(x) + (C2 + log(cos(x) - 1)/2 - log(cos(x) + 1)/2)*sin(x))], 'slow': True, }, 'var_of_parameters_12': { 'eq': f(x).diff(x, 4) - 1/x, 'sol': [Eq(f(x), C1 + C2*x + C3*x**2 + x**3*(C4 + log(x)/6))], 'slow': True, }, # These were from issue: https://github.com/sympy/sympy/issues/15996 'var_of_parameters_13': { 'eq': f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x), 'sol': [Eq(f(x), C1 + x**2 + (C2 + x*(C3 - x/8 + 3*exp(I*x)/2 + 3*exp(-I*x)/2) + 5*exp(2*I*x)/16 + 2*I*exp(I*x) - 2*I*exp(-I*x))*sin(x) + (C4 + x*(C5 + I*x/8 + 3*I*exp(I*x)/2 - 3*I*exp(-I*x)/2) + 5*I*exp(2*I*x)/16 - 2*exp(I*x) - 2*exp(-I*x))*cos(x) - I*exp(I*x))], }, 'var_of_parameters_14': { 'eq': f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - exp(I*x), 'sol': [Eq(f(x), C1 + (C2 + x*(C3 - x/8) + 5*exp(2*I*x)/16)*sin(x) + (C4 + x*(C5 + I*x/8) + 5*I*exp(2*I*x)/16)*cos(x) - I*exp(I*x))], }, # https://github.com/sympy/sympy/issues/14395 'var_of_parameters_15': { 'eq': Derivative(f(x), x, x) + 9*f(x) - sec(x), 'sol': [Eq(f(x), (C1 - x/3 + sin(2*x)/3)*sin(3*x) + (C2 + log(cos(x)) - 2*log(cos(x)**2)/3 + 2*cos(x)**2/3)*cos(3*x))], 'slow': True, }, } } @_add_example_keys def _get_examples_ode_sol_2nd_linear_bessel(): return { 'hint': "2nd_linear_bessel", 'func': f(x), 'examples':{ '2nd_lin_bessel_01': { 'eq': x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - 4)*f(x), 'sol': [Eq(f(x), C1*besselj(2, x) + C2*bessely(2, x))], }, '2nd_lin_bessel_02': { 'eq': x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 +25)*f(x), 'sol': [Eq(f(x), C1*besselj(5*I, x) + C2*bessely(5*I, x))], }, '2nd_lin_bessel_03': { 'eq': x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2)*f(x), 'sol': [Eq(f(x), C1*besselj(0, x) + C2*bessely(0, x))], }, '2nd_lin_bessel_04': { 'eq': x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (81*x**2 -S(1)/9)*f(x), 'sol': [Eq(f(x), C1*besselj(S(1)/3, 9*x) + C2*bessely(S(1)/3, 9*x))], }, '2nd_lin_bessel_05': { 'eq': x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**4 - 4)*f(x), 'sol': [Eq(f(x), C1*besselj(1, x**2/2) + C2*bessely(1, x**2/2))], }, '2nd_lin_bessel_06': { 'eq': x**2*(f(x).diff(x, 2)) + 2*x*(f(x).diff(x)) + (x**4 - 4)*f(x), 'sol': [Eq(f(x), (C1*besselj(sqrt(17)/4, x**2/2) + C2*bessely(sqrt(17)/4, x**2/2))/sqrt(x))], }, '2nd_lin_bessel_07': { 'eq': x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - S(1)/4)*f(x), 'sol': [Eq(f(x), C1*besselj(S(1)/2, x) + C2*bessely(S(1)/2, x))], }, '2nd_lin_bessel_08': { 'eq': x**2*(f(x).diff(x, 2)) - 3*x*(f(x).diff(x)) + (4*x + 4)*f(x), 'sol': [Eq(f(x), x**2*(C1*besselj(0, 4*sqrt(x)) + C2*bessely(0, 4*sqrt(x))))], }, '2nd_lin_bessel_09': { 'eq': x*(f(x).diff(x, 2)) - f(x).diff(x) + 4*x**3*f(x), 'sol': [Eq(f(x), x*(C1*besselj(S(1)/2, x**2) + C2*bessely(S(1)/2, x**2)))], }, '2nd_lin_bessel_10': { 'eq': (x-2)**2*(f(x).diff(x, 2)) - (x-2)*f(x).diff(x) + 4*(x-2)**2*f(x), 'sol': [Eq(f(x), (x - 2)*(C1*besselj(1, 2*x - 4) + C2*bessely(1, 2*x - 4)))], }, # https://github.com/sympy/sympy/issues/4414 '2nd_lin_bessel_11': { 'eq': f(x).diff(x, x) + 2/x*f(x).diff(x) + f(x), 'sol': [Eq(f(x), (C1*besselj(S(1)/2, x) + C2*bessely(S(1)/2, x))/sqrt(x))], }, } } @_add_example_keys def _get_examples_ode_sol_2nd_2F1_hypergeometric(): return { 'hint': "2nd_hypergeometric", 'func': f(x), 'examples':{ '2nd_2F1_hyper_01': { 'eq': x*(x-1)*f(x).diff(x, 2) + (S(3)/2 -2*x)*f(x).diff(x) + 2*f(x), 'sol': [Eq(f(x), C1*x**(S(5)/2)*hyper((S(3)/2, S(1)/2), (S(7)/2,), x) + C2*hyper((-1, -2), (-S(3)/2,), x))], }, '2nd_2F1_hyper_02': { 'eq': x*(x-1)*f(x).diff(x, 2) + (S(7)/2*x)*f(x).diff(x) + f(x), 'sol': [Eq(f(x), (C1*(1 - x)**(S(5)/2)*hyper((S(1)/2, 2), (S(7)/2,), 1 - x) + C2*hyper((-S(1)/2, -2), (-S(3)/2,), 1 - x))/(x - 1)**(S(5)/2))], }, '2nd_2F1_hyper_03': { 'eq': x*(x-1)*f(x).diff(x, 2) + (S(3)+ S(7)/2*x)*f(x).diff(x) + f(x), 'sol': [Eq(f(x), (C1*(1 - x)**(S(11)/2)*hyper((S(1)/2, 2), (S(13)/2,), 1 - x) + C2*hyper((-S(7)/2, -5), (-S(9)/2,), 1 - x))/(x - 1)**(S(11)/2))], }, '2nd_2F1_hyper_04': { 'eq': -x**(S(5)/7)*(-416*x**(S(9)/7)/9 - 2385*x**(S(5)/7)/49 + S(298)*x/3)*f(x)/(196*(-x**(S(6)/7) + x)**2*(x**(S(6)/7) + x)**2) + Derivative(f(x), (x, 2)), 'sol': [Eq(f(x), x**(S(45)/98)*(C1*x**(S(4)/49)*hyper((S(1)/3, -S(1)/2), (S(9)/7,), x**(S(2)/7)) + C2*hyper((S(1)/21, -S(11)/14), (S(5)/7,), x**(S(2)/7)))/(x**(S(2)/7) - 1)**(S(19)/84))], 'checkodesol_XFAIL':True, }, } } @_add_example_keys def _get_examples_ode_sol_2nd_nonlinear_autonomous_conserved(): return { 'hint': "2nd_nonlinear_autonomous_conserved", 'func': f(x), 'examples': { '2nd_nonlinear_autonomous_conserved_01': { 'eq': f(x).diff(x, 2) + exp(f(x)) + log(f(x)), 'sol': [ Eq(Integral(1/sqrt(C1 - 2*_u*log(_u) + 2*_u - 2*exp(_u)), (_u, f(x))), C2 + x), Eq(Integral(1/sqrt(C1 - 2*_u*log(_u) + 2*_u - 2*exp(_u)), (_u, f(x))), C2 - x) ], 'simplify_flag': False, }, '2nd_nonlinear_autonomous_conserved_02': { 'eq': f(x).diff(x, 2) + cbrt(f(x)) + 1/f(x), 'sol': [ Eq(sqrt(2)*Integral(1/sqrt(2*C1 - 3*_u**Rational(4, 3) - 4*log(_u)), (_u, f(x))), C2 + x), Eq(sqrt(2)*Integral(1/sqrt(2*C1 - 3*_u**Rational(4, 3) - 4*log(_u)), (_u, f(x))), C2 - x) ], 'simplify_flag': False, }, '2nd_nonlinear_autonomous_conserved_03': { 'eq': f(x).diff(x, 2) + sin(f(x)), 'sol': [ Eq(Integral(1/sqrt(C1 + 2*cos(_u)), (_u, f(x))), C2 + x), Eq(Integral(1/sqrt(C1 + 2*cos(_u)), (_u, f(x))), C2 - x) ], 'simplify_flag': False, }, '2nd_nonlinear_autonomous_conserved_04': { 'eq': f(x).diff(x, 2) + cosh(f(x)), 'sol': [ Eq(Integral(1/sqrt(C1 - 2*sinh(_u)), (_u, f(x))), C2 + x), Eq(Integral(1/sqrt(C1 - 2*sinh(_u)), (_u, f(x))), C2 - x) ], 'simplify_flag': False, }, '2nd_nonlinear_autonomous_conserved_05': { 'eq': f(x).diff(x, 2) + asin(f(x)), 'sol': [ Eq(Integral(1/sqrt(C1 - 2*_u*asin(_u) - 2*sqrt(1 - _u**2)), (_u, f(x))), C2 + x), Eq(Integral(1/sqrt(C1 - 2*_u*asin(_u) - 2*sqrt(1 - _u**2)), (_u, f(x))), C2 - x) ], 'simplify_flag': False, 'XFAIL': ['2nd_nonlinear_autonomous_conserved_Integral'] } } } @_add_example_keys def _get_examples_ode_sol_separable_reduced(): df = f(x).diff(x) return { 'hint': "separable_reduced", 'func': f(x), 'examples':{ 'separable_reduced_01': { 'eq': x* df + f(x)* (1 / (x**2*f(x) - 1)), 'sol': [Eq(log(x**2*f(x))/3 + log(x**2*f(x) - Rational(3, 2))/6, C1 + log(x))], 'simplify_flag': False, 'XFAIL': ['lie_group'], #It hangs. }, #Note: 'separable_reduced_02' is referred in 'separable_reduced_11' 'separable_reduced_02': { 'eq': f(x).diff(x) + (f(x) / (x**4*f(x) - x)), 'sol': [Eq(log(x**3*f(x))/4 + log(x**3*f(x) - Rational(4,3))/12, C1 + log(x))], 'simplify_flag': False, 'checkodesol_XFAIL':True, #It hangs for this. }, 'separable_reduced_03': { 'eq': x*df + f(x)*(x**2*f(x)), 'sol': [Eq(log(x**2*f(x))/2 - log(x**2*f(x) - 2)/2, C1 + log(x))], 'simplify_flag': False, }, 'separable_reduced_04': { 'eq': Eq(f(x).diff(x) + f(x)/x * (1 + (x**(S(2)/3)*f(x))**2), 0), 'sol': [Eq(-3*log(x**(S(2)/3)*f(x)) + 3*log(3*x**(S(4)/3)*f(x)**2 + 1)/2, C1 + log(x))], 'simplify_flag': False, }, 'separable_reduced_05': { 'eq': Eq(f(x).diff(x) + f(x)/x * (1 + (x*f(x))**2), 0), 'sol': [Eq(f(x), -sqrt(2)*sqrt(1/(C1 + log(x)))/(2*x)),\ Eq(f(x), sqrt(2)*sqrt(1/(C1 + log(x)))/(2*x))], }, 'separable_reduced_06': { 'eq': Eq(f(x).diff(x) + (x**4*f(x)**2 + x**2*f(x))*f(x)/(x*(x**6*f(x)**3 + x**4*f(x)**2)), 0), 'sol': [Eq(f(x), C1 + 1/(2*x**2))], }, 'separable_reduced_07': { 'eq': Eq(f(x).diff(x) + (f(x)**2)*f(x)/(x), 0), 'sol': [ Eq(f(x), -sqrt(2)*sqrt(1/(C1 + log(x)))/2), Eq(f(x), sqrt(2)*sqrt(1/(C1 + log(x)))/2) ], }, 'separable_reduced_08': { 'eq': Eq(f(x).diff(x) + (f(x)+3)*f(x)/(x*(f(x)+2)), 0), 'sol': [Eq(-log(f(x) + 3)/3 - 2*log(f(x))/3, C1 + log(x))], 'simplify_flag': False, 'XFAIL': ['lie_group'], #It hangs. }, 'separable_reduced_09': { 'eq': Eq(f(x).diff(x) + (f(x)+3)*f(x)/x, 0), 'sol': [Eq(f(x), 3/(C1*x**3 - 1))], }, 'separable_reduced_10': { 'eq': Eq(f(x).diff(x) + (f(x)**2+f(x))*f(x)/(x), 0), 'sol': [Eq(- log(x) - log(f(x) + 1) + log(f(x)) + 1/f(x), C1)], 'XFAIL': ['lie_group'],#No algorithms are implemented to solve equation -C1 + x*(_y + 1)*exp(-1/_y)/_y }, # Equivalent to example_name 'separable_reduced_02'. Only difference is testing with simplify=True 'separable_reduced_11': { 'eq': f(x).diff(x) + (f(x) / (x**4*f(x) - x)), 'sol': [Eq(f(x), -sqrt(2)*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) - 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)/6 - sqrt(2)*sqrt(-3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 4/x**6 - 4*sqrt(2)/(x**9*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) - 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)))/6 + 1/(3*x**3)), Eq(f(x), -sqrt(2)*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) - 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)/6 + sqrt(2)*sqrt(-3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 4/x**6 - 4*sqrt(2)/(x**9*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) - 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)))/6 + 1/(3*x**3)), Eq(f(x), sqrt(2)*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) - 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)/6 - sqrt(2)*sqrt(-3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 4/x**6 + 4*sqrt(2)/(x**9*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) - 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)))/6 + 1/(3*x**3)), Eq(f(x), sqrt(2)*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) - 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)/6 + sqrt(2)*sqrt(-3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 4/x**6 + 4*sqrt(2)/(x**9*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) - 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)))/6 + 1/(3*x**3))], 'checkodesol_XFAIL':True, #It hangs for this. 'slow': True, }, #These were from issue: https://github.com/sympy/sympy/issues/6247 'separable_reduced_12': { 'eq': x**2*f(x)**2 + x*Derivative(f(x), x), 'sol': [Eq(f(x), 2*C1/(C1*x**2 - 1))], }, } } @_add_example_keys def _get_examples_ode_sol_lie_group(): a, b, c = symbols("a b c") return { 'hint': "lie_group", 'func': f(x), 'examples':{ #Example 1-4 and 19-20 were from issue: https://github.com/sympy/sympy/issues/17322 'lie_group_01': { 'eq': x*f(x).diff(x)*(f(x)+4) + (f(x)**2) -2*f(x)-2*x, 'sol': [], 'dsolve_too_slow': True, 'checkodesol_too_slow': True, }, 'lie_group_02': { 'eq': x*f(x).diff(x)*(f(x)+4) + (f(x)**2) -2*f(x)-2*x, 'sol': [], 'dsolve_too_slow': True, }, 'lie_group_03': { 'eq': Eq(x**7*Derivative(f(x), x) + 5*x**3*f(x)**2 - (2*x**2 + 2)*f(x)**3, 0), 'sol': [], 'dsolve_too_slow': True, }, 'lie_group_04': { 'eq': f(x).diff(x) - (f(x) - x*log(x))**2/x**2 + log(x), 'sol': [], 'XFAIL': ['lie_group'], }, 'lie_group_05': { 'eq': f(x).diff(x)**2, 'sol': [Eq(f(x), C1)], 'XFAIL': ['factorable'], #It raises Not Implemented error }, 'lie_group_06': { 'eq': Eq(f(x).diff(x), x**2*f(x)), 'sol': [Eq(f(x), C1*exp(x**3)**Rational(1, 3))], }, 'lie_group_07': { 'eq': f(x).diff(x) + a*f(x) - c*exp(b*x), 'sol': [Eq(f(x), Piecewise(((-C1*(a + b) + c*exp(x*(a + b)))*exp(-a*x)/(a + b),\ Ne(a, -b)), ((-C1 + c*x)*exp(-a*x), True)))], }, 'lie_group_08': { 'eq': f(x).diff(x) + 2*x*f(x) - x*exp(-x**2), 'sol': [Eq(f(x), (C1 + x**2/2)*exp(-x**2))], }, 'lie_group_09': { 'eq': (1 + 2*x)*(f(x).diff(x)) + 2 - 4*exp(-f(x)), 'sol': [Eq(f(x), log(C1/(2*x + 1) + 2))], }, 'lie_group_10': { 'eq': x**2*(f(x).diff(x)) - f(x) + x**2*exp(x - (1/x)), 'sol': [Eq(f(x), (C1 - exp(x))*exp(-1/x))], 'XFAIL': ['factorable'], #It raises Recursion Error (maixmum depth exceeded) }, 'lie_group_11': { 'eq': x**2*f(x)**2 + x*Derivative(f(x), x), 'sol': [Eq(f(x), 2/(C1 + x**2))], }, 'lie_group_12': { 'eq': diff(f(x),x) + 2*x*f(x) - x*exp(-x**2), 'sol': [Eq(f(x), exp(-x**2)*(C1 + x**2/2))], }, 'lie_group_13': { 'eq': diff(f(x),x) + f(x)*cos(x) - exp(2*x), 'sol': [Eq(f(x), exp(-sin(x))*(C1 + Integral(exp(2*x)*exp(sin(x)), x)))], }, 'lie_group_14': { 'eq': diff(f(x),x) + f(x)*cos(x) - sin(2*x)/2, 'sol': [Eq(f(x), C1*exp(-sin(x)) + sin(x) - 1)], }, 'lie_group_15': { 'eq': x*diff(f(x),x) + f(x) - x*sin(x), 'sol': [Eq(f(x), (C1 - x*cos(x) + sin(x))/x)], }, 'lie_group_16': { 'eq': x*diff(f(x),x) - f(x) - x/log(x), 'sol': [Eq(f(x), x*(C1 + log(log(x))))], }, 'lie_group_17': { 'eq': (f(x).diff(x)-f(x)) * (f(x).diff(x)+f(x)), 'sol': [Eq(f(x), C1*exp(x)), Eq(f(x), C1*exp(-x))], }, 'lie_group_18': { 'eq': f(x).diff(x) * (f(x).diff(x) - f(x)), 'sol': [Eq(f(x), C1*exp(x)), Eq(f(x), C1)], }, 'lie_group_19': { 'eq': (f(x).diff(x)-f(x)) * (f(x).diff(x)+f(x)), 'sol': [Eq(f(x), C1*exp(-x)), Eq(f(x), C1*exp(x))], }, 'lie_group_20': { 'eq': f(x).diff(x)*(f(x).diff(x)+f(x)), 'sol': [Eq(f(x), C1), Eq(f(x), C1*exp(-x))], }, } } @_add_example_keys def _get_examples_ode_sol_2nd_linear_airy(): return { 'hint': "2nd_linear_airy", 'func': f(x), 'examples':{ '2nd_lin_airy_01': { 'eq': f(x).diff(x, 2) - x*f(x), 'sol': [Eq(f(x), C1*airyai(x) + C2*airybi(x))], }, '2nd_lin_airy_02': { 'eq': f(x).diff(x, 2) + 2*x*f(x), 'sol': [Eq(f(x), C1*airyai(-2**(S(1)/3)*x) + C2*airybi(-2**(S(1)/3)*x))], }, } } @_add_example_keys def _get_examples_ode_sol_nth_linear_constant_coeff_homogeneous(): # From Exercise 20, in Ordinary Differential Equations, # Tenenbaum and Pollard, pg. 220 a = Symbol('a', positive=True) k = Symbol('k', real=True) r1, r2, r3, r4, r5 = [rootof(x**5 + 11*x - 2, n) for n in range(5)] r6, r7, r8, r9, r10 = [rootof(x**5 - 3*x + 1, n) for n in range(5)] r11, r12, r13, r14, r15 = [rootof(x**5 - 100*x**3 + 1000*x + 1, n) for n in range(5)] r16, r17, r18, r19, r20 = [rootof(x**5 - x**4 + 10, n) for n in range(5)] r21, r22, r23, r24, r25 = [rootof(x**5 - x + 1, n) for n in range(5)] E = exp(1) return { 'hint': "nth_linear_constant_coeff_homogeneous", 'func': f(x), 'examples':{ 'lin_const_coeff_hom_01': { 'eq': f(x).diff(x, 2) + 2*f(x).diff(x), 'sol': [Eq(f(x), C1 + C2*exp(-2*x))], }, 'lin_const_coeff_hom_02': { 'eq': f(x).diff(x, 2) - 3*f(x).diff(x) + 2*f(x), 'sol': [Eq(f(x), (C1 + C2*exp(x))*exp(x))], }, 'lin_const_coeff_hom_03': { 'eq': f(x).diff(x, 2) - f(x), 'sol': [Eq(f(x), C1*exp(-x) + C2*exp(x))], }, 'lin_const_coeff_hom_04': { 'eq': f(x).diff(x, 3) + f(x).diff(x, 2) - 6*f(x).diff(x), 'sol': [Eq(f(x), C1 + C2*exp(-3*x) + C3*exp(2*x))], 'slow': True, }, 'lin_const_coeff_hom_05': { 'eq': 6*f(x).diff(x, 2) - 11*f(x).diff(x) + 4*f(x), 'sol': [Eq(f(x), C1*exp(x/2) + C2*exp(x*Rational(4, 3)))], 'slow': True, }, 'lin_const_coeff_hom_06': { 'eq': Eq(f(x).diff(x, 2) + 2*f(x).diff(x) - f(x), 0), 'sol': [Eq(f(x), C1*exp(x*(-1 + sqrt(2))) + C2*exp(-x*(sqrt(2) + 1)))], 'slow': True, }, 'lin_const_coeff_hom_07': { 'eq': diff(f(x), x, 3) + diff(f(x), x, 2) - 10*diff(f(x), x) - 6*f(x), 'sol': [Eq(f(x), C1*exp(3*x) + C3*exp(-x*(2 + sqrt(2))) + C2*exp(x*(-2 + sqrt(2))))], 'slow': True, }, 'lin_const_coeff_hom_08': { 'eq': f(x).diff(x, 4) - f(x).diff(x, 3) - 4*f(x).diff(x, 2) + \ 4*f(x).diff(x), 'sol': [Eq(f(x), C1 + C2*exp(-2*x) + C3*exp(x) + C4*exp(2*x))], 'slow': True, }, 'lin_const_coeff_hom_09': { 'eq': f(x).diff(x, 4) + 4*f(x).diff(x, 3) + f(x).diff(x, 2) - \ 4*f(x).diff(x) - 2*f(x), 'sol': [Eq(f(x), C3*exp(-x) + C4*exp(x) + (C1*exp(-sqrt(2)*x) + C2*exp(sqrt(2)*x))*exp(-2*x))], 'slow': True, }, 'lin_const_coeff_hom_10': { 'eq': f(x).diff(x, 4) - a**2*f(x), 'sol': [Eq(f(x), C1*exp(-sqrt(a)*x) + C2*exp(sqrt(a)*x) + C3*sin(sqrt(a)*x) + C4*cos(sqrt(a)*x))], 'slow': True, }, 'lin_const_coeff_hom_11': { 'eq': f(x).diff(x, 2) - 2*k*f(x).diff(x) - 2*f(x), 'sol': [Eq(f(x), C1*exp(x*(k - sqrt(k**2 + 2))) + C2*exp(x*(k + sqrt(k**2 + 2))))], 'slow': True, }, 'lin_const_coeff_hom_12': { 'eq': f(x).diff(x, 2) + 4*k*f(x).diff(x) - 12*k**2*f(x), 'sol': [Eq(f(x), C1*exp(-6*k*x) + C2*exp(2*k*x))], 'slow': True, }, 'lin_const_coeff_hom_13': { 'eq': f(x).diff(x, 4), 'sol': [Eq(f(x), C1 + C2*x + C3*x**2 + C4*x**3)], 'slow': True, }, 'lin_const_coeff_hom_14': { 'eq': f(x).diff(x, 2) + 4*f(x).diff(x) + 4*f(x), 'sol': [Eq(f(x), (C1 + C2*x)*exp(-2*x))], 'slow': True, }, 'lin_const_coeff_hom_15': { 'eq': 3*f(x).diff(x, 3) + 5*f(x).diff(x, 2) + f(x).diff(x) - f(x), 'sol': [Eq(f(x), (C1 + C2*x)*exp(-x) + C3*exp(x/3))], 'slow': True, }, 'lin_const_coeff_hom_16': { 'eq': f(x).diff(x, 3) - 6*f(x).diff(x, 2) + 12*f(x).diff(x) - 8*f(x), 'sol': [Eq(f(x), (C1 + x*(C2 + C3*x))*exp(2*x))], 'slow': True, }, 'lin_const_coeff_hom_17': { 'eq': f(x).diff(x, 2) - 2*a*f(x).diff(x) + a**2*f(x), 'sol': [Eq(f(x), (C1 + C2*x)*exp(a*x))], 'slow': True, }, 'lin_const_coeff_hom_18': { 'eq': f(x).diff(x, 4) + 3*f(x).diff(x, 3), 'sol': [Eq(f(x), C1 + C2*x + C3*x**2 + C4*exp(-3*x))], 'slow': True, }, 'lin_const_coeff_hom_19': { 'eq': f(x).diff(x, 4) - 2*f(x).diff(x, 2), 'sol': [Eq(f(x), C1 + C2*x + C3*exp(-sqrt(2)*x) + C4*exp(sqrt(2)*x))], 'slow': True, }, 'lin_const_coeff_hom_20': { 'eq': f(x).diff(x, 4) + 2*f(x).diff(x, 3) - 11*f(x).diff(x, 2) - \ 12*f(x).diff(x) + 36*f(x), 'sol': [Eq(f(x), (C1 + C2*x)*exp(-3*x) + (C3 + C4*x)*exp(2*x))], 'slow': True, }, 'lin_const_coeff_hom_21': { 'eq': 36*f(x).diff(x, 4) - 37*f(x).diff(x, 2) + 4*f(x).diff(x) + 5*f(x), 'sol': [Eq(f(x), C1*exp(-x) + C2*exp(-x/3) + C3*exp(x/2) + C4*exp(x*Rational(5, 6)))], 'slow': True, }, 'lin_const_coeff_hom_22': { 'eq': f(x).diff(x, 4) - 8*f(x).diff(x, 2) + 16*f(x), 'sol': [Eq(f(x), (C1 + C2*x)*exp(-2*x) + (C3 + C4*x)*exp(2*x))], 'slow': True, }, 'lin_const_coeff_hom_23': { 'eq': f(x).diff(x, 2) - 2*f(x).diff(x) + 5*f(x), 'sol': [Eq(f(x), (C1*sin(2*x) + C2*cos(2*x))*exp(x))], 'slow': True, }, 'lin_const_coeff_hom_24': { 'eq': f(x).diff(x, 2) - f(x).diff(x) + f(x), 'sol': [Eq(f(x), (C1*sin(x*sqrt(3)/2) + C2*cos(x*sqrt(3)/2))*exp(x/2))], 'slow': True, }, 'lin_const_coeff_hom_25': { 'eq': f(x).diff(x, 4) + 5*f(x).diff(x, 2) + 6*f(x), 'sol': [Eq(f(x), C1*sin(sqrt(2)*x) + C2*sin(sqrt(3)*x) + C3*cos(sqrt(2)*x) + C4*cos(sqrt(3)*x))], 'slow': True, }, 'lin_const_coeff_hom_26': { 'eq': f(x).diff(x, 2) - 4*f(x).diff(x) + 20*f(x), 'sol': [Eq(f(x), (C1*sin(4*x) + C2*cos(4*x))*exp(2*x))], 'slow': True, }, 'lin_const_coeff_hom_27': { 'eq': f(x).diff(x, 4) + 4*f(x).diff(x, 2) + 4*f(x), 'sol': [Eq(f(x), (C1 + C2*x)*sin(x*sqrt(2)) + (C3 + C4*x)*cos(x*sqrt(2)))], 'slow': True, }, 'lin_const_coeff_hom_28': { 'eq': f(x).diff(x, 3) + 8*f(x), 'sol': [Eq(f(x), (C1*sin(x*sqrt(3)) + C2*cos(x*sqrt(3)))*exp(x) + C3*exp(-2*x))], 'slow': True, }, 'lin_const_coeff_hom_29': { 'eq': f(x).diff(x, 4) + 4*f(x).diff(x, 2), 'sol': [Eq(f(x), C1 + C2*x + C3*sin(2*x) + C4*cos(2*x))], 'slow': True, }, 'lin_const_coeff_hom_30': { 'eq': f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x), 'sol': [Eq(f(x), C1 + (C2 + C3*x)*sin(x) + (C4 + C5*x)*cos(x))], 'slow': True, }, 'lin_const_coeff_hom_31': { 'eq': f(x).diff(x, 4) + f(x).diff(x, 2) + f(x), 'sol': [Eq(f(x), (C1*sin(sqrt(3)*x/2) + C2*cos(sqrt(3)*x/2))*exp(-x/2) + (C3*sin(sqrt(3)*x/2) + C4*cos(sqrt(3)*x/2))*exp(x/2))], 'slow': True, }, 'lin_const_coeff_hom_32': { 'eq': f(x).diff(x, 4) + 4*f(x).diff(x, 2) + f(x), 'sol': [Eq(f(x), C1*sin(x*sqrt(-sqrt(3) + 2)) + C2*sin(x*sqrt(sqrt(3) + 2)) + C3*cos(x*sqrt(-sqrt(3) + 2)) + C4*cos(x*sqrt(sqrt(3) + 2)))], 'slow': True, }, # One real root, two complex conjugate pairs 'lin_const_coeff_hom_33': { 'eq': f(x).diff(x, 5) + 11*f(x).diff(x) - 2*f(x), 'sol': [Eq(f(x), C5*exp(r1*x) + exp(re(r2)*x) * (C1*sin(im(r2)*x) + C2*cos(im(r2)*x)) + exp(re(r4)*x) * (C3*sin(im(r4)*x) + C4*cos(im(r4)*x)))], 'checkodesol_XFAIL':True, #It Hangs }, # Three real roots, one complex conjugate pair 'lin_const_coeff_hom_34': { 'eq': f(x).diff(x,5) - 3*f(x).diff(x) + f(x), 'sol': [Eq(f(x), C3*exp(r6*x) + C4*exp(r7*x) + C5*exp(r8*x) + exp(re(r9)*x) * (C1*sin(im(r9)*x) + C2*cos(im(r9)*x)))], 'checkodesol_XFAIL':True, #It Hangs }, # Five distinct real roots 'lin_const_coeff_hom_35': { 'eq': f(x).diff(x,5) - 100*f(x).diff(x,3) + 1000*f(x).diff(x) + f(x), 'sol': [Eq(f(x), C1*exp(r11*x) + C2*exp(r12*x) + C3*exp(r13*x) + C4*exp(r14*x) + C5*exp(r15*x))], 'checkodesol_XFAIL':True, #It Hangs }, # Rational root and unsolvable quintic 'lin_const_coeff_hom_36': { 'eq': f(x).diff(x, 6) - 6*f(x).diff(x, 5) + 5*f(x).diff(x, 4) + 10*f(x).diff(x) - 50 * f(x), 'sol': [Eq(f(x), C5*exp(5*x) + C6*exp(x*r16) + exp(re(r17)*x) * (C1*sin(im(r17)*x) + C2*cos(im(r17)*x)) + exp(re(r19)*x) * (C3*sin(im(r19)*x) + C4*cos(im(r19)*x)))], 'checkodesol_XFAIL':True, #It Hangs }, # Five double roots (this is (x**5 - x + 1)**2) 'lin_const_coeff_hom_37': { 'eq': f(x).diff(x, 10) - 2*f(x).diff(x, 6) + 2*f(x).diff(x, 5) + f(x).diff(x, 2) - 2*f(x).diff(x, 1) + f(x), 'sol': [Eq(f(x), (C1 + C2*x)*exp(x*r21) + (-((C3 + C4*x)*sin(x*im(r22))) + (C5 + C6*x)*cos(x*im(r22)))*exp(x*re(r22)) + (-((C7 + C8*x)*sin(x*im(r24))) + (C10*x + C9)*cos(x*im(r24)))*exp(x*re(r24)))], 'checkodesol_XFAIL':True, #It Hangs }, 'lin_const_coeff_hom_38': { 'eq': Eq(sqrt(2) * f(x).diff(x,x,x) + f(x).diff(x), 0), 'sol': [Eq(f(x), C1 + C2*sin(2**Rational(3, 4)*x/2) + C3*cos(2**Rational(3, 4)*x/2))], }, 'lin_const_coeff_hom_39': { 'eq': Eq(E * f(x).diff(x,x,x) + f(x).diff(x), 0), 'sol': [Eq(f(x), C1 + C2*sin(x/sqrt(E)) + C3*cos(x/sqrt(E)))], }, 'lin_const_coeff_hom_40': { 'eq': Eq(pi * f(x).diff(x,x,x) + f(x).diff(x), 0), 'sol': [Eq(f(x), C1 + C2*sin(x/sqrt(pi)) + C3*cos(x/sqrt(pi)))], }, 'lin_const_coeff_hom_41': { 'eq': Eq(I * f(x).diff(x,x,x) + f(x).diff(x), 0), 'sol': [Eq(f(x), C1 + C2*exp(-sqrt(I)*x) + C3*exp(sqrt(I)*x))], }, 'lin_const_coeff_hom_42': { 'eq': f(x).diff(x, x) + y*f(x), 'sol': [Eq(f(x), C1*exp(-x*sqrt(-y)) + C2*exp(x*sqrt(-y)))], }, 'lin_const_coeff_hom_43': { 'eq': Eq(9*f(x).diff(x, x) + f(x), 0), 'sol': [Eq(f(x), C1*sin(x/3) + C2*cos(x/3))], }, 'lin_const_coeff_hom_44': { 'eq': Eq(9*f(x).diff(x, x), f(x)), 'sol': [Eq(f(x), C1*exp(-x/3) + C2*exp(x/3))], }, 'lin_const_coeff_hom_45': { 'eq': Eq(f(x).diff(x, x) - 3*diff(f(x), x) + 2*f(x), 0), 'sol': [Eq(f(x), (C1 + C2*exp(x))*exp(x))], }, 'lin_const_coeff_hom_46': { 'eq': Eq(f(x).diff(x, x) - 4*diff(f(x), x) + 4*f(x), 0), 'sol': [Eq(f(x), (C1 + C2*x)*exp(2*x))], }, # Type: 2nd order, constant coefficients (two real equal roots) 'lin_const_coeff_hom_47': { 'eq': Eq(f(x).diff(x, x) + 2*diff(f(x), x) + 3*f(x), 0), 'sol': [Eq(f(x), (C1*sin(x*sqrt(2)) + C2*cos(x*sqrt(2)))*exp(-x))], }, #These were from issue: https://github.com/sympy/sympy/issues/6247 'lin_const_coeff_hom_48': { 'eq': f(x).diff(x, x) + 4*f(x), 'sol': [Eq(f(x), C1*sin(2*x) + C2*cos(2*x))], }, } } @_add_example_keys def _get_examples_ode_sol_1st_homogeneous_coeff_subs_dep_div_indep(): return { 'hint': "1st_homogeneous_coeff_subs_dep_div_indep", 'func': f(x), 'examples':{ 'dep_div_indep_01': { 'eq': f(x)/x*cos(f(x)/x) - (x/f(x)*sin(f(x)/x) + cos(f(x)/x))*f(x).diff(x), 'sol': [Eq(log(x), C1 - log(f(x)*sin(f(x)/x)/x))], 'slow': True }, #indep_div_dep actually has a simpler solution for example 2 but it runs too slow. 'dep_div_indep_02': { 'eq': x*f(x).diff(x) - f(x) - x*sin(f(x)/x), 'sol': [Eq(log(x), log(C1) + log(cos(f(x)/x) - 1)/2 - log(cos(f(x)/x) + 1)/2)], 'simplify_flag':False, }, 'dep_div_indep_03': { 'eq': x*exp(f(x)/x) - f(x)*sin(f(x)/x) + x*sin(f(x)/x)*f(x).diff(x), 'sol': [Eq(log(x), C1 + exp(-f(x)/x)*sin(f(x)/x)/2 + exp(-f(x)/x)*cos(f(x)/x)/2)], 'slow': True }, 'dep_div_indep_04': { 'eq': f(x).diff(x) - f(x)/x + 1/sin(f(x)/x), 'sol': [Eq(f(x), x*(-acos(C1 + log(x)) + 2*pi)), Eq(f(x), x*acos(C1 + log(x)))], 'slow': True }, # previous code was testing with these other solution: # example5_solb = Eq(f(x), log(log(C1/x)**(-x))) 'dep_div_indep_05': { 'eq': x*exp(f(x)/x) + f(x) - x*f(x).diff(x), 'sol': [Eq(f(x), log((1/(C1 - log(x)))**x))], 'checkodesol_XFAIL':True, #(because of **x?) }, } } @_add_example_keys def _get_examples_ode_sol_linear_coefficients(): return { 'hint': "linear_coefficients", 'func': f(x), 'examples':{ 'linear_coeff_01': { 'eq': f(x).diff(x) + (3 + 2*f(x))/(x + 3), 'sol': [Eq(f(x), C1/(x**2 + 6*x + 9) - Rational(3, 2))], }, } } @_add_example_keys def _get_examples_ode_sol_1st_homogeneous_coeff_best(): return { 'hint': "1st_homogeneous_coeff_best", 'func': f(x), 'examples':{ # previous code was testing this with other solution: # example1_solb = Eq(-f(x)/(1 + log(x/f(x))), C1) '1st_homogeneous_coeff_best_01': { 'eq': f(x) + (x*log(f(x)/x) - 2*x)*diff(f(x), x), 'sol': [Eq(f(x), -exp(C1)*LambertW(-x*exp(-C1 + 1)))], 'checkodesol_XFAIL':True, #(because of LambertW?) }, '1st_homogeneous_coeff_best_02': { 'eq': 2*f(x)*exp(x/f(x)) + f(x)*f(x).diff(x) - 2*x*exp(x/f(x))*f(x).diff(x), 'sol': [Eq(log(f(x)), C1 - 2*exp(x/f(x)))], }, # previous code was testing this with other solution: # example3_solb = Eq(log(C1*x*sqrt(1/x)*sqrt(f(x))) + x**2/(2*f(x)**2), 0) '1st_homogeneous_coeff_best_03': { 'eq': 2*x**2*f(x) + f(x)**3 + (x*f(x)**2 - 2*x**3)*f(x).diff(x), 'sol': [Eq(f(x), exp(2*C1 + LambertW(-2*x**4*exp(-4*C1))/2)/x)], 'checkodesol_XFAIL':True, #(because of LambertW?) }, '1st_homogeneous_coeff_best_04': { 'eq': (x + sqrt(f(x)**2 - x*f(x)))*f(x).diff(x) - f(x), 'sol': [Eq(log(f(x)), C1 - 2*sqrt(-x/f(x) + 1))], 'slow': True, }, '1st_homogeneous_coeff_best_05': { 'eq': x + f(x) - (x - f(x))*f(x).diff(x), 'sol': [Eq(log(x), C1 - log(sqrt(1 + f(x)**2/x**2)) + atan(f(x)/x))], }, '1st_homogeneous_coeff_best_06': { 'eq': x*f(x).diff(x) - f(x) - x*sin(f(x)/x), 'sol': [Eq(f(x), 2*x*atan(C1*x))], }, '1st_homogeneous_coeff_best_07': { 'eq': x**2 + f(x)**2 - 2*x*f(x)*f(x).diff(x), 'sol': [Eq(f(x), -sqrt(x*(C1 + x))), Eq(f(x), sqrt(x*(C1 + x)))], }, '1st_homogeneous_coeff_best_08': { 'eq': f(x)**2 + (x*sqrt(f(x)**2 - x**2) - x*f(x))*f(x).diff(x), 'sol': [Eq(log(x), C1 - log(f(x)/x) + acosh(f(x)/x))], }, } } def _get_all_examples(): all_examples = _get_examples_ode_sol_euler_homogeneous + \ _get_examples_ode_sol_euler_undetermined_coeff + \ _get_examples_ode_sol_euler_var_para + \ _get_examples_ode_sol_factorable + \ _get_examples_ode_sol_bernoulli + \ _get_examples_ode_sol_nth_algebraic + \ _get_examples_ode_sol_riccati + \ _get_examples_ode_sol_1st_linear + \ _get_examples_ode_sol_1st_exact + \ _get_examples_ode_sol_almost_linear + \ _get_examples_ode_sol_nth_order_reducible + \ _get_examples_ode_sol_nth_linear_undetermined_coefficients + \ _get_examples_ode_sol_liouville + \ _get_examples_ode_sol_separable + \ _get_examples_ode_sol_1st_rational_riccati + \ _get_examples_ode_sol_nth_linear_var_of_parameters + \ _get_examples_ode_sol_2nd_linear_bessel + \ _get_examples_ode_sol_2nd_2F1_hypergeometric + \ _get_examples_ode_sol_2nd_nonlinear_autonomous_conserved + \ _get_examples_ode_sol_separable_reduced + \ _get_examples_ode_sol_lie_group + \ _get_examples_ode_sol_2nd_linear_airy + \ _get_examples_ode_sol_nth_linear_constant_coeff_homogeneous +\ _get_examples_ode_sol_1st_homogeneous_coeff_best +\ _get_examples_ode_sol_1st_homogeneous_coeff_subs_dep_div_indep +\ _get_examples_ode_sol_linear_coefficients return all_examples
c0d0a340528de0441a7aed85d10cb483f21e5da63bda05e5a83b7fc5f21524b3
from sympy.core.numbers import (E, Rational, pi) from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.core import S, symbols, I from sympy.discrete.convolutions import ( convolution, convolution_fft, convolution_ntt, convolution_fwht, convolution_subset, covering_product, intersecting_product) from sympy.testing.pytest import raises from sympy.abc import x, y def test_convolution(): # fft a = [1, Rational(5, 3), sqrt(3), Rational(7, 5)] b = [9, 5, 5, 4, 3, 2] c = [3, 5, 3, 7, 8] d = [1422, 6572, 3213, 5552] assert convolution(a, b) == convolution_fft(a, b) assert convolution(a, b, dps=9) == convolution_fft(a, b, dps=9) assert convolution(a, d, dps=7) == convolution_fft(d, a, dps=7) assert convolution(a, d[1:], dps=3) == convolution_fft(d[1:], a, dps=3) # prime moduli of the form (m*2**k + 1), sequence length # should be a divisor of 2**k p = 7*17*2**23 + 1 q = 19*2**10 + 1 # ntt assert convolution(d, b, prime=q) == convolution_ntt(b, d, prime=q) assert convolution(c, b, prime=p) == convolution_ntt(b, c, prime=p) assert convolution(d, c, prime=p) == convolution_ntt(c, d, prime=p) raises(TypeError, lambda: convolution(b, d, dps=5, prime=q)) raises(TypeError, lambda: convolution(b, d, dps=6, prime=q)) # fwht assert convolution(a, b, dyadic=True) == convolution_fwht(a, b) assert convolution(a, b, dyadic=False) == convolution(a, b) raises(TypeError, lambda: convolution(b, d, dps=2, dyadic=True)) raises(TypeError, lambda: convolution(b, d, prime=p, dyadic=True)) raises(TypeError, lambda: convolution(a, b, dps=2, dyadic=True)) raises(TypeError, lambda: convolution(b, c, prime=p, dyadic=True)) # subset assert convolution(a, b, subset=True) == convolution_subset(a, b) == \ convolution(a, b, subset=True, dyadic=False) == \ convolution(a, b, subset=True) assert convolution(a, b, subset=False) == convolution(a, b) raises(TypeError, lambda: convolution(a, b, subset=True, dyadic=True)) raises(TypeError, lambda: convolution(c, d, subset=True, dps=6)) raises(TypeError, lambda: convolution(a, c, subset=True, prime=q)) def test_cyclic_convolution(): # fft a = [1, Rational(5, 3), sqrt(3), Rational(7, 5)] b = [9, 5, 5, 4, 3, 2] assert convolution([1, 2, 3], [4, 5, 6], cycle=0) == \ convolution([1, 2, 3], [4, 5, 6], cycle=5) == \ convolution([1, 2, 3], [4, 5, 6]) assert convolution([1, 2, 3], [4, 5, 6], cycle=3) == [31, 31, 28] a = [Rational(1, 3), Rational(7, 3), Rational(5, 9), Rational(2, 7), Rational(5, 8)] b = [Rational(3, 5), Rational(4, 7), Rational(7, 8), Rational(8, 9)] assert convolution(a, b, cycle=0) == \ convolution(a, b, cycle=len(a) + len(b) - 1) assert convolution(a, b, cycle=4) == [Rational(87277, 26460), Rational(30521, 11340), Rational(11125, 4032), Rational(3653, 1080)] assert convolution(a, b, cycle=6) == [Rational(20177, 20160), Rational(676, 315), Rational(47, 24), Rational(3053, 1080), Rational(16397, 5292), Rational(2497, 2268)] assert convolution(a, b, cycle=9) == \ convolution(a, b, cycle=0) + [S.Zero] # ntt a = [2313, 5323532, S(3232), 42142, 42242421] b = [S(33456), 56757, 45754, 432423] assert convolution(a, b, prime=19*2**10 + 1, cycle=0) == \ convolution(a, b, prime=19*2**10 + 1, cycle=8) == \ convolution(a, b, prime=19*2**10 + 1) assert convolution(a, b, prime=19*2**10 + 1, cycle=5) == [96, 17146, 2664, 15534, 3517] assert convolution(a, b, prime=19*2**10 + 1, cycle=7) == [4643, 3458, 1260, 15534, 3517, 16314, 13688] assert convolution(a, b, prime=19*2**10 + 1, cycle=9) == \ convolution(a, b, prime=19*2**10 + 1) + [0] # fwht u, v, w, x, y = symbols('u v w x y') p, q, r, s, t = symbols('p q r s t') c = [u, v, w, x, y] d = [p, q, r, s, t] assert convolution(a, b, dyadic=True, cycle=3) == \ [2499522285783, 19861417974796, 4702176579021] assert convolution(a, b, dyadic=True, cycle=5) == [2718149225143, 2114320852171, 20571217906407, 246166418903, 1413262436976] assert convolution(c, d, dyadic=True, cycle=4) == \ [p*u + p*y + q*v + r*w + s*x + t*u + t*y, p*v + q*u + q*y + r*x + s*w + t*v, p*w + q*x + r*u + r*y + s*v + t*w, p*x + q*w + r*v + s*u + s*y + t*x] assert convolution(c, d, dyadic=True, cycle=6) == \ [p*u + q*v + r*w + r*y + s*x + t*w + t*y, p*v + q*u + r*x + s*w + s*y + t*x, p*w + q*x + r*u + s*v, p*x + q*w + r*v + s*u, p*y + t*u, q*y + t*v] # subset assert convolution(a, b, subset=True, cycle=7) == [18266671799811, 178235365533, 213958794, 246166418903, 1413262436976, 2397553088697, 1932759730434] assert convolution(a[1:], b, subset=True, cycle=4) == \ [178104086592, 302255835516, 244982785880, 3717819845434] assert convolution(a, b[:-1], subset=True, cycle=6) == [1932837114162, 178235365533, 213958794, 245166224504, 1413262436976, 2397553088697] assert convolution(c, d, subset=True, cycle=3) == \ [p*u + p*x + q*w + r*v + r*y + s*u + t*w, p*v + p*y + q*u + s*y + t*u + t*x, p*w + q*y + r*u + t*v] assert convolution(c, d, subset=True, cycle=5) == \ [p*u + q*y + t*v, p*v + q*u + r*y + t*w, p*w + r*u + s*y + t*x, p*x + q*w + r*v + s*u, p*y + t*u] raises(ValueError, lambda: convolution([1, 2, 3], [4, 5, 6], cycle=-1)) def test_convolution_fft(): assert all(convolution_fft([], x, dps=y) == [] for x in ([], [1]) for y in (None, 3)) assert convolution_fft([1, 2, 3], [4, 5, 6]) == [4, 13, 28, 27, 18] assert convolution_fft([1], [5, 6, 7]) == [5, 6, 7] assert convolution_fft([1, 3], [5, 6, 7]) == [5, 21, 25, 21] assert convolution_fft([1 + 2*I], [2 + 3*I]) == [-4 + 7*I] assert convolution_fft([1 + 2*I, 3 + 4*I, 5 + 3*I/5], [Rational(2, 5) + 4*I/7]) == \ [Rational(-26, 35) + I*48/35, Rational(-38, 35) + I*116/35, Rational(58, 35) + I*542/175] assert convolution_fft([Rational(3, 4), Rational(5, 6)], [Rational(7, 8), Rational(1, 3), Rational(2, 5)]) == \ [Rational(21, 32), Rational(47, 48), Rational(26, 45), Rational(1, 3)] assert convolution_fft([Rational(1, 9), Rational(2, 3), Rational(3, 5)], [Rational(2, 5), Rational(3, 7), Rational(4, 9)]) == \ [Rational(2, 45), Rational(11, 35), Rational(8152, 14175), Rational(523, 945), Rational(4, 15)] assert convolution_fft([pi, E, sqrt(2)], [sqrt(3), 1/pi, 1/E]) == \ [sqrt(3)*pi, 1 + sqrt(3)*E, E/pi + pi*exp(-1) + sqrt(6), sqrt(2)/pi + 1, sqrt(2)*exp(-1)] assert convolution_fft([2321, 33123], [5321, 6321, 71323]) == \ [12350041, 190918524, 374911166, 2362431729] assert convolution_fft([312313, 31278232], [32139631, 319631]) == \ [10037624576503, 1005370659728895, 9997492572392] raises(TypeError, lambda: convolution_fft(x, y)) raises(ValueError, lambda: convolution_fft([x, y], [y, x])) def test_convolution_ntt(): # prime moduli of the form (m*2**k + 1), sequence length # should be a divisor of 2**k p = 7*17*2**23 + 1 q = 19*2**10 + 1 r = 2*500000003 + 1 # only for sequences of length 1 or 2 # s = 2*3*5*7 # composite modulus assert all(convolution_ntt([], x, prime=y) == [] for x in ([], [1]) for y in (p, q, r)) assert convolution_ntt([2], [3], r) == [6] assert convolution_ntt([2, 3], [4], r) == [8, 12] assert convolution_ntt([32121, 42144, 4214, 4241], [32132, 3232, 87242], p) == [33867619, 459741727, 79180879, 831885249, 381344700, 369993322] assert convolution_ntt([121913, 3171831, 31888131, 12], [17882, 21292, 29921, 312], q) == \ [8158, 3065, 3682, 7090, 1239, 2232, 3744] assert convolution_ntt([12, 19, 21, 98, 67], [2, 6, 7, 8, 9], p) == \ convolution_ntt([12, 19, 21, 98, 67], [2, 6, 7, 8, 9], q) assert convolution_ntt([12, 19, 21, 98, 67], [21, 76, 17, 78, 69], p) == \ convolution_ntt([12, 19, 21, 98, 67], [21, 76, 17, 78, 69], q) raises(ValueError, lambda: convolution_ntt([2, 3], [4, 5], r)) raises(ValueError, lambda: convolution_ntt([x, y], [y, x], q)) raises(TypeError, lambda: convolution_ntt(x, y, p)) def test_convolution_fwht(): assert convolution_fwht([], []) == [] assert convolution_fwht([], [1]) == [] assert convolution_fwht([1, 2, 3], [4, 5, 6]) == [32, 13, 18, 27] assert convolution_fwht([Rational(5, 7), Rational(6, 8), Rational(7, 3)], [2, 4, Rational(6, 7)]) == \ [Rational(45, 7), Rational(61, 14), Rational(776, 147), Rational(419, 42)] a = [1, Rational(5, 3), sqrt(3), Rational(7, 5), 4 + 5*I] b = [94, 51, 53, 45, 31, 27, 13] c = [3 + 4*I, 5 + 7*I, 3, Rational(7, 6), 8] assert convolution_fwht(a, b) == [53*sqrt(3) + 366 + 155*I, 45*sqrt(3) + Rational(5848, 15) + 135*I, 94*sqrt(3) + Rational(1257, 5) + 65*I, 51*sqrt(3) + Rational(3974, 15), 13*sqrt(3) + 452 + 470*I, Rational(4513, 15) + 255*I, 31*sqrt(3) + Rational(1314, 5) + 265*I, 27*sqrt(3) + Rational(3676, 15) + 225*I] assert convolution_fwht(b, c) == [Rational(1993, 2) + 733*I, Rational(6215, 6) + 862*I, Rational(1659, 2) + 527*I, Rational(1988, 3) + 551*I, 1019 + 313*I, Rational(3955, 6) + 325*I, Rational(1175, 2) + 52*I, Rational(3253, 6) + 91*I] assert convolution_fwht(a[3:], c) == [Rational(-54, 5) + I*293/5, -1 + I*204/5, Rational(133, 15) + I*35/6, Rational(409, 30) + 15*I, Rational(56, 5), 32 + 40*I, 0, 0] u, v, w, x, y, z = symbols('u v w x y z') assert convolution_fwht([u, v], [x, y]) == [u*x + v*y, u*y + v*x] assert convolution_fwht([u, v, w], [x, y]) == \ [u*x + v*y, u*y + v*x, w*x, w*y] assert convolution_fwht([u, v, w], [x, y, z]) == \ [u*x + v*y + w*z, u*y + v*x, u*z + w*x, v*z + w*y] raises(TypeError, lambda: convolution_fwht(x, y)) raises(TypeError, lambda: convolution_fwht(x*y, u + v)) def test_convolution_subset(): assert convolution_subset([], []) == [] assert convolution_subset([], [Rational(1, 3)]) == [] assert convolution_subset([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7] a = [1, Rational(5, 3), sqrt(3), 4 + 5*I] b = [64, 71, 55, 47, 33, 29, 15] c = [3 + I*2/3, 5 + 7*I, 7, Rational(7, 5), 9] assert convolution_subset(a, b) == [64, Rational(533, 3), 55 + 64*sqrt(3), 71*sqrt(3) + Rational(1184, 3) + 320*I, 33, 84, 15 + 33*sqrt(3), 29*sqrt(3) + 157 + 165*I] assert convolution_subset(b, c) == [192 + I*128/3, 533 + I*1486/3, 613 + I*110/3, Rational(5013, 5) + I*1249/3, 675 + 22*I, 891 + I*751/3, 771 + 10*I, Rational(3736, 5) + 105*I] assert convolution_subset(a, c) == convolution_subset(c, a) assert convolution_subset(a[:2], b) == \ [64, Rational(533, 3), 55, Rational(416, 3), 33, 84, 15, 25] assert convolution_subset(a[:2], c) == \ [3 + I*2/3, 10 + I*73/9, 7, Rational(196, 15), 9, 15, 0, 0] u, v, w, x, y, z = symbols('u v w x y z') assert convolution_subset([u, v, w], [x, y]) == [u*x, u*y + v*x, w*x, w*y] assert convolution_subset([u, v, w, x], [y, z]) == \ [u*y, u*z + v*y, w*y, w*z + x*y] assert convolution_subset([u, v], [x, y, z]) == \ convolution_subset([x, y, z], [u, v]) raises(TypeError, lambda: convolution_subset(x, z)) raises(TypeError, lambda: convolution_subset(Rational(7, 3), u)) def test_covering_product(): assert covering_product([], []) == [] assert covering_product([], [Rational(1, 3)]) == [] assert covering_product([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7] a = [1, Rational(5, 8), sqrt(7), 4 + 9*I] b = [66, 81, 95, 49, 37, 89, 17] c = [3 + I*2/3, 51 + 72*I, 7, Rational(7, 15), 91] assert covering_product(a, b) == [66, Rational(1383, 8), 95 + 161*sqrt(7), 130*sqrt(7) + 1303 + 2619*I, 37, Rational(671, 4), 17 + 54*sqrt(7), 89*sqrt(7) + Rational(4661, 8) + 1287*I] assert covering_product(b, c) == [198 + 44*I, 7740 + 10638*I, 1412 + I*190/3, Rational(42684, 5) + I*31202/3, 9484 + I*74/3, 22163 + I*27394/3, 10621 + I*34/3, Rational(90236, 15) + 1224*I] assert covering_product(a, c) == covering_product(c, a) assert covering_product(b, c[:-1]) == [198 + 44*I, 7740 + 10638*I, 1412 + I*190/3, Rational(42684, 5) + I*31202/3, 111 + I*74/3, 6693 + I*27394/3, 429 + I*34/3, Rational(23351, 15) + 1224*I] assert covering_product(a, c[:-1]) == [3 + I*2/3, Rational(339, 4) + I*1409/12, 7 + 10*sqrt(7) + 2*sqrt(7)*I/3, -403 + 772*sqrt(7)/15 + 72*sqrt(7)*I + I*12658/15] u, v, w, x, y, z = symbols('u v w x y z') assert covering_product([u, v, w], [x, y]) == \ [u*x, u*y + v*x + v*y, w*x, w*y] assert covering_product([u, v, w, x], [y, z]) == \ [u*y, u*z + v*y + v*z, w*y, w*z + x*y + x*z] assert covering_product([u, v], [x, y, z]) == \ covering_product([x, y, z], [u, v]) raises(TypeError, lambda: covering_product(x, z)) raises(TypeError, lambda: covering_product(Rational(7, 3), u)) def test_intersecting_product(): assert intersecting_product([], []) == [] assert intersecting_product([], [Rational(1, 3)]) == [] assert intersecting_product([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7] a = [1, sqrt(5), Rational(3, 8) + 5*I, 4 + 7*I] b = [67, 51, 65, 48, 36, 79, 27] c = [3 + I*2/5, 5 + 9*I, 7, Rational(7, 19), 13] assert intersecting_product(a, b) == [195*sqrt(5) + Rational(6979, 8) + 1886*I, 178*sqrt(5) + 520 + 910*I, Rational(841, 2) + 1344*I, 192 + 336*I, 0, 0, 0, 0] assert intersecting_product(b, c) == [Rational(128553, 19) + I*9521/5, Rational(17820, 19) + 1602*I, Rational(19264, 19), Rational(336, 19), 1846, 0, 0, 0] assert intersecting_product(a, c) == intersecting_product(c, a) assert intersecting_product(b[1:], c[:-1]) == [Rational(64788, 19) + I*8622/5, Rational(12804, 19) + 1152*I, Rational(11508, 19), Rational(252, 19), 0, 0, 0, 0] assert intersecting_product(a, c[:-2]) == \ [Rational(-99, 5) + 10*sqrt(5) + 2*sqrt(5)*I/5 + I*3021/40, -43 + 5*sqrt(5) + 9*sqrt(5)*I + 71*I, Rational(245, 8) + 84*I, 0] u, v, w, x, y, z = symbols('u v w x y z') assert intersecting_product([u, v, w], [x, y]) == \ [u*x + u*y + v*x + w*x + w*y, v*y, 0, 0] assert intersecting_product([u, v, w, x], [y, z]) == \ [u*y + u*z + v*y + w*y + w*z + x*y, v*z + x*z, 0, 0] assert intersecting_product([u, v], [x, y, z]) == \ intersecting_product([x, y, z], [u, v]) raises(TypeError, lambda: intersecting_product(x, z)) raises(TypeError, lambda: intersecting_product(u, Rational(8, 3)))
bc439115a3efc663d2b30d1fe19da12c4375c03d0577240e6070c463d6959b90
from sympy.functions.elementary.miscellaneous import sqrt from sympy.core import S, Symbol, symbols, I, Rational from sympy.discrete import (fft, ifft, ntt, intt, fwht, ifwht, mobius_transform, inverse_mobius_transform) from sympy.testing.pytest import raises def test_fft_ifft(): assert all(tf(ls) == ls for tf in (fft, ifft) for ls in ([], [Rational(5, 3)])) ls = list(range(6)) fls = [15, -7*sqrt(2)/2 - 4 - sqrt(2)*I/2 + 2*I, 2 + 3*I, -4 + 7*sqrt(2)/2 - 2*I - sqrt(2)*I/2, -3, -4 + 7*sqrt(2)/2 + sqrt(2)*I/2 + 2*I, 2 - 3*I, -7*sqrt(2)/2 - 4 - 2*I + sqrt(2)*I/2] assert fft(ls) == fls assert ifft(fls) == ls + [S.Zero]*2 ls = [1 + 2*I, 3 + 4*I, 5 + 6*I] ifls = [Rational(9, 4) + 3*I, I*Rational(-7, 4), Rational(3, 4) + I, -2 - I/4] assert ifft(ls) == ifls assert fft(ifls) == ls + [S.Zero] x = Symbol('x', real=True) raises(TypeError, lambda: fft(x)) raises(ValueError, lambda: ifft([x, 2*x, 3*x**2, 4*x**3])) def test_ntt_intt(): # prime moduli of the form (m*2**k + 1), sequence length # should be a divisor of 2**k p = 7*17*2**23 + 1 q = 2*500000003 + 1 # only for sequences of length 1 or 2 r = 2*3*5*7 # composite modulus assert all(tf(ls, p) == ls for tf in (ntt, intt) for ls in ([], [5])) ls = list(range(6)) nls = [15, 801133602, 738493201, 334102277, 998244350, 849020224, 259751156, 12232587] assert ntt(ls, p) == nls assert intt(nls, p) == ls + [0]*2 ls = [1 + 2*I, 3 + 4*I, 5 + 6*I] x = Symbol('x', integer=True) raises(TypeError, lambda: ntt(x, p)) raises(ValueError, lambda: intt([x, 2*x, 3*x**2, 4*x**3], p)) raises(ValueError, lambda: intt(ls, p)) raises(ValueError, lambda: ntt([1.2, 2.1, 3.5], p)) raises(ValueError, lambda: ntt([3, 5, 6], q)) raises(ValueError, lambda: ntt([4, 5, 7], r)) raises(ValueError, lambda: ntt([1.0, 2.0, 3.0], p)) def test_fwht_ifwht(): assert all(tf(ls) == ls for tf in (fwht, ifwht) \ for ls in ([], [Rational(7, 4)])) ls = [213, 321, 43235, 5325, 312, 53] fls = [49459, 38061, -47661, -37759, 48729, 37543, -48391, -38277] assert fwht(ls) == fls assert ifwht(fls) == ls + [S.Zero]*2 ls = [S.Half + 2*I, Rational(3, 7) + 4*I, Rational(5, 6) + 6*I, Rational(7, 3), Rational(9, 4)] ifls = [Rational(533, 672) + I*3/2, Rational(23, 224) + I/2, Rational(1, 672), Rational(107, 224) - I, Rational(155, 672) + I*3/2, Rational(-103, 224) + I/2, Rational(-377, 672), Rational(-19, 224) - I] assert ifwht(ls) == ifls assert fwht(ifls) == ls + [S.Zero]*3 x, y = symbols('x y') raises(TypeError, lambda: fwht(x)) ls = [x, 2*x, 3*x**2, 4*x**3] ifls = [x**3 + 3*x**2/4 + x*Rational(3, 4), -x**3 + 3*x**2/4 - x/4, -x**3 - 3*x**2/4 + x*Rational(3, 4), x**3 - 3*x**2/4 - x/4] assert ifwht(ls) == ifls assert fwht(ifls) == ls ls = [x, y, x**2, y**2, x*y] fls = [x**2 + x*y + x + y**2 + y, x**2 + x*y + x - y**2 - y, -x**2 + x*y + x - y**2 + y, -x**2 + x*y + x + y**2 - y, x**2 - x*y + x + y**2 + y, x**2 - x*y + x - y**2 - y, -x**2 - x*y + x - y**2 + y, -x**2 - x*y + x + y**2 - y] assert fwht(ls) == fls assert ifwht(fls) == ls + [S.Zero]*3 ls = list(range(6)) assert fwht(ls) == [x*8 for x in ifwht(ls)] def test_mobius_transform(): assert all(tf(ls, subset=subset) == ls for ls in ([], [Rational(7, 4)]) for subset in (True, False) for tf in (mobius_transform, inverse_mobius_transform)) w, x, y, z = symbols('w x y z') assert mobius_transform([x, y]) == [x, x + y] assert inverse_mobius_transform([x, x + y]) == [x, y] assert mobius_transform([x, y], subset=False) == [x + y, y] assert inverse_mobius_transform([x + y, y], subset=False) == [x, y] assert mobius_transform([w, x, y, z]) == [w, w + x, w + y, w + x + y + z] assert inverse_mobius_transform([w, w + x, w + y, w + x + y + z]) == \ [w, x, y, z] assert mobius_transform([w, x, y, z], subset=False) == \ [w + x + y + z, x + z, y + z, z] assert inverse_mobius_transform([w + x + y + z, x + z, y + z, z], subset=False) == \ [w, x, y, z] ls = [Rational(2, 3), Rational(6, 7), Rational(5, 8), 9, Rational(5, 3) + 7*I] mls = [Rational(2, 3), Rational(32, 21), Rational(31, 24), Rational(1873, 168), Rational(7, 3) + 7*I, Rational(67, 21) + 7*I, Rational(71, 24) + 7*I, Rational(2153, 168) + 7*I] assert mobius_transform(ls) == mls assert inverse_mobius_transform(mls) == ls + [S.Zero]*3 mls = [Rational(2153, 168) + 7*I, Rational(69, 7), Rational(77, 8), 9, Rational(5, 3) + 7*I, 0, 0, 0] assert mobius_transform(ls, subset=False) == mls assert inverse_mobius_transform(mls, subset=False) == ls + [S.Zero]*3 ls = ls[:-1] mls = [Rational(2, 3), Rational(32, 21), Rational(31, 24), Rational(1873, 168)] assert mobius_transform(ls) == mls assert inverse_mobius_transform(mls) == ls mls = [Rational(1873, 168), Rational(69, 7), Rational(77, 8), 9] assert mobius_transform(ls, subset=False) == mls assert inverse_mobius_transform(mls, subset=False) == ls raises(TypeError, lambda: mobius_transform(x, subset=True)) raises(TypeError, lambda: inverse_mobius_transform(y, subset=False))
a492c04e6c2109d510e65fedb2c8ab95073d9c9108488f4526353a206504d78d
from sympy.core.numbers import (E, I, Rational, oo, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import (Abs, re) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (cos, cot, csc, sec, sin, tan) from sympy.functions.special.error_functions import expint from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.simplify.simplify import simplify from sympy.calculus.util import (function_range, continuous_domain, not_empty_in, periodicity, lcim, is_convex, stationary_points, minimum, maximum) from sympy.sets.sets import (Interval, FiniteSet, Complement, Union) from sympy.testing.pytest import raises, _both_exp_pow from sympy.abc import x a = Symbol('a', real=True) def test_function_range(): x, y, a, b = symbols('x y a b') assert function_range(sin(x), x, Interval(-pi/2, pi/2) ) == Interval(-1, 1) assert function_range(sin(x), x, Interval(0, pi) ) == Interval(0, 1) assert function_range(tan(x), x, Interval(0, pi) ) == Interval(-oo, oo) assert function_range(tan(x), x, Interval(pi/2, pi) ) == Interval(-oo, 0) assert function_range((x + 3)/(x - 2), x, Interval(-5, 5) ) == Union(Interval(-oo, Rational(2, 7)), Interval(Rational(8, 3), oo)) assert function_range(1/(x**2), x, Interval(-1, 1) ) == Interval(1, oo) assert function_range(exp(x), x, Interval(-1, 1) ) == Interval(exp(-1), exp(1)) assert function_range(log(x) - x, x, S.Reals ) == Interval(-oo, -1) assert function_range(sqrt(3*x - 1), x, Interval(0, 2) ) == Interval(0, sqrt(5)) assert function_range(x*(x - 1) - (x**2 - x), x, S.Reals ) == FiniteSet(0) assert function_range(x*(x - 1) - (x**2 - x) + y, x, S.Reals ) == FiniteSet(y) assert function_range(sin(x), x, Union(Interval(-5, -3), FiniteSet(4)) ) == Union(Interval(-sin(3), 1), FiniteSet(sin(4))) assert function_range(cos(x), x, Interval(-oo, -4) ) == Interval(-1, 1) assert function_range(cos(x), x, S.EmptySet) == S.EmptySet assert function_range(x/sqrt(x**2+1), x, S.Reals) == Interval.open(-1,1) raises(NotImplementedError, lambda : function_range( exp(x)*(sin(x) - cos(x))/2 - x, x, S.Reals)) raises(NotImplementedError, lambda : function_range( sin(x) + x, x, S.Reals)) # issue 13273 raises(NotImplementedError, lambda : function_range( log(x), x, S.Integers)) raises(NotImplementedError, lambda : function_range( sin(x)/2, x, S.Naturals)) def test_continuous_domain(): x = Symbol('x') assert continuous_domain(sin(x), x, Interval(0, 2*pi)) == Interval(0, 2*pi) assert continuous_domain(tan(x), x, Interval(0, 2*pi)) == \ Union(Interval(0, pi/2, False, True), Interval(pi/2, pi*Rational(3, 2), True, True), Interval(pi*Rational(3, 2), 2*pi, True, False)) assert continuous_domain((x - 1)/((x - 1)**2), x, S.Reals) == \ Union(Interval(-oo, 1, True, True), Interval(1, oo, True, True)) assert continuous_domain(log(x) + log(4*x - 1), x, S.Reals) == \ Interval(Rational(1, 4), oo, True, True) assert continuous_domain(1/sqrt(x - 3), x, S.Reals) == Interval(3, oo, True, True) assert continuous_domain(1/x - 2, x, S.Reals) == \ Union(Interval.open(-oo, 0), Interval.open(0, oo)) assert continuous_domain(1/(x**2 - 4) + 2, x, S.Reals) == \ Union(Interval.open(-oo, -2), Interval.open(-2, 2), Interval.open(2, oo)) domain = continuous_domain(log(tan(x)**2 + 1), x, S.Reals) assert not domain.contains(3*pi/2) assert domain.contains(5) d = Symbol('d', even=True, zero=False) assert continuous_domain(x**(1/d), x, S.Reals) == Interval(0, oo) def test_not_empty_in(): assert not_empty_in(FiniteSet(x, 2*x).intersect(Interval(1, 2, True, False)), x) == \ Interval(S.Half, 2, True, False) assert not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x) == \ Union(Interval(-sqrt(2), -1), Interval(1, 2)) assert not_empty_in(FiniteSet(x**2 + x, x).intersect(Interval(2, 4)), x) == \ Union(Interval(-sqrt(17)/2 - S.Half, -2), Interval(1, Rational(-1, 2) + sqrt(17)/2), Interval(2, 4)) assert not_empty_in(FiniteSet(x/(x - 1)).intersect(S.Reals), x) == \ Complement(S.Reals, FiniteSet(1)) assert not_empty_in(FiniteSet(a/(a - 1)).intersect(S.Reals), a) == \ Complement(S.Reals, FiniteSet(1)) assert not_empty_in(FiniteSet((x**2 - 3*x + 2)/(x - 1)).intersect(S.Reals), x) == \ Complement(S.Reals, FiniteSet(1)) assert not_empty_in(FiniteSet(3, 4, x/(x - 1)).intersect(Interval(2, 3)), x) == \ Interval(-oo, oo) assert not_empty_in(FiniteSet(4, x/(x - 1)).intersect(Interval(2, 3)), x) == \ Interval(S(3)/2, 2) assert not_empty_in(FiniteSet(x/(x**2 - 1)).intersect(S.Reals), x) == \ Complement(S.Reals, FiniteSet(-1, 1)) assert not_empty_in(FiniteSet(x, x**2).intersect(Union(Interval(1, 3, True, True), Interval(4, 5))), x) == \ Union(Interval(-sqrt(5), -2), Interval(-sqrt(3), -1, True, True), Interval(1, 3, True, True), Interval(4, 5)) assert not_empty_in(FiniteSet(1).intersect(Interval(3, 4)), x) == S.EmptySet assert not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x) == \ Union(Interval(-2, -1, True, False), Interval(2, oo)) raises(ValueError, lambda: not_empty_in(x)) raises(ValueError, lambda: not_empty_in(Interval(0, 1), x)) raises(NotImplementedError, lambda: not_empty_in(FiniteSet(x).intersect(S.Reals), x, a)) @_both_exp_pow def test_periodicity(): x = Symbol('x') y = Symbol('y') z = Symbol('z', real=True) assert periodicity(sin(2*x), x) == pi assert periodicity((-2)*tan(4*x), x) == pi/4 assert periodicity(sin(x)**2, x) == 2*pi assert periodicity(3**tan(3*x), x) == pi/3 assert periodicity(tan(x)*cos(x), x) == 2*pi assert periodicity(sin(x)**(tan(x)), x) == 2*pi assert periodicity(tan(x)*sec(x), x) == 2*pi assert periodicity(sin(2*x)*cos(2*x) - y, x) == pi/2 assert periodicity(tan(x) + cot(x), x) == pi assert periodicity(sin(x) - cos(2*x), x) == 2*pi assert periodicity(sin(x) - 1, x) == 2*pi assert periodicity(sin(4*x) + sin(x)*cos(x), x) == pi assert periodicity(exp(sin(x)), x) == 2*pi assert periodicity(log(cot(2*x)) - sin(cos(2*x)), x) == pi assert periodicity(sin(2*x)*exp(tan(x) - csc(2*x)), x) == pi assert periodicity(cos(sec(x) - csc(2*x)), x) == 2*pi assert periodicity(tan(sin(2*x)), x) == pi assert periodicity(2*tan(x)**2, x) == pi assert periodicity(sin(x%4), x) == 4 assert periodicity(sin(x)%4, x) == 2*pi assert periodicity(tan((3*x-2)%4), x) == Rational(4, 3) assert periodicity((sqrt(2)*(x+1)+x) % 3, x) == 3 / (sqrt(2)+1) assert periodicity((x**2+1) % x, x) is None assert periodicity(sin(re(x)), x) == 2*pi assert periodicity(sin(x)**2 + cos(x)**2, x) is S.Zero assert periodicity(tan(x), y) is S.Zero assert periodicity(sin(x) + I*cos(x), x) == 2*pi assert periodicity(x - sin(2*y), y) == pi assert periodicity(exp(x), x) is None assert periodicity(exp(I*x), x) == 2*pi assert periodicity(exp(I*z), z) == 2*pi assert periodicity(exp(z), z) is None assert periodicity(exp(log(sin(z) + I*cos(2*z)), evaluate=False), z) == 2*pi assert periodicity(exp(log(sin(2*z) + I*cos(z)), evaluate=False), z) == 2*pi assert periodicity(exp(sin(z)), z) == 2*pi assert periodicity(exp(2*I*z), z) == pi assert periodicity(exp(z + I*sin(z)), z) is None assert periodicity(exp(cos(z/2) + sin(z)), z) == 4*pi assert periodicity(log(x), x) is None assert periodicity(exp(x)**sin(x), x) is None assert periodicity(sin(x)**y, y) is None assert periodicity(Abs(sin(Abs(sin(x)))), x) == pi assert all(periodicity(Abs(f(x)), x) == pi for f in ( cos, sin, sec, csc, tan, cot)) assert periodicity(Abs(sin(tan(x))), x) == pi assert periodicity(Abs(sin(sin(x) + tan(x))), x) == 2*pi assert periodicity(sin(x) > S.Half, x) == 2*pi assert periodicity(x > 2, x) is None assert periodicity(x**3 - x**2 + 1, x) is None assert periodicity(Abs(x), x) is None assert periodicity(Abs(x**2 - 1), x) is None assert periodicity((x**2 + 4)%2, x) is None assert periodicity((E**x)%3, x) is None assert periodicity(sin(expint(1, x))/expint(1, x), x) is None # returning `None` for any Piecewise p = Piecewise((0, x < -1), (x**2, x <= 1), (log(x), True)) assert periodicity(p, x) is None m = MatrixSymbol('m', 3, 3) raises(NotImplementedError, lambda: periodicity(sin(m), m)) raises(NotImplementedError, lambda: periodicity(sin(m[0, 0]), m)) raises(NotImplementedError, lambda: periodicity(sin(m), m[0, 0])) raises(NotImplementedError, lambda: periodicity(sin(m[0, 0]), m[0, 0])) def test_periodicity_check(): x = Symbol('x') y = Symbol('y') assert periodicity(tan(x), x, check=True) == pi assert periodicity(sin(x) + cos(x), x, check=True) == 2*pi assert periodicity(sec(x), x) == 2*pi assert periodicity(sin(x*y), x) == 2*pi/abs(y) assert periodicity(Abs(sec(sec(x))), x) == pi def test_lcim(): assert lcim([S.Half, S(2), S(3)]) == 6 assert lcim([pi/2, pi/4, pi]) == pi assert lcim([2*pi, pi/2]) == 2*pi assert lcim([S.One, 2*pi]) is None assert lcim([S(2) + 2*E, E/3 + Rational(1, 3), S.One + E]) == S(2) + 2*E def test_is_convex(): assert is_convex(1/x, x, domain=Interval(0, oo)) == True assert is_convex(1/x, x, domain=Interval(-oo, 0)) == False assert is_convex(x**2, x, domain=Interval(0, oo)) == True assert is_convex(log(x), x) == False raises(NotImplementedError, lambda: is_convex(log(x), x, a)) def test_stationary_points(): x, y = symbols('x y') assert stationary_points(sin(x), x, Interval(-pi/2, pi/2) ) == {-pi/2, pi/2} assert stationary_points(sin(x), x, Interval.Ropen(0, pi/4) ) is S.EmptySet assert stationary_points(tan(x), x, ) is S.EmptySet assert stationary_points(sin(x)*cos(x), x, Interval(0, pi) ) == {pi/4, pi*Rational(3, 4)} assert stationary_points(sec(x), x, Interval(0, pi) ) == {0, pi} assert stationary_points((x+3)*(x-2), x ) == FiniteSet(Rational(-1, 2)) assert stationary_points((x + 3)/(x - 2), x, Interval(-5, 5) ) is S.EmptySet assert stationary_points((x**2+3)/(x-2), x ) == {2 - sqrt(7), 2 + sqrt(7)} assert stationary_points((x**2+3)/(x-2), x, Interval(0, 5) ) == {2 + sqrt(7)} assert stationary_points(x**4 + x**3 - 5*x**2, x, S.Reals ) == FiniteSet(-2, 0, Rational(5, 4)) assert stationary_points(exp(x), x ) is S.EmptySet assert stationary_points(log(x) - x, x, S.Reals ) == {1} assert stationary_points(cos(x), x, Union(Interval(0, 5), Interval(-6, -3)) ) == {0, -pi, pi} assert stationary_points(y, x, S.Reals ) == S.Reals assert stationary_points(y, x, S.EmptySet) == S.EmptySet def test_maximum(): x, y = symbols('x y') assert maximum(sin(x), x) is S.One assert maximum(sin(x), x, Interval(0, 1)) == sin(1) assert maximum(tan(x), x) is oo assert maximum(tan(x), x, Interval(-pi/4, pi/4)) is S.One assert maximum(sin(x)*cos(x), x, S.Reals) == S.Half assert simplify(maximum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8))) ) == sqrt(2)/4 assert maximum((x+3)*(x-2), x) is oo assert maximum((x+3)*(x-2), x, Interval(-5, 0)) == S(14) assert maximum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(2, 7) assert simplify(maximum(-x**4-x**3+x**2+10, x) ) == 41*sqrt(41)/512 + Rational(5419, 512) assert maximum(exp(x), x, Interval(-oo, 2)) == exp(2) assert maximum(log(x) - x, x, S.Reals) is S.NegativeOne assert maximum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3)) ) is S.One assert maximum(cos(x)-sin(x), x, S.Reals) == sqrt(2) assert maximum(y, x, S.Reals) == y assert maximum(abs(a**3 + a), a, Interval(0, 2)) == 10 assert maximum(abs(60*a**3 + 24*a), a, Interval(0, 2)) == 528 assert maximum(abs(12*a*(5*a**2 + 2)), a, Interval(0, 2)) == 528 assert maximum(x/sqrt(x**2+1), x, S.Reals) == 1 raises(ValueError, lambda : maximum(sin(x), x, S.EmptySet)) raises(ValueError, lambda : maximum(log(cos(x)), x, S.EmptySet)) raises(ValueError, lambda : maximum(1/(x**2 + y**2 + 1), x, S.EmptySet)) raises(ValueError, lambda : maximum(sin(x), sin(x))) raises(ValueError, lambda : maximum(sin(x), x*y, S.EmptySet)) raises(ValueError, lambda : maximum(sin(x), S.One)) def test_minimum(): x, y = symbols('x y') assert minimum(sin(x), x) is S.NegativeOne assert minimum(sin(x), x, Interval(1, 4)) == sin(4) assert minimum(tan(x), x) is -oo assert minimum(tan(x), x, Interval(-pi/4, pi/4)) is S.NegativeOne assert minimum(sin(x)*cos(x), x, S.Reals) == Rational(-1, 2) assert simplify(minimum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8))) ) == -sqrt(2)/4 assert minimum((x+3)*(x-2), x) == Rational(-25, 4) assert minimum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(-3, 2) assert minimum(x**4-x**3+x**2+10, x) == S(10) assert minimum(exp(x), x, Interval(-2, oo)) == exp(-2) assert minimum(log(x) - x, x, S.Reals) is -oo assert minimum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3)) ) is S.NegativeOne assert minimum(cos(x)-sin(x), x, S.Reals) == -sqrt(2) assert minimum(y, x, S.Reals) == y assert minimum(x/sqrt(x**2+1), x, S.Reals) == -1 raises(ValueError, lambda : minimum(sin(x), x, S.EmptySet)) raises(ValueError, lambda : minimum(log(cos(x)), x, S.EmptySet)) raises(ValueError, lambda : minimum(1/(x**2 + y**2 + 1), x, S.EmptySet)) raises(ValueError, lambda : minimum(sin(x), sin(x))) raises(ValueError, lambda : minimum(sin(x), x*y, S.EmptySet)) raises(ValueError, lambda : minimum(sin(x), S.One)) def test_issue_19869(): t = symbols('t') assert (maximum(sqrt(3)*(t - 1)/(3*sqrt(t**2 + 1)), t) ) == sqrt(3)/3 def test_issue_16469(): x = Symbol("x", real=True) f = abs(x) assert function_range(f, x, S.Reals) == Interval(0, oo, False, True) @_both_exp_pow def test_issue_18747(): assert periodicity(exp(pi*I*(x/4+S.Half/2)), x) == 8
6bf472da7297e566e149ed419369345baf9558ea554e0d059c0f6ef2b352215e
from sympy.core.numbers import (E, Rational, oo, pi, zoo) from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt) from sympy.functions.elementary.trigonometric import (cos, sin, tan) from sympy.calculus.accumulationbounds import AccumBounds from sympy.core import Add, Mul, Pow from sympy.core.expr import unchanged from sympy.testing.pytest import raises, XFAIL from sympy.abc import x a = Symbol('a', real=True) B = AccumBounds def test_AccumBounds(): assert B(1, 2).args == (1, 2) assert B(1, 2).delta is S.One assert B(1, 2).mid == Rational(3, 2) assert B(1, 3).is_real == True assert B(1, 1) is S.One assert B(1, 2) + 1 == B(2, 3) assert 1 + B(1, 2) == B(2, 3) assert B(1, 2) + B(2, 3) == B(3, 5) assert -B(1, 2) == B(-2, -1) assert B(1, 2) - 1 == B(0, 1) assert 1 - B(1, 2) == B(-1, 0) assert B(2, 3) - B(1, 2) == B(0, 2) assert x + B(1, 2) == Add(B(1, 2), x) assert a + B(1, 2) == B(1 + a, 2 + a) assert B(1, 2) - x == Add(B(1, 2), -x) assert B(-oo, 1) + oo == B(-oo, oo) assert B(1, oo) + oo is oo assert B(1, oo) - oo == B(-oo, oo) assert (-oo - B(-1, oo)) is -oo assert B(-oo, 1) - oo is -oo assert B(1, oo) - oo == B(-oo, oo) assert B(-oo, 1) - (-oo) == B(-oo, oo) assert (oo - B(1, oo)) == B(-oo, oo) assert (-oo - B(1, oo)) is -oo assert B(1, 2)/2 == B(S.Half, 1) assert 2/B(2, 3) == B(Rational(2, 3), 1) assert 1/B(-1, 1) == B(-oo, oo) assert abs(B(1, 2)) == B(1, 2) assert abs(B(-2, -1)) == B(1, 2) assert abs(B(-2, 1)) == B(0, 2) assert abs(B(-1, 2)) == B(0, 2) c = Symbol('c') raises(ValueError, lambda: B(0, c)) raises(ValueError, lambda: B(1, -1)) r = Symbol('r', real=True) raises(ValueError, lambda: B(r, r - 1)) def test_AccumBounds_mul(): assert B(1, 2)*2 == B(2, 4) assert 2*B(1, 2) == B(2, 4) assert B(1, 2)*B(2, 3) == B(2, 6) assert B(0, 2)*B(2, oo) == B(0, oo) l, r = B(-oo, oo), B(-a, a) assert l*r == B(-oo, oo) assert r*l == B(-oo, oo) l, r = B(1, oo), B(-3, -2) assert l*r == B(-oo, -2) assert r*l == B(-oo, -2) assert B(1, 2)*0 == 0 assert B(1, oo)*0 == B(0, oo) assert B(-oo, 1)*0 == B(-oo, 0) assert B(-oo, oo)*0 == B(-oo, oo) assert B(1, 2)*x == Mul(B(1, 2), x, evaluate=False) assert B(0, 2)*oo == B(0, oo) assert B(-2, 0)*oo == B(-oo, 0) assert B(0, 2)*(-oo) == B(-oo, 0) assert B(-2, 0)*(-oo) == B(0, oo) assert B(-1, 1)*oo == B(-oo, oo) assert B(-1, 1)*(-oo) == B(-oo, oo) assert B(-oo, oo)*oo == B(-oo, oo) def test_AccumBounds_div(): assert B(-1, 3)/B(3, 4) == B(Rational(-1, 3), 1) assert B(-2, 4)/B(-3, 4) == B(-oo, oo) assert B(-3, -2)/B(-4, 0) == B(S.Half, oo) # these two tests can have a better answer # after Union of B is improved assert B(-3, -2)/B(-2, 1) == B(-oo, oo) assert B(2, 3)/B(-2, 2) == B(-oo, oo) assert B(-3, -2)/B(0, 4) == B(-oo, Rational(-1, 2)) assert B(2, 4)/B(-3, 0) == B(-oo, Rational(-2, 3)) assert B(2, 4)/B(0, 3) == B(Rational(2, 3), oo) assert B(0, 1)/B(0, 1) == B(0, oo) assert B(-1, 0)/B(0, 1) == B(-oo, 0) assert B(-1, 2)/B(-2, 2) == B(-oo, oo) assert 1/B(-1, 2) == B(-oo, oo) assert 1/B(0, 2) == B(S.Half, oo) assert (-1)/B(0, 2) == B(-oo, Rational(-1, 2)) assert 1/B(-oo, 0) == B(-oo, 0) assert 1/B(-1, 0) == B(-oo, -1) assert (-2)/B(-oo, 0) == B(0, oo) assert 1/B(-oo, -1) == B(-1, 0) assert B(1, 2)/a == Mul(B(1, 2), 1/a, evaluate=False) assert B(1, 2)/0 == B(1, 2)*zoo assert B(1, oo)/oo == B(0, oo) assert B(1, oo)/(-oo) == B(-oo, 0) assert B(-oo, -1)/oo == B(-oo, 0) assert B(-oo, -1)/(-oo) == B(0, oo) assert B(-oo, oo)/oo == B(-oo, oo) assert B(-oo, oo)/(-oo) == B(-oo, oo) assert B(-1, oo)/oo == B(0, oo) assert B(-1, oo)/(-oo) == B(-oo, 0) assert B(-oo, 1)/oo == B(-oo, 0) assert B(-oo, 1)/(-oo) == B(0, oo) def test_issue_18795(): r = Symbol('r', real=True) a = B(-1,1) c = B(7, oo) b = B(-oo, oo) assert c - tan(r) == B(7-tan(r), oo) assert b + tan(r) == B(-oo, oo) assert (a + r)/a == B(-oo, oo)*B(r - 1, r + 1) assert (b + a)/a == B(-oo, oo) def test_AccumBounds_func(): assert (x**2 + 2*x + 1).subs(x, B(-1, 1)) == B(-1, 4) assert exp(B(0, 1)) == B(1, E) assert exp(B(-oo, oo)) == B(0, oo) assert log(B(3, 6)) == B(log(3), log(6)) @XFAIL def test_AccumBounds_powf(): nn = Symbol('nn', nonnegative=True) assert B(1 + nn, 2 + nn)**B(1, 2) == B(1 + nn, (2 + nn)**2) i = Symbol('i', integer=True, negative=True) assert B(1, 2)**i == B(2**i, 1) def test_AccumBounds_pow(): assert B(0, 2)**2 == B(0, 4) assert B(-1, 1)**2 == B(0, 1) assert B(1, 2)**2 == B(1, 4) assert B(-1, 2)**3 == B(-1, 8) assert B(-1, 1)**0 == 1 assert B(1, 2)**Rational(5, 2) == B(1, 4*sqrt(2)) assert B(0, 2)**S.Half == B(0, sqrt(2)) neg = Symbol('neg', negative=True) assert unchanged(Pow, B(neg, 1), S.Half) nn = Symbol('nn', nonnegative=True) assert B(nn, nn + 1)**S.Half == B(sqrt(nn), sqrt(nn + 1)) assert B(nn, nn + 1)**nn == B(nn**nn, (nn + 1)**nn) assert unchanged(Pow, B(nn, nn + 1), x) i = Symbol('i', integer=True) assert B(1, 2)**i == B(Min(1, 2**i), Max(1, 2**i)) i = Symbol('i', integer=True, nonnegative=True) assert B(1, 2)**i == B(1, 2**i) assert B(0, 1)**i == B(0**i, 1) assert B(1, 5)**(-2) == B(Rational(1, 25), 1) assert B(-1, 3)**(-2) == B(0, oo) assert B(0, 2)**(-3) == B(Rational(1, 8), oo) assert B(-2, 0)**(-3) == B(-oo, -Rational(1, 8)) assert B(0, 2)**(-2) == B(Rational(1, 4), oo) assert B(-1, 2)**(-3) == B(-oo, oo) assert B(-3, -2)**(-3) == B(Rational(-1, 8), Rational(-1, 27)) assert B(-3, -2)**(-2) == B(Rational(1, 9), Rational(1, 4)) assert B(0, oo)**S.Half == B(0, oo) assert B(-oo, 0)**(-2) == B(0, oo) assert B(-2, 0)**(-2) == B(Rational(1, 4), oo) assert B(Rational(1, 3), S.Half)**oo is S.Zero assert B(0, S.Half)**oo is S.Zero assert B(S.Half, 1)**oo == B(0, oo) assert B(0, 1)**oo == B(0, oo) assert B(2, 3)**oo is oo assert B(1, 2)**oo == B(0, oo) assert B(S.Half, 3)**oo == B(0, oo) assert B(Rational(-1, 3), Rational(-1, 4))**oo is S.Zero assert B(-1, Rational(-1, 2))**oo is S.NaN assert B(-3, -2)**oo is zoo assert B(-2, -1)**oo is S.NaN assert B(-2, Rational(-1, 2))**oo is S.NaN assert B(Rational(-1, 2), S.Half)**oo is S.Zero assert B(Rational(-1, 2), 1)**oo == B(0, oo) assert B(Rational(-2, 3), 2)**oo == B(0, oo) assert B(-1, 1)**oo == B(-oo, oo) assert B(-1, S.Half)**oo == B(-oo, oo) assert B(-1, 2)**oo == B(-oo, oo) assert B(-2, S.Half)**oo == B(-oo, oo) assert B(1, 2)**x == Pow(B(1, 2), x, evaluate=False) assert B(2, 3)**(-oo) is S.Zero assert B(0, 2)**(-oo) == B(0, oo) assert B(-1, 2)**(-oo) == B(-oo, oo) assert (tan(x)**sin(2*x)).subs(x, B(0, pi/2)) == \ Pow(B(-oo, oo), B(0, 1)) def test_AccumBounds_exponent(): # base is 0 z = 0**B(a, a + S.Half) assert z.subs(a, 0) == B(0, 1) assert z.subs(a, 1) == 0 p = z.subs(a, -1) assert p.is_Pow and p.args == (0, B(-1, -S.Half)) # base > 0 # when base is 1 the type of bounds does not matter assert 1**B(a, a + 1) == 1 # otherwise we need to know if 0 is in the bounds assert S.Half**B(-2, 2) == B(S(1)/4, 4) assert 2**B(-2, 2) == B(S(1)/4, 4) # +eps may introduce +oo # if there is a negative integer exponent assert B(0, 1)**B(S(1)/2, 1) == B(0, 1) assert B(0, 1)**B(0, 1) == B(0, 1) # positive bases have positive bounds assert B(2, 3)**B(-3, -2) == B(S(1)/27, S(1)/4) assert B(2, 3)**B(-3, 2) == B(S(1)/27, 9) # bounds generating imaginary parts unevaluated assert unchanged(Pow, B(-1, 1), B(1, 2)) assert B(0, S(1)/2)**B(1, oo) == B(0, S(1)/2) assert B(0, 1)**B(1, oo) == B(0, oo) assert B(0, 2)**B(1, oo) == B(0, oo) assert B(0, oo)**B(1, oo) == B(0, oo) assert B(S(1)/2, 1)**B(1, oo) == B(0, oo) assert B(S(1)/2, 1)**B(-oo, -1) == B(0, oo) assert B(S(1)/2, 1)**B(-oo, oo) == B(0, oo) assert B(S(1)/2, 2)**B(1, oo) == B(0, oo) assert B(S(1)/2, 2)**B(-oo, -1) == B(0, oo) assert B(S(1)/2, 2)**B(-oo, oo) == B(0, oo) assert B(S(1)/2, oo)**B(1, oo) == B(0, oo) assert B(S(1)/2, oo)**B(-oo, -1) == B(0, oo) assert B(S(1)/2, oo)**B(-oo, oo) == B(0, oo) assert B(1, 2)**B(1, oo) == B(0, oo) assert B(1, 2)**B(-oo, -1) == B(0, oo) assert B(1, 2)**B(-oo, oo) == B(0, oo) assert B(1, oo)**B(1, oo) == B(0, oo) assert B(1, oo)**B(-oo, -1) == B(0, oo) assert B(1, oo)**B(-oo, oo) == B(0, oo) assert B(2, oo)**B(1, oo) == B(2, oo) assert B(2, oo)**B(-oo, -1) == B(0, S(1)/2) assert B(2, oo)**B(-oo, oo) == B(0, oo) def test_comparison_AccumBounds(): assert (B(1, 3) < 4) == S.true assert (B(1, 3) < -1) == S.false assert (B(1, 3) < 2).rel_op == '<' assert (B(1, 3) <= 2).rel_op == '<=' assert (B(1, 3) > 4) == S.false assert (B(1, 3) > -1) == S.true assert (B(1, 3) > 2).rel_op == '>' assert (B(1, 3) >= 2).rel_op == '>=' assert (B(1, 3) < B(4, 6)) == S.true assert (B(1, 3) < B(2, 4)).rel_op == '<' assert (B(1, 3) < B(-2, 0)) == S.false assert (B(1, 3) <= B(4, 6)) == S.true assert (B(1, 3) <= B(-2, 0)) == S.false assert (B(1, 3) > B(4, 6)) == S.false assert (B(1, 3) > B(-2, 0)) == S.true assert (B(1, 3) >= B(4, 6)) == S.false assert (B(1, 3) >= B(-2, 0)) == S.true # issue 13499 assert (cos(x) > 0).subs(x, oo) == (B(-1, 1) > 0) c = Symbol('c') raises(TypeError, lambda: (B(0, 1) < c)) raises(TypeError, lambda: (B(0, 1) <= c)) raises(TypeError, lambda: (B(0, 1) > c)) raises(TypeError, lambda: (B(0, 1) >= c)) def test_contains_AccumBounds(): assert (1 in B(1, 2)) == S.true raises(TypeError, lambda: a in B(1, 2)) assert 0 in B(-1, 0) raises(TypeError, lambda: (cos(1)**2 + sin(1)**2 - 1) in B(-1, 0)) assert (-oo in B(1, oo)) == S.true assert (oo in B(-oo, 0)) == S.true # issue 13159 assert Mul(0, B(-1, 1)) == Mul(B(-1, 1), 0) == 0 import itertools for perm in itertools.permutations([0, B(-1, 1), x]): assert Mul(*perm) == 0 def test_intersection_AccumBounds(): assert B(0, 3).intersection(B(1, 2)) == B(1, 2) assert B(0, 3).intersection(B(1, 4)) == B(1, 3) assert B(0, 3).intersection(B(-1, 2)) == B(0, 2) assert B(0, 3).intersection(B(-1, 4)) == B(0, 3) assert B(0, 1).intersection(B(2, 3)) == S.EmptySet raises(TypeError, lambda: B(0, 3).intersection(1)) def test_union_AccumBounds(): assert B(0, 3).union(B(1, 2)) == B(0, 3) assert B(0, 3).union(B(1, 4)) == B(0, 4) assert B(0, 3).union(B(-1, 2)) == B(-1, 3) assert B(0, 3).union(B(-1, 4)) == B(-1, 4) raises(TypeError, lambda: B(0, 3).union(1))
449fdacd15710b27dd4276927b3679d1fffe73c03ab854b96ec7f34fb9d44446
from sympy.core.singleton import S from sympy.strategies.rl import (rm_id, glom, flatten, unpack, sort, distribute, subs, rebuild) from sympy.core.basic import Basic def test_rm_id(): rmzeros = rm_id(lambda x: x == 0) assert rmzeros(Basic(S(0), S(1))) == Basic(S(1)) assert rmzeros(Basic(S(0), S(0))) == Basic(S(0)) assert rmzeros(Basic(S(2), S(1))) == Basic(S(2), S(1)) def test_glom(): from sympy.core.add import Add from sympy.abc import x key = lambda x: x.as_coeff_Mul()[1] count = lambda x: x.as_coeff_Mul()[0] newargs = lambda cnt, arg: cnt * arg rl = glom(key, count, newargs) result = rl(Add(x, -x, 3*x, 2, 3, evaluate=False)) expected = Add(3*x, 5) assert set(result.args) == set(expected.args) def test_flatten(): assert flatten(Basic(S(1), S(2), Basic(S(3), S(4)))) == \ Basic(S(1), S(2), S(3), S(4)) def test_unpack(): assert unpack(Basic(S(2))) == 2 assert unpack(Basic(S(2), S(3))) == Basic(S(2), S(3)) def test_sort(): assert sort(str)(Basic(S(3),S(1),S(2))) == Basic(S(1),S(2),S(3)) def test_distribute(): class T1(Basic): pass class T2(Basic): pass distribute_t12 = distribute(T1, T2) assert distribute_t12(T1(S(1), S(2), T2(S(3), S(4)), S(5))) == \ T2(T1(S(1), S(2), S(3), S(5)), T1(S(1), S(2), S(4), S(5))) assert distribute_t12(T1(S(1), S(2), S(3))) == T1(S(1), S(2), S(3)) def test_distribute_add_mul(): from sympy.core.add import Add from sympy.core.mul import Mul from sympy.core.symbol import symbols x, y = symbols('x, y') expr = Mul(2, Add(x, y), evaluate=False) expected = Add(Mul(2, x), Mul(2, y)) distribute_mul = distribute(Mul, Add) assert distribute_mul(expr) == expected def test_subs(): rl = subs(1, 2) assert rl(1) == 2 assert rl(3) == 3 def test_rebuild(): from sympy.core.add import Add expr = Basic.__new__(Add, S(1), S(2)) assert rebuild(expr) == 3
f5b5975f52c9df9ef45cf20fe6e3c7ce1b251d0895f4073b6361fe08a4f0dbe2
from sympy.strategies.tools import subs, typed from sympy.strategies.rl import rm_id from sympy.core.basic import Basic from sympy.core.singleton import S def test_subs(): from sympy.core.symbol import symbols a,b,c,d,e,f = symbols('a,b,c,d,e,f') mapping = {a: d, d: a, Basic(e): Basic(f)} expr = Basic(a, Basic(b, c), Basic(d, Basic(e))) result = Basic(d, Basic(b, c), Basic(a, Basic(f))) assert subs(mapping)(expr) == result def test_subs_empty(): assert subs({})(Basic(S(1), S(2))) == Basic(S(1), S(2)) def test_typed(): class A(Basic): pass class B(Basic): pass rmzeros = rm_id(lambda x: x == S(0)) rmones = rm_id(lambda x: x == S(1)) remove_something = typed({A: rmzeros, B: rmones}) assert remove_something(A(S(0), S(1))) == A(S(1)) assert remove_something(B(S(0), S(1))) == B(S(0))
adb61a79da1456ad3143a93fa488128aebd65063d119c2c69c37ed4c4b450374
from sympy.strategies.traverse import (top_down, bottom_up, sall, top_down_once, bottom_up_once, basic_fns) from sympy.strategies.rl import rebuild from sympy.strategies.util import expr_fns from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.numbers import Integer from sympy.core.singleton import S from sympy.core.symbol import Str, Symbol from sympy.abc import x, y, z def zero_symbols(expression): return S.Zero if isinstance(expression, Symbol) else expression def test_sall(): zero_onelevel = sall(zero_symbols) assert zero_onelevel(Basic(x, y, Basic(x, z))) == Basic(S(0), S(0), Basic(x, z)) def test_bottom_up(): _test_global_traversal(bottom_up) _test_stop_on_non_basics(bottom_up) def test_top_down(): _test_global_traversal(top_down) _test_stop_on_non_basics(top_down) def _test_global_traversal(trav): zero_all_symbols = trav(zero_symbols) assert zero_all_symbols(Basic(x, y, Basic(x, z))) == \ Basic(S(0), S(0), Basic(S(0), S(0))) def _test_stop_on_non_basics(trav): def add_one_if_can(expr): try: return expr + 1 except TypeError: return expr expr = Basic(S(1), Str('a'), Basic(S(2), Str('b'))) expected = Basic(S(2), Str('a'), Basic(S(3), Str('b'))) rl = trav(add_one_if_can) assert rl(expr) == expected class Basic2(Basic): pass rl = lambda x: Basic2(*x.args) if x.args and not isinstance(x.args[0], Integer) else x def test_top_down_once(): top_rl = top_down_once(rl) assert top_rl(Basic(S(1.0), S(2.0), Basic(S(3), S(4)))) == Basic2(S(1.0), S(2.0), Basic(S(3), S(4))) def test_bottom_up_once(): bottom_rl = bottom_up_once(rl) assert bottom_rl(Basic(S(1), S(2), Basic(S(3.0), S(4.0)))) == Basic(S(1), S(2), Basic2(S(3.0), S(4.0))) def test_expr_fns(): expr = x + y**3 e = bottom_up(lambda v: v + 1, expr_fns)(expr) b = bottom_up(lambda v: Basic.__new__(Add, v, S(1)), basic_fns)(expr) assert rebuild(b) == e
f65d3bedb0246369b6107e19ad1f928f23b517ad0cf1d55c3fa7f23eb087b855
from sympy.strategies.branch.tools import canon from sympy.core.basic import Basic from sympy.core.numbers import Integer from sympy.core.singleton import S def posdec(x): if isinstance(x, Integer) and x > 0: yield x-1 else: yield x def branch5(x): if isinstance(x, Integer): if 0 < x < 5: yield x-1 elif 5 < x < 10: yield x+1 elif x == 5: yield x+1 yield x-1 else: yield x def test_zero_ints(): expr = Basic(S(2), Basic(S(5), S(3)), S(8)) expected = {Basic(S(0), Basic(S(0), S(0)), S(0))} brl = canon(posdec) assert set(brl(expr)) == expected def test_split5(): expr = Basic(S(2), Basic(S(5), S(3)), S(8)) expected = {Basic(S(0), Basic(S(0), S(0)), S(10)), Basic(S(0), Basic(S(10), S(0)), S(10))} brl = canon(branch5) assert set(brl(expr)) == expected
289ae32a94573312d8b5c1061a3545a0343bbcb4b7786f0e203aa8f3fe18155e
from sympy.core.basic import Basic from sympy.core.numbers import Integer from sympy.core.singleton import S from sympy.strategies.branch.traverse import top_down, sall from sympy.strategies.branch.core import do_one, identity def inc(x): if isinstance(x, Integer): yield x + 1 def test_top_down_easy(): expr = Basic(S(1), S(2)) expected = Basic(S(2), S(3)) brl = top_down(inc) assert set(brl(expr)) == {expected} def test_top_down_big_tree(): expr = Basic(S(1), Basic(S(2)), Basic(S(3), Basic(S(4)), S(5))) expected = Basic(S(2), Basic(S(3)), Basic(S(4), Basic(S(5)), S(6))) brl = top_down(inc) assert set(brl(expr)) == {expected} def test_top_down_harder_function(): def split5(x): if x == 5: yield x - 1 yield x + 1 expr = Basic(Basic(S(5), S(6)), S(1)) expected = {Basic(Basic(S(4), S(6)), S(1)), Basic(Basic(S(6), S(6)), S(1))} brl = top_down(split5) assert set(brl(expr)) == expected def test_sall(): expr = Basic(S(1), S(2)) expected = Basic(S(2), S(3)) brl = sall(inc) assert list(brl(expr)) == [expected] expr = Basic(S(1), S(2), Basic(S(3), S(4))) expected = Basic(S(2), S(3), Basic(S(3), S(4))) brl = sall(do_one(inc, identity)) assert list(brl(expr)) == [expected]
10f2ec85cb48fbbdb344e77d05c9635f9d1addcb6811c3ed867cbf30a5b66b6b
from textwrap import dedent import sys from subprocess import Popen, PIPE import os from sympy.core.singleton import S from sympy.testing.pytest import raises from sympy.utilities.misc import translate, replace, ordinal, rawlines, strlines, as_int def test_translate(): abc = 'abc' assert translate(abc, None, 'a') == 'bc' assert translate(abc, None, '') == 'abc' assert translate(abc, {'a': 'x'}, 'c') == 'xb' assert translate(abc, {'a': 'bc'}, 'c') == 'bcb' assert translate(abc, {'ab': 'x'}, 'c') == 'x' assert translate(abc, {'ab': ''}, 'c') == '' assert translate(abc, {'bc': 'x'}, 'c') == 'ab' assert translate(abc, {'abc': 'x', 'a': 'y'}) == 'x' u = chr(4096) assert translate(abc, 'a', 'x', u) == 'xbc' assert (u in translate(abc, 'a', u, u)) is True def test_replace(): assert replace('abc', ('a', 'b')) == 'bbc' assert replace('abc', {'a': 'Aa'}) == 'Aabc' assert replace('abc', ('a', 'b'), ('c', 'C')) == 'bbC' def test_ordinal(): assert ordinal(-1) == '-1st' assert ordinal(0) == '0th' assert ordinal(1) == '1st' assert ordinal(2) == '2nd' assert ordinal(3) == '3rd' assert all(ordinal(i).endswith('th') for i in range(4, 21)) assert ordinal(100) == '100th' assert ordinal(101) == '101st' assert ordinal(102) == '102nd' assert ordinal(103) == '103rd' assert ordinal(104) == '104th' assert ordinal(200) == '200th' assert all(ordinal(i) == str(i) + 'th' for i in range(-220, -203)) def test_rawlines(): assert rawlines('a a\na') == "dedent('''\\\n a a\n a''')" assert rawlines('a a') == "'a a'" assert rawlines(strlines('\\le"ft')) == ( '(\n' " '(\\n'\n" ' \'r\\\'\\\\le"ft\\\'\\n\'\n' " ')'\n" ')') def test_strlines(): q = 'this quote (") is in the middle' # the following assert rhs was prepared with # print(rawlines(strlines(q, 10))) assert strlines(q, 10) == dedent('''\ ( 'this quo' 'te (") i' 's in the' ' middle' )''') assert q == ( 'this quo' 'te (") i' 's in the' ' middle' ) q = "this quote (') is in the middle" assert strlines(q, 20) == dedent('''\ ( "this quote (') is " "in the middle" )''') assert strlines('\\left') == ( '(\n' "r'\\left'\n" ')') assert strlines('\\left', short=True) == r"r'\left'" assert strlines('\\le"ft') == ( '(\n' 'r\'\\le"ft\'\n' ')') q = 'this\nother line' assert strlines(q) == rawlines(q) def test_translate_args(): try: translate(None, None, None, 'not_none') except ValueError: pass # Exception raised successfully else: assert False assert translate('s', None, None, None) == 's' try: translate('s', 'a', 'bc') except ValueError: pass # Exception raised successfully else: assert False def test_debug_output(): env = os.environ.copy() env['SYMPY_DEBUG'] = 'True' cmd = 'from sympy import *; x = Symbol("x"); print(integrate((1-cos(x))/x, x))' cmdline = [sys.executable, '-c', cmd] proc = Popen(cmdline, env=env, stdout=PIPE, stderr=PIPE) out, err = proc.communicate() out = out.decode('ascii') # utf-8? err = err.decode('ascii') expected = 'substituted: -x*(1 - cos(x)), u: 1/x, u_var: _u' assert expected in err, err def test_as_int(): raises(ValueError, lambda : as_int(True)) raises(ValueError, lambda : as_int(1.1)) raises(ValueError, lambda : as_int([])) raises(ValueError, lambda : as_int(S.NaN)) raises(ValueError, lambda : as_int(S.Infinity)) raises(ValueError, lambda : as_int(S.NegativeInfinity)) raises(ValueError, lambda : as_int(S.ComplexInfinity)) # for the following, limited precision makes int(arg) == arg # but the int value is not necessarily what a user might have # expected; Q.prime is more nuanced in its response for # expressions which might be complex representations of an # integer. This is not -- by design -- as_ints role. raises(ValueError, lambda : as_int(1e23)) raises(ValueError, lambda : as_int(S('1.'+'0'*20+'1'))) assert as_int(True, strict=False) == 1
e80df8d334d3f15dc74955af48851fbfc0650268242602c1b63580ed864647de
""" Tests from Michael Wester's 1999 paper "Review of CAS mathematical capabilities". http://www.math.unm.edu/~wester/cas/book/Wester.pdf See also http://math.unm.edu/~wester/cas_review.html for detailed output of each tested system. """ from sympy.assumptions.ask import Q, ask from sympy.assumptions.refine import refine from sympy.concrete.products import product from sympy.core import EulerGamma from sympy.core.evalf import N from sympy.core.function import (Derivative, Function, Lambda, Subs, diff, expand, expand_func) from sympy.core.mul import Mul from sympy.core.numbers import (AlgebraicNumber, E, I, Rational, igcd, nan, oo, pi, zoo) from sympy.core.relational import Eq, Lt from sympy.core.singleton import S from sympy.core.symbol import Dummy, Symbol, symbols from sympy.functions.combinatorial.factorials import (rf, binomial, factorial, factorial2) from sympy.functions.combinatorial.numbers import bernoulli, fibonacci from sympy.functions.elementary.complexes import (conjugate, im, re, sign) from sympy.functions.elementary.exponential import LambertW, exp, log from sympy.functions.elementary.hyperbolic import (asinh, cosh, sinh, tanh) from sympy.functions.elementary.integers import ceiling, floor from sympy.functions.elementary.miscellaneous import Max, Min, sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (acos, acot, asin, atan, cos, cot, csc, sec, sin, tan) from sympy.functions.special.bessel import besselj from sympy.functions.special.delta_functions import DiracDelta from sympy.functions.special.elliptic_integrals import (elliptic_e, elliptic_f) from sympy.functions.special.gamma_functions import gamma, polygamma from sympy.functions.special.hyper import hyper from sympy.functions.special.polynomials import (assoc_legendre, chebyshevt) from sympy.functions.special.zeta_functions import polylog from sympy.geometry.util import idiff from sympy.logic.boolalg import And from sympy.matrices.dense import hessian, wronskian from sympy.matrices.expressions.matmul import MatMul from sympy.ntheory.continued_fraction import ( continued_fraction_convergents as cf_c, continued_fraction_iterator as cf_i, continued_fraction_periodic as cf_p, continued_fraction_reduce as cf_r) from sympy.ntheory.factor_ import factorint, totient from sympy.ntheory.generate import primerange from sympy.ntheory.partitions_ import npartitions from sympy.polys.domains.integerring import ZZ from sympy.polys.orthopolys import legendre_poly from sympy.polys.partfrac import apart from sympy.polys.polytools import Poly, factor, gcd, resultant from sympy.series.limits import limit from sympy.series.order import O from sympy.series.residues import residue from sympy.series.series import series from sympy.sets.fancysets import ImageSet from sympy.sets.sets import FiniteSet, Intersection, Interval, Union from sympy.simplify.combsimp import combsimp from sympy.simplify.hyperexpand import hyperexpand from sympy.simplify.powsimp import powdenest, powsimp from sympy.simplify.radsimp import radsimp from sympy.simplify.simplify import logcombine, simplify from sympy.simplify.sqrtdenest import sqrtdenest from sympy.simplify.trigsimp import trigsimp from sympy.solvers.solvers import solve import mpmath from sympy.functions.combinatorial.numbers import stirling from sympy.functions.special.delta_functions import Heaviside from sympy.functions.special.error_functions import Ci, Si, erf from sympy.functions.special.zeta_functions import zeta from sympy.testing.pytest import (XFAIL, slow, SKIP, skip, ON_TRAVIS, raises) from sympy.utilities.iterables import partitions from mpmath import mpi, mpc from sympy.matrices import Matrix, GramSchmidt, eye from sympy.matrices.expressions.blockmatrix import BlockMatrix, block_collapse from sympy.matrices.expressions import MatrixSymbol, ZeroMatrix from sympy.physics.quantum import Commutator from sympy.polys.rings import PolyRing from sympy.polys.fields import FracField from sympy.polys.solvers import solve_lin_sys from sympy.concrete import Sum from sympy.concrete.products import Product from sympy.integrals import integrate from sympy.integrals.transforms import laplace_transform,\ inverse_laplace_transform, LaplaceTransform, fourier_transform,\ mellin_transform from sympy.solvers.recurr import rsolve from sympy.solvers.solveset import solveset, solveset_real, linsolve from sympy.solvers.ode import dsolve from sympy.core.relational import Equality from itertools import islice, takewhile from sympy.series.formal import fps from sympy.series.fourier import fourier_series from sympy.calculus.util import minimum EmptySet = S.EmptySet R = Rational x, y, z = symbols('x y z') i, j, k, l, m, n = symbols('i j k l m n', integer=True) f = Function('f') g = Function('g') # A. Boolean Logic and Quantifier Elimination # Not implemented. # B. Set Theory def test_B1(): assert (FiniteSet(i, j, j, k, k, k) | FiniteSet(l, k, j) | FiniteSet(j, m, j)) == FiniteSet(i, j, k, l, m) def test_B2(): assert (FiniteSet(i, j, j, k, k, k) & FiniteSet(l, k, j) & FiniteSet(j, m, j)) == Intersection({j, m}, {i, j, k}, {j, k, l}) # Previous output below. Not sure why that should be the expected output. # There should probably be a way to rewrite Intersections that way but I # don't see why an Intersection should evaluate like that: # # == Union({j}, Intersection({m}, Union({j, k}, Intersection({i}, {l})))) def test_B3(): assert (FiniteSet(i, j, k, l, m) - FiniteSet(j) == FiniteSet(i, k, l, m)) def test_B4(): assert (FiniteSet(*(FiniteSet(i, j)*FiniteSet(k, l))) == FiniteSet((i, k), (i, l), (j, k), (j, l))) # C. Numbers def test_C1(): assert (factorial(50) == 30414093201713378043612608166064768844377641568960512000000000000) def test_C2(): assert (factorint(factorial(50)) == {2: 47, 3: 22, 5: 12, 7: 8, 11: 4, 13: 3, 17: 2, 19: 2, 23: 2, 29: 1, 31: 1, 37: 1, 41: 1, 43: 1, 47: 1}) def test_C3(): assert (factorial2(10), factorial2(9)) == (3840, 945) # Base conversions; not really implemented by SymPy # Whatever. Take credit! def test_C4(): assert 0xABC == 2748 def test_C5(): assert 123 == int('234', 7) def test_C6(): assert int('677', 8) == int('1BF', 16) == 447 def test_C7(): assert log(32768, 8) == 5 def test_C8(): # Modular multiplicative inverse. Would be nice if divmod could do this. assert ZZ.invert(5, 7) == 3 assert ZZ.invert(5, 6) == 5 def test_C9(): assert igcd(igcd(1776, 1554), 5698) == 74 def test_C10(): x = 0 for n in range(2, 11): x += R(1, n) assert x == R(4861, 2520) def test_C11(): assert R(1, 7) == S('0.[142857]') def test_C12(): assert R(7, 11) * R(22, 7) == 2 def test_C13(): test = R(10, 7) * (1 + R(29, 1000)) ** R(1, 3) good = 3 ** R(1, 3) assert test == good def test_C14(): assert sqrtdenest(sqrt(2*sqrt(3) + 4)) == 1 + sqrt(3) def test_C15(): test = sqrtdenest(sqrt(14 + 3*sqrt(3 + 2*sqrt(5 - 12*sqrt(3 - 2*sqrt(2)))))) good = sqrt(2) + 3 assert test == good def test_C16(): test = sqrtdenest(sqrt(10 + 2*sqrt(6) + 2*sqrt(10) + 2*sqrt(15))) good = sqrt(2) + sqrt(3) + sqrt(5) assert test == good def test_C17(): test = radsimp((sqrt(3) + sqrt(2)) / (sqrt(3) - sqrt(2))) good = 5 + 2*sqrt(6) assert test == good def test_C18(): assert simplify((sqrt(-2 + sqrt(-5)) * sqrt(-2 - sqrt(-5))).expand(complex=True)) == 3 @XFAIL def test_C19(): assert radsimp(simplify((90 + 34*sqrt(7)) ** R(1, 3))) == 3 + sqrt(7) def test_C20(): inside = (135 + 78*sqrt(3)) test = AlgebraicNumber((inside**R(2, 3) + 3) * sqrt(3) / inside**R(1, 3)) assert simplify(test) == AlgebraicNumber(12) def test_C21(): assert simplify(AlgebraicNumber((41 + 29*sqrt(2)) ** R(1, 5))) == \ AlgebraicNumber(1 + sqrt(2)) @XFAIL def test_C22(): test = simplify(((6 - 4*sqrt(2))*log(3 - 2*sqrt(2)) + (3 - 2*sqrt(2))*log(17 - 12*sqrt(2)) + 32 - 24*sqrt(2)) / (48*sqrt(2) - 72)) good = sqrt(2)/3 - log(sqrt(2) - 1)/3 assert test == good def test_C23(): assert 2 * oo - 3 is oo @XFAIL def test_C24(): raise NotImplementedError("2**aleph_null == aleph_1") # D. Numerical Analysis def test_D1(): assert 0.0 / sqrt(2) == 0.0 def test_D2(): assert str(exp(-1000000).evalf()) == '3.29683147808856e-434295' def test_D3(): assert exp(pi*sqrt(163)).evalf(50).num.ae(262537412640768744) def test_D4(): assert floor(R(-5, 3)) == -2 assert ceiling(R(-5, 3)) == -1 @XFAIL def test_D5(): raise NotImplementedError("cubic_spline([1, 2, 4, 5], [1, 4, 2, 3], x)(3) == 27/8") @XFAIL def test_D6(): raise NotImplementedError("translate sum(a[i]*x**i, (i,1,n)) to FORTRAN") @XFAIL def test_D7(): raise NotImplementedError("translate sum(a[i]*x**i, (i,1,n)) to C") @XFAIL def test_D8(): # One way is to cheat by converting the sum to a string, # and replacing the '[' and ']' with ''. # E.g., horner(S(str(_).replace('[','').replace(']',''))) raise NotImplementedError("apply Horner's rule to sum(a[i]*x**i, (i,1,5))") @XFAIL def test_D9(): raise NotImplementedError("translate D8 to FORTRAN") @XFAIL def test_D10(): raise NotImplementedError("translate D8 to C") @XFAIL def test_D11(): #Is there a way to use count_ops? raise NotImplementedError("flops(sum(product(f[i][k], (i,1,k)), (k,1,n)))") @XFAIL def test_D12(): assert (mpi(-4, 2) * x + mpi(1, 3)) ** 2 == mpi(-8, 16)*x**2 + mpi(-24, 12)*x + mpi(1, 9) @XFAIL def test_D13(): raise NotImplementedError("discretize a PDE: diff(f(x,t),t) == diff(diff(f(x,t),x),x)") # E. Statistics # See scipy; all of this is numerical. # F. Combinatorial Theory. def test_F1(): assert rf(x, 3) == x*(1 + x)*(2 + x) def test_F2(): assert expand_func(binomial(n, 3)) == n*(n - 1)*(n - 2)/6 @XFAIL def test_F3(): assert combsimp(2**n * factorial(n) * factorial2(2*n - 1)) == factorial(2*n) @XFAIL def test_F4(): assert combsimp(2**n * factorial(n) * product(2*k - 1, (k, 1, n))) == factorial(2*n) @XFAIL def test_F5(): assert gamma(n + R(1, 2)) / sqrt(pi) / factorial(n) == factorial(2*n)/2**(2*n)/factorial(n)**2 def test_F6(): partTest = [p.copy() for p in partitions(4)] partDesired = [{4: 1}, {1: 1, 3: 1}, {2: 2}, {1: 2, 2:1}, {1: 4}] assert partTest == partDesired def test_F7(): assert npartitions(4) == 5 def test_F8(): assert stirling(5, 2, signed=True) == -50 # if signed, then kind=1 def test_F9(): assert totient(1776) == 576 # G. Number Theory def test_G1(): assert list(primerange(999983, 1000004)) == [999983, 1000003] @XFAIL def test_G2(): raise NotImplementedError("find the primitive root of 191 == 19") @XFAIL def test_G3(): raise NotImplementedError("(a+b)**p mod p == a**p + b**p mod p; p prime") # ... G14 Modular equations are not implemented. def test_G15(): assert Rational(sqrt(3).evalf()).limit_denominator(15) == R(26, 15) assert list(takewhile(lambda x: x.q <= 15, cf_c(cf_i(sqrt(3)))))[-1] == \ R(26, 15) def test_G16(): assert list(islice(cf_i(pi),10)) == [3, 7, 15, 1, 292, 1, 1, 1, 2, 1] def test_G17(): assert cf_p(0, 1, 23) == [4, [1, 3, 1, 8]] def test_G18(): assert cf_p(1, 2, 5) == [[1]] assert cf_r([[1]]).expand() == S.Half + sqrt(5)/2 @XFAIL def test_G19(): s = symbols('s', integer=True, positive=True) it = cf_i((exp(1/s) - 1)/(exp(1/s) + 1)) assert list(islice(it, 5)) == [0, 2*s, 6*s, 10*s, 14*s] def test_G20(): s = symbols('s', integer=True, positive=True) # Wester erroneously has this as -s + sqrt(s**2 + 1) assert cf_r([[2*s]]) == s + sqrt(s**2 + 1) @XFAIL def test_G20b(): s = symbols('s', integer=True, positive=True) assert cf_p(s, 1, s**2 + 1) == [[2*s]] # H. Algebra def test_H1(): assert simplify(2*2**n) == simplify(2**(n + 1)) assert powdenest(2*2**n) == simplify(2**(n + 1)) def test_H2(): assert powsimp(4 * 2**n) == 2**(n + 2) def test_H3(): assert (-1)**(n*(n + 1)) == 1 def test_H4(): expr = factor(6*x - 10) assert type(expr) is Mul assert expr.args[0] == 2 assert expr.args[1] == 3*x - 5 p1 = 64*x**34 - 21*x**47 - 126*x**8 - 46*x**5 - 16*x**60 - 81 p2 = 72*x**60 - 25*x**25 - 19*x**23 - 22*x**39 - 83*x**52 + 54*x**10 + 81 q = 34*x**19 - 25*x**16 + 70*x**7 + 20*x**3 - 91*x - 86 def test_H5(): assert gcd(p1, p2, x) == 1 def test_H6(): assert gcd(expand(p1 * q), expand(p2 * q)) == q def test_H7(): p1 = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5 p2 = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z assert gcd(p1, p2, x, y, z) == 1 def test_H8(): p1 = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5 p2 = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z q = 11*x**12*y**7*z**13 - 23*x**2*y**8*z**10 + 47*x**17*y**5*z**8 assert gcd(p1 * q, p2 * q, x, y, z) == q def test_H9(): p1 = 2*x**(n + 4) - x**(n + 2) p2 = 4*x**(n + 1) + 3*x**n assert gcd(p1, p2) == x**n def test_H10(): p1 = 3*x**4 + 3*x**3 + x**2 - x - 2 p2 = x**3 - 3*x**2 + x + 5 assert resultant(p1, p2, x) == 0 def test_H11(): assert resultant(p1 * q, p2 * q, x) == 0 def test_H12(): num = x**2 - 4 den = x**2 + 4*x + 4 assert simplify(num/den) == (x - 2)/(x + 2) @XFAIL def test_H13(): assert simplify((exp(x) - 1) / (exp(x/2) + 1)) == exp(x/2) - 1 def test_H14(): p = (x + 1) ** 20 ep = expand(p) assert ep == (1 + 20*x + 190*x**2 + 1140*x**3 + 4845*x**4 + 15504*x**5 + 38760*x**6 + 77520*x**7 + 125970*x**8 + 167960*x**9 + 184756*x**10 + 167960*x**11 + 125970*x**12 + 77520*x**13 + 38760*x**14 + 15504*x**15 + 4845*x**16 + 1140*x**17 + 190*x**18 + 20*x**19 + x**20) dep = diff(ep, x) assert dep == (20 + 380*x + 3420*x**2 + 19380*x**3 + 77520*x**4 + 232560*x**5 + 542640*x**6 + 1007760*x**7 + 1511640*x**8 + 1847560*x**9 + 1847560*x**10 + 1511640*x**11 + 1007760*x**12 + 542640*x**13 + 232560*x**14 + 77520*x**15 + 19380*x**16 + 3420*x**17 + 380*x**18 + 20*x**19) assert factor(dep) == 20*(1 + x)**19 def test_H15(): assert simplify(Mul(*[x - r for r in solveset(x**3 + x**2 - 7)])) == x**3 + x**2 - 7 def test_H16(): assert factor(x**100 - 1) == ((x - 1)*(x + 1)*(x**2 + 1)*(x**4 - x**3 + x**2 - x + 1)*(x**4 + x**3 + x**2 + x + 1)*(x**8 - x**6 + x**4 - x**2 + 1)*(x**20 - x**15 + x**10 - x**5 + 1)*(x**20 + x**15 + x**10 + x**5 + 1)*(x**40 - x**30 + x**20 - x**10 + 1)) def test_H17(): assert simplify(factor(expand(p1 * p2)) - p1*p2) == 0 @XFAIL def test_H18(): # Factor over complex rationals. test = factor(4*x**4 + 8*x**3 + 77*x**2 + 18*x + 153) good = (2*x + 3*I)*(2*x - 3*I)*(x + 1 - 4*I)*(x + 1 + 4*I) assert test == good def test_H19(): a = symbols('a') # The idea is to let a**2 == 2, then solve 1/(a-1). Answer is a+1") assert Poly(a - 1).invert(Poly(a**2 - 2)) == a + 1 @XFAIL def test_H20(): raise NotImplementedError("let a**2==2; (x**3 + (a-2)*x**2 - " + "(2*a+3)*x - 3*a) / (x**2-2) = (x**2 - 2*x - 3) / (x-a)") @XFAIL def test_H21(): raise NotImplementedError("evaluate (b+c)**4 assuming b**3==2, c**2==3. \ Answer is 2*b + 8*c + 18*b**2 + 12*b*c + 9") def test_H22(): assert factor(x**4 - 3*x**2 + 1, modulus=5) == (x - 2)**2 * (x + 2)**2 def test_H23(): f = x**11 + x + 1 g = (x**2 + x + 1) * (x**9 - x**8 + x**6 - x**5 + x**3 - x**2 + 1) assert factor(f, modulus=65537) == g def test_H24(): phi = AlgebraicNumber(S.GoldenRatio.expand(func=True), alias='phi') assert factor(x**4 - 3*x**2 + 1, extension=phi) == \ (x - phi)*(x + 1 - phi)*(x - 1 + phi)*(x + phi) def test_H25(): e = (x - 2*y**2 + 3*z**3) ** 20 assert factor(expand(e)) == e def test_H26(): g = expand((sin(x) - 2*cos(y)**2 + 3*tan(z)**3)**20) assert factor(g, expand=False) == (-sin(x) + 2*cos(y)**2 - 3*tan(z)**3)**20 def test_H27(): f = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5 g = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z h = -2*z*y**7 \ *(6*x**9*y**9*z**3 + 10*x**7*z**6 + 17*y*x**5*z**12 + 40*y**7) \ *(3*x**22 + 47*x**17*y**5*z**8 - 6*x**15*y**9*z**2 - 24*x*y**19*z**8 - 5) assert factor(expand(f*g)) == h @XFAIL def test_H28(): raise NotImplementedError("expand ((1 - c**2)**5 * (1 - s**2)**5 * " + "(c**2 + s**2)**10) with c**2 + s**2 = 1. Answer is c**10*s**10.") @XFAIL def test_H29(): assert factor(4*x**2 - 21*x*y + 20*y**2, modulus=3) == (x + y)*(x - y) def test_H30(): test = factor(x**3 + y**3, extension=sqrt(-3)) answer = (x + y)*(x + y*(-R(1, 2) - sqrt(3)/2*I))*(x + y*(-R(1, 2) + sqrt(3)/2*I)) assert answer == test def test_H31(): f = (x**2 + 2*x + 3)/(x**3 + 4*x**2 + 5*x + 2) g = 2 / (x + 1)**2 - 2 / (x + 1) + 3 / (x + 2) assert apart(f) == g @XFAIL def test_H32(): # issue 6558 raise NotImplementedError("[A*B*C - (A*B*C)**(-1)]*A*C*B (product \ of a non-commuting product and its inverse)") def test_H33(): A, B, C = symbols('A, B, C', commutative=False) assert (Commutator(A, Commutator(B, C)) + Commutator(B, Commutator(C, A)) + Commutator(C, Commutator(A, B))).doit().expand() == 0 # I. Trigonometry def test_I1(): assert tan(pi*R(7, 10)) == -sqrt(1 + 2/sqrt(5)) @XFAIL def test_I2(): assert sqrt((1 + cos(6))/2) == -cos(3) def test_I3(): assert cos(n*pi) + sin((4*n - 1)*pi/2) == (-1)**n - 1 def test_I4(): assert refine(cos(pi*cos(n*pi)) + sin(pi/2*cos(n*pi)), Q.integer(n)) == (-1)**n - 1 @XFAIL def test_I5(): assert sin((n**5/5 + n**4/2 + n**3/3 - n/30) * pi) == 0 @XFAIL def test_I6(): raise NotImplementedError("assuming -3*pi<x<-5*pi/2, abs(cos(x)) == -cos(x), abs(sin(x)) == -sin(x)") @XFAIL def test_I7(): assert cos(3*x)/cos(x) == cos(x)**2 - 3*sin(x)**2 @XFAIL def test_I8(): assert cos(3*x)/cos(x) == 2*cos(2*x) - 1 @XFAIL def test_I9(): # Supposed to do this with rewrite rules. assert cos(3*x)/cos(x) == cos(x)**2 - 3*sin(x)**2 def test_I10(): assert trigsimp((tan(x)**2 + 1 - cos(x)**-2) / (sin(x)**2 + cos(x)**2 - 1)) is nan @SKIP("hangs") @XFAIL def test_I11(): assert limit((tan(x)**2 + 1 - cos(x)**-2) / (sin(x)**2 + cos(x)**2 - 1), x, 0) != 0 @XFAIL def test_I12(): # This should fail or return nan or something. res = diff((tan(x)**2 + 1 - cos(x)**-2) / (sin(x)**2 + cos(x)**2 - 1), x) assert res is nan # trigsimp(res) gives nan # J. Special functions. def test_J1(): assert bernoulli(16) == R(-3617, 510) def test_J2(): assert diff(elliptic_e(x, y**2), y) == (elliptic_e(x, y**2) - elliptic_f(x, y**2))/y @XFAIL def test_J3(): raise NotImplementedError("Jacobi elliptic functions: diff(dn(u,k), u) == -k**2*sn(u,k)*cn(u,k)") def test_J4(): assert gamma(R(-1, 2)) == -2*sqrt(pi) def test_J5(): assert polygamma(0, R(1, 3)) == -log(3) - sqrt(3)*pi/6 - EulerGamma - log(sqrt(3)) def test_J6(): assert mpmath.besselj(2, 1 + 1j).ae(mpc('0.04157988694396212', '0.24739764151330632')) def test_J7(): assert simplify(besselj(R(-5,2), pi/2)) == 12/(pi**2) def test_J8(): p = besselj(R(3,2), z) q = (sin(z)/z - cos(z))/sqrt(pi*z/2) assert simplify(expand_func(p) -q) == 0 def test_J9(): assert besselj(0, z).diff(z) == - besselj(1, z) def test_J10(): mu, nu = symbols('mu, nu', integer=True) assert assoc_legendre(nu, mu, 0) == 2**mu*sqrt(pi)/gamma((nu - mu)/2 + 1)/gamma((-nu - mu + 1)/2) def test_J11(): assert simplify(assoc_legendre(3, 1, x)) == simplify(-R(3, 2)*sqrt(1 - x**2)*(5*x**2 - 1)) @slow def test_J12(): assert simplify(chebyshevt(1008, x) - 2*x*chebyshevt(1007, x) + chebyshevt(1006, x)) == 0 def test_J13(): a = symbols('a', integer=True, negative=False) assert chebyshevt(a, -1) == (-1)**a def test_J14(): p = hyper([S.Half, S.Half], [R(3, 2)], z**2) assert hyperexpand(p) == asin(z)/z @XFAIL def test_J15(): raise NotImplementedError("F((n+2)/2,-(n-2)/2,R(3,2),sin(z)**2) == sin(n*z)/(n*sin(z)*cos(z)); F(.) is hypergeometric function") @XFAIL def test_J16(): raise NotImplementedError("diff(zeta(x), x) @ x=0 == -log(2*pi)/2") def test_J17(): assert integrate(f((x + 2)/5)*DiracDelta((x - 2)/3) - g(x)*diff(DiracDelta(x - 1), x), (x, 0, 3)) == 3*f(R(4, 5)) + Subs(Derivative(g(x), x), x, 1) @XFAIL def test_J18(): raise NotImplementedError("define an antisymmetric function") # K. The Complex Domain def test_K1(): z1, z2 = symbols('z1, z2', complex=True) assert re(z1 + I*z2) == -im(z2) + re(z1) assert im(z1 + I*z2) == im(z1) + re(z2) def test_K2(): assert abs(3 - sqrt(7) + I*sqrt(6*sqrt(7) - 15)) == 1 @XFAIL def test_K3(): a, b = symbols('a, b', real=True) assert simplify(abs(1/(a + I/a + I*b))) == 1/sqrt(a**2 + (I/a + b)**2) def test_K4(): assert log(3 + 4*I).expand(complex=True) == log(5) + I*atan(R(4, 3)) def test_K5(): x, y = symbols('x, y', real=True) assert tan(x + I*y).expand(complex=True) == (sin(2*x)/(cos(2*x) + cosh(2*y)) + I*sinh(2*y)/(cos(2*x) + cosh(2*y))) def test_K6(): assert sqrt(x*y*abs(z)**2)/(sqrt(x)*abs(z)) == sqrt(x*y)/sqrt(x) assert sqrt(x*y*abs(z)**2)/(sqrt(x)*abs(z)) != sqrt(y) def test_K7(): y = symbols('y', real=True, negative=False) expr = sqrt(x*y*abs(z)**2)/(sqrt(x)*abs(z)) sexpr = simplify(expr) assert sexpr == sqrt(y) def test_K8(): z = symbols('z', complex=True) assert simplify(sqrt(1/z) - 1/sqrt(z)) != 0 # Passes z = symbols('z', complex=True, negative=False) assert simplify(sqrt(1/z) - 1/sqrt(z)) == 0 # Fails def test_K9(): z = symbols('z', positive=True) assert simplify(sqrt(1/z) - 1/sqrt(z)) == 0 def test_K10(): z = symbols('z', negative=True) assert simplify(sqrt(1/z) + 1/sqrt(z)) == 0 # This goes up to K25 # L. Determining Zero Equivalence def test_L1(): assert sqrt(997) - (997**3)**R(1, 6) == 0 def test_L2(): assert sqrt(999983) - (999983**3)**R(1, 6) == 0 def test_L3(): assert simplify((2**R(1, 3) + 4**R(1, 3))**3 - 6*(2**R(1, 3) + 4**R(1, 3)) - 6) == 0 def test_L4(): assert trigsimp(cos(x)**3 + cos(x)*sin(x)**2 - cos(x)) == 0 @XFAIL def test_L5(): assert log(tan(R(1, 2)*x + pi/4)) - asinh(tan(x)) == 0 def test_L6(): assert (log(tan(x/2 + pi/4)) - asinh(tan(x))).diff(x).subs({x: 0}) == 0 @XFAIL def test_L7(): assert simplify(log((2*sqrt(x) + 1)/(sqrt(4*x + 4*sqrt(x) + 1)))) == 0 @XFAIL def test_L8(): assert simplify((4*x + 4*sqrt(x) + 1)**(sqrt(x)/(2*sqrt(x) + 1)) \ *(2*sqrt(x) + 1)**(1/(2*sqrt(x) + 1)) - 2*sqrt(x) - 1) == 0 @XFAIL def test_L9(): z = symbols('z', complex=True) assert simplify(2**(1 - z)*gamma(z)*zeta(z)*cos(z*pi/2) - pi**2*zeta(1 - z)) == 0 # M. Equations @XFAIL def test_M1(): assert Equality(x, 2)/2 + Equality(1, 1) == Equality(x/2 + 1, 2) def test_M2(): # The roots of this equation should all be real. Note that this # doesn't test that they are correct. sol = solveset(3*x**3 - 18*x**2 + 33*x - 19, x) assert all(s.expand(complex=True).is_real for s in sol) @XFAIL def test_M5(): assert solveset(x**6 - 9*x**4 - 4*x**3 + 27*x**2 - 36*x - 23, x) == FiniteSet(2**(1/3) + sqrt(3), 2**(1/3) - sqrt(3), +sqrt(3) - 1/2**(2/3) + I*sqrt(3)/2**(2/3), +sqrt(3) - 1/2**(2/3) - I*sqrt(3)/2**(2/3), -sqrt(3) - 1/2**(2/3) + I*sqrt(3)/2**(2/3), -sqrt(3) - 1/2**(2/3) - I*sqrt(3)/2**(2/3)) def test_M6(): assert set(solveset(x**7 - 1, x)) == \ {cos(n*pi*R(2, 7)) + I*sin(n*pi*R(2, 7)) for n in range(0, 7)} # The paper asks for exp terms, but sin's and cos's may be acceptable; # if the results are simplified, exp terms appear for all but # -sin(pi/14) - I*cos(pi/14) and -sin(pi/14) + I*cos(pi/14) which # will simplify if you apply the transformation foo.rewrite(exp).expand() def test_M7(): # TODO: Replace solve with solveset, as of now test fails for solveset assert set(solve(x**8 - 8*x**7 + 34*x**6 - 92*x**5 + 175*x**4 - 236*x**3 + 226*x**2 - 140*x + 46, x)) == set([ 1 - sqrt(2)*I*sqrt(-sqrt(-3 + 4*sqrt(3)) + 3)/2, 1 - sqrt(2)*sqrt(-3 + I*sqrt(3 + 4*sqrt(3)))/2, 1 - sqrt(2)*I*sqrt(sqrt(-3 + 4*sqrt(3)) + 3)/2, 1 - sqrt(2)*sqrt(-3 - I*sqrt(3 + 4*sqrt(3)))/2, 1 + sqrt(2)*I*sqrt(sqrt(-3 + 4*sqrt(3)) + 3)/2, 1 + sqrt(2)*sqrt(-3 - I*sqrt(3 + 4*sqrt(3)))/2, 1 + sqrt(2)*sqrt(-3 + I*sqrt(3 + 4*sqrt(3)))/2, 1 + sqrt(2)*I*sqrt(-sqrt(-3 + 4*sqrt(3)) + 3)/2, ]) @XFAIL # There are an infinite number of solutions. def test_M8(): x = Symbol('x') z = symbols('z', complex=True) assert solveset(exp(2*x) + 2*exp(x) + 1 - z, x, S.Reals) == \ FiniteSet(log(1 + z - 2*sqrt(z))/2, log(1 + z + 2*sqrt(z))/2) # This one could be simplified better (the 1/2 could be pulled into the log # as a sqrt, and the function inside the log can be factored as a square, # giving [log(sqrt(z) - 1), log(sqrt(z) + 1)]). Also, there should be an # infinite number of solutions. # x = {log(sqrt(z) - 1), log(sqrt(z) + 1) + i pi} [+ n 2 pi i, + n 2 pi i] # where n is an arbitrary integer. See url of detailed output above. @XFAIL def test_M9(): # x = symbols('x') raise NotImplementedError("solveset(exp(2-x**2)-exp(-x),x) has complex solutions.") def test_M10(): # TODO: Replace solve with solveset, as of now test fails for solveset assert solve(exp(x) - x, x) == [-LambertW(-1)] @XFAIL def test_M11(): assert solveset(x**x - x, x) == FiniteSet(-1, 1) def test_M12(): # TODO: x = [-1, 2*(+/-asinh(1)*I + n*pi}, 3*(pi/6 + n*pi/3)] # TODO: Replace solve with solveset, as of now test fails for solveset assert solve((x + 1)*(sin(x)**2 + 1)**2*cos(3*x)**3, x) == [ -1, pi/6, pi/2, - I*log(1 + sqrt(2)), I*log(1 + sqrt(2)), pi - I*log(1 + sqrt(2)), pi + I*log(1 + sqrt(2)), ] @XFAIL def test_M13(): n = Dummy('n') assert solveset_real(sin(x) - cos(x), x) == ImageSet(Lambda(n, n*pi - pi*R(7, 4)), S.Integers) @XFAIL def test_M14(): n = Dummy('n') assert solveset_real(tan(x) - 1, x) == ImageSet(Lambda(n, n*pi + pi/4), S.Integers) def test_M15(): n = Dummy('n') got = solveset(sin(x) - S.Half) assert any(got.dummy_eq(i) for i in ( Union(ImageSet(Lambda(n, 2*n*pi + pi/6), S.Integers), ImageSet(Lambda(n, 2*n*pi + pi*R(5, 6)), S.Integers)), Union(ImageSet(Lambda(n, 2*n*pi + pi*R(5, 6)), S.Integers), ImageSet(Lambda(n, 2*n*pi + pi/6), S.Integers)))) @XFAIL def test_M16(): n = Dummy('n') assert solveset(sin(x) - tan(x), x) == ImageSet(Lambda(n, n*pi), S.Integers) @XFAIL def test_M17(): assert solveset_real(asin(x) - atan(x), x) == FiniteSet(0) @XFAIL def test_M18(): assert solveset_real(acos(x) - atan(x), x) == FiniteSet(sqrt((sqrt(5) - 1)/2)) def test_M19(): # TODO: Replace solve with solveset, as of now test fails for solveset assert solve((x - 2)/x**R(1, 3), x) == [2] def test_M20(): assert solveset(sqrt(x**2 + 1) - x + 2, x) == EmptySet def test_M21(): assert solveset(x + sqrt(x) - 2) == FiniteSet(1) def test_M22(): assert solveset(2*sqrt(x) + 3*x**R(1, 4) - 2) == FiniteSet(R(1, 16)) def test_M23(): x = symbols('x', complex=True) # TODO: Replace solve with solveset, as of now test fails for solveset assert solve(x - 1/sqrt(1 + x**2)) == [ -I*sqrt(S.Half + sqrt(5)/2), sqrt(Rational(-1, 2) + sqrt(5)/2)] def test_M24(): # TODO: Replace solve with solveset, as of now test fails for solveset solution = solve(1 - binomial(m, 2)*2**k, k) answer = log(2/(m*(m - 1)), 2) assert solution[0].expand() == answer.expand() def test_M25(): a, b, c, d = symbols(':d', positive=True) x = symbols('x') # TODO: Replace solve with solveset, as of now test fails for solveset assert solve(a*b**x - c*d**x, x)[0].expand() == (log(c/a)/log(b/d)).expand() def test_M26(): # TODO: Replace solve with solveset, as of now test fails for solveset assert solve(sqrt(log(x)) - log(sqrt(x))) == [1, exp(4)] def test_M27(): x = symbols('x', real=True) b = symbols('b', real=True) # TODO: Replace solve with solveset which gives both [+/- current answer] # note that there is a typo in this test in the wester.pdf; there is no # real solution for the equation as it appears in wester.pdf assert solve(log(acos(asin(x**R(2, 3) - b)) - 1) + 2, x ) == [(b + sin(cos(exp(-2) + 1)))**R(3, 2)] @XFAIL def test_M28(): assert solveset_real(5*x + exp((x - 5)/2) - 8*x**3, x, assume=Q.real(x)) == [-0.784966, -0.016291, 0.802557] def test_M29(): x = symbols('x') assert solveset(abs(x - 1) - 2, domain=S.Reals) == FiniteSet(-1, 3) def test_M30(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports assumptions # assert solve(abs(2*x + 5) - abs(x - 2),x, assume=Q.real(x)) == [-1, -7] assert solveset_real(abs(2*x + 5) - abs(x - 2), x) == FiniteSet(-1, -7) def test_M31(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports assumptions # assert solve(1 - abs(x) - max(-x - 2, x - 2),x, assume=Q.real(x)) == [-3/2, 3/2] assert solveset_real(1 - abs(x) - Max(-x - 2, x - 2), x) == FiniteSet(R(-3, 2), R(3, 2)) @XFAIL def test_M32(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports assumptions assert solveset_real(Max(2 - x**2, x)- Max(-x, (x**3)/9), x) == FiniteSet(-1, 3) @XFAIL def test_M33(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports assumptions # Second answer can be written in another form. The second answer is the root of x**3 + 9*x**2 - 18 = 0 in the interval (-2, -1). assert solveset_real(Max(2 - x**2, x) - x**3/9, x) == FiniteSet(-3, -1.554894, 3) @XFAIL def test_M34(): z = symbols('z', complex=True) assert solveset((1 + I) * z + (2 - I) * conjugate(z) + 3*I, z) == FiniteSet(2 + 3*I) def test_M35(): x, y = symbols('x y', real=True) assert linsolve((3*x - 2*y - I*y + 3*I).as_real_imag(), y, x) == FiniteSet((3, 2)) def test_M36(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports solving for function # assert solve(f**2 + f - 2, x) == [Eq(f(x), 1), Eq(f(x), -2)] assert solveset(f(x)**2 + f(x) - 2, f(x)) == FiniteSet(-2, 1) def test_M37(): assert linsolve([x + y + z - 6, 2*x + y + 2*z - 10, x + 3*y + z - 10 ], x, y, z) == \ FiniteSet((-z + 4, 2, z)) def test_M38(): a, b, c = symbols('a, b, c') domain = FracField([a, b, c], ZZ).to_domain() ring = PolyRing('k1:50', domain) (k1, k2, k3, k4, k5, k6, k7, k8, k9, k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k20, k21, k22, k23, k24, k25, k26, k27, k28, k29, k30, k31, k32, k33, k34, k35, k36, k37, k38, k39, k40, k41, k42, k43, k44, k45, k46, k47, k48, k49) = ring.gens system = [ -b*k8/a + c*k8/a, -b*k11/a + c*k11/a, -b*k10/a + c*k10/a + k2, -k3 - b*k9/a + c*k9/a, -b*k14/a + c*k14/a, -b*k15/a + c*k15/a, -b*k18/a + c*k18/a - k2, -b*k17/a + c*k17/a, -b*k16/a + c*k16/a + k4, -b*k13/a + c*k13/a - b*k21/a + c*k21/a + b*k5/a - c*k5/a, b*k44/a - c*k44/a, -b*k45/a + c*k45/a, -b*k20/a + c*k20/a, -b*k44/a + c*k44/a, b*k46/a - c*k46/a, b**2*k47/a**2 - 2*b*c*k47/a**2 + c**2*k47/a**2, k3, -k4, -b*k12/a + c*k12/a - a*k6/b + c*k6/b, -b*k19/a + c*k19/a + a*k7/c - b*k7/c, b*k45/a - c*k45/a, -b*k46/a + c*k46/a, -k48 + c*k48/a + c*k48/b - c**2*k48/(a*b), -k49 + b*k49/a + b*k49/c - b**2*k49/(a*c), a*k1/b - c*k1/b, a*k4/b - c*k4/b, a*k3/b - c*k3/b + k9, -k10 + a*k2/b - c*k2/b, a*k7/b - c*k7/b, -k9, k11, b*k12/a - c*k12/a + a*k6/b - c*k6/b, a*k15/b - c*k15/b, k10 + a*k18/b - c*k18/b, -k11 + a*k17/b - c*k17/b, a*k16/b - c*k16/b, -a*k13/b + c*k13/b + a*k21/b - c*k21/b + a*k5/b - c*k5/b, -a*k44/b + c*k44/b, a*k45/b - c*k45/b, a*k14/c - b*k14/c + a*k20/b - c*k20/b, a*k44/b - c*k44/b, -a*k46/b + c*k46/b, -k47 + c*k47/a + c*k47/b - c**2*k47/(a*b), a*k19/b - c*k19/b, -a*k45/b + c*k45/b, a*k46/b - c*k46/b, a**2*k48/b**2 - 2*a*c*k48/b**2 + c**2*k48/b**2, -k49 + a*k49/b + a*k49/c - a**2*k49/(b*c), k16, -k17, -a*k1/c + b*k1/c, -k16 - a*k4/c + b*k4/c, -a*k3/c + b*k3/c, k18 - a*k2/c + b*k2/c, b*k19/a - c*k19/a - a*k7/c + b*k7/c, -a*k6/c + b*k6/c, -a*k8/c + b*k8/c, -a*k11/c + b*k11/c + k17, -a*k10/c + b*k10/c - k18, -a*k9/c + b*k9/c, -a*k14/c + b*k14/c - a*k20/b + c*k20/b, -a*k13/c + b*k13/c + a*k21/c - b*k21/c - a*k5/c + b*k5/c, a*k44/c - b*k44/c, -a*k45/c + b*k45/c, -a*k44/c + b*k44/c, a*k46/c - b*k46/c, -k47 + b*k47/a + b*k47/c - b**2*k47/(a*c), -a*k12/c + b*k12/c, a*k45/c - b*k45/c, -a*k46/c + b*k46/c, -k48 + a*k48/b + a*k48/c - a**2*k48/(b*c), a**2*k49/c**2 - 2*a*b*k49/c**2 + b**2*k49/c**2, k8, k11, -k15, k10 - k18, -k17, k9, -k16, -k29, k14 - k32, -k21 + k23 - k31, -k24 - k30, -k35, k44, -k45, k36, k13 - k23 + k39, -k20 + k38, k25 + k37, b*k26/a - c*k26/a - k34 + k42, -2*k44, k45, k46, b*k47/a - c*k47/a, k41, k44, -k46, -b*k47/a + c*k47/a, k12 + k24, -k19 - k25, -a*k27/b + c*k27/b - k33, k45, -k46, -a*k48/b + c*k48/b, a*k28/c - b*k28/c + k40, -k45, k46, a*k48/b - c*k48/b, a*k49/c - b*k49/c, -a*k49/c + b*k49/c, -k1, -k4, -k3, k15, k18 - k2, k17, k16, k22, k25 - k7, k24 + k30, k21 + k23 - k31, k28, -k44, k45, -k30 - k6, k20 + k32, k27 + b*k33/a - c*k33/a, k44, -k46, -b*k47/a + c*k47/a, -k36, k31 - k39 - k5, -k32 - k38, k19 - k37, k26 - a*k34/b + c*k34/b - k42, k44, -2*k45, k46, a*k48/b - c*k48/b, a*k35/c - b*k35/c - k41, -k44, k46, b*k47/a - c*k47/a, -a*k49/c + b*k49/c, -k40, k45, -k46, -a*k48/b + c*k48/b, a*k49/c - b*k49/c, k1, k4, k3, -k8, -k11, -k10 + k2, -k9, k37 + k7, -k14 - k38, -k22, -k25 - k37, -k24 + k6, -k13 - k23 + k39, -k28 + b*k40/a - c*k40/a, k44, -k45, -k27, -k44, k46, b*k47/a - c*k47/a, k29, k32 + k38, k31 - k39 + k5, -k12 + k30, k35 - a*k41/b + c*k41/b, -k44, k45, -k26 + k34 + a*k42/c - b*k42/c, k44, k45, -2*k46, -b*k47/a + c*k47/a, -a*k48/b + c*k48/b, a*k49/c - b*k49/c, k33, -k45, k46, a*k48/b - c*k48/b, -a*k49/c + b*k49/c ] solution = { k49: 0, k48: 0, k47: 0, k46: 0, k45: 0, k44: 0, k41: 0, k40: 0, k38: 0, k37: 0, k36: 0, k35: 0, k33: 0, k32: 0, k30: 0, k29: 0, k28: 0, k27: 0, k25: 0, k24: 0, k22: 0, k21: 0, k20: 0, k19: 0, k18: 0, k17: 0, k16: 0, k15: 0, k14: 0, k13: 0, k12: 0, k11: 0, k10: 0, k9: 0, k8: 0, k7: 0, k6: 0, k5: 0, k4: 0, k3: 0, k2: 0, k1: 0, k34: b/c*k42, k31: k39, k26: a/c*k42, k23: k39 } assert solve_lin_sys(system, ring) == solution def test_M39(): x, y, z = symbols('x y z', complex=True) # TODO: Replace solve with solveset, as of now # solveset doesn't supports non-linear multivariate assert solve([x**2*y + 3*y*z - 4, -3*x**2*z + 2*y**2 + 1, 2*y*z**2 - z**2 - 1 ]) ==\ [{y: 1, z: 1, x: -1}, {y: 1, z: 1, x: 1},\ {y: sqrt(2)*I, z: R(1,3) - sqrt(2)*I/3, x: -sqrt(-1 - sqrt(2)*I)},\ {y: sqrt(2)*I, z: R(1,3) - sqrt(2)*I/3, x: sqrt(-1 - sqrt(2)*I)},\ {y: -sqrt(2)*I, z: R(1,3) + sqrt(2)*I/3, x: -sqrt(-1 + sqrt(2)*I)},\ {y: -sqrt(2)*I, z: R(1,3) + sqrt(2)*I/3, x: sqrt(-1 + sqrt(2)*I)}] # N. Inequalities def test_N1(): assert ask(E**pi > pi**E) @XFAIL def test_N2(): x = symbols('x', real=True) assert ask(x**4 - x + 1 > 0) is True assert ask(x**4 - x + 1 > 1) is False @XFAIL def test_N3(): x = symbols('x', real=True) assert ask(And(Lt(-1, x), Lt(x, 1)), abs(x) < 1 ) @XFAIL def test_N4(): x, y = symbols('x y', real=True) assert ask(2*x**2 > 2*y**2, (x > y) & (y > 0)) is True @XFAIL def test_N5(): x, y, k = symbols('x y k', real=True) assert ask(k*x**2 > k*y**2, (x > y) & (y > 0) & (k > 0)) is True @slow @XFAIL def test_N6(): x, y, k, n = symbols('x y k n', real=True) assert ask(k*x**n > k*y**n, (x > y) & (y > 0) & (k > 0) & (n > 0)) is True @XFAIL def test_N7(): x, y = symbols('x y', real=True) assert ask(y > 0, (x > 1) & (y >= x - 1)) is True @XFAIL @slow def test_N8(): x, y, z = symbols('x y z', real=True) assert ask(Eq(x, y) & Eq(y, z), (x >= y) & (y >= z) & (z >= x)) def test_N9(): x = Symbol('x') assert solveset(abs(x - 1) > 2, domain=S.Reals) == Union(Interval(-oo, -1, False, True), Interval(3, oo, True)) def test_N10(): x = Symbol('x') p = (x - 1)*(x - 2)*(x - 3)*(x - 4)*(x - 5) assert solveset(expand(p) < 0, domain=S.Reals) == Union(Interval(-oo, 1, True, True), Interval(2, 3, True, True), Interval(4, 5, True, True)) def test_N11(): x = Symbol('x') assert solveset(6/(x - 3) <= 3, domain=S.Reals) == Union(Interval(-oo, 3, True, True), Interval(5, oo)) def test_N12(): x = Symbol('x') assert solveset(sqrt(x) < 2, domain=S.Reals) == Interval(0, 4, False, True) def test_N13(): x = Symbol('x') assert solveset(sin(x) < 2, domain=S.Reals) == S.Reals @XFAIL def test_N14(): x = Symbol('x') # Gives 'Union(Interval(Integer(0), Mul(Rational(1, 2), pi), false, true), # Interval(Mul(Rational(1, 2), pi), Mul(Integer(2), pi), true, false))' # which is not the correct answer, but the provided also seems wrong. assert solveset(sin(x) < 1, x, domain=S.Reals) == Union(Interval(-oo, pi/2, True, True), Interval(pi/2, oo, True, True)) def test_N15(): r, t = symbols('r t') # raises NotImplementedError: only univariate inequalities are supported solveset(abs(2*r*(cos(t) - 1) + 1) <= 1, r, S.Reals) def test_N16(): r, t = symbols('r t') solveset((r**2)*((cos(t) - 4)**2)*sin(t)**2 < 9, r, S.Reals) @XFAIL def test_N17(): # currently only univariate inequalities are supported assert solveset((x + y > 0, x - y < 0), (x, y)) == (abs(x) < y) def test_O1(): M = Matrix((1 + I, -2, 3*I)) assert sqrt(expand(M.dot(M.H))) == sqrt(15) def test_O2(): assert Matrix((2, 2, -3)).cross(Matrix((1, 3, 1))) == Matrix([[11], [-5], [4]]) # The vector module has no way of representing vectors symbolically (without # respect to a basis) @XFAIL def test_O3(): # assert (va ^ vb) | (vc ^ vd) == -(va | vc)*(vb | vd) + (va | vd)*(vb | vc) raise NotImplementedError("""The vector module has no way of representing vectors symbolically (without respect to a basis)""") def test_O4(): from sympy.vector import CoordSys3D, Del N = CoordSys3D("N") delop = Del() i, j, k = N.base_vectors() x, y, z = N.base_scalars() F = i*(x*y*z) + j*((x*y*z)**2) + k*((y**2)*(z**3)) assert delop.cross(F).doit() == (-2*x**2*y**2*z + 2*y*z**3)*i + x*y*j + (2*x*y**2*z**2 - x*z)*k @XFAIL def test_O5(): #assert grad|(f^g)-g|(grad^f)+f|(grad^g) == 0 raise NotImplementedError("""The vector module has no way of representing vectors symbolically (without respect to a basis)""") #testO8-O9 MISSING!! def test_O10(): L = [Matrix([2, 3, 5]), Matrix([3, 6, 2]), Matrix([8, 3, 6])] assert GramSchmidt(L) == [Matrix([ [2], [3], [5]]), Matrix([ [R(23, 19)], [R(63, 19)], [R(-47, 19)]]), Matrix([ [R(1692, 353)], [R(-1551, 706)], [R(-423, 706)]])] def test_P1(): assert Matrix(3, 3, lambda i, j: j - i).diagonal(-1) == Matrix( 1, 2, [-1, -1]) def test_P2(): M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) M.row_del(1) M.col_del(2) assert M == Matrix([[1, 2], [7, 8]]) def test_P3(): A = Matrix([ [11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]]) A11 = A[0:3, 1:4] A12 = A[(0, 1, 3), (2, 0, 3)] A21 = A A221 = -A[0:2, 2:4] A222 = -A[(3, 0), (2, 1)] A22 = BlockMatrix([[A221, A222]]).T rows = [[-A11, A12], [A21, A22]] raises(ValueError, lambda: BlockMatrix(rows)) B = Matrix(rows) assert B == Matrix([ [-12, -13, -14, 13, 11, 14], [-22, -23, -24, 23, 21, 24], [-32, -33, -34, 43, 41, 44], [11, 12, 13, 14, -13, -23], [21, 22, 23, 24, -14, -24], [31, 32, 33, 34, -43, -13], [41, 42, 43, 44, -42, -12]]) @XFAIL def test_P4(): raise NotImplementedError("Block matrix diagonalization not supported") def test_P5(): M = Matrix([[7, 11], [3, 8]]) assert M % 2 == Matrix([[1, 1], [1, 0]]) def test_P6(): M = Matrix([[cos(x), sin(x)], [-sin(x), cos(x)]]) assert M.diff(x, 2) == Matrix([[-cos(x), -sin(x)], [sin(x), -cos(x)]]) def test_P7(): M = Matrix([[x, y]])*( z*Matrix([[1, 3, 5], [2, 4, 6]]) + Matrix([[7, -9, 11], [-8, 10, -12]])) assert M == Matrix([[x*(z + 7) + y*(2*z - 8), x*(3*z - 9) + y*(4*z + 10), x*(5*z + 11) + y*(6*z - 12)]]) def test_P8(): M = Matrix([[1, -2*I], [-3*I, 4]]) assert M.norm(ord=S.Infinity) == 7 def test_P9(): a, b, c = symbols('a b c', nonzero=True) M = Matrix([[a/(b*c), 1/c, 1/b], [1/c, b/(a*c), 1/a], [1/b, 1/a, c/(a*b)]]) assert factor(M.norm('fro')) == (a**2 + b**2 + c**2)/(abs(a)*abs(b)*abs(c)) @XFAIL def test_P10(): M = Matrix([[1, 2 + 3*I], [f(4 - 5*I), 6]]) # conjugate(f(4 - 5*i)) is not simplified to f(4+5*I) assert M.H == Matrix([[1, f(4 + 5*I)], [2 + 3*I, 6]]) @XFAIL def test_P11(): # raises NotImplementedError("Matrix([[x,y],[1,x*y]]).inv() # not simplifying to extract common factor") assert Matrix([[x, y], [1, x*y]]).inv() == (1/(x**2 - 1))*Matrix([[x, -1], [-1/y, x/y]]) def test_P11_workaround(): # This test was changed to inverse method ADJ because it depended on the # specific form of inverse returned from the 'GE' method which has changed. M = Matrix([[x, y], [1, x*y]]).inv('ADJ') c = gcd(tuple(M)) assert MatMul(c, M/c, evaluate=False) == MatMul(c, Matrix([ [x*y, -y], [ -1, x]]), evaluate=False) def test_P12(): A11 = MatrixSymbol('A11', n, n) A12 = MatrixSymbol('A12', n, n) A22 = MatrixSymbol('A22', n, n) B = BlockMatrix([[A11, A12], [ZeroMatrix(n, n), A22]]) assert block_collapse(B.I) == BlockMatrix([[A11.I, (-1)*A11.I*A12*A22.I], [ZeroMatrix(n, n), A22.I]]) def test_P13(): M = Matrix([[1, x - 2, x - 3], [x - 1, x**2 - 3*x + 6, x**2 - 3*x - 2], [x - 2, x**2 - 8, 2*(x**2) - 12*x + 14]]) L, U, _ = M.LUdecomposition() assert simplify(L) == Matrix([[1, 0, 0], [x - 1, 1, 0], [x - 2, x - 3, 1]]) assert simplify(U) == Matrix([[1, x - 2, x - 3], [0, 4, x - 5], [0, 0, x - 7]]) def test_P14(): M = Matrix([[1, 2, 3, 1, 3], [3, 2, 1, 1, 7], [0, 2, 4, 1, 1], [1, 1, 1, 1, 4]]) R, _ = M.rref() assert R == Matrix([[1, 0, -1, 0, 2], [0, 1, 2, 0, -1], [0, 0, 0, 1, 3], [0, 0, 0, 0, 0]]) def test_P15(): M = Matrix([[-1, 3, 7, -5], [4, -2, 1, 3], [2, 4, 15, -7]]) assert M.rank() == 2 def test_P16(): M = Matrix([[2*sqrt(2), 8], [6*sqrt(6), 24*sqrt(3)]]) assert M.rank() == 1 def test_P17(): t = symbols('t', real=True) M=Matrix([ [sin(2*t), cos(2*t)], [2*(1 - (cos(t)**2))*cos(t), (1 - 2*(sin(t)**2))*sin(t)]]) assert M.rank() == 1 def test_P18(): M = Matrix([[1, 0, -2, 0], [-2, 1, 0, 3], [-1, 2, -6, 6]]) assert M.nullspace() == [Matrix([[2], [4], [1], [0]]), Matrix([[0], [-3], [0], [1]])] def test_P19(): w = symbols('w') M = Matrix([[1, 1, 1, 1], [w, x, y, z], [w**2, x**2, y**2, z**2], [w**3, x**3, y**3, z**3]]) assert M.det() == (w**3*x**2*y - w**3*x**2*z - w**3*x*y**2 + w**3*x*z**2 + w**3*y**2*z - w**3*y*z**2 - w**2*x**3*y + w**2*x**3*z + w**2*x*y**3 - w**2*x*z**3 - w**2*y**3*z + w**2*y*z**3 + w*x**3*y**2 - w*x**3*z**2 - w*x**2*y**3 + w*x**2*z**3 + w*y**3*z**2 - w*y**2*z**3 - x**3*y**2*z + x**3*y*z**2 + x**2*y**3*z - x**2*y*z**3 - x*y**3*z**2 + x*y**2*z**3 ) @XFAIL def test_P20(): raise NotImplementedError("Matrix minimal polynomial not supported") def test_P21(): M = Matrix([[5, -3, -7], [-2, 1, 2], [2, -3, -4]]) assert M.charpoly(x).as_expr() == x**3 - 2*x**2 - 5*x + 6 def test_P22(): d = 100 M = (2 - x)*eye(d) assert M.eigenvals() == {-x + 2: d} def test_P23(): M = Matrix([ [2, 1, 0, 0, 0], [1, 2, 1, 0, 0], [0, 1, 2, 1, 0], [0, 0, 1, 2, 1], [0, 0, 0, 1, 2]]) assert M.eigenvals() == { S('1'): 1, S('2'): 1, S('3'): 1, S('sqrt(3) + 2'): 1, S('-sqrt(3) + 2'): 1} def test_P24(): M = Matrix([[611, 196, -192, 407, -8, -52, -49, 29], [196, 899, 113, -192, -71, -43, -8, -44], [-192, 113, 899, 196, 61, 49, 8, 52], [ 407, -192, 196, 611, 8, 44, 59, -23], [ -8, -71, 61, 8, 411, -599, 208, 208], [ -52, -43, 49, 44, -599, 411, 208, 208], [ -49, -8, 8, 59, 208, 208, 99, -911], [ 29, -44, 52, -23, 208, 208, -911, 99]]) assert M.eigenvals() == { S('0'): 1, S('10*sqrt(10405)'): 1, S('100*sqrt(26) + 510'): 1, S('1000'): 2, S('-100*sqrt(26) + 510'): 1, S('-10*sqrt(10405)'): 1, S('1020'): 1} def test_P25(): MF = N(Matrix([[ 611, 196, -192, 407, -8, -52, -49, 29], [ 196, 899, 113, -192, -71, -43, -8, -44], [-192, 113, 899, 196, 61, 49, 8, 52], [ 407, -192, 196, 611, 8, 44, 59, -23], [ -8, -71, 61, 8, 411, -599, 208, 208], [ -52, -43, 49, 44, -599, 411, 208, 208], [ -49, -8, 8, 59, 208, 208, 99, -911], [ 29, -44, 52, -23, 208, 208, -911, 99]])) ev_1 = sorted(MF.eigenvals(multiple=True)) ev_2 = sorted( [-1020.0490184299969, 0.0, 0.09804864072151699, 1000.0, 1000.0, 1019.9019513592784, 1020.0, 1020.0490184299969]) for x, y in zip(ev_1, ev_2): assert abs(x - y) < 1e-12 def test_P26(): a0, a1, a2, a3, a4 = symbols('a0 a1 a2 a3 a4') M = Matrix([[-a4, -a3, -a2, -a1, -a0, 0, 0, 0, 0], [ 1, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 1, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 1, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 1, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, -1, -1, 0, 0], [ 0, 0, 0, 0, 0, 1, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 1, -1, -1], [ 0, 0, 0, 0, 0, 0, 0, 1, 0]]) assert M.eigenvals(error_when_incomplete=False) == { S('-1/2 - sqrt(3)*I/2'): 2, S('-1/2 + sqrt(3)*I/2'): 2} def test_P27(): a = symbols('a') M = Matrix([[a, 0, 0, 0, 0], [0, 0, 0, 0, 1], [0, 0, a, 0, 0], [0, 0, 0, a, 0], [0, -2, 0, 0, 2]]) assert M.eigenvects() == [ (a, 3, [ Matrix([1, 0, 0, 0, 0]), Matrix([0, 0, 1, 0, 0]), Matrix([0, 0, 0, 1, 0]) ]), (1 - I, 1, [ Matrix([0, (1 + I)/2, 0, 0, 1]) ]), (1 + I, 1, [ Matrix([0, (1 - I)/2, 0, 0, 1]) ]), ] @XFAIL def test_P28(): raise NotImplementedError("Generalized eigenvectors not supported \ https://github.com/sympy/sympy/issues/5293") @XFAIL def test_P29(): raise NotImplementedError("Generalized eigenvectors not supported \ https://github.com/sympy/sympy/issues/5293") def test_P30(): M = Matrix([[1, 0, 0, 1, -1], [0, 1, -2, 3, -3], [0, 0, -1, 2, -2], [1, -1, 1, 0, 1], [1, -1, 1, -1, 2]]) _, J = M.jordan_form() assert J == Matrix([[-1, 0, 0, 0, 0], [0, 1, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 1], [0, 0, 0, 0, 1]]) @XFAIL def test_P31(): raise NotImplementedError("Smith normal form not implemented") def test_P32(): M = Matrix([[1, -2], [2, 1]]) assert exp(M).rewrite(cos).simplify() == Matrix([[E*cos(2), -E*sin(2)], [E*sin(2), E*cos(2)]]) def test_P33(): w, t = symbols('w t') M = Matrix([[0, 1, 0, 0], [0, 0, 0, 2*w], [0, 0, 0, 1], [0, -2*w, 3*w**2, 0]]) assert exp(M*t).rewrite(cos).expand() == Matrix([ [1, -3*t + 4*sin(t*w)/w, 6*t*w - 6*sin(t*w), -2*cos(t*w)/w + 2/w], [0, 4*cos(t*w) - 3, -6*w*cos(t*w) + 6*w, 2*sin(t*w)], [0, 2*cos(t*w)/w - 2/w, -3*cos(t*w) + 4, sin(t*w)/w], [0, -2*sin(t*w), 3*w*sin(t*w), cos(t*w)]]) @XFAIL def test_P34(): a, b, c = symbols('a b c', real=True) M = Matrix([[a, 1, 0, 0, 0, 0], [0, a, 0, 0, 0, 0], [0, 0, b, 0, 0, 0], [0, 0, 0, c, 1, 0], [0, 0, 0, 0, c, 1], [0, 0, 0, 0, 0, c]]) # raises exception, sin(M) not supported. exp(M*I) also not supported # https://github.com/sympy/sympy/issues/6218 assert sin(M) == Matrix([[sin(a), cos(a), 0, 0, 0, 0], [0, sin(a), 0, 0, 0, 0], [0, 0, sin(b), 0, 0, 0], [0, 0, 0, sin(c), cos(c), -sin(c)/2], [0, 0, 0, 0, sin(c), cos(c)], [0, 0, 0, 0, 0, sin(c)]]) @XFAIL def test_P35(): M = pi/2*Matrix([[2, 1, 1], [2, 3, 2], [1, 1, 2]]) # raises exception, sin(M) not supported. exp(M*I) also not supported # https://github.com/sympy/sympy/issues/6218 assert sin(M) == eye(3) @XFAIL def test_P36(): M = Matrix([[10, 7], [7, 17]]) assert sqrt(M) == Matrix([[3, 1], [1, 4]]) def test_P37(): M = Matrix([[1, 1, 0], [0, 1, 0], [0, 0, 1]]) assert M**S.Half == Matrix([[1, R(1, 2), 0], [0, 1, 0], [0, 0, 1]]) @XFAIL def test_P38(): M=Matrix([[0, 1, 0], [0, 0, 0], [0, 0, 0]]) with raises(AssertionError): # raises ValueError: Matrix det == 0; not invertible M**S.Half # if it doesn't raise then this assertion will be # raised and the test will be flagged as not XFAILing assert None @XFAIL def test_P39(): """ M=Matrix([ [1, 1], [2, 2], [3, 3]]) M.SVD() """ raise NotImplementedError("Singular value decomposition not implemented") def test_P40(): r, t = symbols('r t', real=True) M = Matrix([r*cos(t), r*sin(t)]) assert M.jacobian(Matrix([r, t])) == Matrix([[cos(t), -r*sin(t)], [sin(t), r*cos(t)]]) def test_P41(): r, t = symbols('r t', real=True) assert hessian(r**2*sin(t),(r,t)) == Matrix([[ 2*sin(t), 2*r*cos(t)], [2*r*cos(t), -r**2*sin(t)]]) def test_P42(): assert wronskian([cos(x), sin(x)], x).simplify() == 1 def test_P43(): def __my_jacobian(M, Y): return Matrix([M.diff(v).T for v in Y]).T r, t = symbols('r t', real=True) M = Matrix([r*cos(t), r*sin(t)]) assert __my_jacobian(M,[r,t]) == Matrix([[cos(t), -r*sin(t)], [sin(t), r*cos(t)]]) def test_P44(): def __my_hessian(f, Y): V = Matrix([diff(f, v) for v in Y]) return Matrix([V.T.diff(v) for v in Y]) r, t = symbols('r t', real=True) assert __my_hessian(r**2*sin(t), (r, t)) == Matrix([ [ 2*sin(t), 2*r*cos(t)], [2*r*cos(t), -r**2*sin(t)]]) def test_P45(): def __my_wronskian(Y, v): M = Matrix([Matrix(Y).T.diff(x, n) for n in range(0, len(Y))]) return M.det() assert __my_wronskian([cos(x), sin(x)], x).simplify() == 1 # Q1-Q6 Tensor tests missing @XFAIL def test_R1(): i, j, n = symbols('i j n', integer=True, positive=True) xn = MatrixSymbol('xn', n, 1) Sm = Sum((xn[i, 0] - Sum(xn[j, 0], (j, 0, n - 1))/n)**2, (i, 0, n - 1)) # sum does not calculate # Unknown result Sm.doit() raise NotImplementedError('Unknown result') @XFAIL def test_R2(): m, b = symbols('m b') i, n = symbols('i n', integer=True, positive=True) xn = MatrixSymbol('xn', n, 1) yn = MatrixSymbol('yn', n, 1) f = Sum((yn[i, 0] - m*xn[i, 0] - b)**2, (i, 0, n - 1)) f1 = diff(f, m) f2 = diff(f, b) # raises TypeError: solveset() takes at most 2 arguments (3 given) solveset((f1, f2), (m, b), domain=S.Reals) @XFAIL def test_R3(): n, k = symbols('n k', integer=True, positive=True) sk = ((-1)**k) * (binomial(2*n, k))**2 Sm = Sum(sk, (k, 1, oo)) T = Sm.doit() T2 = T.combsimp() # returns -((-1)**n*factorial(2*n) # - (factorial(n))**2)*exp_polar(-I*pi)/(factorial(n))**2 assert T2 == (-1)**n*binomial(2*n, n) @XFAIL def test_R4(): # Macsyma indefinite sum test case: #(c15) /* Check whether the full Gosper algorithm is implemented # => 1/2^(n + 1) binomial(n, k - 1) */ #closedform(indefsum(binomial(n, k)/2^n - binomial(n + 1, k)/2^(n + 1), k)); #Time= 2690 msecs # (- n + k - 1) binomial(n + 1, k) #(d15) - -------------------------------- # n # 2 2 (n + 1) # #(c16) factcomb(makefact(%)); #Time= 220 msecs # n! #(d16) ---------------- # n # 2 k! 2 (n - k)! # Might be possible after fixing https://github.com/sympy/sympy/pull/1879 raise NotImplementedError("Indefinite sum not supported") @XFAIL def test_R5(): a, b, c, n, k = symbols('a b c n k', integer=True, positive=True) sk = ((-1)**k)*(binomial(a + b, a + k) *binomial(b + c, b + k)*binomial(c + a, c + k)) Sm = Sum(sk, (k, 1, oo)) T = Sm.doit() # hypergeometric series not calculated assert T == factorial(a+b+c)/(factorial(a)*factorial(b)*factorial(c)) def test_R6(): n, k = symbols('n k', integer=True, positive=True) gn = MatrixSymbol('gn', n + 2, 1) Sm = Sum(gn[k, 0] - gn[k - 1, 0], (k, 1, n + 1)) assert Sm.doit() == -gn[0, 0] + gn[n + 1, 0] def test_R7(): n, k = symbols('n k', integer=True, positive=True) T = Sum(k**3,(k,1,n)).doit() assert T.factor() == n**2*(n + 1)**2/4 @XFAIL def test_R8(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(k**2*binomial(n, k), (k, 1, n)) T = Sm.doit() #returns Piecewise function assert T.combsimp() == n*(n + 1)*2**(n - 2) def test_R9(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(binomial(n, k - 1)/k, (k, 1, n + 1)) assert Sm.doit().simplify() == (2**(n + 1) - 1)/(n + 1) @XFAIL def test_R10(): n, m, r, k = symbols('n m r k', integer=True, positive=True) Sm = Sum(binomial(n, k)*binomial(m, r - k), (k, 0, r)) T = Sm.doit() T2 = T.combsimp().rewrite(factorial) assert T2 == factorial(m + n)/(factorial(r)*factorial(m + n - r)) assert T2 == binomial(m + n, r).rewrite(factorial) # rewrite(binomial) is not working. # https://github.com/sympy/sympy/issues/7135 T3 = T2.rewrite(binomial) assert T3 == binomial(m + n, r) @XFAIL def test_R11(): n, k = symbols('n k', integer=True, positive=True) sk = binomial(n, k)*fibonacci(k) Sm = Sum(sk, (k, 0, n)) T = Sm.doit() # Fibonacci simplification not implemented # https://github.com/sympy/sympy/issues/7134 assert T == fibonacci(2*n) @XFAIL def test_R12(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(fibonacci(k)**2, (k, 0, n)) T = Sm.doit() assert T == fibonacci(n)*fibonacci(n + 1) @XFAIL def test_R13(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(sin(k*x), (k, 1, n)) T = Sm.doit() # Sum is not calculated assert T.simplify() == cot(x/2)/2 - cos(x*(2*n + 1)/2)/(2*sin(x/2)) @XFAIL def test_R14(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(sin((2*k - 1)*x), (k, 1, n)) T = Sm.doit() # Sum is not calculated assert T.simplify() == sin(n*x)**2/sin(x) @XFAIL def test_R15(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(binomial(n - k, k), (k, 0, floor(n/2))) T = Sm.doit() # Sum is not calculated assert T.simplify() == fibonacci(n + 1) def test_R16(): k = symbols('k', integer=True, positive=True) Sm = Sum(1/k**2 + 1/k**3, (k, 1, oo)) assert Sm.doit() == zeta(3) + pi**2/6 def test_R17(): k = symbols('k', integer=True, positive=True) assert abs(float(Sum(1/k**2 + 1/k**3, (k, 1, oo))) - 2.8469909700078206) < 1e-15 def test_R18(): k = symbols('k', integer=True, positive=True) Sm = Sum(1/(2**k*k**2), (k, 1, oo)) T = Sm.doit() assert T.simplify() == -log(2)**2/2 + pi**2/12 @slow @XFAIL def test_R19(): k = symbols('k', integer=True, positive=True) Sm = Sum(1/((3*k + 1)*(3*k + 2)*(3*k + 3)), (k, 0, oo)) T = Sm.doit() # assert fails, T not simplified assert T.simplify() == -log(3)/4 + sqrt(3)*pi/12 @XFAIL def test_R20(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(binomial(n, 4*k), (k, 0, oo)) T = Sm.doit() # assert fails, T not simplified assert T.simplify() == 2**(n/2)*cos(pi*n/4)/2 + 2**(n - 1)/2 @XFAIL def test_R21(): k = symbols('k', integer=True, positive=True) Sm = Sum(1/(sqrt(k*(k + 1)) * (sqrt(k) + sqrt(k + 1))), (k, 1, oo)) T = Sm.doit() # Sum not calculated assert T.simplify() == 1 # test_R22 answer not available in Wester samples # Sum(Sum(binomial(n, k)*binomial(n - k, n - 2*k)*x**n*y**(n - 2*k), # (k, 0, floor(n/2))), (n, 0, oo)) with abs(x*y)<1? @XFAIL def test_R23(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(Sum((factorial(n)/(factorial(k)**2*factorial(n - 2*k)))* (x/y)**k*(x*y)**(n - k), (n, 2*k, oo)), (k, 0, oo)) # Missing how to express constraint abs(x*y)<1? T = Sm.doit() # Sum not calculated assert T == -1/sqrt(x**2*y**2 - 4*x**2 - 2*x*y + 1) def test_R24(): m, k = symbols('m k', integer=True, positive=True) Sm = Sum(Product(k/(2*k - 1), (k, 1, m)), (m, 2, oo)) assert Sm.doit() == pi/2 def test_S1(): k = symbols('k', integer=True, positive=True) Pr = Product(gamma(k/3), (k, 1, 8)) assert Pr.doit().simplify() == 640*sqrt(3)*pi**3/6561 def test_S2(): n, k = symbols('n k', integer=True, positive=True) assert Product(k, (k, 1, n)).doit() == factorial(n) def test_S3(): n, k = symbols('n k', integer=True, positive=True) assert Product(x**k, (k, 1, n)).doit().simplify() == x**(n*(n + 1)/2) def test_S4(): n, k = symbols('n k', integer=True, positive=True) assert Product(1 + 1/k, (k, 1, n -1)).doit().simplify() == n def test_S5(): n, k = symbols('n k', integer=True, positive=True) assert (Product((2*k - 1)/(2*k), (k, 1, n)).doit().gammasimp() == gamma(n + S.Half)/(sqrt(pi)*gamma(n + 1))) @XFAIL def test_S6(): n, k = symbols('n k', integer=True, positive=True) # Product does not evaluate assert (Product(x**2 -2*x*cos(k*pi/n) + 1, (k, 1, n - 1)).doit().simplify() == (x**(2*n) - 1)/(x**2 - 1)) @XFAIL def test_S7(): k = symbols('k', integer=True, positive=True) Pr = Product((k**3 - 1)/(k**3 + 1), (k, 2, oo)) T = Pr.doit() # Product does not evaluate assert T.simplify() == R(2, 3) @XFAIL def test_S8(): k = symbols('k', integer=True, positive=True) Pr = Product(1 - 1/(2*k)**2, (k, 1, oo)) T = Pr.doit() # Product does not evaluate assert T.simplify() == 2/pi @XFAIL def test_S9(): k = symbols('k', integer=True, positive=True) Pr = Product(1 + (-1)**(k + 1)/(2*k - 1), (k, 1, oo)) T = Pr.doit() # Product produces 0 # https://github.com/sympy/sympy/issues/7133 assert T.simplify() == sqrt(2) @XFAIL def test_S10(): k = symbols('k', integer=True, positive=True) Pr = Product((k*(k + 1) + 1 + I)/(k*(k + 1) + 1 - I), (k, 0, oo)) T = Pr.doit() # Product does not evaluate assert T.simplify() == -1 def test_T1(): assert limit((1 + 1/n)**n, n, oo) == E assert limit((1 - cos(x))/x**2, x, 0) == S.Half def test_T2(): assert limit((3**x + 5**x)**(1/x), x, oo) == 5 def test_T3(): assert limit(log(x)/(log(x) + sin(x)), x, oo) == 1 def test_T4(): assert limit((exp(x*exp(-x)/(exp(-x) + exp(-2*x**2/(x + 1)))) - exp(x))/x, x, oo) == -exp(2) def test_T5(): assert limit(x*log(x)*log(x*exp(x) - x**2)**2/log(log(x**2 + 2*exp(exp(3*x**3*log(x))))), x, oo) == R(1, 3) def test_T6(): assert limit(1/n * factorial(n)**(1/n), n, oo) == exp(-1) def test_T7(): limit(1/n * gamma(n + 1)**(1/n), n, oo) def test_T8(): a, z = symbols('a z', positive=True) assert limit(gamma(z + a)/gamma(z)*exp(-a*log(z)), z, oo) == 1 @XFAIL def test_T9(): z, k = symbols('z k', positive=True) # raises NotImplementedError: # Don't know how to calculate the mrv of '(1, k)' assert limit(hyper((1, k), (1,), z/k), k, oo) == exp(z) @XFAIL def test_T10(): # No longer raises PoleError, but should return euler-mascheroni constant assert limit(zeta(x) - 1/(x - 1), x, 1) == integrate(-1/x + 1/floor(x), (x, 1, oo)) @XFAIL def test_T11(): n, k = symbols('n k', integer=True, positive=True) # evaluates to 0 assert limit(n**x/(x*product((1 + x/k), (k, 1, n))), n, oo) == gamma(x) def test_T12(): x, t = symbols('x t', real=True) # Does not evaluate the limit but returns an expression with erf assert limit(x * integrate(exp(-t**2), (t, 0, x))/(1 - exp(-x**2)), x, 0) == 1 def test_T13(): x = symbols('x', real=True) assert [limit(x/abs(x), x, 0, dir='-'), limit(x/abs(x), x, 0, dir='+')] == [-1, 1] def test_T14(): x = symbols('x', real=True) assert limit(atan(-log(x)), x, 0, dir='+') == pi/2 def test_U1(): x = symbols('x', real=True) assert diff(abs(x), x) == sign(x) def test_U2(): f = Lambda(x, Piecewise((-x, x < 0), (x, x >= 0))) assert diff(f(x), x) == Piecewise((-1, x < 0), (1, x >= 0)) def test_U3(): f = Lambda(x, Piecewise((x**2 - 1, x == 1), (x**3, x != 1))) f1 = Lambda(x, diff(f(x), x)) assert f1(x) == 3*x**2 assert f1(1) == 3 @XFAIL def test_U4(): n = symbols('n', integer=True, positive=True) x = symbols('x', real=True) d = diff(x**n, x, n) assert d.rewrite(factorial) == factorial(n) def test_U5(): # issue 6681 t = symbols('t') ans = ( Derivative(f(g(t)), g(t))*Derivative(g(t), (t, 2)) + Derivative(f(g(t)), (g(t), 2))*Derivative(g(t), t)**2) assert f(g(t)).diff(t, 2) == ans assert ans.doit() == ans def test_U6(): h = Function('h') T = integrate(f(y), (y, h(x), g(x))) assert T.diff(x) == ( f(g(x))*Derivative(g(x), x) - f(h(x))*Derivative(h(x), x)) @XFAIL def test_U7(): p, t = symbols('p t', real=True) # Exact differential => d(V(P, T)) => dV/dP DP + dV/dT DT # raises ValueError: Since there is more than one variable in the # expression, the variable(s) of differentiation must be supplied to # differentiate f(p,t) diff(f(p, t)) def test_U8(): x, y = symbols('x y', real=True) eq = cos(x*y) + x # If SymPy had implicit_diff() function this hack could be avoided # TODO: Replace solve with solveset, current test fails for solveset assert idiff(y - eq, y, x) == (-y*sin(x*y) + 1)/(x*sin(x*y) + 1) def test_U9(): # Wester sample case for Maple: # O29 := diff(f(x, y), x) + diff(f(x, y), y); # /d \ /d \ # |-- f(x, y)| + |-- f(x, y)| # \dx / \dy / # # O30 := factor(subs(f(x, y) = g(x^2 + y^2), %)); # 2 2 # 2 D(g)(x + y ) (x + y) x, y = symbols('x y', real=True) su = diff(f(x, y), x) + diff(f(x, y), y) s2 = su.subs(f(x, y), g(x**2 + y**2)) s3 = s2.doit().factor() # Subs not performed, s3 = 2*(x + y)*Subs(Derivative( # g(_xi_1), _xi_1), _xi_1, x**2 + y**2) # Derivative(g(x*2 + y**2), x**2 + y**2) is not valid in SymPy, # and probably will remain that way. You can take derivatives with respect # to other expressions only if they are atomic, like a symbol or a # function. # D operator should be added to SymPy # See https://github.com/sympy/sympy/issues/4719. assert s3 == (x + y)*Subs(Derivative(g(x), x), x, x**2 + y**2)*2 def test_U10(): # see issue 2519: assert residue((z**3 + 5)/((z**4 - 1)*(z + 1)), z, -1) == R(-9, 4) @XFAIL def test_U11(): # assert (2*dx + dz) ^ (3*dx + dy + dz) ^ (dx + dy + 4*dz) == 8*dx ^ dy ^dz raise NotImplementedError @XFAIL def test_U12(): # Wester sample case: # (c41) /* d(3 x^5 dy /\ dz + 5 x y^2 dz /\ dx + 8 z dx /\ dy) # => (15 x^4 + 10 x y + 8) dx /\ dy /\ dz */ # factor(ext_diff(3*x^5 * dy ~ dz + 5*x*y^2 * dz ~ dx + 8*z * dx ~ dy)); # 4 # (d41) (10 x y + 15 x + 8) dx dy dz raise NotImplementedError( "External diff of differential form not supported") def test_U13(): assert minimum(x**4 - x + 1, x) == -3*2**R(1,3)/8 + 1 @XFAIL def test_U14(): #f = 1/(x**2 + y**2 + 1) #assert [minimize(f), maximize(f)] == [0,1] raise NotImplementedError("minimize(), maximize() not supported") @XFAIL def test_U15(): raise NotImplementedError("minimize() not supported and also solve does \ not support multivariate inequalities") @XFAIL def test_U16(): raise NotImplementedError("minimize() not supported in SymPy and also \ solve does not support multivariate inequalities") @XFAIL def test_U17(): raise NotImplementedError("Linear programming, symbolic simplex not \ supported in SymPy") def test_V1(): x = symbols('x', real=True) assert integrate(abs(x), x) == Piecewise((-x**2/2, x <= 0), (x**2/2, True)) def test_V2(): assert integrate(Piecewise((-x, x < 0), (x, x >= 0)), x ) == Piecewise((-x**2/2, x < 0), (x**2/2, True)) def test_V3(): assert integrate(1/(x**3 + 2),x).diff().simplify() == 1/(x**3 + 2) def test_V4(): assert integrate(2**x/sqrt(1 + 4**x), x) == asinh(2**x)/log(2) @XFAIL def test_V5(): # Returns (-45*x**2 + 80*x - 41)/(5*sqrt(2*x - 1)*(4*x**2 - 4*x + 1)) assert (integrate((3*x - 5)**2/(2*x - 1)**R(7, 2), x).simplify() == (-41 + 80*x - 45*x**2)/(5*(2*x - 1)**R(5, 2))) @XFAIL def test_V6(): # returns RootSum(40*_z**2 - 1, Lambda(_i, _i*log(-4*_i + exp(-m*x))))/m assert (integrate(1/(2*exp(m*x) - 5*exp(-m*x)), x) == sqrt(10)*( log(2*exp(m*x) - sqrt(10)) - log(2*exp(m*x) + sqrt(10)))/(20*m)) def test_V7(): r1 = integrate(sinh(x)**4/cosh(x)**2) assert r1.simplify() == x*R(-3, 2) + sinh(x)**3/(2*cosh(x)) + 3*tanh(x)/2 @XFAIL def test_V8_V9(): #Macsyma test case: #(c27) /* This example involves several symbolic parameters # => 1/sqrt(b^2 - a^2) log([sqrt(b^2 - a^2) tan(x/2) + a + b]/ # [sqrt(b^2 - a^2) tan(x/2) - a - b]) (a^2 < b^2) # [Gradshteyn and Ryzhik 2.553(3)] */ #assume(b^2 > a^2)$ #(c28) integrate(1/(a + b*cos(x)), x); #(c29) trigsimp(ratsimp(diff(%, x))); # 1 #(d29) ------------ # b cos(x) + a raise NotImplementedError( "Integrate with assumption not supported") def test_V10(): assert integrate(1/(3 + 3*cos(x) + 4*sin(x)), x) == log(4*tan(x/2) + 3)/4 def test_V11(): r1 = integrate(1/(4 + 3*cos(x) + 4*sin(x)), x) r2 = factor(r1) assert (logcombine(r2, force=True) == log(((tan(x/2) + 1)/(tan(x/2) + 7))**R(1, 3))) def test_V12(): r1 = integrate(1/(5 + 3*cos(x) + 4*sin(x)), x) assert r1 == -1/(tan(x/2) + 2) @XFAIL def test_V13(): r1 = integrate(1/(6 + 3*cos(x) + 4*sin(x)), x) # expression not simplified, returns: -sqrt(11)*I*log(tan(x/2) + 4/3 # - sqrt(11)*I/3)/11 + sqrt(11)*I*log(tan(x/2) + 4/3 + sqrt(11)*I/3)/11 assert r1.simplify() == 2*sqrt(11)*atan(sqrt(11)*(3*tan(x/2) + 4)/11)/11 @slow @XFAIL def test_V14(): r1 = integrate(log(abs(x**2 - y**2)), x) # Piecewise result does not simplify to the desired result. assert (r1.simplify() == x*log(abs(x**2 - y**2)) + y*log(x + y) - y*log(x - y) - 2*x) def test_V15(): r1 = integrate(x*acot(x/y), x) assert simplify(r1 - (x*y + (x**2 + y**2)*acot(x/y))/2) == 0 @XFAIL def test_V16(): # Integral not calculated assert integrate(cos(5*x)*Ci(2*x), x) == Ci(2*x)*sin(5*x)/5 - (Si(3*x) + Si(7*x))/10 @XFAIL def test_V17(): r1 = integrate((diff(f(x), x)*g(x) - f(x)*diff(g(x), x))/(f(x)**2 - g(x)**2), x) # integral not calculated assert simplify(r1 - (f(x) - g(x))/(f(x) + g(x))/2) == 0 @XFAIL def test_W1(): # The function has a pole at y. # The integral has a Cauchy principal value of zero but SymPy returns -I*pi # https://github.com/sympy/sympy/issues/7159 assert integrate(1/(x - y), (x, y - 1, y + 1)) == 0 @XFAIL def test_W2(): # The function has a pole at y. # The integral is divergent but SymPy returns -2 # https://github.com/sympy/sympy/issues/7160 # Test case in Macsyma: # (c6) errcatch(integrate(1/(x - a)^2, x, a - 1, a + 1)); # Integral is divergent assert integrate(1/(x - y)**2, (x, y - 1, y + 1)) is zoo @XFAIL @slow def test_W3(): # integral is not calculated # https://github.com/sympy/sympy/issues/7161 assert integrate(sqrt(x + 1/x - 2), (x, 0, 1)) == R(4, 3) @XFAIL @slow def test_W4(): # integral is not calculated assert integrate(sqrt(x + 1/x - 2), (x, 1, 2)) == -2*sqrt(2)/3 + R(4, 3) @XFAIL @slow def test_W5(): # integral is not calculated assert integrate(sqrt(x + 1/x - 2), (x, 0, 2)) == -2*sqrt(2)/3 + R(8, 3) @XFAIL @slow def test_W6(): # integral is not calculated assert integrate(sqrt(2 - 2*cos(2*x))/2, (x, pi*R(-3, 4), -pi/4)) == sqrt(2) def test_W7(): a = symbols('a', positive=True) r1 = integrate(cos(x)/(x**2 + a**2), (x, -oo, oo)) assert r1.simplify() == pi*exp(-a)/a @XFAIL def test_W8(): # Test case in Mathematica: # In[19]:= Integrate[t^(a - 1)/(1 + t), {t, 0, Infinity}, # Assumptions -> 0 < a < 1] # Out[19]= Pi Csc[a Pi] raise NotImplementedError( "Integrate with assumption 0 < a < 1 not supported") @XFAIL @slow def test_W9(): # Integrand with a residue at infinity => -2 pi [sin(pi/5) + sin(2pi/5)] # (principal value) [Levinson and Redheffer, p. 234] *) r1 = integrate(5*x**3/(1 + x + x**2 + x**3 + x**4), (x, -oo, oo)) r2 = r1.doit() assert r2 == -2*pi*(sqrt(-sqrt(5)/8 + 5/8) + sqrt(sqrt(5)/8 + 5/8)) @XFAIL def test_W10(): # integrate(1/[1 + x + x^2 + ... + x^(2 n)], x = -infinity..infinity) = # 2 pi/(2 n + 1) [1 + cos(pi/[2 n + 1])] csc(2 pi/[2 n + 1]) # [Levinson and Redheffer, p. 255] => 2 pi/5 [1 + cos(pi/5)] csc(2 pi/5) */ r1 = integrate(x/(1 + x + x**2 + x**4), (x, -oo, oo)) r2 = r1.doit() assert r2 == 2*pi*(sqrt(5)/4 + 5/4)*csc(pi*R(2, 5))/5 @XFAIL def test_W11(): # integral not calculated assert (integrate(sqrt(1 - x**2)/(1 + x**2), (x, -1, 1)) == pi*(-1 + sqrt(2))) def test_W12(): p = symbols('p', positive=True) q = symbols('q', real=True) r1 = integrate(x*exp(-p*x**2 + 2*q*x), (x, -oo, oo)) assert r1.simplify() == sqrt(pi)*q*exp(q**2/p)/p**R(3, 2) @XFAIL def test_W13(): # Integral not calculated. Expected result is 2*(Euler_mascheroni_constant) r1 = integrate(1/log(x) + 1/(1 - x) - log(log(1/x)), (x, 0, 1)) assert r1 == 2*EulerGamma def test_W14(): assert integrate(sin(x)/x*exp(2*I*x), (x, -oo, oo)) == 0 @XFAIL def test_W15(): # integral not calculated assert integrate(log(gamma(x))*cos(6*pi*x), (x, 0, 1)) == R(1, 12) def test_W16(): assert integrate((1 + x)**3*legendre_poly(1, x)*legendre_poly(2, x), (x, -1, 1)) == R(36, 35) def test_W17(): a, b = symbols('a b', positive=True) assert integrate(exp(-a*x)*besselj(0, b*x), (x, 0, oo)) == 1/(b*sqrt(a**2/b**2 + 1)) def test_W18(): assert integrate((besselj(1, x)/x)**2, (x, 0, oo)) == 4/(3*pi) @XFAIL def test_W19(): # Integral not calculated # Expected result is (cos 7 - 1)/7 [Gradshteyn and Ryzhik 6.782(3)] assert integrate(Ci(x)*besselj(0, 2*sqrt(7*x)), (x, 0, oo)) == (cos(7) - 1)/7 @XFAIL def test_W20(): # integral not calculated assert (integrate(x**2*polylog(3, 1/(x + 1)), (x, 0, 1)) == -pi**2/36 - R(17, 108) + zeta(3)/4 + (-pi**2/2 - 4*log(2) + log(2)**2 + 35/3)*log(2)/9) def test_W21(): assert abs(N(integrate(x**2*polylog(3, 1/(x + 1)), (x, 0, 1))) - 0.210882859565594) < 1e-15 def test_W22(): t, u = symbols('t u', real=True) s = Lambda(x, Piecewise((1, And(x >= 1, x <= 2)), (0, True))) assert integrate(s(t)*cos(t), (t, 0, u)) == Piecewise( (0, u < 0), (-sin(Min(1, u)) + sin(Min(2, u)), True)) @slow def test_W23(): a, b = symbols('a b', positive=True) r1 = integrate(integrate(x/(x**2 + y**2), (x, a, b)), (y, -oo, oo)) assert r1.collect(pi).cancel() == -pi*a + pi*b def test_W23b(): # like W23 but limits are reversed a, b = symbols('a b', positive=True) r2 = integrate(integrate(x/(x**2 + y**2), (y, -oo, oo)), (x, a, b)) assert r2.collect(pi) == pi*(-a + b) @XFAIL @slow def test_W24(): if ON_TRAVIS: skip("Too slow for travis.") # Not that slow, but does not fully evaluate so simplify is slow. # Maybe also require doit() x, y = symbols('x y', real=True) r1 = integrate(integrate(sqrt(x**2 + y**2), (x, 0, 1)), (y, 0, 1)) assert (r1 - (sqrt(2) + asinh(1))/3).simplify() == 0 @XFAIL @slow def test_W25(): if ON_TRAVIS: skip("Too slow for travis.") a, x, y = symbols('a x y', real=True) i1 = integrate( sin(a)*sin(y)/sqrt(1 - sin(a)**2*sin(x)**2*sin(y)**2), (x, 0, pi/2)) i2 = integrate(i1, (y, 0, pi/2)) assert (i2 - pi*a/2).simplify() == 0 def test_W26(): x, y = symbols('x y', real=True) assert integrate(integrate(abs(y - x**2), (y, 0, 2)), (x, -1, 1)) == R(46, 15) def test_W27(): a, b, c = symbols('a b c') assert integrate(integrate(integrate(1, (z, 0, c*(1 - x/a - y/b))), (y, 0, b*(1 - x/a))), (x, 0, a)) == a*b*c/6 def test_X1(): v, c = symbols('v c', real=True) assert (series(1/sqrt(1 - (v/c)**2), v, x0=0, n=8) == 5*v**6/(16*c**6) + 3*v**4/(8*c**4) + v**2/(2*c**2) + 1 + O(v**8)) def test_X2(): v, c = symbols('v c', real=True) s1 = series(1/sqrt(1 - (v/c)**2), v, x0=0, n=8) assert (1/s1**2).series(v, x0=0, n=8) == -v**2/c**2 + 1 + O(v**8) def test_X3(): s1 = (sin(x).series()/cos(x).series()).series() s2 = tan(x).series() assert s2 == x + x**3/3 + 2*x**5/15 + O(x**6) assert s1 == s2 def test_X4(): s1 = log(sin(x)/x).series() assert s1 == -x**2/6 - x**4/180 + O(x**6) assert log(series(sin(x)/x)).series() == s1 @XFAIL def test_X5(): # test case in Mathematica syntax: # In[21]:= (* => [a f'(a d) + g(b d) + integrate(h(c y), y = 0..d)] # + [a^2 f''(a d) + b g'(b d) + h(c d)] (x - d) *) # In[22]:= D[f[a*x], x] + g[b*x] + Integrate[h[c*y], {y, 0, x}] # Out[22]= g[b x] + Integrate[h[c y], {y, 0, x}] + a f'[a x] # In[23]:= Series[%, {x, d, 1}] # Out[23]= (g[b d] + Integrate[h[c y], {y, 0, d}] + a f'[a d]) + # 2 2 # (h[c d] + b g'[b d] + a f''[a d]) (-d + x) + O[-d + x] h = Function('h') a, b, c, d = symbols('a b c d', real=True) # series() raises NotImplementedError: # The _eval_nseries method should be added to <class # 'sympy.core.function.Subs'> to give terms up to O(x**n) at x=0 series(diff(f(a*x), x) + g(b*x) + integrate(h(c*y), (y, 0, x)), x, x0=d, n=2) # assert missing, until exception is removed def test_X6(): # Taylor series of nonscalar objects (noncommutative multiplication) # expected result => (B A - A B) t^2/2 + O(t^3) [Stanly Steinberg] a, b = symbols('a b', commutative=False, scalar=False) assert (series(exp((a + b)*x) - exp(a*x) * exp(b*x), x, x0=0, n=3) == x**2*(-a*b/2 + b*a/2) + O(x**3)) def test_X7(): # => sum( Bernoulli[k]/k! x^(k - 2), k = 1..infinity ) # = 1/x^2 - 1/(2 x) + 1/12 - x^2/720 + x^4/30240 + O(x^6) # [Levinson and Redheffer, p. 173] assert (series(1/(x*(exp(x) - 1)), x, 0, 7) == x**(-2) - 1/(2*x) + R(1, 12) - x**2/720 + x**4/30240 - x**6/1209600 + O(x**7)) def test_X8(): # Puiseux series (terms with fractional degree): # => 1/sqrt(x - 3/2 pi) + (x - 3/2 pi)^(3/2) / 12 + O([x - 3/2 pi]^(7/2)) # see issue 7167: x = symbols('x', real=True) assert (series(sqrt(sec(x)), x, x0=pi*3/2, n=4) == 1/sqrt(x - pi*R(3, 2)) + (x - pi*R(3, 2))**R(3, 2)/12 + (x - pi*R(3, 2))**R(7, 2)/160 + O((x - pi*R(3, 2))**4, (x, pi*R(3, 2)))) def test_X9(): assert (series(x**x, x, x0=0, n=4) == 1 + x*log(x) + x**2*log(x)**2/2 + x**3*log(x)**3/6 + O(x**4*log(x)**4)) def test_X10(): z, w = symbols('z w') assert (series(log(sinh(z)) + log(cosh(z + w)), z, x0=0, n=2) == log(cosh(w)) + log(z) + z*sinh(w)/cosh(w) + O(z**2)) def test_X11(): z, w = symbols('z w') assert (series(log(sinh(z) * cosh(z + w)), z, x0=0, n=2) == log(cosh(w)) + log(z) + z*sinh(w)/cosh(w) + O(z**2)) @XFAIL def test_X12(): # Look at the generalized Taylor series around x = 1 # Result => (x - 1)^a/e^b [1 - (a + 2 b) (x - 1) / 2 + O((x - 1)^2)] a, b, x = symbols('a b x', real=True) # series returns O(log(x-1)**2) # https://github.com/sympy/sympy/issues/7168 assert (series(log(x)**a*exp(-b*x), x, x0=1, n=2) == (x - 1)**a/exp(b)*(1 - (a + 2*b)*(x - 1)/2 + O((x - 1)**2))) def test_X13(): assert series(sqrt(2*x**2 + 1), x, x0=oo, n=1) == sqrt(2)*x + O(1/x, (x, oo)) @XFAIL def test_X14(): # Wallis' product => 1/sqrt(pi n) + ... [Knopp, p. 385] assert series(1/2**(2*n)*binomial(2*n, n), n, x==oo, n=1) == 1/(sqrt(pi)*sqrt(n)) + O(1/x, (x, oo)) @SKIP("https://github.com/sympy/sympy/issues/7164") def test_X15(): # => 0!/x - 1!/x^2 + 2!/x^3 - 3!/x^4 + O(1/x^5) [Knopp, p. 544] x, t = symbols('x t', real=True) # raises RuntimeError: maximum recursion depth exceeded # https://github.com/sympy/sympy/issues/7164 # 2019-02-17: Raises # PoleError: # Asymptotic expansion of Ei around [-oo] is not implemented. e1 = integrate(exp(-t)/t, (t, x, oo)) assert (series(e1, x, x0=oo, n=5) == 6/x**4 + 2/x**3 - 1/x**2 + 1/x + O(x**(-5), (x, oo))) def test_X16(): # Multivariate Taylor series expansion => 1 - (x^2 + 2 x y + y^2)/2 + O(x^4) assert (series(cos(x + y), x + y, x0=0, n=4) == 1 - (x + y)**2/2 + O(x**4 + x**3*y + x**2*y**2 + x*y**3 + y**4, x, y)) @XFAIL def test_X17(): # Power series (compute the general formula) # (c41) powerseries(log(sin(x)/x), x, 0); # /aquarius/data2/opt/local/macsyma_422/library1/trgred.so being loaded. # inf # ==== i1 2 i1 2 i1 # \ (- 1) 2 bern(2 i1) x # (d41) > ------------------------------ # / 2 i1 (2 i1)! # ==== # i1 = 1 # fps does not calculate assert fps(log(sin(x)/x)) == \ Sum((-1)**k*2**(2*k - 1)*bernoulli(2*k)*x**(2*k)/(k*factorial(2*k)), (k, 1, oo)) @XFAIL def test_X18(): # Power series (compute the general formula). Maple FPS: # > FormalPowerSeries(exp(-x)*sin(x), x = 0); # infinity # ----- (1/2 k) k # \ 2 sin(3/4 k Pi) x # ) ------------------------- # / k! # ----- # # Now, SymPy returns # oo # _____ # \ ` # \ / k k\ # \ k |I*(-1 - I) I*(-1 + I) | # \ x *|----------- - -----------| # / \ 2 2 / # / ------------------------------ # / k! # /____, # k = 0 k = Dummy('k') assert fps(exp(-x)*sin(x)) == \ Sum(2**(S.Half*k)*sin(R(3, 4)*k*pi)*x**k/factorial(k), (k, 0, oo)) @XFAIL def test_X19(): # (c45) /* Derive an explicit Taylor series solution of y as a function of # x from the following implicit relation: # y = x - 1 + (x - 1)^2/2 + 2/3 (x - 1)^3 + (x - 1)^4 + # 17/10 (x - 1)^5 + ... # */ # x = sin(y) + cos(y); # Time= 0 msecs # (d45) x = sin(y) + cos(y) # # (c46) taylor_revert(%, y, 7); raise NotImplementedError("Solve using series not supported. \ Inverse Taylor series expansion also not supported") @XFAIL def test_X20(): # Pade (rational function) approximation => (2 - x)/(2 + x) # > numapprox[pade](exp(-x), x = 0, [1, 1]); # bytes used=9019816, alloc=3669344, time=13.12 # 1 - 1/2 x # --------- # 1 + 1/2 x # mpmath support numeric Pade approximant but there is # no symbolic implementation in SymPy # https://en.wikipedia.org/wiki/Pad%C3%A9_approximant raise NotImplementedError("Symbolic Pade approximant not supported") def test_X21(): """ Test whether `fourier_series` of x periodical on the [-p, p] interval equals `- (2 p / pi) sum( (-1)^n / n sin(n pi x / p), n = 1..infinity )`. """ p = symbols('p', positive=True) n = symbols('n', positive=True, integer=True) s = fourier_series(x, (x, -p, p)) # All cosine coefficients are equal to 0 assert s.an.formula == 0 # Check for sine coefficients assert s.bn.formula.subs(s.bn.variables[0], 0) == 0 assert s.bn.formula.subs(s.bn.variables[0], n) == \ -2*p/pi * (-1)**n / n * sin(n*pi*x/p) @XFAIL def test_X22(): # (c52) /* => p / 2 # - (2 p / pi^2) sum( [1 - (-1)^n] cos(n pi x / p) / n^2, # n = 1..infinity ) */ # fourier_series(abs(x), x, p); # p # (e52) a = - # 0 2 # # %nn # (2 (- 1) - 2) p # (e53) a = ------------------ # %nn 2 2 # %pi %nn # # (e54) b = 0 # %nn # # Time= 5290 msecs # inf %nn %pi %nn x # ==== (2 (- 1) - 2) cos(---------) # \ p # p > ------------------------------- # / 2 # ==== %nn # %nn = 1 p # (d54) ----------------------------------------- + - # 2 2 # %pi raise NotImplementedError("Fourier series not supported") def test_Y1(): t = symbols('t', positive=True) w = symbols('w', real=True) s = symbols('s') F, _, _ = laplace_transform(cos((w - 1)*t), t, s) assert F == s/(s**2 + (w - 1)**2) def test_Y2(): t = symbols('t', positive=True) w = symbols('w', real=True) s = symbols('s') f = inverse_laplace_transform(s/(s**2 + (w - 1)**2), s, t) assert f == cos(t*(w - 1)) def test_Y3(): t = symbols('t', positive=True) w = symbols('w', real=True) s = symbols('s') F, _, _ = laplace_transform(sinh(w*t)*cosh(w*t), t, s) assert F == w/(s**2 - 4*w**2) def test_Y4(): t = symbols('t', positive=True) s = symbols('s') F, _, _ = laplace_transform(erf(3/sqrt(t)), t, s) assert F == (1 - exp(-6*sqrt(s)))/s def test_Y5_Y6(): # Solve y'' + y = 4 [H(t - 1) - H(t - 2)], y(0) = 1, y'(0) = 0 where H is the # Heaviside (unit step) function (the RHS describes a pulse of magnitude 4 and # duration 1). See David A. Sanchez, Richard C. Allen, Jr. and Walter T. # Kyner, _Differential Equations: An Introduction_, Addison-Wesley Publishing # Company, 1983, p. 211. First, take the Laplace transform of the ODE # => s^2 Y(s) - s + Y(s) = 4/s [e^(-s) - e^(-2 s)] # where Y(s) is the Laplace transform of y(t) t = symbols('t', positive=True) s = symbols('s') y = Function('y') F, _, _ = laplace_transform(diff(y(t), t, 2) + y(t) - 4*(Heaviside(t - 1) - Heaviside(t - 2)), t, s) assert (F == s**2*LaplaceTransform(y(t), t, s) - s*y(0) + LaplaceTransform(y(t), t, s) - Subs(Derivative(y(t), t), t, 0) - 4*exp(-s)/s + 4*exp(-2*s)/s) # TODO implement second part of test case # Now, solve for Y(s) and then take the inverse Laplace transform # => Y(s) = s/(s^2 + 1) + 4 [1/s - s/(s^2 + 1)] [e^(-s) - e^(-2 s)] # => y(t) = cos t + 4 {[1 - cos(t - 1)] H(t - 1) - [1 - cos(t - 2)] H(t - 2)} @XFAIL def test_Y7(): # What is the Laplace transform of an infinite square wave? # => 1/s + 2 sum( (-1)^n e^(- s n a)/s, n = 1..infinity ) # [Sanchez, Allen and Kyner, p. 213] t = symbols('t', positive=True) a = symbols('a', real=True) s = symbols('s') F, _, _ = laplace_transform(1 + 2*Sum((-1)**n*Heaviside(t - n*a), (n, 1, oo)), t, s) # returns 2*LaplaceTransform(Sum((-1)**n*Heaviside(-a*n + t), # (n, 1, oo)), t, s) + 1/s # https://github.com/sympy/sympy/issues/7177 assert F == 2*Sum((-1)**n*exp(-a*n*s)/s, (n, 1, oo)) + 1/s @XFAIL def test_Y8(): assert fourier_transform(1, x, z) == DiracDelta(z) def test_Y9(): assert (fourier_transform(exp(-9*x**2), x, z) == sqrt(pi)*exp(-pi**2*z**2/9)/3) def test_Y10(): assert (fourier_transform(abs(x)*exp(-3*abs(x)), x, z).cancel() == (-8*pi**2*z**2 + 18)/(16*pi**4*z**4 + 72*pi**2*z**2 + 81)) @SKIP("https://github.com/sympy/sympy/issues/7181") @slow def test_Y11(): # => pi cot(pi s) (0 < Re s < 1) [Gradshteyn and Ryzhik 17.43(5)] x, s = symbols('x s') # raises RuntimeError: maximum recursion depth exceeded # https://github.com/sympy/sympy/issues/7181 # Update 2019-02-17 raises: # TypeError: cannot unpack non-iterable MellinTransform object F, _, _ = mellin_transform(1/(1 - x), x, s) assert F == pi*cot(pi*s) @XFAIL def test_Y12(): # => 2^(s - 4) gamma(s/2)/gamma(4 - s/2) (0 < Re s < 1) # [Gradshteyn and Ryzhik 17.43(16)] x, s = symbols('x s') # returns Wrong value -2**(s - 4)*gamma(s/2 - 3)/gamma(-s/2 + 1) # https://github.com/sympy/sympy/issues/7182 F, _, _ = mellin_transform(besselj(3, x)/x**3, x, s) assert F == -2**(s - 4)*gamma(s/2)/gamma(-s/2 + 4) @XFAIL def test_Y13(): # Z[H(t - m T)] => z/[z^m (z - 1)] (H is the Heaviside (unit step) function) z raise NotImplementedError("z-transform not supported") @XFAIL def test_Y14(): # Z[H(t - m T)] => z/[z^m (z - 1)] (H is the Heaviside (unit step) function) raise NotImplementedError("z-transform not supported") def test_Z1(): r = Function('r') assert (rsolve(r(n + 2) - 2*r(n + 1) + r(n) - 2, r(n), {r(0): 1, r(1): m}).simplify() == n**2 + n*(m - 2) + 1) def test_Z2(): r = Function('r') assert (rsolve(r(n) - (5*r(n - 1) - 6*r(n - 2)), r(n), {r(0): 0, r(1): 1}) == -2**n + 3**n) def test_Z3(): # => r(n) = Fibonacci[n + 1] [Cohen, p. 83] r = Function('r') # recurrence solution is correct, Wester expects it to be simplified to # fibonacci(n+1), but that is quite hard expected = ((S(1)/2 - sqrt(5)/2)**n*(S(1)/2 - sqrt(5)/10) + (S(1)/2 + sqrt(5)/2)**n*(sqrt(5)/10 + S(1)/2)) sol = rsolve(r(n) - (r(n - 1) + r(n - 2)), r(n), {r(1): 1, r(2): 2}) assert sol == expected @XFAIL def test_Z4(): # => [c^(n+1) [c^(n+1) - 2 c - 2] + (n+1) c^2 + 2 c - n] / [(c-1)^3 (c+1)] # [Joan Z. Yu and Robert Israel in sci.math.symbolic] r = Function('r') c = symbols('c') # raises ValueError: Polynomial or rational function expected, # got '(c**2 - c**n)/(c - c**n) s = rsolve(r(n) - ((1 + c - c**(n-1) - c**(n+1))/(1 - c**n)*r(n - 1) - c*(1 - c**(n-2))/(1 - c**(n-1))*r(n - 2) + 1), r(n), {r(1): 1, r(2): (2 + 2*c + c**2)/(1 + c)}) assert (s - (c*(n + 1)*(c*(n + 1) - 2*c - 2) + (n + 1)*c**2 + 2*c - n)/((c-1)**3*(c+1)) == 0) @XFAIL def test_Z5(): # Second order ODE with initial conditions---solve directly # transform: f(t) = sin(2 t)/8 - t cos(2 t)/4 C1, C2 = symbols('C1 C2') # initial conditions not supported, this is a manual workaround # https://github.com/sympy/sympy/issues/4720 eq = Derivative(f(x), x, 2) + 4*f(x) - sin(2*x) sol = dsolve(eq, f(x)) f0 = Lambda(x, sol.rhs) assert f0(x) == C2*sin(2*x) + (C1 - x/4)*cos(2*x) f1 = Lambda(x, diff(f0(x), x)) # TODO: Replace solve with solveset, when it works for solveset const_dict = solve((f0(0), f1(0))) result = f0(x).subs(C1, const_dict[C1]).subs(C2, const_dict[C2]) assert result == -x*cos(2*x)/4 + sin(2*x)/8 # Result is OK, but ODE solving with initial conditions should be # supported without all this manual work raise NotImplementedError('ODE solving with initial conditions \ not supported') @XFAIL def test_Z6(): # Second order ODE with initial conditions---solve using Laplace # transform: f(t) = sin(2 t)/8 - t cos(2 t)/4 t = symbols('t', positive=True) s = symbols('s') eq = Derivative(f(t), t, 2) + 4*f(t) - sin(2*t) F, _, _ = laplace_transform(eq, t, s) # Laplace transform for diff() not calculated # https://github.com/sympy/sympy/issues/7176 assert (F == s**2*LaplaceTransform(f(t), t, s) + 4*LaplaceTransform(f(t), t, s) - 2/(s**2 + 4)) # rest of test case not implemented
ff8384ccb70ab0148d4a28b9b9acb9b2d4fce56afa6401fb7a4679e7a0e979d1
import itertools from sympy.core import S from sympy.core.add import Add from sympy.core.containers import Tuple from sympy.core.function import Function from sympy.core.mul import Mul from sympy.core.numbers import Number, Rational from sympy.core.power import Pow from sympy.core.sorting import default_sort_key from sympy.core.symbol import Symbol from sympy.core.sympify import SympifyError from sympy.printing.conventions import requires_partial from sympy.printing.precedence import PRECEDENCE, precedence, precedence_traditional from sympy.printing.printer import Printer, print_function from sympy.printing.str import sstr from sympy.utilities.iterables import has_variety from sympy.utilities.exceptions import SymPyDeprecationWarning from sympy.printing.pretty.stringpict import prettyForm, stringPict from sympy.printing.pretty.pretty_symbology import hobj, vobj, xobj, \ xsym, pretty_symbol, pretty_atom, pretty_use_unicode, greek_unicode, U, \ pretty_try_use_unicode, annotated # rename for usage from outside pprint_use_unicode = pretty_use_unicode pprint_try_use_unicode = pretty_try_use_unicode class PrettyPrinter(Printer): """Printer, which converts an expression into 2D ASCII-art figure.""" printmethod = "_pretty" _default_settings = { "order": None, "full_prec": "auto", "use_unicode": None, "wrap_line": True, "num_columns": None, "use_unicode_sqrt_char": True, "root_notation": True, "mat_symbol_style": "plain", "imaginary_unit": "i", "perm_cyclic": True } def __init__(self, settings=None): Printer.__init__(self, settings) if not isinstance(self._settings['imaginary_unit'], str): raise TypeError("'imaginary_unit' must a string, not {}".format(self._settings['imaginary_unit'])) elif self._settings['imaginary_unit'] not in ("i", "j"): raise ValueError("'imaginary_unit' must be either 'i' or 'j', not '{}'".format(self._settings['imaginary_unit'])) def emptyPrinter(self, expr): return prettyForm(str(expr)) @property def _use_unicode(self): if self._settings['use_unicode']: return True else: return pretty_use_unicode() def doprint(self, expr): return self._print(expr).render(**self._settings) # empty op so _print(stringPict) returns the same def _print_stringPict(self, e): return e def _print_basestring(self, e): return prettyForm(e) def _print_atan2(self, e): pform = prettyForm(*self._print_seq(e.args).parens()) pform = prettyForm(*pform.left('atan2')) return pform def _print_Symbol(self, e, bold_name=False): symb = pretty_symbol(e.name, bold_name) return prettyForm(symb) _print_RandomSymbol = _print_Symbol def _print_MatrixSymbol(self, e): return self._print_Symbol(e, self._settings['mat_symbol_style'] == "bold") def _print_Float(self, e): # we will use StrPrinter's Float printer, but we need to handle the # full_prec ourselves, according to the self._print_level full_prec = self._settings["full_prec"] if full_prec == "auto": full_prec = self._print_level == 1 return prettyForm(sstr(e, full_prec=full_prec)) def _print_Cross(self, e): vec1 = e._expr1 vec2 = e._expr2 pform = self._print(vec2) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('MULTIPLICATION SIGN')))) pform = prettyForm(*pform.left(')')) pform = prettyForm(*pform.left(self._print(vec1))) pform = prettyForm(*pform.left('(')) return pform def _print_Curl(self, e): vec = e._expr pform = self._print(vec) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('MULTIPLICATION SIGN')))) pform = prettyForm(*pform.left(self._print(U('NABLA')))) return pform def _print_Divergence(self, e): vec = e._expr pform = self._print(vec) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('DOT OPERATOR')))) pform = prettyForm(*pform.left(self._print(U('NABLA')))) return pform def _print_Dot(self, e): vec1 = e._expr1 vec2 = e._expr2 pform = self._print(vec2) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('DOT OPERATOR')))) pform = prettyForm(*pform.left(')')) pform = prettyForm(*pform.left(self._print(vec1))) pform = prettyForm(*pform.left('(')) return pform def _print_Gradient(self, e): func = e._expr pform = self._print(func) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('NABLA')))) return pform def _print_Laplacian(self, e): func = e._expr pform = self._print(func) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('INCREMENT')))) return pform def _print_Atom(self, e): try: # print atoms like Exp1 or Pi return prettyForm(pretty_atom(e.__class__.__name__, printer=self)) except KeyError: return self.emptyPrinter(e) # Infinity inherits from Number, so we have to override _print_XXX order _print_Infinity = _print_Atom _print_NegativeInfinity = _print_Atom _print_EmptySet = _print_Atom _print_Naturals = _print_Atom _print_Naturals0 = _print_Atom _print_Integers = _print_Atom _print_Rationals = _print_Atom _print_Complexes = _print_Atom _print_EmptySequence = _print_Atom def _print_Reals(self, e): if self._use_unicode: return self._print_Atom(e) else: inf_list = ['-oo', 'oo'] return self._print_seq(inf_list, '(', ')') def _print_subfactorial(self, e): x = e.args[0] pform = self._print(x) # Add parentheses if needed if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol): pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left('!')) return pform def _print_factorial(self, e): x = e.args[0] pform = self._print(x) # Add parentheses if needed if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol): pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.right('!')) return pform def _print_factorial2(self, e): x = e.args[0] pform = self._print(x) # Add parentheses if needed if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol): pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.right('!!')) return pform def _print_binomial(self, e): n, k = e.args n_pform = self._print(n) k_pform = self._print(k) bar = ' '*max(n_pform.width(), k_pform.width()) pform = prettyForm(*k_pform.above(bar)) pform = prettyForm(*pform.above(n_pform)) pform = prettyForm(*pform.parens('(', ')')) pform.baseline = (pform.baseline + 1)//2 return pform def _print_Relational(self, e): op = prettyForm(' ' + xsym(e.rel_op) + ' ') l = self._print(e.lhs) r = self._print(e.rhs) pform = prettyForm(*stringPict.next(l, op, r), binding=prettyForm.OPEN) return pform def _print_Not(self, e): from sympy.logic.boolalg import (Equivalent, Implies) if self._use_unicode: arg = e.args[0] pform = self._print(arg) if isinstance(arg, Equivalent): return self._print_Equivalent(arg, altchar="\N{LEFT RIGHT DOUBLE ARROW WITH STROKE}") if isinstance(arg, Implies): return self._print_Implies(arg, altchar="\N{RIGHTWARDS ARROW WITH STROKE}") if arg.is_Boolean and not arg.is_Not: pform = prettyForm(*pform.parens()) return prettyForm(*pform.left("\N{NOT SIGN}")) else: return self._print_Function(e) def __print_Boolean(self, e, char, sort=True): args = e.args if sort: args = sorted(e.args, key=default_sort_key) arg = args[0] pform = self._print(arg) if arg.is_Boolean and not arg.is_Not: pform = prettyForm(*pform.parens()) for arg in args[1:]: pform_arg = self._print(arg) if arg.is_Boolean and not arg.is_Not: pform_arg = prettyForm(*pform_arg.parens()) pform = prettyForm(*pform.right(' %s ' % char)) pform = prettyForm(*pform.right(pform_arg)) return pform def _print_And(self, e): if self._use_unicode: return self.__print_Boolean(e, "\N{LOGICAL AND}") else: return self._print_Function(e, sort=True) def _print_Or(self, e): if self._use_unicode: return self.__print_Boolean(e, "\N{LOGICAL OR}") else: return self._print_Function(e, sort=True) def _print_Xor(self, e): if self._use_unicode: return self.__print_Boolean(e, "\N{XOR}") else: return self._print_Function(e, sort=True) def _print_Nand(self, e): if self._use_unicode: return self.__print_Boolean(e, "\N{NAND}") else: return self._print_Function(e, sort=True) def _print_Nor(self, e): if self._use_unicode: return self.__print_Boolean(e, "\N{NOR}") else: return self._print_Function(e, sort=True) def _print_Implies(self, e, altchar=None): if self._use_unicode: return self.__print_Boolean(e, altchar or "\N{RIGHTWARDS ARROW}", sort=False) else: return self._print_Function(e) def _print_Equivalent(self, e, altchar=None): if self._use_unicode: return self.__print_Boolean(e, altchar or "\N{LEFT RIGHT DOUBLE ARROW}") else: return self._print_Function(e, sort=True) def _print_conjugate(self, e): pform = self._print(e.args[0]) return prettyForm( *pform.above( hobj('_', pform.width())) ) def _print_Abs(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.parens('|', '|')) return pform _print_Determinant = _print_Abs def _print_floor(self, e): if self._use_unicode: pform = self._print(e.args[0]) pform = prettyForm(*pform.parens('lfloor', 'rfloor')) return pform else: return self._print_Function(e) def _print_ceiling(self, e): if self._use_unicode: pform = self._print(e.args[0]) pform = prettyForm(*pform.parens('lceil', 'rceil')) return pform else: return self._print_Function(e) def _print_Derivative(self, deriv): if requires_partial(deriv.expr) and self._use_unicode: deriv_symbol = U('PARTIAL DIFFERENTIAL') else: deriv_symbol = r'd' x = None count_total_deriv = 0 for sym, num in reversed(deriv.variable_count): s = self._print(sym) ds = prettyForm(*s.left(deriv_symbol)) count_total_deriv += num if (not num.is_Integer) or (num > 1): ds = ds**prettyForm(str(num)) if x is None: x = ds else: x = prettyForm(*x.right(' ')) x = prettyForm(*x.right(ds)) f = prettyForm( binding=prettyForm.FUNC, *self._print(deriv.expr).parens()) pform = prettyForm(deriv_symbol) if (count_total_deriv > 1) != False: pform = pform**prettyForm(str(count_total_deriv)) pform = prettyForm(*pform.below(stringPict.LINE, x)) pform.baseline = pform.baseline + 1 pform = prettyForm(*stringPict.next(pform, f)) pform.binding = prettyForm.MUL return pform def _print_Cycle(self, dc): from sympy.combinatorics.permutations import Permutation, Cycle # for Empty Cycle if dc == Cycle(): cyc = stringPict('') return prettyForm(*cyc.parens()) dc_list = Permutation(dc.list()).cyclic_form # for Identity Cycle if dc_list == []: cyc = self._print(dc.size - 1) return prettyForm(*cyc.parens()) cyc = stringPict('') for i in dc_list: l = self._print(str(tuple(i)).replace(',', '')) cyc = prettyForm(*cyc.right(l)) return cyc def _print_Permutation(self, expr): from sympy.combinatorics.permutations import Permutation, Cycle perm_cyclic = Permutation.print_cyclic if perm_cyclic is not None: SymPyDeprecationWarning( feature="Permutation.print_cyclic = {}".format(perm_cyclic), useinstead="init_printing(perm_cyclic={})" .format(perm_cyclic), issue=15201, deprecated_since_version="1.6").warn() else: perm_cyclic = self._settings.get("perm_cyclic", True) if perm_cyclic: return self._print_Cycle(Cycle(expr)) lower = expr.array_form upper = list(range(len(lower))) result = stringPict('') first = True for u, l in zip(upper, lower): s1 = self._print(u) s2 = self._print(l) col = prettyForm(*s1.below(s2)) if first: first = False else: col = prettyForm(*col.left(" ")) result = prettyForm(*result.right(col)) return prettyForm(*result.parens()) def _print_Integral(self, integral): f = integral.function # Add parentheses if arg involves addition of terms and # create a pretty form for the argument prettyF = self._print(f) # XXX generalize parens if f.is_Add: prettyF = prettyForm(*prettyF.parens()) # dx dy dz ... arg = prettyF for x in integral.limits: prettyArg = self._print(x[0]) # XXX qparens (parens if needs-parens) if prettyArg.width() > 1: prettyArg = prettyForm(*prettyArg.parens()) arg = prettyForm(*arg.right(' d', prettyArg)) # \int \int \int ... firstterm = True s = None for lim in integral.limits: # Create bar based on the height of the argument h = arg.height() H = h + 2 # XXX hack! ascii_mode = not self._use_unicode if ascii_mode: H += 2 vint = vobj('int', H) # Construct the pretty form with the integral sign and the argument pform = prettyForm(vint) pform.baseline = arg.baseline + ( H - h)//2 # covering the whole argument if len(lim) > 1: # Create pretty forms for endpoints, if definite integral. # Do not print empty endpoints. if len(lim) == 2: prettyA = prettyForm("") prettyB = self._print(lim[1]) if len(lim) == 3: prettyA = self._print(lim[1]) prettyB = self._print(lim[2]) if ascii_mode: # XXX hack # Add spacing so that endpoint can more easily be # identified with the correct integral sign spc = max(1, 3 - prettyB.width()) prettyB = prettyForm(*prettyB.left(' ' * spc)) spc = max(1, 4 - prettyA.width()) prettyA = prettyForm(*prettyA.right(' ' * spc)) pform = prettyForm(*pform.above(prettyB)) pform = prettyForm(*pform.below(prettyA)) if not ascii_mode: # XXX hack pform = prettyForm(*pform.right(' ')) if firstterm: s = pform # first term firstterm = False else: s = prettyForm(*s.left(pform)) pform = prettyForm(*arg.left(s)) pform.binding = prettyForm.MUL return pform def _print_Product(self, expr): func = expr.term pretty_func = self._print(func) horizontal_chr = xobj('_', 1) corner_chr = xobj('_', 1) vertical_chr = xobj('|', 1) if self._use_unicode: # use unicode corners horizontal_chr = xobj('-', 1) corner_chr = '\N{BOX DRAWINGS LIGHT DOWN AND HORIZONTAL}' func_height = pretty_func.height() first = True max_upper = 0 sign_height = 0 for lim in expr.limits: pretty_lower, pretty_upper = self.__print_SumProduct_Limits(lim) width = (func_height + 2) * 5 // 3 - 2 sign_lines = [horizontal_chr + corner_chr + (horizontal_chr * (width-2)) + corner_chr + horizontal_chr] for _ in range(func_height + 1): sign_lines.append(' ' + vertical_chr + (' ' * (width-2)) + vertical_chr + ' ') pretty_sign = stringPict('') pretty_sign = prettyForm(*pretty_sign.stack(*sign_lines)) max_upper = max(max_upper, pretty_upper.height()) if first: sign_height = pretty_sign.height() pretty_sign = prettyForm(*pretty_sign.above(pretty_upper)) pretty_sign = prettyForm(*pretty_sign.below(pretty_lower)) if first: pretty_func.baseline = 0 first = False height = pretty_sign.height() padding = stringPict('') padding = prettyForm(*padding.stack(*[' ']*(height - 1))) pretty_sign = prettyForm(*pretty_sign.right(padding)) pretty_func = prettyForm(*pretty_sign.right(pretty_func)) pretty_func.baseline = max_upper + sign_height//2 pretty_func.binding = prettyForm.MUL return pretty_func def __print_SumProduct_Limits(self, lim): def print_start(lhs, rhs): op = prettyForm(' ' + xsym("==") + ' ') l = self._print(lhs) r = self._print(rhs) pform = prettyForm(*stringPict.next(l, op, r)) return pform prettyUpper = self._print(lim[2]) prettyLower = print_start(lim[0], lim[1]) return prettyLower, prettyUpper def _print_Sum(self, expr): ascii_mode = not self._use_unicode def asum(hrequired, lower, upper, use_ascii): def adjust(s, wid=None, how='<^>'): if not wid or len(s) > wid: return s need = wid - len(s) if how in ('<^>', "<") or how not in list('<^>'): return s + ' '*need half = need//2 lead = ' '*half if how == ">": return " "*need + s return lead + s + ' '*(need - len(lead)) h = max(hrequired, 2) d = h//2 w = d + 1 more = hrequired % 2 lines = [] if use_ascii: lines.append("_"*(w) + ' ') lines.append(r"\%s`" % (' '*(w - 1))) for i in range(1, d): lines.append('%s\\%s' % (' '*i, ' '*(w - i))) if more: lines.append('%s)%s' % (' '*(d), ' '*(w - d))) for i in reversed(range(1, d)): lines.append('%s/%s' % (' '*i, ' '*(w - i))) lines.append("/" + "_"*(w - 1) + ',') return d, h + more, lines, more else: w = w + more d = d + more vsum = vobj('sum', 4) lines.append("_"*(w)) for i in range(0, d): lines.append('%s%s%s' % (' '*i, vsum[2], ' '*(w - i - 1))) for i in reversed(range(0, d)): lines.append('%s%s%s' % (' '*i, vsum[4], ' '*(w - i - 1))) lines.append(vsum[8]*(w)) return d, h + 2*more, lines, more f = expr.function prettyF = self._print(f) if f.is_Add: # add parens prettyF = prettyForm(*prettyF.parens()) H = prettyF.height() + 2 # \sum \sum \sum ... first = True max_upper = 0 sign_height = 0 for lim in expr.limits: prettyLower, prettyUpper = self.__print_SumProduct_Limits(lim) max_upper = max(max_upper, prettyUpper.height()) # Create sum sign based on the height of the argument d, h, slines, adjustment = asum( H, prettyLower.width(), prettyUpper.width(), ascii_mode) prettySign = stringPict('') prettySign = prettyForm(*prettySign.stack(*slines)) if first: sign_height = prettySign.height() prettySign = prettyForm(*prettySign.above(prettyUpper)) prettySign = prettyForm(*prettySign.below(prettyLower)) if first: # change F baseline so it centers on the sign prettyF.baseline -= d - (prettyF.height()//2 - prettyF.baseline) first = False # put padding to the right pad = stringPict('') pad = prettyForm(*pad.stack(*[' ']*h)) prettySign = prettyForm(*prettySign.right(pad)) # put the present prettyF to the right prettyF = prettyForm(*prettySign.right(prettyF)) # adjust baseline of ascii mode sigma with an odd height so that it is # exactly through the center ascii_adjustment = ascii_mode if not adjustment else 0 prettyF.baseline = max_upper + sign_height//2 + ascii_adjustment prettyF.binding = prettyForm.MUL return prettyF def _print_Limit(self, l): e, z, z0, dir = l.args E = self._print(e) if precedence(e) <= PRECEDENCE["Mul"]: E = prettyForm(*E.parens('(', ')')) Lim = prettyForm('lim') LimArg = self._print(z) if self._use_unicode: LimArg = prettyForm(*LimArg.right('\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{RIGHTWARDS ARROW}')) else: LimArg = prettyForm(*LimArg.right('->')) LimArg = prettyForm(*LimArg.right(self._print(z0))) if str(dir) == '+-' or z0 in (S.Infinity, S.NegativeInfinity): dir = "" else: if self._use_unicode: dir = '\N{SUPERSCRIPT PLUS SIGN}' if str(dir) == "+" else '\N{SUPERSCRIPT MINUS}' LimArg = prettyForm(*LimArg.right(self._print(dir))) Lim = prettyForm(*Lim.below(LimArg)) Lim = prettyForm(*Lim.right(E), binding=prettyForm.MUL) return Lim def _print_matrix_contents(self, e): """ This method factors out what is essentially grid printing. """ M = e # matrix Ms = {} # i,j -> pretty(M[i,j]) for i in range(M.rows): for j in range(M.cols): Ms[i, j] = self._print(M[i, j]) # h- and v- spacers hsep = 2 vsep = 1 # max width for columns maxw = [-1] * M.cols for j in range(M.cols): maxw[j] = max([Ms[i, j].width() for i in range(M.rows)] or [0]) # drawing result D = None for i in range(M.rows): D_row = None for j in range(M.cols): s = Ms[i, j] # reshape s to maxw # XXX this should be generalized, and go to stringPict.reshape ? assert s.width() <= maxw[j] # hcenter it, +0.5 to the right 2 # ( it's better to align formula starts for say 0 and r ) # XXX this is not good in all cases -- maybe introduce vbaseline? wdelta = maxw[j] - s.width() wleft = wdelta // 2 wright = wdelta - wleft s = prettyForm(*s.right(' '*wright)) s = prettyForm(*s.left(' '*wleft)) # we don't need vcenter cells -- this is automatically done in # a pretty way because when their baselines are taking into # account in .right() if D_row is None: D_row = s # first box in a row continue D_row = prettyForm(*D_row.right(' '*hsep)) # h-spacer D_row = prettyForm(*D_row.right(s)) if D is None: D = D_row # first row in a picture continue # v-spacer for _ in range(vsep): D = prettyForm(*D.below(' ')) D = prettyForm(*D.below(D_row)) if D is None: D = prettyForm('') # Empty Matrix return D def _print_MatrixBase(self, e): D = self._print_matrix_contents(e) D.baseline = D.height()//2 D = prettyForm(*D.parens('[', ']')) return D def _print_TensorProduct(self, expr): # This should somehow share the code with _print_WedgeProduct: if self._use_unicode: circled_times = "\u2297" else: circled_times = ".*" return self._print_seq(expr.args, None, None, circled_times, parenthesize=lambda x: precedence_traditional(x) <= PRECEDENCE["Mul"]) def _print_WedgeProduct(self, expr): # This should somehow share the code with _print_TensorProduct: if self._use_unicode: wedge_symbol = "\u2227" else: wedge_symbol = '/\\' return self._print_seq(expr.args, None, None, wedge_symbol, parenthesize=lambda x: precedence_traditional(x) <= PRECEDENCE["Mul"]) def _print_Trace(self, e): D = self._print(e.arg) D = prettyForm(*D.parens('(',')')) D.baseline = D.height()//2 D = prettyForm(*D.left('\n'*(0) + 'tr')) return D def _print_MatrixElement(self, expr): from sympy.matrices import MatrixSymbol if (isinstance(expr.parent, MatrixSymbol) and expr.i.is_number and expr.j.is_number): return self._print( Symbol(expr.parent.name + '_%d%d' % (expr.i, expr.j))) else: prettyFunc = self._print(expr.parent) prettyFunc = prettyForm(*prettyFunc.parens()) prettyIndices = self._print_seq((expr.i, expr.j), delimiter=', ' ).parens(left='[', right=']')[0] pform = prettyForm(binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyIndices)) # store pform parts so it can be reassembled e.g. when powered pform.prettyFunc = prettyFunc pform.prettyArgs = prettyIndices return pform def _print_MatrixSlice(self, m): # XXX works only for applied functions from sympy.matrices import MatrixSymbol prettyFunc = self._print(m.parent) if not isinstance(m.parent, MatrixSymbol): prettyFunc = prettyForm(*prettyFunc.parens()) def ppslice(x, dim): x = list(x) if x[2] == 1: del x[2] if x[0] == 0: x[0] = '' if x[1] == dim: x[1] = '' return prettyForm(*self._print_seq(x, delimiter=':')) prettyArgs = self._print_seq((ppslice(m.rowslice, m.parent.rows), ppslice(m.colslice, m.parent.cols)), delimiter=', ').parens(left='[', right=']')[0] pform = prettyForm( binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs)) # store pform parts so it can be reassembled e.g. when powered pform.prettyFunc = prettyFunc pform.prettyArgs = prettyArgs return pform def _print_Transpose(self, expr): pform = self._print(expr.arg) from sympy.matrices import MatrixSymbol if not isinstance(expr.arg, MatrixSymbol): pform = prettyForm(*pform.parens()) pform = pform**(prettyForm('T')) return pform def _print_Adjoint(self, expr): pform = self._print(expr.arg) if self._use_unicode: dag = prettyForm('\N{DAGGER}') else: dag = prettyForm('+') from sympy.matrices import MatrixSymbol if not isinstance(expr.arg, MatrixSymbol): pform = prettyForm(*pform.parens()) pform = pform**dag return pform def _print_BlockMatrix(self, B): if B.blocks.shape == (1, 1): return self._print(B.blocks[0, 0]) return self._print(B.blocks) def _print_MatAdd(self, expr): s = None for item in expr.args: pform = self._print(item) if s is None: s = pform # First element else: coeff = item.as_coeff_mmul()[0] if S(coeff).could_extract_minus_sign(): s = prettyForm(*stringPict.next(s, ' ')) pform = self._print(item) else: s = prettyForm(*stringPict.next(s, ' + ')) s = prettyForm(*stringPict.next(s, pform)) return s def _print_MatMul(self, expr): args = list(expr.args) from sympy.matrices.expressions.hadamard import HadamardProduct from sympy.matrices.expressions.kronecker import KroneckerProduct from sympy.matrices.expressions.matadd import MatAdd for i, a in enumerate(args): if (isinstance(a, (Add, MatAdd, HadamardProduct, KroneckerProduct)) and len(expr.args) > 1): args[i] = prettyForm(*self._print(a).parens()) else: args[i] = self._print(a) return prettyForm.__mul__(*args) def _print_Identity(self, expr): if self._use_unicode: return prettyForm('\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL I}') else: return prettyForm('I') def _print_ZeroMatrix(self, expr): if self._use_unicode: return prettyForm('\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ZERO}') else: return prettyForm('0') def _print_OneMatrix(self, expr): if self._use_unicode: return prettyForm('\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ONE}') else: return prettyForm('1') def _print_DotProduct(self, expr): args = list(expr.args) for i, a in enumerate(args): args[i] = self._print(a) return prettyForm.__mul__(*args) def _print_MatPow(self, expr): pform = self._print(expr.base) from sympy.matrices import MatrixSymbol if not isinstance(expr.base, MatrixSymbol): pform = prettyForm(*pform.parens()) pform = pform**(self._print(expr.exp)) return pform def _print_HadamardProduct(self, expr): from sympy.matrices.expressions.hadamard import HadamardProduct from sympy.matrices.expressions.matadd import MatAdd from sympy.matrices.expressions.matmul import MatMul if self._use_unicode: delim = pretty_atom('Ring') else: delim = '.*' return self._print_seq(expr.args, None, None, delim, parenthesize=lambda x: isinstance(x, (MatAdd, MatMul, HadamardProduct))) def _print_HadamardPower(self, expr): # from sympy import MatAdd, MatMul if self._use_unicode: circ = pretty_atom('Ring') else: circ = self._print('.') pretty_base = self._print(expr.base) pretty_exp = self._print(expr.exp) if precedence(expr.exp) < PRECEDENCE["Mul"]: pretty_exp = prettyForm(*pretty_exp.parens()) pretty_circ_exp = prettyForm( binding=prettyForm.LINE, *stringPict.next(circ, pretty_exp) ) return pretty_base**pretty_circ_exp def _print_KroneckerProduct(self, expr): from sympy.matrices.expressions.matadd import MatAdd from sympy.matrices.expressions.matmul import MatMul if self._use_unicode: delim = ' \N{N-ARY CIRCLED TIMES OPERATOR} ' else: delim = ' x ' return self._print_seq(expr.args, None, None, delim, parenthesize=lambda x: isinstance(x, (MatAdd, MatMul))) def _print_FunctionMatrix(self, X): D = self._print(X.lamda.expr) D = prettyForm(*D.parens('[', ']')) return D def _print_TransferFunction(self, expr): if not expr.num == 1: num, den = expr.num, expr.den res = Mul(num, Pow(den, -1, evaluate=False), evaluate=False) return self._print_Mul(res) else: return self._print(1)/self._print(expr.den) def _print_Series(self, expr): args = list(expr.args) for i, a in enumerate(expr.args): args[i] = prettyForm(*self._print(a).parens()) return prettyForm.__mul__(*args) def _print_MIMOSeries(self, expr): from sympy.physics.control.lti import MIMOParallel args = list(expr.args) pretty_args = [] for i, a in enumerate(reversed(args)): if (isinstance(a, MIMOParallel) and len(expr.args) > 1): expression = self._print(a) expression.baseline = expression.height()//2 pretty_args.append(prettyForm(*expression.parens())) else: expression = self._print(a) expression.baseline = expression.height()//2 pretty_args.append(expression) return prettyForm.__mul__(*pretty_args) def _print_Parallel(self, expr): s = None for item in expr.args: pform = self._print(item) if s is None: s = pform # First element else: s = prettyForm(*stringPict.next(s)) s.baseline = s.height()//2 s = prettyForm(*stringPict.next(s, ' + ')) s = prettyForm(*stringPict.next(s, pform)) return s def _print_MIMOParallel(self, expr): from sympy.physics.control.lti import TransferFunctionMatrix s = None for item in expr.args: pform = self._print(item) if s is None: s = pform # First element else: s = prettyForm(*stringPict.next(s)) s.baseline = s.height()//2 s = prettyForm(*stringPict.next(s, ' + ')) if isinstance(item, TransferFunctionMatrix): s.baseline = s.height() - 1 s = prettyForm(*stringPict.next(s, pform)) # s.baseline = s.height()//2 return s def _print_Feedback(self, expr): from sympy.physics.control import TransferFunction, Series num, tf = expr.sys1, TransferFunction(1, 1, expr.var) num_arg_list = list(num.args) if isinstance(num, Series) else [num] den_arg_list = list(expr.sys2.args) if \ isinstance(expr.sys2, Series) else [expr.sys2] if isinstance(num, Series) and isinstance(expr.sys2, Series): den = Series(*num_arg_list, *den_arg_list) elif isinstance(num, Series) and isinstance(expr.sys2, TransferFunction): if expr.sys2 == tf: den = Series(*num_arg_list) else: den = Series(*num_arg_list, expr.sys2) elif isinstance(num, TransferFunction) and isinstance(expr.sys2, Series): if num == tf: den = Series(*den_arg_list) else: den = Series(num, *den_arg_list) else: if num == tf: den = Series(*den_arg_list) elif expr.sys2 == tf: den = Series(*num_arg_list) else: den = Series(*num_arg_list, *den_arg_list) denom = prettyForm(*stringPict.next(self._print(tf))) denom.baseline = denom.height()//2 denom = prettyForm(*stringPict.next(denom, ' + ')) if expr.sign == -1 \ else prettyForm(*stringPict.next(denom, ' - ')) denom = prettyForm(*stringPict.next(denom, self._print(den))) return self._print(num)/denom def _print_MIMOFeedback(self, expr): from sympy.physics.control import MIMOSeries, TransferFunctionMatrix inv_mat = self._print(MIMOSeries(expr.sys2, expr.sys1)) plant = self._print(expr.sys1) _feedback = prettyForm(*stringPict.next(inv_mat)) _feedback = prettyForm(*stringPict.right("I + ", _feedback)) if expr.sign == -1 \ else prettyForm(*stringPict.right("I - ", _feedback)) _feedback = prettyForm(*stringPict.parens(_feedback)) _feedback.baseline = 0 _feedback = prettyForm(*stringPict.right(_feedback, '-1 ')) _feedback.baseline = _feedback.height()//2 _feedback = prettyForm.__mul__(_feedback, prettyForm(" ")) if isinstance(expr.sys1, TransferFunctionMatrix): _feedback.baseline = _feedback.height() - 1 _feedback = prettyForm(*stringPict.next(_feedback, plant)) return _feedback def _print_TransferFunctionMatrix(self, expr): mat = self._print(expr._expr_mat) mat.baseline = mat.height() - 1 subscript = greek_unicode['tau'] if self._use_unicode else r'{t}' mat = prettyForm(*mat.right(subscript)) return mat def _print_BasisDependent(self, expr): from sympy.vector import Vector if not self._use_unicode: raise NotImplementedError("ASCII pretty printing of BasisDependent is not implemented") if expr == expr.zero: return prettyForm(expr.zero._pretty_form) o1 = [] vectstrs = [] if isinstance(expr, Vector): items = expr.separate().items() else: items = [(0, expr)] for system, vect in items: inneritems = list(vect.components.items()) inneritems.sort(key = lambda x: x[0].__str__()) for k, v in inneritems: #if the coef of the basis vector is 1 #we skip the 1 if v == 1: o1.append("" + k._pretty_form) #Same for -1 elif v == -1: o1.append("(-1) " + k._pretty_form) #For a general expr else: #We always wrap the measure numbers in #parentheses arg_str = self._print( v).parens()[0] o1.append(arg_str + ' ' + k._pretty_form) vectstrs.append(k._pretty_form) #outstr = u("").join(o1) if o1[0].startswith(" + "): o1[0] = o1[0][3:] elif o1[0].startswith(" "): o1[0] = o1[0][1:] #Fixing the newlines lengths = [] strs = [''] flag = [] for i, partstr in enumerate(o1): flag.append(0) # XXX: What is this hack? if '\n' in partstr: tempstr = partstr tempstr = tempstr.replace(vectstrs[i], '') if '\N{right parenthesis extension}' in tempstr: # If scalar is a fraction for paren in range(len(tempstr)): flag[i] = 1 if tempstr[paren] == '\N{right parenthesis extension}': tempstr = tempstr[:paren] + '\N{right parenthesis extension}'\ + ' ' + vectstrs[i] + tempstr[paren + 1:] break elif '\N{RIGHT PARENTHESIS LOWER HOOK}' in tempstr: flag[i] = 1 tempstr = tempstr.replace('\N{RIGHT PARENTHESIS LOWER HOOK}', '\N{RIGHT PARENTHESIS LOWER HOOK}' + ' ' + vectstrs[i]) else: tempstr = tempstr.replace('\N{RIGHT PARENTHESIS UPPER HOOK}', '\N{RIGHT PARENTHESIS UPPER HOOK}' + ' ' + vectstrs[i]) o1[i] = tempstr o1 = [x.split('\n') for x in o1] n_newlines = max([len(x) for x in o1]) # Width of part in its pretty form if 1 in flag: # If there was a fractional scalar for i, parts in enumerate(o1): if len(parts) == 1: # If part has no newline parts.insert(0, ' ' * (len(parts[0]))) flag[i] = 1 for i, parts in enumerate(o1): lengths.append(len(parts[flag[i]])) for j in range(n_newlines): if j+1 <= len(parts): if j >= len(strs): strs.append(' ' * (sum(lengths[:-1]) + 3*(len(lengths)-1))) if j == flag[i]: strs[flag[i]] += parts[flag[i]] + ' + ' else: strs[j] += parts[j] + ' '*(lengths[-1] - len(parts[j])+ 3) else: if j >= len(strs): strs.append(' ' * (sum(lengths[:-1]) + 3*(len(lengths)-1))) strs[j] += ' '*(lengths[-1]+3) return prettyForm('\n'.join([s[:-3] for s in strs])) def _print_NDimArray(self, expr): from sympy.matrices.immutable import ImmutableMatrix if expr.rank() == 0: return self._print(expr[()]) level_str = [[]] + [[] for i in range(expr.rank())] shape_ranges = [list(range(i)) for i in expr.shape] # leave eventual matrix elements unflattened mat = lambda x: ImmutableMatrix(x, evaluate=False) for outer_i in itertools.product(*shape_ranges): level_str[-1].append(expr[outer_i]) even = True for back_outer_i in range(expr.rank()-1, -1, -1): if len(level_str[back_outer_i+1]) < expr.shape[back_outer_i]: break if even: level_str[back_outer_i].append(level_str[back_outer_i+1]) else: level_str[back_outer_i].append(mat( level_str[back_outer_i+1])) if len(level_str[back_outer_i + 1]) == 1: level_str[back_outer_i][-1] = mat( [[level_str[back_outer_i][-1]]]) even = not even level_str[back_outer_i+1] = [] out_expr = level_str[0][0] if expr.rank() % 2 == 1: out_expr = mat([out_expr]) return self._print(out_expr) def _printer_tensor_indices(self, name, indices, index_map={}): center = stringPict(name) top = stringPict(" "*center.width()) bot = stringPict(" "*center.width()) last_valence = None prev_map = None for i, index in enumerate(indices): indpic = self._print(index.args[0]) if ((index in index_map) or prev_map) and last_valence == index.is_up: if index.is_up: top = prettyForm(*stringPict.next(top, ",")) else: bot = prettyForm(*stringPict.next(bot, ",")) if index in index_map: indpic = prettyForm(*stringPict.next(indpic, "=")) indpic = prettyForm(*stringPict.next(indpic, self._print(index_map[index]))) prev_map = True else: prev_map = False if index.is_up: top = stringPict(*top.right(indpic)) center = stringPict(*center.right(" "*indpic.width())) bot = stringPict(*bot.right(" "*indpic.width())) else: bot = stringPict(*bot.right(indpic)) center = stringPict(*center.right(" "*indpic.width())) top = stringPict(*top.right(" "*indpic.width())) last_valence = index.is_up pict = prettyForm(*center.above(top)) pict = prettyForm(*pict.below(bot)) return pict def _print_Tensor(self, expr): name = expr.args[0].name indices = expr.get_indices() return self._printer_tensor_indices(name, indices) def _print_TensorElement(self, expr): name = expr.expr.args[0].name indices = expr.expr.get_indices() index_map = expr.index_map return self._printer_tensor_indices(name, indices, index_map) def _print_TensMul(self, expr): sign, args = expr._get_args_for_traditional_printer() args = [ prettyForm(*self._print(i).parens()) if precedence_traditional(i) < PRECEDENCE["Mul"] else self._print(i) for i in args ] pform = prettyForm.__mul__(*args) if sign: return prettyForm(*pform.left(sign)) else: return pform def _print_TensAdd(self, expr): args = [ prettyForm(*self._print(i).parens()) if precedence_traditional(i) < PRECEDENCE["Mul"] else self._print(i) for i in expr.args ] return prettyForm.__add__(*args) def _print_TensorIndex(self, expr): sym = expr.args[0] if not expr.is_up: sym = -sym return self._print(sym) def _print_PartialDerivative(self, deriv): if self._use_unicode: deriv_symbol = U('PARTIAL DIFFERENTIAL') else: deriv_symbol = r'd' x = None for variable in reversed(deriv.variables): s = self._print(variable) ds = prettyForm(*s.left(deriv_symbol)) if x is None: x = ds else: x = prettyForm(*x.right(' ')) x = prettyForm(*x.right(ds)) f = prettyForm( binding=prettyForm.FUNC, *self._print(deriv.expr).parens()) pform = prettyForm(deriv_symbol) if len(deriv.variables) > 1: pform = pform**self._print(len(deriv.variables)) pform = prettyForm(*pform.below(stringPict.LINE, x)) pform.baseline = pform.baseline + 1 pform = prettyForm(*stringPict.next(pform, f)) pform.binding = prettyForm.MUL return pform def _print_Piecewise(self, pexpr): P = {} for n, ec in enumerate(pexpr.args): P[n, 0] = self._print(ec.expr) if ec.cond == True: P[n, 1] = prettyForm('otherwise') else: P[n, 1] = prettyForm( *prettyForm('for ').right(self._print(ec.cond))) hsep = 2 vsep = 1 len_args = len(pexpr.args) # max widths maxw = [max([P[i, j].width() for i in range(len_args)]) for j in range(2)] # FIXME: Refactor this code and matrix into some tabular environment. # drawing result D = None for i in range(len_args): D_row = None for j in range(2): p = P[i, j] assert p.width() <= maxw[j] wdelta = maxw[j] - p.width() wleft = wdelta // 2 wright = wdelta - wleft p = prettyForm(*p.right(' '*wright)) p = prettyForm(*p.left(' '*wleft)) if D_row is None: D_row = p continue D_row = prettyForm(*D_row.right(' '*hsep)) # h-spacer D_row = prettyForm(*D_row.right(p)) if D is None: D = D_row # first row in a picture continue # v-spacer for _ in range(vsep): D = prettyForm(*D.below(' ')) D = prettyForm(*D.below(D_row)) D = prettyForm(*D.parens('{', '')) D.baseline = D.height()//2 D.binding = prettyForm.OPEN return D def _print_ITE(self, ite): from sympy.functions.elementary.piecewise import Piecewise return self._print(ite.rewrite(Piecewise)) def _hprint_vec(self, v): D = None for a in v: p = a if D is None: D = p else: D = prettyForm(*D.right(', ')) D = prettyForm(*D.right(p)) if D is None: D = stringPict(' ') return D def _hprint_vseparator(self, p1, p2, left=None, right=None, delimiter='', ifascii_nougly=False): if ifascii_nougly and not self._use_unicode: return self._print_seq((p1, '|', p2), left=left, right=right, delimiter=delimiter, ifascii_nougly=True) tmp = self._print_seq((p1, p2,), left=left, right=right, delimiter=delimiter) sep = stringPict(vobj('|', tmp.height()), baseline=tmp.baseline) return self._print_seq((p1, sep, p2), left=left, right=right, delimiter=delimiter) def _print_hyper(self, e): # FIXME refactor Matrix, Piecewise, and this into a tabular environment ap = [self._print(a) for a in e.ap] bq = [self._print(b) for b in e.bq] P = self._print(e.argument) P.baseline = P.height()//2 # Drawing result - first create the ap, bq vectors D = None for v in [ap, bq]: D_row = self._hprint_vec(v) if D is None: D = D_row # first row in a picture else: D = prettyForm(*D.below(' ')) D = prettyForm(*D.below(D_row)) # make sure that the argument `z' is centred vertically D.baseline = D.height()//2 # insert horizontal separator P = prettyForm(*P.left(' ')) D = prettyForm(*D.right(' ')) # insert separating `|` D = self._hprint_vseparator(D, P) # add parens D = prettyForm(*D.parens('(', ')')) # create the F symbol above = D.height()//2 - 1 below = D.height() - above - 1 sz, t, b, add, img = annotated('F') F = prettyForm('\n' * (above - t) + img + '\n' * (below - b), baseline=above + sz) add = (sz + 1)//2 F = prettyForm(*F.left(self._print(len(e.ap)))) F = prettyForm(*F.right(self._print(len(e.bq)))) F.baseline = above + add D = prettyForm(*F.right(' ', D)) return D def _print_meijerg(self, e): # FIXME refactor Matrix, Piecewise, and this into a tabular environment v = {} v[(0, 0)] = [self._print(a) for a in e.an] v[(0, 1)] = [self._print(a) for a in e.aother] v[(1, 0)] = [self._print(b) for b in e.bm] v[(1, 1)] = [self._print(b) for b in e.bother] P = self._print(e.argument) P.baseline = P.height()//2 vp = {} for idx in v: vp[idx] = self._hprint_vec(v[idx]) for i in range(2): maxw = max(vp[(0, i)].width(), vp[(1, i)].width()) for j in range(2): s = vp[(j, i)] left = (maxw - s.width()) // 2 right = maxw - left - s.width() s = prettyForm(*s.left(' ' * left)) s = prettyForm(*s.right(' ' * right)) vp[(j, i)] = s D1 = prettyForm(*vp[(0, 0)].right(' ', vp[(0, 1)])) D1 = prettyForm(*D1.below(' ')) D2 = prettyForm(*vp[(1, 0)].right(' ', vp[(1, 1)])) D = prettyForm(*D1.below(D2)) # make sure that the argument `z' is centred vertically D.baseline = D.height()//2 # insert horizontal separator P = prettyForm(*P.left(' ')) D = prettyForm(*D.right(' ')) # insert separating `|` D = self._hprint_vseparator(D, P) # add parens D = prettyForm(*D.parens('(', ')')) # create the G symbol above = D.height()//2 - 1 below = D.height() - above - 1 sz, t, b, add, img = annotated('G') F = prettyForm('\n' * (above - t) + img + '\n' * (below - b), baseline=above + sz) pp = self._print(len(e.ap)) pq = self._print(len(e.bq)) pm = self._print(len(e.bm)) pn = self._print(len(e.an)) def adjust(p1, p2): diff = p1.width() - p2.width() if diff == 0: return p1, p2 elif diff > 0: return p1, prettyForm(*p2.left(' '*diff)) else: return prettyForm(*p1.left(' '*-diff)), p2 pp, pm = adjust(pp, pm) pq, pn = adjust(pq, pn) pu = prettyForm(*pm.right(', ', pn)) pl = prettyForm(*pp.right(', ', pq)) ht = F.baseline - above - 2 if ht > 0: pu = prettyForm(*pu.below('\n'*ht)) p = prettyForm(*pu.below(pl)) F.baseline = above F = prettyForm(*F.right(p)) F.baseline = above + add D = prettyForm(*F.right(' ', D)) return D def _print_ExpBase(self, e): # TODO should exp_polar be printed differently? # what about exp_polar(0), exp_polar(1)? base = prettyForm(pretty_atom('Exp1', 'e')) return base ** self._print(e.args[0]) def _print_Exp1(self, e): return prettyForm(pretty_atom('Exp1', 'e')) def _print_Function(self, e, sort=False, func_name=None, left='(', right=')'): # optional argument func_name for supplying custom names # XXX works only for applied functions return self._helper_print_function(e.func, e.args, sort=sort, func_name=func_name, left=left, right=right) def _print_mathieuc(self, e): return self._print_Function(e, func_name='C') def _print_mathieus(self, e): return self._print_Function(e, func_name='S') def _print_mathieucprime(self, e): return self._print_Function(e, func_name="C'") def _print_mathieusprime(self, e): return self._print_Function(e, func_name="S'") def _helper_print_function(self, func, args, sort=False, func_name=None, delimiter=', ', elementwise=False, left='(', right=')'): if sort: args = sorted(args, key=default_sort_key) if not func_name and hasattr(func, "__name__"): func_name = func.__name__ if func_name: prettyFunc = self._print(Symbol(func_name)) else: prettyFunc = prettyForm(*self._print(func).parens()) if elementwise: if self._use_unicode: circ = pretty_atom('Modifier Letter Low Ring') else: circ = '.' circ = self._print(circ) prettyFunc = prettyForm( binding=prettyForm.LINE, *stringPict.next(prettyFunc, circ) ) prettyArgs = prettyForm(*self._print_seq(args, delimiter=delimiter).parens( left=left, right=right)) pform = prettyForm( binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs)) # store pform parts so it can be reassembled e.g. when powered pform.prettyFunc = prettyFunc pform.prettyArgs = prettyArgs return pform def _print_ElementwiseApplyFunction(self, e): func = e.function arg = e.expr args = [arg] return self._helper_print_function(func, args, delimiter="", elementwise=True) @property def _special_function_classes(self): from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.functions.special.gamma_functions import gamma, lowergamma from sympy.functions.special.zeta_functions import lerchphi from sympy.functions.special.beta_functions import beta from sympy.functions.special.delta_functions import DiracDelta from sympy.functions.special.error_functions import Chi return {KroneckerDelta: [greek_unicode['delta'], 'delta'], gamma: [greek_unicode['Gamma'], 'Gamma'], lerchphi: [greek_unicode['Phi'], 'lerchphi'], lowergamma: [greek_unicode['gamma'], 'gamma'], beta: [greek_unicode['Beta'], 'B'], DiracDelta: [greek_unicode['delta'], 'delta'], Chi: ['Chi', 'Chi']} def _print_FunctionClass(self, expr): for cls in self._special_function_classes: if issubclass(expr, cls) and expr.__name__ == cls.__name__: if self._use_unicode: return prettyForm(self._special_function_classes[cls][0]) else: return prettyForm(self._special_function_classes[cls][1]) func_name = expr.__name__ return prettyForm(pretty_symbol(func_name)) def _print_GeometryEntity(self, expr): # GeometryEntity is based on Tuple but should not print like a Tuple return self.emptyPrinter(expr) def _print_lerchphi(self, e): func_name = greek_unicode['Phi'] if self._use_unicode else 'lerchphi' return self._print_Function(e, func_name=func_name) def _print_dirichlet_eta(self, e): func_name = greek_unicode['eta'] if self._use_unicode else 'dirichlet_eta' return self._print_Function(e, func_name=func_name) def _print_Heaviside(self, e): func_name = greek_unicode['theta'] if self._use_unicode else 'Heaviside' if e.args[1]==1/2: pform = prettyForm(*self._print(e.args[0]).parens()) pform = prettyForm(*pform.left(func_name)) return pform else: return self._print_Function(e, func_name=func_name) def _print_fresnels(self, e): return self._print_Function(e, func_name="S") def _print_fresnelc(self, e): return self._print_Function(e, func_name="C") def _print_airyai(self, e): return self._print_Function(e, func_name="Ai") def _print_airybi(self, e): return self._print_Function(e, func_name="Bi") def _print_airyaiprime(self, e): return self._print_Function(e, func_name="Ai'") def _print_airybiprime(self, e): return self._print_Function(e, func_name="Bi'") def _print_LambertW(self, e): return self._print_Function(e, func_name="W") def _print_Covariance(self, e): return self._print_Function(e, func_name="Cov") def _print_Variance(self, e): return self._print_Function(e, func_name="Var") def _print_Probability(self, e): return self._print_Function(e, func_name="P") def _print_Expectation(self, e): return self._print_Function(e, func_name="E", left='[', right=']') def _print_Lambda(self, e): expr = e.expr sig = e.signature if self._use_unicode: arrow = " \N{RIGHTWARDS ARROW FROM BAR} " else: arrow = " -> " if len(sig) == 1 and sig[0].is_symbol: sig = sig[0] var_form = self._print(sig) return prettyForm(*stringPict.next(var_form, arrow, self._print(expr)), binding=8) def _print_Order(self, expr): pform = self._print(expr.expr) if (expr.point and any(p != S.Zero for p in expr.point)) or \ len(expr.variables) > 1: pform = prettyForm(*pform.right("; ")) if len(expr.variables) > 1: pform = prettyForm(*pform.right(self._print(expr.variables))) elif len(expr.variables): pform = prettyForm(*pform.right(self._print(expr.variables[0]))) if self._use_unicode: pform = prettyForm(*pform.right(" \N{RIGHTWARDS ARROW} ")) else: pform = prettyForm(*pform.right(" -> ")) if len(expr.point) > 1: pform = prettyForm(*pform.right(self._print(expr.point))) else: pform = prettyForm(*pform.right(self._print(expr.point[0]))) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left("O")) return pform def _print_SingularityFunction(self, e): if self._use_unicode: shift = self._print(e.args[0]-e.args[1]) n = self._print(e.args[2]) base = prettyForm("<") base = prettyForm(*base.right(shift)) base = prettyForm(*base.right(">")) pform = base**n return pform else: n = self._print(e.args[2]) shift = self._print(e.args[0]-e.args[1]) base = self._print_seq(shift, "<", ">", ' ') return base**n def _print_beta(self, e): func_name = greek_unicode['Beta'] if self._use_unicode else 'B' return self._print_Function(e, func_name=func_name) def _print_betainc(self, e): func_name = "B'" return self._print_Function(e, func_name=func_name) def _print_betainc_regularized(self, e): func_name = 'I' return self._print_Function(e, func_name=func_name) def _print_gamma(self, e): func_name = greek_unicode['Gamma'] if self._use_unicode else 'Gamma' return self._print_Function(e, func_name=func_name) def _print_uppergamma(self, e): func_name = greek_unicode['Gamma'] if self._use_unicode else 'Gamma' return self._print_Function(e, func_name=func_name) def _print_lowergamma(self, e): func_name = greek_unicode['gamma'] if self._use_unicode else 'lowergamma' return self._print_Function(e, func_name=func_name) def _print_DiracDelta(self, e): if self._use_unicode: if len(e.args) == 2: a = prettyForm(greek_unicode['delta']) b = self._print(e.args[1]) b = prettyForm(*b.parens()) c = self._print(e.args[0]) c = prettyForm(*c.parens()) pform = a**b pform = prettyForm(*pform.right(' ')) pform = prettyForm(*pform.right(c)) return pform pform = self._print(e.args[0]) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left(greek_unicode['delta'])) return pform else: return self._print_Function(e) def _print_expint(self, e): if e.args[0].is_Integer and self._use_unicode: return self._print_Function(Function('E_%s' % e.args[0])(e.args[1])) return self._print_Function(e) def _print_Chi(self, e): # This needs a special case since otherwise it comes out as greek # letter chi... prettyFunc = prettyForm("Chi") prettyArgs = prettyForm(*self._print_seq(e.args).parens()) pform = prettyForm( binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs)) # store pform parts so it can be reassembled e.g. when powered pform.prettyFunc = prettyFunc pform.prettyArgs = prettyArgs return pform def _print_elliptic_e(self, e): pforma0 = self._print(e.args[0]) if len(e.args) == 1: pform = pforma0 else: pforma1 = self._print(e.args[1]) pform = self._hprint_vseparator(pforma0, pforma1) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left('E')) return pform def _print_elliptic_k(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left('K')) return pform def _print_elliptic_f(self, e): pforma0 = self._print(e.args[0]) pforma1 = self._print(e.args[1]) pform = self._hprint_vseparator(pforma0, pforma1) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left('F')) return pform def _print_elliptic_pi(self, e): name = greek_unicode['Pi'] if self._use_unicode else 'Pi' pforma0 = self._print(e.args[0]) pforma1 = self._print(e.args[1]) if len(e.args) == 2: pform = self._hprint_vseparator(pforma0, pforma1) else: pforma2 = self._print(e.args[2]) pforma = self._hprint_vseparator(pforma1, pforma2, ifascii_nougly=False) pforma = prettyForm(*pforma.left('; ')) pform = prettyForm(*pforma.left(pforma0)) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left(name)) return pform def _print_GoldenRatio(self, expr): if self._use_unicode: return prettyForm(pretty_symbol('phi')) return self._print(Symbol("GoldenRatio")) def _print_EulerGamma(self, expr): if self._use_unicode: return prettyForm(pretty_symbol('gamma')) return self._print(Symbol("EulerGamma")) def _print_Catalan(self, expr): return self._print(Symbol("G")) def _print_Mod(self, expr): pform = self._print(expr.args[0]) if pform.binding > prettyForm.MUL: pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.right(' mod ')) pform = prettyForm(*pform.right(self._print(expr.args[1]))) pform.binding = prettyForm.OPEN return pform def _print_Add(self, expr, order=None): terms = self._as_ordered_terms(expr, order=order) pforms, indices = [], [] def pretty_negative(pform, index): """Prepend a minus sign to a pretty form. """ #TODO: Move this code to prettyForm if index == 0: if pform.height() > 1: pform_neg = '- ' else: pform_neg = '-' else: pform_neg = ' - ' if (pform.binding > prettyForm.NEG or pform.binding == prettyForm.ADD): p = stringPict(*pform.parens()) else: p = pform p = stringPict.next(pform_neg, p) # Lower the binding to NEG, even if it was higher. Otherwise, it # will print as a + ( - (b)), instead of a - (b). return prettyForm(binding=prettyForm.NEG, *p) for i, term in enumerate(terms): if term.is_Mul and term.could_extract_minus_sign(): coeff, other = term.as_coeff_mul(rational=False) if coeff == -1: negterm = Mul(*other, evaluate=False) else: negterm = Mul(-coeff, *other, evaluate=False) pform = self._print(negterm) pforms.append(pretty_negative(pform, i)) elif term.is_Rational and term.q > 1: pforms.append(None) indices.append(i) elif term.is_Number and term < 0: pform = self._print(-term) pforms.append(pretty_negative(pform, i)) elif term.is_Relational: pforms.append(prettyForm(*self._print(term).parens())) else: pforms.append(self._print(term)) if indices: large = True for pform in pforms: if pform is not None and pform.height() > 1: break else: large = False for i in indices: term, negative = terms[i], False if term < 0: term, negative = -term, True if large: pform = prettyForm(str(term.p))/prettyForm(str(term.q)) else: pform = self._print(term) if negative: pform = pretty_negative(pform, i) pforms[i] = pform return prettyForm.__add__(*pforms) def _print_Mul(self, product): from sympy.physics.units import Quantity # Check for unevaluated Mul. In this case we need to make sure the # identities are visible, multiple Rational factors are not combined # etc so we display in a straight-forward form that fully preserves all # args and their order. args = product.args if args[0] is S.One or any(isinstance(arg, Number) for arg in args[1:]): strargs = list(map(self._print, args)) # XXX: This is a hack to work around the fact that # prettyForm.__mul__ absorbs a leading -1 in the args. Probably it # would be better to fix this in prettyForm.__mul__ instead. negone = strargs[0] == '-1' if negone: strargs[0] = prettyForm('1', 0, 0) obj = prettyForm.__mul__(*strargs) if negone: obj = prettyForm('-' + obj.s, obj.baseline, obj.binding) return obj a = [] # items in the numerator b = [] # items that are in the denominator (if any) if self.order not in ('old', 'none'): args = product.as_ordered_factors() else: args = list(product.args) # If quantities are present append them at the back args = sorted(args, key=lambda x: isinstance(x, Quantity) or (isinstance(x, Pow) and isinstance(x.base, Quantity))) # Gather terms for numerator/denominator for item in args: if item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative: if item.exp != -1: b.append(Pow(item.base, -item.exp, evaluate=False)) else: b.append(Pow(item.base, -item.exp)) elif item.is_Rational and item is not S.Infinity: if item.p != 1: a.append( Rational(item.p) ) if item.q != 1: b.append( Rational(item.q) ) else: a.append(item) # Convert to pretty forms. Parentheses are added by `__mul__`. a = [self._print(ai) for ai in a] b = [self._print(bi) for bi in b] # Construct a pretty form if len(b) == 0: return prettyForm.__mul__(*a) else: if len(a) == 0: a.append( self._print(S.One) ) return prettyForm.__mul__(*a)/prettyForm.__mul__(*b) # A helper function for _print_Pow to print x**(1/n) def _print_nth_root(self, base, root): bpretty = self._print(base) # In very simple cases, use a single-char root sign if (self._settings['use_unicode_sqrt_char'] and self._use_unicode and root == 2 and bpretty.height() == 1 and (bpretty.width() == 1 or (base.is_Integer and base.is_nonnegative))): return prettyForm(*bpretty.left('\N{SQUARE ROOT}')) # Construct root sign, start with the \/ shape _zZ = xobj('/', 1) rootsign = xobj('\\', 1) + _zZ # Constructing the number to put on root rpretty = self._print(root) # roots look bad if they are not a single line if rpretty.height() != 1: return self._print(base)**self._print(1/root) # If power is half, no number should appear on top of root sign exp = '' if root == 2 else str(rpretty).ljust(2) if len(exp) > 2: rootsign = ' '*(len(exp) - 2) + rootsign # Stack the exponent rootsign = stringPict(exp + '\n' + rootsign) rootsign.baseline = 0 # Diagonal: length is one less than height of base linelength = bpretty.height() - 1 diagonal = stringPict('\n'.join( ' '*(linelength - i - 1) + _zZ + ' '*i for i in range(linelength) )) # Put baseline just below lowest line: next to exp diagonal.baseline = linelength - 1 # Make the root symbol rootsign = prettyForm(*rootsign.right(diagonal)) # Det the baseline to match contents to fix the height # but if the height of bpretty is one, the rootsign must be one higher rootsign.baseline = max(1, bpretty.baseline) #build result s = prettyForm(hobj('_', 2 + bpretty.width())) s = prettyForm(*bpretty.above(s)) s = prettyForm(*s.left(rootsign)) return s def _print_Pow(self, power): from sympy.simplify.simplify import fraction b, e = power.as_base_exp() if power.is_commutative: if e is S.NegativeOne: return prettyForm("1")/self._print(b) n, d = fraction(e) if n is S.One and d.is_Atom and not e.is_Integer and (e.is_Rational or d.is_Symbol) \ and self._settings['root_notation']: return self._print_nth_root(b, d) if e.is_Rational and e < 0: return prettyForm("1")/self._print(Pow(b, -e, evaluate=False)) if b.is_Relational: return prettyForm(*self._print(b).parens()).__pow__(self._print(e)) return self._print(b)**self._print(e) def _print_UnevaluatedExpr(self, expr): return self._print(expr.args[0]) def __print_numer_denom(self, p, q): if q == 1: if p < 0: return prettyForm(str(p), binding=prettyForm.NEG) else: return prettyForm(str(p)) elif abs(p) >= 10 and abs(q) >= 10: # If more than one digit in numer and denom, print larger fraction if p < 0: return prettyForm(str(p), binding=prettyForm.NEG)/prettyForm(str(q)) # Old printing method: #pform = prettyForm(str(-p))/prettyForm(str(q)) #return prettyForm(binding=prettyForm.NEG, *pform.left('- ')) else: return prettyForm(str(p))/prettyForm(str(q)) else: return None def _print_Rational(self, expr): result = self.__print_numer_denom(expr.p, expr.q) if result is not None: return result else: return self.emptyPrinter(expr) def _print_Fraction(self, expr): result = self.__print_numer_denom(expr.numerator, expr.denominator) if result is not None: return result else: return self.emptyPrinter(expr) def _print_ProductSet(self, p): if len(p.sets) >= 1 and not has_variety(p.sets): return self._print(p.sets[0]) ** self._print(len(p.sets)) else: prod_char = "\N{MULTIPLICATION SIGN}" if self._use_unicode else 'x' return self._print_seq(p.sets, None, None, ' %s ' % prod_char, parenthesize=lambda set: set.is_Union or set.is_Intersection or set.is_ProductSet) def _print_FiniteSet(self, s): items = sorted(s.args, key=default_sort_key) return self._print_seq(items, '{', '}', ', ' ) def _print_Range(self, s): if self._use_unicode: dots = "\N{HORIZONTAL ELLIPSIS}" else: dots = '...' if s.start.is_infinite and s.stop.is_infinite: if s.step.is_positive: printset = dots, -1, 0, 1, dots else: printset = dots, 1, 0, -1, dots elif s.start.is_infinite: printset = dots, s[-1] - s.step, s[-1] elif s.stop.is_infinite: it = iter(s) printset = next(it), next(it), dots elif len(s) > 4: it = iter(s) printset = next(it), next(it), dots, s[-1] else: printset = tuple(s) return self._print_seq(printset, '{', '}', ', ' ) def _print_Interval(self, i): if i.start == i.end: return self._print_seq(i.args[:1], '{', '}') else: if i.left_open: left = '(' else: left = '[' if i.right_open: right = ')' else: right = ']' return self._print_seq(i.args[:2], left, right) def _print_AccumulationBounds(self, i): left = '<' right = '>' return self._print_seq(i.args[:2], left, right) def _print_Intersection(self, u): delimiter = ' %s ' % pretty_atom('Intersection', 'n') return self._print_seq(u.args, None, None, delimiter, parenthesize=lambda set: set.is_ProductSet or set.is_Union or set.is_Complement) def _print_Union(self, u): union_delimiter = ' %s ' % pretty_atom('Union', 'U') return self._print_seq(u.args, None, None, union_delimiter, parenthesize=lambda set: set.is_ProductSet or set.is_Intersection or set.is_Complement) def _print_SymmetricDifference(self, u): if not self._use_unicode: raise NotImplementedError("ASCII pretty printing of SymmetricDifference is not implemented") sym_delimeter = ' %s ' % pretty_atom('SymmetricDifference') return self._print_seq(u.args, None, None, sym_delimeter) def _print_Complement(self, u): delimiter = r' \ ' return self._print_seq(u.args, None, None, delimiter, parenthesize=lambda set: set.is_ProductSet or set.is_Intersection or set.is_Union) def _print_ImageSet(self, ts): if self._use_unicode: inn = "\N{SMALL ELEMENT OF}" else: inn = 'in' fun = ts.lamda sets = ts.base_sets signature = fun.signature expr = self._print(fun.expr) # TODO: the stuff to the left of the | and the stuff to the right of # the | should have independent baselines, that way something like # ImageSet(Lambda(x, 1/x**2), S.Naturals) prints the "x in N" part # centered on the right instead of aligned with the fraction bar on # the left. The same also applies to ConditionSet and ComplexRegion if len(signature) == 1: S = self._print_seq((signature[0], inn, sets[0]), delimiter=' ') return self._hprint_vseparator(expr, S, left='{', right='}', ifascii_nougly=True, delimiter=' ') else: pargs = tuple(j for var, setv in zip(signature, sets) for j in (var, ' ', inn, ' ', setv, ", ")) S = self._print_seq(pargs[:-1], delimiter='') return self._hprint_vseparator(expr, S, left='{', right='}', ifascii_nougly=True, delimiter=' ') def _print_ConditionSet(self, ts): if self._use_unicode: inn = "\N{SMALL ELEMENT OF}" # using _and because and is a keyword and it is bad practice to # overwrite them _and = "\N{LOGICAL AND}" else: inn = 'in' _and = 'and' variables = self._print_seq(Tuple(ts.sym)) as_expr = getattr(ts.condition, 'as_expr', None) if as_expr is not None: cond = self._print(ts.condition.as_expr()) else: cond = self._print(ts.condition) if self._use_unicode: cond = self._print(cond) cond = prettyForm(*cond.parens()) if ts.base_set is S.UniversalSet: return self._hprint_vseparator(variables, cond, left="{", right="}", ifascii_nougly=True, delimiter=' ') base = self._print(ts.base_set) C = self._print_seq((variables, inn, base, _and, cond), delimiter=' ') return self._hprint_vseparator(variables, C, left="{", right="}", ifascii_nougly=True, delimiter=' ') def _print_ComplexRegion(self, ts): if self._use_unicode: inn = "\N{SMALL ELEMENT OF}" else: inn = 'in' variables = self._print_seq(ts.variables) expr = self._print(ts.expr) prodsets = self._print(ts.sets) C = self._print_seq((variables, inn, prodsets), delimiter=' ') return self._hprint_vseparator(expr, C, left="{", right="}", ifascii_nougly=True, delimiter=' ') def _print_Contains(self, e): var, set = e.args if self._use_unicode: el = " \N{ELEMENT OF} " return prettyForm(*stringPict.next(self._print(var), el, self._print(set)), binding=8) else: return prettyForm(sstr(e)) def _print_FourierSeries(self, s): if self._use_unicode: dots = "\N{HORIZONTAL ELLIPSIS}" else: dots = '...' return self._print_Add(s.truncate()) + self._print(dots) def _print_FormalPowerSeries(self, s): return self._print_Add(s.infinite) def _print_SetExpr(self, se): pretty_set = prettyForm(*self._print(se.set).parens()) pretty_name = self._print(Symbol("SetExpr")) return prettyForm(*pretty_name.right(pretty_set)) def _print_SeqFormula(self, s): if self._use_unicode: dots = "\N{HORIZONTAL ELLIPSIS}" else: dots = '...' if len(s.start.free_symbols) > 0 or len(s.stop.free_symbols) > 0: raise NotImplementedError("Pretty printing of sequences with symbolic bound not implemented") if s.start is S.NegativeInfinity: stop = s.stop printset = (dots, s.coeff(stop - 3), s.coeff(stop - 2), s.coeff(stop - 1), s.coeff(stop)) elif s.stop is S.Infinity or s.length > 4: printset = s[:4] printset.append(dots) printset = tuple(printset) else: printset = tuple(s) return self._print_list(printset) _print_SeqPer = _print_SeqFormula _print_SeqAdd = _print_SeqFormula _print_SeqMul = _print_SeqFormula def _print_seq(self, seq, left=None, right=None, delimiter=', ', parenthesize=lambda x: False, ifascii_nougly=True): try: pforms = [] for item in seq: pform = self._print(item) if parenthesize(item): pform = prettyForm(*pform.parens()) if pforms: pforms.append(delimiter) pforms.append(pform) if not pforms: s = stringPict('') else: s = prettyForm(*stringPict.next(*pforms)) # XXX: Under the tests from #15686 the above raises: # AttributeError: 'Fake' object has no attribute 'baseline' # This is caught below but that is not the right way to # fix it. except AttributeError: s = None for item in seq: pform = self.doprint(item) if parenthesize(item): pform = prettyForm(*pform.parens()) if s is None: # first element s = pform else : s = prettyForm(*stringPict.next(s, delimiter)) s = prettyForm(*stringPict.next(s, pform)) if s is None: s = stringPict('') s = prettyForm(*s.parens(left, right, ifascii_nougly=ifascii_nougly)) return s def join(self, delimiter, args): pform = None for arg in args: if pform is None: pform = arg else: pform = prettyForm(*pform.right(delimiter)) pform = prettyForm(*pform.right(arg)) if pform is None: return prettyForm("") else: return pform def _print_list(self, l): return self._print_seq(l, '[', ']') def _print_tuple(self, t): if len(t) == 1: ptuple = prettyForm(*stringPict.next(self._print(t[0]), ',')) return prettyForm(*ptuple.parens('(', ')', ifascii_nougly=True)) else: return self._print_seq(t, '(', ')') def _print_Tuple(self, expr): return self._print_tuple(expr) def _print_dict(self, d): keys = sorted(d.keys(), key=default_sort_key) items = [] for k in keys: K = self._print(k) V = self._print(d[k]) s = prettyForm(*stringPict.next(K, ': ', V)) items.append(s) return self._print_seq(items, '{', '}') def _print_Dict(self, d): return self._print_dict(d) def _print_set(self, s): if not s: return prettyForm('set()') items = sorted(s, key=default_sort_key) pretty = self._print_seq(items) pretty = prettyForm(*pretty.parens('{', '}', ifascii_nougly=True)) return pretty def _print_frozenset(self, s): if not s: return prettyForm('frozenset()') items = sorted(s, key=default_sort_key) pretty = self._print_seq(items) pretty = prettyForm(*pretty.parens('{', '}', ifascii_nougly=True)) pretty = prettyForm(*pretty.parens('(', ')', ifascii_nougly=True)) pretty = prettyForm(*stringPict.next(type(s).__name__, pretty)) return pretty def _print_UniversalSet(self, s): if self._use_unicode: return prettyForm("\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL U}") else: return prettyForm('UniversalSet') def _print_PolyRing(self, ring): return prettyForm(sstr(ring)) def _print_FracField(self, field): return prettyForm(sstr(field)) def _print_FreeGroupElement(self, elm): return prettyForm(str(elm)) def _print_PolyElement(self, poly): return prettyForm(sstr(poly)) def _print_FracElement(self, frac): return prettyForm(sstr(frac)) def _print_AlgebraicNumber(self, expr): if expr.is_aliased: return self._print(expr.as_poly().as_expr()) else: return self._print(expr.as_expr()) def _print_ComplexRootOf(self, expr): args = [self._print_Add(expr.expr, order='lex'), expr.index] pform = prettyForm(*self._print_seq(args).parens()) pform = prettyForm(*pform.left('CRootOf')) return pform def _print_RootSum(self, expr): args = [self._print_Add(expr.expr, order='lex')] if expr.fun is not S.IdentityFunction: args.append(self._print(expr.fun)) pform = prettyForm(*self._print_seq(args).parens()) pform = prettyForm(*pform.left('RootSum')) return pform def _print_FiniteField(self, expr): if self._use_unicode: form = '\N{DOUBLE-STRUCK CAPITAL Z}_%d' else: form = 'GF(%d)' return prettyForm(pretty_symbol(form % expr.mod)) def _print_IntegerRing(self, expr): if self._use_unicode: return prettyForm('\N{DOUBLE-STRUCK CAPITAL Z}') else: return prettyForm('ZZ') def _print_RationalField(self, expr): if self._use_unicode: return prettyForm('\N{DOUBLE-STRUCK CAPITAL Q}') else: return prettyForm('QQ') def _print_RealField(self, domain): if self._use_unicode: prefix = '\N{DOUBLE-STRUCK CAPITAL R}' else: prefix = 'RR' if domain.has_default_precision: return prettyForm(prefix) else: return self._print(pretty_symbol(prefix + "_" + str(domain.precision))) def _print_ComplexField(self, domain): if self._use_unicode: prefix = '\N{DOUBLE-STRUCK CAPITAL C}' else: prefix = 'CC' if domain.has_default_precision: return prettyForm(prefix) else: return self._print(pretty_symbol(prefix + "_" + str(domain.precision))) def _print_PolynomialRing(self, expr): args = list(expr.symbols) if not expr.order.is_default: order = prettyForm(*prettyForm("order=").right(self._print(expr.order))) args.append(order) pform = self._print_seq(args, '[', ']') pform = prettyForm(*pform.left(self._print(expr.domain))) return pform def _print_FractionField(self, expr): args = list(expr.symbols) if not expr.order.is_default: order = prettyForm(*prettyForm("order=").right(self._print(expr.order))) args.append(order) pform = self._print_seq(args, '(', ')') pform = prettyForm(*pform.left(self._print(expr.domain))) return pform def _print_PolynomialRingBase(self, expr): g = expr.symbols if str(expr.order) != str(expr.default_order): g = g + ("order=" + str(expr.order),) pform = self._print_seq(g, '[', ']') pform = prettyForm(*pform.left(self._print(expr.domain))) return pform def _print_GroebnerBasis(self, basis): exprs = [ self._print_Add(arg, order=basis.order) for arg in basis.exprs ] exprs = prettyForm(*self.join(", ", exprs).parens(left="[", right="]")) gens = [ self._print(gen) for gen in basis.gens ] domain = prettyForm( *prettyForm("domain=").right(self._print(basis.domain))) order = prettyForm( *prettyForm("order=").right(self._print(basis.order))) pform = self.join(", ", [exprs] + gens + [domain, order]) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left(basis.__class__.__name__)) return pform def _print_Subs(self, e): pform = self._print(e.expr) pform = prettyForm(*pform.parens()) h = pform.height() if pform.height() > 1 else 2 rvert = stringPict(vobj('|', h), baseline=pform.baseline) pform = prettyForm(*pform.right(rvert)) b = pform.baseline pform.baseline = pform.height() - 1 pform = prettyForm(*pform.right(self._print_seq([ self._print_seq((self._print(v[0]), xsym('=='), self._print(v[1])), delimiter='') for v in zip(e.variables, e.point) ]))) pform.baseline = b return pform def _print_number_function(self, e, name): # Print name_arg[0] for one argument or name_arg[0](arg[1]) # for more than one argument pform = prettyForm(name) arg = self._print(e.args[0]) pform_arg = prettyForm(" "*arg.width()) pform_arg = prettyForm(*pform_arg.below(arg)) pform = prettyForm(*pform.right(pform_arg)) if len(e.args) == 1: return pform m, x = e.args # TODO: copy-pasted from _print_Function: can we do better? prettyFunc = pform prettyArgs = prettyForm(*self._print_seq([x]).parens()) pform = prettyForm( binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs)) pform.prettyFunc = prettyFunc pform.prettyArgs = prettyArgs return pform def _print_euler(self, e): return self._print_number_function(e, "E") def _print_catalan(self, e): return self._print_number_function(e, "C") def _print_bernoulli(self, e): return self._print_number_function(e, "B") _print_bell = _print_bernoulli def _print_lucas(self, e): return self._print_number_function(e, "L") def _print_fibonacci(self, e): return self._print_number_function(e, "F") def _print_tribonacci(self, e): return self._print_number_function(e, "T") def _print_stieltjes(self, e): if self._use_unicode: return self._print_number_function(e, '\N{GREEK SMALL LETTER GAMMA}') else: return self._print_number_function(e, "stieltjes") def _print_KroneckerDelta(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.right(prettyForm(','))) pform = prettyForm(*pform.right(self._print(e.args[1]))) if self._use_unicode: a = stringPict(pretty_symbol('delta')) else: a = stringPict('d') b = pform top = stringPict(*b.left(' '*a.width())) bot = stringPict(*a.right(' '*b.width())) return prettyForm(binding=prettyForm.POW, *bot.below(top)) def _print_RandomDomain(self, d): if hasattr(d, 'as_boolean'): pform = self._print('Domain: ') pform = prettyForm(*pform.right(self._print(d.as_boolean()))) return pform elif hasattr(d, 'set'): pform = self._print('Domain: ') pform = prettyForm(*pform.right(self._print(d.symbols))) pform = prettyForm(*pform.right(self._print(' in '))) pform = prettyForm(*pform.right(self._print(d.set))) return pform elif hasattr(d, 'symbols'): pform = self._print('Domain on ') pform = prettyForm(*pform.right(self._print(d.symbols))) return pform else: return self._print(None) def _print_DMP(self, p): try: if p.ring is not None: # TODO incorporate order return self._print(p.ring.to_sympy(p)) except SympifyError: pass return self._print(repr(p)) def _print_DMF(self, p): return self._print_DMP(p) def _print_Object(self, object): return self._print(pretty_symbol(object.name)) def _print_Morphism(self, morphism): arrow = xsym("-->") domain = self._print(morphism.domain) codomain = self._print(morphism.codomain) tail = domain.right(arrow, codomain)[0] return prettyForm(tail) def _print_NamedMorphism(self, morphism): pretty_name = self._print(pretty_symbol(morphism.name)) pretty_morphism = self._print_Morphism(morphism) return prettyForm(pretty_name.right(":", pretty_morphism)[0]) def _print_IdentityMorphism(self, morphism): from sympy.categories import NamedMorphism return self._print_NamedMorphism( NamedMorphism(morphism.domain, morphism.codomain, "id")) def _print_CompositeMorphism(self, morphism): circle = xsym(".") # All components of the morphism have names and it is thus # possible to build the name of the composite. component_names_list = [pretty_symbol(component.name) for component in morphism.components] component_names_list.reverse() component_names = circle.join(component_names_list) + ":" pretty_name = self._print(component_names) pretty_morphism = self._print_Morphism(morphism) return prettyForm(pretty_name.right(pretty_morphism)[0]) def _print_Category(self, category): return self._print(pretty_symbol(category.name)) def _print_Diagram(self, diagram): if not diagram.premises: # This is an empty diagram. return self._print(S.EmptySet) pretty_result = self._print(diagram.premises) if diagram.conclusions: results_arrow = " %s " % xsym("==>") pretty_conclusions = self._print(diagram.conclusions)[0] pretty_result = pretty_result.right( results_arrow, pretty_conclusions) return prettyForm(pretty_result[0]) def _print_DiagramGrid(self, grid): from sympy.matrices import Matrix matrix = Matrix([[grid[i, j] if grid[i, j] else Symbol(" ") for j in range(grid.width)] for i in range(grid.height)]) return self._print_matrix_contents(matrix) def _print_FreeModuleElement(self, m): # Print as row vector for convenience, for now. return self._print_seq(m, '[', ']') def _print_SubModule(self, M): return self._print_seq(M.gens, '<', '>') def _print_FreeModule(self, M): return self._print(M.ring)**self._print(M.rank) def _print_ModuleImplementedIdeal(self, M): return self._print_seq([x for [x] in M._module.gens], '<', '>') def _print_QuotientRing(self, R): return self._print(R.ring) / self._print(R.base_ideal) def _print_QuotientRingElement(self, R): return self._print(R.data) + self._print(R.ring.base_ideal) def _print_QuotientModuleElement(self, m): return self._print(m.data) + self._print(m.module.killed_module) def _print_QuotientModule(self, M): return self._print(M.base) / self._print(M.killed_module) def _print_MatrixHomomorphism(self, h): matrix = self._print(h._sympy_matrix()) matrix.baseline = matrix.height() // 2 pform = prettyForm(*matrix.right(' : ', self._print(h.domain), ' %s> ' % hobj('-', 2), self._print(h.codomain))) return pform def _print_Manifold(self, manifold): return self._print(manifold.name) def _print_Patch(self, patch): return self._print(patch.name) def _print_CoordSystem(self, coords): return self._print(coords.name) def _print_BaseScalarField(self, field): string = field._coord_sys.symbols[field._index].name return self._print(pretty_symbol(string)) def _print_BaseVectorField(self, field): s = U('PARTIAL DIFFERENTIAL') + '_' + field._coord_sys.symbols[field._index].name return self._print(pretty_symbol(s)) def _print_Differential(self, diff): if self._use_unicode: d = '\N{DOUBLE-STRUCK ITALIC SMALL D}' else: d = 'd' field = diff._form_field if hasattr(field, '_coord_sys'): string = field._coord_sys.symbols[field._index].name return self._print(d + ' ' + pretty_symbol(string)) else: pform = self._print(field) pform = prettyForm(*pform.parens()) return prettyForm(*pform.left(d)) def _print_Tr(self, p): #TODO: Handle indices pform = self._print(p.args[0]) pform = prettyForm(*pform.left('%s(' % (p.__class__.__name__))) pform = prettyForm(*pform.right(')')) return pform def _print_primenu(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.parens()) if self._use_unicode: pform = prettyForm(*pform.left(greek_unicode['nu'])) else: pform = prettyForm(*pform.left('nu')) return pform def _print_primeomega(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.parens()) if self._use_unicode: pform = prettyForm(*pform.left(greek_unicode['Omega'])) else: pform = prettyForm(*pform.left('Omega')) return pform def _print_Quantity(self, e): if e.name.name == 'degree': pform = self._print("\N{DEGREE SIGN}") return pform else: return self.emptyPrinter(e) def _print_AssignmentBase(self, e): op = prettyForm(' ' + xsym(e.op) + ' ') l = self._print(e.lhs) r = self._print(e.rhs) pform = prettyForm(*stringPict.next(l, op, r)) return pform def _print_Str(self, s): return self._print(s.name) @print_function(PrettyPrinter) def pretty(expr, **settings): """Returns a string containing the prettified form of expr. For information on keyword arguments see pretty_print function. """ pp = PrettyPrinter(settings) # XXX: this is an ugly hack, but at least it works use_unicode = pp._settings['use_unicode'] uflag = pretty_use_unicode(use_unicode) try: return pp.doprint(expr) finally: pretty_use_unicode(uflag) def pretty_print(expr, **kwargs): """Prints expr in pretty form. pprint is just a shortcut for this function. Parameters ========== expr : expression The expression to print. wrap_line : bool, optional (default=True) Line wrapping enabled/disabled. num_columns : int or None, optional (default=None) Number of columns before line breaking (default to None which reads the terminal width), useful when using SymPy without terminal. use_unicode : bool or None, optional (default=None) Use unicode characters, such as the Greek letter pi instead of the string pi. full_prec : bool or string, optional (default="auto") Use full precision. order : bool or string, optional (default=None) Set to 'none' for long expressions if slow; default is None. use_unicode_sqrt_char : bool, optional (default=True) Use compact single-character square root symbol (when unambiguous). root_notation : bool, optional (default=True) Set to 'False' for printing exponents of the form 1/n in fractional form. By default exponent is printed in root form. mat_symbol_style : string, optional (default="plain") Set to "bold" for printing MatrixSymbols using a bold mathematical symbol face. By default the standard face is used. imaginary_unit : string, optional (default="i") Letter to use for imaginary unit when use_unicode is True. Can be "i" (default) or "j". """ print(pretty(expr, **kwargs)) pprint = pretty_print def pager_print(expr, **settings): """Prints expr using the pager, in pretty form. This invokes a pager command using pydoc. Lines are not wrapped automatically. This routine is meant to be used with a pager that allows sideways scrolling, like ``less -S``. Parameters are the same as for ``pretty_print``. If you wish to wrap lines, pass ``num_columns=None`` to auto-detect the width of the terminal. """ from pydoc import pager from locale import getpreferredencoding if 'num_columns' not in settings: settings['num_columns'] = 500000 # disable line wrap pager(pretty(expr, **settings).encode(getpreferredencoding()))
0beb83a16aacea9c4c5e775deae6bb4db418472f22e5f6e9b0a2a96edc8cbf4b
"""Prettyprinter by Jurjen Bos. (I hate spammers: mail me at pietjepuk314 at the reverse of ku.oc.oohay). All objects have a method that create a "stringPict", that can be used in the str method for pretty printing. Updates by Jason Gedge (email <my last name> at cs mun ca) - terminal_string() method - minor fixes and changes (mostly to prettyForm) TODO: - Allow left/center/right alignment options for above/below and top/center/bottom alignment options for left/right """ from .pretty_symbology import hobj, vobj, xsym, xobj, pretty_use_unicode, line_width from sympy.utilities.exceptions import SymPyDeprecationWarning class stringPict: """An ASCII picture. The pictures are represented as a list of equal length strings. """ #special value for stringPict.below LINE = 'line' def __init__(self, s, baseline=0): """Initialize from string. Multiline strings are centered. """ self.s = s #picture is a string that just can be printed self.picture = stringPict.equalLengths(s.splitlines()) #baseline is the line number of the "base line" self.baseline = baseline self.binding = None @staticmethod def equalLengths(lines): # empty lines if not lines: return [''] width = max(line_width(line) for line in lines) return [line.center(width) for line in lines] def height(self): """The height of the picture in characters.""" return len(self.picture) def width(self): """The width of the picture in characters.""" return line_width(self.picture[0]) @staticmethod def next(*args): """Put a string of stringPicts next to each other. Returns string, baseline arguments for stringPict. """ #convert everything to stringPicts objects = [] for arg in args: if isinstance(arg, str): arg = stringPict(arg) objects.append(arg) #make a list of pictures, with equal height and baseline newBaseline = max(obj.baseline for obj in objects) newHeightBelowBaseline = max( obj.height() - obj.baseline for obj in objects) newHeight = newBaseline + newHeightBelowBaseline pictures = [] for obj in objects: oneEmptyLine = [' '*obj.width()] basePadding = newBaseline - obj.baseline totalPadding = newHeight - obj.height() pictures.append( oneEmptyLine * basePadding + obj.picture + oneEmptyLine * (totalPadding - basePadding)) result = [''.join(lines) for lines in zip(*pictures)] return '\n'.join(result), newBaseline def right(self, *args): r"""Put pictures next to this one. Returns string, baseline arguments for stringPict. (Multiline) strings are allowed, and are given a baseline of 0. Examples ======== >>> from sympy.printing.pretty.stringpict import stringPict >>> print(stringPict("10").right(" + ",stringPict("1\r-\r2",1))[0]) 1 10 + - 2 """ return stringPict.next(self, *args) def left(self, *args): """Put pictures (left to right) at left. Returns string, baseline arguments for stringPict. """ return stringPict.next(*(args + (self,))) @staticmethod def stack(*args): """Put pictures on top of each other, from top to bottom. Returns string, baseline arguments for stringPict. The baseline is the baseline of the second picture. Everything is centered. Baseline is the baseline of the second picture. Strings are allowed. The special value stringPict.LINE is a row of '-' extended to the width. """ #convert everything to stringPicts; keep LINE objects = [] for arg in args: if arg is not stringPict.LINE and isinstance(arg, str): arg = stringPict(arg) objects.append(arg) #compute new width newWidth = max( obj.width() for obj in objects if obj is not stringPict.LINE) lineObj = stringPict(hobj('-', newWidth)) #replace LINE with proper lines for i, obj in enumerate(objects): if obj is stringPict.LINE: objects[i] = lineObj #stack the pictures, and center the result newPicture = [] for obj in objects: newPicture.extend(obj.picture) newPicture = [line.center(newWidth) for line in newPicture] newBaseline = objects[0].height() + objects[1].baseline return '\n'.join(newPicture), newBaseline def below(self, *args): """Put pictures under this picture. Returns string, baseline arguments for stringPict. Baseline is baseline of top picture Examples ======== >>> from sympy.printing.pretty.stringpict import stringPict >>> print(stringPict("x+3").below( ... stringPict.LINE, '3')[0]) #doctest: +NORMALIZE_WHITESPACE x+3 --- 3 """ s, baseline = stringPict.stack(self, *args) return s, self.baseline def above(self, *args): """Put pictures above this picture. Returns string, baseline arguments for stringPict. Baseline is baseline of bottom picture. """ string, baseline = stringPict.stack(*(args + (self,))) baseline = len(string.splitlines()) - self.height() + self.baseline return string, baseline def parens(self, left='(', right=')', ifascii_nougly=False): """Put parentheses around self. Returns string, baseline arguments for stringPict. left or right can be None or empty string which means 'no paren from that side' """ h = self.height() b = self.baseline # XXX this is a hack -- ascii parens are ugly! if ifascii_nougly and not pretty_use_unicode(): h = 1 b = 0 res = self if left: lparen = stringPict(vobj(left, h), baseline=b) res = stringPict(*lparen.right(self)) if right: rparen = stringPict(vobj(right, h), baseline=b) res = stringPict(*res.right(rparen)) return ('\n'.join(res.picture), res.baseline) def leftslash(self): """Precede object by a slash of the proper size. """ # XXX not used anywhere ? height = max( self.baseline, self.height() - 1 - self.baseline)*2 + 1 slash = '\n'.join( ' '*(height - i - 1) + xobj('/', 1) + ' '*i for i in range(height) ) return self.left(stringPict(slash, height//2)) def root(self, n=None): """Produce a nice root symbol. Produces ugly results for big n inserts. """ # XXX not used anywhere # XXX duplicate of root drawing in pretty.py #put line over expression result = self.above('_'*self.width()) #construct right half of root symbol height = self.height() slash = '\n'.join( ' ' * (height - i - 1) + '/' + ' ' * i for i in range(height) ) slash = stringPict(slash, height - 1) #left half of root symbol if height > 2: downline = stringPict('\\ \n \\', 1) else: downline = stringPict('\\') #put n on top, as low as possible if n is not None and n.width() > downline.width(): downline = downline.left(' '*(n.width() - downline.width())) downline = downline.above(n) #build root symbol root = downline.right(slash) #glue it on at the proper height #normally, the root symbel is as high as self #which is one less than result #this moves the root symbol one down #if the root became higher, the baseline has to grow too root.baseline = result.baseline - result.height() + root.height() return result.left(root) def render(self, * args, **kwargs): """Return the string form of self. Unless the argument line_break is set to False, it will break the expression in a form that can be printed on the terminal without being broken up. """ if kwargs["wrap_line"] is False: return "\n".join(self.picture) if kwargs["num_columns"] is not None: # Read the argument num_columns if it is not None ncols = kwargs["num_columns"] else: # Attempt to get a terminal width ncols = self.terminal_width() ncols -= 2 if ncols <= 0: ncols = 78 # If smaller than the terminal width, no need to correct if self.width() <= ncols: return type(self.picture[0])(self) # for one-line pictures we don't need v-spacers. on the other hand, for # multiline-pictures, we need v-spacers between blocks, compare: # # 2 2 3 | a*c*e + a*c*f + a*d | a*c*e + a*c*f + a*d | 3.14159265358979323 # 6*x *y + 4*x*y + | | *e + a*d*f + b*c*e | 84626433832795 # | *e + a*d*f + b*c*e | + b*c*f + b*d*e + b | # 3 4 4 | | *d*f | # 4*y*x + x + y | + b*c*f + b*d*e + b | | # | | | # | *d*f i = 0 svals = [] do_vspacers = (self.height() > 1) while i < self.width(): svals.extend([ sval[i:i + ncols] for sval in self.picture ]) if do_vspacers: svals.append("") # a vertical spacer i += ncols if svals[-1] == '': del svals[-1] # Get rid of the last spacer return "\n".join(svals) def terminal_width(self): """Return the terminal width if possible, otherwise return 0. """ ncols = 0 try: import curses import io try: curses.setupterm() ncols = curses.tigetnum('cols') except AttributeError: # windows curses doesn't implement setupterm or tigetnum # code below from # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440694 from ctypes import windll, create_string_buffer # stdin handle is -10 # stdout handle is -11 # stderr handle is -12 h = windll.kernel32.GetStdHandle(-12) csbi = create_string_buffer(22) res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) if res: import struct (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw) ncols = right - left + 1 except curses.error: pass except io.UnsupportedOperation: pass except (ImportError, TypeError): pass return ncols def __eq__(self, o): if isinstance(o, str): return '\n'.join(self.picture) == o elif isinstance(o, stringPict): return o.picture == self.picture return False def __hash__(self): return super().__hash__() def __str__(self): return '\n'.join(self.picture) def __repr__(self): return "stringPict(%r,%d)" % ('\n'.join(self.picture), self.baseline) def __getitem__(self, index): return self.picture[index] def __len__(self): return len(self.s) class prettyForm(stringPict): """ Extension of the stringPict class that knows about basic math applications, optimizing double minus signs. "Binding" is interpreted as follows:: ATOM this is an atom: never needs to be parenthesized FUNC this is a function application: parenthesize if added (?) DIV this is a division: make wider division if divided POW this is a power: only parenthesize if exponent MUL this is a multiplication: parenthesize if powered ADD this is an addition: parenthesize if multiplied or powered NEG this is a negative number: optimize if added, parenthesize if multiplied or powered OPEN this is an open object: parenthesize if added, multiplied, or powered (example: Piecewise) """ ATOM, FUNC, DIV, POW, MUL, ADD, NEG, OPEN = range(8) def __init__(self, s, baseline=0, binding=0, unicode=None): """Initialize from stringPict and binding power.""" stringPict.__init__(self, s, baseline) self.binding = binding if unicode is not None: SymPyDeprecationWarning( feature="``unicode`` argument to ``prettyForm``", useinstead="the ``s`` argument", deprecated_since_version="1.7").warn() self._unicode = unicode or s @property def unicode(self): SymPyDeprecationWarning( feature="``prettyForm.unicode`` attribute", useinstead="``stringPrict.s`` attribute", deprecated_since_version="1.7").warn() return self._unicode # Note: code to handle subtraction is in _print_Add def __add__(self, *others): """Make a pretty addition. Addition of negative numbers is simplified. """ arg = self if arg.binding > prettyForm.NEG: arg = stringPict(*arg.parens()) result = [arg] for arg in others: #add parentheses for weak binders if arg.binding > prettyForm.NEG: arg = stringPict(*arg.parens()) #use existing minus sign if available if arg.binding != prettyForm.NEG: result.append(' + ') result.append(arg) return prettyForm(binding=prettyForm.ADD, *stringPict.next(*result)) def __truediv__(self, den, slashed=False): """Make a pretty division; stacked or slashed. """ if slashed: raise NotImplementedError("Can't do slashed fraction yet") num = self if num.binding == prettyForm.DIV: num = stringPict(*num.parens()) if den.binding == prettyForm.DIV: den = stringPict(*den.parens()) if num.binding==prettyForm.NEG: num = num.right(" ")[0] return prettyForm(binding=prettyForm.DIV, *stringPict.stack( num, stringPict.LINE, den)) def __mul__(self, *others): """Make a pretty multiplication. Parentheses are needed around +, - and neg. """ quantity = { 'degree': "\N{DEGREE SIGN}" } if len(others) == 0: return self # We aren't actually multiplying... So nothing to do here. # add parens on args that need them arg = self if arg.binding > prettyForm.MUL and arg.binding != prettyForm.NEG: arg = stringPict(*arg.parens()) result = [arg] for arg in others: if arg.picture[0] not in quantity.values(): result.append(xsym('*')) #add parentheses for weak binders if arg.binding > prettyForm.MUL and arg.binding != prettyForm.NEG: arg = stringPict(*arg.parens()) result.append(arg) len_res = len(result) for i in range(len_res): if i < len_res - 1 and result[i] == '-1' and result[i + 1] == xsym('*'): # substitute -1 by -, like in -1*x -> -x result.pop(i) result.pop(i) result.insert(i, '-') if result[0][0] == '-': # if there is a - sign in front of all # This test was failing to catch a prettyForm.__mul__(prettyForm("-1", 0, 6)) being negative bin = prettyForm.NEG if result[0] == '-': right = result[1] if right.picture[right.baseline][0] == '-': result[0] = '- ' else: bin = prettyForm.MUL return prettyForm(binding=bin, *stringPict.next(*result)) def __repr__(self): return "prettyForm(%r,%d,%d)" % ( '\n'.join(self.picture), self.baseline, self.binding) def __pow__(self, b): """Make a pretty power. """ a = self use_inline_func_form = False if b.binding == prettyForm.POW: b = stringPict(*b.parens()) if a.binding > prettyForm.FUNC: a = stringPict(*a.parens()) elif a.binding == prettyForm.FUNC: # heuristic for when to use inline power if b.height() > 1: a = stringPict(*a.parens()) else: use_inline_func_form = True if use_inline_func_form: # 2 # sin + + (x) b.baseline = a.prettyFunc.baseline + b.height() func = stringPict(*a.prettyFunc.right(b)) return prettyForm(*func.right(a.prettyArgs)) else: # 2 <-- top # (x+y) <-- bot top = stringPict(*b.left(' '*a.width())) bot = stringPict(*a.right(' '*b.width())) return prettyForm(binding=prettyForm.POW, *bot.above(top)) simpleFunctions = ["sin", "cos", "tan"] @staticmethod def apply(function, *args): """Functions of one or more variables. """ if function in prettyForm.simpleFunctions: #simple function: use only space if possible assert len( args) == 1, "Simple function %s must have 1 argument" % function arg = args[0].__pretty__() if arg.binding <= prettyForm.DIV: #optimization: no parentheses necessary return prettyForm(binding=prettyForm.FUNC, *arg.left(function + ' ')) argumentList = [] for arg in args: argumentList.append(',') argumentList.append(arg.__pretty__()) argumentList = stringPict(*stringPict.next(*argumentList[1:])) argumentList = stringPict(*argumentList.parens()) return prettyForm(binding=prettyForm.ATOM, *argumentList.left(function))
c63a864485de22578fb5696a04c39c89b3576b0156874fd847301635f2c7f5fd
from sympy.algebras.quaternion import Quaternion from sympy.assumptions.ask import Q from sympy.calculus.accumulationbounds import AccumBounds from sympy.combinatorics.partitions import Partition from sympy.concrete.summations import (Sum, summation) from sympy.core.add import Add from sympy.core.containers import (Dict, Tuple) from sympy.core.expr import UnevaluatedExpr, Expr from sympy.core.function import (Derivative, Function, Lambda, Subs, WildFunction) from sympy.core.mul import Mul from sympy.core import (Catalan, EulerGamma, GoldenRatio, TribonacciConstant) from sympy.core.numbers import (E, Float, I, Integer, Rational, nan, oo, pi, zoo) from sympy.core.parameters import _exp_is_pow from sympy.core.power import Pow from sympy.core.relational import (Eq, Rel, Ne) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, Wild, symbols) from sympy.functions.combinatorial.factorials import (factorial, factorial2, subfactorial) from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.delta_functions import Heaviside from sympy.functions.special.zeta_functions import zeta from sympy.integrals.integrals import Integral from sympy.logic.boolalg import (Equivalent, false, true, Xor) from sympy.matrices.dense import Matrix from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.expressions.slice import MatrixSlice from sympy.matrices import SparseMatrix from sympy.polys.polytools import factor from sympy.series.limits import Limit from sympy.series.order import O from sympy.sets.sets import (Complement, FiniteSet, Interval, SymmetricDifference) from sympy.external import import_module from sympy.physics.control.lti import TransferFunction, Series, Parallel, \ Feedback, TransferFunctionMatrix, MIMOSeries, MIMOParallel, MIMOFeedback from sympy.physics.units import second, joule from sympy.polys import (Poly, rootof, RootSum, groebner, ring, field, ZZ, QQ, ZZ_I, QQ_I, lex, grlex) from sympy.geometry import Point, Circle, Polygon, Ellipse, Triangle from sympy.tensor import NDimArray from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayElement from sympy.testing.pytest import raises from sympy.printing import sstr, sstrrepr, StrPrinter from sympy.physics.quantum.trace import Tr x, y, z, w, t = symbols('x,y,z,w,t') d = Dummy('d') def test_printmethod(): class R(Abs): def _sympystr(self, printer): return "foo(%s)" % printer._print(self.args[0]) assert sstr(R(x)) == "foo(x)" class R(Abs): def _sympystr(self, printer): return "foo" assert sstr(R(x)) == "foo" def test_Abs(): assert str(Abs(x)) == "Abs(x)" assert str(Abs(Rational(1, 6))) == "1/6" assert str(Abs(Rational(-1, 6))) == "1/6" def test_Add(): assert str(x + y) == "x + y" assert str(x + 1) == "x + 1" assert str(x + x**2) == "x**2 + x" assert str(Add(0, 1, evaluate=False)) == "0 + 1" assert str(Add(0, 0, 1, evaluate=False)) == "0 + 0 + 1" assert str(1.0*x) == "1.0*x" assert str(5 + x + y + x*y + x**2 + y**2) == "x**2 + x*y + x + y**2 + y + 5" assert str(1 + x + x**2/2 + x**3/3) == "x**3/3 + x**2/2 + x + 1" assert str(2*x - 7*x**2 + 2 + 3*y) == "-7*x**2 + 2*x + 3*y + 2" assert str(x - y) == "x - y" assert str(2 - x) == "2 - x" assert str(x - 2) == "x - 2" assert str(x - y - z - w) == "-w + x - y - z" assert str(x - z*y**2*z*w) == "-w*y**2*z**2 + x" assert str(x - 1*y*x*y) == "-x*y**2 + x" assert str(sin(x).series(x, 0, 15)) == "x - x**3/6 + x**5/120 - x**7/5040 + x**9/362880 - x**11/39916800 + x**13/6227020800 + O(x**15)" def test_Catalan(): assert str(Catalan) == "Catalan" def test_ComplexInfinity(): assert str(zoo) == "zoo" def test_Derivative(): assert str(Derivative(x, y)) == "Derivative(x, y)" assert str(Derivative(x**2, x, evaluate=False)) == "Derivative(x**2, x)" assert str(Derivative( x**2/y, x, y, evaluate=False)) == "Derivative(x**2/y, x, y)" def test_dict(): assert str({1: 1 + x}) == sstr({1: 1 + x}) == "{1: x + 1}" assert str({1: x**2, 2: y*x}) in ("{1: x**2, 2: x*y}", "{2: x*y, 1: x**2}") assert sstr({1: x**2, 2: y*x}) == "{1: x**2, 2: x*y}" def test_Dict(): assert str(Dict({1: 1 + x})) == sstr({1: 1 + x}) == "{1: x + 1}" assert str(Dict({1: x**2, 2: y*x})) in ( "{1: x**2, 2: x*y}", "{2: x*y, 1: x**2}") assert sstr(Dict({1: x**2, 2: y*x})) == "{1: x**2, 2: x*y}" def test_Dummy(): assert str(d) == "_d" assert str(d + x) == "_d + x" def test_EulerGamma(): assert str(EulerGamma) == "EulerGamma" def test_Exp(): assert str(E) == "E" with _exp_is_pow(True): assert str(exp(x)) == "E**x" def test_factorial(): n = Symbol('n', integer=True) assert str(factorial(-2)) == "zoo" assert str(factorial(0)) == "1" assert str(factorial(7)) == "5040" assert str(factorial(n)) == "factorial(n)" assert str(factorial(2*n)) == "factorial(2*n)" assert str(factorial(factorial(n))) == 'factorial(factorial(n))' assert str(factorial(factorial2(n))) == 'factorial(factorial2(n))' assert str(factorial2(factorial(n))) == 'factorial2(factorial(n))' assert str(factorial2(factorial2(n))) == 'factorial2(factorial2(n))' assert str(subfactorial(3)) == "2" assert str(subfactorial(n)) == "subfactorial(n)" assert str(subfactorial(2*n)) == "subfactorial(2*n)" def test_Function(): f = Function('f') fx = f(x) w = WildFunction('w') assert str(f) == "f" assert str(fx) == "f(x)" assert str(w) == "w_" def test_Geometry(): assert sstr(Point(0, 0)) == 'Point2D(0, 0)' assert sstr(Circle(Point(0, 0), 3)) == 'Circle(Point2D(0, 0), 3)' assert sstr(Ellipse(Point(1, 2), 3, 4)) == 'Ellipse(Point2D(1, 2), 3, 4)' assert sstr(Triangle(Point(1, 1), Point(7, 8), Point(0, -1))) == \ 'Triangle(Point2D(1, 1), Point2D(7, 8), Point2D(0, -1))' assert sstr(Polygon(Point(5, 6), Point(-2, -3), Point(0, 0), Point(4, 7))) == \ 'Polygon(Point2D(5, 6), Point2D(-2, -3), Point2D(0, 0), Point2D(4, 7))' assert sstr(Triangle(Point(0, 0), Point(1, 0), Point(0, 1)), sympy_integers=True) == \ 'Triangle(Point2D(S(0), S(0)), Point2D(S(1), S(0)), Point2D(S(0), S(1)))' assert sstr(Ellipse(Point(1, 2), 3, 4), sympy_integers=True) == \ 'Ellipse(Point2D(S(1), S(2)), S(3), S(4))' def test_GoldenRatio(): assert str(GoldenRatio) == "GoldenRatio" def test_Heaviside(): assert str(Heaviside(x)) == str(Heaviside(x, S.Half)) == "Heaviside(x)" assert str(Heaviside(x, 1)) == "Heaviside(x, 1)" def test_TribonacciConstant(): assert str(TribonacciConstant) == "TribonacciConstant" def test_ImaginaryUnit(): assert str(I) == "I" def test_Infinity(): assert str(oo) == "oo" assert str(oo*I) == "oo*I" def test_Integer(): assert str(Integer(-1)) == "-1" assert str(Integer(1)) == "1" assert str(Integer(-3)) == "-3" assert str(Integer(0)) == "0" assert str(Integer(25)) == "25" def test_Integral(): assert str(Integral(sin(x), y)) == "Integral(sin(x), y)" assert str(Integral(sin(x), (y, 0, 1))) == "Integral(sin(x), (y, 0, 1))" def test_Interval(): n = (S.NegativeInfinity, 1, 2, S.Infinity) for i in range(len(n)): for j in range(i + 1, len(n)): for l in (True, False): for r in (True, False): ival = Interval(n[i], n[j], l, r) assert S(str(ival)) == ival def test_AccumBounds(): a = Symbol('a', real=True) assert str(AccumBounds(0, a)) == "AccumBounds(0, a)" assert str(AccumBounds(0, 1)) == "AccumBounds(0, 1)" def test_Lambda(): assert str(Lambda(d, d**2)) == "Lambda(_d, _d**2)" # issue 2908 assert str(Lambda((), 1)) == "Lambda((), 1)" assert str(Lambda((), x)) == "Lambda((), x)" assert str(Lambda((x, y), x+y)) == "Lambda((x, y), x + y)" assert str(Lambda(((x, y),), x+y)) == "Lambda(((x, y),), x + y)" def test_Limit(): assert str(Limit(sin(x)/x, x, y)) == "Limit(sin(x)/x, x, y)" assert str(Limit(1/x, x, 0)) == "Limit(1/x, x, 0)" assert str( Limit(sin(x)/x, x, y, dir="-")) == "Limit(sin(x)/x, x, y, dir='-')" def test_list(): assert str([x]) == sstr([x]) == "[x]" assert str([x**2, x*y + 1]) == sstr([x**2, x*y + 1]) == "[x**2, x*y + 1]" assert str([x**2, [y + x]]) == sstr([x**2, [y + x]]) == "[x**2, [x + y]]" def test_Matrix_str(): M = Matrix([[x**+1, 1], [y, x + y]]) assert str(M) == "Matrix([[x, 1], [y, x + y]])" assert sstr(M) == "Matrix([\n[x, 1],\n[y, x + y]])" M = Matrix([[1]]) assert str(M) == sstr(M) == "Matrix([[1]])" M = Matrix([[1, 2]]) assert str(M) == sstr(M) == "Matrix([[1, 2]])" M = Matrix() assert str(M) == sstr(M) == "Matrix(0, 0, [])" M = Matrix(0, 1, lambda i, j: 0) assert str(M) == sstr(M) == "Matrix(0, 1, [])" def test_Mul(): assert str(x/y) == "x/y" assert str(y/x) == "y/x" assert str(x/y/z) == "x/(y*z)" assert str((x + 1)/(y + 2)) == "(x + 1)/(y + 2)" assert str(2*x/3) == '2*x/3' assert str(-2*x/3) == '-2*x/3' assert str(-1.0*x) == '-1.0*x' assert str(1.0*x) == '1.0*x' assert str(Mul(0, 1, evaluate=False)) == '0*1' assert str(Mul(1, 0, evaluate=False)) == '1*0' assert str(Mul(1, 1, evaluate=False)) == '1*1' assert str(Mul(1, 1, 1, evaluate=False)) == '1*1*1' assert str(Mul(1, 2, evaluate=False)) == '1*2' assert str(Mul(1, S.Half, evaluate=False)) == '1*(1/2)' assert str(Mul(1, 1, S.Half, evaluate=False)) == '1*1*(1/2)' assert str(Mul(1, 1, 2, 3, x, evaluate=False)) == '1*1*2*3*x' assert str(Mul(1, -1, evaluate=False)) == '1*(-1)' assert str(Mul(-1, 1, evaluate=False)) == '-1*1' assert str(Mul(4, 3, 2, 1, 0, y, x, evaluate=False)) == '4*3*2*1*0*y*x' assert str(Mul(4, 3, 2, 1+z, 0, y, x, evaluate=False)) == '4*3*2*(z + 1)*0*y*x' assert str(Mul(Rational(2, 3), Rational(5, 7), evaluate=False)) == '(2/3)*(5/7)' # For issue 14160 assert str(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False), evaluate=False)) == '-2*x/(y*y)' # issue 21537 assert str(Mul(x, Pow(1/y, -1, evaluate=False), evaluate=False)) == 'x/(1/y)' class CustomClass1(Expr): is_commutative = True class CustomClass2(Expr): is_commutative = True cc1 = CustomClass1() cc2 = CustomClass2() assert str(Rational(2)*cc1) == '2*CustomClass1()' assert str(cc1*Rational(2)) == '2*CustomClass1()' assert str(cc1*Float("1.5")) == '1.5*CustomClass1()' assert str(cc2*Rational(2)) == '2*CustomClass2()' assert str(cc2*Rational(2)*cc1) == '2*CustomClass1()*CustomClass2()' assert str(cc1*Rational(2)*cc2) == '2*CustomClass1()*CustomClass2()' def test_NaN(): assert str(nan) == "nan" def test_NegativeInfinity(): assert str(-oo) == "-oo" def test_Order(): assert str(O(x)) == "O(x)" assert str(O(x**2)) == "O(x**2)" assert str(O(x*y)) == "O(x*y, x, y)" assert str(O(x, x)) == "O(x)" assert str(O(x, (x, 0))) == "O(x)" assert str(O(x, (x, oo))) == "O(x, (x, oo))" assert str(O(x, x, y)) == "O(x, x, y)" assert str(O(x, x, y)) == "O(x, x, y)" assert str(O(x, (x, oo), (y, oo))) == "O(x, (x, oo), (y, oo))" def test_Permutation_Cycle(): from sympy.combinatorics import Permutation, Cycle # general principle: economically, canonically show all moved elements # and the size of the permutation. for p, s in [ (Cycle(), '()'), (Cycle(2), '(2)'), (Cycle(2, 1), '(1 2)'), (Cycle(1, 2)(5)(6, 7)(10), '(1 2)(6 7)(10)'), (Cycle(3, 4)(1, 2)(3, 4), '(1 2)(4)'), ]: assert sstr(p) == s for p, s in [ (Permutation([]), 'Permutation([])'), (Permutation([], size=1), 'Permutation([0])'), (Permutation([], size=2), 'Permutation([0, 1])'), (Permutation([], size=10), 'Permutation([], size=10)'), (Permutation([1, 0, 2]), 'Permutation([1, 0, 2])'), (Permutation([1, 0, 2, 3, 4, 5]), 'Permutation([1, 0], size=6)'), (Permutation([1, 0, 2, 3, 4, 5], size=10), 'Permutation([1, 0], size=10)'), ]: assert sstr(p, perm_cyclic=False) == s for p, s in [ (Permutation([]), '()'), (Permutation([], size=1), '(0)'), (Permutation([], size=2), '(1)'), (Permutation([], size=10), '(9)'), (Permutation([1, 0, 2]), '(2)(0 1)'), (Permutation([1, 0, 2, 3, 4, 5]), '(5)(0 1)'), (Permutation([1, 0, 2, 3, 4, 5], size=10), '(9)(0 1)'), (Permutation([0, 1, 3, 2, 4, 5], size=10), '(9)(2 3)'), ]: assert sstr(p) == s def test_Pi(): assert str(pi) == "pi" def test_Poly(): assert str(Poly(0, x)) == "Poly(0, x, domain='ZZ')" assert str(Poly(1, x)) == "Poly(1, x, domain='ZZ')" assert str(Poly(x, x)) == "Poly(x, x, domain='ZZ')" assert str(Poly(2*x + 1, x)) == "Poly(2*x + 1, x, domain='ZZ')" assert str(Poly(2*x - 1, x)) == "Poly(2*x - 1, x, domain='ZZ')" assert str(Poly(-1, x)) == "Poly(-1, x, domain='ZZ')" assert str(Poly(-x, x)) == "Poly(-x, x, domain='ZZ')" assert str(Poly(-2*x + 1, x)) == "Poly(-2*x + 1, x, domain='ZZ')" assert str(Poly(-2*x - 1, x)) == "Poly(-2*x - 1, x, domain='ZZ')" assert str(Poly(x - 1, x)) == "Poly(x - 1, x, domain='ZZ')" assert str(Poly(2*x + x**5, x)) == "Poly(x**5 + 2*x, x, domain='ZZ')" assert str(Poly(3**(2*x), 3**x)) == "Poly((3**x)**2, 3**x, domain='ZZ')" assert str(Poly((x**2)**x)) == "Poly(((x**2)**x), (x**2)**x, domain='ZZ')" assert str(Poly((x + y)**3, (x + y), expand=False) ) == "Poly((x + y)**3, x + y, domain='ZZ')" assert str(Poly((x - 1)**2, (x - 1), expand=False) ) == "Poly((x - 1)**2, x - 1, domain='ZZ')" assert str( Poly(x**2 + 1 + y, x)) == "Poly(x**2 + y + 1, x, domain='ZZ[y]')" assert str( Poly(x**2 - 1 + y, x)) == "Poly(x**2 + y - 1, x, domain='ZZ[y]')" assert str(Poly(x**2 + I*x, x)) == "Poly(x**2 + I*x, x, domain='ZZ_I')" assert str(Poly(x**2 - I*x, x)) == "Poly(x**2 - I*x, x, domain='ZZ_I')" assert str(Poly(-x*y*z + x*y - 1, x, y, z) ) == "Poly(-x*y*z + x*y - 1, x, y, z, domain='ZZ')" assert str(Poly(-w*x**21*y**7*z + (1 + w)*z**3 - 2*x*z + 1, x, y, z)) == \ "Poly(-w*x**21*y**7*z - 2*x*z + (w + 1)*z**3 + 1, x, y, z, domain='ZZ[w]')" assert str(Poly(x**2 + 1, x, modulus=2)) == "Poly(x**2 + 1, x, modulus=2)" assert str(Poly(2*x**2 + 3*x + 4, x, modulus=17)) == "Poly(2*x**2 + 3*x + 4, x, modulus=17)" def test_PolyRing(): assert str(ring("x", ZZ, lex)[0]) == "Polynomial ring in x over ZZ with lex order" assert str(ring("x,y", QQ, grlex)[0]) == "Polynomial ring in x, y over QQ with grlex order" assert str(ring("x,y,z", ZZ["t"], lex)[0]) == "Polynomial ring in x, y, z over ZZ[t] with lex order" def test_FracField(): assert str(field("x", ZZ, lex)[0]) == "Rational function field in x over ZZ with lex order" assert str(field("x,y", QQ, grlex)[0]) == "Rational function field in x, y over QQ with grlex order" assert str(field("x,y,z", ZZ["t"], lex)[0]) == "Rational function field in x, y, z over ZZ[t] with lex order" def test_PolyElement(): Ruv, u,v = ring("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Ruv) Rx_zzi, xz = ring("x", ZZ_I) assert str(x - x) == "0" assert str(x - 1) == "x - 1" assert str(x + 1) == "x + 1" assert str(x**2) == "x**2" assert str(x**(-2)) == "x**(-2)" assert str(x**QQ(1, 2)) == "x**(1/2)" assert str((u**2 + 3*u*v + 1)*x**2*y + u + 1) == "(u**2 + 3*u*v + 1)*x**2*y + u + 1" assert str((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x) == "(u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x" assert str((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x + 1) == "(u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x + 1" assert str((-u**2 + 3*u*v - 1)*x**2*y - (u + 1)*x - 1) == "-(u**2 - 3*u*v + 1)*x**2*y - (u + 1)*x - 1" assert str(-(v**2 + v + 1)*x + 3*u*v + 1) == "-(v**2 + v + 1)*x + 3*u*v + 1" assert str(-(v**2 + v + 1)*x - 3*u*v + 1) == "-(v**2 + v + 1)*x - 3*u*v + 1" assert str((1+I)*xz + 2) == "(1 + 1*I)*x + (2 + 0*I)" def test_FracElement(): Fuv, u,v = field("u,v", ZZ) Fxyzt, x,y,z,t = field("x,y,z,t", Fuv) Rx_zzi, xz = field("x", QQ_I) i = QQ_I(0, 1) assert str(x - x) == "0" assert str(x - 1) == "x - 1" assert str(x + 1) == "x + 1" assert str(x/3) == "x/3" assert str(x/z) == "x/z" assert str(x*y/z) == "x*y/z" assert str(x/(z*t)) == "x/(z*t)" assert str(x*y/(z*t)) == "x*y/(z*t)" assert str((x - 1)/y) == "(x - 1)/y" assert str((x + 1)/y) == "(x + 1)/y" assert str((-x - 1)/y) == "(-x - 1)/y" assert str((x + 1)/(y*z)) == "(x + 1)/(y*z)" assert str(-y/(x + 1)) == "-y/(x + 1)" assert str(y*z/(x + 1)) == "y*z/(x + 1)" assert str(((u + 1)*x*y + 1)/((v - 1)*z - 1)) == "((u + 1)*x*y + 1)/((v - 1)*z - 1)" assert str(((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1)) == "((u + 1)*x*y + 1)/((v - 1)*z - u*v*t - 1)" assert str((1+i)/xz) == "(1 + 1*I)/x" assert str(((1+i)*xz - i)/xz) == "((1 + 1*I)*x + (0 + -1*I))/x" def test_GaussianInteger(): assert str(ZZ_I(1, 0)) == "1" assert str(ZZ_I(-1, 0)) == "-1" assert str(ZZ_I(0, 1)) == "I" assert str(ZZ_I(0, -1)) == "-I" assert str(ZZ_I(0, 2)) == "2*I" assert str(ZZ_I(0, -2)) == "-2*I" assert str(ZZ_I(1, 1)) == "1 + I" assert str(ZZ_I(-1, -1)) == "-1 - I" assert str(ZZ_I(-1, -2)) == "-1 - 2*I" def test_GaussianRational(): assert str(QQ_I(1, 0)) == "1" assert str(QQ_I(QQ(2, 3), 0)) == "2/3" assert str(QQ_I(0, QQ(2, 3))) == "2*I/3" assert str(QQ_I(QQ(1, 2), QQ(-2, 3))) == "1/2 - 2*I/3" def test_Pow(): assert str(x**-1) == "1/x" assert str(x**-2) == "x**(-2)" assert str(x**2) == "x**2" assert str((x + y)**-1) == "1/(x + y)" assert str((x + y)**-2) == "(x + y)**(-2)" assert str((x + y)**2) == "(x + y)**2" assert str((x + y)**(1 + x)) == "(x + y)**(x + 1)" assert str(x**Rational(1, 3)) == "x**(1/3)" assert str(1/x**Rational(1, 3)) == "x**(-1/3)" assert str(sqrt(sqrt(x))) == "x**(1/4)" # not the same as x**-1 assert str(x**-1.0) == 'x**(-1.0)' # see issue #2860 assert str(Pow(S(2), -1.0, evaluate=False)) == '2**(-1.0)' def test_sqrt(): assert str(sqrt(x)) == "sqrt(x)" assert str(sqrt(x**2)) == "sqrt(x**2)" assert str(1/sqrt(x)) == "1/sqrt(x)" assert str(1/sqrt(x**2)) == "1/sqrt(x**2)" assert str(y/sqrt(x)) == "y/sqrt(x)" assert str(x**0.5) == "x**0.5" assert str(1/x**0.5) == "x**(-0.5)" def test_Rational(): n1 = Rational(1, 4) n2 = Rational(1, 3) n3 = Rational(2, 4) n4 = Rational(2, -4) n5 = Rational(0) n7 = Rational(3) n8 = Rational(-3) assert str(n1*n2) == "1/12" assert str(n1*n2) == "1/12" assert str(n3) == "1/2" assert str(n1*n3) == "1/8" assert str(n1 + n3) == "3/4" assert str(n1 + n2) == "7/12" assert str(n1 + n4) == "-1/4" assert str(n4*n4) == "1/4" assert str(n4 + n2) == "-1/6" assert str(n4 + n5) == "-1/2" assert str(n4*n5) == "0" assert str(n3 + n4) == "0" assert str(n1**n7) == "1/64" assert str(n2**n7) == "1/27" assert str(n2**n8) == "27" assert str(n7**n8) == "1/27" assert str(Rational("-25")) == "-25" assert str(Rational("1.25")) == "5/4" assert str(Rational("-2.6e-2")) == "-13/500" assert str(S("25/7")) == "25/7" assert str(S("-123/569")) == "-123/569" assert str(S("0.1[23]", rational=1)) == "61/495" assert str(S("5.1[666]", rational=1)) == "31/6" assert str(S("-5.1[666]", rational=1)) == "-31/6" assert str(S("0.[9]", rational=1)) == "1" assert str(S("-0.[9]", rational=1)) == "-1" assert str(sqrt(Rational(1, 4))) == "1/2" assert str(sqrt(Rational(1, 36))) == "1/6" assert str((123**25) ** Rational(1, 25)) == "123" assert str((123**25 + 1)**Rational(1, 25)) != "123" assert str((123**25 - 1)**Rational(1, 25)) != "123" assert str((123**25 - 1)**Rational(1, 25)) != "122" assert str(sqrt(Rational(81, 36))**3) == "27/8" assert str(1/sqrt(Rational(81, 36))**3) == "8/27" assert str(sqrt(-4)) == str(2*I) assert str(2**Rational(1, 10**10)) == "2**(1/10000000000)" assert sstr(Rational(2, 3), sympy_integers=True) == "S(2)/3" x = Symbol("x") assert sstr(x**Rational(2, 3), sympy_integers=True) == "x**(S(2)/3)" assert sstr(Eq(x, Rational(2, 3)), sympy_integers=True) == "Eq(x, S(2)/3)" assert sstr(Limit(x, x, Rational(7, 2)), sympy_integers=True) == \ "Limit(x, x, S(7)/2)" def test_Float(): # NOTE dps is the whole number of decimal digits assert str(Float('1.23', dps=1 + 2)) == '1.23' assert str(Float('1.23456789', dps=1 + 8)) == '1.23456789' assert str( Float('1.234567890123456789', dps=1 + 18)) == '1.234567890123456789' assert str(pi.evalf(1 + 2)) == '3.14' assert str(pi.evalf(1 + 14)) == '3.14159265358979' assert str(pi.evalf(1 + 64)) == ('3.141592653589793238462643383279' '5028841971693993751058209749445923') assert str(pi.round(-1)) == '0.0' assert str((pi**400 - (pi**400).round(1)).n(2)) == '-0.e+88' assert sstr(Float("100"), full_prec=False, min=-2, max=2) == '1.0e+2' assert sstr(Float("100"), full_prec=False, min=-2, max=3) == '100.0' assert sstr(Float("0.1"), full_prec=False, min=-2, max=3) == '0.1' assert sstr(Float("0.099"), min=-2, max=3) == '9.90000000000000e-2' def test_Relational(): assert str(Rel(x, y, "<")) == "x < y" assert str(Rel(x + y, y, "==")) == "Eq(x + y, y)" assert str(Rel(x, y, "!=")) == "Ne(x, y)" assert str(Eq(x, 1) | Eq(x, 2)) == "Eq(x, 1) | Eq(x, 2)" assert str(Ne(x, 1) & Ne(x, 2)) == "Ne(x, 1) & Ne(x, 2)" def test_AppliedBinaryRelation(): assert str(Q.eq(x, y)) == "Q.eq(x, y)" assert str(Q.ne(x, y)) == "Q.ne(x, y)" def test_CRootOf(): assert str(rootof(x**5 + 2*x - 1, 0)) == "CRootOf(x**5 + 2*x - 1, 0)" def test_RootSum(): f = x**5 + 2*x - 1 assert str( RootSum(f, Lambda(z, z), auto=False)) == "RootSum(x**5 + 2*x - 1)" assert str(RootSum(f, Lambda( z, z**2), auto=False)) == "RootSum(x**5 + 2*x - 1, Lambda(z, z**2))" def test_GroebnerBasis(): assert str(groebner( [], x, y)) == "GroebnerBasis([], x, y, domain='ZZ', order='lex')" F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1] assert str(groebner(F, order='grlex')) == \ "GroebnerBasis([x**2 - x - 3*y + 1, y**2 - 2*x + y - 1], x, y, domain='ZZ', order='grlex')" assert str(groebner(F, order='lex')) == \ "GroebnerBasis([2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7], x, y, domain='ZZ', order='lex')" def test_set(): assert sstr(set()) == 'set()' assert sstr(frozenset()) == 'frozenset()' assert sstr({1}) == '{1}' assert sstr(frozenset([1])) == 'frozenset({1})' assert sstr({1, 2, 3}) == '{1, 2, 3}' assert sstr(frozenset([1, 2, 3])) == 'frozenset({1, 2, 3})' assert sstr( {1, x, x**2, x**3, x**4}) == '{1, x, x**2, x**3, x**4}' assert sstr( frozenset([1, x, x**2, x**3, x**4])) == 'frozenset({1, x, x**2, x**3, x**4})' def test_SparseMatrix(): M = SparseMatrix([[x**+1, 1], [y, x + y]]) assert str(M) == "Matrix([[x, 1], [y, x + y]])" assert sstr(M) == "Matrix([\n[x, 1],\n[y, x + y]])" def test_Sum(): assert str(summation(cos(3*z), (z, x, y))) == "Sum(cos(3*z), (z, x, y))" assert str(Sum(x*y**2, (x, -2, 2), (y, -5, 5))) == \ "Sum(x*y**2, (x, -2, 2), (y, -5, 5))" def test_Symbol(): assert str(y) == "y" assert str(x) == "x" e = x assert str(e) == "x" def test_tuple(): assert str((x,)) == sstr((x,)) == "(x,)" assert str((x + y, 1 + x)) == sstr((x + y, 1 + x)) == "(x + y, x + 1)" assert str((x + y, ( 1 + x, x**2))) == sstr((x + y, (1 + x, x**2))) == "(x + y, (x + 1, x**2))" def test_Series_str(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y) assert str(Series(tf1, tf2)) == \ "Series(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y))" assert str(Series(tf1, tf2, tf3)) == \ "Series(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y), TransferFunction(t*x**2 - t**w*x + w, t - y, y))" assert str(Series(-tf2, tf1)) == \ "Series(TransferFunction(-x + y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y))" def test_MIMOSeries_str(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]]) assert str(MIMOSeries(tfm_1, tfm_2)) == \ "MIMOSeries(TransferFunctionMatrix(((TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)), "\ "(TransferFunction(x - y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y)))), "\ "TransferFunctionMatrix(((TransferFunction(x - y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y)), "\ "(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)))))" def test_TransferFunction_str(): tf1 = TransferFunction(x - 1, x + 1, x) assert str(tf1) == "TransferFunction(x - 1, x + 1, x)" tf2 = TransferFunction(x + 1, 2 - y, x) assert str(tf2) == "TransferFunction(x + 1, 2 - y, x)" tf3 = TransferFunction(y, y**2 + 2*y + 3, y) assert str(tf3) == "TransferFunction(y, y**2 + 2*y + 3, y)" def test_Parallel_str(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y) assert str(Parallel(tf1, tf2)) == \ "Parallel(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y))" assert str(Parallel(tf1, tf2, tf3)) == \ "Parallel(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y), TransferFunction(t*x**2 - t**w*x + w, t - y, y))" assert str(Parallel(-tf2, tf1)) == \ "Parallel(TransferFunction(-x + y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y))" def test_MIMOParallel_str(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]]) assert str(MIMOParallel(tfm_1, tfm_2)) == \ "MIMOParallel(TransferFunctionMatrix(((TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)), "\ "(TransferFunction(x - y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y)))), "\ "TransferFunctionMatrix(((TransferFunction(x - y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y)), "\ "(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)))))" def test_Feedback_str(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y) assert str(Feedback(tf1*tf2, tf3)) == \ "Feedback(Series(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)), " \ "TransferFunction(t*x**2 - t**w*x + w, t - y, y), -1)" assert str(Feedback(tf1, TransferFunction(1, 1, y), 1)) == \ "Feedback(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(1, 1, y), 1)" def test_MIMOFeedback_str(): tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) tfm_1 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]]) tfm_2 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) assert (str(MIMOFeedback(tfm_1, tfm_2)) \ == "MIMOFeedback(TransferFunctionMatrix(((TransferFunction(-x + y, y + z, x), TransferFunction(x**2 - y**3, y - z, x))," \ " (TransferFunction(x**2 - y**3, y - z, x), TransferFunction(-x + y, y + z, x)))), " \ "TransferFunctionMatrix(((TransferFunction(x**2 - y**3, y - z, x), " \ "TransferFunction(-x + y, y + z, x)), (TransferFunction(-x + y, y + z, x), TransferFunction(x**2 - y**3, y - z, x)))), -1)") assert (str(MIMOFeedback(tfm_1, tfm_2, 1)) \ == "MIMOFeedback(TransferFunctionMatrix(((TransferFunction(-x + y, y + z, x), TransferFunction(x**2 - y**3, y - z, x)), " \ "(TransferFunction(x**2 - y**3, y - z, x), TransferFunction(-x + y, y + z, x)))), " \ "TransferFunctionMatrix(((TransferFunction(x**2 - y**3, y - z, x), TransferFunction(-x + y, y + z, x)), "\ "(TransferFunction(-x + y, y + z, x), TransferFunction(x**2 - y**3, y - z, x)))), 1)") def test_TransferFunctionMatrix_str(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y) assert str(TransferFunctionMatrix([[tf1], [tf2]])) == \ "TransferFunctionMatrix(((TransferFunction(x*y**2 - z, -t**3 + y**3, y),), (TransferFunction(x - y, x + y, y),)))" assert str(TransferFunctionMatrix([[tf1, tf2], [tf3, tf2]])) == \ "TransferFunctionMatrix(((TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)), (TransferFunction(t*x**2 - t**w*x + w, t - y, y), TransferFunction(x - y, x + y, y))))" def test_Quaternion_str_printer(): q = Quaternion(x, y, z, t) assert str(q) == "x + y*i + z*j + t*k" q = Quaternion(x,y,z,x*t) assert str(q) == "x + y*i + z*j + t*x*k" q = Quaternion(x,y,z,x+t) assert str(q) == "x + y*i + z*j + (t + x)*k" def test_Quantity_str(): assert sstr(second, abbrev=True) == "s" assert sstr(joule, abbrev=True) == "J" assert str(second) == "second" assert str(joule) == "joule" def test_wild_str(): # Check expressions containing Wild not causing infinite recursion w = Wild('x') assert str(w + 1) == 'x_ + 1' assert str(exp(2**w) + 5) == 'exp(2**x_) + 5' assert str(3*w + 1) == '3*x_ + 1' assert str(1/w + 1) == '1 + 1/x_' assert str(w**2 + 1) == 'x_**2 + 1' assert str(1/(1 - w)) == '1/(1 - x_)' def test_wild_matchpy(): from sympy.utilities.matchpy_connector import WildDot, WildPlus, WildStar matchpy = import_module("matchpy") if matchpy is None: return wd = WildDot('w_') wp = WildPlus('w__') ws = WildStar('w___') assert str(wd) == 'w_' assert str(wp) == 'w__' assert str(ws) == 'w___' assert str(wp/ws + 2**wd) == '2**w_ + w__/w___' assert str(sin(wd)*cos(wp)*sqrt(ws)) == 'sqrt(w___)*sin(w_)*cos(w__)' def test_zeta(): assert str(zeta(3)) == "zeta(3)" def test_issue_3101(): e = x - y a = str(e) b = str(e) assert a == b def test_issue_3103(): e = -2*sqrt(x) - y/sqrt(x)/2 assert str(e) not in ["(-2)*x**1/2(-1/2)*x**(-1/2)*y", "-2*x**1/2(-1/2)*x**(-1/2)*y", "-2*x**1/2-1/2*x**-1/2*w"] assert str(e) == "-2*sqrt(x) - y/(2*sqrt(x))" def test_issue_4021(): e = Integral(x, x) + 1 assert str(e) == 'Integral(x, x) + 1' def test_sstrrepr(): assert sstr('abc') == 'abc' assert sstrrepr('abc') == "'abc'" e = ['a', 'b', 'c', x] assert sstr(e) == "[a, b, c, x]" assert sstrrepr(e) == "['a', 'b', 'c', x]" def test_infinity(): assert sstr(oo*I) == "oo*I" def test_full_prec(): assert sstr(S("0.3"), full_prec=True) == "0.300000000000000" assert sstr(S("0.3"), full_prec="auto") == "0.300000000000000" assert sstr(S("0.3"), full_prec=False) == "0.3" assert sstr(S("0.3")*x, full_prec=True) in [ "0.300000000000000*x", "x*0.300000000000000" ] assert sstr(S("0.3")*x, full_prec="auto") in [ "0.3*x", "x*0.3" ] assert sstr(S("0.3")*x, full_prec=False) in [ "0.3*x", "x*0.3" ] def test_noncommutative(): A, B, C = symbols('A,B,C', commutative=False) assert sstr(A*B*C**-1) == "A*B*C**(-1)" assert sstr(C**-1*A*B) == "C**(-1)*A*B" assert sstr(A*C**-1*B) == "A*C**(-1)*B" assert sstr(sqrt(A)) == "sqrt(A)" assert sstr(1/sqrt(A)) == "A**(-1/2)" def test_empty_printer(): str_printer = StrPrinter() assert str_printer.emptyPrinter("foo") == "foo" assert str_printer.emptyPrinter(x*y) == "x*y" assert str_printer.emptyPrinter(32) == "32" def test_settings(): raises(TypeError, lambda: sstr(S(4), method="garbage")) def test_RandomDomain(): from sympy.stats import Normal, Die, Exponential, pspace, where X = Normal('x1', 0, 1) assert str(where(X > 0)) == "Domain: (0 < x1) & (x1 < oo)" D = Die('d1', 6) assert str(where(D > 4)) == "Domain: Eq(d1, 5) | Eq(d1, 6)" A = Exponential('a', 1) B = Exponential('b', 1) assert str(pspace(Tuple(A, B)).domain) == "Domain: (0 <= a) & (0 <= b) & (a < oo) & (b < oo)" def test_FiniteSet(): assert str(FiniteSet(*range(1, 51))) == ( '{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,' ' 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,' ' 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50}' ) assert str(FiniteSet(*range(1, 6))) == '{1, 2, 3, 4, 5}' assert str(FiniteSet(*[x*y, x**2])) == '{x**2, x*y}' assert str(FiniteSet(FiniteSet(FiniteSet(x, y), 5), FiniteSet(x,y), 5) ) == 'FiniteSet(5, FiniteSet(5, {x, y}), {x, y})' def test_Partition(): assert str(Partition(FiniteSet(x, y), {z})) == 'Partition({z}, {x, y})' def test_UniversalSet(): assert str(S.UniversalSet) == 'UniversalSet' def test_PrettyPoly(): F = QQ.frac_field(x, y) R = QQ[x, y] assert sstr(F.convert(x/(x + y))) == sstr(x/(x + y)) assert sstr(R.convert(x + y)) == sstr(x + y) def test_categories(): from sympy.categories import (Object, NamedMorphism, IdentityMorphism, Category) A = Object("A") B = Object("B") f = NamedMorphism(A, B, "f") id_A = IdentityMorphism(A) K = Category("K") assert str(A) == 'Object("A")' assert str(f) == 'NamedMorphism(Object("A"), Object("B"), "f")' assert str(id_A) == 'IdentityMorphism(Object("A"))' assert str(K) == 'Category("K")' def test_Tr(): A, B = symbols('A B', commutative=False) t = Tr(A*B) assert str(t) == 'Tr(A*B)' def test_issue_6387(): assert str(factor(-3.0*z + 3)) == '-3.0*(1.0*z - 1.0)' def test_MatMul_MatAdd(): X, Y = MatrixSymbol("X", 2, 2), MatrixSymbol("Y", 2, 2) assert str(2*(X + Y)) == "2*X + 2*Y" assert str(I*X) == "I*X" assert str(-I*X) == "-I*X" assert str((1 + I)*X) == '(1 + I)*X' assert str(-(1 + I)*X) == '(-1 - I)*X' def test_MatrixSlice(): n = Symbol('n', integer=True) X = MatrixSymbol('X', n, n) Y = MatrixSymbol('Y', 10, 10) Z = MatrixSymbol('Z', 10, 10) assert str(MatrixSlice(X, (None, None, None), (None, None, None))) == 'X[:, :]' assert str(X[x:x + 1, y:y + 1]) == 'X[x:x + 1, y:y + 1]' assert str(X[x:x + 1:2, y:y + 1:2]) == 'X[x:x + 1:2, y:y + 1:2]' assert str(X[:x, y:]) == 'X[:x, y:]' assert str(X[:x, y:]) == 'X[:x, y:]' assert str(X[x:, :y]) == 'X[x:, :y]' assert str(X[x:y, z:w]) == 'X[x:y, z:w]' assert str(X[x:y:t, w:t:x]) == 'X[x:y:t, w:t:x]' assert str(X[x::y, t::w]) == 'X[x::y, t::w]' assert str(X[:x:y, :t:w]) == 'X[:x:y, :t:w]' assert str(X[::x, ::y]) == 'X[::x, ::y]' assert str(MatrixSlice(X, (0, None, None), (0, None, None))) == 'X[:, :]' assert str(MatrixSlice(X, (None, n, None), (None, n, None))) == 'X[:, :]' assert str(MatrixSlice(X, (0, n, None), (0, n, None))) == 'X[:, :]' assert str(MatrixSlice(X, (0, n, 2), (0, n, 2))) == 'X[::2, ::2]' assert str(X[1:2:3, 4:5:6]) == 'X[1:2:3, 4:5:6]' assert str(X[1:3:5, 4:6:8]) == 'X[1:3:5, 4:6:8]' assert str(X[1:10:2]) == 'X[1:10:2, :]' assert str(Y[:5, 1:9:2]) == 'Y[:5, 1:9:2]' assert str(Y[:5, 1:10:2]) == 'Y[:5, 1::2]' assert str(Y[5, :5:2]) == 'Y[5:6, :5:2]' assert str(X[0:1, 0:1]) == 'X[:1, :1]' assert str(X[0:1:2, 0:1:2]) == 'X[:1:2, :1:2]' assert str((Y + Z)[2:, 2:]) == '(Y + Z)[2:, 2:]' def test_true_false(): assert str(true) == repr(true) == sstr(true) == "True" assert str(false) == repr(false) == sstr(false) == "False" def test_Equivalent(): assert str(Equivalent(y, x)) == "Equivalent(x, y)" def test_Xor(): assert str(Xor(y, x, evaluate=False)) == "x ^ y" def test_Complement(): assert str(Complement(S.Reals, S.Naturals)) == 'Complement(Reals, Naturals)' def test_SymmetricDifference(): assert str(SymmetricDifference(Interval(2, 3), Interval(3, 4),evaluate=False)) == \ 'SymmetricDifference(Interval(2, 3), Interval(3, 4))' def test_UnevaluatedExpr(): a, b = symbols("a b") expr1 = 2*UnevaluatedExpr(a+b) assert str(expr1) == "2*(a + b)" def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) assert(str(A[0, 0]) == "A[0, 0]") assert(str(3 * A[0, 0]) == "3*A[0, 0]") F = C[0, 0].subs(C, A - B) assert str(F) == "(A - B)[0, 0]" def test_MatrixSymbol_printing(): A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) assert str(A - A*B - B) == "A - A*B - B" assert str(A*B - (A+B)) == "-A + A*B - B" assert str(A**(-1)) == "A**(-1)" assert str(A**3) == "A**3" def test_MatrixExpressions(): n = Symbol('n', integer=True) X = MatrixSymbol('X', n, n) assert str(X) == "X" # Apply function elementwise (`ElementwiseApplyFunc`): expr = (X.T*X).applyfunc(sin) assert str(expr) == 'Lambda(_d, sin(_d)).(X.T*X)' lamda = Lambda(x, 1/x) expr = (n*X).applyfunc(lamda) assert str(expr) == 'Lambda(x, 1/x).(n*X)' def test_Subs_printing(): assert str(Subs(x, (x,), (1,))) == 'Subs(x, x, 1)' assert str(Subs(x + y, (x, y), (1, 2))) == 'Subs(x + y, (x, y), (1, 2))' def test_issue_15716(): e = Integral(factorial(x), (x, -oo, oo)) assert e.as_terms() == ([(e, ((1.0, 0.0), (1,), ()))], [e]) def test_str_special_matrices(): from sympy.matrices import Identity, ZeroMatrix, OneMatrix assert str(Identity(4)) == 'I' assert str(ZeroMatrix(2, 2)) == '0' assert str(OneMatrix(2, 2)) == '1' def test_issue_14567(): assert factorial(Sum(-1, (x, 0, 0))) + y # doesn't raise an error def test_issue_21823(): assert str(Partition([1, 2])) == 'Partition({1, 2})' assert str(Partition({1, 2})) == 'Partition({1, 2})' def test_issue_22689(): assert str(Mul(Pow(x,-2, evaluate=False), Pow(3,-1,evaluate=False), evaluate=False)) == "1/(x**2*3)" def test_issue_21119_21460(): ss = lambda x: str(S(x, evaluate=False)) assert ss('4/2') == '4/2' assert ss('4/-2') == '4/(-2)' assert ss('-4/2') == '-4/2' assert ss('-4/-2') == '-4/(-2)' assert ss('-2*3/-1') == '-2*3/(-1)' assert ss('-2*3/-1/2') == '-2*3/(-1*2)' assert ss('4/2/1') == '4/(2*1)' assert ss('-2/-1/2') == '-2/(-1*2)' assert ss('2*3*4**(-2*3)') == '2*3/4**(2*3)' assert ss('2*3*1*4**(-2*3)') == '2*3*1/4**(2*3)' def test_Str(): from sympy.core.symbol import Str assert str(Str('x')) == 'x' assert sstrrepr(Str('x')) == "Str('x')" def test_diffgeom(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField x,y = symbols('x y', real=True) m = Manifold('M', 2) assert str(m) == "M" p = Patch('P', m) assert str(p) == "P" rect = CoordSystem('rect', p, [x, y]) assert str(rect) == "rect" b = BaseScalarField(rect, 0) assert str(b) == "x" def test_NDimArray(): assert sstr(NDimArray(1.0), full_prec=True) == '1.00000000000000' assert sstr(NDimArray(1.0), full_prec=False) == '1.0' assert sstr(NDimArray([1.0, 2.0]), full_prec=True) == '[1.00000000000000, 2.00000000000000]' assert sstr(NDimArray([1.0, 2.0]), full_prec=False) == '[1.0, 2.0]' def test_Predicate(): assert sstr(Q.even) == 'Q.even' def test_AppliedPredicate(): assert sstr(Q.even(x)) == 'Q.even(x)' def test_printing_str_array_expressions(): assert sstr(ArraySymbol("A", (2, 3, 4))) == "A" assert sstr(ArrayElement("A", (2, 1/(1-x), 0))) == "A[2, 1/(1 - x), 0]" M = MatrixSymbol("M", 3, 3) N = MatrixSymbol("N", 3, 3) assert sstr(ArrayElement(M*N, [x, 0])) == "(M*N)[x, 0]"
66a19dea2f7d53c706583976ac75e9d9a44dbcec4456fa3717a79f6922b790f5
from sympy.core import ( S, pi, oo, symbols, Rational, Integer, Float, Mod, GoldenRatio, EulerGamma, Catalan, Lambda, Dummy, nan, Mul, Pow, UnevaluatedExpr ) from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne) from sympy.functions import ( Abs, acos, acosh, asin, asinh, atan, atanh, atan2, ceiling, cos, cosh, erf, erfc, exp, floor, gamma, log, loggamma, Max, Min, Piecewise, sign, sin, sinh, sqrt, tan, tanh, fibonacci, lucas ) from sympy.sets import Range from sympy.logic import ITE, Implies, Equivalent from sympy.codegen import For, aug_assign, Assignment from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy from sympy.printing.c import C89CodePrinter, C99CodePrinter, get_math_macros from sympy.codegen.ast import ( AddAugmentedAssignment, Element, Type, FloatType, Declaration, Pointer, Variable, value_const, pointer_const, While, Scope, Print, FunctionPrototype, FunctionDefinition, FunctionCall, Return, real, float32, float64, float80, float128, intc, Comment, CodeBlock ) from sympy.codegen.cfunctions import expm1, log1p, exp2, log2, fma, log10, Cbrt, hypot, Sqrt from sympy.codegen.cnodes import restrict from sympy.utilities.lambdify import implemented_function from sympy.tensor import IndexedBase, Idx from sympy.matrices import Matrix, MatrixSymbol, SparseMatrix from sympy.printing.codeprinter import ccode x, y, z = symbols('x,y,z') def test_printmethod(): class fabs(Abs): def _ccode(self, printer): return "fabs(%s)" % printer._print(self.args[0]) assert ccode(fabs(x)) == "fabs(x)" def test_ccode_sqrt(): assert ccode(sqrt(x)) == "sqrt(x)" assert ccode(x**0.5) == "sqrt(x)" assert ccode(sqrt(x)) == "sqrt(x)" def test_ccode_Pow(): assert ccode(x**3) == "pow(x, 3)" assert ccode(x**(y**3)) == "pow(x, pow(y, 3))" g = implemented_function('g', Lambda(x, 2*x)) assert ccode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \ "pow(3.5*2*x, -x + pow(y, x))/(pow(x, 2) + y)" assert ccode(x**-1.0) == '1.0/x' assert ccode(x**Rational(2, 3)) == 'pow(x, 2.0/3.0)' assert ccode(x**Rational(2, 3), type_aliases={real: float80}) == 'powl(x, 2.0L/3.0L)' _cond_cfunc = [(lambda base, exp: exp.is_integer, "dpowi"), (lambda base, exp: not exp.is_integer, "pow")] assert ccode(x**3, user_functions={'Pow': _cond_cfunc}) == 'dpowi(x, 3)' assert ccode(x**0.5, user_functions={'Pow': _cond_cfunc}) == 'pow(x, 0.5)' assert ccode(x**Rational(16, 5), user_functions={'Pow': _cond_cfunc}) == 'pow(x, 16.0/5.0)' _cond_cfunc2 = [(lambda base, exp: base == 2, lambda base, exp: 'exp2(%s)' % exp), (lambda base, exp: base != 2, 'pow')] # Related to gh-11353 assert ccode(2**x, user_functions={'Pow': _cond_cfunc2}) == 'exp2(x)' assert ccode(x**2, user_functions={'Pow': _cond_cfunc2}) == 'pow(x, 2)' # For issue 14160 assert ccode(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False), evaluate=False)) == '-2*x/(y*y)' def test_ccode_Max(): # Test for gh-11926 assert ccode(Max(x,x*x),user_functions={"Max":"my_max", "Pow":"my_pow"}) == 'my_max(x, my_pow(x, 2))' def test_ccode_Min_performance(): #Shouldn't take more than a few seconds big_min = Min(*symbols('a[0:50]')) for curr_standard in ('c89', 'c99', 'c11'): output = ccode(big_min, standard=curr_standard) assert output.count('(') == output.count(')') def test_ccode_constants_mathh(): assert ccode(exp(1)) == "M_E" assert ccode(pi) == "M_PI" assert ccode(oo, standard='c89') == "HUGE_VAL" assert ccode(-oo, standard='c89') == "-HUGE_VAL" assert ccode(oo) == "INFINITY" assert ccode(-oo, standard='c99') == "-INFINITY" assert ccode(pi, type_aliases={real: float80}) == "M_PIl" def test_ccode_constants_other(): assert ccode(2*GoldenRatio) == "const double GoldenRatio = %s;\n2*GoldenRatio" % GoldenRatio.evalf(17) assert ccode( 2*Catalan) == "const double Catalan = %s;\n2*Catalan" % Catalan.evalf(17) assert ccode(2*EulerGamma) == "const double EulerGamma = %s;\n2*EulerGamma" % EulerGamma.evalf(17) def test_ccode_Rational(): assert ccode(Rational(3, 7)) == "3.0/7.0" assert ccode(Rational(3, 7), type_aliases={real: float80}) == "3.0L/7.0L" assert ccode(Rational(18, 9)) == "2" assert ccode(Rational(3, -7)) == "-3.0/7.0" assert ccode(Rational(3, -7), type_aliases={real: float80}) == "-3.0L/7.0L" assert ccode(Rational(-3, -7)) == "3.0/7.0" assert ccode(Rational(-3, -7), type_aliases={real: float80}) == "3.0L/7.0L" assert ccode(x + Rational(3, 7)) == "x + 3.0/7.0" assert ccode(x + Rational(3, 7), type_aliases={real: float80}) == "x + 3.0L/7.0L" assert ccode(Rational(3, 7)*x) == "(3.0/7.0)*x" assert ccode(Rational(3, 7)*x, type_aliases={real: float80}) == "(3.0L/7.0L)*x" def test_ccode_Integer(): assert ccode(Integer(67)) == "67" assert ccode(Integer(-1)) == "-1" def test_ccode_functions(): assert ccode(sin(x) ** cos(x)) == "pow(sin(x), cos(x))" def test_ccode_inline_function(): x = symbols('x') g = implemented_function('g', Lambda(x, 2*x)) assert ccode(g(x)) == "2*x" g = implemented_function('g', Lambda(x, 2*x/Catalan)) assert ccode( g(x)) == "const double Catalan = %s;\n2*x/Catalan" % Catalan.evalf(17) A = IndexedBase('A') i = Idx('i', symbols('n', integer=True)) g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x))) assert ccode(g(A[i]), assign_to=A[i]) == ( "for (int i=0; i<n; i++){\n" " A[i] = (A[i] + 1)*(A[i] + 2)*A[i];\n" "}" ) def test_ccode_exceptions(): assert ccode(gamma(x), standard='C99') == "tgamma(x)" gamma_c89 = ccode(gamma(x), standard='C89') assert 'not supported in c' in gamma_c89.lower() gamma_c89 = ccode(gamma(x), standard='C89', allow_unknown_functions=False) assert 'not supported in c' in gamma_c89.lower() gamma_c89 = ccode(gamma(x), standard='C89', allow_unknown_functions=True) assert 'not supported in c' not in gamma_c89.lower() def test_ccode_functions2(): assert ccode(ceiling(x)) == "ceil(x)" assert ccode(Abs(x)) == "fabs(x)" assert ccode(gamma(x)) == "tgamma(x)" r, s = symbols('r,s', real=True) assert ccode(Mod(ceiling(r), ceiling(s))) == '((ceil(r) % ceil(s)) + '\ 'ceil(s)) % ceil(s)' assert ccode(Mod(r, s)) == "fmod(r, s)" p1, p2 = symbols('p1 p2', integer=True, positive=True) assert ccode(Mod(p1, p2)) == 'p1 % p2' assert ccode(Mod(p1, p2 + 3)) == 'p1 % (p2 + 3)' assert ccode(Mod(-3, -7, evaluate=False)) == '(-3) % (-7)' assert ccode(-Mod(3, 7, evaluate=False)) == '-(3 % 7)' assert ccode(r*Mod(p1, p2)) == 'r*(p1 % p2)' assert ccode(Mod(p1, p2)**s) == 'pow(p1 % p2, s)' n = symbols('n', integer=True, negative=True) assert ccode(Mod(-n, p2)) == '(-n) % p2' assert ccode(fibonacci(n)) == '(1.0/5.0)*pow(2, -n)*sqrt(5)*(-pow(1 - sqrt(5), n) + pow(1 + sqrt(5), n))' assert ccode(lucas(n)) == 'pow(2, -n)*(pow(1 - sqrt(5), n) + pow(1 + sqrt(5), n))' def test_ccode_user_functions(): x = symbols('x', integer=False) n = symbols('n', integer=True) custom_functions = { "ceiling": "ceil", "Abs": [(lambda x: not x.is_integer, "fabs"), (lambda x: x.is_integer, "abs")], } assert ccode(ceiling(x), user_functions=custom_functions) == "ceil(x)" assert ccode(Abs(x), user_functions=custom_functions) == "fabs(x)" assert ccode(Abs(n), user_functions=custom_functions) == "abs(n)" def test_ccode_boolean(): assert ccode(True) == "true" assert ccode(S.true) == "true" assert ccode(False) == "false" assert ccode(S.false) == "false" assert ccode(x & y) == "x && y" assert ccode(x | y) == "x || y" assert ccode(~x) == "!x" assert ccode(x & y & z) == "x && y && z" assert ccode(x | y | z) == "x || y || z" assert ccode((x & y) | z) == "z || x && y" assert ccode((x | y) & z) == "z && (x || y)" # Automatic rewrites assert ccode(x ^ y) == '(x || y) && (!x || !y)' assert ccode((x ^ y) ^ z) == '(x || y || z) && (x || !y || !z) && (y || !x || !z) && (z || !x || !y)' assert ccode(Implies(x, y)) == 'y || !x' assert ccode(Equivalent(x, z ^ y, Implies(z, x))) == '(x || (y || !z) && (z || !y)) && (z && !x || (y || z) && (!y || !z))' def test_ccode_Relational(): assert ccode(Eq(x, y)) == "x == y" assert ccode(Ne(x, y)) == "x != y" assert ccode(Le(x, y)) == "x <= y" assert ccode(Lt(x, y)) == "x < y" assert ccode(Gt(x, y)) == "x > y" assert ccode(Ge(x, y)) == "x >= y" def test_ccode_Piecewise(): expr = Piecewise((x, x < 1), (x**2, True)) assert ccode(expr) == ( "((x < 1) ? (\n" " x\n" ")\n" ": (\n" " pow(x, 2)\n" "))") assert ccode(expr, assign_to="c") == ( "if (x < 1) {\n" " c = x;\n" "}\n" "else {\n" " c = pow(x, 2);\n" "}") expr = Piecewise((x, x < 1), (x + 1, x < 2), (x**2, True)) assert ccode(expr) == ( "((x < 1) ? (\n" " x\n" ")\n" ": ((x < 2) ? (\n" " x + 1\n" ")\n" ": (\n" " pow(x, 2)\n" ")))") assert ccode(expr, assign_to='c') == ( "if (x < 1) {\n" " c = x;\n" "}\n" "else if (x < 2) {\n" " c = x + 1;\n" "}\n" "else {\n" " c = pow(x, 2);\n" "}") # Check that Piecewise without a True (default) condition error expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0)) raises(ValueError, lambda: ccode(expr)) def test_ccode_sinc(): from sympy.functions.elementary.trigonometric import sinc expr = sinc(x) assert ccode(expr) == ( "((x != 0) ? (\n" " sin(x)/x\n" ")\n" ": (\n" " 1\n" "))") def test_ccode_Piecewise_deep(): p = ccode(2*Piecewise((x, x < 1), (x + 1, x < 2), (x**2, True))) assert p == ( "2*((x < 1) ? (\n" " x\n" ")\n" ": ((x < 2) ? (\n" " x + 1\n" ")\n" ": (\n" " pow(x, 2)\n" ")))") expr = x*y*z + x**2 + y**2 + Piecewise((0, x < 0.5), (1, True)) + cos(z) - 1 assert ccode(expr) == ( "pow(x, 2) + x*y*z + pow(y, 2) + ((x < 0.5) ? (\n" " 0\n" ")\n" ": (\n" " 1\n" ")) + cos(z) - 1") assert ccode(expr, assign_to='c') == ( "c = pow(x, 2) + x*y*z + pow(y, 2) + ((x < 0.5) ? (\n" " 0\n" ")\n" ": (\n" " 1\n" ")) + cos(z) - 1;") def test_ccode_ITE(): expr = ITE(x < 1, y, z) assert ccode(expr) == ( "((x < 1) ? (\n" " y\n" ")\n" ": (\n" " z\n" "))") def test_ccode_settings(): raises(TypeError, lambda: ccode(sin(x), method="garbage")) def test_ccode_Indexed(): s, n, m, o = symbols('s n m o', integer=True) i, j, k = Idx('i', n), Idx('j', m), Idx('k', o) x = IndexedBase('x')[j] A = IndexedBase('A')[i, j] B = IndexedBase('B')[i, j, k] p = C99CodePrinter() assert p._print_Indexed(x) == 'x[j]' assert p._print_Indexed(A) == 'A[%s]' % (m*i+j) assert p._print_Indexed(B) == 'B[%s]' % (i*o*m+j*o+k) A = IndexedBase('A', shape=(5,3))[i, j] assert p._print_Indexed(A) == 'A[%s]' % (3*i + j) A = IndexedBase('A', shape=(5,3), strides='F')[i, j] assert ccode(A) == 'A[%s]' % (i + 5*j) A = IndexedBase('A', shape=(29,29), strides=(1, s), offset=o)[i, j] assert ccode(A) == 'A[o + s*j + i]' Abase = IndexedBase('A', strides=(s, m, n), offset=o) assert ccode(Abase[i, j, k]) == 'A[m*j + n*k + o + s*i]' assert ccode(Abase[2, 3, k]) == 'A[3*m + n*k + o + 2*s]' def test_Element(): assert ccode(Element('x', 'ij')) == 'x[i][j]' assert ccode(Element('x', 'ij', strides='kl', offset='o')) == 'x[i*k + j*l + o]' assert ccode(Element('x', (3,))) == 'x[3]' assert ccode(Element('x', (3,4,5))) == 'x[3][4][5]' def test_ccode_Indexed_without_looking_for_contraction(): len_y = 5 y = IndexedBase('y', shape=(len_y,)) x = IndexedBase('x', shape=(len_y,)) Dy = IndexedBase('Dy', shape=(len_y-1,)) i = Idx('i', len_y-1) e = Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i])) code0 = ccode(e.rhs, assign_to=e.lhs, contract=False) assert code0 == 'Dy[i] = (y[%s] - y[i])/(x[%s] - x[i]);' % (i + 1, i + 1) def test_ccode_loops_matrix_vector(): n, m = symbols('n m', integer=True) A = IndexedBase('A') x = IndexedBase('x') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) s = ( 'for (int i=0; i<m; i++){\n' ' y[i] = 0;\n' '}\n' 'for (int i=0; i<m; i++){\n' ' for (int j=0; j<n; j++){\n' ' y[i] = A[%s]*x[j] + y[i];\n' % (i*n + j) +\ ' }\n' '}' ) assert ccode(A[i, j]*x[j], assign_to=y[i]) == s def test_dummy_loops(): i, m = symbols('i m', integer=True, cls=Dummy) x = IndexedBase('x') y = IndexedBase('y') i = Idx(i, m) expected = ( 'for (int i_%(icount)i=0; i_%(icount)i<m_%(mcount)i; i_%(icount)i++){\n' ' y[i_%(icount)i] = x[i_%(icount)i];\n' '}' ) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index} assert ccode(x[i], assign_to=y[i]) == expected def test_ccode_loops_add(): n, m = symbols('n m', integer=True) A = IndexedBase('A') x = IndexedBase('x') y = IndexedBase('y') z = IndexedBase('z') i = Idx('i', m) j = Idx('j', n) s = ( 'for (int i=0; i<m; i++){\n' ' y[i] = x[i] + z[i];\n' '}\n' 'for (int i=0; i<m; i++){\n' ' for (int j=0; j<n; j++){\n' ' y[i] = A[%s]*x[j] + y[i];\n' % (i*n + j) +\ ' }\n' '}' ) assert ccode(A[i, j]*x[j] + x[i] + z[i], assign_to=y[i]) == s def test_ccode_loops_multiple_contractions(): n, m, o, p = symbols('n m o p', integer=True) a = IndexedBase('a') b = IndexedBase('b') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) k = Idx('k', o) l = Idx('l', p) s = ( 'for (int i=0; i<m; i++){\n' ' y[i] = 0;\n' '}\n' 'for (int i=0; i<m; i++){\n' ' for (int j=0; j<n; j++){\n' ' for (int k=0; k<o; k++){\n' ' for (int l=0; l<p; l++){\n' ' y[i] = a[%s]*b[%s] + y[i];\n' % (i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\ ' }\n' ' }\n' ' }\n' '}' ) assert ccode(b[j, k, l]*a[i, j, k, l], assign_to=y[i]) == s def test_ccode_loops_addfactor(): n, m, o, p = symbols('n m o p', integer=True) a = IndexedBase('a') b = IndexedBase('b') c = IndexedBase('c') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) k = Idx('k', o) l = Idx('l', p) s = ( 'for (int i=0; i<m; i++){\n' ' y[i] = 0;\n' '}\n' 'for (int i=0; i<m; i++){\n' ' for (int j=0; j<n; j++){\n' ' for (int k=0; k<o; k++){\n' ' for (int l=0; l<p; l++){\n' ' y[i] = (a[%s] + b[%s])*c[%s] + y[i];\n' % (i*n*o*p + j*o*p + k*p + l, i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\ ' }\n' ' }\n' ' }\n' '}' ) assert ccode((a[i, j, k, l] + b[i, j, k, l])*c[j, k, l], assign_to=y[i]) == s def test_ccode_loops_multiple_terms(): n, m, o, p = symbols('n m o p', integer=True) a = IndexedBase('a') b = IndexedBase('b') c = IndexedBase('c') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) k = Idx('k', o) s0 = ( 'for (int i=0; i<m; i++){\n' ' y[i] = 0;\n' '}\n' ) s1 = ( 'for (int i=0; i<m; i++){\n' ' for (int j=0; j<n; j++){\n' ' for (int k=0; k<o; k++){\n' ' y[i] = b[j]*b[k]*c[%s] + y[i];\n' % (i*n*o + j*o + k) +\ ' }\n' ' }\n' '}\n' ) s2 = ( 'for (int i=0; i<m; i++){\n' ' for (int k=0; k<o; k++){\n' ' y[i] = a[%s]*b[k] + y[i];\n' % (i*o + k) +\ ' }\n' '}\n' ) s3 = ( 'for (int i=0; i<m; i++){\n' ' for (int j=0; j<n; j++){\n' ' y[i] = a[%s]*b[j] + y[i];\n' % (i*n + j) +\ ' }\n' '}\n' ) c = ccode(b[j]*a[i, j] + b[k]*a[i, k] + b[j]*b[k]*c[i, j, k], assign_to=y[i]) assert (c == s0 + s1 + s2 + s3[:-1] or c == s0 + s1 + s3 + s2[:-1] or c == s0 + s2 + s1 + s3[:-1] or c == s0 + s2 + s3 + s1[:-1] or c == s0 + s3 + s1 + s2[:-1] or c == s0 + s3 + s2 + s1[:-1]) def test_dereference_printing(): expr = x + y + sin(z) + z assert ccode(expr, dereference=[z]) == "x + y + (*z) + sin((*z))" def test_Matrix_printing(): # Test returning a Matrix mat = Matrix([x*y, Piecewise((2 + x, y>0), (y, True)), sin(z)]) A = MatrixSymbol('A', 3, 1) assert ccode(mat, A) == ( "A[0] = x*y;\n" "if (y > 0) {\n" " A[1] = x + 2;\n" "}\n" "else {\n" " A[1] = y;\n" "}\n" "A[2] = sin(z);") # Test using MatrixElements in expressions expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0] assert ccode(expr) == ( "((x > 0) ? (\n" " 2*A[2]\n" ")\n" ": (\n" " A[2]\n" ")) + sin(A[1]) + A[0]") # Test using MatrixElements in a Matrix q = MatrixSymbol('q', 5, 1) M = MatrixSymbol('M', 3, 3) m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])], [q[1,0] + q[2,0], q[3, 0], 5], [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]]) assert ccode(m, M) == ( "M[0] = sin(q[1]);\n" "M[1] = 0;\n" "M[2] = cos(q[2]);\n" "M[3] = q[1] + q[2];\n" "M[4] = q[3];\n" "M[5] = 5;\n" "M[6] = 2*q[4]/q[1];\n" "M[7] = sqrt(q[0]) + 4;\n" "M[8] = 0;") def test_sparse_matrix(): # gh-15791 assert 'Not supported in C' in ccode(SparseMatrix([[1, 2, 3]])) def test_ccode_reserved_words(): x, y = symbols('x, if') with raises(ValueError): ccode(y**2, error_on_reserved=True, standard='C99') assert ccode(y**2) == 'pow(if_, 2)' assert ccode(x * y**2, dereference=[y]) == 'pow((*if_), 2)*x' assert ccode(y**2, reserved_word_suffix='_unreserved') == 'pow(if_unreserved, 2)' def test_ccode_sign(): expr1, ref1 = sign(x) * y, 'y*(((x) > 0) - ((x) < 0))' expr2, ref2 = sign(cos(x)), '(((cos(x)) > 0) - ((cos(x)) < 0))' expr3, ref3 = sign(2 * x + x**2) * x + x**2, 'pow(x, 2) + x*(((pow(x, 2) + 2*x) > 0) - ((pow(x, 2) + 2*x) < 0))' assert ccode(expr1) == ref1 assert ccode(expr1, 'z') == 'z = %s;' % ref1 assert ccode(expr2) == ref2 assert ccode(expr3) == ref3 def test_ccode_Assignment(): assert ccode(Assignment(x, y + z)) == 'x = y + z;' assert ccode(aug_assign(x, '+', y + z)) == 'x += y + z;' def test_ccode_For(): f = For(x, Range(0, 10, 2), [aug_assign(y, '*', x)]) assert ccode(f) == ("for (x = 0; x < 10; x += 2) {\n" " y *= x;\n" "}") def test_ccode_Max_Min(): assert ccode(Max(x, 0), standard='C89') == '((0 > x) ? 0 : x)' assert ccode(Max(x, 0), standard='C99') == 'fmax(0, x)' assert ccode(Min(x, 0, sqrt(x)), standard='c89') == ( '((0 < ((x < sqrt(x)) ? x : sqrt(x))) ? 0 : ((x < sqrt(x)) ? x : sqrt(x)))' ) def test_ccode_standard(): assert ccode(expm1(x), standard='c99') == 'expm1(x)' assert ccode(nan, standard='c99') == 'NAN' assert ccode(float('nan'), standard='c99') == 'NAN' def test_C89CodePrinter(): c89printer = C89CodePrinter() assert c89printer.language == 'C' assert c89printer.standard == 'C89' assert 'void' in c89printer.reserved_words assert 'template' not in c89printer.reserved_words def test_C99CodePrinter(): assert C99CodePrinter().doprint(expm1(x)) == 'expm1(x)' assert C99CodePrinter().doprint(log1p(x)) == 'log1p(x)' assert C99CodePrinter().doprint(exp2(x)) == 'exp2(x)' assert C99CodePrinter().doprint(log2(x)) == 'log2(x)' assert C99CodePrinter().doprint(fma(x, y, -z)) == 'fma(x, y, -z)' assert C99CodePrinter().doprint(log10(x)) == 'log10(x)' assert C99CodePrinter().doprint(Cbrt(x)) == 'cbrt(x)' # note Cbrt due to cbrt already taken. assert C99CodePrinter().doprint(hypot(x, y)) == 'hypot(x, y)' assert C99CodePrinter().doprint(loggamma(x)) == 'lgamma(x)' assert C99CodePrinter().doprint(Max(x, 3, x**2)) == 'fmax(3, fmax(x, pow(x, 2)))' assert C99CodePrinter().doprint(Min(x, 3)) == 'fmin(3, x)' c99printer = C99CodePrinter() assert c99printer.language == 'C' assert c99printer.standard == 'C99' assert 'restrict' in c99printer.reserved_words assert 'using' not in c99printer.reserved_words @XFAIL def test_C99CodePrinter__precision_f80(): f80_printer = C99CodePrinter(dict(type_aliases={real: float80})) assert f80_printer.doprint(sin(x+Float('2.1'))) == 'sinl(x + 2.1L)' def test_C99CodePrinter__precision(): n = symbols('n', integer=True) p = symbols('p', integer=True, positive=True) f32_printer = C99CodePrinter(dict(type_aliases={real: float32})) f64_printer = C99CodePrinter(dict(type_aliases={real: float64})) f80_printer = C99CodePrinter(dict(type_aliases={real: float80})) assert f32_printer.doprint(sin(x+2.1)) == 'sinf(x + 2.1F)' assert f64_printer.doprint(sin(x+2.1)) == 'sin(x + 2.1000000000000001)' assert f80_printer.doprint(sin(x+Float('2.0'))) == 'sinl(x + 2.0L)' for printer, suffix in zip([f32_printer, f64_printer, f80_printer], ['f', '', 'l']): def check(expr, ref): assert printer.doprint(expr) == ref.format(s=suffix, S=suffix.upper()) check(Abs(n), 'abs(n)') check(Abs(x + 2.0), 'fabs{s}(x + 2.0{S})') check(sin(x + 4.0)**cos(x - 2.0), 'pow{s}(sin{s}(x + 4.0{S}), cos{s}(x - 2.0{S}))') check(exp(x*8.0), 'exp{s}(8.0{S}*x)') check(exp2(x), 'exp2{s}(x)') check(expm1(x*4.0), 'expm1{s}(4.0{S}*x)') check(Mod(p, 2), 'p % 2') check(Mod(2*p + 3, 3*p + 5, evaluate=False), '(2*p + 3) % (3*p + 5)') check(Mod(x + 2.0, 3.0), 'fmod{s}(1.0{S}*x + 2.0{S}, 3.0{S})') check(Mod(x, 2.0*x + 3.0), 'fmod{s}(1.0{S}*x, 2.0{S}*x + 3.0{S})') check(log(x/2), 'log{s}((1.0{S}/2.0{S})*x)') check(log10(3*x/2), 'log10{s}((3.0{S}/2.0{S})*x)') check(log2(x*8.0), 'log2{s}(8.0{S}*x)') check(log1p(x), 'log1p{s}(x)') check(2**x, 'pow{s}(2, x)') check(2.0**x, 'pow{s}(2.0{S}, x)') check(x**3, 'pow{s}(x, 3)') check(x**4.0, 'pow{s}(x, 4.0{S})') check(sqrt(3+x), 'sqrt{s}(x + 3)') check(Cbrt(x-2.0), 'cbrt{s}(x - 2.0{S})') check(hypot(x, y), 'hypot{s}(x, y)') check(sin(3.*x + 2.), 'sin{s}(3.0{S}*x + 2.0{S})') check(cos(3.*x - 1.), 'cos{s}(3.0{S}*x - 1.0{S})') check(tan(4.*y + 2.), 'tan{s}(4.0{S}*y + 2.0{S})') check(asin(3.*x + 2.), 'asin{s}(3.0{S}*x + 2.0{S})') check(acos(3.*x + 2.), 'acos{s}(3.0{S}*x + 2.0{S})') check(atan(3.*x + 2.), 'atan{s}(3.0{S}*x + 2.0{S})') check(atan2(3.*x, 2.*y), 'atan2{s}(3.0{S}*x, 2.0{S}*y)') check(sinh(3.*x + 2.), 'sinh{s}(3.0{S}*x + 2.0{S})') check(cosh(3.*x - 1.), 'cosh{s}(3.0{S}*x - 1.0{S})') check(tanh(4.0*y + 2.), 'tanh{s}(4.0{S}*y + 2.0{S})') check(asinh(3.*x + 2.), 'asinh{s}(3.0{S}*x + 2.0{S})') check(acosh(3.*x + 2.), 'acosh{s}(3.0{S}*x + 2.0{S})') check(atanh(3.*x + 2.), 'atanh{s}(3.0{S}*x + 2.0{S})') check(erf(42.*x), 'erf{s}(42.0{S}*x)') check(erfc(42.*x), 'erfc{s}(42.0{S}*x)') check(gamma(x), 'tgamma{s}(x)') check(loggamma(x), 'lgamma{s}(x)') check(ceiling(x + 2.), "ceil{s}(x + 2.0{S})") check(floor(x + 2.), "floor{s}(x + 2.0{S})") check(fma(x, y, -z), 'fma{s}(x, y, -z)') check(Max(x, 8.0, x**4.0), 'fmax{s}(8.0{S}, fmax{s}(x, pow{s}(x, 4.0{S})))') check(Min(x, 2.0), 'fmin{s}(2.0{S}, x)') def test_get_math_macros(): macros = get_math_macros() assert macros[exp(1)] == 'M_E' assert macros[1/Sqrt(2)] == 'M_SQRT1_2' def test_ccode_Declaration(): i = symbols('i', integer=True) var1 = Variable(i, type=Type.from_expr(i)) dcl1 = Declaration(var1) assert ccode(dcl1) == 'int i' var2 = Variable(x, type=float32, attrs={value_const}) dcl2a = Declaration(var2) assert ccode(dcl2a) == 'const float x' dcl2b = var2.as_Declaration(value=pi) assert ccode(dcl2b) == 'const float x = M_PI' var3 = Variable(y, type=Type('bool')) dcl3 = Declaration(var3) printer = C89CodePrinter() assert 'stdbool.h' not in printer.headers assert printer.doprint(dcl3) == 'bool y' assert 'stdbool.h' in printer.headers u = symbols('u', real=True) ptr4 = Pointer.deduced(u, attrs={pointer_const, restrict}) dcl4 = Declaration(ptr4) assert ccode(dcl4) == 'double * const restrict u' var5 = Variable(x, Type('__float128'), attrs={value_const}) dcl5a = Declaration(var5) assert ccode(dcl5a) == 'const __float128 x' var5b = Variable(var5.symbol, var5.type, pi, attrs=var5.attrs) dcl5b = Declaration(var5b) assert ccode(dcl5b) == 'const __float128 x = M_PI' def test_C99CodePrinter_custom_type(): # We will look at __float128 (new in glibc 2.26) f128 = FloatType('_Float128', float128.nbits, float128.nmant, float128.nexp) p128 = C99CodePrinter(dict( type_aliases={real: f128}, type_literal_suffixes={f128: 'Q'}, type_func_suffixes={f128: 'f128'}, type_math_macro_suffixes={ real: 'f128', f128: 'f128' }, type_macros={ f128: ('__STDC_WANT_IEC_60559_TYPES_EXT__',) } )) assert p128.doprint(x) == 'x' assert not p128.headers assert not p128.libraries assert not p128.macros assert p128.doprint(2.0) == '2.0Q' assert not p128.headers assert not p128.libraries assert p128.macros == {'__STDC_WANT_IEC_60559_TYPES_EXT__'} assert p128.doprint(Rational(1, 2)) == '1.0Q/2.0Q' assert p128.doprint(sin(x)) == 'sinf128(x)' assert p128.doprint(cos(2., evaluate=False)) == 'cosf128(2.0Q)' assert p128.doprint(x**-1.0) == '1.0Q/x' var5 = Variable(x, f128, attrs={value_const}) dcl5a = Declaration(var5) assert ccode(dcl5a) == 'const _Float128 x' var5b = Variable(x, f128, pi, attrs={value_const}) dcl5b = Declaration(var5b) assert p128.doprint(dcl5b) == 'const _Float128 x = M_PIf128' var5b = Variable(x, f128, value=Catalan.evalf(38), attrs={value_const}) dcl5c = Declaration(var5b) assert p128.doprint(dcl5c) == 'const _Float128 x = %sQ' % Catalan.evalf(f128.decimal_dig) def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) assert(ccode(A[0, 0]) == "A[0]") assert(ccode(3 * A[0, 0]) == "3*A[0]") F = C[0, 0].subs(C, A - B) assert(ccode(F) == "(A - B)[0]") def test_ccode_math_macros(): assert ccode(z + exp(1)) == 'z + M_E' assert ccode(z + log2(exp(1))) == 'z + M_LOG2E' assert ccode(z + 1/log(2)) == 'z + M_LOG2E' assert ccode(z + log(2)) == 'z + M_LN2' assert ccode(z + log(10)) == 'z + M_LN10' assert ccode(z + pi) == 'z + M_PI' assert ccode(z + pi/2) == 'z + M_PI_2' assert ccode(z + pi/4) == 'z + M_PI_4' assert ccode(z + 1/pi) == 'z + M_1_PI' assert ccode(z + 2/pi) == 'z + M_2_PI' assert ccode(z + 2/sqrt(pi)) == 'z + M_2_SQRTPI' assert ccode(z + 2/Sqrt(pi)) == 'z + M_2_SQRTPI' assert ccode(z + sqrt(2)) == 'z + M_SQRT2' assert ccode(z + Sqrt(2)) == 'z + M_SQRT2' assert ccode(z + 1/sqrt(2)) == 'z + M_SQRT1_2' assert ccode(z + 1/Sqrt(2)) == 'z + M_SQRT1_2' def test_ccode_Type(): assert ccode(Type('float')) == 'float' assert ccode(intc) == 'int' def test_ccode_codegen_ast(): assert ccode(Comment("this is a comment")) == "// this is a comment" assert ccode(While(abs(x) > 1, [aug_assign(x, '-', 1)])) == ( 'while (fabs(x) > 1) {\n' ' x -= 1;\n' '}' ) assert ccode(Scope([AddAugmentedAssignment(x, 1)])) == ( '{\n' ' x += 1;\n' '}' ) inp_x = Declaration(Variable(x, type=real)) assert ccode(FunctionPrototype(real, 'pwer', [inp_x])) == 'double pwer(double x)' assert ccode(FunctionDefinition(real, 'pwer', [inp_x], [Assignment(x, x**2)])) == ( 'double pwer(double x){\n' ' x = pow(x, 2);\n' '}' ) # Elements of CodeBlock are formatted as statements: block = CodeBlock( x, Print([x, y], "%d %d"), FunctionCall('pwer', [x]), Return(x), ) assert ccode(block) == '\n'.join([ 'x;', 'printf("%d %d", x, y);', 'pwer(x);', 'return x;', ]) def test_ccode_submodule(): # Test the compatibility sympy.printing.ccode module imports with warns_deprecated_sympy(): import sympy.printing.ccode # noqa:F401 def test_ccode_UnevaluatedExpr(): assert ccode(UnevaluatedExpr(y * x) + z) == "z + x*y" assert ccode(UnevaluatedExpr(y + x) + z) == "z + (x + y)" # gh-21955 w = symbols('w') assert ccode(UnevaluatedExpr(y + x) + UnevaluatedExpr(z + w)) == "(w + z) + (x + y)" p, q, r = symbols("p q r", real=True) q_r = UnevaluatedExpr(q + r) expr = abs(exp(p+q_r)) assert ccode(expr) == "exp(p + (q + r))" def test_ccode_array_like_containers(): assert ccode([2,3,4]) == "{2, 3, 4}" assert ccode((2,3,4)) == "{2, 3, 4}"
31029f2ec339092abdbf82393026a473560f21e862f85f256ae2710c6590394e
from sympy.algebras.quaternion import Quaternion from sympy.calculus.accumulationbounds import AccumBounds from sympy.combinatorics.permutations import Cycle, Permutation, AppliedPermutation from sympy.concrete.products import Product from sympy.concrete.summations import Sum from sympy.core.containers import Tuple, Dict from sympy.core.expr import UnevaluatedExpr from sympy.core.function import (Derivative, Function, Lambda, Subs, diff) from sympy.core.mod import Mod from sympy.core.mul import Mul from sympy.core.numbers import (AlgebraicNumber, Float, I, Integer, Rational, oo, pi) from sympy.core.power import Pow from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Symbol, Wild, symbols) from sympy.functions.combinatorial.factorials import (FallingFactorial, RisingFactorial, binomial, factorial, factorial2, subfactorial) from sympy.functions.combinatorial.numbers import bernoulli, bell, catalan, euler, lucas, fibonacci, tribonacci from sympy.functions.elementary.complexes import (Abs, arg, conjugate, im, polar_lift, re) from sympy.functions.elementary.exponential import (LambertW, exp, log) from sympy.functions.elementary.hyperbolic import (asinh, coth) from sympy.functions.elementary.integers import (ceiling, floor, frac) from sympy.functions.elementary.miscellaneous import (Max, Min, root, sqrt) from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (acsc, asin, cos, cot, sin, tan) from sympy.functions.special.beta_functions import beta from sympy.functions.special.delta_functions import (DiracDelta, Heaviside) from sympy.functions.special.elliptic_integrals import (elliptic_e, elliptic_f, elliptic_k, elliptic_pi) from sympy.functions.special.error_functions import (Chi, Ci, Ei, Shi, Si, expint) from sympy.functions.special.gamma_functions import (gamma, uppergamma) from sympy.functions.special.hyper import (hyper, meijerg) from sympy.functions.special.mathieu_functions import (mathieuc, mathieucprime, mathieus, mathieusprime) from sympy.functions.special.polynomials import (assoc_laguerre, assoc_legendre, chebyshevt, chebyshevu, gegenbauer, hermite, jacobi, laguerre, legendre) from sympy.functions.special.singularity_functions import SingularityFunction from sympy.functions.special.spherical_harmonics import (Ynm, Znm) from sympy.functions.special.tensor_functions import (KroneckerDelta, LeviCivita) from sympy.functions.special.zeta_functions import (dirichlet_eta, lerchphi, polylog, stieltjes, zeta) from sympy.integrals.integrals import Integral from sympy.integrals.transforms import (CosineTransform, FourierTransform, InverseCosineTransform, InverseFourierTransform, InverseLaplaceTransform, InverseMellinTransform, InverseSineTransform, LaplaceTransform, MellinTransform, SineTransform) from sympy.logic import Implies from sympy.logic.boolalg import (And, Or, Xor, Equivalent, false, Not, true) from sympy.matrices.dense import Matrix from sympy.matrices.expressions.kronecker import KroneckerProduct from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.expressions.permutation import PermutationMatrix from sympy.matrices.expressions.slice import MatrixSlice from sympy.physics.control.lti import TransferFunction, Series, Parallel, Feedback, TransferFunctionMatrix, MIMOSeries, MIMOParallel, MIMOFeedback from sympy.ntheory.factor_ import (divisor_sigma, primenu, primeomega, reduced_totient, totient, udivisor_sigma) from sympy.physics.quantum import Commutator, Operator from sympy.physics.quantum.trace import Tr from sympy.physics.units import meter, gibibyte, microgram, second from sympy.polys.domains.integerring import ZZ from sympy.polys.fields import field from sympy.polys.polytools import Poly from sympy.polys.rings import ring from sympy.polys.rootoftools import (RootSum, rootof) from sympy.series.formal import fps from sympy.series.fourier import fourier_series from sympy.series.limits import Limit from sympy.series.order import Order from sympy.series.sequences import (SeqAdd, SeqFormula, SeqMul, SeqPer) from sympy.sets.conditionset import ConditionSet from sympy.sets.contains import Contains from sympy.sets.fancysets import (ComplexRegion, ImageSet, Range) from sympy.sets.sets import (FiniteSet, Interval, Union, Intersection, Complement, SymmetricDifference, ProductSet) from sympy.sets.setexpr import SetExpr from sympy.stats.crv_types import Normal from sympy.stats.symbolic_probability import (Covariance, Expectation, Probability, Variance) from sympy.tensor.array import (ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableSparseNDimArray, MutableDenseNDimArray, tensorproduct) from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayElement from sympy.tensor.indexed import (Indexed, IndexedBase) from sympy.tensor.toperators import PartialDerivative from sympy.vector import CoordSys3D, Cross, Curl, Dot, Divergence, Gradient, Laplacian from sympy.testing.pytest import XFAIL, raises, _both_exp_pow from sympy.printing.latex import (latex, translate, greek_letters_set, tex_greek_dictionary, multiline_latex, latex_escape, LatexPrinter) import sympy as sym from sympy.abc import mu, tau class lowergamma(sym.lowergamma): pass # testing notation inheritance by a subclass with same name x, y, z, t, w, a, b, c, s, p = symbols('x y z t w a b c s p') k, m, n = symbols('k m n', integer=True) def test_printmethod(): class R(Abs): def _latex(self, printer): return "foo(%s)" % printer._print(self.args[0]) assert latex(R(x)) == r"foo(x)" class R(Abs): def _latex(self, printer): return "foo" assert latex(R(x)) == r"foo" def test_latex_basic(): assert latex(1 + x) == r"x + 1" assert latex(x**2) == r"x^{2}" assert latex(x**(1 + x)) == r"x^{x + 1}" assert latex(x**3 + x + 1 + x**2) == r"x^{3} + x^{2} + x + 1" assert latex(2*x*y) == r"2 x y" assert latex(2*x*y, mul_symbol='dot') == r"2 \cdot x \cdot y" assert latex(3*x**2*y, mul_symbol='\\,') == r"3\,x^{2}\,y" assert latex(1.5*3**x, mul_symbol='\\,') == r"1.5 \cdot 3^{x}" assert latex(x**S.Half**5) == r"\sqrt[32]{x}" assert latex(Mul(S.Half, x**2, -5, evaluate=False)) == r"\frac{1}{2} x^{2} \left(-5\right)" assert latex(Mul(S.Half, x**2, 5, evaluate=False)) == r"\frac{1}{2} x^{2} \cdot 5" assert latex(Mul(-5, -5, evaluate=False)) == r"\left(-5\right) \left(-5\right)" assert latex(Mul(5, -5, evaluate=False)) == r"5 \left(-5\right)" assert latex(Mul(S.Half, -5, S.Half, evaluate=False)) == r"\frac{1}{2} \left(-5\right) \frac{1}{2}" assert latex(Mul(5, I, 5, evaluate=False)) == r"5 i 5" assert latex(Mul(5, I, -5, evaluate=False)) == r"5 i \left(-5\right)" assert latex(Mul(0, 1, evaluate=False)) == r'0 \cdot 1' assert latex(Mul(1, 0, evaluate=False)) == r'1 \cdot 0' assert latex(Mul(1, 1, evaluate=False)) == r'1 \cdot 1' assert latex(Mul(-1, 1, evaluate=False)) == r'\left(-1\right) 1' assert latex(Mul(1, 1, 1, evaluate=False)) == r'1 \cdot 1 \cdot 1' assert latex(Mul(1, 2, evaluate=False)) == r'1 \cdot 2' assert latex(Mul(1, S.Half, evaluate=False)) == r'1 \cdot \frac{1}{2}' assert latex(Mul(1, 1, S.Half, evaluate=False)) == \ r'1 \cdot 1 \cdot \frac{1}{2}' assert latex(Mul(1, 1, 2, 3, x, evaluate=False)) == \ r'1 \cdot 1 \cdot 2 \cdot 3 x' assert latex(Mul(1, -1, evaluate=False)) == r'1 \left(-1\right)' assert latex(Mul(4, 3, 2, 1, 0, y, x, evaluate=False)) == \ r'4 \cdot 3 \cdot 2 \cdot 1 \cdot 0 y x' assert latex(Mul(4, 3, 2, 1+z, 0, y, x, evaluate=False)) == \ r'4 \cdot 3 \cdot 2 \left(z + 1\right) 0 y x' assert latex(Mul(Rational(2, 3), Rational(5, 7), evaluate=False)) == \ r'\frac{2}{3} \cdot \frac{5}{7}' assert latex(1/x) == r"\frac{1}{x}" assert latex(1/x, fold_short_frac=True) == r"1 / x" assert latex(-S(3)/2) == r"- \frac{3}{2}" assert latex(-S(3)/2, fold_short_frac=True) == r"- 3 / 2" assert latex(1/x**2) == r"\frac{1}{x^{2}}" assert latex(1/(x + y)/2) == r"\frac{1}{2 \left(x + y\right)}" assert latex(x/2) == r"\frac{x}{2}" assert latex(x/2, fold_short_frac=True) == r"x / 2" assert latex((x + y)/(2*x)) == r"\frac{x + y}{2 x}" assert latex((x + y)/(2*x), fold_short_frac=True) == \ r"\left(x + y\right) / 2 x" assert latex((x + y)/(2*x), long_frac_ratio=0) == \ r"\frac{1}{2 x} \left(x + y\right)" assert latex((x + y)/x) == r"\frac{x + y}{x}" assert latex((x + y)/x, long_frac_ratio=3) == r"\frac{x + y}{x}" assert latex((2*sqrt(2)*x)/3) == r"\frac{2 \sqrt{2} x}{3}" assert latex((2*sqrt(2)*x)/3, long_frac_ratio=2) == \ r"\frac{2 x}{3} \sqrt{2}" assert latex(binomial(x, y)) == r"{\binom{x}{y}}" x_star = Symbol('x^*') f = Function('f') assert latex(x_star**2) == r"\left(x^{*}\right)^{2}" assert latex(x_star**2, parenthesize_super=False) == r"{x^{*}}^{2}" assert latex(Derivative(f(x_star), x_star,2)) == r"\frac{d^{2}}{d \left(x^{*}\right)^{2}} f{\left(x^{*} \right)}" assert latex(Derivative(f(x_star), x_star,2), parenthesize_super=False) == r"\frac{d^{2}}{d {x^{*}}^{2}} f{\left(x^{*} \right)}" assert latex(2*Integral(x, x)/3) == r"\frac{2 \int x\, dx}{3}" assert latex(2*Integral(x, x)/3, fold_short_frac=True) == \ r"\left(2 \int x\, dx\right) / 3" assert latex(sqrt(x)) == r"\sqrt{x}" assert latex(x**Rational(1, 3)) == r"\sqrt[3]{x}" assert latex(x**Rational(1, 3), root_notation=False) == r"x^{\frac{1}{3}}" assert latex(sqrt(x)**3) == r"x^{\frac{3}{2}}" assert latex(sqrt(x), itex=True) == r"\sqrt{x}" assert latex(x**Rational(1, 3), itex=True) == r"\root{3}{x}" assert latex(sqrt(x)**3, itex=True) == r"x^{\frac{3}{2}}" assert latex(x**Rational(3, 4)) == r"x^{\frac{3}{4}}" assert latex(x**Rational(3, 4), fold_frac_powers=True) == r"x^{3/4}" assert latex((x + 1)**Rational(3, 4)) == \ r"\left(x + 1\right)^{\frac{3}{4}}" assert latex((x + 1)**Rational(3, 4), fold_frac_powers=True) == \ r"\left(x + 1\right)^{3/4}" assert latex(AlgebraicNumber(sqrt(2))) == r"\sqrt{2}" assert latex(AlgebraicNumber(sqrt(2), [3, -7])) == r"-7 + 3 \sqrt{2}" assert latex(AlgebraicNumber(sqrt(2), alias='alpha')) == r"\alpha" assert latex(AlgebraicNumber(sqrt(2), [3, -7], alias='alpha')) == \ r"3 \alpha - 7" assert latex(AlgebraicNumber(2**(S(1)/3), [1, 3, -7], alias='beta')) == \ r"\beta^{2} + 3 \beta - 7" assert latex(1.5e20*x) == r"1.5 \cdot 10^{20} x" assert latex(1.5e20*x, mul_symbol='dot') == r"1.5 \cdot 10^{20} \cdot x" assert latex(1.5e20*x, mul_symbol='times') == \ r"1.5 \times 10^{20} \times x" assert latex(1/sin(x)) == r"\frac{1}{\sin{\left(x \right)}}" assert latex(sin(x)**-1) == r"\frac{1}{\sin{\left(x \right)}}" assert latex(sin(x)**Rational(3, 2)) == \ r"\sin^{\frac{3}{2}}{\left(x \right)}" assert latex(sin(x)**Rational(3, 2), fold_frac_powers=True) == \ r"\sin^{3/2}{\left(x \right)}" assert latex(~x) == r"\neg x" assert latex(x & y) == r"x \wedge y" assert latex(x & y & z) == r"x \wedge y \wedge z" assert latex(x | y) == r"x \vee y" assert latex(x | y | z) == r"x \vee y \vee z" assert latex((x & y) | z) == r"z \vee \left(x \wedge y\right)" assert latex(Implies(x, y)) == r"x \Rightarrow y" assert latex(~(x >> ~y)) == r"x \not\Rightarrow \neg y" assert latex(Implies(Or(x,y), z)) == r"\left(x \vee y\right) \Rightarrow z" assert latex(Implies(z, Or(x,y))) == r"z \Rightarrow \left(x \vee y\right)" assert latex(~(x & y)) == r"\neg \left(x \wedge y\right)" assert latex(~x, symbol_names={x: "x_i"}) == r"\neg x_i" assert latex(x & y, symbol_names={x: "x_i", y: "y_i"}) == \ r"x_i \wedge y_i" assert latex(x & y & z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \ r"x_i \wedge y_i \wedge z_i" assert latex(x | y, symbol_names={x: "x_i", y: "y_i"}) == r"x_i \vee y_i" assert latex(x | y | z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \ r"x_i \vee y_i \vee z_i" assert latex((x & y) | z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \ r"z_i \vee \left(x_i \wedge y_i\right)" assert latex(Implies(x, y), symbol_names={x: "x_i", y: "y_i"}) == \ r"x_i \Rightarrow y_i" assert latex(Pow(Rational(1, 3), -1, evaluate=False)) == r"\frac{1}{\frac{1}{3}}" assert latex(Pow(Rational(1, 3), -2, evaluate=False)) == r"\frac{1}{(\frac{1}{3})^{2}}" assert latex(Pow(Integer(1)/100, -1, evaluate=False)) == r"\frac{1}{\frac{1}{100}}" p = Symbol('p', positive=True) assert latex(exp(-p)*log(p)) == r"e^{- p} \log{\left(p \right)}" def test_latex_builtins(): assert latex(True) == r"\text{True}" assert latex(False) == r"\text{False}" assert latex(None) == r"\text{None}" assert latex(true) == r"\text{True}" assert latex(false) == r'\text{False}' def test_latex_SingularityFunction(): assert latex(SingularityFunction(x, 4, 5)) == \ r"{\left\langle x - 4 \right\rangle}^{5}" assert latex(SingularityFunction(x, -3, 4)) == \ r"{\left\langle x + 3 \right\rangle}^{4}" assert latex(SingularityFunction(x, 0, 4)) == \ r"{\left\langle x \right\rangle}^{4}" assert latex(SingularityFunction(x, a, n)) == \ r"{\left\langle - a + x \right\rangle}^{n}" assert latex(SingularityFunction(x, 4, -2)) == \ r"{\left\langle x - 4 \right\rangle}^{-2}" assert latex(SingularityFunction(x, 4, -1)) == \ r"{\left\langle x - 4 \right\rangle}^{-1}" assert latex(SingularityFunction(x, 4, 5)**3) == \ r"{\left({\langle x - 4 \rangle}^{5}\right)}^{3}" assert latex(SingularityFunction(x, -3, 4)**3) == \ r"{\left({\langle x + 3 \rangle}^{4}\right)}^{3}" assert latex(SingularityFunction(x, 0, 4)**3) == \ r"{\left({\langle x \rangle}^{4}\right)}^{3}" assert latex(SingularityFunction(x, a, n)**3) == \ r"{\left({\langle - a + x \rangle}^{n}\right)}^{3}" assert latex(SingularityFunction(x, 4, -2)**3) == \ r"{\left({\langle x - 4 \rangle}^{-2}\right)}^{3}" assert latex((SingularityFunction(x, 4, -1)**3)**3) == \ r"{\left({\langle x - 4 \rangle}^{-1}\right)}^{9}" def test_latex_cycle(): assert latex(Cycle(1, 2, 4)) == r"\left( 1\; 2\; 4\right)" assert latex(Cycle(1, 2)(4, 5, 6)) == \ r"\left( 1\; 2\right)\left( 4\; 5\; 6\right)" assert latex(Cycle()) == r"\left( \right)" def test_latex_permutation(): assert latex(Permutation(1, 2, 4)) == r"\left( 1\; 2\; 4\right)" assert latex(Permutation(1, 2)(4, 5, 6)) == \ r"\left( 1\; 2\right)\left( 4\; 5\; 6\right)" assert latex(Permutation()) == r"\left( \right)" assert latex(Permutation(2, 4)*Permutation(5)) == \ r"\left( 2\; 4\right)\left( 5\right)" assert latex(Permutation(5)) == r"\left( 5\right)" assert latex(Permutation(0, 1), perm_cyclic=False) == \ r"\begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}" assert latex(Permutation(0, 1)(2, 3), perm_cyclic=False) == \ r"\begin{pmatrix} 0 & 1 & 2 & 3 \\ 1 & 0 & 3 & 2 \end{pmatrix}" assert latex(Permutation(), perm_cyclic=False) == \ r"\left( \right)" def test_latex_Float(): assert latex(Float(1.0e100)) == r"1.0 \cdot 10^{100}" assert latex(Float(1.0e-100)) == r"1.0 \cdot 10^{-100}" assert latex(Float(1.0e-100), mul_symbol="times") == \ r"1.0 \times 10^{-100}" assert latex(Float('10000.0'), full_prec=False, min=-2, max=2) == \ r"1.0 \cdot 10^{4}" assert latex(Float('10000.0'), full_prec=False, min=-2, max=4) == \ r"1.0 \cdot 10^{4}" assert latex(Float('10000.0'), full_prec=False, min=-2, max=5) == \ r"10000.0" assert latex(Float('0.099999'), full_prec=True, min=-2, max=5) == \ r"9.99990000000000 \cdot 10^{-2}" def test_latex_vector_expressions(): A = CoordSys3D('A') assert latex(Cross(A.i, A.j*A.x*3+A.k)) == \ r"\mathbf{\hat{i}_{A}} \times \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}} + \mathbf{\hat{k}_{A}}\right)" assert latex(Cross(A.i, A.j)) == \ r"\mathbf{\hat{i}_{A}} \times \mathbf{\hat{j}_{A}}" assert latex(x*Cross(A.i, A.j)) == \ r"x \left(\mathbf{\hat{i}_{A}} \times \mathbf{\hat{j}_{A}}\right)" assert latex(Cross(x*A.i, A.j)) == \ r'- \mathbf{\hat{j}_{A}} \times \left((x)\mathbf{\hat{i}_{A}}\right)' assert latex(Curl(3*A.x*A.j)) == \ r"\nabla\times \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)" assert latex(Curl(3*A.x*A.j+A.i)) == \ r"\nabla\times \left(\mathbf{\hat{i}_{A}} + (3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)" assert latex(Curl(3*x*A.x*A.j)) == \ r"\nabla\times \left((3 \mathbf{{x}_{A}} x)\mathbf{\hat{j}_{A}}\right)" assert latex(x*Curl(3*A.x*A.j)) == \ r"x \left(\nabla\times \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)\right)" assert latex(Divergence(3*A.x*A.j+A.i)) == \ r"\nabla\cdot \left(\mathbf{\hat{i}_{A}} + (3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)" assert latex(Divergence(3*A.x*A.j)) == \ r"\nabla\cdot \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)" assert latex(x*Divergence(3*A.x*A.j)) == \ r"x \left(\nabla\cdot \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)\right)" assert latex(Dot(A.i, A.j*A.x*3+A.k)) == \ r"\mathbf{\hat{i}_{A}} \cdot \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}} + \mathbf{\hat{k}_{A}}\right)" assert latex(Dot(A.i, A.j)) == \ r"\mathbf{\hat{i}_{A}} \cdot \mathbf{\hat{j}_{A}}" assert latex(Dot(x*A.i, A.j)) == \ r"\mathbf{\hat{j}_{A}} \cdot \left((x)\mathbf{\hat{i}_{A}}\right)" assert latex(x*Dot(A.i, A.j)) == \ r"x \left(\mathbf{\hat{i}_{A}} \cdot \mathbf{\hat{j}_{A}}\right)" assert latex(Gradient(A.x)) == r"\nabla \mathbf{{x}_{A}}" assert latex(Gradient(A.x + 3*A.y)) == \ r"\nabla \left(\mathbf{{x}_{A}} + 3 \mathbf{{y}_{A}}\right)" assert latex(x*Gradient(A.x)) == r"x \left(\nabla \mathbf{{x}_{A}}\right)" assert latex(Gradient(x*A.x)) == r"\nabla \left(\mathbf{{x}_{A}} x\right)" assert latex(Laplacian(A.x)) == r"\triangle \mathbf{{x}_{A}}" assert latex(Laplacian(A.x + 3*A.y)) == \ r"\triangle \left(\mathbf{{x}_{A}} + 3 \mathbf{{y}_{A}}\right)" assert latex(x*Laplacian(A.x)) == r"x \left(\triangle \mathbf{{x}_{A}}\right)" assert latex(Laplacian(x*A.x)) == r"\triangle \left(\mathbf{{x}_{A}} x\right)" def test_latex_symbols(): Gamma, lmbda, rho = symbols('Gamma, lambda, rho') tau, Tau, TAU, taU = symbols('tau, Tau, TAU, taU') assert latex(tau) == r"\tau" assert latex(Tau) == r"T" assert latex(TAU) == r"\tau" assert latex(taU) == r"\tau" # Check that all capitalized greek letters are handled explicitly capitalized_letters = {l.capitalize() for l in greek_letters_set} assert len(capitalized_letters - set(tex_greek_dictionary.keys())) == 0 assert latex(Gamma + lmbda) == r"\Gamma + \lambda" assert latex(Gamma * lmbda) == r"\Gamma \lambda" assert latex(Symbol('q1')) == r"q_{1}" assert latex(Symbol('q21')) == r"q_{21}" assert latex(Symbol('epsilon0')) == r"\epsilon_{0}" assert latex(Symbol('omega1')) == r"\omega_{1}" assert latex(Symbol('91')) == r"91" assert latex(Symbol('alpha_new')) == r"\alpha_{new}" assert latex(Symbol('C^orig')) == r"C^{orig}" assert latex(Symbol('x^alpha')) == r"x^{\alpha}" assert latex(Symbol('beta^alpha')) == r"\beta^{\alpha}" assert latex(Symbol('e^Alpha')) == r"e^{A}" assert latex(Symbol('omega_alpha^beta')) == r"\omega^{\beta}_{\alpha}" assert latex(Symbol('omega') ** Symbol('beta')) == r"\omega^{\beta}" @XFAIL def test_latex_symbols_failing(): rho, mass, volume = symbols('rho, mass, volume') assert latex( volume * rho == mass) == r"\rho \mathrm{volume} = \mathrm{mass}" assert latex(volume / mass * rho == 1) == \ r"\rho \mathrm{volume} {\mathrm{mass}}^{(-1)} = 1" assert latex(mass**3 * volume**3) == \ r"{\mathrm{mass}}^{3} \cdot {\mathrm{volume}}^{3}" @_both_exp_pow def test_latex_functions(): assert latex(exp(x)) == r"e^{x}" assert latex(exp(1) + exp(2)) == r"e + e^{2}" f = Function('f') assert latex(f(x)) == r'f{\left(x \right)}' assert latex(f) == r'f' g = Function('g') assert latex(g(x, y)) == r'g{\left(x,y \right)}' assert latex(g) == r'g' h = Function('h') assert latex(h(x, y, z)) == r'h{\left(x,y,z \right)}' assert latex(h) == r'h' Li = Function('Li') assert latex(Li) == r'\operatorname{Li}' assert latex(Li(x)) == r'\operatorname{Li}{\left(x \right)}' mybeta = Function('beta') # not to be confused with the beta function assert latex(mybeta(x, y, z)) == r"\beta{\left(x,y,z \right)}" assert latex(beta(x, y)) == r'\operatorname{B}\left(x, y\right)' assert latex(beta(x, y)**2) == r'\operatorname{B}^{2}\left(x, y\right)' assert latex(mybeta(x)) == r"\beta{\left(x \right)}" assert latex(mybeta) == r"\beta" g = Function('gamma') # not to be confused with the gamma function assert latex(g(x, y, z)) == r"\gamma{\left(x,y,z \right)}" assert latex(g(x)) == r"\gamma{\left(x \right)}" assert latex(g) == r"\gamma" a1 = Function('a_1') assert latex(a1) == r"\operatorname{a_{1}}" assert latex(a1(x)) == r"\operatorname{a_{1}}{\left(x \right)}" # issue 5868 omega1 = Function('omega1') assert latex(omega1) == r"\omega_{1}" assert latex(omega1(x)) == r"\omega_{1}{\left(x \right)}" assert latex(sin(x)) == r"\sin{\left(x \right)}" assert latex(sin(x), fold_func_brackets=True) == r"\sin {x}" assert latex(sin(2*x**2), fold_func_brackets=True) == \ r"\sin {2 x^{2}}" assert latex(sin(x**2), fold_func_brackets=True) == \ r"\sin {x^{2}}" assert latex(asin(x)**2) == r"\operatorname{asin}^{2}{\left(x \right)}" assert latex(asin(x)**2, inv_trig_style="full") == \ r"\arcsin^{2}{\left(x \right)}" assert latex(asin(x)**2, inv_trig_style="power") == \ r"\sin^{-1}{\left(x \right)}^{2}" assert latex(asin(x**2), inv_trig_style="power", fold_func_brackets=True) == \ r"\sin^{-1} {x^{2}}" assert latex(acsc(x), inv_trig_style="full") == \ r"\operatorname{arccsc}{\left(x \right)}" assert latex(asinh(x), inv_trig_style="full") == \ r"\operatorname{arcsinh}{\left(x \right)}" assert latex(factorial(k)) == r"k!" assert latex(factorial(-k)) == r"\left(- k\right)!" assert latex(factorial(k)**2) == r"k!^{2}" assert latex(subfactorial(k)) == r"!k" assert latex(subfactorial(-k)) == r"!\left(- k\right)" assert latex(subfactorial(k)**2) == r"\left(!k\right)^{2}" assert latex(factorial2(k)) == r"k!!" assert latex(factorial2(-k)) == r"\left(- k\right)!!" assert latex(factorial2(k)**2) == r"k!!^{2}" assert latex(binomial(2, k)) == r"{\binom{2}{k}}" assert latex(binomial(2, k)**2) == r"{\binom{2}{k}}^{2}" assert latex(FallingFactorial(3, k)) == r"{\left(3\right)}_{k}" assert latex(RisingFactorial(3, k)) == r"{3}^{\left(k\right)}" assert latex(floor(x)) == r"\left\lfloor{x}\right\rfloor" assert latex(ceiling(x)) == r"\left\lceil{x}\right\rceil" assert latex(frac(x)) == r"\operatorname{frac}{\left(x\right)}" assert latex(floor(x)**2) == r"\left\lfloor{x}\right\rfloor^{2}" assert latex(ceiling(x)**2) == r"\left\lceil{x}\right\rceil^{2}" assert latex(frac(x)**2) == r"\operatorname{frac}{\left(x\right)}^{2}" assert latex(Min(x, 2, x**3)) == r"\min\left(2, x, x^{3}\right)" assert latex(Min(x, y)**2) == r"\min\left(x, y\right)^{2}" assert latex(Max(x, 2, x**3)) == r"\max\left(2, x, x^{3}\right)" assert latex(Max(x, y)**2) == r"\max\left(x, y\right)^{2}" assert latex(Abs(x)) == r"\left|{x}\right|" assert latex(Abs(x)**2) == r"\left|{x}\right|^{2}" assert latex(re(x)) == r"\operatorname{re}{\left(x\right)}" assert latex(re(x + y)) == \ r"\operatorname{re}{\left(x\right)} + \operatorname{re}{\left(y\right)}" assert latex(im(x)) == r"\operatorname{im}{\left(x\right)}" assert latex(conjugate(x)) == r"\overline{x}" assert latex(conjugate(x)**2) == r"\overline{x}^{2}" assert latex(conjugate(x**2)) == r"\overline{x}^{2}" assert latex(gamma(x)) == r"\Gamma\left(x\right)" w = Wild('w') assert latex(gamma(w)) == r"\Gamma\left(w\right)" assert latex(Order(x)) == r"O\left(x\right)" assert latex(Order(x, x)) == r"O\left(x\right)" assert latex(Order(x, (x, 0))) == r"O\left(x\right)" assert latex(Order(x, (x, oo))) == r"O\left(x; x\rightarrow \infty\right)" assert latex(Order(x - y, (x, y))) == \ r"O\left(x - y; x\rightarrow y\right)" assert latex(Order(x, x, y)) == \ r"O\left(x; \left( x, \ y\right)\rightarrow \left( 0, \ 0\right)\right)" assert latex(Order(x, x, y)) == \ r"O\left(x; \left( x, \ y\right)\rightarrow \left( 0, \ 0\right)\right)" assert latex(Order(x, (x, oo), (y, oo))) == \ r"O\left(x; \left( x, \ y\right)\rightarrow \left( \infty, \ \infty\right)\right)" assert latex(lowergamma(x, y)) == r'\gamma\left(x, y\right)' assert latex(lowergamma(x, y)**2) == r'\gamma^{2}\left(x, y\right)' assert latex(uppergamma(x, y)) == r'\Gamma\left(x, y\right)' assert latex(uppergamma(x, y)**2) == r'\Gamma^{2}\left(x, y\right)' assert latex(cot(x)) == r'\cot{\left(x \right)}' assert latex(coth(x)) == r'\coth{\left(x \right)}' assert latex(re(x)) == r'\operatorname{re}{\left(x\right)}' assert latex(im(x)) == r'\operatorname{im}{\left(x\right)}' assert latex(root(x, y)) == r'x^{\frac{1}{y}}' assert latex(arg(x)) == r'\arg{\left(x \right)}' assert latex(zeta(x)) == r"\zeta\left(x\right)" assert latex(zeta(x)**2) == r"\zeta^{2}\left(x\right)" assert latex(zeta(x, y)) == r"\zeta\left(x, y\right)" assert latex(zeta(x, y)**2) == r"\zeta^{2}\left(x, y\right)" assert latex(dirichlet_eta(x)) == r"\eta\left(x\right)" assert latex(dirichlet_eta(x)**2) == r"\eta^{2}\left(x\right)" assert latex(polylog(x, y)) == r"\operatorname{Li}_{x}\left(y\right)" assert latex( polylog(x, y)**2) == r"\operatorname{Li}_{x}^{2}\left(y\right)" assert latex(lerchphi(x, y, n)) == r"\Phi\left(x, y, n\right)" assert latex(lerchphi(x, y, n)**2) == r"\Phi^{2}\left(x, y, n\right)" assert latex(stieltjes(x)) == r"\gamma_{x}" assert latex(stieltjes(x)**2) == r"\gamma_{x}^{2}" assert latex(stieltjes(x, y)) == r"\gamma_{x}\left(y\right)" assert latex(stieltjes(x, y)**2) == r"\gamma_{x}\left(y\right)^{2}" assert latex(elliptic_k(z)) == r"K\left(z\right)" assert latex(elliptic_k(z)**2) == r"K^{2}\left(z\right)" assert latex(elliptic_f(x, y)) == r"F\left(x\middle| y\right)" assert latex(elliptic_f(x, y)**2) == r"F^{2}\left(x\middle| y\right)" assert latex(elliptic_e(x, y)) == r"E\left(x\middle| y\right)" assert latex(elliptic_e(x, y)**2) == r"E^{2}\left(x\middle| y\right)" assert latex(elliptic_e(z)) == r"E\left(z\right)" assert latex(elliptic_e(z)**2) == r"E^{2}\left(z\right)" assert latex(elliptic_pi(x, y, z)) == r"\Pi\left(x; y\middle| z\right)" assert latex(elliptic_pi(x, y, z)**2) == \ r"\Pi^{2}\left(x; y\middle| z\right)" assert latex(elliptic_pi(x, y)) == r"\Pi\left(x\middle| y\right)" assert latex(elliptic_pi(x, y)**2) == r"\Pi^{2}\left(x\middle| y\right)" assert latex(Ei(x)) == r'\operatorname{Ei}{\left(x \right)}' assert latex(Ei(x)**2) == r'\operatorname{Ei}^{2}{\left(x \right)}' assert latex(expint(x, y)) == r'\operatorname{E}_{x}\left(y\right)' assert latex(expint(x, y)**2) == r'\operatorname{E}_{x}^{2}\left(y\right)' assert latex(Shi(x)**2) == r'\operatorname{Shi}^{2}{\left(x \right)}' assert latex(Si(x)**2) == r'\operatorname{Si}^{2}{\left(x \right)}' assert latex(Ci(x)**2) == r'\operatorname{Ci}^{2}{\left(x \right)}' assert latex(Chi(x)**2) == r'\operatorname{Chi}^{2}\left(x\right)' assert latex(Chi(x)) == r'\operatorname{Chi}\left(x\right)' assert latex(jacobi(n, a, b, x)) == \ r'P_{n}^{\left(a,b\right)}\left(x\right)' assert latex(jacobi(n, a, b, x)**2) == \ r'\left(P_{n}^{\left(a,b\right)}\left(x\right)\right)^{2}' assert latex(gegenbauer(n, a, x)) == \ r'C_{n}^{\left(a\right)}\left(x\right)' assert latex(gegenbauer(n, a, x)**2) == \ r'\left(C_{n}^{\left(a\right)}\left(x\right)\right)^{2}' assert latex(chebyshevt(n, x)) == r'T_{n}\left(x\right)' assert latex(chebyshevt(n, x)**2) == \ r'\left(T_{n}\left(x\right)\right)^{2}' assert latex(chebyshevu(n, x)) == r'U_{n}\left(x\right)' assert latex(chebyshevu(n, x)**2) == \ r'\left(U_{n}\left(x\right)\right)^{2}' assert latex(legendre(n, x)) == r'P_{n}\left(x\right)' assert latex(legendre(n, x)**2) == r'\left(P_{n}\left(x\right)\right)^{2}' assert latex(assoc_legendre(n, a, x)) == \ r'P_{n}^{\left(a\right)}\left(x\right)' assert latex(assoc_legendre(n, a, x)**2) == \ r'\left(P_{n}^{\left(a\right)}\left(x\right)\right)^{2}' assert latex(laguerre(n, x)) == r'L_{n}\left(x\right)' assert latex(laguerre(n, x)**2) == r'\left(L_{n}\left(x\right)\right)^{2}' assert latex(assoc_laguerre(n, a, x)) == \ r'L_{n}^{\left(a\right)}\left(x\right)' assert latex(assoc_laguerre(n, a, x)**2) == \ r'\left(L_{n}^{\left(a\right)}\left(x\right)\right)^{2}' assert latex(hermite(n, x)) == r'H_{n}\left(x\right)' assert latex(hermite(n, x)**2) == r'\left(H_{n}\left(x\right)\right)^{2}' theta = Symbol("theta", real=True) phi = Symbol("phi", real=True) assert latex(Ynm(n, m, theta, phi)) == r'Y_{n}^{m}\left(\theta,\phi\right)' assert latex(Ynm(n, m, theta, phi)**3) == \ r'\left(Y_{n}^{m}\left(\theta,\phi\right)\right)^{3}' assert latex(Znm(n, m, theta, phi)) == r'Z_{n}^{m}\left(\theta,\phi\right)' assert latex(Znm(n, m, theta, phi)**3) == \ r'\left(Z_{n}^{m}\left(\theta,\phi\right)\right)^{3}' # Test latex printing of function names with "_" assert latex(polar_lift(0)) == \ r"\operatorname{polar\_lift}{\left(0 \right)}" assert latex(polar_lift(0)**3) == \ r"\operatorname{polar\_lift}^{3}{\left(0 \right)}" assert latex(totient(n)) == r'\phi\left(n\right)' assert latex(totient(n) ** 2) == r'\left(\phi\left(n\right)\right)^{2}' assert latex(reduced_totient(n)) == r'\lambda\left(n\right)' assert latex(reduced_totient(n) ** 2) == \ r'\left(\lambda\left(n\right)\right)^{2}' assert latex(divisor_sigma(x)) == r"\sigma\left(x\right)" assert latex(divisor_sigma(x)**2) == r"\sigma^{2}\left(x\right)" assert latex(divisor_sigma(x, y)) == r"\sigma_y\left(x\right)" assert latex(divisor_sigma(x, y)**2) == r"\sigma^{2}_y\left(x\right)" assert latex(udivisor_sigma(x)) == r"\sigma^*\left(x\right)" assert latex(udivisor_sigma(x)**2) == r"\sigma^*^{2}\left(x\right)" assert latex(udivisor_sigma(x, y)) == r"\sigma^*_y\left(x\right)" assert latex(udivisor_sigma(x, y)**2) == r"\sigma^*^{2}_y\left(x\right)" assert latex(primenu(n)) == r'\nu\left(n\right)' assert latex(primenu(n) ** 2) == r'\left(\nu\left(n\right)\right)^{2}' assert latex(primeomega(n)) == r'\Omega\left(n\right)' assert latex(primeomega(n) ** 2) == \ r'\left(\Omega\left(n\right)\right)^{2}' assert latex(LambertW(n)) == r'W\left(n\right)' assert latex(LambertW(n, -1)) == r'W_{-1}\left(n\right)' assert latex(LambertW(n, k)) == r'W_{k}\left(n\right)' assert latex(LambertW(n) * LambertW(n)) == r"W^{2}\left(n\right)" assert latex(Pow(LambertW(n), 2)) == r"W^{2}\left(n\right)" assert latex(LambertW(n)**k) == r"W^{k}\left(n\right)" assert latex(LambertW(n, k)**p) == r"W^{p}_{k}\left(n\right)" assert latex(Mod(x, 7)) == r'x \bmod 7' assert latex(Mod(x + 1, 7)) == r'\left(x + 1\right) \bmod 7' assert latex(Mod(7, x + 1)) == r'7 \bmod \left(x + 1\right)' assert latex(Mod(2 * x, 7)) == r'2 x \bmod 7' assert latex(Mod(7, 2 * x)) == r'7 \bmod 2 x' assert latex(Mod(x, 7) + 1) == r'\left(x \bmod 7\right) + 1' assert latex(2 * Mod(x, 7)) == r'2 \left(x \bmod 7\right)' assert latex(Mod(7, 2 * x)**n) == r'\left(7 \bmod 2 x\right)^{n}' # some unknown function name should get rendered with \operatorname fjlkd = Function('fjlkd') assert latex(fjlkd(x)) == r'\operatorname{fjlkd}{\left(x \right)}' # even when it is referred to without an argument assert latex(fjlkd) == r'\operatorname{fjlkd}' # test that notation passes to subclasses of the same name only def test_function_subclass_different_name(): class mygamma(gamma): pass assert latex(mygamma) == r"\operatorname{mygamma}" assert latex(mygamma(x)) == r"\operatorname{mygamma}{\left(x \right)}" def test_hyper_printing(): from sympy.abc import x, z assert latex(meijerg(Tuple(pi, pi, x), Tuple(1), (0, 1), Tuple(1, 2, 3/pi), z)) == \ r'{G_{4, 5}^{2, 3}\left(\begin{matrix} \pi, \pi, x & 1 \\0, 1 & 1, 2, '\ r'\frac{3}{\pi} \end{matrix} \middle| {z} \right)}' assert latex(meijerg(Tuple(), Tuple(1), (0,), Tuple(), z)) == \ r'{G_{1, 1}^{1, 0}\left(\begin{matrix} & 1 \\0 & \end{matrix} \middle| {z} \right)}' assert latex(hyper((x, 2), (3,), z)) == \ r'{{}_{2}F_{1}\left(\begin{matrix} x, 2 ' \ r'\\ 3 \end{matrix}\middle| {z} \right)}' assert latex(hyper(Tuple(), Tuple(1), z)) == \ r'{{}_{0}F_{1}\left(\begin{matrix} ' \ r'\\ 1 \end{matrix}\middle| {z} \right)}' def test_latex_bessel(): from sympy.functions.special.bessel import (besselj, bessely, besseli, besselk, hankel1, hankel2, jn, yn, hn1, hn2) from sympy.abc import z assert latex(besselj(n, z**2)**k) == r'J^{k}_{n}\left(z^{2}\right)' assert latex(bessely(n, z)) == r'Y_{n}\left(z\right)' assert latex(besseli(n, z)) == r'I_{n}\left(z\right)' assert latex(besselk(n, z)) == r'K_{n}\left(z\right)' assert latex(hankel1(n, z**2)**2) == \ r'\left(H^{(1)}_{n}\left(z^{2}\right)\right)^{2}' assert latex(hankel2(n, z)) == r'H^{(2)}_{n}\left(z\right)' assert latex(jn(n, z)) == r'j_{n}\left(z\right)' assert latex(yn(n, z)) == r'y_{n}\left(z\right)' assert latex(hn1(n, z)) == r'h^{(1)}_{n}\left(z\right)' assert latex(hn2(n, z)) == r'h^{(2)}_{n}\left(z\right)' def test_latex_fresnel(): from sympy.functions.special.error_functions import (fresnels, fresnelc) from sympy.abc import z assert latex(fresnels(z)) == r'S\left(z\right)' assert latex(fresnelc(z)) == r'C\left(z\right)' assert latex(fresnels(z)**2) == r'S^{2}\left(z\right)' assert latex(fresnelc(z)**2) == r'C^{2}\left(z\right)' def test_latex_brackets(): assert latex((-1)**x) == r"\left(-1\right)^{x}" def test_latex_indexed(): Psi_symbol = Symbol('Psi_0', complex=True, real=False) Psi_indexed = IndexedBase(Symbol('Psi', complex=True, real=False)) symbol_latex = latex(Psi_symbol * conjugate(Psi_symbol)) indexed_latex = latex(Psi_indexed[0] * conjugate(Psi_indexed[0])) # \\overline{{\\Psi}_{0}} {\\Psi}_{0} vs. \\Psi_{0} \\overline{\\Psi_{0}} assert symbol_latex == r'\Psi_{0} \overline{\Psi_{0}}' assert indexed_latex == r'\overline{{\Psi}_{0}} {\Psi}_{0}' # Symbol('gamma') gives r'\gamma' assert latex(Indexed('x1', Symbol('i'))) == r'{x_{1}}_{i}' assert latex(IndexedBase('gamma')) == r'\gamma' assert latex(IndexedBase('a b')) == r'a b' assert latex(IndexedBase('a_b')) == r'a_{b}' def test_latex_derivatives(): # regular "d" for ordinary derivatives assert latex(diff(x**3, x, evaluate=False)) == \ r"\frac{d}{d x} x^{3}" assert latex(diff(sin(x) + x**2, x, evaluate=False)) == \ r"\frac{d}{d x} \left(x^{2} + \sin{\left(x \right)}\right)" assert latex(diff(diff(sin(x) + x**2, x, evaluate=False), evaluate=False))\ == \ r"\frac{d^{2}}{d x^{2}} \left(x^{2} + \sin{\left(x \right)}\right)" assert latex(diff(diff(diff(sin(x) + x**2, x, evaluate=False), evaluate=False), evaluate=False)) == \ r"\frac{d^{3}}{d x^{3}} \left(x^{2} + \sin{\left(x \right)}\right)" # \partial for partial derivatives assert latex(diff(sin(x * y), x, evaluate=False)) == \ r"\frac{\partial}{\partial x} \sin{\left(x y \right)}" assert latex(diff(sin(x * y) + x**2, x, evaluate=False)) == \ r"\frac{\partial}{\partial x} \left(x^{2} + \sin{\left(x y \right)}\right)" assert latex(diff(diff(sin(x*y) + x**2, x, evaluate=False), x, evaluate=False)) == \ r"\frac{\partial^{2}}{\partial x^{2}} \left(x^{2} + \sin{\left(x y \right)}\right)" assert latex(diff(diff(diff(sin(x*y) + x**2, x, evaluate=False), x, evaluate=False), x, evaluate=False)) == \ r"\frac{\partial^{3}}{\partial x^{3}} \left(x^{2} + \sin{\left(x y \right)}\right)" # mixed partial derivatives f = Function("f") assert latex(diff(diff(f(x, y), x, evaluate=False), y, evaluate=False)) == \ r"\frac{\partial^{2}}{\partial y\partial x} " + latex(f(x, y)) assert latex(diff(diff(diff(f(x, y), x, evaluate=False), x, evaluate=False), y, evaluate=False)) == \ r"\frac{\partial^{3}}{\partial y\partial x^{2}} " + latex(f(x, y)) # for negative nested Derivative assert latex(diff(-diff(y**2,x,evaluate=False),x,evaluate=False)) == r'\frac{d}{d x} \left(- \frac{d}{d x} y^{2}\right)' assert latex(diff(diff(-diff(diff(y,x,evaluate=False),x,evaluate=False),x,evaluate=False),x,evaluate=False)) == \ r'\frac{d^{2}}{d x^{2}} \left(- \frac{d^{2}}{d x^{2}} y\right)' # use ordinary d when one of the variables has been integrated out assert latex(diff(Integral(exp(-x*y), (x, 0, oo)), y, evaluate=False)) == \ r"\frac{d}{d y} \int\limits_{0}^{\infty} e^{- x y}\, dx" # Derivative wrapped in power: assert latex(diff(x, x, evaluate=False)**2) == \ r"\left(\frac{d}{d x} x\right)^{2}" assert latex(diff(f(x), x)**2) == \ r"\left(\frac{d}{d x} f{\left(x \right)}\right)^{2}" assert latex(diff(f(x), (x, n))) == \ r"\frac{d^{n}}{d x^{n}} f{\left(x \right)}" x1 = Symbol('x1') x2 = Symbol('x2') assert latex(diff(f(x1, x2), x1)) == r'\frac{\partial}{\partial x_{1}} f{\left(x_{1},x_{2} \right)}' n1 = Symbol('n1') assert latex(diff(f(x), (x, n1))) == r'\frac{d^{n_{1}}}{d x^{n_{1}}} f{\left(x \right)}' n2 = Symbol('n2') assert latex(diff(f(x), (x, Max(n1, n2)))) == \ r'\frac{d^{\max\left(n_{1}, n_{2}\right)}}{d x^{\max\left(n_{1}, n_{2}\right)}} f{\left(x \right)}' def test_latex_subs(): assert latex(Subs(x*y, (x, y), (1, 2))) == r'\left. x y \right|_{\substack{ x=1\\ y=2 }}' def test_latex_integrals(): assert latex(Integral(log(x), x)) == r"\int \log{\left(x \right)}\, dx" assert latex(Integral(x**2, (x, 0, 1))) == \ r"\int\limits_{0}^{1} x^{2}\, dx" assert latex(Integral(x**2, (x, 10, 20))) == \ r"\int\limits_{10}^{20} x^{2}\, dx" assert latex(Integral(y*x**2, (x, 0, 1), y)) == \ r"\int\int\limits_{0}^{1} x^{2} y\, dx\, dy" assert latex(Integral(y*x**2, (x, 0, 1), y), mode='equation*') == \ r"\begin{equation*}\int\int\limits_{0}^{1} x^{2} y\, dx\, dy\end{equation*}" assert latex(Integral(y*x**2, (x, 0, 1), y), mode='equation*', itex=True) \ == r"$$\int\int_{0}^{1} x^{2} y\, dx\, dy$$" assert latex(Integral(x, (x, 0))) == r"\int\limits^{0} x\, dx" assert latex(Integral(x*y, x, y)) == r"\iint x y\, dx\, dy" assert latex(Integral(x*y*z, x, y, z)) == r"\iiint x y z\, dx\, dy\, dz" assert latex(Integral(x*y*z*t, x, y, z, t)) == \ r"\iiiint t x y z\, dx\, dy\, dz\, dt" assert latex(Integral(x, x, x, x, x, x, x)) == \ r"\int\int\int\int\int\int x\, dx\, dx\, dx\, dx\, dx\, dx" assert latex(Integral(x, x, y, (z, 0, 1))) == \ r"\int\limits_{0}^{1}\int\int x\, dx\, dy\, dz" # for negative nested Integral assert latex(Integral(-Integral(y**2,x),x)) == \ r'\int \left(- \int y^{2}\, dx\right)\, dx' assert latex(Integral(-Integral(-Integral(y,x),x),x)) == \ r'\int \left(- \int \left(- \int y\, dx\right)\, dx\right)\, dx' # fix issue #10806 assert latex(Integral(z, z)**2) == r"\left(\int z\, dz\right)^{2}" assert latex(Integral(x + z, z)) == r"\int \left(x + z\right)\, dz" assert latex(Integral(x+z/2, z)) == \ r"\int \left(x + \frac{z}{2}\right)\, dz" assert latex(Integral(x**y, z)) == r"\int x^{y}\, dz" def test_latex_sets(): for s in (frozenset, set): assert latex(s([x*y, x**2])) == r"\left\{x^{2}, x y\right\}" assert latex(s(range(1, 6))) == r"\left\{1, 2, 3, 4, 5\right\}" assert latex(s(range(1, 13))) == \ r"\left\{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12\right\}" s = FiniteSet assert latex(s(*[x*y, x**2])) == r"\left\{x^{2}, x y\right\}" assert latex(s(*range(1, 6))) == r"\left\{1, 2, 3, 4, 5\right\}" assert latex(s(*range(1, 13))) == \ r"\left\{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12\right\}" def test_latex_SetExpr(): iv = Interval(1, 3) se = SetExpr(iv) assert latex(se) == r"SetExpr\left(\left[1, 3\right]\right)" def test_latex_Range(): assert latex(Range(1, 51)) == r'\left\{1, 2, \ldots, 50\right\}' assert latex(Range(1, 4)) == r'\left\{1, 2, 3\right\}' assert latex(Range(0, 3, 1)) == r'\left\{0, 1, 2\right\}' assert latex(Range(0, 30, 1)) == r'\left\{0, 1, \ldots, 29\right\}' assert latex(Range(30, 1, -1)) == r'\left\{30, 29, \ldots, 2\right\}' assert latex(Range(0, oo, 2)) == r'\left\{0, 2, \ldots\right\}' assert latex(Range(oo, -2, -2)) == r'\left\{\ldots, 2, 0\right\}' assert latex(Range(-2, -oo, -1)) == r'\left\{-2, -3, \ldots\right\}' assert latex(Range(-oo, oo)) == r'\left\{\ldots, -1, 0, 1, \ldots\right\}' assert latex(Range(oo, -oo, -1)) == r'\left\{\ldots, 1, 0, -1, \ldots\right\}' a, b, c = symbols('a:c') assert latex(Range(a, b, c)) == r'\text{Range}\left(a, b, c\right)' assert latex(Range(a, 10, 1)) == r'\text{Range}\left(a, 10\right)' assert latex(Range(0, b, 1)) == r'\text{Range}\left(b\right)' assert latex(Range(0, 10, c)) == r'\text{Range}\left(0, 10, c\right)' i = Symbol('i', integer=True) n = Symbol('n', negative=True, integer=True) p = Symbol('p', positive=True, integer=True) assert latex(Range(i, i + 3)) == r'\left\{i, i + 1, i + 2\right\}' assert latex(Range(-oo, n, 2)) == r'\left\{\ldots, n - 4, n - 2\right\}' assert latex(Range(p, oo)) == r'\left\{p, p + 1, \ldots\right\}' # The following will work if __iter__ is improved # assert latex(Range(-3, p + 7)) == r'\left\{-3, -2, \ldots, p + 6\right\}' # Must have integer assumptions assert latex(Range(a, a + 3)) == r'\text{Range}\left(a, a + 3\right)' def test_latex_sequences(): s1 = SeqFormula(a**2, (0, oo)) s2 = SeqPer((1, 2)) latex_str = r'\left[0, 1, 4, 9, \ldots\right]' assert latex(s1) == latex_str latex_str = r'\left[1, 2, 1, 2, \ldots\right]' assert latex(s2) == latex_str s3 = SeqFormula(a**2, (0, 2)) s4 = SeqPer((1, 2), (0, 2)) latex_str = r'\left[0, 1, 4\right]' assert latex(s3) == latex_str latex_str = r'\left[1, 2, 1\right]' assert latex(s4) == latex_str s5 = SeqFormula(a**2, (-oo, 0)) s6 = SeqPer((1, 2), (-oo, 0)) latex_str = r'\left[\ldots, 9, 4, 1, 0\right]' assert latex(s5) == latex_str latex_str = r'\left[\ldots, 2, 1, 2, 1\right]' assert latex(s6) == latex_str latex_str = r'\left[1, 3, 5, 11, \ldots\right]' assert latex(SeqAdd(s1, s2)) == latex_str latex_str = r'\left[1, 3, 5\right]' assert latex(SeqAdd(s3, s4)) == latex_str latex_str = r'\left[\ldots, 11, 5, 3, 1\right]' assert latex(SeqAdd(s5, s6)) == latex_str latex_str = r'\left[0, 2, 4, 18, \ldots\right]' assert latex(SeqMul(s1, s2)) == latex_str latex_str = r'\left[0, 2, 4\right]' assert latex(SeqMul(s3, s4)) == latex_str latex_str = r'\left[\ldots, 18, 4, 2, 0\right]' assert latex(SeqMul(s5, s6)) == latex_str # Sequences with symbolic limits, issue 12629 s7 = SeqFormula(a**2, (a, 0, x)) latex_str = r'\left\{a^{2}\right\}_{a=0}^{x}' assert latex(s7) == latex_str b = Symbol('b') s8 = SeqFormula(b*a**2, (a, 0, 2)) latex_str = r'\left[0, b, 4 b\right]' assert latex(s8) == latex_str def test_latex_FourierSeries(): latex_str = \ r'2 \sin{\left(x \right)} - \sin{\left(2 x \right)} + \frac{2 \sin{\left(3 x \right)}}{3} + \ldots' assert latex(fourier_series(x, (x, -pi, pi))) == latex_str def test_latex_FormalPowerSeries(): latex_str = r'\sum_{k=1}^{\infty} - \frac{\left(-1\right)^{- k} x^{k}}{k}' assert latex(fps(log(1 + x))) == latex_str def test_latex_intervals(): a = Symbol('a', real=True) assert latex(Interval(0, 0)) == r"\left\{0\right\}" assert latex(Interval(0, a)) == r"\left[0, a\right]" assert latex(Interval(0, a, False, False)) == r"\left[0, a\right]" assert latex(Interval(0, a, True, False)) == r"\left(0, a\right]" assert latex(Interval(0, a, False, True)) == r"\left[0, a\right)" assert latex(Interval(0, a, True, True)) == r"\left(0, a\right)" def test_latex_AccumuBounds(): a = Symbol('a', real=True) assert latex(AccumBounds(0, 1)) == r"\left\langle 0, 1\right\rangle" assert latex(AccumBounds(0, a)) == r"\left\langle 0, a\right\rangle" assert latex(AccumBounds(a + 1, a + 2)) == \ r"\left\langle a + 1, a + 2\right\rangle" def test_latex_emptyset(): assert latex(S.EmptySet) == r"\emptyset" def test_latex_universalset(): assert latex(S.UniversalSet) == r"\mathbb{U}" def test_latex_commutator(): A = Operator('A') B = Operator('B') comm = Commutator(B, A) assert latex(comm.doit()) == r"- (A B - B A)" def test_latex_union(): assert latex(Union(Interval(0, 1), Interval(2, 3))) == \ r"\left[0, 1\right] \cup \left[2, 3\right]" assert latex(Union(Interval(1, 1), Interval(2, 2), Interval(3, 4))) == \ r"\left\{1, 2\right\} \cup \left[3, 4\right]" def test_latex_intersection(): assert latex(Intersection(Interval(0, 1), Interval(x, y))) == \ r"\left[0, 1\right] \cap \left[x, y\right]" def test_latex_symmetric_difference(): assert latex(SymmetricDifference(Interval(2, 5), Interval(4, 7), evaluate=False)) == \ r'\left[2, 5\right] \triangle \left[4, 7\right]' def test_latex_Complement(): assert latex(Complement(S.Reals, S.Naturals)) == \ r"\mathbb{R} \setminus \mathbb{N}" def test_latex_productset(): line = Interval(0, 1) bigline = Interval(0, 10) fset = FiniteSet(1, 2, 3) assert latex(line**2) == r"%s^{2}" % latex(line) assert latex(line**10) == r"%s^{10}" % latex(line) assert latex((line * bigline * fset).flatten()) == r"%s \times %s \times %s" % ( latex(line), latex(bigline), latex(fset)) def test_set_operators_parenthesis(): a, b, c, d = symbols('a:d') A = FiniteSet(a) B = FiniteSet(b) C = FiniteSet(c) D = FiniteSet(d) U1 = Union(A, B, evaluate=False) U2 = Union(C, D, evaluate=False) I1 = Intersection(A, B, evaluate=False) I2 = Intersection(C, D, evaluate=False) C1 = Complement(A, B, evaluate=False) C2 = Complement(C, D, evaluate=False) D1 = SymmetricDifference(A, B, evaluate=False) D2 = SymmetricDifference(C, D, evaluate=False) # XXX ProductSet does not support evaluate keyword P1 = ProductSet(A, B) P2 = ProductSet(C, D) assert latex(Intersection(A, U2, evaluate=False)) == \ r'\left\{a\right\} \cap ' \ r'\left(\left\{c\right\} \cup \left\{d\right\}\right)' assert latex(Intersection(U1, U2, evaluate=False)) == \ r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \ r'\cap \left(\left\{c\right\} \cup \left\{d\right\}\right)' assert latex(Intersection(C1, C2, evaluate=False)) == \ r'\left(\left\{a\right\} \setminus ' \ r'\left\{b\right\}\right) \cap \left(\left\{c\right\} ' \ r'\setminus \left\{d\right\}\right)' assert latex(Intersection(D1, D2, evaluate=False)) == \ r'\left(\left\{a\right\} \triangle ' \ r'\left\{b\right\}\right) \cap \left(\left\{c\right\} ' \ r'\triangle \left\{d\right\}\right)' assert latex(Intersection(P1, P2, evaluate=False)) == \ r'\left(\left\{a\right\} \times \left\{b\right\}\right) ' \ r'\cap \left(\left\{c\right\} \times ' \ r'\left\{d\right\}\right)' assert latex(Union(A, I2, evaluate=False)) == \ r'\left\{a\right\} \cup ' \ r'\left(\left\{c\right\} \cap \left\{d\right\}\right)' assert latex(Union(I1, I2, evaluate=False)) == \ r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \ r'\cup \left(\left\{c\right\} \cap \left\{d\right\}\right)' assert latex(Union(C1, C2, evaluate=False)) == \ r'\left(\left\{a\right\} \setminus ' \ r'\left\{b\right\}\right) \cup \left(\left\{c\right\} ' \ r'\setminus \left\{d\right\}\right)' assert latex(Union(D1, D2, evaluate=False)) == \ r'\left(\left\{a\right\} \triangle ' \ r'\left\{b\right\}\right) \cup \left(\left\{c\right\} ' \ r'\triangle \left\{d\right\}\right)' assert latex(Union(P1, P2, evaluate=False)) == \ r'\left(\left\{a\right\} \times \left\{b\right\}\right) ' \ r'\cup \left(\left\{c\right\} \times ' \ r'\left\{d\right\}\right)' assert latex(Complement(A, C2, evaluate=False)) == \ r'\left\{a\right\} \setminus \left(\left\{c\right\} ' \ r'\setminus \left\{d\right\}\right)' assert latex(Complement(U1, U2, evaluate=False)) == \ r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \ r'\setminus \left(\left\{c\right\} \cup ' \ r'\left\{d\right\}\right)' assert latex(Complement(I1, I2, evaluate=False)) == \ r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \ r'\setminus \left(\left\{c\right\} \cap ' \ r'\left\{d\right\}\right)' assert latex(Complement(D1, D2, evaluate=False)) == \ r'\left(\left\{a\right\} \triangle ' \ r'\left\{b\right\}\right) \setminus ' \ r'\left(\left\{c\right\} \triangle \left\{d\right\}\right)' assert latex(Complement(P1, P2, evaluate=False)) == \ r'\left(\left\{a\right\} \times \left\{b\right\}\right) '\ r'\setminus \left(\left\{c\right\} \times '\ r'\left\{d\right\}\right)' assert latex(SymmetricDifference(A, D2, evaluate=False)) == \ r'\left\{a\right\} \triangle \left(\left\{c\right\} ' \ r'\triangle \left\{d\right\}\right)' assert latex(SymmetricDifference(U1, U2, evaluate=False)) == \ r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \ r'\triangle \left(\left\{c\right\} \cup ' \ r'\left\{d\right\}\right)' assert latex(SymmetricDifference(I1, I2, evaluate=False)) == \ r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \ r'\triangle \left(\left\{c\right\} \cap ' \ r'\left\{d\right\}\right)' assert latex(SymmetricDifference(C1, C2, evaluate=False)) == \ r'\left(\left\{a\right\} \setminus ' \ r'\left\{b\right\}\right) \triangle ' \ r'\left(\left\{c\right\} \setminus \left\{d\right\}\right)' assert latex(SymmetricDifference(P1, P2, evaluate=False)) == \ r'\left(\left\{a\right\} \times \left\{b\right\}\right) ' \ r'\triangle \left(\left\{c\right\} \times ' \ r'\left\{d\right\}\right)' # XXX This can be incorrect since cartesian product is not associative assert latex(ProductSet(A, P2).flatten()) == \ r'\left\{a\right\} \times \left\{c\right\} \times ' \ r'\left\{d\right\}' assert latex(ProductSet(U1, U2)) == \ r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \ r'\times \left(\left\{c\right\} \cup ' \ r'\left\{d\right\}\right)' assert latex(ProductSet(I1, I2)) == \ r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \ r'\times \left(\left\{c\right\} \cap ' \ r'\left\{d\right\}\right)' assert latex(ProductSet(C1, C2)) == \ r'\left(\left\{a\right\} \setminus ' \ r'\left\{b\right\}\right) \times \left(\left\{c\right\} ' \ r'\setminus \left\{d\right\}\right)' assert latex(ProductSet(D1, D2)) == \ r'\left(\left\{a\right\} \triangle ' \ r'\left\{b\right\}\right) \times \left(\left\{c\right\} ' \ r'\triangle \left\{d\right\}\right)' def test_latex_Complexes(): assert latex(S.Complexes) == r"\mathbb{C}" def test_latex_Naturals(): assert latex(S.Naturals) == r"\mathbb{N}" def test_latex_Naturals0(): assert latex(S.Naturals0) == r"\mathbb{N}_0" def test_latex_Integers(): assert latex(S.Integers) == r"\mathbb{Z}" def test_latex_ImageSet(): x = Symbol('x') assert latex(ImageSet(Lambda(x, x**2), S.Naturals)) == \ r"\left\{x^{2}\; \middle|\; x \in \mathbb{N}\right\}" y = Symbol('y') imgset = ImageSet(Lambda((x, y), x + y), {1, 2, 3}, {3, 4}) assert latex(imgset) == \ r"\left\{x + y\; \middle|\; x \in \left\{1, 2, 3\right\}, y \in \left\{3, 4\right\}\right\}" imgset = ImageSet(Lambda(((x, y),), x + y), ProductSet({1, 2, 3}, {3, 4})) assert latex(imgset) == \ r"\left\{x + y\; \middle|\; \left( x, \ y\right) \in \left\{1, 2, 3\right\} \times \left\{3, 4\right\}\right\}" def test_latex_ConditionSet(): x = Symbol('x') assert latex(ConditionSet(x, Eq(x**2, 1), S.Reals)) == \ r"\left\{x\; \middle|\; x \in \mathbb{R} \wedge x^{2} = 1 \right\}" assert latex(ConditionSet(x, Eq(x**2, 1), S.UniversalSet)) == \ r"\left\{x\; \middle|\; x^{2} = 1 \right\}" def test_latex_ComplexRegion(): assert latex(ComplexRegion(Interval(3, 5)*Interval(4, 6))) == \ r"\left\{x + y i\; \middle|\; x, y \in \left[3, 5\right] \times \left[4, 6\right] \right\}" assert latex(ComplexRegion(Interval(0, 1)*Interval(0, 2*pi), polar=True)) == \ r"\left\{r \left(i \sin{\left(\theta \right)} + \cos{\left(\theta "\ r"\right)}\right)\; \middle|\; r, \theta \in \left[0, 1\right] \times \left[0, 2 \pi\right) \right\}" def test_latex_Contains(): x = Symbol('x') assert latex(Contains(x, S.Naturals)) == r"x \in \mathbb{N}" def test_latex_sum(): assert latex(Sum(x*y**2, (x, -2, 2), (y, -5, 5))) == \ r"\sum_{\substack{-2 \leq x \leq 2\\-5 \leq y \leq 5}} x y^{2}" assert latex(Sum(x**2, (x, -2, 2))) == \ r"\sum_{x=-2}^{2} x^{2}" assert latex(Sum(x**2 + y, (x, -2, 2))) == \ r"\sum_{x=-2}^{2} \left(x^{2} + y\right)" assert latex(Sum(x**2 + y, (x, -2, 2))**2) == \ r"\left(\sum_{x=-2}^{2} \left(x^{2} + y\right)\right)^{2}" def test_latex_product(): assert latex(Product(x*y**2, (x, -2, 2), (y, -5, 5))) == \ r"\prod_{\substack{-2 \leq x \leq 2\\-5 \leq y \leq 5}} x y^{2}" assert latex(Product(x**2, (x, -2, 2))) == \ r"\prod_{x=-2}^{2} x^{2}" assert latex(Product(x**2 + y, (x, -2, 2))) == \ r"\prod_{x=-2}^{2} \left(x^{2} + y\right)" assert latex(Product(x, (x, -2, 2))**2) == \ r"\left(\prod_{x=-2}^{2} x\right)^{2}" def test_latex_limits(): assert latex(Limit(x, x, oo)) == r"\lim_{x \to \infty} x" # issue 8175 f = Function('f') assert latex(Limit(f(x), x, 0)) == r"\lim_{x \to 0^+} f{\left(x \right)}" assert latex(Limit(f(x), x, 0, "-")) == \ r"\lim_{x \to 0^-} f{\left(x \right)}" # issue #10806 assert latex(Limit(f(x), x, 0)**2) == \ r"\left(\lim_{x \to 0^+} f{\left(x \right)}\right)^{2}" # bi-directional limit assert latex(Limit(f(x), x, 0, dir='+-')) == \ r"\lim_{x \to 0} f{\left(x \right)}" def test_latex_log(): assert latex(log(x)) == r"\log{\left(x \right)}" assert latex(log(x), ln_notation=True) == r"\ln{\left(x \right)}" assert latex(log(x) + log(y)) == \ r"\log{\left(x \right)} + \log{\left(y \right)}" assert latex(log(x) + log(y), ln_notation=True) == \ r"\ln{\left(x \right)} + \ln{\left(y \right)}" assert latex(pow(log(x), x)) == r"\log{\left(x \right)}^{x}" assert latex(pow(log(x), x), ln_notation=True) == \ r"\ln{\left(x \right)}^{x}" def test_issue_3568(): beta = Symbol(r'\beta') y = beta + x assert latex(y) in [r'\beta + x', r'x + \beta'] beta = Symbol(r'beta') y = beta + x assert latex(y) in [r'\beta + x', r'x + \beta'] def test_latex(): assert latex((2*tau)**Rational(7, 2)) == r"8 \sqrt{2} \tau^{\frac{7}{2}}" assert latex((2*mu)**Rational(7, 2), mode='equation*') == \ r"\begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*}" assert latex((2*mu)**Rational(7, 2), mode='equation', itex=True) == \ r"$$8 \sqrt{2} \mu^{\frac{7}{2}}$$" assert latex([2/x, y]) == r"\left[ \frac{2}{x}, \ y\right]" def test_latex_dict(): d = {Rational(1): 1, x**2: 2, x: 3, x**3: 4} assert latex(d) == \ r'\left\{ 1 : 1, \ x : 3, \ x^{2} : 2, \ x^{3} : 4\right\}' D = Dict(d) assert latex(D) == \ r'\left\{ 1 : 1, \ x : 3, \ x^{2} : 2, \ x^{3} : 4\right\}' def test_latex_list(): ll = [Symbol('omega1'), Symbol('a'), Symbol('alpha')] assert latex(ll) == r'\left[ \omega_{1}, \ a, \ \alpha\right]' def test_latex_NumberSymbols(): assert latex(S.Catalan) == "G" assert latex(S.EulerGamma) == r"\gamma" assert latex(S.Exp1) == "e" assert latex(S.GoldenRatio) == r"\phi" assert latex(S.Pi) == r"\pi" assert latex(S.TribonacciConstant) == r"\text{TribonacciConstant}" def test_latex_rational(): # tests issue 3973 assert latex(-Rational(1, 2)) == r"- \frac{1}{2}" assert latex(Rational(-1, 2)) == r"- \frac{1}{2}" assert latex(Rational(1, -2)) == r"- \frac{1}{2}" assert latex(-Rational(-1, 2)) == r"\frac{1}{2}" assert latex(-Rational(1, 2)*x) == r"- \frac{x}{2}" assert latex(-Rational(1, 2)*x + Rational(-2, 3)*y) == \ r"- \frac{x}{2} - \frac{2 y}{3}" def test_latex_inverse(): # tests issue 4129 assert latex(1/x) == r"\frac{1}{x}" assert latex(1/(x + y)) == r"\frac{1}{x + y}" def test_latex_DiracDelta(): assert latex(DiracDelta(x)) == r"\delta\left(x\right)" assert latex(DiracDelta(x)**2) == r"\left(\delta\left(x\right)\right)^{2}" assert latex(DiracDelta(x, 0)) == r"\delta\left(x\right)" assert latex(DiracDelta(x, 5)) == \ r"\delta^{\left( 5 \right)}\left( x \right)" assert latex(DiracDelta(x, 5)**2) == \ r"\left(\delta^{\left( 5 \right)}\left( x \right)\right)^{2}" def test_latex_Heaviside(): assert latex(Heaviside(x)) == r"\theta\left(x\right)" assert latex(Heaviside(x)**2) == r"\left(\theta\left(x\right)\right)^{2}" def test_latex_KroneckerDelta(): assert latex(KroneckerDelta(x, y)) == r"\delta_{x y}" assert latex(KroneckerDelta(x, y + 1)) == r"\delta_{x, y + 1}" # issue 6578 assert latex(KroneckerDelta(x + 1, y)) == r"\delta_{y, x + 1}" assert latex(Pow(KroneckerDelta(x, y), 2, evaluate=False)) == \ r"\left(\delta_{x y}\right)^{2}" def test_latex_LeviCivita(): assert latex(LeviCivita(x, y, z)) == r"\varepsilon_{x y z}" assert latex(LeviCivita(x, y, z)**2) == \ r"\left(\varepsilon_{x y z}\right)^{2}" assert latex(LeviCivita(x, y, z + 1)) == r"\varepsilon_{x, y, z + 1}" assert latex(LeviCivita(x, y + 1, z)) == r"\varepsilon_{x, y + 1, z}" assert latex(LeviCivita(x + 1, y, z)) == r"\varepsilon_{x + 1, y, z}" def test_mode(): expr = x + y assert latex(expr) == r'x + y' assert latex(expr, mode='plain') == r'x + y' assert latex(expr, mode='inline') == r'$x + y$' assert latex( expr, mode='equation*') == r'\begin{equation*}x + y\end{equation*}' assert latex( expr, mode='equation') == r'\begin{equation}x + y\end{equation}' raises(ValueError, lambda: latex(expr, mode='foo')) def test_latex_mathieu(): assert latex(mathieuc(x, y, z)) == r"C\left(x, y, z\right)" assert latex(mathieus(x, y, z)) == r"S\left(x, y, z\right)" assert latex(mathieuc(x, y, z)**2) == r"C\left(x, y, z\right)^{2}" assert latex(mathieus(x, y, z)**2) == r"S\left(x, y, z\right)^{2}" assert latex(mathieucprime(x, y, z)) == r"C^{\prime}\left(x, y, z\right)" assert latex(mathieusprime(x, y, z)) == r"S^{\prime}\left(x, y, z\right)" assert latex(mathieucprime(x, y, z)**2) == r"C^{\prime}\left(x, y, z\right)^{2}" assert latex(mathieusprime(x, y, z)**2) == r"S^{\prime}\left(x, y, z\right)^{2}" def test_latex_Piecewise(): p = Piecewise((x, x < 1), (x**2, True)) assert latex(p) == r"\begin{cases} x & \text{for}\: x < 1 \\x^{2} &" \ r" \text{otherwise} \end{cases}" assert latex(p, itex=True) == \ r"\begin{cases} x & \text{for}\: x \lt 1 \\x^{2} &" \ r" \text{otherwise} \end{cases}" p = Piecewise((x, x < 0), (0, x >= 0)) assert latex(p) == r'\begin{cases} x & \text{for}\: x < 0 \\0 &' \ r' \text{otherwise} \end{cases}' A, B = symbols("A B", commutative=False) p = Piecewise((A**2, Eq(A, B)), (A*B, True)) s = r"\begin{cases} A^{2} & \text{for}\: A = B \\A B & \text{otherwise} \end{cases}" assert latex(p) == s assert latex(A*p) == r"A \left(%s\right)" % s assert latex(p*A) == r"\left(%s\right) A" % s assert latex(Piecewise((x, x < 1), (x**2, x < 2))) == \ r'\begin{cases} x & ' \ r'\text{for}\: x < 1 \\x^{2} & \text{for}\: x < 2 \end{cases}' def test_latex_Matrix(): M = Matrix([[1 + x, y], [y, x - 1]]) assert latex(M) == \ r'\left[\begin{matrix}x + 1 & y\\y & x - 1\end{matrix}\right]' assert latex(M, mode='inline') == \ r'$\left[\begin{smallmatrix}x + 1 & y\\' \ r'y & x - 1\end{smallmatrix}\right]$' assert latex(M, mat_str='array') == \ r'\left[\begin{array}{cc}x + 1 & y\\y & x - 1\end{array}\right]' assert latex(M, mat_str='bmatrix') == \ r'\left[\begin{bmatrix}x + 1 & y\\y & x - 1\end{bmatrix}\right]' assert latex(M, mat_delim=None, mat_str='bmatrix') == \ r'\begin{bmatrix}x + 1 & y\\y & x - 1\end{bmatrix}' M2 = Matrix(1, 11, range(11)) assert latex(M2) == \ r'\left[\begin{array}{ccccccccccc}' \ r'0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10\end{array}\right]' def test_latex_matrix_with_functions(): t = symbols('t') theta1 = symbols('theta1', cls=Function) M = Matrix([[sin(theta1(t)), cos(theta1(t))], [cos(theta1(t).diff(t)), sin(theta1(t).diff(t))]]) expected = (r'\left[\begin{matrix}\sin{\left(' r'\theta_{1}{\left(t \right)} \right)} & ' r'\cos{\left(\theta_{1}{\left(t \right)} \right)' r'}\\\cos{\left(\frac{d}{d t} \theta_{1}{\left(t ' r'\right)} \right)} & \sin{\left(\frac{d}{d t} ' r'\theta_{1}{\left(t \right)} \right' r')}\end{matrix}\right]') assert latex(M) == expected def test_latex_NDimArray(): x, y, z, w = symbols("x y z w") for ArrayType in (ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableDenseNDimArray, MutableSparseNDimArray): # Basic: scalar array M = ArrayType(x) assert latex(M) == r"x" M = ArrayType([[1 / x, y], [z, w]]) M1 = ArrayType([1 / x, y, z]) M2 = tensorproduct(M1, M) M3 = tensorproduct(M, M) assert latex(M) == \ r'\left[\begin{matrix}\frac{1}{x} & y\\z & w\end{matrix}\right]' assert latex(M1) == \ r"\left[\begin{matrix}\frac{1}{x} & y & z\end{matrix}\right]" assert latex(M2) == \ r"\left[\begin{matrix}" \ r"\left[\begin{matrix}\frac{1}{x^{2}} & \frac{y}{x}\\\frac{z}{x} & \frac{w}{x}\end{matrix}\right] & " \ r"\left[\begin{matrix}\frac{y}{x} & y^{2}\\y z & w y\end{matrix}\right] & " \ r"\left[\begin{matrix}\frac{z}{x} & y z\\z^{2} & w z\end{matrix}\right]" \ r"\end{matrix}\right]" assert latex(M3) == \ r"""\left[\begin{matrix}"""\ r"""\left[\begin{matrix}\frac{1}{x^{2}} & \frac{y}{x}\\\frac{z}{x} & \frac{w}{x}\end{matrix}\right] & """\ r"""\left[\begin{matrix}\frac{y}{x} & y^{2}\\y z & w y\end{matrix}\right]\\"""\ r"""\left[\begin{matrix}\frac{z}{x} & y z\\z^{2} & w z\end{matrix}\right] & """\ r"""\left[\begin{matrix}\frac{w}{x} & w y\\w z & w^{2}\end{matrix}\right]"""\ r"""\end{matrix}\right]""" Mrow = ArrayType([[x, y, 1/z]]) Mcolumn = ArrayType([[x], [y], [1/z]]) Mcol2 = ArrayType([Mcolumn.tolist()]) assert latex(Mrow) == \ r"\left[\left[\begin{matrix}x & y & \frac{1}{z}\end{matrix}\right]\right]" assert latex(Mcolumn) == \ r"\left[\begin{matrix}x\\y\\\frac{1}{z}\end{matrix}\right]" assert latex(Mcol2) == \ r'\left[\begin{matrix}\left[\begin{matrix}x\\y\\\frac{1}{z}\end{matrix}\right]\end{matrix}\right]' def test_latex_mul_symbol(): assert latex(4*4**x, mul_symbol='times') == r"4 \times 4^{x}" assert latex(4*4**x, mul_symbol='dot') == r"4 \cdot 4^{x}" assert latex(4*4**x, mul_symbol='ldot') == r"4 \,.\, 4^{x}" assert latex(4*x, mul_symbol='times') == r"4 \times x" assert latex(4*x, mul_symbol='dot') == r"4 \cdot x" assert latex(4*x, mul_symbol='ldot') == r"4 \,.\, x" def test_latex_issue_4381(): y = 4*4**log(2) assert latex(y) == r'4 \cdot 4^{\log{\left(2 \right)}}' assert latex(1/y) == r'\frac{1}{4 \cdot 4^{\log{\left(2 \right)}}}' def test_latex_issue_4576(): assert latex(Symbol("beta_13_2")) == r"\beta_{13 2}" assert latex(Symbol("beta_132_20")) == r"\beta_{132 20}" assert latex(Symbol("beta_13")) == r"\beta_{13}" assert latex(Symbol("x_a_b")) == r"x_{a b}" assert latex(Symbol("x_1_2_3")) == r"x_{1 2 3}" assert latex(Symbol("x_a_b1")) == r"x_{a b1}" assert latex(Symbol("x_a_1")) == r"x_{a 1}" assert latex(Symbol("x_1_a")) == r"x_{1 a}" assert latex(Symbol("x_1^aa")) == r"x^{aa}_{1}" assert latex(Symbol("x_1__aa")) == r"x^{aa}_{1}" assert latex(Symbol("x_11^a")) == r"x^{a}_{11}" assert latex(Symbol("x_11__a")) == r"x^{a}_{11}" assert latex(Symbol("x_a_a_a_a")) == r"x_{a a a a}" assert latex(Symbol("x_a_a^a^a")) == r"x^{a a}_{a a}" assert latex(Symbol("x_a_a__a__a")) == r"x^{a a}_{a a}" assert latex(Symbol("alpha_11")) == r"\alpha_{11}" assert latex(Symbol("alpha_11_11")) == r"\alpha_{11 11}" assert latex(Symbol("alpha_alpha")) == r"\alpha_{\alpha}" assert latex(Symbol("alpha^aleph")) == r"\alpha^{\aleph}" assert latex(Symbol("alpha__aleph")) == r"\alpha^{\aleph}" def test_latex_pow_fraction(): x = Symbol('x') # Testing exp assert r'e^{-x}' in latex(exp(-x)/2).replace(' ', '') # Remove Whitespace # Testing e^{-x} in case future changes alter behavior of muls or fracs # In particular current output is \frac{1}{2}e^{- x} but perhaps this will # change to \frac{e^{-x}}{2} # Testing general, non-exp, power assert r'3^{-x}' in latex(3**-x/2).replace(' ', '') def test_noncommutative(): A, B, C = symbols('A,B,C', commutative=False) assert latex(A*B*C**-1) == r"A B C^{-1}" assert latex(C**-1*A*B) == r"C^{-1} A B" assert latex(A*C**-1*B) == r"A C^{-1} B" def test_latex_order(): expr = x**3 + x**2*y + y**4 + 3*x*y**3 assert latex(expr, order='lex') == r"x^{3} + x^{2} y + 3 x y^{3} + y^{4}" assert latex( expr, order='rev-lex') == r"y^{4} + 3 x y^{3} + x^{2} y + x^{3}" assert latex(expr, order='none') == r"x^{3} + y^{4} + y x^{2} + 3 x y^{3}" def test_latex_Lambda(): assert latex(Lambda(x, x + 1)) == r"\left( x \mapsto x + 1 \right)" assert latex(Lambda((x, y), x + 1)) == r"\left( \left( x, \ y\right) \mapsto x + 1 \right)" assert latex(Lambda(x, x)) == r"\left( x \mapsto x \right)" def test_latex_PolyElement(): Ruv, u, v = ring("u,v", ZZ) Rxyz, x, y, z = ring("x,y,z", Ruv) assert latex(x - x) == r"0" assert latex(x - 1) == r"x - 1" assert latex(x + 1) == r"x + 1" assert latex((u**2 + 3*u*v + 1)*x**2*y + u + 1) == \ r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + u + 1" assert latex((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x) == \ r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + \left(u + 1\right) x" assert latex((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x + 1) == \ r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + \left(u + 1\right) x + 1" assert latex((-u**2 + 3*u*v - 1)*x**2*y - (u + 1)*x - 1) == \ r"-\left({u}^{2} - 3 u v + 1\right) {x}^{2} y - \left(u + 1\right) x - 1" assert latex(-(v**2 + v + 1)*x + 3*u*v + 1) == \ r"-\left({v}^{2} + v + 1\right) x + 3 u v + 1" assert latex(-(v**2 + v + 1)*x - 3*u*v + 1) == \ r"-\left({v}^{2} + v + 1\right) x - 3 u v + 1" def test_latex_FracElement(): Fuv, u, v = field("u,v", ZZ) Fxyzt, x, y, z, t = field("x,y,z,t", Fuv) assert latex(x - x) == r"0" assert latex(x - 1) == r"x - 1" assert latex(x + 1) == r"x + 1" assert latex(x/3) == r"\frac{x}{3}" assert latex(x/z) == r"\frac{x}{z}" assert latex(x*y/z) == r"\frac{x y}{z}" assert latex(x/(z*t)) == r"\frac{x}{z t}" assert latex(x*y/(z*t)) == r"\frac{x y}{z t}" assert latex((x - 1)/y) == r"\frac{x - 1}{y}" assert latex((x + 1)/y) == r"\frac{x + 1}{y}" assert latex((-x - 1)/y) == r"\frac{-x - 1}{y}" assert latex((x + 1)/(y*z)) == r"\frac{x + 1}{y z}" assert latex(-y/(x + 1)) == r"\frac{-y}{x + 1}" assert latex(y*z/(x + 1)) == r"\frac{y z}{x + 1}" assert latex(((u + 1)*x*y + 1)/((v - 1)*z - 1)) == \ r"\frac{\left(u + 1\right) x y + 1}{\left(v - 1\right) z - 1}" assert latex(((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1)) == \ r"\frac{\left(u + 1\right) x y + 1}{\left(v - 1\right) z - u v t - 1}" def test_latex_Poly(): assert latex(Poly(x**2 + 2 * x, x)) == \ r"\operatorname{Poly}{\left( x^{2} + 2 x, x, domain=\mathbb{Z} \right)}" assert latex(Poly(x/y, x)) == \ r"\operatorname{Poly}{\left( \frac{1}{y} x, x, domain=\mathbb{Z}\left(y\right) \right)}" assert latex(Poly(2.0*x + y)) == \ r"\operatorname{Poly}{\left( 2.0 x + 1.0 y, x, y, domain=\mathbb{R} \right)}" def test_latex_Poly_order(): assert latex(Poly([a, 1, b, 2, c, 3], x)) == \ r'\operatorname{Poly}{\left( a x^{5} + x^{4} + b x^{3} + 2 x^{2} + c'\ r' x + 3, x, domain=\mathbb{Z}\left[a, b, c\right] \right)}' assert latex(Poly([a, 1, b+c, 2, 3], x)) == \ r'\operatorname{Poly}{\left( a x^{4} + x^{3} + \left(b + c\right) '\ r'x^{2} + 2 x + 3, x, domain=\mathbb{Z}\left[a, b, c\right] \right)}' assert latex(Poly(a*x**3 + x**2*y - x*y - c*y**3 - b*x*y**2 + y - a*x + b, (x, y))) == \ r'\operatorname{Poly}{\left( a x^{3} + x^{2}y - b xy^{2} - xy - '\ r'a x - c y^{3} + y + b, x, y, domain=\mathbb{Z}\left[a, b, c\right] \right)}' def test_latex_ComplexRootOf(): assert latex(rootof(x**5 + x + 3, 0)) == \ r"\operatorname{CRootOf} {\left(x^{5} + x + 3, 0\right)}" def test_latex_RootSum(): assert latex(RootSum(x**5 + x + 3, sin)) == \ r"\operatorname{RootSum} {\left(x^{5} + x + 3, \left( x \mapsto \sin{\left(x \right)} \right)\right)}" def test_settings(): raises(TypeError, lambda: latex(x*y, method="garbage")) def test_latex_numbers(): assert latex(catalan(n)) == r"C_{n}" assert latex(catalan(n)**2) == r"C_{n}^{2}" assert latex(bernoulli(n)) == r"B_{n}" assert latex(bernoulli(n, x)) == r"B_{n}\left(x\right)" assert latex(bernoulli(n)**2) == r"B_{n}^{2}" assert latex(bernoulli(n, x)**2) == r"B_{n}^{2}\left(x\right)" assert latex(bell(n)) == r"B_{n}" assert latex(bell(n, x)) == r"B_{n}\left(x\right)" assert latex(bell(n, m, (x, y))) == r"B_{n, m}\left(x, y\right)" assert latex(bell(n)**2) == r"B_{n}^{2}" assert latex(bell(n, x)**2) == r"B_{n}^{2}\left(x\right)" assert latex(bell(n, m, (x, y))**2) == r"B_{n, m}^{2}\left(x, y\right)" assert latex(fibonacci(n)) == r"F_{n}" assert latex(fibonacci(n, x)) == r"F_{n}\left(x\right)" assert latex(fibonacci(n)**2) == r"F_{n}^{2}" assert latex(fibonacci(n, x)**2) == r"F_{n}^{2}\left(x\right)" assert latex(lucas(n)) == r"L_{n}" assert latex(lucas(n)**2) == r"L_{n}^{2}" assert latex(tribonacci(n)) == r"T_{n}" assert latex(tribonacci(n, x)) == r"T_{n}\left(x\right)" assert latex(tribonacci(n)**2) == r"T_{n}^{2}" assert latex(tribonacci(n, x)**2) == r"T_{n}^{2}\left(x\right)" def test_latex_euler(): assert latex(euler(n)) == r"E_{n}" assert latex(euler(n, x)) == r"E_{n}\left(x\right)" assert latex(euler(n, x)**2) == r"E_{n}^{2}\left(x\right)" def test_lamda(): assert latex(Symbol('lamda')) == r"\lambda" assert latex(Symbol('Lamda')) == r"\Lambda" def test_custom_symbol_names(): x = Symbol('x') y = Symbol('y') assert latex(x) == r"x" assert latex(x, symbol_names={x: "x_i"}) == r"x_i" assert latex(x + y, symbol_names={x: "x_i"}) == r"x_i + y" assert latex(x**2, symbol_names={x: "x_i"}) == r"x_i^{2}" assert latex(x + y, symbol_names={x: "x_i", y: "y_j"}) == r"x_i + y_j" def test_matAdd(): C = MatrixSymbol('C', 5, 5) B = MatrixSymbol('B', 5, 5) l = LatexPrinter() assert l._print(C - 2*B) in [r'- 2 B + C', r'C -2 B'] assert l._print(C + 2*B) in [r'2 B + C', r'C + 2 B'] assert l._print(B - 2*C) in [r'B - 2 C', r'- 2 C + B'] assert l._print(B + 2*C) in [r'B + 2 C', r'2 C + B'] def test_matMul(): A = MatrixSymbol('A', 5, 5) B = MatrixSymbol('B', 5, 5) x = Symbol('x') lp = LatexPrinter() assert lp._print_MatMul(2*A) == r'2 A' assert lp._print_MatMul(2*x*A) == r'2 x A' assert lp._print_MatMul(-2*A) == r'- 2 A' assert lp._print_MatMul(1.5*A) == r'1.5 A' assert lp._print_MatMul(sqrt(2)*A) == r'\sqrt{2} A' assert lp._print_MatMul(-sqrt(2)*A) == r'- \sqrt{2} A' assert lp._print_MatMul(2*sqrt(2)*x*A) == r'2 \sqrt{2} x A' assert lp._print_MatMul(-2*A*(A + 2*B)) in [r'- 2 A \left(A + 2 B\right)', r'- 2 A \left(2 B + A\right)'] def test_latex_MatrixSlice(): n = Symbol('n', integer=True) x, y, z, w, t, = symbols('x y z w t') X = MatrixSymbol('X', n, n) Y = MatrixSymbol('Y', 10, 10) Z = MatrixSymbol('Z', 10, 10) assert latex(MatrixSlice(X, (None, None, None), (None, None, None))) == r'X\left[:, :\right]' assert latex(X[x:x + 1, y:y + 1]) == r'X\left[x:x + 1, y:y + 1\right]' assert latex(X[x:x + 1:2, y:y + 1:2]) == r'X\left[x:x + 1:2, y:y + 1:2\right]' assert latex(X[:x, y:]) == r'X\left[:x, y:\right]' assert latex(X[:x, y:]) == r'X\left[:x, y:\right]' assert latex(X[x:, :y]) == r'X\left[x:, :y\right]' assert latex(X[x:y, z:w]) == r'X\left[x:y, z:w\right]' assert latex(X[x:y:t, w:t:x]) == r'X\left[x:y:t, w:t:x\right]' assert latex(X[x::y, t::w]) == r'X\left[x::y, t::w\right]' assert latex(X[:x:y, :t:w]) == r'X\left[:x:y, :t:w\right]' assert latex(X[::x, ::y]) == r'X\left[::x, ::y\right]' assert latex(MatrixSlice(X, (0, None, None), (0, None, None))) == r'X\left[:, :\right]' assert latex(MatrixSlice(X, (None, n, None), (None, n, None))) == r'X\left[:, :\right]' assert latex(MatrixSlice(X, (0, n, None), (0, n, None))) == r'X\left[:, :\right]' assert latex(MatrixSlice(X, (0, n, 2), (0, n, 2))) == r'X\left[::2, ::2\right]' assert latex(X[1:2:3, 4:5:6]) == r'X\left[1:2:3, 4:5:6\right]' assert latex(X[1:3:5, 4:6:8]) == r'X\left[1:3:5, 4:6:8\right]' assert latex(X[1:10:2]) == r'X\left[1:10:2, :\right]' assert latex(Y[:5, 1:9:2]) == r'Y\left[:5, 1:9:2\right]' assert latex(Y[:5, 1:10:2]) == r'Y\left[:5, 1::2\right]' assert latex(Y[5, :5:2]) == r'Y\left[5:6, :5:2\right]' assert latex(X[0:1, 0:1]) == r'X\left[:1, :1\right]' assert latex(X[0:1:2, 0:1:2]) == r'X\left[:1:2, :1:2\right]' assert latex((Y + Z)[2:, 2:]) == r'\left(Y + Z\right)\left[2:, 2:\right]' def test_latex_RandomDomain(): from sympy.stats import Normal, Die, Exponential, pspace, where from sympy.stats.rv import RandomDomain X = Normal('x1', 0, 1) assert latex(where(X > 0)) == r"\text{Domain: }0 < x_{1} \wedge x_{1} < \infty" D = Die('d1', 6) assert latex(where(D > 4)) == r"\text{Domain: }d_{1} = 5 \vee d_{1} = 6" A = Exponential('a', 1) B = Exponential('b', 1) assert latex( pspace(Tuple(A, B)).domain) == \ r"\text{Domain: }0 \leq a \wedge 0 \leq b \wedge a < \infty \wedge b < \infty" assert latex(RandomDomain(FiniteSet(x), FiniteSet(1, 2))) == \ r'\text{Domain: }\left\{x\right\} \in \left\{1, 2\right\}' def test_PrettyPoly(): from sympy.polys.domains import QQ F = QQ.frac_field(x, y) R = QQ[x, y] assert latex(F.convert(x/(x + y))) == latex(x/(x + y)) assert latex(R.convert(x + y)) == latex(x + y) def test_integral_transforms(): x = Symbol("x") k = Symbol("k") f = Function("f") a = Symbol("a") b = Symbol("b") assert latex(MellinTransform(f(x), x, k)) == \ r"\mathcal{M}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseMellinTransform(f(k), k, x, a, b)) == \ r"\mathcal{M}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(LaplaceTransform(f(x), x, k)) == \ r"\mathcal{L}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseLaplaceTransform(f(k), k, x, (a, b))) == \ r"\mathcal{L}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(FourierTransform(f(x), x, k)) == \ r"\mathcal{F}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseFourierTransform(f(k), k, x)) == \ r"\mathcal{F}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(CosineTransform(f(x), x, k)) == \ r"\mathcal{COS}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseCosineTransform(f(k), k, x)) == \ r"\mathcal{COS}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(SineTransform(f(x), x, k)) == \ r"\mathcal{SIN}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseSineTransform(f(k), k, x)) == \ r"\mathcal{SIN}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" def test_PolynomialRingBase(): from sympy.polys.domains import QQ assert latex(QQ.old_poly_ring(x, y)) == r"\mathbb{Q}\left[x, y\right]" assert latex(QQ.old_poly_ring(x, y, order="ilex")) == \ r"S_<^{-1}\mathbb{Q}\left[x, y\right]" def test_categories(): from sympy.categories import (Object, IdentityMorphism, NamedMorphism, Category, Diagram, DiagramGrid) A1 = Object("A1") A2 = Object("A2") A3 = Object("A3") f1 = NamedMorphism(A1, A2, "f1") f2 = NamedMorphism(A2, A3, "f2") id_A1 = IdentityMorphism(A1) K1 = Category("K1") assert latex(A1) == r"A_{1}" assert latex(f1) == r"f_{1}:A_{1}\rightarrow A_{2}" assert latex(id_A1) == r"id:A_{1}\rightarrow A_{1}" assert latex(f2*f1) == r"f_{2}\circ f_{1}:A_{1}\rightarrow A_{3}" assert latex(K1) == r"\mathbf{K_{1}}" d = Diagram() assert latex(d) == r"\emptyset" d = Diagram({f1: "unique", f2: S.EmptySet}) assert latex(d) == r"\left\{ f_{2}\circ f_{1}:A_{1}" \ r"\rightarrow A_{3} : \emptyset, \ id:A_{1}\rightarrow " \ r"A_{1} : \emptyset, \ id:A_{2}\rightarrow A_{2} : " \ r"\emptyset, \ id:A_{3}\rightarrow A_{3} : \emptyset, " \ r"\ f_{1}:A_{1}\rightarrow A_{2} : \left\{unique\right\}, " \ r"\ f_{2}:A_{2}\rightarrow A_{3} : \emptyset\right\}" d = Diagram({f1: "unique", f2: S.EmptySet}, {f2 * f1: "unique"}) assert latex(d) == r"\left\{ f_{2}\circ f_{1}:A_{1}" \ r"\rightarrow A_{3} : \emptyset, \ id:A_{1}\rightarrow " \ r"A_{1} : \emptyset, \ id:A_{2}\rightarrow A_{2} : " \ r"\emptyset, \ id:A_{3}\rightarrow A_{3} : \emptyset, " \ r"\ f_{1}:A_{1}\rightarrow A_{2} : \left\{unique\right\}," \ r" \ f_{2}:A_{2}\rightarrow A_{3} : \emptyset\right\}" \ r"\Longrightarrow \left\{ f_{2}\circ f_{1}:A_{1}" \ r"\rightarrow A_{3} : \left\{unique\right\}\right\}" # A linear diagram. A = Object("A") B = Object("B") C = Object("C") f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") d = Diagram([f, g]) grid = DiagramGrid(d) assert latex(grid) == r"\begin{array}{cc}" + "\n" \ r"A & B \\" + "\n" \ r" & C " + "\n" \ r"\end{array}" + "\n" def test_Modules(): from sympy.polys.domains import QQ from sympy.polys.agca import homomorphism R = QQ.old_poly_ring(x, y) F = R.free_module(2) M = F.submodule([x, y], [1, x**2]) assert latex(F) == r"{\mathbb{Q}\left[x, y\right]}^{2}" assert latex(M) == \ r"\left\langle {\left[ {x},{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle" I = R.ideal(x**2, y) assert latex(I) == r"\left\langle {x^{2}},{y} \right\rangle" Q = F / M assert latex(Q) == \ r"\frac{{\mathbb{Q}\left[x, y\right]}^{2}}{\left\langle {\left[ {x},"\ r"{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle}" assert latex(Q.submodule([1, x**3/2], [2, y])) == \ r"\left\langle {{\left[ {1},{\frac{x^{3}}{2}} \right]} + {\left"\ r"\langle {\left[ {x},{y} \right]},{\left[ {1},{x^{2}} \right]} "\ r"\right\rangle}},{{\left[ {2},{y} \right]} + {\left\langle {\left[ "\ r"{x},{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle}} \right\rangle" h = homomorphism(QQ.old_poly_ring(x).free_module(2), QQ.old_poly_ring(x).free_module(2), [0, 0]) assert latex(h) == \ r"{\left[\begin{matrix}0 & 0\\0 & 0\end{matrix}\right]} : "\ r"{{\mathbb{Q}\left[x\right]}^{2}} \to {{\mathbb{Q}\left[x\right]}^{2}}" def test_QuotientRing(): from sympy.polys.domains import QQ R = QQ.old_poly_ring(x)/[x**2 + 1] assert latex(R) == \ r"\frac{\mathbb{Q}\left[x\right]}{\left\langle {x^{2} + 1} \right\rangle}" assert latex(R.one) == r"{1} + {\left\langle {x^{2} + 1} \right\rangle}" def test_Tr(): #TODO: Handle indices A, B = symbols('A B', commutative=False) t = Tr(A*B) assert latex(t) == r'\operatorname{tr}\left(A B\right)' def test_Adjoint(): from sympy.matrices import Adjoint, Inverse, Transpose X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert latex(Adjoint(X)) == r'X^{\dagger}' assert latex(Adjoint(X + Y)) == r'\left(X + Y\right)^{\dagger}' assert latex(Adjoint(X) + Adjoint(Y)) == r'X^{\dagger} + Y^{\dagger}' assert latex(Adjoint(X*Y)) == r'\left(X Y\right)^{\dagger}' assert latex(Adjoint(Y)*Adjoint(X)) == r'Y^{\dagger} X^{\dagger}' assert latex(Adjoint(X**2)) == r'\left(X^{2}\right)^{\dagger}' assert latex(Adjoint(X)**2) == r'\left(X^{\dagger}\right)^{2}' assert latex(Adjoint(Inverse(X))) == r'\left(X^{-1}\right)^{\dagger}' assert latex(Inverse(Adjoint(X))) == r'\left(X^{\dagger}\right)^{-1}' assert latex(Adjoint(Transpose(X))) == r'\left(X^{T}\right)^{\dagger}' assert latex(Transpose(Adjoint(X))) == r'\left(X^{\dagger}\right)^{T}' assert latex(Transpose(Adjoint(X) + Y)) == r'\left(X^{\dagger} + Y\right)^{T}' def test_Transpose(): from sympy.matrices import Transpose, MatPow, HadamardPower X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert latex(Transpose(X)) == r'X^{T}' assert latex(Transpose(X + Y)) == r'\left(X + Y\right)^{T}' assert latex(Transpose(HadamardPower(X, 2))) == r'\left(X^{\circ {2}}\right)^{T}' assert latex(HadamardPower(Transpose(X), 2)) == r'\left(X^{T}\right)^{\circ {2}}' assert latex(Transpose(MatPow(X, 2))) == r'\left(X^{2}\right)^{T}' assert latex(MatPow(Transpose(X), 2)) == r'\left(X^{T}\right)^{2}' def test_Hadamard(): from sympy.matrices import HadamardProduct, HadamardPower from sympy.matrices.expressions import MatAdd, MatMul, MatPow X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert latex(HadamardProduct(X, Y*Y)) == r'X \circ Y^{2}' assert latex(HadamardProduct(X, Y)*Y) == r'\left(X \circ Y\right) Y' assert latex(HadamardPower(X, 2)) == r'X^{\circ {2}}' assert latex(HadamardPower(X, -1)) == r'X^{\circ \left({-1}\right)}' assert latex(HadamardPower(MatAdd(X, Y), 2)) == \ r'\left(X + Y\right)^{\circ {2}}' assert latex(HadamardPower(MatMul(X, Y), 2)) == \ r'\left(X Y\right)^{\circ {2}}' assert latex(HadamardPower(MatPow(X, -1), -1)) == \ r'\left(X^{-1}\right)^{\circ \left({-1}\right)}' assert latex(MatPow(HadamardPower(X, -1), -1)) == \ r'\left(X^{\circ \left({-1}\right)}\right)^{-1}' assert latex(HadamardPower(X, n+1)) == \ r'X^{\circ \left({n + 1}\right)}' def test_ElementwiseApplyFunction(): X = MatrixSymbol('X', 2, 2) expr = (X.T*X).applyfunc(sin) assert latex(expr) == r"{\left( d \mapsto \sin{\left(d \right)} \right)}_{\circ}\left({X^{T} X}\right)" expr = X.applyfunc(Lambda(x, 1/x)) assert latex(expr) == r'{\left( x \mapsto \frac{1}{x} \right)}_{\circ}\left({X}\right)' def test_ZeroMatrix(): from sympy.matrices.expressions.special import ZeroMatrix assert latex(ZeroMatrix(1, 1), mat_symbol_style='plain') == r"0" assert latex(ZeroMatrix(1, 1), mat_symbol_style='bold') == r"\mathbf{0}" def test_OneMatrix(): from sympy.matrices.expressions.special import OneMatrix assert latex(OneMatrix(3, 4), mat_symbol_style='plain') == r"1" assert latex(OneMatrix(3, 4), mat_symbol_style='bold') == r"\mathbf{1}" def test_Identity(): from sympy.matrices.expressions.special import Identity assert latex(Identity(1), mat_symbol_style='plain') == r"\mathbb{I}" assert latex(Identity(1), mat_symbol_style='bold') == r"\mathbf{I}" def test_latex_DFT_IDFT(): from sympy.matrices.expressions.fourier import DFT, IDFT assert latex(DFT(13)) == r"\text{DFT}_{13}" assert latex(IDFT(x)) == r"\text{IDFT}_{x}" def test_boolean_args_order(): syms = symbols('a:f') expr = And(*syms) assert latex(expr) == r'a \wedge b \wedge c \wedge d \wedge e \wedge f' expr = Or(*syms) assert latex(expr) == r'a \vee b \vee c \vee d \vee e \vee f' expr = Equivalent(*syms) assert latex(expr) == \ r'a \Leftrightarrow b \Leftrightarrow c \Leftrightarrow d \Leftrightarrow e \Leftrightarrow f' expr = Xor(*syms) assert latex(expr) == \ r'a \veebar b \veebar c \veebar d \veebar e \veebar f' def test_imaginary(): i = sqrt(-1) assert latex(i) == r'i' def test_builtins_without_args(): assert latex(sin) == r'\sin' assert latex(cos) == r'\cos' assert latex(tan) == r'\tan' assert latex(log) == r'\log' assert latex(Ei) == r'\operatorname{Ei}' assert latex(zeta) == r'\zeta' def test_latex_greek_functions(): # bug because capital greeks that have roman equivalents should not use # \Alpha, \Beta, \Eta, etc. s = Function('Alpha') assert latex(s) == r'A' assert latex(s(x)) == r'A{\left(x \right)}' s = Function('Beta') assert latex(s) == r'B' s = Function('Eta') assert latex(s) == r'H' assert latex(s(x)) == r'H{\left(x \right)}' # bug because sympy.core.numbers.Pi is special p = Function('Pi') # assert latex(p(x)) == r'\Pi{\left(x \right)}' assert latex(p) == r'\Pi' # bug because not all greeks are included c = Function('chi') assert latex(c(x)) == r'\chi{\left(x \right)}' assert latex(c) == r'\chi' def test_translate(): s = 'Alpha' assert translate(s) == r'A' s = 'Beta' assert translate(s) == r'B' s = 'Eta' assert translate(s) == r'H' s = 'omicron' assert translate(s) == r'o' s = 'Pi' assert translate(s) == r'\Pi' s = 'pi' assert translate(s) == r'\pi' s = 'LamdaHatDOT' assert translate(s) == r'\dot{\hat{\Lambda}}' def test_other_symbols(): from sympy.printing.latex import other_symbols for s in other_symbols: assert latex(symbols(s)) == r"" "\\" + s def test_modifiers(): # Test each modifier individually in the simplest case # (with funny capitalizations) assert latex(symbols("xMathring")) == r"\mathring{x}" assert latex(symbols("xCheck")) == r"\check{x}" assert latex(symbols("xBreve")) == r"\breve{x}" assert latex(symbols("xAcute")) == r"\acute{x}" assert latex(symbols("xGrave")) == r"\grave{x}" assert latex(symbols("xTilde")) == r"\tilde{x}" assert latex(symbols("xPrime")) == r"{x}'" assert latex(symbols("xddDDot")) == r"\ddddot{x}" assert latex(symbols("xDdDot")) == r"\dddot{x}" assert latex(symbols("xDDot")) == r"\ddot{x}" assert latex(symbols("xBold")) == r"\boldsymbol{x}" assert latex(symbols("xnOrM")) == r"\left\|{x}\right\|" assert latex(symbols("xAVG")) == r"\left\langle{x}\right\rangle" assert latex(symbols("xHat")) == r"\hat{x}" assert latex(symbols("xDot")) == r"\dot{x}" assert latex(symbols("xBar")) == r"\bar{x}" assert latex(symbols("xVec")) == r"\vec{x}" assert latex(symbols("xAbs")) == r"\left|{x}\right|" assert latex(symbols("xMag")) == r"\left|{x}\right|" assert latex(symbols("xPrM")) == r"{x}'" assert latex(symbols("xBM")) == r"\boldsymbol{x}" # Test strings that are *only* the names of modifiers assert latex(symbols("Mathring")) == r"Mathring" assert latex(symbols("Check")) == r"Check" assert latex(symbols("Breve")) == r"Breve" assert latex(symbols("Acute")) == r"Acute" assert latex(symbols("Grave")) == r"Grave" assert latex(symbols("Tilde")) == r"Tilde" assert latex(symbols("Prime")) == r"Prime" assert latex(symbols("DDot")) == r"\dot{D}" assert latex(symbols("Bold")) == r"Bold" assert latex(symbols("NORm")) == r"NORm" assert latex(symbols("AVG")) == r"AVG" assert latex(symbols("Hat")) == r"Hat" assert latex(symbols("Dot")) == r"Dot" assert latex(symbols("Bar")) == r"Bar" assert latex(symbols("Vec")) == r"Vec" assert latex(symbols("Abs")) == r"Abs" assert latex(symbols("Mag")) == r"Mag" assert latex(symbols("PrM")) == r"PrM" assert latex(symbols("BM")) == r"BM" assert latex(symbols("hbar")) == r"\hbar" # Check a few combinations assert latex(symbols("xvecdot")) == r"\dot{\vec{x}}" assert latex(symbols("xDotVec")) == r"\vec{\dot{x}}" assert latex(symbols("xHATNorm")) == r"\left\|{\hat{x}}\right\|" # Check a couple big, ugly combinations assert latex(symbols('xMathringBm_yCheckPRM__zbreveAbs')) == \ r"\boldsymbol{\mathring{x}}^{\left|{\breve{z}}\right|}_{{\check{y}}'}" assert latex(symbols('alphadothat_nVECDOT__tTildePrime')) == \ r"\hat{\dot{\alpha}}^{{\tilde{t}}'}_{\dot{\vec{n}}}" def test_greek_symbols(): assert latex(Symbol('alpha')) == r'\alpha' assert latex(Symbol('beta')) == r'\beta' assert latex(Symbol('gamma')) == r'\gamma' assert latex(Symbol('delta')) == r'\delta' assert latex(Symbol('epsilon')) == r'\epsilon' assert latex(Symbol('zeta')) == r'\zeta' assert latex(Symbol('eta')) == r'\eta' assert latex(Symbol('theta')) == r'\theta' assert latex(Symbol('iota')) == r'\iota' assert latex(Symbol('kappa')) == r'\kappa' assert latex(Symbol('lambda')) == r'\lambda' assert latex(Symbol('mu')) == r'\mu' assert latex(Symbol('nu')) == r'\nu' assert latex(Symbol('xi')) == r'\xi' assert latex(Symbol('omicron')) == r'o' assert latex(Symbol('pi')) == r'\pi' assert latex(Symbol('rho')) == r'\rho' assert latex(Symbol('sigma')) == r'\sigma' assert latex(Symbol('tau')) == r'\tau' assert latex(Symbol('upsilon')) == r'\upsilon' assert latex(Symbol('phi')) == r'\phi' assert latex(Symbol('chi')) == r'\chi' assert latex(Symbol('psi')) == r'\psi' assert latex(Symbol('omega')) == r'\omega' assert latex(Symbol('Alpha')) == r'A' assert latex(Symbol('Beta')) == r'B' assert latex(Symbol('Gamma')) == r'\Gamma' assert latex(Symbol('Delta')) == r'\Delta' assert latex(Symbol('Epsilon')) == r'E' assert latex(Symbol('Zeta')) == r'Z' assert latex(Symbol('Eta')) == r'H' assert latex(Symbol('Theta')) == r'\Theta' assert latex(Symbol('Iota')) == r'I' assert latex(Symbol('Kappa')) == r'K' assert latex(Symbol('Lambda')) == r'\Lambda' assert latex(Symbol('Mu')) == r'M' assert latex(Symbol('Nu')) == r'N' assert latex(Symbol('Xi')) == r'\Xi' assert latex(Symbol('Omicron')) == r'O' assert latex(Symbol('Pi')) == r'\Pi' assert latex(Symbol('Rho')) == r'P' assert latex(Symbol('Sigma')) == r'\Sigma' assert latex(Symbol('Tau')) == r'T' assert latex(Symbol('Upsilon')) == r'\Upsilon' assert latex(Symbol('Phi')) == r'\Phi' assert latex(Symbol('Chi')) == r'X' assert latex(Symbol('Psi')) == r'\Psi' assert latex(Symbol('Omega')) == r'\Omega' assert latex(Symbol('varepsilon')) == r'\varepsilon' assert latex(Symbol('varkappa')) == r'\varkappa' assert latex(Symbol('varphi')) == r'\varphi' assert latex(Symbol('varpi')) == r'\varpi' assert latex(Symbol('varrho')) == r'\varrho' assert latex(Symbol('varsigma')) == r'\varsigma' assert latex(Symbol('vartheta')) == r'\vartheta' def test_fancyset_symbols(): assert latex(S.Rationals) == r'\mathbb{Q}' assert latex(S.Naturals) == r'\mathbb{N}' assert latex(S.Naturals0) == r'\mathbb{N}_0' assert latex(S.Integers) == r'\mathbb{Z}' assert latex(S.Reals) == r'\mathbb{R}' assert latex(S.Complexes) == r'\mathbb{C}' @XFAIL def test_builtin_without_args_mismatched_names(): assert latex(CosineTransform) == r'\mathcal{COS}' def test_builtin_no_args(): assert latex(Chi) == r'\operatorname{Chi}' assert latex(beta) == r'\operatorname{B}' assert latex(gamma) == r'\Gamma' assert latex(KroneckerDelta) == r'\delta' assert latex(DiracDelta) == r'\delta' assert latex(lowergamma) == r'\gamma' def test_issue_6853(): p = Function('Pi') assert latex(p(x)) == r"\Pi{\left(x \right)}" def test_Mul(): e = Mul(-2, x + 1, evaluate=False) assert latex(e) == r'- 2 \left(x + 1\right)' e = Mul(2, x + 1, evaluate=False) assert latex(e) == r'2 \left(x + 1\right)' e = Mul(S.Half, x + 1, evaluate=False) assert latex(e) == r'\frac{x + 1}{2}' e = Mul(y, x + 1, evaluate=False) assert latex(e) == r'y \left(x + 1\right)' e = Mul(-y, x + 1, evaluate=False) assert latex(e) == r'- y \left(x + 1\right)' e = Mul(-2, x + 1) assert latex(e) == r'- 2 x - 2' e = Mul(2, x + 1) assert latex(e) == r'2 x + 2' def test_Pow(): e = Pow(2, 2, evaluate=False) assert latex(e) == r'2^{2}' assert latex(x**(Rational(-1, 3))) == r'\frac{1}{\sqrt[3]{x}}' x2 = Symbol(r'x^2') assert latex(x2**2) == r'\left(x^{2}\right)^{2}' def test_issue_7180(): assert latex(Equivalent(x, y)) == r"x \Leftrightarrow y" assert latex(Not(Equivalent(x, y))) == r"x \not\Leftrightarrow y" def test_issue_8409(): assert latex(S.Half**n) == r"\left(\frac{1}{2}\right)^{n}" def test_issue_8470(): from sympy.parsing.sympy_parser import parse_expr e = parse_expr("-B*A", evaluate=False) assert latex(e) == r"A \left(- B\right)" def test_issue_15439(): x = MatrixSymbol('x', 2, 2) y = MatrixSymbol('y', 2, 2) assert latex((x * y).subs(y, -y)) == r"x \left(- y\right)" assert latex((x * y).subs(y, -2*y)) == r"x \left(- 2 y\right)" assert latex((x * y).subs(x, -x)) == r"- x y" def test_issue_2934(): assert latex(Symbol(r'\frac{a_1}{b_1}')) == r'\frac{a_1}{b_1}' def test_issue_10489(): latexSymbolWithBrace = r'C_{x_{0}}' s = Symbol(latexSymbolWithBrace) assert latex(s) == latexSymbolWithBrace assert latex(cos(s)) == r'\cos{\left(C_{x_{0}} \right)}' def test_issue_12886(): m__1, l__1 = symbols('m__1, l__1') assert latex(m__1**2 + l__1**2) == \ r'\left(l^{1}\right)^{2} + \left(m^{1}\right)^{2}' def test_issue_13559(): from sympy.parsing.sympy_parser import parse_expr expr = parse_expr('5/1', evaluate=False) assert latex(expr) == r"\frac{5}{1}" def test_issue_13651(): expr = c + Mul(-1, a + b, evaluate=False) assert latex(expr) == r"c - \left(a + b\right)" def test_latex_UnevaluatedExpr(): x = symbols("x") he = UnevaluatedExpr(1/x) assert latex(he) == latex(1/x) == r"\frac{1}{x}" assert latex(he**2) == r"\left(\frac{1}{x}\right)^{2}" assert latex(he + 1) == r"1 + \frac{1}{x}" assert latex(x*he) == r"x \frac{1}{x}" def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) assert latex(A[0, 0]) == r"A_{0, 0}" assert latex(3 * A[0, 0]) == r"3 A_{0, 0}" F = C[0, 0].subs(C, A - B) assert latex(F) == r"\left(A - B\right)_{0, 0}" i, j, k = symbols("i j k") M = MatrixSymbol("M", k, k) N = MatrixSymbol("N", k, k) assert latex((M*N)[i, j]) == \ r'\sum_{i_{1}=0}^{k - 1} M_{i, i_{1}} N_{i_{1}, j}' def test_MatrixSymbol_printing(): # test cases for issue #14237 A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) C = MatrixSymbol("C", 3, 3) assert latex(-A) == r"- A" assert latex(A - A*B - B) == r"A - A B - B" assert latex(-A*B - A*B*C - B) == r"- A B - A B C - B" def test_KroneckerProduct_printing(): A = MatrixSymbol('A', 3, 3) B = MatrixSymbol('B', 2, 2) assert latex(KroneckerProduct(A, B)) == r'A \otimes B' def test_Series_printing(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y) assert latex(Series(tf1, tf2)) == \ r'\left(\frac{x y^{2} - z}{- t^{3} + y^{3}}\right) \left(\frac{x - y}{x + y}\right)' assert latex(Series(tf1, tf2, tf3)) == \ r'\left(\frac{x y^{2} - z}{- t^{3} + y^{3}}\right) \left(\frac{x - y}{x + y}\right) \left(\frac{t x^{2} - t^{w} x + w}{t - y}\right)' assert latex(Series(-tf2, tf1)) == \ r'\left(\frac{- x + y}{x + y}\right) \left(\frac{x y^{2} - z}{- t^{3} + y^{3}}\right)' M_1 = Matrix([[5/s], [5/(2*s)]]) T_1 = TransferFunctionMatrix.from_Matrix(M_1, s) M_2 = Matrix([[5, 6*s**3]]) T_2 = TransferFunctionMatrix.from_Matrix(M_2, s) # Brackets assert latex(T_1*(T_2 + T_2)) == \ r'\left[\begin{matrix}\frac{5}{s}\\\frac{5}{2 s}\end{matrix}\right]_\tau\cdot\left(\left[\begin{matrix}\frac{5}{1} &' \ r' \frac{6 s^{3}}{1}\end{matrix}\right]_\tau + \left[\begin{matrix}\frac{5}{1} & \frac{6 s^{3}}{1}\end{matrix}\right]_\tau\right)' \ == latex(MIMOSeries(MIMOParallel(T_2, T_2), T_1)) # No Brackets M_3 = Matrix([[5, 6], [6, 5/s]]) T_3 = TransferFunctionMatrix.from_Matrix(M_3, s) assert latex(T_1*T_2 + T_3) == r'\left[\begin{matrix}\frac{5}{s}\\\frac{5}{2 s}\end{matrix}\right]_\tau\cdot\left[\begin{matrix}' \ r'\frac{5}{1} & \frac{6 s^{3}}{1}\end{matrix}\right]_\tau + \left[\begin{matrix}\frac{5}{1} & \frac{6}{1}\\\frac{6}{1} & ' \ r'\frac{5}{s}\end{matrix}\right]_\tau' == latex(MIMOParallel(MIMOSeries(T_2, T_1), T_3)) def test_TransferFunction_printing(): tf1 = TransferFunction(x - 1, x + 1, x) assert latex(tf1) == r"\frac{x - 1}{x + 1}" tf2 = TransferFunction(x + 1, 2 - y, x) assert latex(tf2) == r"\frac{x + 1}{2 - y}" tf3 = TransferFunction(y, y**2 + 2*y + 3, y) assert latex(tf3) == r"\frac{y}{y^{2} + 2 y + 3}" def test_Parallel_printing(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) assert latex(Parallel(tf1, tf2)) == \ r'\frac{x y^{2} - z}{- t^{3} + y^{3}} + \frac{x - y}{x + y}' assert latex(Parallel(-tf2, tf1)) == \ r'\frac{- x + y}{x + y} + \frac{x y^{2} - z}{- t^{3} + y^{3}}' M_1 = Matrix([[5, 6], [6, 5/s]]) T_1 = TransferFunctionMatrix.from_Matrix(M_1, s) M_2 = Matrix([[5/s, 6], [6, 5/(s - 1)]]) T_2 = TransferFunctionMatrix.from_Matrix(M_2, s) M_3 = Matrix([[6, 5/(s*(s - 1))], [5, 6]]) T_3 = TransferFunctionMatrix.from_Matrix(M_3, s) assert latex(T_1 + T_2 + T_3) == r'\left[\begin{matrix}\frac{5}{1} & \frac{6}{1}\\\frac{6}{1} & \frac{5}{s}\end{matrix}\right]' \ r'_\tau + \left[\begin{matrix}\frac{5}{s} & \frac{6}{1}\\\frac{6}{1} & \frac{5}{s - 1}\end{matrix}\right]_\tau + \left[\begin{matrix}' \ r'\frac{6}{1} & \frac{5}{s \left(s - 1\right)}\\\frac{5}{1} & \frac{6}{1}\end{matrix}\right]_\tau' \ == latex(MIMOParallel(T_1, T_2, T_3)) == latex(MIMOParallel(T_1, MIMOParallel(T_2, T_3))) == latex(MIMOParallel(MIMOParallel(T_1, T_2), T_3)) def test_TransferFunctionMatrix_printing(): tf1 = TransferFunction(p, p + x, p) tf2 = TransferFunction(-s + p, p + s, p) tf3 = TransferFunction(p, y**2 + 2*y + 3, p) assert latex(TransferFunctionMatrix([[tf1], [tf2]])) == \ r'\left[\begin{matrix}\frac{p}{p + x}\\\frac{p - s}{p + s}\end{matrix}\right]_\tau' assert latex(TransferFunctionMatrix([[tf1, tf2], [tf3, -tf1]])) == \ r'\left[\begin{matrix}\frac{p}{p + x} & \frac{p - s}{p + s}\\\frac{p}{y^{2} + 2 y + 3} & \frac{\left(-1\right) p}{p + x}\end{matrix}\right]_\tau' def test_Feedback_printing(): tf1 = TransferFunction(p, p + x, p) tf2 = TransferFunction(-s + p, p + s, p) # Negative Feedback (Default) assert latex(Feedback(tf1, tf2)) == \ r'\frac{\frac{p}{p + x}}{\frac{1}{1} + \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}' assert latex(Feedback(tf1*tf2, TransferFunction(1, 1, p))) == \ r'\frac{\left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}{\frac{1}{1} + \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}' # Positive Feedback assert latex(Feedback(tf1, tf2, 1)) == \ r'\frac{\frac{p}{p + x}}{\frac{1}{1} - \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}' assert latex(Feedback(tf1*tf2, sign=1)) == \ r'\frac{\left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}{\frac{1}{1} - \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}' def test_MIMOFeedback_printing(): tf1 = TransferFunction(1, s, s) tf2 = TransferFunction(s, s**2 - 1, s) tf3 = TransferFunction(s, s - 1, s) tf4 = TransferFunction(s**2, s**2 - 1, s) tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]]) tfm_2 = TransferFunctionMatrix([[tf4, tf3], [tf2, tf1]]) # Negative Feedback (Default) assert latex(MIMOFeedback(tfm_1, tfm_2)) == \ r'\left(I_{\tau} + \left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\cdot\left[' \ r'\begin{matrix}\frac{s^{2}}{s^{2} - 1} & \frac{s}{s - 1}\\\frac{s}{s^{2} - 1} & \frac{1}{s}\end{matrix}\right]_\tau\right)^{-1} \cdot \left[\begin{matrix}' \ r'\frac{1}{s} & \frac{s}{s^{2} - 1}\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau' # Positive Feedback assert latex(MIMOFeedback(tfm_1*tfm_2, tfm_1, 1)) == \ r'\left(I_{\tau} - \left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\cdot\left' \ r'[\begin{matrix}\frac{s^{2}}{s^{2} - 1} & \frac{s}{s - 1}\\\frac{s}{s^{2} - 1} & \frac{1}{s}\end{matrix}\right]_\tau\cdot\left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}' \ r'\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\right)^{-1} \cdot \left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}' \ r'\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\cdot\left[\begin{matrix}\frac{s^{2}}{s^{2} - 1} & \frac{s}{s - 1}\\\frac{s}{s^{2} - 1}' \ r' & \frac{1}{s}\end{matrix}\right]_\tau' def test_Quaternion_latex_printing(): q = Quaternion(x, y, z, t) assert latex(q) == r"x + y i + z j + t k" q = Quaternion(x, y, z, x*t) assert latex(q) == r"x + y i + z j + t x k" q = Quaternion(x, y, z, x + t) assert latex(q) == r"x + y i + z j + \left(t + x\right) k" def test_TensorProduct_printing(): from sympy.tensor.functions import TensorProduct A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) assert latex(TensorProduct(A, B)) == r"A \otimes B" def test_WedgeProduct_printing(): from sympy.diffgeom.rn import R2 from sympy.diffgeom import WedgeProduct wp = WedgeProduct(R2.dx, R2.dy) assert latex(wp) == r"\operatorname{d}x \wedge \operatorname{d}y" def test_issue_9216(): expr_1 = Pow(1, -1, evaluate=False) assert latex(expr_1) == r"1^{-1}" expr_2 = Pow(1, Pow(1, -1, evaluate=False), evaluate=False) assert latex(expr_2) == r"1^{1^{-1}}" expr_3 = Pow(3, -2, evaluate=False) assert latex(expr_3) == r"\frac{1}{9}" expr_4 = Pow(1, -2, evaluate=False) assert latex(expr_4) == r"1^{-2}" def test_latex_printer_tensor(): from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, tensor_heads L = TensorIndexType("L") i, j, k, l = tensor_indices("i j k l", L) i0 = tensor_indices("i_0", L) A, B, C, D = tensor_heads("A B C D", [L]) H = TensorHead("H", [L, L]) K = TensorHead("K", [L, L, L, L]) assert latex(i) == r"{}^{i}" assert latex(-i) == r"{}_{i}" expr = A(i) assert latex(expr) == r"A{}^{i}" expr = A(i0) assert latex(expr) == r"A{}^{i_{0}}" expr = A(-i) assert latex(expr) == r"A{}_{i}" expr = -3*A(i) assert latex(expr) == r"-3A{}^{i}" expr = K(i, j, -k, -i0) assert latex(expr) == r"K{}^{ij}{}_{ki_{0}}" expr = K(i, -j, -k, i0) assert latex(expr) == r"K{}^{i}{}_{jk}{}^{i_{0}}" expr = K(i, -j, k, -i0) assert latex(expr) == r"K{}^{i}{}_{j}{}^{k}{}_{i_{0}}" expr = H(i, -j) assert latex(expr) == r"H{}^{i}{}_{j}" expr = H(i, j) assert latex(expr) == r"H{}^{ij}" expr = H(-i, -j) assert latex(expr) == r"H{}_{ij}" expr = (1+x)*A(i) assert latex(expr) == r"\left(x + 1\right)A{}^{i}" expr = H(i, -i) assert latex(expr) == r"H{}^{L_{0}}{}_{L_{0}}" expr = H(i, -j)*A(j)*B(k) assert latex(expr) == r"H{}^{i}{}_{L_{0}}A{}^{L_{0}}B{}^{k}" expr = A(i) + 3*B(i) assert latex(expr) == r"3B{}^{i} + A{}^{i}" # Test ``TensorElement``: from sympy.tensor.tensor import TensorElement expr = TensorElement(K(i, j, k, l), {i: 3, k: 2}) assert latex(expr) == r'K{}^{i=3,j,k=2,l}' expr = TensorElement(K(i, j, k, l), {i: 3}) assert latex(expr) == r'K{}^{i=3,jkl}' expr = TensorElement(K(i, -j, k, l), {i: 3, k: 2}) assert latex(expr) == r'K{}^{i=3}{}_{j}{}^{k=2,l}' expr = TensorElement(K(i, -j, k, -l), {i: 3, k: 2}) assert latex(expr) == r'K{}^{i=3}{}_{j}{}^{k=2}{}_{l}' expr = TensorElement(K(i, j, -k, -l), {i: 3, -k: 2}) assert latex(expr) == r'K{}^{i=3,j}{}_{k=2,l}' expr = TensorElement(K(i, j, -k, -l), {i: 3}) assert latex(expr) == r'K{}^{i=3,j}{}_{kl}' expr = PartialDerivative(A(i), A(i)) assert latex(expr) == r"\frac{\partial}{\partial {A{}^{L_{0}}}}{A{}^{L_{0}}}" expr = PartialDerivative(A(-i), A(-j)) assert latex(expr) == r"\frac{\partial}{\partial {A{}_{j}}}{A{}_{i}}" expr = PartialDerivative(K(i, j, -k, -l), A(m), A(-n)) assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}^{m}} \partial {A{}_{n}}}{K{}^{ij}{}_{kl}}" expr = PartialDerivative(B(-i) + A(-i), A(-j), A(-n)) assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}_{j}} \partial {A{}_{n}}}{\left(A{}_{i} + B{}_{i}\right)}" expr = PartialDerivative(3*A(-i), A(-j), A(-n)) assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}_{j}} \partial {A{}_{n}}}{\left(3A{}_{i}\right)}" def test_multiline_latex(): a, b, c, d, e, f = symbols('a b c d e f') expr = -a + 2*b -3*c +4*d -5*e expected = r"\begin{eqnarray}" + "\n"\ r"f & = &- a \nonumber\\" + "\n"\ r"& & + 2 b \nonumber\\" + "\n"\ r"& & - 3 c \nonumber\\" + "\n"\ r"& & + 4 d \nonumber\\" + "\n"\ r"& & - 5 e " + "\n"\ r"\end{eqnarray}" assert multiline_latex(f, expr, environment="eqnarray") == expected expected2 = r'\begin{eqnarray}' + '\n'\ r'f & = &- a + 2 b \nonumber\\' + '\n'\ r'& & - 3 c + 4 d \nonumber\\' + '\n'\ r'& & - 5 e ' + '\n'\ r'\end{eqnarray}' assert multiline_latex(f, expr, 2, environment="eqnarray") == expected2 expected3 = r'\begin{eqnarray}' + '\n'\ r'f & = &- a + 2 b - 3 c \nonumber\\'+ '\n'\ r'& & + 4 d - 5 e ' + '\n'\ r'\end{eqnarray}' assert multiline_latex(f, expr, 3, environment="eqnarray") == expected3 expected3dots = r'\begin{eqnarray}' + '\n'\ r'f & = &- a + 2 b - 3 c \dots\nonumber\\'+ '\n'\ r'& & + 4 d - 5 e ' + '\n'\ r'\end{eqnarray}' assert multiline_latex(f, expr, 3, environment="eqnarray", use_dots=True) == expected3dots expected3align = r'\begin{align*}' + '\n'\ r'f = &- a + 2 b - 3 c \\'+ '\n'\ r'& + 4 d - 5 e ' + '\n'\ r'\end{align*}' assert multiline_latex(f, expr, 3) == expected3align assert multiline_latex(f, expr, 3, environment='align*') == expected3align expected2ieee = r'\begin{IEEEeqnarray}{rCl}' + '\n'\ r'f & = &- a + 2 b \nonumber\\' + '\n'\ r'& & - 3 c + 4 d \nonumber\\' + '\n'\ r'& & - 5 e ' + '\n'\ r'\end{IEEEeqnarray}' assert multiline_latex(f, expr, 2, environment="IEEEeqnarray") == expected2ieee raises(ValueError, lambda: multiline_latex(f, expr, environment="foo")) def test_issue_15353(): a, x = symbols('a x') # Obtained from nonlinsolve([(sin(a*x)),cos(a*x)],[x,a]) sol = ConditionSet( Tuple(x, a), Eq(sin(a*x), 0) & Eq(cos(a*x), 0), S.Complexes**2) assert latex(sol) == \ r'\left\{\left( x, \ a\right)\; \middle|\; \left( x, \ a\right) \in ' \ r'\mathbb{C}^{2} \wedge \sin{\left(a x \right)} = 0 \wedge ' \ r'\cos{\left(a x \right)} = 0 \right\}' def test_latex_symbolic_probability(): mu = symbols("mu") sigma = symbols("sigma", positive=True) X = Normal("X", mu, sigma) assert latex(Expectation(X)) == r'\operatorname{E}\left[X\right]' assert latex(Variance(X)) == r'\operatorname{Var}\left(X\right)' assert latex(Probability(X > 0)) == r'\operatorname{P}\left(X > 0\right)' Y = Normal("Y", mu, sigma) assert latex(Covariance(X, Y)) == r'\operatorname{Cov}\left(X, Y\right)' def test_trace(): # Issue 15303 from sympy.matrices.expressions.trace import trace A = MatrixSymbol("A", 2, 2) assert latex(trace(A)) == r"\operatorname{tr}\left(A \right)" assert latex(trace(A**2)) == r"\operatorname{tr}\left(A^{2} \right)" def test_print_basic(): # Issue 15303 from sympy.core.basic import Basic from sympy.core.expr import Expr # dummy class for testing printing where the function is not # implemented in latex.py class UnimplementedExpr(Expr): def __new__(cls, e): return Basic.__new__(cls, e) # dummy function for testing def unimplemented_expr(expr): return UnimplementedExpr(expr).doit() # override class name to use superscript / subscript def unimplemented_expr_sup_sub(expr): result = UnimplementedExpr(expr) result.__class__.__name__ = 'UnimplementedExpr_x^1' return result assert latex(unimplemented_expr(x)) == r'UnimplementedExpr\left(x\right)' assert latex(unimplemented_expr(x**2)) == \ r'UnimplementedExpr\left(x^{2}\right)' assert latex(unimplemented_expr_sup_sub(x)) == \ r'UnimplementedExpr^{1}_{x}\left(x\right)' def test_MatrixSymbol_bold(): # Issue #15871 from sympy.matrices.expressions.trace import trace A = MatrixSymbol("A", 2, 2) assert latex(trace(A), mat_symbol_style='bold') == \ r"\operatorname{tr}\left(\mathbf{A} \right)" assert latex(trace(A), mat_symbol_style='plain') == \ r"\operatorname{tr}\left(A \right)" A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) C = MatrixSymbol("C", 3, 3) assert latex(-A, mat_symbol_style='bold') == r"- \mathbf{A}" assert latex(A - A*B - B, mat_symbol_style='bold') == \ r"\mathbf{A} - \mathbf{A} \mathbf{B} - \mathbf{B}" assert latex(-A*B - A*B*C - B, mat_symbol_style='bold') == \ r"- \mathbf{A} \mathbf{B} - \mathbf{A} \mathbf{B} \mathbf{C} - \mathbf{B}" A_k = MatrixSymbol("A_k", 3, 3) assert latex(A_k, mat_symbol_style='bold') == r"\mathbf{A}_{k}" A = MatrixSymbol(r"\nabla_k", 3, 3) assert latex(A, mat_symbol_style='bold') == r"\mathbf{\nabla}_{k}" def test_AppliedPermutation(): p = Permutation(0, 1, 2) x = Symbol('x') assert latex(AppliedPermutation(p, x)) == \ r'\sigma_{\left( 0\; 1\; 2\right)}(x)' def test_PermutationMatrix(): p = Permutation(0, 1, 2) assert latex(PermutationMatrix(p)) == r'P_{\left( 0\; 1\; 2\right)}' p = Permutation(0, 3)(1, 2) assert latex(PermutationMatrix(p)) == \ r'P_{\left( 0\; 3\right)\left( 1\; 2\right)}' def test_imaginary_unit(): assert latex(1 + I) == r'1 + i' assert latex(1 + I, imaginary_unit='i') == r'1 + i' assert latex(1 + I, imaginary_unit='j') == r'1 + j' assert latex(1 + I, imaginary_unit='foo') == r'1 + foo' assert latex(I, imaginary_unit="ti") == r'\text{i}' assert latex(I, imaginary_unit="tj") == r'\text{j}' def test_text_re_im(): assert latex(im(x), gothic_re_im=True) == r'\Im{\left(x\right)}' assert latex(im(x), gothic_re_im=False) == r'\operatorname{im}{\left(x\right)}' assert latex(re(x), gothic_re_im=True) == r'\Re{\left(x\right)}' assert latex(re(x), gothic_re_im=False) == r'\operatorname{re}{\left(x\right)}' def test_latex_diffgeom(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential from sympy.diffgeom.rn import R2 x,y = symbols('x y', real=True) m = Manifold('M', 2) assert latex(m) == r'\text{M}' p = Patch('P', m) assert latex(p) == r'\text{P}_{\text{M}}' rect = CoordSystem('rect', p, [x, y]) assert latex(rect) == r'\text{rect}^{\text{P}}_{\text{M}}' b = BaseScalarField(rect, 0) assert latex(b) == r'\mathbf{x}' g = Function('g') s_field = g(R2.x, R2.y) assert latex(Differential(s_field)) == \ r'\operatorname{d}\left(g{\left(\mathbf{x},\mathbf{y} \right)}\right)' def test_unit_printing(): assert latex(5*meter) == r'5 \text{m}' assert latex(3*gibibyte) == r'3 \text{gibibyte}' assert latex(4*microgram/second) == r'\frac{4 \mu\text{g}}{\text{s}}' def test_issue_17092(): x_star = Symbol('x^*') assert latex(Derivative(x_star, x_star,2)) == r'\frac{d^{2}}{d \left(x^{*}\right)^{2}} x^{*}' def test_latex_decimal_separator(): x, y, z, t = symbols('x y z t') k, m, n = symbols('k m n', integer=True) f, g, h = symbols('f g h', cls=Function) # comma decimal_separator assert(latex([1, 2.3, 4.5], decimal_separator='comma') == r'\left[ 1; \ 2{,}3; \ 4{,}5\right]') assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='comma') == r'\left\{1; 2{,}3; 4{,}5\right\}') assert(latex((1, 2.3, 4.6), decimal_separator = 'comma') == r'\left( 1; \ 2{,}3; \ 4{,}6\right)') assert(latex((1,), decimal_separator='comma') == r'\left( 1;\right)') # period decimal_separator assert(latex([1, 2.3, 4.5], decimal_separator='period') == r'\left[ 1, \ 2.3, \ 4.5\right]' ) assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='period') == r'\left\{1, 2.3, 4.5\right\}') assert(latex((1, 2.3, 4.6), decimal_separator = 'period') == r'\left( 1, \ 2.3, \ 4.6\right)') assert(latex((1,), decimal_separator='period') == r'\left( 1,\right)') # default decimal_separator assert(latex([1, 2.3, 4.5]) == r'\left[ 1, \ 2.3, \ 4.5\right]') assert(latex(FiniteSet(1, 2.3, 4.5)) == r'\left\{1, 2.3, 4.5\right\}') assert(latex((1, 2.3, 4.6)) == r'\left( 1, \ 2.3, \ 4.6\right)') assert(latex((1,)) == r'\left( 1,\right)') assert(latex(Mul(3.4,5.3), decimal_separator = 'comma') == r'18{,}02') assert(latex(3.4*5.3, decimal_separator = 'comma') == r'18{,}02') x = symbols('x') y = symbols('y') z = symbols('z') assert(latex(x*5.3 + 2**y**3.4 + 4.5 + z, decimal_separator = 'comma') == r'2^{y^{3{,}4}} + 5{,}3 x + z + 4{,}5') assert(latex(0.987, decimal_separator='comma') == r'0{,}987') assert(latex(S(0.987), decimal_separator='comma') == r'0{,}987') assert(latex(.3, decimal_separator='comma') == r'0{,}3') assert(latex(S(.3), decimal_separator='comma') == r'0{,}3') assert(latex(5.8*10**(-7), decimal_separator='comma') == r'5{,}8 \cdot 10^{-7}') assert(latex(S(5.7)*10**(-7), decimal_separator='comma') == r'5{,}7 \cdot 10^{-7}') assert(latex(S(5.7*10**(-7)), decimal_separator='comma') == r'5{,}7 \cdot 10^{-7}') x = symbols('x') assert(latex(1.2*x+3.4, decimal_separator='comma') == r'1{,}2 x + 3{,}4') assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='period') == r'\left\{1, 2.3, 4.5\right\}') # Error Handling tests raises(ValueError, lambda: latex([1,2.3,4.5], decimal_separator='non_existing_decimal_separator_in_list')) raises(ValueError, lambda: latex(FiniteSet(1,2.3,4.5), decimal_separator='non_existing_decimal_separator_in_set')) raises(ValueError, lambda: latex((1,2.3,4.5), decimal_separator='non_existing_decimal_separator_in_tuple')) def test_Str(): from sympy.core.symbol import Str assert str(Str('x')) == r'x' def test_latex_escape(): assert latex_escape(r"~^\&%$#_{}") == "".join([ r'\textasciitilde', r'\textasciicircum', r'\textbackslash', r'\&', r'\%', r'\$', r'\#', r'\_', r'\{', r'\}', ]) def test_emptyPrinter(): class MyObject: def __repr__(self): return "<MyObject with {...}>" # unknown objects are monospaced assert latex(MyObject()) == r"\mathtt{\text{<MyObject with \{...\}>}}" # even if they are nested within other objects assert latex((MyObject(),)) == r"\left( \mathtt{\text{<MyObject with \{...\}>}},\right)" def test_global_settings(): import inspect # settings should be visible in the signature of `latex` assert inspect.signature(latex).parameters['imaginary_unit'].default == r'i' assert latex(I) == r'i' try: # but changing the defaults... LatexPrinter.set_global_settings(imaginary_unit='j') # ... should change the signature assert inspect.signature(latex).parameters['imaginary_unit'].default == r'j' assert latex(I) == r'j' finally: # there's no public API to undo this, but we need to make sure we do # so as not to impact other tests del LatexPrinter._global_settings['imaginary_unit'] # check we really did undo it assert inspect.signature(latex).parameters['imaginary_unit'].default == r'i' assert latex(I) == r'i' def test_pickleable(): # this tests that the _PrintFunction instance is pickleable import pickle assert pickle.loads(pickle.dumps(latex)) is latex def test_printing_latex_array_expressions(): assert latex(ArraySymbol("A", (2, 3, 4))) == "A" assert latex(ArrayElement("A", (2, 1/(1-x), 0))) == "{{A}_{2, \\frac{1}{1 - x}, 0}}" M = MatrixSymbol("M", 3, 3) N = MatrixSymbol("N", 3, 3) assert latex(ArrayElement(M*N, [x, 0])) == "{{\\left(M N\\right)}_{x, 0}}"
c7821c92b3313a54b3b7a0b1185a4774dda5e8e5e5ef3adcc481f09fe2b1792f
from sympy.calculus.accumulationbounds import AccumBounds from sympy.concrete.summations import Sum from sympy.core.basic import Basic from sympy.core.containers import Tuple from sympy.core.function import Derivative, Lambda, diff, Function from sympy.core.numbers import (zoo, Float, Integer, I, oo, pi, E, Rational) from sympy.core.relational import Lt, Ge, Ne, Eq from sympy.core.singleton import S from sympy.core.symbol import symbols, Symbol from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import (factorial2, binomial, factorial) from sympy.functions.combinatorial.numbers import (lucas, bell, catalan, euler, tribonacci, fibonacci, bernoulli) from sympy.functions.elementary.complexes import re, im, conjugate, Abs from sympy.functions.elementary.exponential import exp, LambertW, log from sympy.functions.elementary.hyperbolic import (tanh, acoth, atanh, coth, asinh, acsch, asech, acosh, csch, sinh, cosh, sech) from sympy.functions.elementary.integers import ceiling, floor from sympy.functions.elementary.miscellaneous import Max, Min from sympy.functions.elementary.trigonometric import (csc, sec, tan, atan, sin, asec, cot, cos, acot, acsc, asin, acos) from sympy.functions.special.delta_functions import Heaviside from sympy.functions.special.elliptic_integrals import (elliptic_pi, elliptic_f, elliptic_k, elliptic_e) from sympy.functions.special.error_functions import (fresnelc, fresnels, Ei, expint) from sympy.functions.special.gamma_functions import (gamma, uppergamma, lowergamma) from sympy.functions.special.mathieu_functions import (mathieusprime, mathieus, mathieucprime, mathieuc) from sympy.functions.special.polynomials import (jacobi, chebyshevu, chebyshevt, hermite, assoc_legendre, gegenbauer, assoc_laguerre, legendre, laguerre) from sympy.functions.special.singularity_functions import SingularityFunction from sympy.functions.special.zeta_functions import (polylog, stieltjes, lerchphi, dirichlet_eta, zeta) from sympy.integrals.integrals import Integral from sympy.logic.boolalg import (Xor, Or, false, true, And, Equivalent, Implies, Not) from sympy.matrices.dense import Matrix from sympy.matrices.expressions.determinant import Determinant from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.ntheory.factor_ import (totient, reduced_totient, primenu, primeomega) from sympy.physics.quantum import (ComplexSpace, FockSpace, hbar, HilbertSpace, Dagger) from sympy.printing.mathml import (MathMLPresentationPrinter, MathMLPrinter, MathMLContentPrinter, mathml) from sympy.series.limits import Limit from sympy.sets.contains import Contains from sympy.sets.fancysets import Range from sympy.sets.sets import (Interval, Union, SymmetricDifference, Complement, FiniteSet, Intersection, ProductSet) from sympy.stats.rv import RandomSymbol from sympy.tensor.indexed import IndexedBase from sympy.vector import (Divergence, CoordSys3D, Cross, Curl, Dot, Laplacian, Gradient) from sympy.testing.pytest import raises x, y, z, a, b, c, d, e, n = symbols('x:z a:e n') mp = MathMLContentPrinter() mpp = MathMLPresentationPrinter() def test_mathml_printer(): m = MathMLPrinter() assert m.doprint(1+x) == mp.doprint(1+x) def test_content_printmethod(): assert mp.doprint(1 + x) == '<apply><plus/><ci>x</ci><cn>1</cn></apply>' def test_content_mathml_core(): mml_1 = mp._print(1 + x) assert mml_1.nodeName == 'apply' nodes = mml_1.childNodes assert len(nodes) == 3 assert nodes[0].nodeName == 'plus' assert nodes[0].hasChildNodes() is False assert nodes[0].nodeValue is None assert nodes[1].nodeName in ['cn', 'ci'] if nodes[1].nodeName == 'cn': assert nodes[1].childNodes[0].nodeValue == '1' assert nodes[2].childNodes[0].nodeValue == 'x' else: assert nodes[1].childNodes[0].nodeValue == 'x' assert nodes[2].childNodes[0].nodeValue == '1' mml_2 = mp._print(x**2) assert mml_2.nodeName == 'apply' nodes = mml_2.childNodes assert nodes[1].childNodes[0].nodeValue == 'x' assert nodes[2].childNodes[0].nodeValue == '2' mml_3 = mp._print(2*x) assert mml_3.nodeName == 'apply' nodes = mml_3.childNodes assert nodes[0].nodeName == 'times' assert nodes[1].childNodes[0].nodeValue == '2' assert nodes[2].childNodes[0].nodeValue == 'x' mml = mp._print(Float(1.0, 2)*x) assert mml.nodeName == 'apply' nodes = mml.childNodes assert nodes[0].nodeName == 'times' assert nodes[1].childNodes[0].nodeValue == '1.0' assert nodes[2].childNodes[0].nodeValue == 'x' def test_content_mathml_functions(): mml_1 = mp._print(sin(x)) assert mml_1.nodeName == 'apply' assert mml_1.childNodes[0].nodeName == 'sin' assert mml_1.childNodes[1].nodeName == 'ci' mml_2 = mp._print(diff(sin(x), x, evaluate=False)) assert mml_2.nodeName == 'apply' assert mml_2.childNodes[0].nodeName == 'diff' assert mml_2.childNodes[1].nodeName == 'bvar' assert mml_2.childNodes[1].childNodes[ 0].nodeName == 'ci' # below bvar there's <ci>x/ci> mml_3 = mp._print(diff(cos(x*y), x, evaluate=False)) assert mml_3.nodeName == 'apply' assert mml_3.childNodes[0].nodeName == 'partialdiff' assert mml_3.childNodes[1].nodeName == 'bvar' assert mml_3.childNodes[1].childNodes[ 0].nodeName == 'ci' # below bvar there's <ci>x/ci> def test_content_mathml_limits(): # XXX No unevaluated limits lim_fun = sin(x)/x mml_1 = mp._print(Limit(lim_fun, x, 0)) assert mml_1.childNodes[0].nodeName == 'limit' assert mml_1.childNodes[1].nodeName == 'bvar' assert mml_1.childNodes[2].nodeName == 'lowlimit' assert mml_1.childNodes[3].toxml() == mp._print(lim_fun).toxml() def test_content_mathml_integrals(): integrand = x mml_1 = mp._print(Integral(integrand, (x, 0, 1))) assert mml_1.childNodes[0].nodeName == 'int' assert mml_1.childNodes[1].nodeName == 'bvar' assert mml_1.childNodes[2].nodeName == 'lowlimit' assert mml_1.childNodes[3].nodeName == 'uplimit' assert mml_1.childNodes[4].toxml() == mp._print(integrand).toxml() def test_content_mathml_matrices(): A = Matrix([1, 2, 3]) B = Matrix([[0, 5, 4], [2, 3, 1], [9, 7, 9]]) mll_1 = mp._print(A) assert mll_1.childNodes[0].nodeName == 'matrixrow' assert mll_1.childNodes[0].childNodes[0].nodeName == 'cn' assert mll_1.childNodes[0].childNodes[0].childNodes[0].nodeValue == '1' assert mll_1.childNodes[1].nodeName == 'matrixrow' assert mll_1.childNodes[1].childNodes[0].nodeName == 'cn' assert mll_1.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2' assert mll_1.childNodes[2].nodeName == 'matrixrow' assert mll_1.childNodes[2].childNodes[0].nodeName == 'cn' assert mll_1.childNodes[2].childNodes[0].childNodes[0].nodeValue == '3' mll_2 = mp._print(B) assert mll_2.childNodes[0].nodeName == 'matrixrow' assert mll_2.childNodes[0].childNodes[0].nodeName == 'cn' assert mll_2.childNodes[0].childNodes[0].childNodes[0].nodeValue == '0' assert mll_2.childNodes[0].childNodes[1].nodeName == 'cn' assert mll_2.childNodes[0].childNodes[1].childNodes[0].nodeValue == '5' assert mll_2.childNodes[0].childNodes[2].nodeName == 'cn' assert mll_2.childNodes[0].childNodes[2].childNodes[0].nodeValue == '4' assert mll_2.childNodes[1].nodeName == 'matrixrow' assert mll_2.childNodes[1].childNodes[0].nodeName == 'cn' assert mll_2.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2' assert mll_2.childNodes[1].childNodes[1].nodeName == 'cn' assert mll_2.childNodes[1].childNodes[1].childNodes[0].nodeValue == '3' assert mll_2.childNodes[1].childNodes[2].nodeName == 'cn' assert mll_2.childNodes[1].childNodes[2].childNodes[0].nodeValue == '1' assert mll_2.childNodes[2].nodeName == 'matrixrow' assert mll_2.childNodes[2].childNodes[0].nodeName == 'cn' assert mll_2.childNodes[2].childNodes[0].childNodes[0].nodeValue == '9' assert mll_2.childNodes[2].childNodes[1].nodeName == 'cn' assert mll_2.childNodes[2].childNodes[1].childNodes[0].nodeValue == '7' assert mll_2.childNodes[2].childNodes[2].nodeName == 'cn' assert mll_2.childNodes[2].childNodes[2].childNodes[0].nodeValue == '9' def test_content_mathml_sums(): summand = x mml_1 = mp._print(Sum(summand, (x, 1, 10))) assert mml_1.childNodes[0].nodeName == 'sum' assert mml_1.childNodes[1].nodeName == 'bvar' assert mml_1.childNodes[2].nodeName == 'lowlimit' assert mml_1.childNodes[3].nodeName == 'uplimit' assert mml_1.childNodes[4].toxml() == mp._print(summand).toxml() def test_content_mathml_tuples(): mml_1 = mp._print([2]) assert mml_1.nodeName == 'list' assert mml_1.childNodes[0].nodeName == 'cn' assert len(mml_1.childNodes) == 1 mml_2 = mp._print([2, Integer(1)]) assert mml_2.nodeName == 'list' assert mml_2.childNodes[0].nodeName == 'cn' assert mml_2.childNodes[1].nodeName == 'cn' assert len(mml_2.childNodes) == 2 def test_content_mathml_add(): mml = mp._print(x**5 - x**4 + x) assert mml.childNodes[0].nodeName == 'plus' assert mml.childNodes[1].childNodes[0].nodeName == 'minus' assert mml.childNodes[1].childNodes[1].nodeName == 'apply' def test_content_mathml_Rational(): mml_1 = mp._print(Rational(1, 1)) """should just return a number""" assert mml_1.nodeName == 'cn' mml_2 = mp._print(Rational(2, 5)) assert mml_2.childNodes[0].nodeName == 'divide' def test_content_mathml_constants(): mml = mp._print(I) assert mml.nodeName == 'imaginaryi' mml = mp._print(E) assert mml.nodeName == 'exponentiale' mml = mp._print(oo) assert mml.nodeName == 'infinity' mml = mp._print(pi) assert mml.nodeName == 'pi' assert mathml(hbar) == '<hbar/>' assert mathml(S.TribonacciConstant) == '<tribonacciconstant/>' assert mathml(S.GoldenRatio) == '<cn>&#966;</cn>' mml = mathml(S.EulerGamma) assert mml == '<eulergamma/>' mml = mathml(S.EmptySet) assert mml == '<emptyset/>' mml = mathml(S.true) assert mml == '<true/>' mml = mathml(S.false) assert mml == '<false/>' mml = mathml(S.NaN) assert mml == '<notanumber/>' def test_content_mathml_trig(): mml = mp._print(sin(x)) assert mml.childNodes[0].nodeName == 'sin' mml = mp._print(cos(x)) assert mml.childNodes[0].nodeName == 'cos' mml = mp._print(tan(x)) assert mml.childNodes[0].nodeName == 'tan' mml = mp._print(cot(x)) assert mml.childNodes[0].nodeName == 'cot' mml = mp._print(csc(x)) assert mml.childNodes[0].nodeName == 'csc' mml = mp._print(sec(x)) assert mml.childNodes[0].nodeName == 'sec' mml = mp._print(asin(x)) assert mml.childNodes[0].nodeName == 'arcsin' mml = mp._print(acos(x)) assert mml.childNodes[0].nodeName == 'arccos' mml = mp._print(atan(x)) assert mml.childNodes[0].nodeName == 'arctan' mml = mp._print(acot(x)) assert mml.childNodes[0].nodeName == 'arccot' mml = mp._print(acsc(x)) assert mml.childNodes[0].nodeName == 'arccsc' mml = mp._print(asec(x)) assert mml.childNodes[0].nodeName == 'arcsec' mml = mp._print(sinh(x)) assert mml.childNodes[0].nodeName == 'sinh' mml = mp._print(cosh(x)) assert mml.childNodes[0].nodeName == 'cosh' mml = mp._print(tanh(x)) assert mml.childNodes[0].nodeName == 'tanh' mml = mp._print(coth(x)) assert mml.childNodes[0].nodeName == 'coth' mml = mp._print(csch(x)) assert mml.childNodes[0].nodeName == 'csch' mml = mp._print(sech(x)) assert mml.childNodes[0].nodeName == 'sech' mml = mp._print(asinh(x)) assert mml.childNodes[0].nodeName == 'arcsinh' mml = mp._print(atanh(x)) assert mml.childNodes[0].nodeName == 'arctanh' mml = mp._print(acosh(x)) assert mml.childNodes[0].nodeName == 'arccosh' mml = mp._print(acoth(x)) assert mml.childNodes[0].nodeName == 'arccoth' mml = mp._print(acsch(x)) assert mml.childNodes[0].nodeName == 'arccsch' mml = mp._print(asech(x)) assert mml.childNodes[0].nodeName == 'arcsech' def test_content_mathml_relational(): mml_1 = mp._print(Eq(x, 1)) assert mml_1.nodeName == 'apply' assert mml_1.childNodes[0].nodeName == 'eq' assert mml_1.childNodes[1].nodeName == 'ci' assert mml_1.childNodes[1].childNodes[0].nodeValue == 'x' assert mml_1.childNodes[2].nodeName == 'cn' assert mml_1.childNodes[2].childNodes[0].nodeValue == '1' mml_2 = mp._print(Ne(1, x)) assert mml_2.nodeName == 'apply' assert mml_2.childNodes[0].nodeName == 'neq' assert mml_2.childNodes[1].nodeName == 'cn' assert mml_2.childNodes[1].childNodes[0].nodeValue == '1' assert mml_2.childNodes[2].nodeName == 'ci' assert mml_2.childNodes[2].childNodes[0].nodeValue == 'x' mml_3 = mp._print(Ge(1, x)) assert mml_3.nodeName == 'apply' assert mml_3.childNodes[0].nodeName == 'geq' assert mml_3.childNodes[1].nodeName == 'cn' assert mml_3.childNodes[1].childNodes[0].nodeValue == '1' assert mml_3.childNodes[2].nodeName == 'ci' assert mml_3.childNodes[2].childNodes[0].nodeValue == 'x' mml_4 = mp._print(Lt(1, x)) assert mml_4.nodeName == 'apply' assert mml_4.childNodes[0].nodeName == 'lt' assert mml_4.childNodes[1].nodeName == 'cn' assert mml_4.childNodes[1].childNodes[0].nodeValue == '1' assert mml_4.childNodes[2].nodeName == 'ci' assert mml_4.childNodes[2].childNodes[0].nodeValue == 'x' def test_content_symbol(): mml = mp._print(x) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeValue == 'x' del mml mml = mp._print(Symbol("x^2")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msup' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2' del mml mml = mp._print(Symbol("x__2")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msup' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2' del mml mml = mp._print(Symbol("x_2")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msub' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2' del mml mml = mp._print(Symbol("x^3_2")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msubsup' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2' assert mml.childNodes[0].childNodes[2].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[2].childNodes[0].nodeValue == '3' del mml mml = mp._print(Symbol("x__3_2")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msubsup' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2' assert mml.childNodes[0].childNodes[2].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[2].childNodes[0].nodeValue == '3' del mml mml = mp._print(Symbol("x_2_a")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msub' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mrow' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].childNodes[ 0].nodeValue == '2' assert mml.childNodes[0].childNodes[1].childNodes[1].nodeName == 'mml:mo' assert mml.childNodes[0].childNodes[1].childNodes[1].childNodes[ 0].nodeValue == ' ' assert mml.childNodes[0].childNodes[1].childNodes[2].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[2].childNodes[ 0].nodeValue == 'a' del mml mml = mp._print(Symbol("x^2^a")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msup' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mrow' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].childNodes[ 0].nodeValue == '2' assert mml.childNodes[0].childNodes[1].childNodes[1].nodeName == 'mml:mo' assert mml.childNodes[0].childNodes[1].childNodes[1].childNodes[ 0].nodeValue == ' ' assert mml.childNodes[0].childNodes[1].childNodes[2].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[2].childNodes[ 0].nodeValue == 'a' del mml mml = mp._print(Symbol("x__2__a")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msup' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mrow' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].childNodes[ 0].nodeValue == '2' assert mml.childNodes[0].childNodes[1].childNodes[1].nodeName == 'mml:mo' assert mml.childNodes[0].childNodes[1].childNodes[1].childNodes[ 0].nodeValue == ' ' assert mml.childNodes[0].childNodes[1].childNodes[2].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[2].childNodes[ 0].nodeValue == 'a' del mml def test_content_mathml_greek(): mml = mp._print(Symbol('alpha')) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeValue == '\N{GREEK SMALL LETTER ALPHA}' assert mp.doprint(Symbol('alpha')) == '<ci>&#945;</ci>' assert mp.doprint(Symbol('beta')) == '<ci>&#946;</ci>' assert mp.doprint(Symbol('gamma')) == '<ci>&#947;</ci>' assert mp.doprint(Symbol('delta')) == '<ci>&#948;</ci>' assert mp.doprint(Symbol('epsilon')) == '<ci>&#949;</ci>' assert mp.doprint(Symbol('zeta')) == '<ci>&#950;</ci>' assert mp.doprint(Symbol('eta')) == '<ci>&#951;</ci>' assert mp.doprint(Symbol('theta')) == '<ci>&#952;</ci>' assert mp.doprint(Symbol('iota')) == '<ci>&#953;</ci>' assert mp.doprint(Symbol('kappa')) == '<ci>&#954;</ci>' assert mp.doprint(Symbol('lambda')) == '<ci>&#955;</ci>' assert mp.doprint(Symbol('mu')) == '<ci>&#956;</ci>' assert mp.doprint(Symbol('nu')) == '<ci>&#957;</ci>' assert mp.doprint(Symbol('xi')) == '<ci>&#958;</ci>' assert mp.doprint(Symbol('omicron')) == '<ci>&#959;</ci>' assert mp.doprint(Symbol('pi')) == '<ci>&#960;</ci>' assert mp.doprint(Symbol('rho')) == '<ci>&#961;</ci>' assert mp.doprint(Symbol('varsigma')) == '<ci>&#962;</ci>' assert mp.doprint(Symbol('sigma')) == '<ci>&#963;</ci>' assert mp.doprint(Symbol('tau')) == '<ci>&#964;</ci>' assert mp.doprint(Symbol('upsilon')) == '<ci>&#965;</ci>' assert mp.doprint(Symbol('phi')) == '<ci>&#966;</ci>' assert mp.doprint(Symbol('chi')) == '<ci>&#967;</ci>' assert mp.doprint(Symbol('psi')) == '<ci>&#968;</ci>' assert mp.doprint(Symbol('omega')) == '<ci>&#969;</ci>' assert mp.doprint(Symbol('Alpha')) == '<ci>&#913;</ci>' assert mp.doprint(Symbol('Beta')) == '<ci>&#914;</ci>' assert mp.doprint(Symbol('Gamma')) == '<ci>&#915;</ci>' assert mp.doprint(Symbol('Delta')) == '<ci>&#916;</ci>' assert mp.doprint(Symbol('Epsilon')) == '<ci>&#917;</ci>' assert mp.doprint(Symbol('Zeta')) == '<ci>&#918;</ci>' assert mp.doprint(Symbol('Eta')) == '<ci>&#919;</ci>' assert mp.doprint(Symbol('Theta')) == '<ci>&#920;</ci>' assert mp.doprint(Symbol('Iota')) == '<ci>&#921;</ci>' assert mp.doprint(Symbol('Kappa')) == '<ci>&#922;</ci>' assert mp.doprint(Symbol('Lambda')) == '<ci>&#923;</ci>' assert mp.doprint(Symbol('Mu')) == '<ci>&#924;</ci>' assert mp.doprint(Symbol('Nu')) == '<ci>&#925;</ci>' assert mp.doprint(Symbol('Xi')) == '<ci>&#926;</ci>' assert mp.doprint(Symbol('Omicron')) == '<ci>&#927;</ci>' assert mp.doprint(Symbol('Pi')) == '<ci>&#928;</ci>' assert mp.doprint(Symbol('Rho')) == '<ci>&#929;</ci>' assert mp.doprint(Symbol('Sigma')) == '<ci>&#931;</ci>' assert mp.doprint(Symbol('Tau')) == '<ci>&#932;</ci>' assert mp.doprint(Symbol('Upsilon')) == '<ci>&#933;</ci>' assert mp.doprint(Symbol('Phi')) == '<ci>&#934;</ci>' assert mp.doprint(Symbol('Chi')) == '<ci>&#935;</ci>' assert mp.doprint(Symbol('Psi')) == '<ci>&#936;</ci>' assert mp.doprint(Symbol('Omega')) == '<ci>&#937;</ci>' def test_content_mathml_order(): expr = x**3 + x**2*y + 3*x*y**3 + y**4 mp = MathMLContentPrinter({'order': 'lex'}) mml = mp._print(expr) assert mml.childNodes[1].childNodes[0].nodeName == 'power' assert mml.childNodes[1].childNodes[1].childNodes[0].data == 'x' assert mml.childNodes[1].childNodes[2].childNodes[0].data == '3' assert mml.childNodes[4].childNodes[0].nodeName == 'power' assert mml.childNodes[4].childNodes[1].childNodes[0].data == 'y' assert mml.childNodes[4].childNodes[2].childNodes[0].data == '4' mp = MathMLContentPrinter({'order': 'rev-lex'}) mml = mp._print(expr) assert mml.childNodes[1].childNodes[0].nodeName == 'power' assert mml.childNodes[1].childNodes[1].childNodes[0].data == 'y' assert mml.childNodes[1].childNodes[2].childNodes[0].data == '4' assert mml.childNodes[4].childNodes[0].nodeName == 'power' assert mml.childNodes[4].childNodes[1].childNodes[0].data == 'x' assert mml.childNodes[4].childNodes[2].childNodes[0].data == '3' def test_content_settings(): raises(TypeError, lambda: mathml(x, method="garbage")) def test_content_mathml_logic(): assert mathml(And(x, y)) == '<apply><and/><ci>x</ci><ci>y</ci></apply>' assert mathml(Or(x, y)) == '<apply><or/><ci>x</ci><ci>y</ci></apply>' assert mathml(Xor(x, y)) == '<apply><xor/><ci>x</ci><ci>y</ci></apply>' assert mathml(Implies(x, y)) == '<apply><implies/><ci>x</ci><ci>y</ci></apply>' assert mathml(Not(x)) == '<apply><not/><ci>x</ci></apply>' def test_content_finite_sets(): assert mathml(FiniteSet(a)) == '<set><ci>a</ci></set>' assert mathml(FiniteSet(a, b)) == '<set><ci>a</ci><ci>b</ci></set>' assert mathml(FiniteSet(FiniteSet(a, b), c)) == \ '<set><ci>c</ci><set><ci>a</ci><ci>b</ci></set></set>' A = FiniteSet(a) B = FiniteSet(b) C = FiniteSet(c) D = FiniteSet(d) U1 = Union(A, B, evaluate=False) U2 = Union(C, D, evaluate=False) I1 = Intersection(A, B, evaluate=False) I2 = Intersection(C, D, evaluate=False) C1 = Complement(A, B, evaluate=False) C2 = Complement(C, D, evaluate=False) # XXX ProductSet does not support evaluate keyword P1 = ProductSet(A, B) P2 = ProductSet(C, D) assert mathml(U1) == \ '<apply><union/><set><ci>a</ci></set><set><ci>b</ci></set></apply>' assert mathml(I1) == \ '<apply><intersect/><set><ci>a</ci></set><set><ci>b</ci></set>' \ '</apply>' assert mathml(C1) == \ '<apply><setdiff/><set><ci>a</ci></set><set><ci>b</ci></set></apply>' assert mathml(P1) == \ '<apply><cartesianproduct/><set><ci>a</ci></set><set><ci>b</ci>' \ '</set></apply>' assert mathml(Intersection(A, U2, evaluate=False)) == \ '<apply><intersect/><set><ci>a</ci></set><apply><union/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' assert mathml(Intersection(U1, U2, evaluate=False)) == \ '<apply><intersect/><apply><union/><set><ci>a</ci></set><set>' \ '<ci>b</ci></set></apply><apply><union/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' # XXX Does the parenthesis appear correctly for these examples in mathjax? assert mathml(Intersection(C1, C2, evaluate=False)) == \ '<apply><intersect/><apply><setdiff/><set><ci>a</ci></set><set>' \ '<ci>b</ci></set></apply><apply><setdiff/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' assert mathml(Intersection(P1, P2, evaluate=False)) == \ '<apply><intersect/><apply><cartesianproduct/><set><ci>a</ci></set>' \ '<set><ci>b</ci></set></apply><apply><cartesianproduct/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' assert mathml(Union(A, I2, evaluate=False)) == \ '<apply><union/><set><ci>a</ci></set><apply><intersect/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' assert mathml(Union(I1, I2, evaluate=False)) == \ '<apply><union/><apply><intersect/><set><ci>a</ci></set><set>' \ '<ci>b</ci></set></apply><apply><intersect/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' assert mathml(Union(C1, C2, evaluate=False)) == \ '<apply><union/><apply><setdiff/><set><ci>a</ci></set><set>' \ '<ci>b</ci></set></apply><apply><setdiff/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' assert mathml(Union(P1, P2, evaluate=False)) == \ '<apply><union/><apply><cartesianproduct/><set><ci>a</ci></set>' \ '<set><ci>b</ci></set></apply><apply><cartesianproduct/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' assert mathml(Complement(A, C2, evaluate=False)) == \ '<apply><setdiff/><set><ci>a</ci></set><apply><setdiff/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' assert mathml(Complement(U1, U2, evaluate=False)) == \ '<apply><setdiff/><apply><union/><set><ci>a</ci></set><set>' \ '<ci>b</ci></set></apply><apply><union/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' assert mathml(Complement(I1, I2, evaluate=False)) == \ '<apply><setdiff/><apply><intersect/><set><ci>a</ci></set><set>' \ '<ci>b</ci></set></apply><apply><intersect/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' assert mathml(Complement(P1, P2, evaluate=False)) == \ '<apply><setdiff/><apply><cartesianproduct/><set><ci>a</ci></set>' \ '<set><ci>b</ci></set></apply><apply><cartesianproduct/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' assert mathml(ProductSet(A, P2)) == \ '<apply><cartesianproduct/><set><ci>a</ci></set>' \ '<apply><cartesianproduct/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' assert mathml(ProductSet(U1, U2)) == \ '<apply><cartesianproduct/><apply><union/><set><ci>a</ci></set>' \ '<set><ci>b</ci></set></apply><apply><union/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' assert mathml(ProductSet(I1, I2)) == \ '<apply><cartesianproduct/><apply><intersect/><set><ci>a</ci></set>' \ '<set><ci>b</ci></set></apply><apply><intersect/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' assert mathml(ProductSet(C1, C2)) == \ '<apply><cartesianproduct/><apply><setdiff/><set><ci>a</ci></set>' \ '<set><ci>b</ci></set></apply><apply><setdiff/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' def test_presentation_printmethod(): assert mpp.doprint(1 + x) == '<mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow>' assert mpp.doprint(x**2) == '<msup><mi>x</mi><mn>2</mn></msup>' assert mpp.doprint(x**-1) == '<mfrac><mn>1</mn><mi>x</mi></mfrac>' assert mpp.doprint(x**-2) == \ '<mfrac><mn>1</mn><msup><mi>x</mi><mn>2</mn></msup></mfrac>' assert mpp.doprint(2*x) == \ '<mrow><mn>2</mn><mo>&InvisibleTimes;</mo><mi>x</mi></mrow>' def test_presentation_mathml_core(): mml_1 = mpp._print(1 + x) assert mml_1.nodeName == 'mrow' nodes = mml_1.childNodes assert len(nodes) == 3 assert nodes[0].nodeName in ['mi', 'mn'] assert nodes[1].nodeName == 'mo' if nodes[0].nodeName == 'mn': assert nodes[0].childNodes[0].nodeValue == '1' assert nodes[2].childNodes[0].nodeValue == 'x' else: assert nodes[0].childNodes[0].nodeValue == 'x' assert nodes[2].childNodes[0].nodeValue == '1' mml_2 = mpp._print(x**2) assert mml_2.nodeName == 'msup' nodes = mml_2.childNodes assert nodes[0].childNodes[0].nodeValue == 'x' assert nodes[1].childNodes[0].nodeValue == '2' mml_3 = mpp._print(2*x) assert mml_3.nodeName == 'mrow' nodes = mml_3.childNodes assert nodes[0].childNodes[0].nodeValue == '2' assert nodes[1].childNodes[0].nodeValue == '&InvisibleTimes;' assert nodes[2].childNodes[0].nodeValue == 'x' mml = mpp._print(Float(1.0, 2)*x) assert mml.nodeName == 'mrow' nodes = mml.childNodes assert nodes[0].childNodes[0].nodeValue == '1.0' assert nodes[1].childNodes[0].nodeValue == '&InvisibleTimes;' assert nodes[2].childNodes[0].nodeValue == 'x' def test_presentation_mathml_functions(): mml_1 = mpp._print(sin(x)) assert mml_1.childNodes[0].childNodes[0 ].nodeValue == 'sin' assert mml_1.childNodes[1].childNodes[0 ].childNodes[0].nodeValue == 'x' mml_2 = mpp._print(diff(sin(x), x, evaluate=False)) assert mml_2.nodeName == 'mrow' assert mml_2.childNodes[0].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '&dd;' assert mml_2.childNodes[1].childNodes[1 ].nodeName == 'mfenced' assert mml_2.childNodes[0].childNodes[1 ].childNodes[0].childNodes[0].nodeValue == '&dd;' mml_3 = mpp._print(diff(cos(x*y), x, evaluate=False)) assert mml_3.childNodes[0].nodeName == 'mfrac' assert mml_3.childNodes[0].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '&#x2202;' assert mml_3.childNodes[1].childNodes[0 ].childNodes[0].nodeValue == 'cos' def test_print_derivative(): f = Function('f') d = Derivative(f(x, y, z), x, z, x, z, z, y) assert mathml(d) == \ '<apply><partialdiff/><bvar><ci>y</ci><ci>z</ci><degree><cn>2</cn></degree><ci>x</ci><ci>z</ci><ci>x</ci></bvar><apply><f/><ci>x</ci><ci>y</ci><ci>z</ci></apply></apply>' assert mathml(d, printer='presentation') == \ '<mrow><mfrac><mrow><msup><mo>&#x2202;</mo><mn>6</mn></msup></mrow><mrow><mo>&#x2202;</mo><mi>y</mi><msup><mo>&#x2202;</mo><mn>2</mn></msup><mi>z</mi><mo>&#x2202;</mo><mi>x</mi><mo>&#x2202;</mo><mi>z</mi><mo>&#x2202;</mo><mi>x</mi></mrow></mfrac><mrow><mi>f</mi><mfenced><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow></mrow>' def test_presentation_mathml_limits(): lim_fun = sin(x)/x mml_1 = mpp._print(Limit(lim_fun, x, 0)) assert mml_1.childNodes[0].nodeName == 'munder' assert mml_1.childNodes[0].childNodes[0 ].childNodes[0].nodeValue == 'lim' assert mml_1.childNodes[0].childNodes[1 ].childNodes[0].childNodes[0 ].nodeValue == 'x' assert mml_1.childNodes[0].childNodes[1 ].childNodes[1].childNodes[0 ].nodeValue == '&#x2192;' assert mml_1.childNodes[0].childNodes[1 ].childNodes[2].childNodes[0 ].nodeValue == '0' def test_presentation_mathml_integrals(): assert mpp.doprint(Integral(x, (x, 0, 1))) == \ '<mrow><msubsup><mo>&#x222B;</mo><mn>0</mn><mn>1</mn></msubsup>'\ '<mi>x</mi><mo>&dd;</mo><mi>x</mi></mrow>' assert mpp.doprint(Integral(log(x), x)) == \ '<mrow><mo>&#x222B;</mo><mrow><mi>log</mi><mfenced><mi>x</mi>'\ '</mfenced></mrow><mo>&dd;</mo><mi>x</mi></mrow>' assert mpp.doprint(Integral(x*y, x, y)) == \ '<mrow><mo>&#x222C;</mo><mrow><mi>x</mi><mo>&InvisibleTimes;</mo>'\ '<mi>y</mi></mrow><mo>&dd;</mo><mi>y</mi><mo>&dd;</mo><mi>x</mi></mrow>' z, w = symbols('z w') assert mpp.doprint(Integral(x*y*z, x, y, z)) == \ '<mrow><mo>&#x222D;</mo><mrow><mi>x</mi><mo>&InvisibleTimes;</mo>'\ '<mi>y</mi><mo>&InvisibleTimes;</mo><mi>z</mi></mrow><mo>&dd;</mo>'\ '<mi>z</mi><mo>&dd;</mo><mi>y</mi><mo>&dd;</mo><mi>x</mi></mrow>' assert mpp.doprint(Integral(x*y*z*w, x, y, z, w)) == \ '<mrow><mo>&#x222B;</mo><mo>&#x222B;</mo><mo>&#x222B;</mo>'\ '<mo>&#x222B;</mo><mrow><mi>w</mi><mo>&InvisibleTimes;</mo>'\ '<mi>x</mi><mo>&InvisibleTimes;</mo><mi>y</mi>'\ '<mo>&InvisibleTimes;</mo><mi>z</mi></mrow><mo>&dd;</mo><mi>w</mi>'\ '<mo>&dd;</mo><mi>z</mi><mo>&dd;</mo><mi>y</mi><mo>&dd;</mo><mi>x</mi></mrow>' assert mpp.doprint(Integral(x, x, y, (z, 0, 1))) == \ '<mrow><msubsup><mo>&#x222B;</mo><mn>0</mn><mn>1</mn></msubsup>'\ '<mo>&#x222B;</mo><mo>&#x222B;</mo><mi>x</mi><mo>&dd;</mo><mi>z</mi>'\ '<mo>&dd;</mo><mi>y</mi><mo>&dd;</mo><mi>x</mi></mrow>' assert mpp.doprint(Integral(x, (x, 0))) == \ '<mrow><msup><mo>&#x222B;</mo><mn>0</mn></msup><mi>x</mi><mo>&dd;</mo>'\ '<mi>x</mi></mrow>' def test_presentation_mathml_matrices(): A = Matrix([1, 2, 3]) B = Matrix([[0, 5, 4], [2, 3, 1], [9, 7, 9]]) mll_1 = mpp._print(A) assert mll_1.childNodes[0].nodeName == 'mtable' assert mll_1.childNodes[0].childNodes[0].nodeName == 'mtr' assert len(mll_1.childNodes[0].childNodes) == 3 assert mll_1.childNodes[0].childNodes[0].childNodes[0].nodeName == 'mtd' assert len(mll_1.childNodes[0].childNodes[0].childNodes) == 1 assert mll_1.childNodes[0].childNodes[0].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '1' assert mll_1.childNodes[0].childNodes[1].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '2' assert mll_1.childNodes[0].childNodes[2].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '3' mll_2 = mpp._print(B) assert mll_2.childNodes[0].nodeName == 'mtable' assert mll_2.childNodes[0].childNodes[0].nodeName == 'mtr' assert len(mll_2.childNodes[0].childNodes) == 3 assert mll_2.childNodes[0].childNodes[0].childNodes[0].nodeName == 'mtd' assert len(mll_2.childNodes[0].childNodes[0].childNodes) == 3 assert mll_2.childNodes[0].childNodes[0].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '0' assert mll_2.childNodes[0].childNodes[0].childNodes[1 ].childNodes[0].childNodes[0].nodeValue == '5' assert mll_2.childNodes[0].childNodes[0].childNodes[2 ].childNodes[0].childNodes[0].nodeValue == '4' assert mll_2.childNodes[0].childNodes[1].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '2' assert mll_2.childNodes[0].childNodes[1].childNodes[1 ].childNodes[0].childNodes[0].nodeValue == '3' assert mll_2.childNodes[0].childNodes[1].childNodes[2 ].childNodes[0].childNodes[0].nodeValue == '1' assert mll_2.childNodes[0].childNodes[2].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '9' assert mll_2.childNodes[0].childNodes[2].childNodes[1 ].childNodes[0].childNodes[0].nodeValue == '7' assert mll_2.childNodes[0].childNodes[2].childNodes[2 ].childNodes[0].childNodes[0].nodeValue == '9' def test_presentation_mathml_sums(): summand = x mml_1 = mpp._print(Sum(summand, (x, 1, 10))) assert mml_1.childNodes[0].nodeName == 'munderover' assert len(mml_1.childNodes[0].childNodes) == 3 assert mml_1.childNodes[0].childNodes[0].childNodes[0 ].nodeValue == '&#x2211;' assert len(mml_1.childNodes[0].childNodes[1].childNodes) == 3 assert mml_1.childNodes[0].childNodes[2].childNodes[0 ].nodeValue == '10' assert mml_1.childNodes[1].childNodes[0].nodeValue == 'x' def test_presentation_mathml_add(): mml = mpp._print(x**5 - x**4 + x) assert len(mml.childNodes) == 5 assert mml.childNodes[0].childNodes[0].childNodes[0 ].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].childNodes[0 ].nodeValue == '5' assert mml.childNodes[1].childNodes[0].nodeValue == '-' assert mml.childNodes[2].childNodes[0].childNodes[0 ].nodeValue == 'x' assert mml.childNodes[2].childNodes[1].childNodes[0 ].nodeValue == '4' assert mml.childNodes[3].childNodes[0].nodeValue == '+' assert mml.childNodes[4].childNodes[0].nodeValue == 'x' def test_presentation_mathml_Rational(): mml_1 = mpp._print(Rational(1, 1)) assert mml_1.nodeName == 'mn' mml_2 = mpp._print(Rational(2, 5)) assert mml_2.nodeName == 'mfrac' assert mml_2.childNodes[0].childNodes[0].nodeValue == '2' assert mml_2.childNodes[1].childNodes[0].nodeValue == '5' def test_presentation_mathml_constants(): mml = mpp._print(I) assert mml.childNodes[0].nodeValue == '&ImaginaryI;' mml = mpp._print(E) assert mml.childNodes[0].nodeValue == '&ExponentialE;' mml = mpp._print(oo) assert mml.childNodes[0].nodeValue == '&#x221E;' mml = mpp._print(pi) assert mml.childNodes[0].nodeValue == '&pi;' assert mathml(hbar, printer='presentation') == '<mi>&#x210F;</mi>' assert mathml(S.TribonacciConstant, printer='presentation' ) == '<mi>TribonacciConstant</mi>' assert mathml(S.EulerGamma, printer='presentation' ) == '<mi>&#x3B3;</mi>' assert mathml(S.GoldenRatio, printer='presentation' ) == '<mi>&#x3A6;</mi>' assert mathml(zoo, printer='presentation') == \ '<mover><mo>&#x221E;</mo><mo>~</mo></mover>' assert mathml(S.NaN, printer='presentation') == '<mi>NaN</mi>' def test_presentation_mathml_trig(): mml = mpp._print(sin(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'sin' mml = mpp._print(cos(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'cos' mml = mpp._print(tan(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'tan' mml = mpp._print(asin(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arcsin' mml = mpp._print(acos(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arccos' mml = mpp._print(atan(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arctan' mml = mpp._print(sinh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'sinh' mml = mpp._print(cosh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'cosh' mml = mpp._print(tanh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'tanh' mml = mpp._print(asinh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arcsinh' mml = mpp._print(atanh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arctanh' mml = mpp._print(acosh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arccosh' def test_presentation_mathml_relational(): mml_1 = mpp._print(Eq(x, 1)) assert len(mml_1.childNodes) == 3 assert mml_1.childNodes[0].nodeName == 'mi' assert mml_1.childNodes[0].childNodes[0].nodeValue == 'x' assert mml_1.childNodes[1].nodeName == 'mo' assert mml_1.childNodes[1].childNodes[0].nodeValue == '=' assert mml_1.childNodes[2].nodeName == 'mn' assert mml_1.childNodes[2].childNodes[0].nodeValue == '1' mml_2 = mpp._print(Ne(1, x)) assert len(mml_2.childNodes) == 3 assert mml_2.childNodes[0].nodeName == 'mn' assert mml_2.childNodes[0].childNodes[0].nodeValue == '1' assert mml_2.childNodes[1].nodeName == 'mo' assert mml_2.childNodes[1].childNodes[0].nodeValue == '&#x2260;' assert mml_2.childNodes[2].nodeName == 'mi' assert mml_2.childNodes[2].childNodes[0].nodeValue == 'x' mml_3 = mpp._print(Ge(1, x)) assert len(mml_3.childNodes) == 3 assert mml_3.childNodes[0].nodeName == 'mn' assert mml_3.childNodes[0].childNodes[0].nodeValue == '1' assert mml_3.childNodes[1].nodeName == 'mo' assert mml_3.childNodes[1].childNodes[0].nodeValue == '&#x2265;' assert mml_3.childNodes[2].nodeName == 'mi' assert mml_3.childNodes[2].childNodes[0].nodeValue == 'x' mml_4 = mpp._print(Lt(1, x)) assert len(mml_4.childNodes) == 3 assert mml_4.childNodes[0].nodeName == 'mn' assert mml_4.childNodes[0].childNodes[0].nodeValue == '1' assert mml_4.childNodes[1].nodeName == 'mo' assert mml_4.childNodes[1].childNodes[0].nodeValue == '<' assert mml_4.childNodes[2].nodeName == 'mi' assert mml_4.childNodes[2].childNodes[0].nodeValue == 'x' def test_presentation_symbol(): mml = mpp._print(x) assert mml.nodeName == 'mi' assert mml.childNodes[0].nodeValue == 'x' del mml mml = mpp._print(Symbol("x^2")) assert mml.nodeName == 'msup' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].nodeValue == '2' del mml mml = mpp._print(Symbol("x__2")) assert mml.nodeName == 'msup' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].nodeValue == '2' del mml mml = mpp._print(Symbol("x_2")) assert mml.nodeName == 'msub' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].nodeValue == '2' del mml mml = mpp._print(Symbol("x^3_2")) assert mml.nodeName == 'msubsup' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].nodeValue == '2' assert mml.childNodes[2].nodeName == 'mi' assert mml.childNodes[2].childNodes[0].nodeValue == '3' del mml mml = mpp._print(Symbol("x__3_2")) assert mml.nodeName == 'msubsup' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].nodeValue == '2' assert mml.childNodes[2].nodeName == 'mi' assert mml.childNodes[2].childNodes[0].nodeValue == '3' del mml mml = mpp._print(Symbol("x_2_a")) assert mml.nodeName == 'msub' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mrow' assert mml.childNodes[1].childNodes[0].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2' assert mml.childNodes[1].childNodes[1].nodeName == 'mo' assert mml.childNodes[1].childNodes[1].childNodes[0].nodeValue == ' ' assert mml.childNodes[1].childNodes[2].nodeName == 'mi' assert mml.childNodes[1].childNodes[2].childNodes[0].nodeValue == 'a' del mml mml = mpp._print(Symbol("x^2^a")) assert mml.nodeName == 'msup' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mrow' assert mml.childNodes[1].childNodes[0].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2' assert mml.childNodes[1].childNodes[1].nodeName == 'mo' assert mml.childNodes[1].childNodes[1].childNodes[0].nodeValue == ' ' assert mml.childNodes[1].childNodes[2].nodeName == 'mi' assert mml.childNodes[1].childNodes[2].childNodes[0].nodeValue == 'a' del mml mml = mpp._print(Symbol("x__2__a")) assert mml.nodeName == 'msup' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mrow' assert mml.childNodes[1].childNodes[0].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2' assert mml.childNodes[1].childNodes[1].nodeName == 'mo' assert mml.childNodes[1].childNodes[1].childNodes[0].nodeValue == ' ' assert mml.childNodes[1].childNodes[2].nodeName == 'mi' assert mml.childNodes[1].childNodes[2].childNodes[0].nodeValue == 'a' del mml def test_presentation_mathml_greek(): mml = mpp._print(Symbol('alpha')) assert mml.nodeName == 'mi' assert mml.childNodes[0].nodeValue == '\N{GREEK SMALL LETTER ALPHA}' assert mpp.doprint(Symbol('alpha')) == '<mi>&#945;</mi>' assert mpp.doprint(Symbol('beta')) == '<mi>&#946;</mi>' assert mpp.doprint(Symbol('gamma')) == '<mi>&#947;</mi>' assert mpp.doprint(Symbol('delta')) == '<mi>&#948;</mi>' assert mpp.doprint(Symbol('epsilon')) == '<mi>&#949;</mi>' assert mpp.doprint(Symbol('zeta')) == '<mi>&#950;</mi>' assert mpp.doprint(Symbol('eta')) == '<mi>&#951;</mi>' assert mpp.doprint(Symbol('theta')) == '<mi>&#952;</mi>' assert mpp.doprint(Symbol('iota')) == '<mi>&#953;</mi>' assert mpp.doprint(Symbol('kappa')) == '<mi>&#954;</mi>' assert mpp.doprint(Symbol('lambda')) == '<mi>&#955;</mi>' assert mpp.doprint(Symbol('mu')) == '<mi>&#956;</mi>' assert mpp.doprint(Symbol('nu')) == '<mi>&#957;</mi>' assert mpp.doprint(Symbol('xi')) == '<mi>&#958;</mi>' assert mpp.doprint(Symbol('omicron')) == '<mi>&#959;</mi>' assert mpp.doprint(Symbol('pi')) == '<mi>&#960;</mi>' assert mpp.doprint(Symbol('rho')) == '<mi>&#961;</mi>' assert mpp.doprint(Symbol('varsigma')) == '<mi>&#962;</mi>' assert mpp.doprint(Symbol('sigma')) == '<mi>&#963;</mi>' assert mpp.doprint(Symbol('tau')) == '<mi>&#964;</mi>' assert mpp.doprint(Symbol('upsilon')) == '<mi>&#965;</mi>' assert mpp.doprint(Symbol('phi')) == '<mi>&#966;</mi>' assert mpp.doprint(Symbol('chi')) == '<mi>&#967;</mi>' assert mpp.doprint(Symbol('psi')) == '<mi>&#968;</mi>' assert mpp.doprint(Symbol('omega')) == '<mi>&#969;</mi>' assert mpp.doprint(Symbol('Alpha')) == '<mi>&#913;</mi>' assert mpp.doprint(Symbol('Beta')) == '<mi>&#914;</mi>' assert mpp.doprint(Symbol('Gamma')) == '<mi>&#915;</mi>' assert mpp.doprint(Symbol('Delta')) == '<mi>&#916;</mi>' assert mpp.doprint(Symbol('Epsilon')) == '<mi>&#917;</mi>' assert mpp.doprint(Symbol('Zeta')) == '<mi>&#918;</mi>' assert mpp.doprint(Symbol('Eta')) == '<mi>&#919;</mi>' assert mpp.doprint(Symbol('Theta')) == '<mi>&#920;</mi>' assert mpp.doprint(Symbol('Iota')) == '<mi>&#921;</mi>' assert mpp.doprint(Symbol('Kappa')) == '<mi>&#922;</mi>' assert mpp.doprint(Symbol('Lambda')) == '<mi>&#923;</mi>' assert mpp.doprint(Symbol('Mu')) == '<mi>&#924;</mi>' assert mpp.doprint(Symbol('Nu')) == '<mi>&#925;</mi>' assert mpp.doprint(Symbol('Xi')) == '<mi>&#926;</mi>' assert mpp.doprint(Symbol('Omicron')) == '<mi>&#927;</mi>' assert mpp.doprint(Symbol('Pi')) == '<mi>&#928;</mi>' assert mpp.doprint(Symbol('Rho')) == '<mi>&#929;</mi>' assert mpp.doprint(Symbol('Sigma')) == '<mi>&#931;</mi>' assert mpp.doprint(Symbol('Tau')) == '<mi>&#932;</mi>' assert mpp.doprint(Symbol('Upsilon')) == '<mi>&#933;</mi>' assert mpp.doprint(Symbol('Phi')) == '<mi>&#934;</mi>' assert mpp.doprint(Symbol('Chi')) == '<mi>&#935;</mi>' assert mpp.doprint(Symbol('Psi')) == '<mi>&#936;</mi>' assert mpp.doprint(Symbol('Omega')) == '<mi>&#937;</mi>' def test_presentation_mathml_order(): expr = x**3 + x**2*y + 3*x*y**3 + y**4 mp = MathMLPresentationPrinter({'order': 'lex'}) mml = mp._print(expr) assert mml.childNodes[0].nodeName == 'msup' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '3' assert mml.childNodes[6].nodeName == 'msup' assert mml.childNodes[6].childNodes[0].childNodes[0].nodeValue == 'y' assert mml.childNodes[6].childNodes[1].childNodes[0].nodeValue == '4' mp = MathMLPresentationPrinter({'order': 'rev-lex'}) mml = mp._print(expr) assert mml.childNodes[0].nodeName == 'msup' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'y' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '4' assert mml.childNodes[6].nodeName == 'msup' assert mml.childNodes[6].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[6].childNodes[1].childNodes[0].nodeValue == '3' def test_print_intervals(): a = Symbol('a', real=True) assert mpp.doprint(Interval(0, a)) == \ '<mrow><mfenced close="]" open="["><mn>0</mn><mi>a</mi></mfenced></mrow>' assert mpp.doprint(Interval(0, a, False, False)) == \ '<mrow><mfenced close="]" open="["><mn>0</mn><mi>a</mi></mfenced></mrow>' assert mpp.doprint(Interval(0, a, True, False)) == \ '<mrow><mfenced close="]" open="("><mn>0</mn><mi>a</mi></mfenced></mrow>' assert mpp.doprint(Interval(0, a, False, True)) == \ '<mrow><mfenced close=")" open="["><mn>0</mn><mi>a</mi></mfenced></mrow>' assert mpp.doprint(Interval(0, a, True, True)) == \ '<mrow><mfenced close=")" open="("><mn>0</mn><mi>a</mi></mfenced></mrow>' def test_print_tuples(): assert mpp.doprint(Tuple(0,)) == \ '<mrow><mfenced><mn>0</mn></mfenced></mrow>' assert mpp.doprint(Tuple(0, a)) == \ '<mrow><mfenced><mn>0</mn><mi>a</mi></mfenced></mrow>' assert mpp.doprint(Tuple(0, a, a)) == \ '<mrow><mfenced><mn>0</mn><mi>a</mi><mi>a</mi></mfenced></mrow>' assert mpp.doprint(Tuple(0, 1, 2, 3, 4)) == \ '<mrow><mfenced><mn>0</mn><mn>1</mn><mn>2</mn><mn>3</mn><mn>4</mn></mfenced></mrow>' assert mpp.doprint(Tuple(0, 1, Tuple(2, 3, 4))) == \ '<mrow><mfenced><mn>0</mn><mn>1</mn><mrow><mfenced><mn>2</mn><mn>3'\ '</mn><mn>4</mn></mfenced></mrow></mfenced></mrow>' def test_print_re_im(): assert mpp.doprint(re(x)) == \ '<mrow><mi mathvariant="fraktur">R</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(im(x)) == \ '<mrow><mi mathvariant="fraktur">I</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(re(x + 1)) == \ '<mrow><mrow><mi mathvariant="fraktur">R</mi><mfenced><mi>x</mi>'\ '</mfenced></mrow><mo>+</mo><mn>1</mn></mrow>' assert mpp.doprint(im(x + 1)) == \ '<mrow><mi mathvariant="fraktur">I</mi><mfenced><mi>x</mi></mfenced></mrow>' def test_print_Abs(): assert mpp.doprint(Abs(x)) == \ '<mrow><mfenced close="|" open="|"><mi>x</mi></mfenced></mrow>' assert mpp.doprint(Abs(x + 1)) == \ '<mrow><mfenced close="|" open="|"><mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow></mfenced></mrow>' def test_print_Determinant(): assert mpp.doprint(Determinant(Matrix([[1, 2], [3, 4]]))) == \ '<mrow><mfenced close="|" open="|"><mfenced close="]" open="["><mtable><mtr><mtd><mn>1</mn></mtd><mtd><mn>2</mn></mtd></mtr><mtr><mtd><mn>3</mn></mtd><mtd><mn>4</mn></mtd></mtr></mtable></mfenced></mfenced></mrow>' def test_presentation_settings(): raises(TypeError, lambda: mathml(x, printer='presentation', method="garbage")) def test_toprettyxml_hooking(): # test that the patch doesn't influence the behavior of the standard # library import xml.dom.minidom doc1 = xml.dom.minidom.parseString( "<apply><plus/><ci>x</ci><cn>1</cn></apply>") doc2 = xml.dom.minidom.parseString( "<mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow>") prettyxml_old1 = doc1.toprettyxml() prettyxml_old2 = doc2.toprettyxml() mp.apply_patch() mp.restore_patch() assert prettyxml_old1 == doc1.toprettyxml() assert prettyxml_old2 == doc2.toprettyxml() def test_print_domains(): from sympy.sets import Integers, Naturals, Naturals0, Reals, Complexes assert mpp.doprint(Complexes) == '<mi mathvariant="normal">&#x2102;</mi>' assert mpp.doprint(Integers) == '<mi mathvariant="normal">&#x2124;</mi>' assert mpp.doprint(Naturals) == '<mi mathvariant="normal">&#x2115;</mi>' assert mpp.doprint(Naturals0) == \ '<msub><mi mathvariant="normal">&#x2115;</mi><mn>0</mn></msub>' assert mpp.doprint(Reals) == '<mi mathvariant="normal">&#x211D;</mi>' def test_print_expression_with_minus(): assert mpp.doprint(-x) == '<mrow><mo>-</mo><mi>x</mi></mrow>' assert mpp.doprint(-x/y) == \ '<mrow><mo>-</mo><mfrac><mi>x</mi><mi>y</mi></mfrac></mrow>' assert mpp.doprint(-Rational(1, 2)) == \ '<mrow><mo>-</mo><mfrac><mn>1</mn><mn>2</mn></mfrac></mrow>' def test_print_AssocOp(): from sympy.core.operations import AssocOp class TestAssocOp(AssocOp): identity = 0 expr = TestAssocOp(1, 2) assert mpp.doprint(expr) == \ '<mrow><mi>testassocop</mi><mn>1</mn><mn>2</mn></mrow>' def test_print_basic(): expr = Basic(S(1), S(2)) assert mpp.doprint(expr) == \ '<mrow><mi>basic</mi><mfenced><mn>1</mn><mn>2</mn></mfenced></mrow>' assert mp.doprint(expr) == '<basic><cn>1</cn><cn>2</cn></basic>' def test_mat_delim_print(): expr = Matrix([[1, 2], [3, 4]]) assert mathml(expr, printer='presentation', mat_delim='[') == \ '<mfenced close="]" open="["><mtable><mtr><mtd><mn>1</mn></mtd><mtd>'\ '<mn>2</mn></mtd></mtr><mtr><mtd><mn>3</mn></mtd><mtd><mn>4</mn>'\ '</mtd></mtr></mtable></mfenced>' assert mathml(expr, printer='presentation', mat_delim='(') == \ '<mfenced><mtable><mtr><mtd><mn>1</mn></mtd><mtd><mn>2</mn></mtd>'\ '</mtr><mtr><mtd><mn>3</mn></mtd><mtd><mn>4</mn></mtd></mtr></mtable></mfenced>' assert mathml(expr, printer='presentation', mat_delim='') == \ '<mtable><mtr><mtd><mn>1</mn></mtd><mtd><mn>2</mn></mtd></mtr><mtr>'\ '<mtd><mn>3</mn></mtd><mtd><mn>4</mn></mtd></mtr></mtable>' def test_ln_notation_print(): expr = log(x) assert mathml(expr, printer='presentation') == \ '<mrow><mi>log</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mathml(expr, printer='presentation', ln_notation=False) == \ '<mrow><mi>log</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mathml(expr, printer='presentation', ln_notation=True) == \ '<mrow><mi>ln</mi><mfenced><mi>x</mi></mfenced></mrow>' def test_mul_symbol_print(): expr = x * y assert mathml(expr, printer='presentation') == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mi>y</mi></mrow>' assert mathml(expr, printer='presentation', mul_symbol=None) == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mi>y</mi></mrow>' assert mathml(expr, printer='presentation', mul_symbol='dot') == \ '<mrow><mi>x</mi><mo>&#xB7;</mo><mi>y</mi></mrow>' assert mathml(expr, printer='presentation', mul_symbol='ldot') == \ '<mrow><mi>x</mi><mo>&#x2024;</mo><mi>y</mi></mrow>' assert mathml(expr, printer='presentation', mul_symbol='times') == \ '<mrow><mi>x</mi><mo>&#xD7;</mo><mi>y</mi></mrow>' def test_print_lerchphi(): assert mpp.doprint(lerchphi(1, 2, 3)) == \ '<mrow><mi>&#x3A6;</mi><mfenced><mn>1</mn><mn>2</mn><mn>3</mn></mfenced></mrow>' def test_print_polylog(): assert mp.doprint(polylog(x, y)) == \ '<apply><polylog/><ci>x</ci><ci>y</ci></apply>' assert mpp.doprint(polylog(x, y)) == \ '<mrow><msub><mi>Li</mi><mi>x</mi></msub><mfenced><mi>y</mi></mfenced></mrow>' def test_print_set_frozenset(): f = frozenset({1, 5, 3}) assert mpp.doprint(f) == \ '<mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mn>5</mn></mfenced>' s = set({1, 2, 3}) assert mpp.doprint(s) == \ '<mfenced close="}" open="{"><mn>1</mn><mn>2</mn><mn>3</mn></mfenced>' def test_print_FiniteSet(): f1 = FiniteSet(x, 1, 3) assert mpp.doprint(f1) == \ '<mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mi>x</mi></mfenced>' def test_print_LambertW(): assert mpp.doprint(LambertW(x)) == '<mrow><mi>W</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(LambertW(x, y)) == '<mrow><mi>W</mi><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>' def test_print_EmptySet(): assert mpp.doprint(S.EmptySet) == '<mo>&#x2205;</mo>' def test_print_UniversalSet(): assert mpp.doprint(S.UniversalSet) == '<mo>&#x1D54C;</mo>' def test_print_spaces(): assert mpp.doprint(HilbertSpace()) == '<mi>&#x210B;</mi>' assert mpp.doprint(ComplexSpace(2)) == '<msup>&#x1D49E;<mn>2</mn></msup>' assert mpp.doprint(FockSpace()) == '<mi>&#x2131;</mi>' def test_print_constants(): assert mpp.doprint(hbar) == '<mi>&#x210F;</mi>' assert mpp.doprint(S.TribonacciConstant) == '<mi>TribonacciConstant</mi>' assert mpp.doprint(S.GoldenRatio) == '<mi>&#x3A6;</mi>' assert mpp.doprint(S.EulerGamma) == '<mi>&#x3B3;</mi>' def test_print_Contains(): assert mpp.doprint(Contains(x, S.Naturals)) == \ '<mrow><mi>x</mi><mo>&#x2208;</mo><mi mathvariant="normal">&#x2115;</mi></mrow>' def test_print_Dagger(): assert mpp.doprint(Dagger(x)) == '<msup><mi>x</mi>&#x2020;</msup>' def test_print_SetOp(): f1 = FiniteSet(x, 1, 3) f2 = FiniteSet(y, 2, 4) prntr = lambda x: mathml(x, printer='presentation') assert prntr(Union(f1, f2, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mi>x</mi>'\ '</mfenced><mo>&#x222A;</mo><mfenced close="}" open="{"><mn>2</mn>'\ '<mn>4</mn><mi>y</mi></mfenced></mrow>' assert prntr(Intersection(f1, f2, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mi>x</mi>'\ '</mfenced><mo>&#x2229;</mo><mfenced close="}" open="{"><mn>2</mn>'\ '<mn>4</mn><mi>y</mi></mfenced></mrow>' assert prntr(Complement(f1, f2, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mi>x</mi>'\ '</mfenced><mo>&#x2216;</mo><mfenced close="}" open="{"><mn>2</mn>'\ '<mn>4</mn><mi>y</mi></mfenced></mrow>' assert prntr(SymmetricDifference(f1, f2, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mi>x</mi>'\ '</mfenced><mo>&#x2206;</mo><mfenced close="}" open="{"><mn>2</mn>'\ '<mn>4</mn><mi>y</mi></mfenced></mrow>' A = FiniteSet(a) C = FiniteSet(c) D = FiniteSet(d) U1 = Union(C, D, evaluate=False) I1 = Intersection(C, D, evaluate=False) C1 = Complement(C, D, evaluate=False) D1 = SymmetricDifference(C, D, evaluate=False) # XXX ProductSet does not support evaluate keyword P1 = ProductSet(C, D) assert prntr(Union(A, I1, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mi>a</mi></mfenced>' \ '<mo>&#x222A;</mo><mfenced><mrow><mfenced close="}" open="{">' \ '<mi>c</mi></mfenced><mo>&#x2229;</mo><mfenced close="}" open="{">' \ '<mi>d</mi></mfenced></mrow></mfenced></mrow>' assert prntr(Intersection(A, C1, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mi>a</mi></mfenced>' \ '<mo>&#x2229;</mo><mfenced><mrow><mfenced close="}" open="{">' \ '<mi>c</mi></mfenced><mo>&#x2216;</mo><mfenced close="}" open="{">' \ '<mi>d</mi></mfenced></mrow></mfenced></mrow>' assert prntr(Complement(A, D1, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mi>a</mi></mfenced>' \ '<mo>&#x2216;</mo><mfenced><mrow><mfenced close="}" open="{">' \ '<mi>c</mi></mfenced><mo>&#x2206;</mo><mfenced close="}" open="{">' \ '<mi>d</mi></mfenced></mrow></mfenced></mrow>' assert prntr(SymmetricDifference(A, P1, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mi>a</mi></mfenced>' \ '<mo>&#x2206;</mo><mfenced><mrow><mfenced close="}" open="{">' \ '<mi>c</mi></mfenced><mo>&#x00d7;</mo><mfenced close="}" open="{">' \ '<mi>d</mi></mfenced></mrow></mfenced></mrow>' assert prntr(ProductSet(A, U1)) == \ '<mrow><mfenced close="}" open="{"><mi>a</mi></mfenced>' \ '<mo>&#x00d7;</mo><mfenced><mrow><mfenced close="}" open="{">' \ '<mi>c</mi></mfenced><mo>&#x222A;</mo><mfenced close="}" open="{">' \ '<mi>d</mi></mfenced></mrow></mfenced></mrow>' def test_print_logic(): assert mpp.doprint(And(x, y)) == \ '<mrow><mi>x</mi><mo>&#x2227;</mo><mi>y</mi></mrow>' assert mpp.doprint(Or(x, y)) == \ '<mrow><mi>x</mi><mo>&#x2228;</mo><mi>y</mi></mrow>' assert mpp.doprint(Xor(x, y)) == \ '<mrow><mi>x</mi><mo>&#x22BB;</mo><mi>y</mi></mrow>' assert mpp.doprint(Implies(x, y)) == \ '<mrow><mi>x</mi><mo>&#x21D2;</mo><mi>y</mi></mrow>' assert mpp.doprint(Equivalent(x, y)) == \ '<mrow><mi>x</mi><mo>&#x21D4;</mo><mi>y</mi></mrow>' assert mpp.doprint(And(Eq(x, y), x > 4)) == \ '<mrow><mrow><mi>x</mi><mo>=</mo><mi>y</mi></mrow><mo>&#x2227;</mo>'\ '<mrow><mi>x</mi><mo>></mo><mn>4</mn></mrow></mrow>' assert mpp.doprint(And(Eq(x, 3), y < 3, x > y + 1)) == \ '<mrow><mrow><mi>x</mi><mo>=</mo><mn>3</mn></mrow><mo>&#x2227;</mo>'\ '<mrow><mi>x</mi><mo>></mo><mrow><mi>y</mi><mo>+</mo><mn>1</mn></mrow>'\ '</mrow><mo>&#x2227;</mo><mrow><mi>y</mi><mo><</mo><mn>3</mn></mrow></mrow>' assert mpp.doprint(Or(Eq(x, y), x > 4)) == \ '<mrow><mrow><mi>x</mi><mo>=</mo><mi>y</mi></mrow><mo>&#x2228;</mo>'\ '<mrow><mi>x</mi><mo>></mo><mn>4</mn></mrow></mrow>' assert mpp.doprint(And(Eq(x, 3), Or(y < 3, x > y + 1))) == \ '<mrow><mrow><mi>x</mi><mo>=</mo><mn>3</mn></mrow><mo>&#x2227;</mo>'\ '<mfenced><mrow><mrow><mi>x</mi><mo>></mo><mrow><mi>y</mi><mo>+</mo>'\ '<mn>1</mn></mrow></mrow><mo>&#x2228;</mo><mrow><mi>y</mi><mo><</mo>'\ '<mn>3</mn></mrow></mrow></mfenced></mrow>' assert mpp.doprint(Not(x)) == '<mrow><mo>&#xAC;</mo><mi>x</mi></mrow>' assert mpp.doprint(Not(And(x, y))) == \ '<mrow><mo>&#xAC;</mo><mfenced><mrow><mi>x</mi><mo>&#x2227;</mo>'\ '<mi>y</mi></mrow></mfenced></mrow>' def test_root_notation_print(): assert mathml(x**(S.One/3), printer='presentation') == \ '<mroot><mi>x</mi><mn>3</mn></mroot>' assert mathml(x**(S.One/3), printer='presentation', root_notation=False) ==\ '<msup><mi>x</mi><mfrac><mn>1</mn><mn>3</mn></mfrac></msup>' assert mathml(x**(S.One/3), printer='content') == \ '<apply><root/><degree><cn>3</cn></degree><ci>x</ci></apply>' assert mathml(x**(S.One/3), printer='content', root_notation=False) == \ '<apply><power/><ci>x</ci><apply><divide/><cn>1</cn><cn>3</cn></apply></apply>' assert mathml(x**(Rational(-1, 3)), printer='presentation') == \ '<mfrac><mn>1</mn><mroot><mi>x</mi><mn>3</mn></mroot></mfrac>' assert mathml(x**(Rational(-1, 3)), printer='presentation', root_notation=False) \ == '<mfrac><mn>1</mn><msup><mi>x</mi><mfrac><mn>1</mn><mn>3</mn></mfrac></msup></mfrac>' def test_fold_frac_powers_print(): expr = x ** Rational(5, 2) assert mathml(expr, printer='presentation') == \ '<msup><mi>x</mi><mfrac><mn>5</mn><mn>2</mn></mfrac></msup>' assert mathml(expr, printer='presentation', fold_frac_powers=True) == \ '<msup><mi>x</mi><mfrac bevelled="true"><mn>5</mn><mn>2</mn></mfrac></msup>' assert mathml(expr, printer='presentation', fold_frac_powers=False) == \ '<msup><mi>x</mi><mfrac><mn>5</mn><mn>2</mn></mfrac></msup>' def test_fold_short_frac_print(): expr = Rational(2, 5) assert mathml(expr, printer='presentation') == \ '<mfrac><mn>2</mn><mn>5</mn></mfrac>' assert mathml(expr, printer='presentation', fold_short_frac=True) == \ '<mfrac bevelled="true"><mn>2</mn><mn>5</mn></mfrac>' assert mathml(expr, printer='presentation', fold_short_frac=False) == \ '<mfrac><mn>2</mn><mn>5</mn></mfrac>' def test_print_factorials(): assert mpp.doprint(factorial(x)) == '<mrow><mi>x</mi><mo>!</mo></mrow>' assert mpp.doprint(factorial(x + 1)) == \ '<mrow><mfenced><mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow></mfenced><mo>!</mo></mrow>' assert mpp.doprint(factorial2(x)) == '<mrow><mi>x</mi><mo>!!</mo></mrow>' assert mpp.doprint(factorial2(x + 1)) == \ '<mrow><mfenced><mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow></mfenced><mo>!!</mo></mrow>' assert mpp.doprint(binomial(x, y)) == \ '<mfenced><mfrac linethickness="0"><mi>x</mi><mi>y</mi></mfrac></mfenced>' assert mpp.doprint(binomial(4, x + y)) == \ '<mfenced><mfrac linethickness="0"><mn>4</mn><mrow><mi>x</mi>'\ '<mo>+</mo><mi>y</mi></mrow></mfrac></mfenced>' def test_print_floor(): expr = floor(x) assert mathml(expr, printer='presentation') == \ '<mrow><mfenced close="&#8971;" open="&#8970;"><mi>x</mi></mfenced></mrow>' def test_print_ceiling(): expr = ceiling(x) assert mathml(expr, printer='presentation') == \ '<mrow><mfenced close="&#8969;" open="&#8968;"><mi>x</mi></mfenced></mrow>' def test_print_Lambda(): expr = Lambda(x, x+1) assert mathml(expr, printer='presentation') == \ '<mfenced><mrow><mi>x</mi><mo>&#x21A6;</mo><mrow><mi>x</mi><mo>+</mo>'\ '<mn>1</mn></mrow></mrow></mfenced>' expr = Lambda((x, y), x + y) assert mathml(expr, printer='presentation') == \ '<mfenced><mrow><mrow><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>'\ '<mo>&#x21A6;</mo><mrow><mi>x</mi><mo>+</mo><mi>y</mi></mrow></mrow></mfenced>' def test_print_conjugate(): assert mpp.doprint(conjugate(x)) == \ '<menclose notation="top"><mi>x</mi></menclose>' assert mpp.doprint(conjugate(x + 1)) == \ '<mrow><menclose notation="top"><mi>x</mi></menclose><mo>+</mo><mn>1</mn></mrow>' def test_print_AccumBounds(): a = Symbol('a', real=True) assert mpp.doprint(AccumBounds(0, 1)) == '<mfenced close="&#10217;" open="&#10216;"><mn>0</mn><mn>1</mn></mfenced>' assert mpp.doprint(AccumBounds(0, a)) == '<mfenced close="&#10217;" open="&#10216;"><mn>0</mn><mi>a</mi></mfenced>' assert mpp.doprint(AccumBounds(a + 1, a + 2)) == '<mfenced close="&#10217;" open="&#10216;"><mrow><mi>a</mi><mo>+</mo><mn>1</mn></mrow><mrow><mi>a</mi><mo>+</mo><mn>2</mn></mrow></mfenced>' def test_print_Float(): assert mpp.doprint(Float(1e100)) == '<mrow><mn>1.0</mn><mo>&#xB7;</mo><msup><mn>10</mn><mn>100</mn></msup></mrow>' assert mpp.doprint(Float(1e-100)) == '<mrow><mn>1.0</mn><mo>&#xB7;</mo><msup><mn>10</mn><mn>-100</mn></msup></mrow>' assert mpp.doprint(Float(-1e100)) == '<mrow><mn>-1.0</mn><mo>&#xB7;</mo><msup><mn>10</mn><mn>100</mn></msup></mrow>' assert mpp.doprint(Float(1.0*oo)) == '<mi>&#x221E;</mi>' assert mpp.doprint(Float(-1.0*oo)) == '<mrow><mo>-</mo><mi>&#x221E;</mi></mrow>' def test_print_different_functions(): assert mpp.doprint(gamma(x)) == '<mrow><mi>&#x393;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(lowergamma(x, y)) == '<mrow><mi>&#x3B3;</mi><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>' assert mpp.doprint(uppergamma(x, y)) == '<mrow><mi>&#x393;</mi><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>' assert mpp.doprint(zeta(x)) == '<mrow><mi>&#x3B6;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(zeta(x, y)) == '<mrow><mi>&#x3B6;</mi><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>' assert mpp.doprint(dirichlet_eta(x)) == '<mrow><mi>&#x3B7;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(elliptic_k(x)) == '<mrow><mi>&#x39A;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(totient(x)) == '<mrow><mi>&#x3D5;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(reduced_totient(x)) == '<mrow><mi>&#x3BB;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(primenu(x)) == '<mrow><mi>&#x3BD;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(primeomega(x)) == '<mrow><mi>&#x3A9;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(fresnels(x)) == '<mrow><mi>S</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(fresnelc(x)) == '<mrow><mi>C</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(Heaviside(x)) == '<mrow><mi>&#x398;</mi><mfenced><mi>x</mi><mfrac><mn>1</mn><mn>2</mn></mfrac></mfenced></mrow>' def test_mathml_builtins(): assert mpp.doprint(None) == '<mi>None</mi>' assert mpp.doprint(true) == '<mi>True</mi>' assert mpp.doprint(false) == '<mi>False</mi>' def test_mathml_Range(): assert mpp.doprint(Range(1, 51)) == \ '<mfenced close="}" open="{"><mn>1</mn><mn>2</mn><mi>&#8230;</mi><mn>50</mn></mfenced>' assert mpp.doprint(Range(1, 4)) == \ '<mfenced close="}" open="{"><mn>1</mn><mn>2</mn><mn>3</mn></mfenced>' assert mpp.doprint(Range(0, 3, 1)) == \ '<mfenced close="}" open="{"><mn>0</mn><mn>1</mn><mn>2</mn></mfenced>' assert mpp.doprint(Range(0, 30, 1)) == \ '<mfenced close="}" open="{"><mn>0</mn><mn>1</mn><mi>&#8230;</mi><mn>29</mn></mfenced>' assert mpp.doprint(Range(30, 1, -1)) == \ '<mfenced close="}" open="{"><mn>30</mn><mn>29</mn><mi>&#8230;</mi>'\ '<mn>2</mn></mfenced>' assert mpp.doprint(Range(0, oo, 2)) == \ '<mfenced close="}" open="{"><mn>0</mn><mn>2</mn><mi>&#8230;</mi></mfenced>' assert mpp.doprint(Range(oo, -2, -2)) == \ '<mfenced close="}" open="{"><mi>&#8230;</mi><mn>2</mn><mn>0</mn></mfenced>' assert mpp.doprint(Range(-2, -oo, -1)) == \ '<mfenced close="}" open="{"><mn>-2</mn><mn>-3</mn><mi>&#8230;</mi></mfenced>' def test_print_exp(): assert mpp.doprint(exp(x)) == \ '<msup><mi>&ExponentialE;</mi><mi>x</mi></msup>' assert mpp.doprint(exp(1) + exp(2)) == \ '<mrow><mi>&ExponentialE;</mi><mo>+</mo><msup><mi>&ExponentialE;</mi><mn>2</mn></msup></mrow>' def test_print_MinMax(): assert mpp.doprint(Min(x, y)) == \ '<mrow><mo>min</mo><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>' assert mpp.doprint(Min(x, 2, x**3)) == \ '<mrow><mo>min</mo><mfenced><mn>2</mn><mi>x</mi><msup><mi>x</mi>'\ '<mn>3</mn></msup></mfenced></mrow>' assert mpp.doprint(Max(x, y)) == \ '<mrow><mo>max</mo><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>' assert mpp.doprint(Max(x, 2, x**3)) == \ '<mrow><mo>max</mo><mfenced><mn>2</mn><mi>x</mi><msup><mi>x</mi>'\ '<mn>3</mn></msup></mfenced></mrow>' def test_mathml_presentation_numbers(): n = Symbol('n') assert mathml(catalan(n), printer='presentation') == \ '<msub><mi>C</mi><mi>n</mi></msub>' assert mathml(bernoulli(n), printer='presentation') == \ '<msub><mi>B</mi><mi>n</mi></msub>' assert mathml(bell(n), printer='presentation') == \ '<msub><mi>B</mi><mi>n</mi></msub>' assert mathml(euler(n), printer='presentation') == \ '<msub><mi>E</mi><mi>n</mi></msub>' assert mathml(fibonacci(n), printer='presentation') == \ '<msub><mi>F</mi><mi>n</mi></msub>' assert mathml(lucas(n), printer='presentation') == \ '<msub><mi>L</mi><mi>n</mi></msub>' assert mathml(tribonacci(n), printer='presentation') == \ '<msub><mi>T</mi><mi>n</mi></msub>' assert mathml(bernoulli(n, x), printer='presentation') == \ '<mrow><msub><mi>B</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' assert mathml(bell(n, x), printer='presentation') == \ '<mrow><msub><mi>B</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' assert mathml(euler(n, x), printer='presentation') == \ '<mrow><msub><mi>E</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' assert mathml(fibonacci(n, x), printer='presentation') == \ '<mrow><msub><mi>F</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' assert mathml(tribonacci(n, x), printer='presentation') == \ '<mrow><msub><mi>T</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' def test_mathml_presentation_mathieu(): assert mathml(mathieuc(x, y, z), printer='presentation') == \ '<mrow><mi>C</mi><mfenced><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow>' assert mathml(mathieus(x, y, z), printer='presentation') == \ '<mrow><mi>S</mi><mfenced><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow>' assert mathml(mathieucprime(x, y, z), printer='presentation') == \ '<mrow><mi>C&#x2032;</mi><mfenced><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow>' assert mathml(mathieusprime(x, y, z), printer='presentation') == \ '<mrow><mi>S&#x2032;</mi><mfenced><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow>' def test_mathml_presentation_stieltjes(): assert mathml(stieltjes(n), printer='presentation') == \ '<msub><mi>&#x03B3;</mi><mi>n</mi></msub>' assert mathml(stieltjes(n, x), printer='presentation') == \ '<mrow><msub><mi>&#x03B3;</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' def test_print_matrix_symbol(): A = MatrixSymbol('A', 1, 2) assert mpp.doprint(A) == '<mi>A</mi>' assert mp.doprint(A) == '<ci>A</ci>' assert mathml(A, printer='presentation', mat_symbol_style="bold") == \ '<mi mathvariant="bold">A</mi>' # No effect in content printer assert mathml(A, mat_symbol_style="bold") == '<ci>A</ci>' def test_print_hadamard(): from sympy.matrices.expressions import HadamardProduct from sympy.matrices.expressions import Transpose X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert mathml(HadamardProduct(X, Y*Y), printer="presentation") == \ '<mrow>' \ '<mi>X</mi>' \ '<mo>&#x2218;</mo>' \ '<msup><mi>Y</mi><mn>2</mn></msup>' \ '</mrow>' assert mathml(HadamardProduct(X, Y)*Y, printer="presentation") == \ '<mrow>' \ '<mfenced>' \ '<mrow><mi>X</mi><mo>&#x2218;</mo><mi>Y</mi></mrow>' \ '</mfenced>' \ '<mo>&InvisibleTimes;</mo><mi>Y</mi>' \ '</mrow>' assert mathml(HadamardProduct(X, Y, Y), printer="presentation") == \ '<mrow>' \ '<mi>X</mi><mo>&#x2218;</mo>' \ '<mi>Y</mi><mo>&#x2218;</mo>' \ '<mi>Y</mi>' \ '</mrow>' assert mathml( Transpose(HadamardProduct(X, Y)), printer="presentation") == \ '<msup>' \ '<mfenced>' \ '<mrow><mi>X</mi><mo>&#x2218;</mo><mi>Y</mi></mrow>' \ '</mfenced>' \ '<mo>T</mo>' \ '</msup>' def test_print_random_symbol(): R = RandomSymbol(Symbol('R')) assert mpp.doprint(R) == '<mi>R</mi>' assert mp.doprint(R) == '<ci>R</ci>' def test_print_IndexedBase(): assert mathml(IndexedBase(a)[b], printer='presentation') == \ '<msub><mi>a</mi><mi>b</mi></msub>' assert mathml(IndexedBase(a)[b, c, d], printer='presentation') == \ '<msub><mi>a</mi><mfenced><mi>b</mi><mi>c</mi><mi>d</mi></mfenced></msub>' assert mathml(IndexedBase(a)[b]*IndexedBase(c)[d]*IndexedBase(e), printer='presentation') == \ '<mrow><msub><mi>a</mi><mi>b</mi></msub><mo>&InvisibleTimes;'\ '</mo><msub><mi>c</mi><mi>d</mi></msub><mo>&InvisibleTimes;</mo><mi>e</mi></mrow>' def test_print_Indexed(): assert mathml(IndexedBase(a), printer='presentation') == '<mi>a</mi>' assert mathml(IndexedBase(a/b), printer='presentation') == \ '<mrow><mfrac><mi>a</mi><mi>b</mi></mfrac></mrow>' assert mathml(IndexedBase((a, b)), printer='presentation') == \ '<mrow><mfenced><mi>a</mi><mi>b</mi></mfenced></mrow>' def test_print_MatrixElement(): i, j = symbols('i j') A = MatrixSymbol('A', i, j) assert mathml(A[0,0],printer = 'presentation') == \ '<msub><mi>A</mi><mfenced close="" open=""><mn>0</mn><mn>0</mn></mfenced></msub>' assert mathml(A[i,j], printer = 'presentation') == \ '<msub><mi>A</mi><mfenced close="" open=""><mi>i</mi><mi>j</mi></mfenced></msub>' assert mathml(A[i*j,0], printer = 'presentation') == \ '<msub><mi>A</mi><mfenced close="" open=""><mrow><mi>i</mi><mo>&InvisibleTimes;</mo><mi>j</mi></mrow><mn>0</mn></mfenced></msub>' def test_print_Vector(): ACS = CoordSys3D('A') assert mathml(Cross(ACS.i, ACS.j*ACS.x*3 + ACS.k), printer='presentation') == \ '<mrow><msub><mover><mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xD7;</mo><mfenced><mrow>'\ '<mfenced><mrow><mn>3</mn><mo>&InvisibleTimes;</mo><msub>'\ '<mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi></msub>'\ '</mrow></mfenced><mo>&InvisibleTimes;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>+</mo><msub><mover>'\ '<mi mathvariant="bold">k</mi><mo>^</mo></mover><mi mathvariant="bold">'\ 'A</mi></msub></mrow></mfenced></mrow>' assert mathml(Cross(ACS.i, ACS.j), printer='presentation') == \ '<mrow><msub><mover><mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xD7;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow>' assert mathml(x*Cross(ACS.i, ACS.j), printer='presentation') == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mfenced><mrow><msub><mover>'\ '<mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xD7;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(Cross(x*ACS.i, ACS.j), printer='presentation') == \ '<mrow><mo>-</mo><mrow><msub><mover><mi mathvariant="bold">j</mi>'\ '<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub>'\ '<mo>&#xD7;</mo><mfenced><mrow><mfenced><mi>x</mi></mfenced>'\ '<mo>&InvisibleTimes;</mo><msub><mover><mi mathvariant="bold">i</mi>'\ '<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub></mrow>'\ '</mfenced></mrow></mrow>' assert mathml(Curl(3*ACS.x*ACS.j), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><mo>&#xD7;</mo><mfenced><mrow><mfenced><mrow>'\ '<mn>3</mn><mo>&InvisibleTimes;</mo><msub>'\ '<mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi></msub>'\ '</mrow></mfenced><mo>&InvisibleTimes;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(Curl(3*x*ACS.x*ACS.j), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><mo>&#xD7;</mo><mfenced><mrow><mfenced><mrow>'\ '<mn>3</mn><mo>&InvisibleTimes;</mo><msub><mi mathvariant="bold">x'\ '</mi><mi mathvariant="bold">A</mi></msub><mo>&InvisibleTimes;</mo>'\ '<mi>x</mi></mrow></mfenced><mo>&InvisibleTimes;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(x*Curl(3*ACS.x*ACS.j), printer='presentation') == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mfenced><mrow><mo>&#x2207;</mo>'\ '<mo>&#xD7;</mo><mfenced><mrow><mfenced><mrow><mn>3</mn>'\ '<mo>&InvisibleTimes;</mo><msub><mi mathvariant="bold">x</mi>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced>'\ '<mo>&InvisibleTimes;</mo><msub><mover><mi mathvariant="bold">j</mi>'\ '<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub></mrow>'\ '</mfenced></mrow></mfenced></mrow>' assert mathml(Curl(3*x*ACS.x*ACS.j + ACS.i), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><mo>&#xD7;</mo><mfenced><mrow><msub><mover>'\ '<mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>+</mo><mfenced><mrow>'\ '<mn>3</mn><mo>&InvisibleTimes;</mo><msub><mi mathvariant="bold">x'\ '</mi><mi mathvariant="bold">A</mi></msub><mo>&InvisibleTimes;</mo>'\ '<mi>x</mi></mrow></mfenced><mo>&InvisibleTimes;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(Divergence(3*ACS.x*ACS.j), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><mo>&#xB7;</mo><mfenced><mrow><mfenced><mrow>'\ '<mn>3</mn><mo>&InvisibleTimes;</mo><msub><mi mathvariant="bold">x'\ '</mi><mi mathvariant="bold">A</mi></msub></mrow></mfenced>'\ '<mo>&InvisibleTimes;</mo><msub><mover><mi mathvariant="bold">j</mi>'\ '<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(x*Divergence(3*ACS.x*ACS.j), printer='presentation') == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mfenced><mrow><mo>&#x2207;</mo>'\ '<mo>&#xB7;</mo><mfenced><mrow><mfenced><mrow><mn>3</mn>'\ '<mo>&InvisibleTimes;</mo><msub><mi mathvariant="bold">x</mi>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced>'\ '<mo>&InvisibleTimes;</mo><msub><mover><mi mathvariant="bold">j</mi>'\ '<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub></mrow>'\ '</mfenced></mrow></mfenced></mrow>' assert mathml(Divergence(3*x*ACS.x*ACS.j + ACS.i), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><mo>&#xB7;</mo><mfenced><mrow><msub><mover>'\ '<mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>+</mo><mfenced><mrow>'\ '<mn>3</mn><mo>&InvisibleTimes;</mo><msub>'\ '<mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi></msub>'\ '<mo>&InvisibleTimes;</mo><mi>x</mi></mrow></mfenced>'\ '<mo>&InvisibleTimes;</mo><msub><mover><mi mathvariant="bold">j</mi>'\ '<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(Dot(ACS.i, ACS.j*ACS.x*3+ACS.k), printer='presentation') == \ '<mrow><msub><mover><mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xB7;</mo><mfenced><mrow>'\ '<mfenced><mrow><mn>3</mn><mo>&InvisibleTimes;</mo><msub>'\ '<mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi></msub>'\ '</mrow></mfenced><mo>&InvisibleTimes;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>+</mo><msub><mover>'\ '<mi mathvariant="bold">k</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(Dot(ACS.i, ACS.j), printer='presentation') == \ '<mrow><msub><mover><mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xB7;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow>' assert mathml(Dot(x*ACS.i, ACS.j), printer='presentation') == \ '<mrow><msub><mover><mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xB7;</mo><mfenced><mrow>'\ '<mfenced><mi>x</mi></mfenced><mo>&InvisibleTimes;</mo><msub><mover>'\ '<mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(x*Dot(ACS.i, ACS.j), printer='presentation') == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mfenced><mrow><msub><mover>'\ '<mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xB7;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(Gradient(ACS.x), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><msub><mi mathvariant="bold">x</mi>'\ '<mi mathvariant="bold">A</mi></msub></mrow>' assert mathml(Gradient(ACS.x + 3*ACS.y), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><mfenced><mrow><msub><mi mathvariant="bold">'\ 'x</mi><mi mathvariant="bold">A</mi></msub><mo>+</mo><mrow><mn>3</mn>'\ '<mo>&InvisibleTimes;</mo><msub><mi mathvariant="bold">y</mi>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mrow></mfenced></mrow>' assert mathml(x*Gradient(ACS.x), printer='presentation') == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mfenced><mrow><mo>&#x2207;</mo>'\ '<msub><mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi>'\ '</msub></mrow></mfenced></mrow>' assert mathml(Gradient(x*ACS.x), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><mfenced><mrow><msub><mi mathvariant="bold">'\ 'x</mi><mi mathvariant="bold">A</mi></msub><mo>&InvisibleTimes;</mo>'\ '<mi>x</mi></mrow></mfenced></mrow>' assert mathml(Cross(ACS.x, ACS.z) + Cross(ACS.z, ACS.x), printer='presentation') == \ '<mover><mi mathvariant="bold">0</mi><mo>^</mo></mover>' assert mathml(Cross(ACS.z, ACS.x), printer='presentation') == \ '<mrow><mo>-</mo><mrow><msub><mi mathvariant="bold">x</mi>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xD7;</mo><msub>'\ '<mi mathvariant="bold">z</mi><mi mathvariant="bold">A</mi></msub></mrow></mrow>' assert mathml(Laplacian(ACS.x), printer='presentation') == \ '<mrow><mo>&#x2206;</mo><msub><mi mathvariant="bold">x</mi>'\ '<mi mathvariant="bold">A</mi></msub></mrow>' assert mathml(Laplacian(ACS.x + 3*ACS.y), printer='presentation') == \ '<mrow><mo>&#x2206;</mo><mfenced><mrow><msub><mi mathvariant="bold">'\ 'x</mi><mi mathvariant="bold">A</mi></msub><mo>+</mo><mrow><mn>3</mn>'\ '<mo>&InvisibleTimes;</mo><msub><mi mathvariant="bold">y</mi>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mrow></mfenced></mrow>' assert mathml(x*Laplacian(ACS.x), printer='presentation') == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mfenced><mrow><mo>&#x2206;</mo>'\ '<msub><mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi>'\ '</msub></mrow></mfenced></mrow>' assert mathml(Laplacian(x*ACS.x), printer='presentation') == \ '<mrow><mo>&#x2206;</mo><mfenced><mrow><msub><mi mathvariant="bold">'\ 'x</mi><mi mathvariant="bold">A</mi></msub><mo>&InvisibleTimes;</mo>'\ '<mi>x</mi></mrow></mfenced></mrow>' def test_print_elliptic_f(): assert mathml(elliptic_f(x, y), printer = 'presentation') == \ '<mrow><mi>&#x1d5a5;</mi><mfenced separators="|"><mi>x</mi><mi>y</mi></mfenced></mrow>' assert mathml(elliptic_f(x/y, y), printer = 'presentation') == \ '<mrow><mi>&#x1d5a5;</mi><mfenced separators="|"><mrow><mfrac><mi>x</mi><mi>y</mi></mfrac></mrow><mi>y</mi></mfenced></mrow>' def test_print_elliptic_e(): assert mathml(elliptic_e(x), printer = 'presentation') == \ '<mrow><mi>&#x1d5a4;</mi><mfenced separators="|"><mi>x</mi></mfenced></mrow>' assert mathml(elliptic_e(x, y), printer = 'presentation') == \ '<mrow><mi>&#x1d5a4;</mi><mfenced separators="|"><mi>x</mi><mi>y</mi></mfenced></mrow>' def test_print_elliptic_pi(): assert mathml(elliptic_pi(x, y), printer = 'presentation') == \ '<mrow><mi>&#x1d6f1;</mi><mfenced separators="|"><mi>x</mi><mi>y</mi></mfenced></mrow>' assert mathml(elliptic_pi(x, y, z), printer = 'presentation') == \ '<mrow><mi>&#x1d6f1;</mi><mfenced separators=";|"><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow>' def test_print_Ei(): assert mathml(Ei(x), printer = 'presentation') == \ '<mrow><mi>Ei</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mathml(Ei(x**y), printer = 'presentation') == \ '<mrow><mi>Ei</mi><mfenced><msup><mi>x</mi><mi>y</mi></msup></mfenced></mrow>' def test_print_expint(): assert mathml(expint(x, y), printer = 'presentation') == \ '<mrow><msub><mo>E</mo><mi>x</mi></msub><mfenced><mi>y</mi></mfenced></mrow>' assert mathml(expint(IndexedBase(x)[1], IndexedBase(x)[2]), printer = 'presentation') == \ '<mrow><msub><mo>E</mo><msub><mi>x</mi><mn>1</mn></msub></msub><mfenced><msub><mi>x</mi><mn>2</mn></msub></mfenced></mrow>' def test_print_jacobi(): assert mathml(jacobi(n, a, b, x), printer = 'presentation') == \ '<mrow><msubsup><mo>P</mo><mi>n</mi><mfenced><mi>a</mi><mi>b</mi></mfenced></msubsup><mfenced><mi>x</mi></mfenced></mrow>' def test_print_gegenbauer(): assert mathml(gegenbauer(n, a, x), printer = 'presentation') == \ '<mrow><msubsup><mo>C</mo><mi>n</mi><mfenced><mi>a</mi></mfenced></msubsup><mfenced><mi>x</mi></mfenced></mrow>' def test_print_chebyshevt(): assert mathml(chebyshevt(n, x), printer = 'presentation') == \ '<mrow><msub><mo>T</mo><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' def test_print_chebyshevu(): assert mathml(chebyshevu(n, x), printer = 'presentation') == \ '<mrow><msub><mo>U</mo><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' def test_print_legendre(): assert mathml(legendre(n, x), printer = 'presentation') == \ '<mrow><msub><mo>P</mo><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' def test_print_assoc_legendre(): assert mathml(assoc_legendre(n, a, x), printer = 'presentation') == \ '<mrow><msubsup><mo>P</mo><mi>n</mi><mfenced><mi>a</mi></mfenced></msubsup><mfenced><mi>x</mi></mfenced></mrow>' def test_print_laguerre(): assert mathml(laguerre(n, x), printer = 'presentation') == \ '<mrow><msub><mo>L</mo><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' def test_print_assoc_laguerre(): assert mathml(assoc_laguerre(n, a, x), printer = 'presentation') == \ '<mrow><msubsup><mo>L</mo><mi>n</mi><mfenced><mi>a</mi></mfenced></msubsup><mfenced><mi>x</mi></mfenced></mrow>' def test_print_hermite(): assert mathml(hermite(n, x), printer = 'presentation') == \ '<mrow><msub><mo>H</mo><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' def test_mathml_SingularityFunction(): assert mathml(SingularityFunction(x, 4, 5), printer='presentation') == \ '<msup><mfenced close="&#10217;" open="&#10216;"><mrow><mi>x</mi>' \ '<mo>-</mo><mn>4</mn></mrow></mfenced><mn>5</mn></msup>' assert mathml(SingularityFunction(x, -3, 4), printer='presentation') == \ '<msup><mfenced close="&#10217;" open="&#10216;"><mrow><mi>x</mi>' \ '<mo>+</mo><mn>3</mn></mrow></mfenced><mn>4</mn></msup>' assert mathml(SingularityFunction(x, 0, 4), printer='presentation') == \ '<msup><mfenced close="&#10217;" open="&#10216;"><mi>x</mi></mfenced>' \ '<mn>4</mn></msup>' assert mathml(SingularityFunction(x, a, n), printer='presentation') == \ '<msup><mfenced close="&#10217;" open="&#10216;"><mrow><mrow>' \ '<mo>-</mo><mi>a</mi></mrow><mo>+</mo><mi>x</mi></mrow></mfenced>' \ '<mi>n</mi></msup>' assert mathml(SingularityFunction(x, 4, -2), printer='presentation') == \ '<msup><mfenced close="&#10217;" open="&#10216;"><mrow><mi>x</mi>' \ '<mo>-</mo><mn>4</mn></mrow></mfenced><mn>-2</mn></msup>' assert mathml(SingularityFunction(x, 4, -1), printer='presentation') == \ '<msup><mfenced close="&#10217;" open="&#10216;"><mrow><mi>x</mi>' \ '<mo>-</mo><mn>4</mn></mrow></mfenced><mn>-1</mn></msup>' def test_mathml_matrix_functions(): from sympy.matrices import Adjoint, Inverse, Transpose X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert mathml(Adjoint(X), printer='presentation') == \ '<msup><mi>X</mi><mo>&#x2020;</mo></msup>' assert mathml(Adjoint(X + Y), printer='presentation') == \ '<msup><mfenced><mrow><mi>X</mi><mo>+</mo><mi>Y</mi></mrow></mfenced><mo>&#x2020;</mo></msup>' assert mathml(Adjoint(X) + Adjoint(Y), printer='presentation') == \ '<mrow><msup><mi>X</mi><mo>&#x2020;</mo></msup><mo>+</mo><msup>' \ '<mi>Y</mi><mo>&#x2020;</mo></msup></mrow>' assert mathml(Adjoint(X*Y), printer='presentation') == \ '<msup><mfenced><mrow><mi>X</mi><mo>&InvisibleTimes;</mo>' \ '<mi>Y</mi></mrow></mfenced><mo>&#x2020;</mo></msup>' assert mathml(Adjoint(Y)*Adjoint(X), printer='presentation') == \ '<mrow><msup><mi>Y</mi><mo>&#x2020;</mo></msup><mo>&InvisibleTimes;' \ '</mo><msup><mi>X</mi><mo>&#x2020;</mo></msup></mrow>' assert mathml(Adjoint(X**2), printer='presentation') == \ '<msup><mfenced><msup><mi>X</mi><mn>2</mn></msup></mfenced><mo>&#x2020;</mo></msup>' assert mathml(Adjoint(X)**2, printer='presentation') == \ '<msup><mfenced><msup><mi>X</mi><mo>&#x2020;</mo></msup></mfenced><mn>2</mn></msup>' assert mathml(Adjoint(Inverse(X)), printer='presentation') == \ '<msup><mfenced><msup><mi>X</mi><mn>-1</mn></msup></mfenced><mo>&#x2020;</mo></msup>' assert mathml(Inverse(Adjoint(X)), printer='presentation') == \ '<msup><mfenced><msup><mi>X</mi><mo>&#x2020;</mo></msup></mfenced><mn>-1</mn></msup>' assert mathml(Adjoint(Transpose(X)), printer='presentation') == \ '<msup><mfenced><msup><mi>X</mi><mo>T</mo></msup></mfenced><mo>&#x2020;</mo></msup>' assert mathml(Transpose(Adjoint(X)), printer='presentation') == \ '<msup><mfenced><msup><mi>X</mi><mo>&#x2020;</mo></msup></mfenced><mo>T</mo></msup>' assert mathml(Transpose(Adjoint(X) + Y), printer='presentation') == \ '<msup><mfenced><mrow><msup><mi>X</mi><mo>&#x2020;</mo></msup>' \ '<mo>+</mo><mi>Y</mi></mrow></mfenced><mo>T</mo></msup>' assert mathml(Transpose(X), printer='presentation') == \ '<msup><mi>X</mi><mo>T</mo></msup>' assert mathml(Transpose(X + Y), printer='presentation') == \ '<msup><mfenced><mrow><mi>X</mi><mo>+</mo><mi>Y</mi></mrow></mfenced><mo>T</mo></msup>' def test_mathml_special_matrices(): from sympy.matrices import Identity, ZeroMatrix, OneMatrix assert mathml(Identity(4), printer='presentation') == '<mi>&#x1D540;</mi>' assert mathml(ZeroMatrix(2, 2), printer='presentation') == '<mn>&#x1D7D8</mn>' assert mathml(OneMatrix(2, 2), printer='presentation') == '<mn>&#x1D7D9</mn>' def test_mathml_piecewise(): from sympy.functions.elementary.piecewise import Piecewise # Content MathML assert mathml(Piecewise((x, x <= 1), (x**2, True))) == \ '<piecewise><piece><ci>x</ci><apply><leq/><ci>x</ci><cn>1</cn></apply></piece><otherwise><apply><power/><ci>x</ci><cn>2</cn></apply></otherwise></piecewise>' raises(ValueError, lambda: mathml(Piecewise((x, x <= 1)))) def test_issue_17857(): assert mathml(Range(-oo, oo), printer='presentation') == \ '<mfenced close="}" open="{"><mi>&#8230;</mi><mn>-1</mn><mn>0</mn><mn>1</mn><mi>&#8230;</mi></mfenced>' assert mathml(Range(oo, -oo, -1), printer='presentation') == \ '<mfenced close="}" open="{"><mi>&#8230;</mi><mn>1</mn><mn>0</mn><mn>-1</mn><mi>&#8230;</mi></mfenced>' def test_float_roundtrip(): x = sympify(0.8975979010256552) y = float(mp.doprint(x).strip('</cn>')) assert x == y
4d202d8062202bf25b63e44c6d0814be7008f3b489a9e24eab370b8c0a1b84a3
from sympy.printing.dot import (purestr, styleof, attrprint, dotnode, dotedges, dotprint) from sympy.core.basic import Basic from sympy.core.expr import Expr from sympy.core.numbers import (Float, Integer) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.printing.repr import srepr from sympy.abc import x def test_purestr(): assert purestr(Symbol('x')) == "Symbol('x')" assert purestr(Basic(S(1), S(2))) == "Basic(Integer(1), Integer(2))" assert purestr(Float(2)) == "Float('2.0', precision=53)" assert purestr(Symbol('x'), with_args=True) == ("Symbol('x')", ()) assert purestr(Basic(S(1), S(2)), with_args=True) == \ ('Basic(Integer(1), Integer(2))', ('Integer(1)', 'Integer(2)')) assert purestr(Float(2), with_args=True) == \ ("Float('2.0', precision=53)", ()) def test_styleof(): styles = [(Basic, {'color': 'blue', 'shape': 'ellipse'}), (Expr, {'color': 'black'})] assert styleof(Basic(S(1)), styles) == {'color': 'blue', 'shape': 'ellipse'} assert styleof(x + 1, styles) == {'color': 'black', 'shape': 'ellipse'} def test_attrprint(): assert attrprint({'color': 'blue', 'shape': 'ellipse'}) == \ '"color"="blue", "shape"="ellipse"' def test_dotnode(): assert dotnode(x, repeat=False) == \ '"Symbol(\'x\')" ["color"="black", "label"="x", "shape"="ellipse"];' assert dotnode(x+2, repeat=False) == \ '"Add(Integer(2), Symbol(\'x\'))" ' \ '["color"="black", "label"="Add", "shape"="ellipse"];', \ dotnode(x+2,repeat=0) assert dotnode(x + x**2, repeat=False) == \ '"Add(Symbol(\'x\'), Pow(Symbol(\'x\'), Integer(2)))" ' \ '["color"="black", "label"="Add", "shape"="ellipse"];' assert dotnode(x + x**2, repeat=True) == \ '"Add(Symbol(\'x\'), Pow(Symbol(\'x\'), Integer(2)))_()" ' \ '["color"="black", "label"="Add", "shape"="ellipse"];' def test_dotedges(): assert sorted(dotedges(x+2, repeat=False)) == [ '"Add(Integer(2), Symbol(\'x\'))" -> "Integer(2)";', '"Add(Integer(2), Symbol(\'x\'))" -> "Symbol(\'x\')";' ] assert sorted(dotedges(x + 2, repeat=True)) == [ '"Add(Integer(2), Symbol(\'x\'))_()" -> "Integer(2)_(0,)";', '"Add(Integer(2), Symbol(\'x\'))_()" -> "Symbol(\'x\')_(1,)";' ] def test_dotprint(): text = dotprint(x+2, repeat=False) assert all(e in text for e in dotedges(x+2, repeat=False)) assert all( n in text for n in [dotnode(expr, repeat=False) for expr in (x, Integer(2), x+2)]) assert 'digraph' in text text = dotprint(x+x**2, repeat=False) assert all(e in text for e in dotedges(x+x**2, repeat=False)) assert all( n in text for n in [dotnode(expr, repeat=False) for expr in (x, Integer(2), x**2)]) assert 'digraph' in text text = dotprint(x+x**2, repeat=True) assert all(e in text for e in dotedges(x+x**2, repeat=True)) assert all( n in text for n in [dotnode(expr, pos=()) for expr in [x + x**2]]) text = dotprint(x**x, repeat=True) assert all(e in text for e in dotedges(x**x, repeat=True)) assert all( n in text for n in [dotnode(x, pos=(0,)), dotnode(x, pos=(1,))]) assert 'digraph' in text def test_dotprint_depth(): text = dotprint(3*x+2, depth=1) assert dotnode(3*x+2) in text assert dotnode(x) not in text text = dotprint(3*x+2) assert "depth" not in text def test_Matrix_and_non_basics(): from sympy.matrices.expressions.matexpr import MatrixSymbol n = Symbol('n') assert dotprint(MatrixSymbol('X', n, n)) == \ """digraph{ # Graph style "ordering"="out" "rankdir"="TD" ######### # Nodes # ######### "MatrixSymbol(Str('X'), Symbol('n'), Symbol('n'))_()" ["color"="black", "label"="MatrixSymbol", "shape"="ellipse"]; "Str('X')_(0,)" ["color"="blue", "label"="X", "shape"="ellipse"]; "Symbol('n')_(1,)" ["color"="black", "label"="n", "shape"="ellipse"]; "Symbol('n')_(2,)" ["color"="black", "label"="n", "shape"="ellipse"]; ######### # Edges # ######### "MatrixSymbol(Str('X'), Symbol('n'), Symbol('n'))_()" -> "Str('X')_(0,)"; "MatrixSymbol(Str('X'), Symbol('n'), Symbol('n'))_()" -> "Symbol('n')_(1,)"; "MatrixSymbol(Str('X'), Symbol('n'), Symbol('n'))_()" -> "Symbol('n')_(2,)"; }""" def test_labelfunc(): text = dotprint(x + 2, labelfunc=srepr) assert "Symbol('x')" in text assert "Integer(2)" in text def test_commutative(): x, y = symbols('x y', commutative=False) assert dotprint(x + y) == dotprint(y + x) assert dotprint(x*y) != dotprint(y*x)
69f449a45703ab15dd7212a90681485f09ee3772566686885242351e4f64effa
# -*- coding: utf-8 -*- from sympy.concrete.products import Product from sympy.concrete.summations import Sum from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.containers import (Dict, Tuple) from sympy.core.function import (Derivative, Function, Lambda, Subs) from sympy.core.mul import Mul from sympy.core import (EulerGamma, GoldenRatio, Catalan) from sympy.core.numbers import (I, Rational, oo, pi) from sympy.core.power import Pow from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import conjugate from sympy.functions.elementary.exponential import LambertW from sympy.functions.special.bessel import (airyai, airyaiprime, airybi, airybiprime) from sympy.functions.special.delta_functions import Heaviside from sympy.functions.special.error_functions import (fresnelc, fresnels) from sympy.functions.special.singularity_functions import SingularityFunction from sympy.functions.special.zeta_functions import dirichlet_eta from sympy.geometry.line import (Ray, Segment) from sympy.integrals.integrals import Integral from sympy.logic.boolalg import (And, Equivalent, ITE, Implies, Nand, Nor, Not, Or, Xor) from sympy.matrices.dense import (Matrix, diag) from sympy.matrices.expressions.slice import MatrixSlice from sympy.matrices.expressions.trace import Trace from sympy.polys.domains.finitefield import FF from sympy.polys.domains.integerring import ZZ from sympy.polys.domains.rationalfield import QQ from sympy.polys.domains.realfield import RR from sympy.polys.orderings import (grlex, ilex) from sympy.polys.polytools import groebner from sympy.polys.rootoftools import (RootSum, rootof) from sympy.series.formal import fps from sympy.series.fourier import fourier_series from sympy.series.limits import Limit from sympy.series.order import O from sympy.series.sequences import (SeqAdd, SeqFormula, SeqMul, SeqPer) from sympy.sets.contains import Contains from sympy.sets.fancysets import Range from sympy.sets.sets import (Complement, FiniteSet, Intersection, Interval, Union) from sympy.codegen.ast import (Assignment, AddAugmentedAssignment, SubAugmentedAssignment, MulAugmentedAssignment, DivAugmentedAssignment, ModAugmentedAssignment) from sympy.core.expr import UnevaluatedExpr from sympy.physics.quantum.trace import Tr from sympy.functions import (Abs, Chi, Ci, Ei, KroneckerDelta, Piecewise, Shi, Si, atan2, beta, binomial, catalan, ceiling, cos, euler, exp, expint, factorial, factorial2, floor, gamma, hyper, log, meijerg, sin, sqrt, subfactorial, tan, uppergamma, lerchphi, elliptic_k, elliptic_f, elliptic_e, elliptic_pi, DiracDelta, bell, bernoulli, fibonacci, tribonacci, lucas, stieltjes, mathieuc, mathieus, mathieusprime, mathieucprime) from sympy.matrices import Adjoint, Inverse, MatrixSymbol, Transpose, KroneckerProduct from sympy.matrices.expressions import hadamard_power from sympy.physics import mechanics from sympy.physics.control.lti import (TransferFunction, Feedback, TransferFunctionMatrix, Series, Parallel, MIMOSeries, MIMOParallel, MIMOFeedback) from sympy.physics.units import joule, degree from sympy.printing.pretty import pprint, pretty as xpretty from sympy.printing.pretty.pretty_symbology import center_accent, is_combining from sympy.sets.conditionset import ConditionSet from sympy.sets import ImageSet, ProductSet from sympy.sets.setexpr import SetExpr from sympy.stats.crv_types import Normal from sympy.stats.symbolic_probability import (Covariance, Expectation, Probability, Variance) from sympy.tensor.array import (ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableDenseNDimArray, MutableSparseNDimArray, tensorproduct) from sympy.tensor.functions import TensorProduct from sympy.tensor.tensor import (TensorIndexType, tensor_indices, TensorHead, TensorElement, tensor_heads) from sympy.testing.pytest import raises, _both_exp_pow from sympy.vector import CoordSys3D, Gradient, Curl, Divergence, Dot, Cross, Laplacian import sympy as sym class lowergamma(sym.lowergamma): pass # testing notation inheritance by a subclass with same name a, b, c, d, x, y, z, k, n, s, p = symbols('a,b,c,d,x,y,z,k,n,s,p') f = Function("f") th = Symbol('theta') ph = Symbol('phi') """ Expressions whose pretty-printing is tested here: (A '#' to the right of an expression indicates that its various acceptable orderings are accounted for by the tests.) BASIC EXPRESSIONS: oo (x**2) 1/x y*x**-2 x**Rational(-5,2) (-2)**x Pow(3, 1, evaluate=False) (x**2 + x + 1) # 1-x # 1-2*x # x/y -x/y (x+2)/y # (1+x)*y #3 -5*x/(x+10) # correct placement of negative sign 1 - Rational(3,2)*(x+1) -(-x + 5)*(-x - 2*sqrt(2) + 5) - (-y + 5)*(-y + 5) # issue 5524 ORDERING: x**2 + x + 1 1 - x 1 - 2*x 2*x**4 + y**2 - x**2 + y**3 RELATIONAL: Eq(x, y) Lt(x, y) Gt(x, y) Le(x, y) Ge(x, y) Ne(x/(y+1), y**2) # RATIONAL NUMBERS: y*x**-2 y**Rational(3,2) * x**Rational(-5,2) sin(x)**3/tan(x)**2 FUNCTIONS (ABS, CONJ, EXP, FUNCTION BRACES, FACTORIAL, FLOOR, CEILING): (2*x + exp(x)) # Abs(x) Abs(x/(x**2+1)) # Abs(1 / (y - Abs(x))) factorial(n) factorial(2*n) subfactorial(n) subfactorial(2*n) factorial(factorial(factorial(n))) factorial(n+1) # conjugate(x) conjugate(f(x+1)) # f(x) f(x, y) f(x/(y+1), y) # f(x**x**x**x**x**x) sin(x)**2 conjugate(a+b*I) conjugate(exp(a+b*I)) conjugate( f(1 + conjugate(f(x))) ) # f(x/(y+1), y) # denom of first arg floor(1 / (y - floor(x))) ceiling(1 / (y - ceiling(x))) SQRT: sqrt(2) 2**Rational(1,3) 2**Rational(1,1000) sqrt(x**2 + 1) (1 + sqrt(5))**Rational(1,3) 2**(1/x) sqrt(2+pi) (2+(1+x**2)/(2+x))**Rational(1,4)+(1+x**Rational(1,1000))/sqrt(3+x**2) DERIVATIVES: Derivative(log(x), x, evaluate=False) Derivative(log(x), x, evaluate=False) + x # Derivative(log(x) + x**2, x, y, evaluate=False) Derivative(2*x*y, y, x, evaluate=False) + x**2 # beta(alpha).diff(alpha) INTEGRALS: Integral(log(x), x) Integral(x**2, x) Integral((sin(x))**2 / (tan(x))**2) Integral(x**(2**x), x) Integral(x**2, (x,1,2)) Integral(x**2, (x,Rational(1,2),10)) Integral(x**2*y**2, x,y) Integral(x**2, (x, None, 1)) Integral(x**2, (x, 1, None)) Integral(sin(th)/cos(ph), (th,0,pi), (ph, 0, 2*pi)) MATRICES: Matrix([[x**2+1, 1], [y, x+y]]) # Matrix([[x/y, y, th], [0, exp(I*k*ph), 1]]) PIECEWISE: Piecewise((x,x<1),(x**2,True)) ITE: ITE(x, y, z) SEQUENCES (TUPLES, LISTS, DICTIONARIES): () [] {} (1/x,) [x**2, 1/x, x, y, sin(th)**2/cos(ph)**2] (x**2, 1/x, x, y, sin(th)**2/cos(ph)**2) {x: sin(x)} {1/x: 1/y, x: sin(x)**2} # [x**2] (x**2,) {x**2: 1} LIMITS: Limit(x, x, oo) Limit(x**2, x, 0) Limit(1/x, x, 0) Limit(sin(x)/x, x, 0) UNITS: joule => kg*m**2/s SUBS: Subs(f(x), x, ph**2) Subs(f(x).diff(x), x, 0) Subs(f(x).diff(x)/y, (x, y), (0, Rational(1, 2))) ORDER: O(1) O(1/x) O(x**2 + y**2) """ def pretty(expr, order=None): """ASCII pretty-printing""" return xpretty(expr, order=order, use_unicode=False, wrap_line=False) def upretty(expr, order=None): """Unicode pretty-printing""" return xpretty(expr, order=order, use_unicode=True, wrap_line=False) def test_pretty_ascii_str(): assert pretty( 'xxx' ) == 'xxx' assert pretty( "xxx" ) == 'xxx' assert pretty( 'xxx\'xxx' ) == 'xxx\'xxx' assert pretty( 'xxx"xxx' ) == 'xxx\"xxx' assert pretty( 'xxx\"xxx' ) == 'xxx\"xxx' assert pretty( "xxx'xxx" ) == 'xxx\'xxx' assert pretty( "xxx\'xxx" ) == 'xxx\'xxx' assert pretty( "xxx\"xxx" ) == 'xxx\"xxx' assert pretty( "xxx\"xxx\'xxx" ) == 'xxx"xxx\'xxx' assert pretty( "xxx\nxxx" ) == 'xxx\nxxx' def test_pretty_unicode_str(): assert pretty( 'xxx' ) == 'xxx' assert pretty( 'xxx' ) == 'xxx' assert pretty( 'xxx\'xxx' ) == 'xxx\'xxx' assert pretty( 'xxx"xxx' ) == 'xxx\"xxx' assert pretty( 'xxx\"xxx' ) == 'xxx\"xxx' assert pretty( "xxx'xxx" ) == 'xxx\'xxx' assert pretty( "xxx\'xxx" ) == 'xxx\'xxx' assert pretty( "xxx\"xxx" ) == 'xxx\"xxx' assert pretty( "xxx\"xxx\'xxx" ) == 'xxx"xxx\'xxx' assert pretty( "xxx\nxxx" ) == 'xxx\nxxx' def test_upretty_greek(): assert upretty( oo ) == '∞' assert upretty( Symbol('alpha^+_1') ) == 'α⁺₁' assert upretty( Symbol('beta') ) == 'β' assert upretty(Symbol('lambda')) == 'λ' def test_upretty_multiindex(): assert upretty( Symbol('beta12') ) == 'β₁₂' assert upretty( Symbol('Y00') ) == 'Y₀₀' assert upretty( Symbol('Y_00') ) == 'Y₀₀' assert upretty( Symbol('F^+-') ) == 'F⁺⁻' def test_upretty_sub_super(): assert upretty( Symbol('beta_1_2') ) == 'β₁ ₂' assert upretty( Symbol('beta^1^2') ) == 'β¹ ²' assert upretty( Symbol('beta_1^2') ) == 'β²₁' assert upretty( Symbol('beta_10_20') ) == 'β₁₀ ₂₀' assert upretty( Symbol('beta_ax_gamma^i') ) == 'βⁱₐₓ ᵧ' assert upretty( Symbol("F^1^2_3_4") ) == 'F¹ ²₃ ₄' assert upretty( Symbol("F_1_2^3^4") ) == 'F³ ⁴₁ ₂' assert upretty( Symbol("F_1_2_3_4") ) == 'F₁ ₂ ₃ ₄' assert upretty( Symbol("F^1^2^3^4") ) == 'F¹ ² ³ ⁴' def test_upretty_subs_missing_in_24(): assert upretty( Symbol('F_beta') ) == 'Fᵦ' assert upretty( Symbol('F_gamma') ) == 'Fᵧ' assert upretty( Symbol('F_rho') ) == 'Fᵨ' assert upretty( Symbol('F_phi') ) == 'Fᵩ' assert upretty( Symbol('F_chi') ) == 'Fᵪ' assert upretty( Symbol('F_a') ) == 'Fₐ' assert upretty( Symbol('F_e') ) == 'Fₑ' assert upretty( Symbol('F_i') ) == 'Fᵢ' assert upretty( Symbol('F_o') ) == 'Fₒ' assert upretty( Symbol('F_u') ) == 'Fᵤ' assert upretty( Symbol('F_r') ) == 'Fᵣ' assert upretty( Symbol('F_v') ) == 'Fᵥ' assert upretty( Symbol('F_x') ) == 'Fₓ' def test_missing_in_2X_issue_9047(): assert upretty( Symbol('F_h') ) == 'Fₕ' assert upretty( Symbol('F_k') ) == 'Fₖ' assert upretty( Symbol('F_l') ) == 'Fₗ' assert upretty( Symbol('F_m') ) == 'Fₘ' assert upretty( Symbol('F_n') ) == 'Fₙ' assert upretty( Symbol('F_p') ) == 'Fₚ' assert upretty( Symbol('F_s') ) == 'Fₛ' assert upretty( Symbol('F_t') ) == 'Fₜ' def test_upretty_modifiers(): # Accents assert upretty( Symbol('Fmathring') ) == 'F̊' assert upretty( Symbol('Fddddot') ) == 'F⃜' assert upretty( Symbol('Fdddot') ) == 'F⃛' assert upretty( Symbol('Fddot') ) == 'F̈' assert upretty( Symbol('Fdot') ) == 'Ḟ' assert upretty( Symbol('Fcheck') ) == 'F̌' assert upretty( Symbol('Fbreve') ) == 'F̆' assert upretty( Symbol('Facute') ) == 'F́' assert upretty( Symbol('Fgrave') ) == 'F̀' assert upretty( Symbol('Ftilde') ) == 'F̃' assert upretty( Symbol('Fhat') ) == 'F̂' assert upretty( Symbol('Fbar') ) == 'F̅' assert upretty( Symbol('Fvec') ) == 'F⃗' assert upretty( Symbol('Fprime') ) == 'F′' assert upretty( Symbol('Fprm') ) == 'F′' # No faces are actually implemented, but test to make sure the modifiers are stripped assert upretty( Symbol('Fbold') ) == 'Fbold' assert upretty( Symbol('Fbm') ) == 'Fbm' assert upretty( Symbol('Fcal') ) == 'Fcal' assert upretty( Symbol('Fscr') ) == 'Fscr' assert upretty( Symbol('Ffrak') ) == 'Ffrak' # Brackets assert upretty( Symbol('Fnorm') ) == '‖F‖' assert upretty( Symbol('Favg') ) == '⟨F⟩' assert upretty( Symbol('Fabs') ) == '|F|' assert upretty( Symbol('Fmag') ) == '|F|' # Combinations assert upretty( Symbol('xvecdot') ) == 'x⃗̇' assert upretty( Symbol('xDotVec') ) == 'ẋ⃗' assert upretty( Symbol('xHATNorm') ) == '‖x̂‖' assert upretty( Symbol('xMathring_yCheckPRM__zbreveAbs') ) == 'x̊_y̌′__|z̆|' assert upretty( Symbol('alphadothat_nVECDOT__tTildePrime') ) == 'α̇̂_n⃗̇__t̃′' assert upretty( Symbol('x_dot') ) == 'x_dot' assert upretty( Symbol('x__dot') ) == 'x__dot' def test_pretty_Cycle(): from sympy.combinatorics.permutations import Cycle assert pretty(Cycle(1, 2)) == '(1 2)' assert pretty(Cycle(2)) == '(2)' assert pretty(Cycle(1, 3)(4, 5)) == '(1 3)(4 5)' assert pretty(Cycle()) == '()' def test_pretty_Permutation(): from sympy.combinatorics.permutations import Permutation p1 = Permutation(1, 2)(3, 4) assert xpretty(p1, perm_cyclic=True, use_unicode=True) == "(1 2)(3 4)" assert xpretty(p1, perm_cyclic=True, use_unicode=False) == "(1 2)(3 4)" assert xpretty(p1, perm_cyclic=False, use_unicode=True) == \ '⎛0 1 2 3 4⎞\n'\ '⎝0 2 1 4 3⎠' assert xpretty(p1, perm_cyclic=False, use_unicode=False) == \ "/0 1 2 3 4\\\n"\ "\\0 2 1 4 3/" def test_pretty_basic(): assert pretty( -Rational(1)/2 ) == '-1/2' assert pretty( -Rational(13)/22 ) == \ """\ -13 \n\ ----\n\ 22 \ """ expr = oo ascii_str = \ """\ oo\ """ ucode_str = \ """\ ∞\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (x**2) ascii_str = \ """\ 2\n\ x \ """ ucode_str = \ """\ 2\n\ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 1/x ascii_str = \ """\ 1\n\ -\n\ x\ """ ucode_str = \ """\ 1\n\ ─\n\ x\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str # not the same as 1/x expr = x**-1.0 ascii_str = \ """\ -1.0\n\ x \ """ ucode_str = \ """\ -1.0\n\ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str # see issue #2860 expr = Pow(S(2), -1.0, evaluate=False) ascii_str = \ """\ -1.0\n\ 2 \ """ ucode_str = \ """\ -1.0\n\ 2 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = y*x**-2 ascii_str = \ """\ y \n\ --\n\ 2\n\ x \ """ ucode_str = \ """\ y \n\ ──\n\ 2\n\ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str #see issue #14033 expr = x**Rational(1, 3) ascii_str = \ """\ 1/3\n\ x \ """ ucode_str = \ """\ 1/3\n\ x \ """ assert xpretty(expr, use_unicode=False, wrap_line=False,\ root_notation = False) == ascii_str assert xpretty(expr, use_unicode=True, wrap_line=False,\ root_notation = False) == ucode_str expr = x**Rational(-5, 2) ascii_str = \ """\ 1 \n\ ----\n\ 5/2\n\ x \ """ ucode_str = \ """\ 1 \n\ ────\n\ 5/2\n\ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (-2)**x ascii_str = \ """\ x\n\ (-2) \ """ ucode_str = \ """\ x\n\ (-2) \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str # See issue 4923 expr = Pow(3, 1, evaluate=False) ascii_str = \ """\ 1\n\ 3 \ """ ucode_str = \ """\ 1\n\ 3 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (x**2 + x + 1) ascii_str_1 = \ """\ 2\n\ 1 + x + x \ """ ascii_str_2 = \ """\ 2 \n\ x + x + 1\ """ ascii_str_3 = \ """\ 2 \n\ x + 1 + x\ """ ucode_str_1 = \ """\ 2\n\ 1 + x + x \ """ ucode_str_2 = \ """\ 2 \n\ x + x + 1\ """ ucode_str_3 = \ """\ 2 \n\ x + 1 + x\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2, ascii_str_3] assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3] expr = 1 - x ascii_str_1 = \ """\ 1 - x\ """ ascii_str_2 = \ """\ -x + 1\ """ ucode_str_1 = \ """\ 1 - x\ """ ucode_str_2 = \ """\ -x + 1\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = 1 - 2*x ascii_str_1 = \ """\ 1 - 2*x\ """ ascii_str_2 = \ """\ -2*x + 1\ """ ucode_str_1 = \ """\ 1 - 2⋅x\ """ ucode_str_2 = \ """\ -2⋅x + 1\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = x/y ascii_str = \ """\ x\n\ -\n\ y\ """ ucode_str = \ """\ x\n\ ─\n\ y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -x/y ascii_str = \ """\ -x \n\ ---\n\ y \ """ ucode_str = \ """\ -x \n\ ───\n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (x + 2)/y ascii_str_1 = \ """\ 2 + x\n\ -----\n\ y \ """ ascii_str_2 = \ """\ x + 2\n\ -----\n\ y \ """ ucode_str_1 = \ """\ 2 + x\n\ ─────\n\ y \ """ ucode_str_2 = \ """\ x + 2\n\ ─────\n\ y \ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = (1 + x)*y ascii_str_1 = \ """\ y*(1 + x)\ """ ascii_str_2 = \ """\ (1 + x)*y\ """ ascii_str_3 = \ """\ y*(x + 1)\ """ ucode_str_1 = \ """\ y⋅(1 + x)\ """ ucode_str_2 = \ """\ (1 + x)⋅y\ """ ucode_str_3 = \ """\ y⋅(x + 1)\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2, ascii_str_3] assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3] # Test for correct placement of the negative sign expr = -5*x/(x + 10) ascii_str_1 = \ """\ -5*x \n\ ------\n\ 10 + x\ """ ascii_str_2 = \ """\ -5*x \n\ ------\n\ x + 10\ """ ucode_str_1 = \ """\ -5⋅x \n\ ──────\n\ 10 + x\ """ ucode_str_2 = \ """\ -5⋅x \n\ ──────\n\ x + 10\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = -S.Half - 3*x ascii_str = \ """\ -3*x - 1/2\ """ ucode_str = \ """\ -3⋅x - 1/2\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = S.Half - 3*x ascii_str = \ """\ 1/2 - 3*x\ """ ucode_str = \ """\ 1/2 - 3⋅x\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -S.Half - 3*x/2 ascii_str = \ """\ 3*x 1\n\ - --- - -\n\ 2 2\ """ ucode_str = \ """\ 3⋅x 1\n\ - ─── - ─\n\ 2 2\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = S.Half - 3*x/2 ascii_str = \ """\ 1 3*x\n\ - - ---\n\ 2 2 \ """ ucode_str = \ """\ 1 3⋅x\n\ ─ - ───\n\ 2 2 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_negative_fractions(): expr = -x/y ascii_str =\ """\ -x \n\ ---\n\ y \ """ ucode_str =\ """\ -x \n\ ───\n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -x*z/y ascii_str =\ """\ -x*z \n\ -----\n\ y \ """ ucode_str =\ """\ -x⋅z \n\ ─────\n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = x**2/y ascii_str =\ """\ 2\n\ x \n\ --\n\ y \ """ ucode_str =\ """\ 2\n\ x \n\ ──\n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -x**2/y ascii_str =\ """\ 2 \n\ -x \n\ ----\n\ y \ """ ucode_str =\ """\ 2 \n\ -x \n\ ────\n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -x/(y*z) ascii_str =\ """\ -x \n\ ---\n\ y*z\ """ ucode_str =\ """\ -x \n\ ───\n\ y⋅z\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -a/y**2 ascii_str =\ """\ -a \n\ ---\n\ 2\n\ y \ """ ucode_str =\ """\ -a \n\ ───\n\ 2\n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = y**(-a/b) ascii_str =\ """\ -a \n\ ---\n\ b \n\ y \ """ ucode_str =\ """\ -a \n\ ───\n\ b \n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -1/y**2 ascii_str =\ """\ -1 \n\ ---\n\ 2\n\ y \ """ ucode_str =\ """\ -1 \n\ ───\n\ 2\n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -10/b**2 ascii_str =\ """\ -10 \n\ ----\n\ 2 \n\ b \ """ ucode_str =\ """\ -10 \n\ ────\n\ 2 \n\ b \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Rational(-200, 37) ascii_str =\ """\ -200 \n\ -----\n\ 37 \ """ ucode_str =\ """\ -200 \n\ ─────\n\ 37 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_Mul(): expr = Mul(0, 1, evaluate=False) assert pretty(expr) == "0*1" assert upretty(expr) == "0⋅1" expr = Mul(1, 0, evaluate=False) assert pretty(expr) == "1*0" assert upretty(expr) == "1⋅0" expr = Mul(1, 1, evaluate=False) assert pretty(expr) == "1*1" assert upretty(expr) == "1⋅1" expr = Mul(1, 1, 1, evaluate=False) assert pretty(expr) == "1*1*1" assert upretty(expr) == "1⋅1⋅1" expr = Mul(1, 2, evaluate=False) assert pretty(expr) == "1*2" assert upretty(expr) == "1⋅2" expr = Add(0, 1, evaluate=False) assert pretty(expr) == "0 + 1" assert upretty(expr) == "0 + 1" expr = Mul(1, 1, 2, evaluate=False) assert pretty(expr) == "1*1*2" assert upretty(expr) == "1⋅1⋅2" expr = Add(0, 0, 1, evaluate=False) assert pretty(expr) == "0 + 0 + 1" assert upretty(expr) == "0 + 0 + 1" expr = Mul(1, -1, evaluate=False) assert pretty(expr) == "1*-1" assert upretty(expr) == "1⋅-1" expr = Mul(1.0, x, evaluate=False) assert pretty(expr) == "1.0*x" assert upretty(expr) == "1.0⋅x" expr = Mul(1, 1, 2, 3, x, evaluate=False) assert pretty(expr) == "1*1*2*3*x" assert upretty(expr) == "1⋅1⋅2⋅3⋅x" expr = Mul(-1, 1, evaluate=False) assert pretty(expr) == "-1*1" assert upretty(expr) == "-1⋅1" expr = Mul(4, 3, 2, 1, 0, y, x, evaluate=False) assert pretty(expr) == "4*3*2*1*0*y*x" assert upretty(expr) == "4⋅3⋅2⋅1⋅0⋅y⋅x" expr = Mul(4, 3, 2, 1+z, 0, y, x, evaluate=False) assert pretty(expr) == "4*3*2*(z + 1)*0*y*x" assert upretty(expr) == "4⋅3⋅2⋅(z + 1)⋅0⋅y⋅x" expr = Mul(Rational(2, 3), Rational(5, 7), evaluate=False) assert pretty(expr) == "2/3*5/7" assert upretty(expr) == "2/3⋅5/7" expr = Mul(x + y, Rational(1, 2), evaluate=False) assert pretty(expr) == "(x + y)*1/2" assert upretty(expr) == "(x + y)⋅1/2" expr = Mul(Rational(1, 2), x + y, evaluate=False) assert pretty(expr) == "x + y\n-----\n 2 " assert upretty(expr) == "x + y\n─────\n 2 " expr = Mul(S.One, x + y, evaluate=False) assert pretty(expr) == "1*(x + y)" assert upretty(expr) == "1⋅(x + y)" expr = Mul(x - y, S.One, evaluate=False) assert pretty(expr) == "(x - y)*1" assert upretty(expr) == "(x - y)⋅1" expr = Mul(Rational(1, 2), x - y, S.One, x + y, evaluate=False) assert pretty(expr) == "1/2*(x - y)*1*(x + y)" assert upretty(expr) == "1/2⋅(x - y)⋅1⋅(x + y)" expr = Mul(x + y, Rational(3, 4), S.One, y - z, evaluate=False) assert pretty(expr) == "(x + y)*3/4*1*(y - z)" assert upretty(expr) == "(x + y)⋅3/4⋅1⋅(y - z)" expr = Mul(x + y, Rational(1, 1), Rational(3, 4), Rational(5, 6),evaluate=False) assert pretty(expr) == "(x + y)*1*3/4*5/6" assert upretty(expr) == "(x + y)⋅1⋅3/4⋅5/6" expr = Mul(Rational(3, 4), x + y, S.One, y - z, evaluate=False) assert pretty(expr) == "3/4*(x + y)*1*(y - z)" assert upretty(expr) == "3/4⋅(x + y)⋅1⋅(y - z)" def test_issue_5524(): assert pretty(-(-x + 5)*(-x - 2*sqrt(2) + 5) - (-y + 5)*(-y + 5)) == \ """\ 2 / ___ \\\n\ - (5 - y) + (x - 5)*\\-x - 2*\\/ 2 + 5/\ """ assert upretty(-(-x + 5)*(-x - 2*sqrt(2) + 5) - (-y + 5)*(-y + 5)) == \ """\ 2 \n\ - (5 - y) + (x - 5)⋅(-x - 2⋅√2 + 5)\ """ def test_pretty_ordering(): assert pretty(x**2 + x + 1, order='lex') == \ """\ 2 \n\ x + x + 1\ """ assert pretty(x**2 + x + 1, order='rev-lex') == \ """\ 2\n\ 1 + x + x \ """ assert pretty(1 - x, order='lex') == '-x + 1' assert pretty(1 - x, order='rev-lex') == '1 - x' assert pretty(1 - 2*x, order='lex') == '-2*x + 1' assert pretty(1 - 2*x, order='rev-lex') == '1 - 2*x' f = 2*x**4 + y**2 - x**2 + y**3 assert pretty(f, order=None) == \ """\ 4 2 3 2\n\ 2*x - x + y + y \ """ assert pretty(f, order='lex') == \ """\ 4 2 3 2\n\ 2*x - x + y + y \ """ assert pretty(f, order='rev-lex') == \ """\ 2 3 2 4\n\ y + y - x + 2*x \ """ expr = x - x**3/6 + x**5/120 + O(x**6) ascii_str = \ """\ 3 5 \n\ x x / 6\\\n\ x - -- + --- + O\\x /\n\ 6 120 \ """ ucode_str = \ """\ 3 5 \n\ x x ⎛ 6⎞\n\ x - ── + ─── + O⎝x ⎠\n\ 6 120 \ """ assert pretty(expr, order=None) == ascii_str assert upretty(expr, order=None) == ucode_str assert pretty(expr, order='lex') == ascii_str assert upretty(expr, order='lex') == ucode_str assert pretty(expr, order='rev-lex') == ascii_str assert upretty(expr, order='rev-lex') == ucode_str def test_EulerGamma(): assert pretty(EulerGamma) == str(EulerGamma) == "EulerGamma" assert upretty(EulerGamma) == "γ" def test_GoldenRatio(): assert pretty(GoldenRatio) == str(GoldenRatio) == "GoldenRatio" assert upretty(GoldenRatio) == "φ" def test_Catalan(): assert pretty(Catalan) == upretty(Catalan) == "G" def test_pretty_relational(): expr = Eq(x, y) ascii_str = \ """\ x = y\ """ ucode_str = \ """\ x = y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Lt(x, y) ascii_str = \ """\ x < y\ """ ucode_str = \ """\ x < y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Gt(x, y) ascii_str = \ """\ x > y\ """ ucode_str = \ """\ x > y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Le(x, y) ascii_str = \ """\ x <= y\ """ ucode_str = \ """\ x ≤ y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Ge(x, y) ascii_str = \ """\ x >= y\ """ ucode_str = \ """\ x ≥ y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Ne(x/(y + 1), y**2) ascii_str_1 = \ """\ x 2\n\ ----- != y \n\ 1 + y \ """ ascii_str_2 = \ """\ x 2\n\ ----- != y \n\ y + 1 \ """ ucode_str_1 = \ """\ x 2\n\ ───── ≠ y \n\ 1 + y \ """ ucode_str_2 = \ """\ x 2\n\ ───── ≠ y \n\ y + 1 \ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] def test_Assignment(): expr = Assignment(x, y) ascii_str = \ """\ x := y\ """ ucode_str = \ """\ x := y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_AugmentedAssignment(): expr = AddAugmentedAssignment(x, y) ascii_str = \ """\ x += y\ """ ucode_str = \ """\ x += y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = SubAugmentedAssignment(x, y) ascii_str = \ """\ x -= y\ """ ucode_str = \ """\ x -= y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = MulAugmentedAssignment(x, y) ascii_str = \ """\ x *= y\ """ ucode_str = \ """\ x *= y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = DivAugmentedAssignment(x, y) ascii_str = \ """\ x /= y\ """ ucode_str = \ """\ x /= y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = ModAugmentedAssignment(x, y) ascii_str = \ """\ x %= y\ """ ucode_str = \ """\ x %= y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_rational(): expr = y*x**-2 ascii_str = \ """\ y \n\ --\n\ 2\n\ x \ """ ucode_str = \ """\ y \n\ ──\n\ 2\n\ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = y**Rational(3, 2) * x**Rational(-5, 2) ascii_str = \ """\ 3/2\n\ y \n\ ----\n\ 5/2\n\ x \ """ ucode_str = \ """\ 3/2\n\ y \n\ ────\n\ 5/2\n\ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = sin(x)**3/tan(x)**2 ascii_str = \ """\ 3 \n\ sin (x)\n\ -------\n\ 2 \n\ tan (x)\ """ ucode_str = \ """\ 3 \n\ sin (x)\n\ ───────\n\ 2 \n\ tan (x)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str @_both_exp_pow def test_pretty_functions(): """Tests for Abs, conjugate, exp, function braces, and factorial.""" expr = (2*x + exp(x)) ascii_str_1 = \ """\ x\n\ 2*x + e \ """ ascii_str_2 = \ """\ x \n\ e + 2*x\ """ ucode_str_1 = \ """\ x\n\ 2⋅x + ℯ \ """ ucode_str_2 = \ """\ x \n\ ℯ + 2⋅x\ """ ucode_str_3 = \ """\ x \n\ ℯ + 2⋅x\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3] expr = Abs(x) ascii_str = \ """\ |x|\ """ ucode_str = \ """\ │x│\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Abs(x/(x**2 + 1)) ascii_str_1 = \ """\ | x |\n\ |------|\n\ | 2|\n\ |1 + x |\ """ ascii_str_2 = \ """\ | x |\n\ |------|\n\ | 2 |\n\ |x + 1|\ """ ucode_str_1 = \ """\ │ x │\n\ │──────│\n\ │ 2│\n\ │1 + x │\ """ ucode_str_2 = \ """\ │ x │\n\ │──────│\n\ │ 2 │\n\ │x + 1│\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = Abs(1 / (y - Abs(x))) ascii_str = \ """\ 1 \n\ ---------\n\ |y - |x||\ """ ucode_str = \ """\ 1 \n\ ─────────\n\ │y - │x││\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str n = Symbol('n', integer=True) expr = factorial(n) ascii_str = \ """\ n!\ """ ucode_str = \ """\ n!\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial(2*n) ascii_str = \ """\ (2*n)!\ """ ucode_str = \ """\ (2⋅n)!\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial(factorial(factorial(n))) ascii_str = \ """\ ((n!)!)!\ """ ucode_str = \ """\ ((n!)!)!\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial(n + 1) ascii_str_1 = \ """\ (1 + n)!\ """ ascii_str_2 = \ """\ (n + 1)!\ """ ucode_str_1 = \ """\ (1 + n)!\ """ ucode_str_2 = \ """\ (n + 1)!\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = subfactorial(n) ascii_str = \ """\ !n\ """ ucode_str = \ """\ !n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = subfactorial(2*n) ascii_str = \ """\ !(2*n)\ """ ucode_str = \ """\ !(2⋅n)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str n = Symbol('n', integer=True) expr = factorial2(n) ascii_str = \ """\ n!!\ """ ucode_str = \ """\ n!!\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial2(2*n) ascii_str = \ """\ (2*n)!!\ """ ucode_str = \ """\ (2⋅n)!!\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial2(factorial2(factorial2(n))) ascii_str = \ """\ ((n!!)!!)!!\ """ ucode_str = \ """\ ((n!!)!!)!!\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial2(n + 1) ascii_str_1 = \ """\ (1 + n)!!\ """ ascii_str_2 = \ """\ (n + 1)!!\ """ ucode_str_1 = \ """\ (1 + n)!!\ """ ucode_str_2 = \ """\ (n + 1)!!\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = 2*binomial(n, k) ascii_str = \ """\ /n\\\n\ 2*| |\n\ \\k/\ """ ucode_str = \ """\ ⎛n⎞\n\ 2⋅⎜ ⎟\n\ ⎝k⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2*binomial(2*n, k) ascii_str = \ """\ /2*n\\\n\ 2*| |\n\ \\ k /\ """ ucode_str = \ """\ ⎛2⋅n⎞\n\ 2⋅⎜ ⎟\n\ ⎝ k ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2*binomial(n**2, k) ascii_str = \ """\ / 2\\\n\ |n |\n\ 2*| |\n\ \\k /\ """ ucode_str = \ """\ ⎛ 2⎞\n\ ⎜n ⎟\n\ 2⋅⎜ ⎟\n\ ⎝k ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = catalan(n) ascii_str = \ """\ C \n\ n\ """ ucode_str = \ """\ C \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = catalan(n) ascii_str = \ """\ C \n\ n\ """ ucode_str = \ """\ C \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = bell(n) ascii_str = \ """\ B \n\ n\ """ ucode_str = \ """\ B \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = bernoulli(n) ascii_str = \ """\ B \n\ n\ """ ucode_str = \ """\ B \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = bernoulli(n, x) ascii_str = \ """\ B (x)\n\ n \ """ ucode_str = \ """\ B (x)\n\ n \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = fibonacci(n) ascii_str = \ """\ F \n\ n\ """ ucode_str = \ """\ F \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = lucas(n) ascii_str = \ """\ L \n\ n\ """ ucode_str = \ """\ L \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = tribonacci(n) ascii_str = \ """\ T \n\ n\ """ ucode_str = \ """\ T \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = stieltjes(n) ascii_str = \ """\ stieltjes \n\ n\ """ ucode_str = \ """\ γ \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = stieltjes(n, x) ascii_str = \ """\ stieltjes (x)\n\ n \ """ ucode_str = \ """\ γ (x)\n\ n \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = mathieuc(x, y, z) ascii_str = 'C(x, y, z)' ucode_str = 'C(x, y, z)' assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = mathieus(x, y, z) ascii_str = 'S(x, y, z)' ucode_str = 'S(x, y, z)' assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = mathieucprime(x, y, z) ascii_str = "C'(x, y, z)" ucode_str = "C'(x, y, z)" assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = mathieusprime(x, y, z) ascii_str = "S'(x, y, z)" ucode_str = "S'(x, y, z)" assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = conjugate(x) ascii_str = \ """\ _\n\ x\ """ ucode_str = \ """\ _\n\ x\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str f = Function('f') expr = conjugate(f(x + 1)) ascii_str_1 = \ """\ ________\n\ f(1 + x)\ """ ascii_str_2 = \ """\ ________\n\ f(x + 1)\ """ ucode_str_1 = \ """\ ________\n\ f(1 + x)\ """ ucode_str_2 = \ """\ ________\n\ f(x + 1)\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = f(x) ascii_str = \ """\ f(x)\ """ ucode_str = \ """\ f(x)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = f(x, y) ascii_str = \ """\ f(x, y)\ """ ucode_str = \ """\ f(x, y)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = f(x/(y + 1), y) ascii_str_1 = \ """\ / x \\\n\ f|-----, y|\n\ \\1 + y /\ """ ascii_str_2 = \ """\ / x \\\n\ f|-----, y|\n\ \\y + 1 /\ """ ucode_str_1 = \ """\ ⎛ x ⎞\n\ f⎜─────, y⎟\n\ ⎝1 + y ⎠\ """ ucode_str_2 = \ """\ ⎛ x ⎞\n\ f⎜─────, y⎟\n\ ⎝y + 1 ⎠\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = f(x**x**x**x**x**x) ascii_str = \ """\ / / / / / x\\\\\\\\\\ | | | | \\x /|||| | | | \\x /||| | | \\x /|| | \\x /| f\\x /\ """ ucode_str = \ """\ ⎛ ⎛ ⎛ ⎛ ⎛ x⎞⎞⎞⎞⎞ ⎜ ⎜ ⎜ ⎜ ⎝x ⎠⎟⎟⎟⎟ ⎜ ⎜ ⎜ ⎝x ⎠⎟⎟⎟ ⎜ ⎜ ⎝x ⎠⎟⎟ ⎜ ⎝x ⎠⎟ f⎝x ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = sin(x)**2 ascii_str = \ """\ 2 \n\ sin (x)\ """ ucode_str = \ """\ 2 \n\ sin (x)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = conjugate(a + b*I) ascii_str = \ """\ _ _\n\ a - I*b\ """ ucode_str = \ """\ _ _\n\ a - ⅈ⋅b\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = conjugate(exp(a + b*I)) ascii_str = \ """\ _ _\n\ a - I*b\n\ e \ """ ucode_str = \ """\ _ _\n\ a - ⅈ⋅b\n\ ℯ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = conjugate( f(1 + conjugate(f(x))) ) ascii_str_1 = \ """\ ___________\n\ / ____\\\n\ f\\1 + f(x)/\ """ ascii_str_2 = \ """\ ___________\n\ /____ \\\n\ f\\f(x) + 1/\ """ ucode_str_1 = \ """\ ___________\n\ ⎛ ____⎞\n\ f⎝1 + f(x)⎠\ """ ucode_str_2 = \ """\ ___________\n\ ⎛____ ⎞\n\ f⎝f(x) + 1⎠\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = f(x/(y + 1), y) ascii_str_1 = \ """\ / x \\\n\ f|-----, y|\n\ \\1 + y /\ """ ascii_str_2 = \ """\ / x \\\n\ f|-----, y|\n\ \\y + 1 /\ """ ucode_str_1 = \ """\ ⎛ x ⎞\n\ f⎜─────, y⎟\n\ ⎝1 + y ⎠\ """ ucode_str_2 = \ """\ ⎛ x ⎞\n\ f⎜─────, y⎟\n\ ⎝y + 1 ⎠\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = floor(1 / (y - floor(x))) ascii_str = \ """\ / 1 \\\n\ floor|------------|\n\ \\y - floor(x)/\ """ ucode_str = \ """\ ⎢ 1 ⎥\n\ ⎢───────⎥\n\ ⎣y - ⌊x⌋⎦\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = ceiling(1 / (y - ceiling(x))) ascii_str = \ """\ / 1 \\\n\ ceiling|--------------|\n\ \\y - ceiling(x)/\ """ ucode_str = \ """\ ⎡ 1 ⎤\n\ ⎢───────⎥\n\ ⎢y - ⌈x⌉⎥\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = euler(n) ascii_str = \ """\ E \n\ n\ """ ucode_str = \ """\ E \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = euler(1/(1 + 1/(1 + 1/n))) ascii_str = \ """\ E \n\ 1 \n\ ---------\n\ 1 \n\ 1 + -----\n\ 1\n\ 1 + -\n\ n\ """ ucode_str = \ """\ E \n\ 1 \n\ ─────────\n\ 1 \n\ 1 + ─────\n\ 1\n\ 1 + ─\n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = euler(n, x) ascii_str = \ """\ E (x)\n\ n \ """ ucode_str = \ """\ E (x)\n\ n \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = euler(n, x/2) ascii_str = \ """\ /x\\\n\ E |-|\n\ n\\2/\ """ ucode_str = \ """\ ⎛x⎞\n\ E ⎜─⎟\n\ n⎝2⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_sqrt(): expr = sqrt(2) ascii_str = \ """\ ___\n\ \\/ 2 \ """ ucode_str = \ "√2" assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2**Rational(1, 3) ascii_str = \ """\ 3 ___\n\ \\/ 2 \ """ ucode_str = \ """\ 3 ___\n\ ╲╱ 2 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2**Rational(1, 1000) ascii_str = \ """\ 1000___\n\ \\/ 2 \ """ ucode_str = \ """\ 1000___\n\ ╲╱ 2 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = sqrt(x**2 + 1) ascii_str = \ """\ ________\n\ / 2 \n\ \\/ x + 1 \ """ ucode_str = \ """\ ________\n\ ╱ 2 \n\ ╲╱ x + 1 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (1 + sqrt(5))**Rational(1, 3) ascii_str = \ """\ ___________\n\ 3 / ___ \n\ \\/ 1 + \\/ 5 \ """ ucode_str = \ """\ 3 ________\n\ ╲╱ 1 + √5 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2**(1/x) ascii_str = \ """\ x ___\n\ \\/ 2 \ """ ucode_str = \ """\ x ___\n\ ╲╱ 2 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = sqrt(2 + pi) ascii_str = \ """\ ________\n\ \\/ 2 + pi \ """ ucode_str = \ """\ _______\n\ ╲╱ 2 + π \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (2 + ( 1 + x**2)/(2 + x))**Rational(1, 4) + (1 + x**Rational(1, 1000))/sqrt(3 + x**2) ascii_str = \ """\ ____________ \n\ / 2 1000___ \n\ / x + 1 \\/ x + 1\n\ 4 / 2 + ------ + -----------\n\ \\/ x + 2 ________\n\ / 2 \n\ \\/ x + 3 \ """ ucode_str = \ """\ ____________ \n\ ╱ 2 1000___ \n\ ╱ x + 1 ╲╱ x + 1\n\ 4 ╱ 2 + ────── + ───────────\n\ ╲╱ x + 2 ________\n\ ╱ 2 \n\ ╲╱ x + 3 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_sqrt_char_knob(): # See PR #9234. expr = sqrt(2) ucode_str1 = \ """\ ___\n\ ╲╱ 2 \ """ ucode_str2 = \ "√2" assert xpretty(expr, use_unicode=True, use_unicode_sqrt_char=False) == ucode_str1 assert xpretty(expr, use_unicode=True, use_unicode_sqrt_char=True) == ucode_str2 def test_pretty_sqrt_longsymbol_no_sqrt_char(): # Do not use unicode sqrt char for long symbols (see PR #9234). expr = sqrt(Symbol('C1')) ucode_str = \ """\ ____\n\ ╲╱ C₁ \ """ assert upretty(expr) == ucode_str def test_pretty_KroneckerDelta(): x, y = symbols("x, y") expr = KroneckerDelta(x, y) ascii_str = \ """\ d \n\ x,y\ """ ucode_str = \ """\ δ \n\ x,y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_product(): n, m, k, l = symbols('n m k l') f = symbols('f', cls=Function) expr = Product(f((n/3)**2), (n, k**2, l)) unicode_str = \ """\ l \n\ ─┬──────┬─ \n\ │ │ ⎛ 2⎞\n\ │ │ ⎜n ⎟\n\ │ │ f⎜──⎟\n\ │ │ ⎝9 ⎠\n\ │ │ \n\ 2 \n\ n = k """ ascii_str = \ """\ l \n\ __________ \n\ | | / 2\\\n\ | | |n |\n\ | | f|--|\n\ | | \\9 /\n\ | | \n\ 2 \n\ n = k """ expr = Product(f((n/3)**2), (n, k**2, l), (l, 1, m)) unicode_str = \ """\ m l \n\ ─┬──────┬─ ─┬──────┬─ \n\ │ │ │ │ ⎛ 2⎞\n\ │ │ │ │ ⎜n ⎟\n\ │ │ │ │ f⎜──⎟\n\ │ │ │ │ ⎝9 ⎠\n\ │ │ │ │ \n\ l = 1 2 \n\ n = k """ ascii_str = \ """\ m l \n\ __________ __________ \n\ | | | | / 2\\\n\ | | | | |n |\n\ | | | | f|--|\n\ | | | | \\9 /\n\ | | | | \n\ l = 1 2 \n\ n = k """ assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str def test_pretty_Lambda(): # S.IdentityFunction is a special case expr = Lambda(y, y) assert pretty(expr) == "x -> x" assert upretty(expr) == "x ↦ x" expr = Lambda(x, x+1) assert pretty(expr) == "x -> x + 1" assert upretty(expr) == "x ↦ x + 1" expr = Lambda(x, x**2) ascii_str = \ """\ 2\n\ x -> x \ """ ucode_str = \ """\ 2\n\ x ↦ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Lambda(x, x**2)**2 ascii_str = \ """\ 2 / 2\\ \n\ \\x -> x / \ """ ucode_str = \ """\ 2 ⎛ 2⎞ \n\ ⎝x ↦ x ⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Lambda((x, y), x) ascii_str = "(x, y) -> x" ucode_str = "(x, y) ↦ x" assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Lambda((x, y), x**2) ascii_str = \ """\ 2\n\ (x, y) -> x \ """ ucode_str = \ """\ 2\n\ (x, y) ↦ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Lambda(((x, y),), x**2) ascii_str = \ """\ 2\n\ ((x, y),) -> x \ """ ucode_str = \ """\ 2\n\ ((x, y),) ↦ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_TransferFunction(): tf1 = TransferFunction(s - 1, s + 1, s) assert upretty(tf1) == "s - 1\n─────\ns + 1" tf2 = TransferFunction(2*s + 1, 3 - p, s) assert upretty(tf2) == "2⋅s + 1\n───────\n 3 - p " tf3 = TransferFunction(p, p + 1, p) assert upretty(tf3) == " p \n─────\np + 1" def test_pretty_Series(): tf1 = TransferFunction(x + y, x - 2*y, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(x**2 + y, y - x, y) tf4 = TransferFunction(2, 3, y) tfm1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]]) tfm2 = TransferFunctionMatrix([[tf3], [-tf4]]) tfm3 = TransferFunctionMatrix([[tf1, -tf2, -tf3], [tf3, -tf4, tf2]]) tfm4 = TransferFunctionMatrix([[tf1, tf2], [tf3, -tf4], [-tf2, -tf1]]) tfm5 = TransferFunctionMatrix([[-tf2, -tf1], [tf4, -tf3], [tf1, tf2]]) expected1 = \ """\ ⎛ 2 ⎞\n\ ⎛ x + y ⎞ ⎜x + y⎟\n\ ⎜───────⎟⋅⎜──────⎟\n\ ⎝x - 2⋅y⎠ ⎝-x + y⎠\ """ expected2 = \ """\ ⎛-x + y⎞ ⎛ -x - y⎞\n\ ⎜──────⎟⋅⎜───────⎟\n\ ⎝x + y ⎠ ⎝x - 2⋅y⎠\ """ expected3 = \ """\ ⎛ 2 ⎞ \n\ ⎜x + y⎟ ⎛ x + y ⎞ ⎛ -x - y x - y⎞\n\ ⎜──────⎟⋅⎜───────⎟⋅⎜─────── + ─────⎟\n\ ⎝-x + y⎠ ⎝x - 2⋅y⎠ ⎝x - 2⋅y x + y⎠\ """ expected4 = \ """\ ⎛ 2 ⎞\n\ ⎛ x + y x - y⎞ ⎜x - y x + y⎟\n\ ⎜─────── + ─────⎟⋅⎜───── + ──────⎟\n\ ⎝x - 2⋅y x + y⎠ ⎝x + y -x + y⎠\ """ expected5 = \ """\ ⎡ x + y x - y⎤ ⎡ 2 ⎤ \n\ ⎢─────── ─────⎥ ⎢x + y⎥ \n\ ⎢x - 2⋅y x + y⎥ ⎢──────⎥ \n\ ⎢ ⎥ ⎢-x + y⎥ \n\ ⎢ 2 ⎥ ⋅⎢ ⎥ \n\ ⎢x + y 2 ⎥ ⎢ -2 ⎥ \n\ ⎢────── ─ ⎥ ⎢ ─── ⎥ \n\ ⎣-x + y 3 ⎦τ ⎣ 3 ⎦τ\ """ expected6 = \ """\ ⎛⎡ x + y x - y ⎤ ⎡ x - y x + y ⎤ ⎞\n\ ⎜⎢─────── ───── ⎥ ⎢ ───── ───────⎥ ⎟\n\ ⎡ x + y x - y⎤ ⎡ 2 ⎤ ⎜⎢x - 2⋅y x + y ⎥ ⎢ x + y x - 2⋅y⎥ ⎟\n\ ⎢─────── ─────⎥ ⎢ x + y -x + y - x - y⎥ ⎜⎢ ⎥ ⎢ ⎥ ⎟\n\ ⎢x - 2⋅y x + y⎥ ⎢─────── ────── ────────⎥ ⎜⎢ 2 ⎥ ⎢ 2 ⎥ ⎟\n\ ⎢ ⎥ ⎢x - 2⋅y x + y -x + y ⎥ ⎜⎢x + y -2 ⎥ ⎢ -2 x + y ⎥ ⎟\n\ ⎢ 2 ⎥ ⋅⎢ ⎥ ⋅⎜⎢────── ─── ⎥ + ⎢ ─── ────── ⎥ ⎟\n\ ⎢x + y 2 ⎥ ⎢ 2 ⎥ ⎜⎢-x + y 3 ⎥ ⎢ 3 -x + y ⎥ ⎟\n\ ⎢────── ─ ⎥ ⎢x + y -2 x - y ⎥ ⎜⎢ ⎥ ⎢ ⎥ ⎟\n\ ⎣-x + y 3 ⎦τ ⎢────── ─── ───── ⎥ ⎜⎢-x + y -x - y⎥ ⎢ -x - y -x + y ⎥ ⎟\n\ ⎣-x + y 3 x + y ⎦τ ⎜⎢────── ───────⎥ ⎢─────── ────── ⎥ ⎟\n\ ⎝⎣x + y x - 2⋅y⎦τ ⎣x - 2⋅y x + y ⎦τ⎠\ """ assert upretty(Series(tf1, tf3)) == expected1 assert upretty(Series(-tf2, -tf1)) == expected2 assert upretty(Series(tf3, tf1, Parallel(-tf1, tf2))) == expected3 assert upretty(Series(Parallel(tf1, tf2), Parallel(tf2, tf3))) == expected4 assert upretty(MIMOSeries(tfm2, tfm1)) == expected5 assert upretty(MIMOSeries(MIMOParallel(tfm4, -tfm5), tfm3, tfm1)) == expected6 def test_pretty_Parallel(): tf1 = TransferFunction(x + y, x - 2*y, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(x**2 + y, y - x, y) tf4 = TransferFunction(y**2 - x, x**3 + x, y) tfm1 = TransferFunctionMatrix([[tf1, tf2], [tf3, -tf4], [-tf2, -tf1]]) tfm2 = TransferFunctionMatrix([[-tf2, -tf1], [tf4, -tf3], [tf1, tf2]]) tfm3 = TransferFunctionMatrix([[-tf1, tf2], [-tf3, tf4], [tf2, tf1]]) tfm4 = TransferFunctionMatrix([[-tf1, -tf2], [-tf3, -tf4]]) expected1 = \ """\ x + y x - y\n\ ─────── + ─────\n\ x - 2⋅y x + y\ """ expected2 = \ """\ -x + y -x - y\n\ ────── + ───────\n\ x + y x - 2⋅y\ """ expected3 = \ """\ 2 \n\ x + y x + y ⎛ -x - y⎞ ⎛x - y⎞\n\ ────── + ─────── + ⎜───────⎟⋅⎜─────⎟\n\ -x + y x - 2⋅y ⎝x - 2⋅y⎠ ⎝x + y⎠\ """ expected4 = \ """\ ⎛ 2 ⎞\n\ ⎛ x + y ⎞ ⎛x - y⎞ ⎛x - y⎞ ⎜x + y⎟\n\ ⎜───────⎟⋅⎜─────⎟ + ⎜─────⎟⋅⎜──────⎟\n\ ⎝x - 2⋅y⎠ ⎝x + y⎠ ⎝x + y⎠ ⎝-x + y⎠\ """ expected5 = \ """\ ⎡ x + y -x + y ⎤ ⎡ x - y x + y ⎤ ⎡ x + y x - y ⎤ \n\ ⎢─────── ────── ⎥ ⎢ ───── ───────⎥ ⎢─────── ───── ⎥ \n\ ⎢x - 2⋅y x + y ⎥ ⎢ x + y x - 2⋅y⎥ ⎢x - 2⋅y x + y ⎥ \n\ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ \n\ ⎢ 2 2 ⎥ ⎢ 2 2 ⎥ ⎢ 2 2 ⎥ \n\ ⎢x + y x - y ⎥ ⎢x - y x + y ⎥ ⎢x + y x - y ⎥ \n\ ⎢────── ────── ⎥ + ⎢────── ────── ⎥ + ⎢────── ────── ⎥ \n\ ⎢-x + y 3 ⎥ ⎢ 3 -x + y ⎥ ⎢-x + y 3 ⎥ \n\ ⎢ x + x ⎥ ⎢x + x ⎥ ⎢ x + x ⎥ \n\ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ \n\ ⎢-x + y -x - y⎥ ⎢ -x - y -x + y ⎥ ⎢-x + y -x - y⎥ \n\ ⎢────── ───────⎥ ⎢─────── ────── ⎥ ⎢────── ───────⎥ \n\ ⎣x + y x - 2⋅y⎦τ ⎣x - 2⋅y x + y ⎦τ ⎣x + y x - 2⋅y⎦τ\ """ expected6 = \ """\ ⎡ x - y x + y ⎤ ⎡-x + y -x - y ⎤ \n\ ⎢ ───── ───────⎥ ⎢────── ─────── ⎥ \n\ ⎢ x + y x - 2⋅y⎥ ⎡ -x - y -x + y⎤ ⎢x + y x - 2⋅y ⎥ \n\ ⎢ ⎥ ⎢─────── ──────⎥ ⎢ ⎥ \n\ ⎢ 2 2 ⎥ ⎢x - 2⋅y x + y ⎥ ⎢ 2 2 ⎥ \n\ ⎢x - y x + y ⎥ ⎢ ⎥ ⎢-x + y - x - y⎥ \n\ ⎢────── ────── ⎥ ⋅⎢ 2 2⎥ + ⎢─────── ────────⎥ \n\ ⎢ 3 -x + y ⎥ ⎢- x - y x - y ⎥ ⎢ 3 -x + y ⎥ \n\ ⎢x + x ⎥ ⎢──────── ──────⎥ ⎢ x + x ⎥ \n\ ⎢ ⎥ ⎢ -x + y 3 ⎥ ⎢ ⎥ \n\ ⎢ -x - y -x + y ⎥ ⎣ x + x⎦τ ⎢ x + y x - y ⎥ \n\ ⎢─────── ────── ⎥ ⎢─────── ───── ⎥ \n\ ⎣x - 2⋅y x + y ⎦τ ⎣x - 2⋅y x + y ⎦τ\ """ assert upretty(Parallel(tf1, tf2)) == expected1 assert upretty(Parallel(-tf2, -tf1)) == expected2 assert upretty(Parallel(tf3, tf1, Series(-tf1, tf2))) == expected3 assert upretty(Parallel(Series(tf1, tf2), Series(tf2, tf3))) == expected4 assert upretty(MIMOParallel(-tfm3, -tfm2, tfm1)) == expected5 assert upretty(MIMOParallel(MIMOSeries(tfm4, -tfm2), tfm2)) == expected6 def test_pretty_Feedback(): tf = TransferFunction(1, 1, y) tf1 = TransferFunction(x + y, x - 2*y, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(y**2 - 2*y + 1, y + 5, y) tf4 = TransferFunction(x - 2*y**3, x + y, x) tf5 = TransferFunction(1 - x, x - y, y) tf6 = TransferFunction(2, 2, x) expected1 = \ """\ ⎛1⎞ \n\ ⎜─⎟ \n\ ⎝1⎠ \n\ ─────────────\n\ 1 ⎛ x + y ⎞\n\ ─ + ⎜───────⎟\n\ 1 ⎝x - 2⋅y⎠\ """ expected2 = \ """\ ⎛1⎞ \n\ ⎜─⎟ \n\ ⎝1⎠ \n\ ────────────────────────────────────\n\ ⎛ 2 ⎞\n\ 1 ⎛x - y⎞ ⎛ x + y ⎞ ⎜y - 2⋅y + 1⎟\n\ ─ + ⎜─────⎟⋅⎜───────⎟⋅⎜────────────⎟\n\ 1 ⎝x + y⎠ ⎝x - 2⋅y⎠ ⎝ y + 5 ⎠\ """ expected3 = \ """\ ⎛ x + y ⎞ \n\ ⎜───────⎟ \n\ ⎝x - 2⋅y⎠ \n\ ────────────────────────────────────────────\n\ ⎛ 2 ⎞ \n\ 1 ⎛ x + y ⎞ ⎛x - y⎞ ⎜y - 2⋅y + 1⎟ ⎛1 - x⎞\n\ ─ + ⎜───────⎟⋅⎜─────⎟⋅⎜────────────⎟⋅⎜─────⎟\n\ 1 ⎝x - 2⋅y⎠ ⎝x + y⎠ ⎝ y + 5 ⎠ ⎝x - y⎠\ """ expected4 = \ """\ ⎛ x + y ⎞ ⎛x - y⎞ \n\ ⎜───────⎟⋅⎜─────⎟ \n\ ⎝x - 2⋅y⎠ ⎝x + y⎠ \n\ ─────────────────────\n\ 1 ⎛ x + y ⎞ ⎛x - y⎞\n\ ─ + ⎜───────⎟⋅⎜─────⎟\n\ 1 ⎝x - 2⋅y⎠ ⎝x + y⎠\ """ expected5 = \ """\ ⎛ x + y ⎞ ⎛x - y⎞ \n\ ⎜───────⎟⋅⎜─────⎟ \n\ ⎝x - 2⋅y⎠ ⎝x + y⎠ \n\ ─────────────────────────────\n\ 1 ⎛ x + y ⎞ ⎛x - y⎞ ⎛1 - x⎞\n\ ─ + ⎜───────⎟⋅⎜─────⎟⋅⎜─────⎟\n\ 1 ⎝x - 2⋅y⎠ ⎝x + y⎠ ⎝x - y⎠\ """ expected6 = \ """\ ⎛ 2 ⎞ \n\ ⎜y - 2⋅y + 1⎟ ⎛1 - x⎞ \n\ ⎜────────────⎟⋅⎜─────⎟ \n\ ⎝ y + 5 ⎠ ⎝x - y⎠ \n\ ────────────────────────────────────────────\n\ ⎛ 2 ⎞ \n\ 1 ⎜y - 2⋅y + 1⎟ ⎛1 - x⎞ ⎛x - y⎞ ⎛ x + y ⎞\n\ ─ + ⎜────────────⎟⋅⎜─────⎟⋅⎜─────⎟⋅⎜───────⎟\n\ 1 ⎝ y + 5 ⎠ ⎝x - y⎠ ⎝x + y⎠ ⎝x - 2⋅y⎠\ """ expected7 = \ """\ ⎛ 3⎞ \n\ ⎜x - 2⋅y ⎟ \n\ ⎜────────⎟ \n\ ⎝ x + y ⎠ \n\ ──────────────────\n\ ⎛ 3⎞ \n\ 1 ⎜x - 2⋅y ⎟ ⎛2⎞\n\ ─ + ⎜────────⎟⋅⎜─⎟\n\ 1 ⎝ x + y ⎠ ⎝2⎠\ """ expected8 = \ """\ ⎛1 - x⎞ \n\ ⎜─────⎟ \n\ ⎝x - y⎠ \n\ ───────────\n\ 1 ⎛1 - x⎞\n\ ─ + ⎜─────⎟\n\ 1 ⎝x - y⎠\ """ expected9 = \ """\ ⎛ x + y ⎞ ⎛x - y⎞ \n\ ⎜───────⎟⋅⎜─────⎟ \n\ ⎝x - 2⋅y⎠ ⎝x + y⎠ \n\ ─────────────────────────────\n\ 1 ⎛ x + y ⎞ ⎛x - y⎞ ⎛1 - x⎞\n\ ─ - ⎜───────⎟⋅⎜─────⎟⋅⎜─────⎟\n\ 1 ⎝x - 2⋅y⎠ ⎝x + y⎠ ⎝x - y⎠\ """ expected10 = \ """\ ⎛1 - x⎞ \n\ ⎜─────⎟ \n\ ⎝x - y⎠ \n\ ───────────\n\ 1 ⎛1 - x⎞\n\ ─ - ⎜─────⎟\n\ 1 ⎝x - y⎠\ """ assert upretty(Feedback(tf, tf1)) == expected1 assert upretty(Feedback(tf, tf2*tf1*tf3)) == expected2 assert upretty(Feedback(tf1, tf2*tf3*tf5)) == expected3 assert upretty(Feedback(tf1*tf2, tf)) == expected4 assert upretty(Feedback(tf1*tf2, tf5)) == expected5 assert upretty(Feedback(tf3*tf5, tf2*tf1)) == expected6 assert upretty(Feedback(tf4, tf6)) == expected7 assert upretty(Feedback(tf5, tf)) == expected8 assert upretty(Feedback(tf1*tf2, tf5, 1)) == expected9 assert upretty(Feedback(tf5, tf, 1)) == expected10 def test_pretty_MIMOFeedback(): tf1 = TransferFunction(x + y, x - 2*y, y) tf2 = TransferFunction(x - y, x + y, y) tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]]) tfm_3 = TransferFunctionMatrix([[tf1, tf1], [tf2, tf2]]) expected1 = \ """\ ⎛ ⎡ x + y x - y ⎤ ⎡ x - y x + y ⎤ ⎞-1 ⎡ x + y x - y ⎤ \n\ ⎜ ⎢─────── ───── ⎥ ⎢ ───── ───────⎥ ⎟ ⎢─────── ───── ⎥ \n\ ⎜ ⎢x - 2⋅y x + y ⎥ ⎢ x + y x - 2⋅y⎥ ⎟ ⎢x - 2⋅y x + y ⎥ \n\ ⎜I - ⎢ ⎥ ⋅⎢ ⎥ ⎟ ⋅ ⎢ ⎥ \n\ ⎜ ⎢ x - y x + y ⎥ ⎢ x + y x - y ⎥ ⎟ ⎢ x - y x + y ⎥ \n\ ⎜ ⎢ ───── ───────⎥ ⎢─────── ───── ⎥ ⎟ ⎢ ───── ───────⎥ \n\ ⎝ ⎣ x + y x - 2⋅y⎦τ ⎣x - 2⋅y x + y ⎦τ⎠ ⎣ x + y x - 2⋅y⎦τ\ """ expected2 = \ """\ ⎛ ⎡ x + y x - y ⎤ ⎡ x - y x + y ⎤ ⎡ x + y x + y ⎤ ⎞-1 ⎡ x + y x - y ⎤ ⎡ x - y x + y ⎤ \n\ ⎜ ⎢─────── ───── ⎥ ⎢ ───── ───────⎥ ⎢─────── ───────⎥ ⎟ ⎢─────── ───── ⎥ ⎢ ───── ───────⎥ \n\ ⎜ ⎢x - 2⋅y x + y ⎥ ⎢ x + y x - 2⋅y⎥ ⎢x - 2⋅y x - 2⋅y⎥ ⎟ ⎢x - 2⋅y x + y ⎥ ⎢ x + y x - 2⋅y⎥ \n\ ⎜I + ⎢ ⎥ ⋅⎢ ⎥ ⋅⎢ ⎥ ⎟ ⋅ ⎢ ⎥ ⋅⎢ ⎥ \n\ ⎜ ⎢ x - y x + y ⎥ ⎢ x + y x - y ⎥ ⎢ x - y x - y ⎥ ⎟ ⎢ x - y x + y ⎥ ⎢ x + y x - y ⎥ \n\ ⎜ ⎢ ───── ───────⎥ ⎢─────── ───── ⎥ ⎢ ───── ───── ⎥ ⎟ ⎢ ───── ───────⎥ ⎢─────── ───── ⎥ \n\ ⎝ ⎣ x + y x - 2⋅y⎦τ ⎣x - 2⋅y x + y ⎦τ ⎣ x + y x + y ⎦τ⎠ ⎣ x + y x - 2⋅y⎦τ ⎣x - 2⋅y x + y ⎦τ\ """ assert upretty(MIMOFeedback(tfm_1, tfm_2, 1)) == \ expected1 # Positive MIMOFeedback assert upretty(MIMOFeedback(tfm_1*tfm_2, tfm_3)) == \ expected2 # Negative MIMOFeedback (Default) def test_pretty_TransferFunctionMatrix(): tf1 = TransferFunction(x + y, x - 2*y, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(y**2 - 2*y + 1, y + 5, y) tf4 = TransferFunction(y, x**2 + x + 1, y) tf5 = TransferFunction(1 - x, x - y, y) tf6 = TransferFunction(2, 2, y) expected1 = \ """\ ⎡ x + y ⎤ \n\ ⎢───────⎥ \n\ ⎢x - 2⋅y⎥ \n\ ⎢ ⎥ \n\ ⎢ x - y ⎥ \n\ ⎢ ───── ⎥ \n\ ⎣ x + y ⎦τ\ """ expected2 = \ """\ ⎡ x + y ⎤ \n\ ⎢ ─────── ⎥ \n\ ⎢ x - 2⋅y ⎥ \n\ ⎢ ⎥ \n\ ⎢ x - y ⎥ \n\ ⎢ ───── ⎥ \n\ ⎢ x + y ⎥ \n\ ⎢ ⎥ \n\ ⎢ 2 ⎥ \n\ ⎢- y + 2⋅y - 1⎥ \n\ ⎢──────────────⎥ \n\ ⎣ y + 5 ⎦τ\ """ expected3 = \ """\ ⎡ x + y x - y ⎤ \n\ ⎢ ─────── ───── ⎥ \n\ ⎢ x - 2⋅y x + y ⎥ \n\ ⎢ ⎥ \n\ ⎢ 2 ⎥ \n\ ⎢y - 2⋅y + 1 y ⎥ \n\ ⎢──────────── ──────────⎥ \n\ ⎢ y + 5 2 ⎥ \n\ ⎢ x + x + 1⎥ \n\ ⎢ ⎥ \n\ ⎢ 1 - x 2 ⎥ \n\ ⎢ ───── ─ ⎥ \n\ ⎣ x - y 2 ⎦τ\ """ expected4 = \ """\ ⎡ x - y x + y y ⎤ \n\ ⎢ ───── ─────── ──────────⎥ \n\ ⎢ x + y x - 2⋅y 2 ⎥ \n\ ⎢ x + x + 1⎥ \n\ ⎢ ⎥ \n\ ⎢ 2 ⎥ \n\ ⎢- y + 2⋅y - 1 x - 1 -2 ⎥ \n\ ⎢────────────── ───── ─── ⎥ \n\ ⎣ y + 5 x - y 2 ⎦τ\ """ expected5 = \ """\ ⎡ x + y x - y x + y y ⎤ \n\ ⎢───────⋅───── ─────── ──────────⎥ \n\ ⎢x - 2⋅y x + y x - 2⋅y 2 ⎥ \n\ ⎢ x + x + 1⎥ \n\ ⎢ ⎥ \n\ ⎢ 1 - x 2 x + y -2 ⎥ \n\ ⎢ ───── + ─ ─────── ─── ⎥ \n\ ⎣ x - y 2 x - 2⋅y 2 ⎦τ\ """ assert upretty(TransferFunctionMatrix([[tf1], [tf2]])) == expected1 assert upretty(TransferFunctionMatrix([[tf1], [tf2], [-tf3]])) == expected2 assert upretty(TransferFunctionMatrix([[tf1, tf2], [tf3, tf4], [tf5, tf6]])) == expected3 assert upretty(TransferFunctionMatrix([[tf2, tf1, tf4], [-tf3, -tf5, -tf6]])) == expected4 assert upretty(TransferFunctionMatrix([[Series(tf2, tf1), tf1, tf4], [Parallel(tf6, tf5), tf1, -tf6]])) == \ expected5 def test_pretty_order(): expr = O(1) ascii_str = \ """\ O(1)\ """ ucode_str = \ """\ O(1)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = O(1/x) ascii_str = \ """\ /1\\\n\ O|-|\n\ \\x/\ """ ucode_str = \ """\ ⎛1⎞\n\ O⎜─⎟\n\ ⎝x⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = O(x**2 + y**2) ascii_str = \ """\ / 2 2 \\\n\ O\\x + y ; (x, y) -> (0, 0)/\ """ ucode_str = \ """\ ⎛ 2 2 ⎞\n\ O⎝x + y ; (x, y) → (0, 0)⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = O(1, (x, oo)) ascii_str = \ """\ O(1; x -> oo)\ """ ucode_str = \ """\ O(1; x → ∞)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = O(1/x, (x, oo)) ascii_str = \ """\ /1 \\\n\ O|-; x -> oo|\n\ \\x /\ """ ucode_str = \ """\ ⎛1 ⎞\n\ O⎜─; x → ∞⎟\n\ ⎝x ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = O(x**2 + y**2, (x, oo), (y, oo)) ascii_str = \ """\ / 2 2 \\\n\ O\\x + y ; (x, y) -> (oo, oo)/\ """ ucode_str = \ """\ ⎛ 2 2 ⎞\n\ O⎝x + y ; (x, y) → (∞, ∞)⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_derivatives(): # Simple expr = Derivative(log(x), x, evaluate=False) ascii_str = \ """\ d \n\ --(log(x))\n\ dx \ """ ucode_str = \ """\ d \n\ ──(log(x))\n\ dx \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Derivative(log(x), x, evaluate=False) + x ascii_str_1 = \ """\ d \n\ x + --(log(x))\n\ dx \ """ ascii_str_2 = \ """\ d \n\ --(log(x)) + x\n\ dx \ """ ucode_str_1 = \ """\ d \n\ x + ──(log(x))\n\ dx \ """ ucode_str_2 = \ """\ d \n\ ──(log(x)) + x\n\ dx \ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] # basic partial derivatives expr = Derivative(log(x + y) + x, x) ascii_str_1 = \ """\ d \n\ --(log(x + y) + x)\n\ dx \ """ ascii_str_2 = \ """\ d \n\ --(x + log(x + y))\n\ dx \ """ ucode_str_1 = \ """\ ∂ \n\ ──(log(x + y) + x)\n\ ∂x \ """ ucode_str_2 = \ """\ ∂ \n\ ──(x + log(x + y))\n\ ∂x \ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2], upretty(expr) # Multiple symbols expr = Derivative(log(x) + x**2, x, y) ascii_str_1 = \ """\ 2 \n\ d / 2\\\n\ -----\\log(x) + x /\n\ dy dx \ """ ascii_str_2 = \ """\ 2 \n\ d / 2 \\\n\ -----\\x + log(x)/\n\ dy dx \ """ ucode_str_1 = \ """\ 2 \n\ d ⎛ 2⎞\n\ ─────⎝log(x) + x ⎠\n\ dy dx \ """ ucode_str_2 = \ """\ 2 \n\ d ⎛ 2 ⎞\n\ ─────⎝x + log(x)⎠\n\ dy dx \ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = Derivative(2*x*y, y, x) + x**2 ascii_str_1 = \ """\ 2 \n\ d 2\n\ -----(2*x*y) + x \n\ dx dy \ """ ascii_str_2 = \ """\ 2 \n\ 2 d \n\ x + -----(2*x*y)\n\ dx dy \ """ ucode_str_1 = \ """\ 2 \n\ ∂ 2\n\ ─────(2⋅x⋅y) + x \n\ ∂x ∂y \ """ ucode_str_2 = \ """\ 2 \n\ 2 ∂ \n\ x + ─────(2⋅x⋅y)\n\ ∂x ∂y \ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = Derivative(2*x*y, x, x) ascii_str = \ """\ 2 \n\ d \n\ ---(2*x*y)\n\ 2 \n\ dx \ """ ucode_str = \ """\ 2 \n\ ∂ \n\ ───(2⋅x⋅y)\n\ 2 \n\ ∂x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Derivative(2*x*y, x, 17) ascii_str = \ """\ 17 \n\ d \n\ ----(2*x*y)\n\ 17 \n\ dx \ """ ucode_str = \ """\ 17 \n\ ∂ \n\ ────(2⋅x⋅y)\n\ 17 \n\ ∂x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Derivative(2*x*y, x, x, y) ascii_str = \ """\ 3 \n\ d \n\ ------(2*x*y)\n\ 2 \n\ dy dx \ """ ucode_str = \ """\ 3 \n\ ∂ \n\ ──────(2⋅x⋅y)\n\ 2 \n\ ∂y ∂x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str # Greek letters alpha = Symbol('alpha') beta = Function('beta') expr = beta(alpha).diff(alpha) ascii_str = \ """\ d \n\ ------(beta(alpha))\n\ dalpha \ """ ucode_str = \ """\ d \n\ ──(β(α))\n\ dα \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Derivative(f(x), (x, n)) ascii_str = \ """\ n \n\ d \n\ ---(f(x))\n\ n \n\ dx \ """ ucode_str = \ """\ n \n\ d \n\ ───(f(x))\n\ n \n\ dx \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_integrals(): expr = Integral(log(x), x) ascii_str = \ """\ / \n\ | \n\ | log(x) dx\n\ | \n\ / \ """ ucode_str = \ """\ ⌠ \n\ ⎮ log(x) dx\n\ ⌡ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(x**2, x) ascii_str = \ """\ / \n\ | \n\ | 2 \n\ | x dx\n\ | \n\ / \ """ ucode_str = \ """\ ⌠ \n\ ⎮ 2 \n\ ⎮ x dx\n\ ⌡ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral((sin(x))**2 / (tan(x))**2) ascii_str = \ """\ / \n\ | \n\ | 2 \n\ | sin (x) \n\ | ------- dx\n\ | 2 \n\ | tan (x) \n\ | \n\ / \ """ ucode_str = \ """\ ⌠ \n\ ⎮ 2 \n\ ⎮ sin (x) \n\ ⎮ ─────── dx\n\ ⎮ 2 \n\ ⎮ tan (x) \n\ ⌡ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(x**(2**x), x) ascii_str = \ """\ / \n\ | \n\ | / x\\ \n\ | \\2 / \n\ | x dx\n\ | \n\ / \ """ ucode_str = \ """\ ⌠ \n\ ⎮ ⎛ x⎞ \n\ ⎮ ⎝2 ⎠ \n\ ⎮ x dx\n\ ⌡ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(x**2, (x, 1, 2)) ascii_str = \ """\ 2 \n\ / \n\ | \n\ | 2 \n\ | x dx\n\ | \n\ / \n\ 1 \ """ ucode_str = \ """\ 2 \n\ ⌠ \n\ ⎮ 2 \n\ ⎮ x dx\n\ ⌡ \n\ 1 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(x**2, (x, Rational(1, 2), 10)) ascii_str = \ """\ 10 \n\ / \n\ | \n\ | 2 \n\ | x dx\n\ | \n\ / \n\ 1/2 \ """ ucode_str = \ """\ 10 \n\ ⌠ \n\ ⎮ 2 \n\ ⎮ x dx\n\ ⌡ \n\ 1/2 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(x**2*y**2, x, y) ascii_str = \ """\ / / \n\ | | \n\ | | 2 2 \n\ | | x *y dx dy\n\ | | \n\ / / \ """ ucode_str = \ """\ ⌠ ⌠ \n\ ⎮ ⎮ 2 2 \n\ ⎮ ⎮ x ⋅y dx dy\n\ ⌡ ⌡ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(sin(th)/cos(ph), (th, 0, pi), (ph, 0, 2*pi)) ascii_str = \ """\ 2*pi pi \n\ / / \n\ | | \n\ | | sin(theta) \n\ | | ---------- d(theta) d(phi)\n\ | | cos(phi) \n\ | | \n\ / / \n\ 0 0 \ """ ucode_str = \ """\ 2⋅π π \n\ ⌠ ⌠ \n\ ⎮ ⎮ sin(θ) \n\ ⎮ ⎮ ────── dθ dφ\n\ ⎮ ⎮ cos(φ) \n\ ⌡ ⌡ \n\ 0 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_matrix(): # Empty Matrix expr = Matrix() ascii_str = "[]" unicode_str = "[]" assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str expr = Matrix(2, 0, lambda i, j: 0) ascii_str = "[]" unicode_str = "[]" assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str expr = Matrix(0, 2, lambda i, j: 0) ascii_str = "[]" unicode_str = "[]" assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str expr = Matrix([[x**2 + 1, 1], [y, x + y]]) ascii_str_1 = \ """\ [ 2 ] [1 + x 1 ] [ ] [ y x + y]\ """ ascii_str_2 = \ """\ [ 2 ] [x + 1 1 ] [ ] [ y x + y]\ """ ucode_str_1 = \ """\ ⎡ 2 ⎤ ⎢1 + x 1 ⎥ ⎢ ⎥ ⎣ y x + y⎦\ """ ucode_str_2 = \ """\ ⎡ 2 ⎤ ⎢x + 1 1 ⎥ ⎢ ⎥ ⎣ y x + y⎦\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = Matrix([[x/y, y, th], [0, exp(I*k*ph), 1]]) ascii_str = \ """\ [x ] [- y theta] [y ] [ ] [ I*k*phi ] [0 e 1 ]\ """ ucode_str = \ """\ ⎡x ⎤ ⎢─ y θ⎥ ⎢y ⎥ ⎢ ⎥ ⎢ ⅈ⋅k⋅φ ⎥ ⎣0 ℯ 1⎦\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str unicode_str = \ """\ ⎡v̇_msc_00 0 0 ⎤ ⎢ ⎥ ⎢ 0 v̇_msc_01 0 ⎥ ⎢ ⎥ ⎣ 0 0 v̇_msc_02⎦\ """ expr = diag(*MatrixSymbol('vdot_msc',1,3)) assert upretty(expr) == unicode_str def test_pretty_ndim_arrays(): x, y, z, w = symbols("x y z w") for ArrayType in (ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableDenseNDimArray, MutableSparseNDimArray): # Basic: scalar array M = ArrayType(x) assert pretty(M) == "x" assert upretty(M) == "x" M = ArrayType([[1/x, y], [z, w]]) M1 = ArrayType([1/x, y, z]) M2 = tensorproduct(M1, M) M3 = tensorproduct(M, M) ascii_str = \ """\ [1 ]\n\ [- y]\n\ [x ]\n\ [ ]\n\ [z w]\ """ ucode_str = \ """\ ⎡1 ⎤\n\ ⎢─ y⎥\n\ ⎢x ⎥\n\ ⎢ ⎥\n\ ⎣z w⎦\ """ assert pretty(M) == ascii_str assert upretty(M) == ucode_str ascii_str = \ """\ [1 ]\n\ [- y z]\n\ [x ]\ """ ucode_str = \ """\ ⎡1 ⎤\n\ ⎢─ y z⎥\n\ ⎣x ⎦\ """ assert pretty(M1) == ascii_str assert upretty(M1) == ucode_str ascii_str = \ """\ [[1 y] ]\n\ [[-- -] [z ]]\n\ [[ 2 x] [ y 2 ] [- y*z]]\n\ [[x ] [ - y ] [x ]]\n\ [[ ] [ x ] [ ]]\n\ [[z w] [ ] [ 2 ]]\n\ [[- -] [y*z w*y] [z w*z]]\n\ [[x x] ]\ """ ucode_str = \ """\ ⎡⎡1 y⎤ ⎤\n\ ⎢⎢── ─⎥ ⎡z ⎤⎥\n\ ⎢⎢ 2 x⎥ ⎡ y 2 ⎤ ⎢─ y⋅z⎥⎥\n\ ⎢⎢x ⎥ ⎢ ─ y ⎥ ⎢x ⎥⎥\n\ ⎢⎢ ⎥ ⎢ x ⎥ ⎢ ⎥⎥\n\ ⎢⎢z w⎥ ⎢ ⎥ ⎢ 2 ⎥⎥\n\ ⎢⎢─ ─⎥ ⎣y⋅z w⋅y⎦ ⎣z w⋅z⎦⎥\n\ ⎣⎣x x⎦ ⎦\ """ assert pretty(M2) == ascii_str assert upretty(M2) == ucode_str ascii_str = \ """\ [ [1 y] ]\n\ [ [-- -] ]\n\ [ [ 2 x] [ y 2 ]]\n\ [ [x ] [ - y ]]\n\ [ [ ] [ x ]]\n\ [ [z w] [ ]]\n\ [ [- -] [y*z w*y]]\n\ [ [x x] ]\n\ [ ]\n\ [[z ] [ w ]]\n\ [[- y*z] [ - w*y]]\n\ [[x ] [ x ]]\n\ [[ ] [ ]]\n\ [[ 2 ] [ 2 ]]\n\ [[z w*z] [w*z w ]]\ """ ucode_str = \ """\ ⎡ ⎡1 y⎤ ⎤\n\ ⎢ ⎢── ─⎥ ⎥\n\ ⎢ ⎢ 2 x⎥ ⎡ y 2 ⎤⎥\n\ ⎢ ⎢x ⎥ ⎢ ─ y ⎥⎥\n\ ⎢ ⎢ ⎥ ⎢ x ⎥⎥\n\ ⎢ ⎢z w⎥ ⎢ ⎥⎥\n\ ⎢ ⎢─ ─⎥ ⎣y⋅z w⋅y⎦⎥\n\ ⎢ ⎣x x⎦ ⎥\n\ ⎢ ⎥\n\ ⎢⎡z ⎤ ⎡ w ⎤⎥\n\ ⎢⎢─ y⋅z⎥ ⎢ ─ w⋅y⎥⎥\n\ ⎢⎢x ⎥ ⎢ x ⎥⎥\n\ ⎢⎢ ⎥ ⎢ ⎥⎥\n\ ⎢⎢ 2 ⎥ ⎢ 2 ⎥⎥\n\ ⎣⎣z w⋅z⎦ ⎣w⋅z w ⎦⎦\ """ assert pretty(M3) == ascii_str assert upretty(M3) == ucode_str Mrow = ArrayType([[x, y, 1 / z]]) Mcolumn = ArrayType([[x], [y], [1 / z]]) Mcol2 = ArrayType([Mcolumn.tolist()]) ascii_str = \ """\ [[ 1]]\n\ [[x y -]]\n\ [[ z]]\ """ ucode_str = \ """\ ⎡⎡ 1⎤⎤\n\ ⎢⎢x y ─⎥⎥\n\ ⎣⎣ z⎦⎦\ """ assert pretty(Mrow) == ascii_str assert upretty(Mrow) == ucode_str ascii_str = \ """\ [x]\n\ [ ]\n\ [y]\n\ [ ]\n\ [1]\n\ [-]\n\ [z]\ """ ucode_str = \ """\ ⎡x⎤\n\ ⎢ ⎥\n\ ⎢y⎥\n\ ⎢ ⎥\n\ ⎢1⎥\n\ ⎢─⎥\n\ ⎣z⎦\ """ assert pretty(Mcolumn) == ascii_str assert upretty(Mcolumn) == ucode_str ascii_str = \ """\ [[x]]\n\ [[ ]]\n\ [[y]]\n\ [[ ]]\n\ [[1]]\n\ [[-]]\n\ [[z]]\ """ ucode_str = \ """\ ⎡⎡x⎤⎤\n\ ⎢⎢ ⎥⎥\n\ ⎢⎢y⎥⎥\n\ ⎢⎢ ⎥⎥\n\ ⎢⎢1⎥⎥\n\ ⎢⎢─⎥⎥\n\ ⎣⎣z⎦⎦\ """ assert pretty(Mcol2) == ascii_str assert upretty(Mcol2) == ucode_str def test_tensor_TensorProduct(): A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) assert upretty(TensorProduct(A, B)) == "A\u2297B" assert upretty(TensorProduct(A, B, A)) == "A\u2297B\u2297A" def test_diffgeom_print_WedgeProduct(): from sympy.diffgeom.rn import R2 from sympy.diffgeom import WedgeProduct wp = WedgeProduct(R2.dx, R2.dy) assert upretty(wp) == "ⅆ x∧ⅆ y" assert pretty(wp) == r"d x/\d y" def test_Adjoint(): X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert pretty(Adjoint(X)) == " +\nX " assert pretty(Adjoint(X + Y)) == " +\n(X + Y) " assert pretty(Adjoint(X) + Adjoint(Y)) == " + +\nX + Y " assert pretty(Adjoint(X*Y)) == " +\n(X*Y) " assert pretty(Adjoint(Y)*Adjoint(X)) == " + +\nY *X " assert pretty(Adjoint(X**2)) == " +\n/ 2\\ \n\\X / " assert pretty(Adjoint(X)**2) == " 2\n/ +\\ \n\\X / " assert pretty(Adjoint(Inverse(X))) == " +\n/ -1\\ \n\\X / " assert pretty(Inverse(Adjoint(X))) == " -1\n/ +\\ \n\\X / " assert pretty(Adjoint(Transpose(X))) == " +\n/ T\\ \n\\X / " assert pretty(Transpose(Adjoint(X))) == " T\n/ +\\ \n\\X / " assert upretty(Adjoint(X)) == " †\nX " assert upretty(Adjoint(X + Y)) == " †\n(X + Y) " assert upretty(Adjoint(X) + Adjoint(Y)) == " † †\nX + Y " assert upretty(Adjoint(X*Y)) == " †\n(X⋅Y) " assert upretty(Adjoint(Y)*Adjoint(X)) == " † †\nY ⋅X " assert upretty(Adjoint(X**2)) == \ " †\n⎛ 2⎞ \n⎝X ⎠ " assert upretty(Adjoint(X)**2) == \ " 2\n⎛ †⎞ \n⎝X ⎠ " assert upretty(Adjoint(Inverse(X))) == \ " †\n⎛ -1⎞ \n⎝X ⎠ " assert upretty(Inverse(Adjoint(X))) == \ " -1\n⎛ †⎞ \n⎝X ⎠ " assert upretty(Adjoint(Transpose(X))) == \ " †\n⎛ T⎞ \n⎝X ⎠ " assert upretty(Transpose(Adjoint(X))) == \ " T\n⎛ †⎞ \n⎝X ⎠ " def test_pretty_Trace_issue_9044(): X = Matrix([[1, 2], [3, 4]]) Y = Matrix([[2, 4], [6, 8]]) ascii_str_1 = \ """\ /[1 2]\\ tr|[ ]| \\[3 4]/\ """ ucode_str_1 = \ """\ ⎛⎡1 2⎤⎞ tr⎜⎢ ⎥⎟ ⎝⎣3 4⎦⎠\ """ ascii_str_2 = \ """\ /[1 2]\\ /[2 4]\\ tr|[ ]| + tr|[ ]| \\[3 4]/ \\[6 8]/\ """ ucode_str_2 = \ """\ ⎛⎡1 2⎤⎞ ⎛⎡2 4⎤⎞ tr⎜⎢ ⎥⎟ + tr⎜⎢ ⎥⎟ ⎝⎣3 4⎦⎠ ⎝⎣6 8⎦⎠\ """ assert pretty(Trace(X)) == ascii_str_1 assert upretty(Trace(X)) == ucode_str_1 assert pretty(Trace(X) + Trace(Y)) == ascii_str_2 assert upretty(Trace(X) + Trace(Y)) == ucode_str_2 def test_MatrixSlice(): n = Symbol('n', integer=True) x, y, z, w, t, = symbols('x y z w t') X = MatrixSymbol('X', n, n) Y = MatrixSymbol('Y', 10, 10) Z = MatrixSymbol('Z', 10, 10) expr = MatrixSlice(X, (None, None, None), (None, None, None)) assert pretty(expr) == upretty(expr) == 'X[:, :]' expr = X[x:x + 1, y:y + 1] assert pretty(expr) == upretty(expr) == 'X[x:x + 1, y:y + 1]' expr = X[x:x + 1:2, y:y + 1:2] assert pretty(expr) == upretty(expr) == 'X[x:x + 1:2, y:y + 1:2]' expr = X[:x, y:] assert pretty(expr) == upretty(expr) == 'X[:x, y:]' expr = X[:x, y:] assert pretty(expr) == upretty(expr) == 'X[:x, y:]' expr = X[x:, :y] assert pretty(expr) == upretty(expr) == 'X[x:, :y]' expr = X[x:y, z:w] assert pretty(expr) == upretty(expr) == 'X[x:y, z:w]' expr = X[x:y:t, w:t:x] assert pretty(expr) == upretty(expr) == 'X[x:y:t, w:t:x]' expr = X[x::y, t::w] assert pretty(expr) == upretty(expr) == 'X[x::y, t::w]' expr = X[:x:y, :t:w] assert pretty(expr) == upretty(expr) == 'X[:x:y, :t:w]' expr = X[::x, ::y] assert pretty(expr) == upretty(expr) == 'X[::x, ::y]' expr = MatrixSlice(X, (0, None, None), (0, None, None)) assert pretty(expr) == upretty(expr) == 'X[:, :]' expr = MatrixSlice(X, (None, n, None), (None, n, None)) assert pretty(expr) == upretty(expr) == 'X[:, :]' expr = MatrixSlice(X, (0, n, None), (0, n, None)) assert pretty(expr) == upretty(expr) == 'X[:, :]' expr = MatrixSlice(X, (0, n, 2), (0, n, 2)) assert pretty(expr) == upretty(expr) == 'X[::2, ::2]' expr = X[1:2:3, 4:5:6] assert pretty(expr) == upretty(expr) == 'X[1:2:3, 4:5:6]' expr = X[1:3:5, 4:6:8] assert pretty(expr) == upretty(expr) == 'X[1:3:5, 4:6:8]' expr = X[1:10:2] assert pretty(expr) == upretty(expr) == 'X[1:10:2, :]' expr = Y[:5, 1:9:2] assert pretty(expr) == upretty(expr) == 'Y[:5, 1:9:2]' expr = Y[:5, 1:10:2] assert pretty(expr) == upretty(expr) == 'Y[:5, 1::2]' expr = Y[5, :5:2] assert pretty(expr) == upretty(expr) == 'Y[5:6, :5:2]' expr = X[0:1, 0:1] assert pretty(expr) == upretty(expr) == 'X[:1, :1]' expr = X[0:1:2, 0:1:2] assert pretty(expr) == upretty(expr) == 'X[:1:2, :1:2]' expr = (Y + Z)[2:, 2:] assert pretty(expr) == upretty(expr) == '(Y + Z)[2:, 2:]' def test_MatrixExpressions(): n = Symbol('n', integer=True) X = MatrixSymbol('X', n, n) assert pretty(X) == upretty(X) == "X" # Apply function elementwise (`ElementwiseApplyFunc`): expr = (X.T*X).applyfunc(sin) ascii_str = """\ / T \\\n\ (d -> sin(d)).\\X *X/\ """ ucode_str = """\ ⎛ T ⎞\n\ (d ↦ sin(d))˳⎝X ⋅X⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str lamda = Lambda(x, 1/x) expr = (n*X).applyfunc(lamda) ascii_str = """\ / 1\\ \n\ |x -> -|.(n*X)\n\ \\ x/ \ """ ucode_str = """\ ⎛ 1⎞ \n\ ⎜x ↦ ─⎟˳(n⋅X)\n\ ⎝ x⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_dotproduct(): from sympy.matrices.expressions.dotproduct import DotProduct n = symbols("n", integer=True) A = MatrixSymbol('A', n, 1) B = MatrixSymbol('B', n, 1) C = Matrix(1, 3, [1, 2, 3]) D = Matrix(1, 3, [1, 3, 4]) assert pretty(DotProduct(A, B)) == "A*B" assert pretty(DotProduct(C, D)) == "[1 2 3]*[1 3 4]" assert upretty(DotProduct(A, B)) == "A⋅B" assert upretty(DotProduct(C, D)) == "[1 2 3]⋅[1 3 4]" def test_pretty_piecewise(): expr = Piecewise((x, x < 1), (x**2, True)) ascii_str = \ """\ /x for x < 1\n\ | \n\ < 2 \n\ |x otherwise\n\ \\ \ """ ucode_str = \ """\ ⎧x for x < 1\n\ ⎪ \n\ ⎨ 2 \n\ ⎪x otherwise\n\ ⎩ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -Piecewise((x, x < 1), (x**2, True)) ascii_str = \ """\ //x for x < 1\\\n\ || |\n\ -|< 2 |\n\ ||x otherwise|\n\ \\\\ /\ """ ucode_str = \ """\ ⎛⎧x for x < 1⎞\n\ ⎜⎪ ⎟\n\ -⎜⎨ 2 ⎟\n\ ⎜⎪x otherwise⎟\n\ ⎝⎩ ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = x + Piecewise((x, x > 0), (y, True)) + Piecewise((x/y, x < 2), (y**2, x > 2), (1, True)) + 1 ascii_str = \ """\ //x \\ \n\ ||- for x < 2| \n\ ||y | \n\ //x for x > 0\\ || | \n\ x + |< | + |< 2 | + 1\n\ \\\\y otherwise/ ||y for x > 2| \n\ || | \n\ ||1 otherwise| \n\ \\\\ / \ """ ucode_str = \ """\ ⎛⎧x ⎞ \n\ ⎜⎪─ for x < 2⎟ \n\ ⎜⎪y ⎟ \n\ ⎛⎧x for x > 0⎞ ⎜⎪ ⎟ \n\ x + ⎜⎨ ⎟ + ⎜⎨ 2 ⎟ + 1\n\ ⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟ \n\ ⎜⎪ ⎟ \n\ ⎜⎪1 otherwise⎟ \n\ ⎝⎩ ⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = x - Piecewise((x, x > 0), (y, True)) + Piecewise((x/y, x < 2), (y**2, x > 2), (1, True)) + 1 ascii_str = \ """\ //x \\ \n\ ||- for x < 2| \n\ ||y | \n\ //x for x > 0\\ || | \n\ x - |< | + |< 2 | + 1\n\ \\\\y otherwise/ ||y for x > 2| \n\ || | \n\ ||1 otherwise| \n\ \\\\ / \ """ ucode_str = \ """\ ⎛⎧x ⎞ \n\ ⎜⎪─ for x < 2⎟ \n\ ⎜⎪y ⎟ \n\ ⎛⎧x for x > 0⎞ ⎜⎪ ⎟ \n\ x - ⎜⎨ ⎟ + ⎜⎨ 2 ⎟ + 1\n\ ⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟ \n\ ⎜⎪ ⎟ \n\ ⎜⎪1 otherwise⎟ \n\ ⎝⎩ ⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = x*Piecewise((x, x > 0), (y, True)) ascii_str = \ """\ //x for x > 0\\\n\ x*|< |\n\ \\\\y otherwise/\ """ ucode_str = \ """\ ⎛⎧x for x > 0⎞\n\ x⋅⎜⎨ ⎟\n\ ⎝⎩y otherwise⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Piecewise((x, x > 0), (y, True))*Piecewise((x/y, x < 2), (y**2, x > 2), (1, True)) ascii_str = \ """\ //x \\\n\ ||- for x < 2|\n\ ||y |\n\ //x for x > 0\\ || |\n\ |< |*|< 2 |\n\ \\\\y otherwise/ ||y for x > 2|\n\ || |\n\ ||1 otherwise|\n\ \\\\ /\ """ ucode_str = \ """\ ⎛⎧x ⎞\n\ ⎜⎪─ for x < 2⎟\n\ ⎜⎪y ⎟\n\ ⎛⎧x for x > 0⎞ ⎜⎪ ⎟\n\ ⎜⎨ ⎟⋅⎜⎨ 2 ⎟\n\ ⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟\n\ ⎜⎪ ⎟\n\ ⎜⎪1 otherwise⎟\n\ ⎝⎩ ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -Piecewise((x, x > 0), (y, True))*Piecewise((x/y, x < 2), (y**2, x > 2), (1, True)) ascii_str = \ """\ //x \\\n\ ||- for x < 2|\n\ ||y |\n\ //x for x > 0\\ || |\n\ -|< |*|< 2 |\n\ \\\\y otherwise/ ||y for x > 2|\n\ || |\n\ ||1 otherwise|\n\ \\\\ /\ """ ucode_str = \ """\ ⎛⎧x ⎞\n\ ⎜⎪─ for x < 2⎟\n\ ⎜⎪y ⎟\n\ ⎛⎧x for x > 0⎞ ⎜⎪ ⎟\n\ -⎜⎨ ⎟⋅⎜⎨ 2 ⎟\n\ ⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟\n\ ⎜⎪ ⎟\n\ ⎜⎪1 otherwise⎟\n\ ⎝⎩ ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Piecewise((0, Abs(1/y) < 1), (1, Abs(y) < 1), (y*meijerg(((2, 1), ()), ((), (1, 0)), 1/y), True)) ascii_str = \ """\ / 1 \n\ | 0 for --- < 1\n\ | |y| \n\ | \n\ < 1 for |y| < 1\n\ | \n\ | __0, 2 /2, 1 | 1\\ \n\ |y*/__ | | -| otherwise \n\ \\ \\_|2, 2 \\ 1, 0 | y/ \ """ ucode_str = \ """\ ⎧ 1 \n\ ⎪ 0 for ─── < 1\n\ ⎪ │y│ \n\ ⎪ \n\ ⎨ 1 for │y│ < 1\n\ ⎪ \n\ ⎪ ╭─╮0, 2 ⎛2, 1 │ 1⎞ \n\ ⎪y⋅│╶┐ ⎜ │ ─⎟ otherwise \n\ ⎩ ╰─╯2, 2 ⎝ 1, 0 │ y⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str # XXX: We have to use evaluate=False here because Piecewise._eval_power # denests the power. expr = Pow(Piecewise((x, x > 0), (y, True)), 2, evaluate=False) ascii_str = \ """\ 2\n\ //x for x > 0\\ \n\ |< | \n\ \\\\y otherwise/ \ """ ucode_str = \ """\ 2\n\ ⎛⎧x for x > 0⎞ \n\ ⎜⎨ ⎟ \n\ ⎝⎩y otherwise⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_ITE(): expr = ITE(x, y, z) assert pretty(expr) == ( '/y for x \n' '< \n' '\\z otherwise' ) assert upretty(expr) == """\ ⎧y for x \n\ ⎨ \n\ ⎩z otherwise\ """ def test_pretty_seq(): expr = () ascii_str = \ """\ ()\ """ ucode_str = \ """\ ()\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = [] ascii_str = \ """\ []\ """ ucode_str = \ """\ []\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = {} expr_2 = {} ascii_str = \ """\ {}\ """ ucode_str = \ """\ {}\ """ assert pretty(expr) == ascii_str assert pretty(expr_2) == ascii_str assert upretty(expr) == ucode_str assert upretty(expr_2) == ucode_str expr = (1/x,) ascii_str = \ """\ 1 \n\ (-,)\n\ x \ """ ucode_str = \ """\ ⎛1 ⎞\n\ ⎜─,⎟\n\ ⎝x ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = [x**2, 1/x, x, y, sin(th)**2/cos(ph)**2] ascii_str = \ """\ 2 \n\ 2 1 sin (theta) \n\ [x , -, x, y, -----------]\n\ x 2 \n\ cos (phi) \ """ ucode_str = \ """\ ⎡ 2 ⎤\n\ ⎢ 2 1 sin (θ)⎥\n\ ⎢x , ─, x, y, ───────⎥\n\ ⎢ x 2 ⎥\n\ ⎣ cos (φ)⎦\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (x**2, 1/x, x, y, sin(th)**2/cos(ph)**2) ascii_str = \ """\ 2 \n\ 2 1 sin (theta) \n\ (x , -, x, y, -----------)\n\ x 2 \n\ cos (phi) \ """ ucode_str = \ """\ ⎛ 2 ⎞\n\ ⎜ 2 1 sin (θ)⎟\n\ ⎜x , ─, x, y, ───────⎟\n\ ⎜ x 2 ⎟\n\ ⎝ cos (φ)⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Tuple(x**2, 1/x, x, y, sin(th)**2/cos(ph)**2) ascii_str = \ """\ 2 \n\ 2 1 sin (theta) \n\ (x , -, x, y, -----------)\n\ x 2 \n\ cos (phi) \ """ ucode_str = \ """\ ⎛ 2 ⎞\n\ ⎜ 2 1 sin (θ)⎟\n\ ⎜x , ─, x, y, ───────⎟\n\ ⎜ x 2 ⎟\n\ ⎝ cos (φ)⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = {x: sin(x)} expr_2 = Dict({x: sin(x)}) ascii_str = \ """\ {x: sin(x)}\ """ ucode_str = \ """\ {x: sin(x)}\ """ assert pretty(expr) == ascii_str assert pretty(expr_2) == ascii_str assert upretty(expr) == ucode_str assert upretty(expr_2) == ucode_str expr = {1/x: 1/y, x: sin(x)**2} expr_2 = Dict({1/x: 1/y, x: sin(x)**2}) ascii_str = \ """\ 1 1 2 \n\ {-: -, x: sin (x)}\n\ x y \ """ ucode_str = \ """\ ⎧1 1 2 ⎫\n\ ⎨─: ─, x: sin (x)⎬\n\ ⎩x y ⎭\ """ assert pretty(expr) == ascii_str assert pretty(expr_2) == ascii_str assert upretty(expr) == ucode_str assert upretty(expr_2) == ucode_str # There used to be a bug with pretty-printing sequences of even height. expr = [x**2] ascii_str = \ """\ 2 \n\ [x ]\ """ ucode_str = \ """\ ⎡ 2⎤\n\ ⎣x ⎦\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (x**2,) ascii_str = \ """\ 2 \n\ (x ,)\ """ ucode_str = \ """\ ⎛ 2 ⎞\n\ ⎝x ,⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Tuple(x**2) ascii_str = \ """\ 2 \n\ (x ,)\ """ ucode_str = \ """\ ⎛ 2 ⎞\n\ ⎝x ,⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = {x**2: 1} expr_2 = Dict({x**2: 1}) ascii_str = \ """\ 2 \n\ {x : 1}\ """ ucode_str = \ """\ ⎧ 2 ⎫\n\ ⎨x : 1⎬\n\ ⎩ ⎭\ """ assert pretty(expr) == ascii_str assert pretty(expr_2) == ascii_str assert upretty(expr) == ucode_str assert upretty(expr_2) == ucode_str def test_any_object_in_sequence(): # Cf. issue 5306 b1 = Basic() b2 = Basic(Basic()) expr = [b2, b1] assert pretty(expr) == "[Basic(Basic()), Basic()]" assert upretty(expr) == "[Basic(Basic()), Basic()]" expr = {b2, b1} assert pretty(expr) == "{Basic(), Basic(Basic())}" assert upretty(expr) == "{Basic(), Basic(Basic())}" expr = {b2: b1, b1: b2} expr2 = Dict({b2: b1, b1: b2}) assert pretty(expr) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}" assert pretty( expr2) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}" assert upretty( expr) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}" assert upretty( expr2) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}" def test_print_builtin_set(): assert pretty(set()) == 'set()' assert upretty(set()) == 'set()' assert pretty(frozenset()) == 'frozenset()' assert upretty(frozenset()) == 'frozenset()' s1 = {1/x, x} s2 = frozenset(s1) assert pretty(s1) == \ """\ 1 \n\ {-, x} x \ """ assert upretty(s1) == \ """\ ⎧1 ⎫ ⎨─, x⎬ ⎩x ⎭\ """ assert pretty(s2) == \ """\ 1 \n\ frozenset({-, x}) x \ """ assert upretty(s2) == \ """\ ⎛⎧1 ⎫⎞ frozenset⎜⎨─, x⎬⎟ ⎝⎩x ⎭⎠\ """ def test_pretty_sets(): s = FiniteSet assert pretty(s(*[x*y, x**2])) == \ """\ 2 \n\ {x , x*y}\ """ assert pretty(s(*range(1, 6))) == "{1, 2, 3, 4, 5}" assert pretty(s(*range(1, 13))) == "{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}" assert pretty({x*y, x**2}) == \ """\ 2 \n\ {x , x*y}\ """ assert pretty(set(range(1, 6))) == "{1, 2, 3, 4, 5}" assert pretty(set(range(1, 13))) == \ "{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}" assert pretty(frozenset([x*y, x**2])) == \ """\ 2 \n\ frozenset({x , x*y})\ """ assert pretty(frozenset(range(1, 6))) == "frozenset({1, 2, 3, 4, 5})" assert pretty(frozenset(range(1, 13))) == \ "frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12})" assert pretty(Range(0, 3, 1)) == '{0, 1, 2}' ascii_str = '{0, 1, ..., 29}' ucode_str = '{0, 1, …, 29}' assert pretty(Range(0, 30, 1)) == ascii_str assert upretty(Range(0, 30, 1)) == ucode_str ascii_str = '{30, 29, ..., 2}' ucode_str = '{30, 29, …, 2}' assert pretty(Range(30, 1, -1)) == ascii_str assert upretty(Range(30, 1, -1)) == ucode_str ascii_str = '{0, 2, ...}' ucode_str = '{0, 2, …}' assert pretty(Range(0, oo, 2)) == ascii_str assert upretty(Range(0, oo, 2)) == ucode_str ascii_str = '{..., 2, 0}' ucode_str = '{…, 2, 0}' assert pretty(Range(oo, -2, -2)) == ascii_str assert upretty(Range(oo, -2, -2)) == ucode_str ascii_str = '{-2, -3, ...}' ucode_str = '{-2, -3, …}' assert pretty(Range(-2, -oo, -1)) == ascii_str assert upretty(Range(-2, -oo, -1)) == ucode_str def test_pretty_SetExpr(): iv = Interval(1, 3) se = SetExpr(iv) ascii_str = "SetExpr([1, 3])" ucode_str = "SetExpr([1, 3])" assert pretty(se) == ascii_str assert upretty(se) == ucode_str def test_pretty_ImageSet(): imgset = ImageSet(Lambda((x, y), x + y), {1, 2, 3}, {3, 4}) ascii_str = '{x + y | x in {1, 2, 3}, y in {3, 4}}' ucode_str = '{x + y │ x ∊ {1, 2, 3}, y ∊ {3, 4}}' assert pretty(imgset) == ascii_str assert upretty(imgset) == ucode_str imgset = ImageSet(Lambda(((x, y),), x + y), ProductSet({1, 2, 3}, {3, 4})) ascii_str = '{x + y | (x, y) in {1, 2, 3} x {3, 4}}' ucode_str = '{x + y │ (x, y) ∊ {1, 2, 3} × {3, 4}}' assert pretty(imgset) == ascii_str assert upretty(imgset) == ucode_str imgset = ImageSet(Lambda(x, x**2), S.Naturals) ascii_str = '''\ 2 \n\ {x | x in Naturals}''' ucode_str = '''\ ⎧ 2 │ ⎫\n\ ⎨x │ x ∊ ℕ⎬\n\ ⎩ │ ⎭''' assert pretty(imgset) == ascii_str assert upretty(imgset) == ucode_str # TODO: The "x in N" parts below should be centered independently of the # 1/x**2 fraction imgset = ImageSet(Lambda(x, 1/x**2), S.Naturals) ascii_str = '''\ 1 \n\ {-- | x in Naturals} 2 \n\ x ''' ucode_str = '''\ ⎧1 │ ⎫\n\ ⎪── │ x ∊ ℕ⎪\n\ ⎨ 2 │ ⎬\n\ ⎪x │ ⎪\n\ ⎩ │ ⎭''' assert pretty(imgset) == ascii_str assert upretty(imgset) == ucode_str imgset = ImageSet(Lambda((x, y), 1/(x + y)**2), S.Naturals, S.Naturals) ascii_str = '''\ 1 \n\ {-------- | x in Naturals, y in Naturals} 2 \n\ (x + y) ''' ucode_str = '''\ ⎧ 1 │ ⎫ ⎪──────── │ x ∊ ℕ, y ∊ ℕ⎪ ⎨ 2 │ ⎬ ⎪(x + y) │ ⎪ ⎩ │ ⎭''' assert pretty(imgset) == ascii_str assert upretty(imgset) == ucode_str def test_pretty_ConditionSet(): ascii_str = '{x | x in (-oo, oo) and sin(x) = 0}' ucode_str = '{x │ x ∊ ℝ ∧ (sin(x) = 0)}' assert pretty(ConditionSet(x, Eq(sin(x), 0), S.Reals)) == ascii_str assert upretty(ConditionSet(x, Eq(sin(x), 0), S.Reals)) == ucode_str assert pretty(ConditionSet(x, Contains(x, S.Reals, evaluate=False), FiniteSet(1))) == '{1}' assert upretty(ConditionSet(x, Contains(x, S.Reals, evaluate=False), FiniteSet(1))) == '{1}' assert pretty(ConditionSet(x, And(x > 1, x < -1), FiniteSet(1, 2, 3))) == "EmptySet" assert upretty(ConditionSet(x, And(x > 1, x < -1), FiniteSet(1, 2, 3))) == "∅" assert pretty(ConditionSet(x, Or(x > 1, x < -1), FiniteSet(1, 2))) == '{2}' assert upretty(ConditionSet(x, Or(x > 1, x < -1), FiniteSet(1, 2))) == '{2}' condset = ConditionSet(x, 1/x**2 > 0) ascii_str = '''\ 1 \n\ {x | -- > 0} 2 \n\ x ''' ucode_str = '''\ ⎧ │ ⎛1 ⎞⎫ ⎪x │ ⎜── > 0⎟⎪ ⎨ │ ⎜ 2 ⎟⎬ ⎪ │ ⎝x ⎠⎪ ⎩ │ ⎭''' assert pretty(condset) == ascii_str assert upretty(condset) == ucode_str condset = ConditionSet(x, 1/x**2 > 0, S.Reals) ascii_str = '''\ 1 \n\ {x | x in (-oo, oo) and -- > 0} 2 \n\ x ''' ucode_str = '''\ ⎧ │ ⎛1 ⎞⎫ ⎪x │ x ∊ ℝ ∧ ⎜── > 0⎟⎪ ⎨ │ ⎜ 2 ⎟⎬ ⎪ │ ⎝x ⎠⎪ ⎩ │ ⎭''' assert pretty(condset) == ascii_str assert upretty(condset) == ucode_str def test_pretty_ComplexRegion(): from sympy.sets.fancysets import ComplexRegion cregion = ComplexRegion(Interval(3, 5)*Interval(4, 6)) ascii_str = '{x + y*I | x, y in [3, 5] x [4, 6]}' ucode_str = '{x + y⋅ⅈ │ x, y ∊ [3, 5] × [4, 6]}' assert pretty(cregion) == ascii_str assert upretty(cregion) == ucode_str cregion = ComplexRegion(Interval(0, 1)*Interval(0, 2*pi), polar=True) ascii_str = '{r*(I*sin(theta) + cos(theta)) | r, theta in [0, 1] x [0, 2*pi)}' ucode_str = '{r⋅(ⅈ⋅sin(θ) + cos(θ)) │ r, θ ∊ [0, 1] × [0, 2⋅π)}' assert pretty(cregion) == ascii_str assert upretty(cregion) == ucode_str cregion = ComplexRegion(Interval(3, 1/a**2)*Interval(4, 6)) ascii_str = '''\ 1 \n\ {x + y*I | x, y in [3, --] x [4, 6]} 2 \n\ a ''' ucode_str = '''\ ⎧ │ ⎡ 1 ⎤ ⎫ ⎪x + y⋅ⅈ │ x, y ∊ ⎢3, ──⎥ × [4, 6]⎪ ⎨ │ ⎢ 2⎥ ⎬ ⎪ │ ⎣ a ⎦ ⎪ ⎩ │ ⎭''' assert pretty(cregion) == ascii_str assert upretty(cregion) == ucode_str cregion = ComplexRegion(Interval(0, 1/a**2)*Interval(0, 2*pi), polar=True) ascii_str = '''\ 1 \n\ {r*(I*sin(theta) + cos(theta)) | r, theta in [0, --] x [0, 2*pi)} 2 \n\ a ''' ucode_str = '''\ ⎧ │ ⎡ 1 ⎤ ⎫ ⎪r⋅(ⅈ⋅sin(θ) + cos(θ)) │ r, θ ∊ ⎢0, ──⎥ × [0, 2⋅π)⎪ ⎨ │ ⎢ 2⎥ ⎬ ⎪ │ ⎣ a ⎦ ⎪ ⎩ │ ⎭''' assert pretty(cregion) == ascii_str assert upretty(cregion) == ucode_str def test_pretty_Union_issue_10414(): a, b = Interval(2, 3), Interval(4, 7) ucode_str = '[2, 3] ∪ [4, 7]' ascii_str = '[2, 3] U [4, 7]' assert upretty(Union(a, b)) == ucode_str assert pretty(Union(a, b)) == ascii_str def test_pretty_Intersection_issue_10414(): x, y, z, w = symbols('x, y, z, w') a, b = Interval(x, y), Interval(z, w) ucode_str = '[x, y] ∩ [z, w]' ascii_str = '[x, y] n [z, w]' assert upretty(Intersection(a, b)) == ucode_str assert pretty(Intersection(a, b)) == ascii_str def test_ProductSet_exponent(): ucode_str = ' 1\n[0, 1] ' assert upretty(Interval(0, 1)**1) == ucode_str ucode_str = ' 2\n[0, 1] ' assert upretty(Interval(0, 1)**2) == ucode_str def test_ProductSet_parenthesis(): ucode_str = '([4, 7] × {1, 2}) ∪ ([2, 3] × [4, 7])' a, b = Interval(2, 3), Interval(4, 7) assert upretty(Union(a*b, b*FiniteSet(1, 2))) == ucode_str def test_ProductSet_prod_char_issue_10413(): ascii_str = '[2, 3] x [4, 7]' ucode_str = '[2, 3] × [4, 7]' a, b = Interval(2, 3), Interval(4, 7) assert pretty(a*b) == ascii_str assert upretty(a*b) == ucode_str def test_pretty_sequences(): s1 = SeqFormula(a**2, (0, oo)) s2 = SeqPer((1, 2)) ascii_str = '[0, 1, 4, 9, ...]' ucode_str = '[0, 1, 4, 9, …]' assert pretty(s1) == ascii_str assert upretty(s1) == ucode_str ascii_str = '[1, 2, 1, 2, ...]' ucode_str = '[1, 2, 1, 2, …]' assert pretty(s2) == ascii_str assert upretty(s2) == ucode_str s3 = SeqFormula(a**2, (0, 2)) s4 = SeqPer((1, 2), (0, 2)) ascii_str = '[0, 1, 4]' ucode_str = '[0, 1, 4]' assert pretty(s3) == ascii_str assert upretty(s3) == ucode_str ascii_str = '[1, 2, 1]' ucode_str = '[1, 2, 1]' assert pretty(s4) == ascii_str assert upretty(s4) == ucode_str s5 = SeqFormula(a**2, (-oo, 0)) s6 = SeqPer((1, 2), (-oo, 0)) ascii_str = '[..., 9, 4, 1, 0]' ucode_str = '[…, 9, 4, 1, 0]' assert pretty(s5) == ascii_str assert upretty(s5) == ucode_str ascii_str = '[..., 2, 1, 2, 1]' ucode_str = '[…, 2, 1, 2, 1]' assert pretty(s6) == ascii_str assert upretty(s6) == ucode_str ascii_str = '[1, 3, 5, 11, ...]' ucode_str = '[1, 3, 5, 11, …]' assert pretty(SeqAdd(s1, s2)) == ascii_str assert upretty(SeqAdd(s1, s2)) == ucode_str ascii_str = '[1, 3, 5]' ucode_str = '[1, 3, 5]' assert pretty(SeqAdd(s3, s4)) == ascii_str assert upretty(SeqAdd(s3, s4)) == ucode_str ascii_str = '[..., 11, 5, 3, 1]' ucode_str = '[…, 11, 5, 3, 1]' assert pretty(SeqAdd(s5, s6)) == ascii_str assert upretty(SeqAdd(s5, s6)) == ucode_str ascii_str = '[0, 2, 4, 18, ...]' ucode_str = '[0, 2, 4, 18, …]' assert pretty(SeqMul(s1, s2)) == ascii_str assert upretty(SeqMul(s1, s2)) == ucode_str ascii_str = '[0, 2, 4]' ucode_str = '[0, 2, 4]' assert pretty(SeqMul(s3, s4)) == ascii_str assert upretty(SeqMul(s3, s4)) == ucode_str ascii_str = '[..., 18, 4, 2, 0]' ucode_str = '[…, 18, 4, 2, 0]' assert pretty(SeqMul(s5, s6)) == ascii_str assert upretty(SeqMul(s5, s6)) == ucode_str # Sequences with symbolic limits, issue 12629 s7 = SeqFormula(a**2, (a, 0, x)) raises(NotImplementedError, lambda: pretty(s7)) raises(NotImplementedError, lambda: upretty(s7)) b = Symbol('b') s8 = SeqFormula(b*a**2, (a, 0, 2)) ascii_str = '[0, b, 4*b]' ucode_str = '[0, b, 4⋅b]' assert pretty(s8) == ascii_str assert upretty(s8) == ucode_str def test_pretty_FourierSeries(): f = fourier_series(x, (x, -pi, pi)) ascii_str = \ """\ 2*sin(3*x) \n\ 2*sin(x) - sin(2*x) + ---------- + ...\n\ 3 \ """ ucode_str = \ """\ 2⋅sin(3⋅x) \n\ 2⋅sin(x) - sin(2⋅x) + ────────── + …\n\ 3 \ """ assert pretty(f) == ascii_str assert upretty(f) == ucode_str def test_pretty_FormalPowerSeries(): f = fps(log(1 + x)) ascii_str = \ """\ oo \n\ ____ \n\ \\ ` \n\ \\ -k k \n\ \\ -(-1) *x \n\ / -----------\n\ / k \n\ /___, \n\ k = 1 \ """ ucode_str = \ """\ ∞ \n\ ____ \n\ ╲ \n\ ╲ -k k \n\ ╲ -(-1) ⋅x \n\ ╱ ───────────\n\ ╱ k \n\ ╱ \n\ ‾‾‾‾ \n\ k = 1 \ """ assert pretty(f) == ascii_str assert upretty(f) == ucode_str def test_pretty_limits(): expr = Limit(x, x, oo) ascii_str = \ """\ lim x\n\ x->oo \ """ ucode_str = \ """\ lim x\n\ x─→∞ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(x**2, x, 0) ascii_str = \ """\ 2\n\ lim x \n\ x->0+ \ """ ucode_str = \ """\ 2\n\ lim x \n\ x─→0⁺ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(1/x, x, 0) ascii_str = \ """\ 1\n\ lim -\n\ x->0+x\ """ ucode_str = \ """\ 1\n\ lim ─\n\ x─→0⁺x\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(sin(x)/x, x, 0) ascii_str = \ """\ /sin(x)\\\n\ lim |------|\n\ x->0+\\ x /\ """ ucode_str = \ """\ ⎛sin(x)⎞\n\ lim ⎜──────⎟\n\ x─→0⁺⎝ x ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(sin(x)/x, x, 0, "-") ascii_str = \ """\ /sin(x)\\\n\ lim |------|\n\ x->0-\\ x /\ """ ucode_str = \ """\ ⎛sin(x)⎞\n\ lim ⎜──────⎟\n\ x─→0⁻⎝ x ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(x + sin(x), x, 0) ascii_str = \ """\ lim (x + sin(x))\n\ x->0+ \ """ ucode_str = \ """\ lim (x + sin(x))\n\ x─→0⁺ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(x, x, 0)**2 ascii_str = \ """\ 2\n\ / lim x\\ \n\ \\x->0+ / \ """ ucode_str = \ """\ 2\n\ ⎛ lim x⎞ \n\ ⎝x─→0⁺ ⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(x*Limit(y/2,y,0), x, 0) ascii_str = \ """\ / /y\\\\\n\ lim |x* lim |-||\n\ x->0+\\ y->0+\\2//\ """ ucode_str = \ """\ ⎛ ⎛y⎞⎞\n\ lim ⎜x⋅ lim ⎜─⎟⎟\n\ x─→0⁺⎝ y─→0⁺⎝2⎠⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2*Limit(x*Limit(y/2,y,0), x, 0) ascii_str = \ """\ / /y\\\\\n\ 2* lim |x* lim |-||\n\ x->0+\\ y->0+\\2//\ """ ucode_str = \ """\ ⎛ ⎛y⎞⎞\n\ 2⋅ lim ⎜x⋅ lim ⎜─⎟⎟\n\ x─→0⁺⎝ y─→0⁺⎝2⎠⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(sin(x), x, 0, dir='+-') ascii_str = \ """\ lim sin(x)\n\ x->0 \ """ ucode_str = \ """\ lim sin(x)\n\ x─→0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_ComplexRootOf(): expr = rootof(x**5 + 11*x - 2, 0) ascii_str = \ """\ / 5 \\\n\ CRootOf\\x + 11*x - 2, 0/\ """ ucode_str = \ """\ ⎛ 5 ⎞\n\ CRootOf⎝x + 11⋅x - 2, 0⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_RootSum(): expr = RootSum(x**5 + 11*x - 2, auto=False) ascii_str = \ """\ / 5 \\\n\ RootSum\\x + 11*x - 2/\ """ ucode_str = \ """\ ⎛ 5 ⎞\n\ RootSum⎝x + 11⋅x - 2⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = RootSum(x**5 + 11*x - 2, Lambda(z, exp(z))) ascii_str = \ """\ / 5 z\\\n\ RootSum\\x + 11*x - 2, z -> e /\ """ ucode_str = \ """\ ⎛ 5 z⎞\n\ RootSum⎝x + 11⋅x - 2, z ↦ ℯ ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_GroebnerBasis(): expr = groebner([], x, y) ascii_str = \ """\ GroebnerBasis([], x, y, domain=ZZ, order=lex)\ """ ucode_str = \ """\ GroebnerBasis([], x, y, domain=ℤ, order=lex)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1] expr = groebner(F, x, y, order='grlex') ascii_str = \ """\ /[ 2 2 ] \\\n\ GroebnerBasis\\[x - x - 3*y + 1, y - 2*x + y - 1], x, y, domain=ZZ, order=grlex/\ """ ucode_str = \ """\ ⎛⎡ 2 2 ⎤ ⎞\n\ GroebnerBasis⎝⎣x - x - 3⋅y + 1, y - 2⋅x + y - 1⎦, x, y, domain=ℤ, order=grlex⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = expr.fglm('lex') ascii_str = \ """\ /[ 2 4 3 2 ] \\\n\ GroebnerBasis\\[2*x - y - y + 1, y + 2*y - 3*y - 16*y + 7], x, y, domain=ZZ, order=lex/\ """ ucode_str = \ """\ ⎛⎡ 2 4 3 2 ⎤ ⎞\n\ GroebnerBasis⎝⎣2⋅x - y - y + 1, y + 2⋅y - 3⋅y - 16⋅y + 7⎦, x, y, domain=ℤ, order=lex⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_UniversalSet(): assert pretty(S.UniversalSet) == "UniversalSet" assert upretty(S.UniversalSet) == '𝕌' def test_pretty_Boolean(): expr = Not(x, evaluate=False) assert pretty(expr) == "Not(x)" assert upretty(expr) == "¬x" expr = And(x, y) assert pretty(expr) == "And(x, y)" assert upretty(expr) == "x ∧ y" expr = Or(x, y) assert pretty(expr) == "Or(x, y)" assert upretty(expr) == "x ∨ y" syms = symbols('a:f') expr = And(*syms) assert pretty(expr) == "And(a, b, c, d, e, f)" assert upretty(expr) == "a ∧ b ∧ c ∧ d ∧ e ∧ f" expr = Or(*syms) assert pretty(expr) == "Or(a, b, c, d, e, f)" assert upretty(expr) == "a ∨ b ∨ c ∨ d ∨ e ∨ f" expr = Xor(x, y, evaluate=False) assert pretty(expr) == "Xor(x, y)" assert upretty(expr) == "x ⊻ y" expr = Nand(x, y, evaluate=False) assert pretty(expr) == "Nand(x, y)" assert upretty(expr) == "x ⊼ y" expr = Nor(x, y, evaluate=False) assert pretty(expr) == "Nor(x, y)" assert upretty(expr) == "x ⊽ y" expr = Implies(x, y, evaluate=False) assert pretty(expr) == "Implies(x, y)" assert upretty(expr) == "x → y" # don't sort args expr = Implies(y, x, evaluate=False) assert pretty(expr) == "Implies(y, x)" assert upretty(expr) == "y → x" expr = Equivalent(x, y, evaluate=False) assert pretty(expr) == "Equivalent(x, y)" assert upretty(expr) == "x ⇔ y" expr = Equivalent(y, x, evaluate=False) assert pretty(expr) == "Equivalent(x, y)" assert upretty(expr) == "x ⇔ y" def test_pretty_Domain(): expr = FF(23) assert pretty(expr) == "GF(23)" assert upretty(expr) == "ℤ₂₃" expr = ZZ assert pretty(expr) == "ZZ" assert upretty(expr) == "ℤ" expr = QQ assert pretty(expr) == "QQ" assert upretty(expr) == "ℚ" expr = RR assert pretty(expr) == "RR" assert upretty(expr) == "ℝ" expr = QQ[x] assert pretty(expr) == "QQ[x]" assert upretty(expr) == "ℚ[x]" expr = QQ[x, y] assert pretty(expr) == "QQ[x, y]" assert upretty(expr) == "ℚ[x, y]" expr = ZZ.frac_field(x) assert pretty(expr) == "ZZ(x)" assert upretty(expr) == "ℤ(x)" expr = ZZ.frac_field(x, y) assert pretty(expr) == "ZZ(x, y)" assert upretty(expr) == "ℤ(x, y)" expr = QQ.poly_ring(x, y, order=grlex) assert pretty(expr) == "QQ[x, y, order=grlex]" assert upretty(expr) == "ℚ[x, y, order=grlex]" expr = QQ.poly_ring(x, y, order=ilex) assert pretty(expr) == "QQ[x, y, order=ilex]" assert upretty(expr) == "ℚ[x, y, order=ilex]" def test_pretty_prec(): assert xpretty(S("0.3"), full_prec=True, wrap_line=False) == "0.300000000000000" assert xpretty(S("0.3"), full_prec="auto", wrap_line=False) == "0.300000000000000" assert xpretty(S("0.3"), full_prec=False, wrap_line=False) == "0.3" assert xpretty(S("0.3")*x, full_prec=True, use_unicode=False, wrap_line=False) in [ "0.300000000000000*x", "x*0.300000000000000" ] assert xpretty(S("0.3")*x, full_prec="auto", use_unicode=False, wrap_line=False) in [ "0.3*x", "x*0.3" ] assert xpretty(S("0.3")*x, full_prec=False, use_unicode=False, wrap_line=False) in [ "0.3*x", "x*0.3" ] def test_pprint(): import sys from io import StringIO fd = StringIO() sso = sys.stdout sys.stdout = fd try: pprint(pi, use_unicode=False, wrap_line=False) finally: sys.stdout = sso assert fd.getvalue() == 'pi\n' def test_pretty_class(): """Test that the printer dispatcher correctly handles classes.""" class C: pass # C has no .__class__ and this was causing problems class D: pass assert pretty( C ) == str( C ) assert pretty( D ) == str( D ) def test_pretty_no_wrap_line(): huge_expr = 0 for i in range(20): huge_expr += i*sin(i + x) assert xpretty(huge_expr ).find('\n') != -1 assert xpretty(huge_expr, wrap_line=False).find('\n') == -1 def test_settings(): raises(TypeError, lambda: pretty(S(4), method="garbage")) def test_pretty_sum(): from sympy.abc import x, a, b, k, m, n expr = Sum(k**k, (k, 0, n)) ascii_str = \ """\ n \n\ ___ \n\ \\ ` \n\ \\ k\n\ / k \n\ /__, \n\ k = 0 \ """ ucode_str = \ """\ n \n\ ___ \n\ ╲ \n\ ╲ k\n\ ╱ k \n\ ╱ \n\ ‾‾‾ \n\ k = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(k**k, (k, oo, n)) ascii_str = \ """\ n \n\ ___ \n\ \\ ` \n\ \\ k\n\ / k \n\ /__, \n\ k = oo \ """ ucode_str = \ """\ n \n\ ___ \n\ ╲ \n\ ╲ k\n\ ╱ k \n\ ╱ \n\ ‾‾‾ \n\ k = ∞ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(k**(Integral(x**n, (x, -oo, oo))), (k, 0, n**n)) ascii_str = \ """\ n \n\ n \n\ ______ \n\ \\ ` \n\ \\ oo \n\ \\ / \n\ \\ | \n\ \\ | n \n\ ) | x dx\n\ / | \n\ / / \n\ / -oo \n\ / k \n\ /_____, \n\ k = 0 \ """ ucode_str = \ """\ n \n\ n \n\ ______ \n\ ╲ \n\ ╲ \n\ ╲ ∞ \n\ ╲ ⌠ \n\ ╲ ⎮ n \n\ ╱ ⎮ x dx\n\ ╱ ⌡ \n\ ╱ -∞ \n\ ╱ k \n\ ╱ \n\ ‾‾‾‾‾‾ \n\ k = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(k**( Integral(x**n, (x, -oo, oo))), (k, 0, Integral(x**x, (x, -oo, oo)))) ascii_str = \ """\ oo \n\ / \n\ | \n\ | x \n\ | x dx \n\ | \n\ / \n\ -oo \n\ ______ \n\ \\ ` \n\ \\ oo \n\ \\ / \n\ \\ | \n\ \\ | n \n\ ) | x dx\n\ / | \n\ / / \n\ / -oo \n\ / k \n\ /_____, \n\ k = 0 \ """ ucode_str = \ """\ ∞ \n\ ⌠ \n\ ⎮ x \n\ ⎮ x dx \n\ ⌡ \n\ -∞ \n\ ______ \n\ ╲ \n\ ╲ \n\ ╲ ∞ \n\ ╲ ⌠ \n\ ╲ ⎮ n \n\ ╱ ⎮ x dx\n\ ╱ ⌡ \n\ ╱ -∞ \n\ ╱ k \n\ ╱ \n\ ‾‾‾‾‾‾ \n\ k = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(k**(Integral(x**n, (x, -oo, oo))), ( k, x + n + x**2 + n**2 + (x/n) + (1/x), Integral(x**x, (x, -oo, oo)))) ascii_str = \ """\ oo \n\ / \n\ | \n\ | x \n\ | x dx \n\ | \n\ / \n\ -oo \n\ ______ \n\ \\ ` \n\ \\ oo \n\ \\ / \n\ \\ | \n\ \\ | n \n\ ) | x dx\n\ / | \n\ / / \n\ / -oo \n\ / k \n\ /_____, \n\ 2 2 1 x \n\ k = n + n + x + x + - + - \n\ x n \ """ ucode_str = \ """\ ∞ \n\ ⌠ \n\ ⎮ x \n\ ⎮ x dx \n\ ⌡ \n\ -∞ \n\ ______ \n\ ╲ \n\ ╲ \n\ ╲ ∞ \n\ ╲ ⌠ \n\ ╲ ⎮ n \n\ ╱ ⎮ x dx\n\ ╱ ⌡ \n\ ╱ -∞ \n\ ╱ k \n\ ╱ \n\ ‾‾‾‾‾‾ \n\ 2 2 1 x \n\ k = n + n + x + x + ─ + ─ \n\ x n \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(k**( Integral(x**n, (x, -oo, oo))), (k, 0, x + n + x**2 + n**2 + (x/n) + (1/x))) ascii_str = \ """\ 2 2 1 x \n\ n + n + x + x + - + - \n\ x n \n\ ______ \n\ \\ ` \n\ \\ oo \n\ \\ / \n\ \\ | \n\ \\ | n \n\ ) | x dx\n\ / | \n\ / / \n\ / -oo \n\ / k \n\ /_____, \n\ k = 0 \ """ ucode_str = \ """\ 2 2 1 x \n\ n + n + x + x + ─ + ─ \n\ x n \n\ ______ \n\ ╲ \n\ ╲ \n\ ╲ ∞ \n\ ╲ ⌠ \n\ ╲ ⎮ n \n\ ╱ ⎮ x dx\n\ ╱ ⌡ \n\ ╱ -∞ \n\ ╱ k \n\ ╱ \n\ ‾‾‾‾‾‾ \n\ k = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(x, (x, 0, oo)) ascii_str = \ """\ oo \n\ __ \n\ \\ ` \n\ ) x\n\ /_, \n\ x = 0 \ """ ucode_str = \ """\ ∞ \n\ ___ \n\ ╲ \n\ ╲ \n\ ╱ x\n\ ╱ \n\ ‾‾‾ \n\ x = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(x**2, (x, 0, oo)) ascii_str = \ """\ oo \n\ ___ \n\ \\ ` \n\ \\ 2\n\ / x \n\ /__, \n\ x = 0 \ """ ucode_str = \ """\ ∞ \n\ ___ \n\ ╲ \n\ ╲ 2\n\ ╱ x \n\ ╱ \n\ ‾‾‾ \n\ x = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(x/2, (x, 0, oo)) ascii_str = \ """\ oo \n\ ___ \n\ \\ ` \n\ \\ x\n\ ) -\n\ / 2\n\ /__, \n\ x = 0 \ """ ucode_str = \ """\ ∞ \n\ ____ \n\ ╲ \n\ ╲ \n\ ╲ x\n\ ╱ ─\n\ ╱ 2\n\ ╱ \n\ ‾‾‾‾ \n\ x = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(x**3/2, (x, 0, oo)) ascii_str = \ """\ oo \n\ ____ \n\ \\ ` \n\ \\ 3\n\ \\ x \n\ / --\n\ / 2 \n\ /___, \n\ x = 0 \ """ ucode_str = \ """\ ∞ \n\ ____ \n\ ╲ \n\ ╲ 3\n\ ╲ x \n\ ╱ ──\n\ ╱ 2 \n\ ╱ \n\ ‾‾‾‾ \n\ x = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum((x**3*y**(x/2))**n, (x, 0, oo)) ascii_str = \ """\ oo \n\ ____ \n\ \\ ` \n\ \\ n\n\ \\ / x\\ \n\ ) | -| \n\ / | 3 2| \n\ / \\x *y / \n\ /___, \n\ x = 0 \ """ ucode_str = \ """\ ∞ \n\ _____ \n\ ╲ \n\ ╲ \n\ ╲ n\n\ ╲ ⎛ x⎞ \n\ ╱ ⎜ ─⎟ \n\ ╱ ⎜ 3 2⎟ \n\ ╱ ⎝x ⋅y ⎠ \n\ ╱ \n\ ‾‾‾‾‾ \n\ x = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(1/x**2, (x, 0, oo)) ascii_str = \ """\ oo \n\ ____ \n\ \\ ` \n\ \\ 1 \n\ \\ --\n\ / 2\n\ / x \n\ /___, \n\ x = 0 \ """ ucode_str = \ """\ ∞ \n\ ____ \n\ ╲ \n\ ╲ 1 \n\ ╲ ──\n\ ╱ 2\n\ ╱ x \n\ ╱ \n\ ‾‾‾‾ \n\ x = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(1/y**(a/b), (x, 0, oo)) ascii_str = \ """\ oo \n\ ____ \n\ \\ ` \n\ \\ -a \n\ \\ ---\n\ / b \n\ / y \n\ /___, \n\ x = 0 \ """ ucode_str = \ """\ ∞ \n\ ____ \n\ ╲ \n\ ╲ -a \n\ ╲ ───\n\ ╱ b \n\ ╱ y \n\ ╱ \n\ ‾‾‾‾ \n\ x = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(1/y**(a/b), (x, 0, oo), (y, 1, 2)) ascii_str = \ """\ 2 oo \n\ ____ ____ \n\ \\ ` \\ ` \n\ \\ \\ -a\n\ \\ \\ --\n\ / / b \n\ / / y \n\ /___, /___, \n\ y = 1 x = 0 \ """ ucode_str = \ """\ 2 ∞ \n\ ____ ____ \n\ ╲ ╲ \n\ ╲ ╲ -a\n\ ╲ ╲ ──\n\ ╱ ╱ b \n\ ╱ ╱ y \n\ ╱ ╱ \n\ ‾‾‾‾ ‾‾‾‾ \n\ y = 1 x = 0 \ """ expr = Sum(1/(1 + 1/( 1 + 1/k)) + 1, (k, 111, 1 + 1/n), (k, 1/(1 + m), oo)) + 1/(1 + 1/k) ascii_str = \ """\ 1 \n\ 1 + - \n\ oo n \n\ _____ _____ \n\ \\ ` \\ ` \n\ \\ \\ / 1 \\ \n\ \\ \\ |1 + ---------| \n\ \\ \\ | 1 | 1 \n\ ) ) | 1 + -----| + -----\n\ / / | 1| 1\n\ / / | 1 + -| 1 + -\n\ / / \\ k/ k\n\ /____, /____, \n\ 1 k = 111 \n\ k = ----- \n\ m + 1 \ """ ucode_str = \ """\ 1 \n\ 1 + ─ \n\ ∞ n \n\ ______ ______ \n\ ╲ ╲ \n\ ╲ ╲ \n\ ╲ ╲ ⎛ 1 ⎞ \n\ ╲ ╲ ⎜1 + ─────────⎟ \n\ ╲ ╲ ⎜ 1 ⎟ 1 \n\ ╱ ╱ ⎜ 1 + ─────⎟ + ─────\n\ ╱ ╱ ⎜ 1⎟ 1\n\ ╱ ╱ ⎜ 1 + ─⎟ 1 + ─\n\ ╱ ╱ ⎝ k⎠ k\n\ ╱ ╱ \n\ ‾‾‾‾‾‾ ‾‾‾‾‾‾ \n\ 1 k = 111 \n\ k = ───── \n\ m + 1 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_units(): expr = joule ascii_str1 = \ """\ 2\n\ kilogram*meter \n\ ---------------\n\ 2 \n\ second \ """ unicode_str1 = \ """\ 2\n\ kilogram⋅meter \n\ ───────────────\n\ 2 \n\ second \ """ ascii_str2 = \ """\ 2\n\ 3*x*y*kilogram*meter \n\ ---------------------\n\ 2 \n\ second \ """ unicode_str2 = \ """\ 2\n\ 3⋅x⋅y⋅kilogram⋅meter \n\ ─────────────────────\n\ 2 \n\ second \ """ from sympy.physics.units import kg, m, s assert upretty(expr) == "joule" assert pretty(expr) == "joule" assert upretty(expr.convert_to(kg*m**2/s**2)) == unicode_str1 assert pretty(expr.convert_to(kg*m**2/s**2)) == ascii_str1 assert upretty(3*kg*x*m**2*y/s**2) == unicode_str2 assert pretty(3*kg*x*m**2*y/s**2) == ascii_str2 def test_pretty_Subs(): f = Function('f') expr = Subs(f(x), x, ph**2) ascii_str = \ """\ (f(x))| 2\n\ |x=phi \ """ unicode_str = \ """\ (f(x))│ 2\n\ │x=φ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str expr = Subs(f(x).diff(x), x, 0) ascii_str = \ """\ /d \\| \n\ |--(f(x))|| \n\ \\dx /|x=0\ """ unicode_str = \ """\ ⎛d ⎞│ \n\ ⎜──(f(x))⎟│ \n\ ⎝dx ⎠│x=0\ """ assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str expr = Subs(f(x).diff(x)/y, (x, y), (0, Rational(1, 2))) ascii_str = \ """\ /d \\| \n\ |--(f(x))|| \n\ |dx || \n\ |--------|| \n\ \\ y /|x=0, y=1/2\ """ unicode_str = \ """\ ⎛d ⎞│ \n\ ⎜──(f(x))⎟│ \n\ ⎜dx ⎟│ \n\ ⎜────────⎟│ \n\ ⎝ y ⎠│x=0, y=1/2\ """ assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str def test_gammas(): assert upretty(lowergamma(x, y)) == "γ(x, y)" assert upretty(uppergamma(x, y)) == "Γ(x, y)" assert xpretty(gamma(x), use_unicode=True) == 'Γ(x)' assert xpretty(gamma, use_unicode=True) == 'Γ' assert xpretty(symbols('gamma', cls=Function)(x), use_unicode=True) == 'γ(x)' assert xpretty(symbols('gamma', cls=Function), use_unicode=True) == 'γ' def test_beta(): assert xpretty(beta(x,y), use_unicode=True) == 'Β(x, y)' assert xpretty(beta(x,y), use_unicode=False) == 'B(x, y)' assert xpretty(beta, use_unicode=True) == 'Β' assert xpretty(beta, use_unicode=False) == 'B' mybeta = Function('beta') assert xpretty(mybeta(x), use_unicode=True) == 'β(x)' assert xpretty(mybeta(x, y, z), use_unicode=False) == 'beta(x, y, z)' assert xpretty(mybeta, use_unicode=True) == 'β' # test that notation passes to subclasses of the same name only def test_function_subclass_different_name(): class mygamma(gamma): pass assert xpretty(mygamma, use_unicode=True) == r"mygamma" assert xpretty(mygamma(x), use_unicode=True) == r"mygamma(x)" def test_SingularityFunction(): assert xpretty(SingularityFunction(x, 0, n), use_unicode=True) == ( """\ n\n\ <x> \ """) assert xpretty(SingularityFunction(x, 1, n), use_unicode=True) == ( """\ n\n\ <x - 1> \ """) assert xpretty(SingularityFunction(x, -1, n), use_unicode=True) == ( """\ n\n\ <x + 1> \ """) assert xpretty(SingularityFunction(x, a, n), use_unicode=True) == ( """\ n\n\ <-a + x> \ """) assert xpretty(SingularityFunction(x, y, n), use_unicode=True) == ( """\ n\n\ <x - y> \ """) assert xpretty(SingularityFunction(x, 0, n), use_unicode=False) == ( """\ n\n\ <x> \ """) assert xpretty(SingularityFunction(x, 1, n), use_unicode=False) == ( """\ n\n\ <x - 1> \ """) assert xpretty(SingularityFunction(x, -1, n), use_unicode=False) == ( """\ n\n\ <x + 1> \ """) assert xpretty(SingularityFunction(x, a, n), use_unicode=False) == ( """\ n\n\ <-a + x> \ """) assert xpretty(SingularityFunction(x, y, n), use_unicode=False) == ( """\ n\n\ <x - y> \ """) def test_deltas(): assert xpretty(DiracDelta(x), use_unicode=True) == 'δ(x)' assert xpretty(DiracDelta(x, 1), use_unicode=True) == \ """\ (1) \n\ δ (x)\ """ assert xpretty(x*DiracDelta(x, 1), use_unicode=True) == \ """\ (1) \n\ x⋅δ (x)\ """ def test_hyper(): expr = hyper((), (), z) ucode_str = \ """\ ┌─ ⎛ │ ⎞\n\ ├─ ⎜ │ z⎟\n\ 0╵ 0 ⎝ │ ⎠\ """ ascii_str = \ """\ _ \n\ |_ / | \\\n\ | | | z|\n\ 0 0 \\ | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hyper((), (1,), x) ucode_str = \ """\ ┌─ ⎛ │ ⎞\n\ ├─ ⎜ │ x⎟\n\ 0╵ 1 ⎝1 │ ⎠\ """ ascii_str = \ """\ _ \n\ |_ / | \\\n\ | | | x|\n\ 0 1 \\1 | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hyper([2], [1], x) ucode_str = \ """\ ┌─ ⎛2 │ ⎞\n\ ├─ ⎜ │ x⎟\n\ 1╵ 1 ⎝1 │ ⎠\ """ ascii_str = \ """\ _ \n\ |_ /2 | \\\n\ | | | x|\n\ 1 1 \\1 | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hyper((pi/3, -2*k), (3, 4, 5, -3), x) ucode_str = \ """\ ⎛ π │ ⎞\n\ ┌─ ⎜ ─, -2⋅k │ ⎟\n\ ├─ ⎜ 3 │ x⎟\n\ 2╵ 4 ⎜ │ ⎟\n\ ⎝3, 4, 5, -3 │ ⎠\ """ ascii_str = \ """\ \n\ _ / pi | \\\n\ |_ | --, -2*k | |\n\ | | 3 | x|\n\ 2 4 | | |\n\ \\3, 4, 5, -3 | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hyper((pi, S('2/3'), -2*k), (3, 4, 5, -3), x**2) ucode_str = \ """\ ┌─ ⎛π, 2/3, -2⋅k │ 2⎞\n\ ├─ ⎜ │ x ⎟\n\ 3╵ 4 ⎝3, 4, 5, -3 │ ⎠\ """ ascii_str = \ """\ _ \n\ |_ /pi, 2/3, -2*k | 2\\\n\ | | | x |\n\ 3 4 \\ 3, 4, 5, -3 | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hyper([1, 2], [3, 4], 1/(1/(1/(1/x + 1) + 1) + 1)) ucode_str = \ """\ ⎛ │ 1 ⎞\n\ ⎜ │ ─────────────⎟\n\ ⎜ │ 1 ⎟\n\ ┌─ ⎜1, 2 │ 1 + ─────────⎟\n\ ├─ ⎜ │ 1 ⎟\n\ 2╵ 2 ⎜3, 4 │ 1 + ─────⎟\n\ ⎜ │ 1⎟\n\ ⎜ │ 1 + ─⎟\n\ ⎝ │ x⎠\ """ ascii_str = \ """\ \n\ / | 1 \\\n\ | | -------------|\n\ _ | | 1 |\n\ |_ |1, 2 | 1 + ---------|\n\ | | | 1 |\n\ 2 2 |3, 4 | 1 + -----|\n\ | | 1|\n\ | | 1 + -|\n\ \\ | x/\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_meijerg(): expr = meijerg([pi, pi, x], [1], [0, 1], [1, 2, 3], z) ucode_str = \ """\ ╭─╮2, 3 ⎛π, π, x 1 │ ⎞\n\ │╶┐ ⎜ │ z⎟\n\ ╰─╯4, 5 ⎝ 0, 1 1, 2, 3 │ ⎠\ """ ascii_str = \ """\ __2, 3 /pi, pi, x 1 | \\\n\ /__ | | z|\n\ \\_|4, 5 \\ 0, 1 1, 2, 3 | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = meijerg([1, pi/7], [2, pi, 5], [], [], z**2) ucode_str = \ """\ ⎛ π │ ⎞\n\ ╭─╮0, 2 ⎜1, ─ 2, π, 5 │ 2⎟\n\ │╶┐ ⎜ 7 │ z ⎟\n\ ╰─╯5, 0 ⎜ │ ⎟\n\ ⎝ │ ⎠\ """ ascii_str = \ """\ / pi | \\\n\ __0, 2 |1, -- 2, pi, 5 | 2|\n\ /__ | 7 | z |\n\ \\_|5, 0 | | |\n\ \\ | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ucode_str = \ """\ ╭─╮ 1, 10 ⎛1, 1, 1, 1, 1, 1, 1, 1, 1, 1 1 │ ⎞\n\ │╶┐ ⎜ │ z⎟\n\ ╰─╯11, 2 ⎝ 1 1 │ ⎠\ """ ascii_str = \ """\ __ 1, 10 /1, 1, 1, 1, 1, 1, 1, 1, 1, 1 1 | \\\n\ /__ | | z|\n\ \\_|11, 2 \\ 1 1 | /\ """ expr = meijerg([1]*10, [1], [1], [1], z) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = meijerg([1, 2, ], [4, 3], [3], [4, 5], 1/(1/(1/(1/x + 1) + 1) + 1)) ucode_str = \ """\ ⎛ │ 1 ⎞\n\ ⎜ │ ─────────────⎟\n\ ⎜ │ 1 ⎟\n\ ╭─╮1, 2 ⎜1, 2 4, 3 │ 1 + ─────────⎟\n\ │╶┐ ⎜ │ 1 ⎟\n\ ╰─╯4, 3 ⎜ 3 4, 5 │ 1 + ─────⎟\n\ ⎜ │ 1⎟\n\ ⎜ │ 1 + ─⎟\n\ ⎝ │ x⎠\ """ ascii_str = \ """\ / | 1 \\\n\ | | -------------|\n\ | | 1 |\n\ __1, 2 |1, 2 4, 3 | 1 + ---------|\n\ /__ | | 1 |\n\ \\_|4, 3 | 3 4, 5 | 1 + -----|\n\ | | 1|\n\ | | 1 + -|\n\ \\ | x/\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(expr, x) ucode_str = \ """\ ⌠ \n\ ⎮ ⎛ │ 1 ⎞ \n\ ⎮ ⎜ │ ─────────────⎟ \n\ ⎮ ⎜ │ 1 ⎟ \n\ ⎮ ╭─╮1, 2 ⎜1, 2 4, 3 │ 1 + ─────────⎟ \n\ ⎮ │╶┐ ⎜ │ 1 ⎟ dx\n\ ⎮ ╰─╯4, 3 ⎜ 3 4, 5 │ 1 + ─────⎟ \n\ ⎮ ⎜ │ 1⎟ \n\ ⎮ ⎜ │ 1 + ─⎟ \n\ ⎮ ⎝ │ x⎠ \n\ ⌡ \ """ ascii_str = \ """\ / \n\ | \n\ | / | 1 \\ \n\ | | | -------------| \n\ | | | 1 | \n\ | __1, 2 |1, 2 4, 3 | 1 + ---------| \n\ | /__ | | 1 | dx\n\ | \\_|4, 3 | 3 4, 5 | 1 + -----| \n\ | | | 1| \n\ | | | 1 + -| \n\ | \\ | x/ \n\ | \n\ / \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_noncommutative(): A, B, C = symbols('A,B,C', commutative=False) expr = A*B*C**-1 ascii_str = \ """\ -1\n\ A*B*C \ """ ucode_str = \ """\ -1\n\ A⋅B⋅C \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = C**-1*A*B ascii_str = \ """\ -1 \n\ C *A*B\ """ ucode_str = \ """\ -1 \n\ C ⋅A⋅B\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A*C**-1*B ascii_str = \ """\ -1 \n\ A*C *B\ """ ucode_str = \ """\ -1 \n\ A⋅C ⋅B\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A*C**-1*B/x ascii_str = \ """\ -1 \n\ A*C *B\n\ -------\n\ x \ """ ucode_str = \ """\ -1 \n\ A⋅C ⋅B\n\ ───────\n\ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_special_functions(): x, y = symbols("x y") # atan2 expr = atan2(y/sqrt(200), sqrt(x)) ascii_str = \ """\ / ___ \\\n\ |\\/ 2 *y ___|\n\ atan2|-------, \\/ x |\n\ \\ 20 /\ """ ucode_str = \ """\ ⎛√2⋅y ⎞\n\ atan2⎜────, √x⎟\n\ ⎝ 20 ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_geometry(): e = Segment((0, 1), (0, 2)) assert pretty(e) == 'Segment2D(Point2D(0, 1), Point2D(0, 2))' e = Ray((1, 1), angle=4.02*pi) assert pretty(e) == 'Ray2D(Point2D(1, 1), Point2D(2, tan(pi/50) + 1))' def test_expint(): expr = Ei(x) string = 'Ei(x)' assert pretty(expr) == string assert upretty(expr) == string expr = expint(1, z) ucode_str = "E₁(z)" ascii_str = "expint(1, z)" assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str assert pretty(Shi(x)) == 'Shi(x)' assert pretty(Si(x)) == 'Si(x)' assert pretty(Ci(x)) == 'Ci(x)' assert pretty(Chi(x)) == 'Chi(x)' assert upretty(Shi(x)) == 'Shi(x)' assert upretty(Si(x)) == 'Si(x)' assert upretty(Ci(x)) == 'Ci(x)' assert upretty(Chi(x)) == 'Chi(x)' def test_elliptic_functions(): ascii_str = \ """\ / 1 \\\n\ K|-----|\n\ \\z + 1/\ """ ucode_str = \ """\ ⎛ 1 ⎞\n\ K⎜─────⎟\n\ ⎝z + 1⎠\ """ expr = elliptic_k(1/(z + 1)) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ascii_str = \ """\ / | 1 \\\n\ F|1|-----|\n\ \\ |z + 1/\ """ ucode_str = \ """\ ⎛ │ 1 ⎞\n\ F⎜1│─────⎟\n\ ⎝ │z + 1⎠\ """ expr = elliptic_f(1, 1/(1 + z)) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ascii_str = \ """\ / 1 \\\n\ E|-----|\n\ \\z + 1/\ """ ucode_str = \ """\ ⎛ 1 ⎞\n\ E⎜─────⎟\n\ ⎝z + 1⎠\ """ expr = elliptic_e(1/(z + 1)) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ascii_str = \ """\ / | 1 \\\n\ E|1|-----|\n\ \\ |z + 1/\ """ ucode_str = \ """\ ⎛ │ 1 ⎞\n\ E⎜1│─────⎟\n\ ⎝ │z + 1⎠\ """ expr = elliptic_e(1, 1/(1 + z)) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ascii_str = \ """\ / |4\\\n\ Pi|3|-|\n\ \\ |x/\ """ ucode_str = \ """\ ⎛ │4⎞\n\ Π⎜3│─⎟\n\ ⎝ │x⎠\ """ expr = elliptic_pi(3, 4/x) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ascii_str = \ """\ / 4| \\\n\ Pi|3; -|6|\n\ \\ x| /\ """ ucode_str = \ """\ ⎛ 4│ ⎞\n\ Π⎜3; ─│6⎟\n\ ⎝ x│ ⎠\ """ expr = elliptic_pi(3, 4/x, 6) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_RandomDomain(): from sympy.stats import Normal, Die, Exponential, pspace, where X = Normal('x1', 0, 1) assert upretty(where(X > 0)) == "Domain: 0 < x₁ ∧ x₁ < ∞" D = Die('d1', 6) assert upretty(where(D > 4)) == 'Domain: d₁ = 5 ∨ d₁ = 6' A = Exponential('a', 1) B = Exponential('b', 1) assert upretty(pspace(Tuple(A, B)).domain) == \ 'Domain: 0 ≤ a ∧ 0 ≤ b ∧ a < ∞ ∧ b < ∞' def test_PrettyPoly(): F = QQ.frac_field(x, y) R = QQ.poly_ring(x, y) expr = F.convert(x/(x + y)) assert pretty(expr) == "x/(x + y)" assert upretty(expr) == "x/(x + y)" expr = R.convert(x + y) assert pretty(expr) == "x + y" assert upretty(expr) == "x + y" def test_issue_6285(): assert pretty(Pow(2, -5, evaluate=False)) == '1 \n--\n 5\n2 ' assert pretty(Pow(x, (1/pi))) == \ ' 1 \n'\ ' --\n'\ ' pi\n'\ 'x ' def test_issue_6359(): assert pretty(Integral(x**2, x)**2) == \ """\ 2 / / \\ \n\ | | | \n\ | | 2 | \n\ | | x dx| \n\ | | | \n\ \\/ / \ """ assert upretty(Integral(x**2, x)**2) == \ """\ 2 ⎛⌠ ⎞ \n\ ⎜⎮ 2 ⎟ \n\ ⎜⎮ x dx⎟ \n\ ⎝⌡ ⎠ \ """ assert pretty(Sum(x**2, (x, 0, 1))**2) == \ """\ 2 / 1 \\ \n\ | ___ | \n\ | \\ ` | \n\ | \\ 2| \n\ | / x | \n\ | /__, | \n\ \\x = 0 / \ """ assert upretty(Sum(x**2, (x, 0, 1))**2) == \ """\ 2 ⎛ 1 ⎞ \n\ ⎜ ___ ⎟ \n\ ⎜ ╲ ⎟ \n\ ⎜ ╲ 2⎟ \n\ ⎜ ╱ x ⎟ \n\ ⎜ ╱ ⎟ \n\ ⎜ ‾‾‾ ⎟ \n\ ⎝x = 0 ⎠ \ """ assert pretty(Product(x**2, (x, 1, 2))**2) == \ """\ 2 / 2 \\ \n\ |______ | \n\ | | | 2| \n\ | | | x | \n\ | | | | \n\ \\x = 1 / \ """ assert upretty(Product(x**2, (x, 1, 2))**2) == \ """\ 2 ⎛ 2 ⎞ \n\ ⎜─┬──┬─ ⎟ \n\ ⎜ │ │ 2⎟ \n\ ⎜ │ │ x ⎟ \n\ ⎜ │ │ ⎟ \n\ ⎝x = 1 ⎠ \ """ f = Function('f') assert pretty(Derivative(f(x), x)**2) == \ """\ 2 /d \\ \n\ |--(f(x))| \n\ \\dx / \ """ assert upretty(Derivative(f(x), x)**2) == \ """\ 2 ⎛d ⎞ \n\ ⎜──(f(x))⎟ \n\ ⎝dx ⎠ \ """ def test_issue_6739(): ascii_str = \ """\ 1 \n\ -----\n\ ___\n\ \\/ x \ """ ucode_str = \ """\ 1 \n\ ──\n\ √x\ """ assert pretty(1/sqrt(x)) == ascii_str assert upretty(1/sqrt(x)) == ucode_str def test_complicated_symbol_unchanged(): for symb_name in ["dexpr2_d1tau", "dexpr2^d1tau"]: assert pretty(Symbol(symb_name)) == symb_name def test_categories(): from sympy.categories import (Object, IdentityMorphism, NamedMorphism, Category, Diagram, DiagramGrid) A1 = Object("A1") A2 = Object("A2") A3 = Object("A3") f1 = NamedMorphism(A1, A2, "f1") f2 = NamedMorphism(A2, A3, "f2") id_A1 = IdentityMorphism(A1) K1 = Category("K1") assert pretty(A1) == "A1" assert upretty(A1) == "A₁" assert pretty(f1) == "f1:A1-->A2" assert upretty(f1) == "f₁:A₁——▶A₂" assert pretty(id_A1) == "id:A1-->A1" assert upretty(id_A1) == "id:A₁——▶A₁" assert pretty(f2*f1) == "f2*f1:A1-->A3" assert upretty(f2*f1) == "f₂∘f₁:A₁——▶A₃" assert pretty(K1) == "K1" assert upretty(K1) == "K₁" # Test how diagrams are printed. d = Diagram() assert pretty(d) == "EmptySet" assert upretty(d) == "∅" d = Diagram({f1: "unique", f2: S.EmptySet}) assert pretty(d) == "{f2*f1:A1-->A3: EmptySet, id:A1-->A1: " \ "EmptySet, id:A2-->A2: EmptySet, id:A3-->A3: " \ "EmptySet, f1:A1-->A2: {unique}, f2:A2-->A3: EmptySet}" assert upretty(d) == "{f₂∘f₁:A₁——▶A₃: ∅, id:A₁——▶A₁: ∅, " \ "id:A₂——▶A₂: ∅, id:A₃——▶A₃: ∅, f₁:A₁——▶A₂: {unique}, f₂:A₂——▶A₃: ∅}" d = Diagram({f1: "unique", f2: S.EmptySet}, {f2 * f1: "unique"}) assert pretty(d) == "{f2*f1:A1-->A3: EmptySet, id:A1-->A1: " \ "EmptySet, id:A2-->A2: EmptySet, id:A3-->A3: " \ "EmptySet, f1:A1-->A2: {unique}, f2:A2-->A3: EmptySet}" \ " ==> {f2*f1:A1-->A3: {unique}}" assert upretty(d) == "{f₂∘f₁:A₁——▶A₃: ∅, id:A₁——▶A₁: ∅, id:A₂——▶A₂: " \ "∅, id:A₃——▶A₃: ∅, f₁:A₁——▶A₂: {unique}, f₂:A₂——▶A₃: ∅}" \ " ══▶ {f₂∘f₁:A₁——▶A₃: {unique}}" grid = DiagramGrid(d) assert pretty(grid) == "A1 A2\n \nA3 " assert upretty(grid) == "A₁ A₂\n \nA₃ " def test_PrettyModules(): R = QQ.old_poly_ring(x, y) F = R.free_module(2) M = F.submodule([x, y], [1, x**2]) ucode_str = \ """\ 2\n\ ℚ[x, y] \ """ ascii_str = \ """\ 2\n\ QQ[x, y] \ """ assert upretty(F) == ucode_str assert pretty(F) == ascii_str ucode_str = \ """\ ╱ ⎡ 2⎤╲\n\ ╲[x, y], ⎣1, x ⎦╱\ """ ascii_str = \ """\ 2 \n\ <[x, y], [1, x ]>\ """ assert upretty(M) == ucode_str assert pretty(M) == ascii_str I = R.ideal(x**2, y) ucode_str = \ """\ ╱ 2 ╲\n\ ╲x , y╱\ """ ascii_str = \ """\ 2 \n\ <x , y>\ """ assert upretty(I) == ucode_str assert pretty(I) == ascii_str Q = F / M ucode_str = \ """\ 2 \n\ ℚ[x, y] \n\ ─────────────────\n\ ╱ ⎡ 2⎤╲\n\ ╲[x, y], ⎣1, x ⎦╱\ """ ascii_str = \ """\ 2 \n\ QQ[x, y] \n\ -----------------\n\ 2 \n\ <[x, y], [1, x ]>\ """ assert upretty(Q) == ucode_str assert pretty(Q) == ascii_str ucode_str = \ """\ ╱⎡ 3⎤ ╲\n\ │⎢ x ⎥ ╱ ⎡ 2⎤╲ ╱ ⎡ 2⎤╲│\n\ │⎢1, ──⎥ + ╲[x, y], ⎣1, x ⎦╱, [2, y] + ╲[x, y], ⎣1, x ⎦╱│\n\ ╲⎣ 2 ⎦ ╱\ """ ascii_str = \ """\ 3 \n\ x 2 2 \n\ <[1, --] + <[x, y], [1, x ]>, [2, y] + <[x, y], [1, x ]>>\n\ 2 \ """ def test_QuotientRing(): R = QQ.old_poly_ring(x)/[x**2 + 1] ucode_str = \ """\ ℚ[x] \n\ ────────\n\ ╱ 2 ╲\n\ ╲x + 1╱\ """ ascii_str = \ """\ QQ[x] \n\ --------\n\ 2 \n\ <x + 1>\ """ assert upretty(R) == ucode_str assert pretty(R) == ascii_str ucode_str = \ """\ ╱ 2 ╲\n\ 1 + ╲x + 1╱\ """ ascii_str = \ """\ 2 \n\ 1 + <x + 1>\ """ assert upretty(R.one) == ucode_str assert pretty(R.one) == ascii_str def test_Homomorphism(): from sympy.polys.agca import homomorphism R = QQ.old_poly_ring(x) expr = homomorphism(R.free_module(1), R.free_module(1), [0]) ucode_str = \ """\ 1 1\n\ [0] : ℚ[x] ──> ℚ[x] \ """ ascii_str = \ """\ 1 1\n\ [0] : QQ[x] --> QQ[x] \ """ assert upretty(expr) == ucode_str assert pretty(expr) == ascii_str expr = homomorphism(R.free_module(2), R.free_module(2), [0, 0]) ucode_str = \ """\ ⎡0 0⎤ 2 2\n\ ⎢ ⎥ : ℚ[x] ──> ℚ[x] \n\ ⎣0 0⎦ \ """ ascii_str = \ """\ [0 0] 2 2\n\ [ ] : QQ[x] --> QQ[x] \n\ [0 0] \ """ assert upretty(expr) == ucode_str assert pretty(expr) == ascii_str expr = homomorphism(R.free_module(1), R.free_module(1) / [[x]], [0]) ucode_str = \ """\ 1\n\ 1 ℚ[x] \n\ [0] : ℚ[x] ──> ─────\n\ <[x]>\ """ ascii_str = \ """\ 1\n\ 1 QQ[x] \n\ [0] : QQ[x] --> ------\n\ <[x]> \ """ assert upretty(expr) == ucode_str assert pretty(expr) == ascii_str def test_Tr(): A, B = symbols('A B', commutative=False) t = Tr(A*B) assert pretty(t) == r'Tr(A*B)' assert upretty(t) == 'Tr(A⋅B)' def test_pretty_Add(): eq = Mul(-2, x - 2, evaluate=False) + 5 assert pretty(eq) == '5 - 2*(x - 2)' def test_issue_7179(): assert upretty(Not(Equivalent(x, y))) == 'x ⇎ y' assert upretty(Not(Implies(x, y))) == 'x ↛ y' def test_issue_7180(): assert upretty(Equivalent(x, y)) == 'x ⇔ y' def test_pretty_Complement(): assert pretty(S.Reals - S.Naturals) == '(-oo, oo) \\ Naturals' assert upretty(S.Reals - S.Naturals) == 'ℝ \\ ℕ' assert pretty(S.Reals - S.Naturals0) == '(-oo, oo) \\ Naturals0' assert upretty(S.Reals - S.Naturals0) == 'ℝ \\ ℕ₀' def test_pretty_SymmetricDifference(): from sympy.sets.sets import SymmetricDifference assert upretty(SymmetricDifference(Interval(2,3), Interval(3,5), \ evaluate = False)) == '[2, 3] ∆ [3, 5]' with raises(NotImplementedError): pretty(SymmetricDifference(Interval(2,3), Interval(3,5), evaluate = False)) def test_pretty_Contains(): assert pretty(Contains(x, S.Integers)) == 'Contains(x, Integers)' assert upretty(Contains(x, S.Integers)) == 'x ∈ ℤ' def test_issue_8292(): from sympy.core import sympify e = sympify('((x+x**4)/(x-1))-(2*(x-1)**4/(x-1)**4)', evaluate=False) ucode_str = \ """\ 4 4 \n\ 2⋅(x - 1) x + x\n\ - ────────── + ──────\n\ 4 x - 1 \n\ (x - 1) \ """ ascii_str = \ """\ 4 4 \n\ 2*(x - 1) x + x\n\ - ---------- + ------\n\ 4 x - 1 \n\ (x - 1) \ """ assert pretty(e) == ascii_str assert upretty(e) == ucode_str def test_issue_4335(): y = Function('y') expr = -y(x).diff(x) ucode_str = \ """\ d \n\ -──(y(x))\n\ dx \ """ ascii_str = \ """\ d \n\ - --(y(x))\n\ dx \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_issue_8344(): from sympy.core import sympify e = sympify('2*x*y**2/1**2 + 1', evaluate=False) ucode_str = \ """\ 2 \n\ 2⋅x⋅y \n\ ────── + 1\n\ 2 \n\ 1 \ """ assert upretty(e) == ucode_str def test_issue_6324(): x = Pow(2, 3, evaluate=False) y = Pow(10, -2, evaluate=False) e = Mul(x, y, evaluate=False) ucode_str = \ """\ 3\n\ 2 \n\ ───\n\ 2\n\ 10 \ """ assert upretty(e) == ucode_str def test_issue_7927(): e = sin(x/2)**cos(x/2) ucode_str = \ """\ ⎛x⎞\n\ cos⎜─⎟\n\ ⎝2⎠\n\ ⎛ ⎛x⎞⎞ \n\ ⎜sin⎜─⎟⎟ \n\ ⎝ ⎝2⎠⎠ \ """ assert upretty(e) == ucode_str e = sin(x)**(S(11)/13) ucode_str = \ """\ 11\n\ ──\n\ 13\n\ (sin(x)) \ """ assert upretty(e) == ucode_str def test_issue_6134(): from sympy.abc import lamda, t phi = Function('phi') e = lamda*x*Integral(phi(t)*pi*sin(pi*t), (t, 0, 1)) + lamda*x**2*Integral(phi(t)*2*pi*sin(2*pi*t), (t, 0, 1)) ucode_str = \ """\ 1 1 \n\ 2 ⌠ ⌠ \n\ λ⋅x ⋅⎮ 2⋅π⋅φ(t)⋅sin(2⋅π⋅t) dt + λ⋅x⋅⎮ π⋅φ(t)⋅sin(π⋅t) dt\n\ ⌡ ⌡ \n\ 0 0 \ """ assert upretty(e) == ucode_str def test_issue_9877(): ucode_str1 = '(2, 3) ∪ ([1, 2] \\ {x})' a, b, c = Interval(2, 3, True, True), Interval(1, 2), FiniteSet(x) assert upretty(Union(a, Complement(b, c))) == ucode_str1 ucode_str2 = '{x} ∩ {y} ∩ ({z} \\ [1, 2])' d, e, f, g = FiniteSet(x), FiniteSet(y), FiniteSet(z), Interval(1, 2) assert upretty(Intersection(d, e, Complement(f, g))) == ucode_str2 def test_issue_13651(): expr1 = c + Mul(-1, a + b, evaluate=False) assert pretty(expr1) == 'c - (a + b)' expr2 = c + Mul(-1, a - b + d, evaluate=False) assert pretty(expr2) == 'c - (a - b + d)' def test_pretty_primenu(): from sympy.ntheory.factor_ import primenu ascii_str1 = "nu(n)" ucode_str1 = "ν(n)" n = symbols('n', integer=True) assert pretty(primenu(n)) == ascii_str1 assert upretty(primenu(n)) == ucode_str1 def test_pretty_primeomega(): from sympy.ntheory.factor_ import primeomega ascii_str1 = "Omega(n)" ucode_str1 = "Ω(n)" n = symbols('n', integer=True) assert pretty(primeomega(n)) == ascii_str1 assert upretty(primeomega(n)) == ucode_str1 def test_pretty_Mod(): from sympy.core import Mod ascii_str1 = "x mod 7" ucode_str1 = "x mod 7" ascii_str2 = "(x + 1) mod 7" ucode_str2 = "(x + 1) mod 7" ascii_str3 = "2*x mod 7" ucode_str3 = "2⋅x mod 7" ascii_str4 = "(x mod 7) + 1" ucode_str4 = "(x mod 7) + 1" ascii_str5 = "2*(x mod 7)" ucode_str5 = "2⋅(x mod 7)" x = symbols('x', integer=True) assert pretty(Mod(x, 7)) == ascii_str1 assert upretty(Mod(x, 7)) == ucode_str1 assert pretty(Mod(x + 1, 7)) == ascii_str2 assert upretty(Mod(x + 1, 7)) == ucode_str2 assert pretty(Mod(2 * x, 7)) == ascii_str3 assert upretty(Mod(2 * x, 7)) == ucode_str3 assert pretty(Mod(x, 7) + 1) == ascii_str4 assert upretty(Mod(x, 7) + 1) == ucode_str4 assert pretty(2 * Mod(x, 7)) == ascii_str5 assert upretty(2 * Mod(x, 7)) == ucode_str5 def test_issue_11801(): assert pretty(Symbol("")) == "" assert upretty(Symbol("")) == "" def test_pretty_UnevaluatedExpr(): x = symbols('x') he = UnevaluatedExpr(1/x) ucode_str = \ """\ 1\n\ ─\n\ x\ """ assert upretty(he) == ucode_str ucode_str = \ """\ 2\n\ ⎛1⎞ \n\ ⎜─⎟ \n\ ⎝x⎠ \ """ assert upretty(he**2) == ucode_str ucode_str = \ """\ 1\n\ 1 + ─\n\ x\ """ assert upretty(he + 1) == ucode_str ucode_str = \ ('''\ 1\n\ x⋅─\n\ x\ ''') assert upretty(x*he) == ucode_str def test_issue_10472(): M = (Matrix([[0, 0], [0, 0]]), Matrix([0, 0])) ucode_str = \ """\ ⎛⎡0 0⎤ ⎡0⎤⎞ ⎜⎢ ⎥, ⎢ ⎥⎟ ⎝⎣0 0⎦ ⎣0⎦⎠\ """ assert upretty(M) == ucode_str def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) ascii_str1 = "A_00" ucode_str1 = "A₀₀" assert pretty(A[0, 0]) == ascii_str1 assert upretty(A[0, 0]) == ucode_str1 ascii_str1 = "3*A_00" ucode_str1 = "3⋅A₀₀" assert pretty(3*A[0, 0]) == ascii_str1 assert upretty(3*A[0, 0]) == ucode_str1 ascii_str1 = "(-B + A)[0, 0]" ucode_str1 = "(-B + A)[0, 0]" F = C[0, 0].subs(C, A - B) assert pretty(F) == ascii_str1 assert upretty(F) == ucode_str1 def test_issue_12675(): x, y, t, j = symbols('x y t j') e = CoordSys3D('e') ucode_str = \ """\ ⎛ t⎞ \n\ ⎜⎛x⎞ ⎟ j_e\n\ ⎜⎜─⎟ ⎟ \n\ ⎝⎝y⎠ ⎠ \ """ assert upretty((x/y)**t*e.j) == ucode_str ucode_str = \ """\ ⎛1⎞ \n\ ⎜─⎟ j_e\n\ ⎝y⎠ \ """ assert upretty((1/y)*e.j) == ucode_str def test_MatrixSymbol_printing(): # test cases for issue #14237 A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) C = MatrixSymbol("C", 3, 3) assert pretty(-A*B*C) == "-A*B*C" assert pretty(A - B) == "-B + A" assert pretty(A*B*C - A*B - B*C) == "-A*B -B*C + A*B*C" # issue #14814 x = MatrixSymbol('x', n, n) y = MatrixSymbol('y*', n, n) assert pretty(x + y) == "x + y*" ascii_str = \ """\ 2 \n\ -2*y* -a*x\ """ assert pretty(-a*x + -2*y*y) == ascii_str def test_degree_printing(): expr1 = 90*degree assert pretty(expr1) == '90°' expr2 = x*degree assert pretty(expr2) == 'x°' expr3 = cos(x*degree + 90*degree) assert pretty(expr3) == 'cos(x° + 90°)' def test_vector_expr_pretty_printing(): A = CoordSys3D('A') assert upretty(Cross(A.i, A.x*A.i+3*A.y*A.j)) == "(i_A)×((x_A) i_A + (3⋅y_A) j_A)" assert upretty(x*Cross(A.i, A.j)) == 'x⋅(i_A)×(j_A)' assert upretty(Curl(A.x*A.i + 3*A.y*A.j)) == "∇×((x_A) i_A + (3⋅y_A) j_A)" assert upretty(Divergence(A.x*A.i + 3*A.y*A.j)) == "∇⋅((x_A) i_A + (3⋅y_A) j_A)" assert upretty(Dot(A.i, A.x*A.i+3*A.y*A.j)) == "(i_A)⋅((x_A) i_A + (3⋅y_A) j_A)" assert upretty(Gradient(A.x+3*A.y)) == "∇(x_A + 3⋅y_A)" assert upretty(Laplacian(A.x+3*A.y)) == "∆(x_A + 3⋅y_A)" # TODO: add support for ASCII pretty. def test_pretty_print_tensor_expr(): L = TensorIndexType("L") i, j, k = tensor_indices("i j k", L) i0 = tensor_indices("i_0", L) A, B, C, D = tensor_heads("A B C D", [L]) H = TensorHead("H", [L, L]) expr = -i ascii_str = \ """\ -i\ """ ucode_str = \ """\ -i\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(i) ascii_str = \ """\ i\n\ A \n\ \ """ ucode_str = \ """\ i\n\ A \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(i0) ascii_str = \ """\ i_0\n\ A \n\ \ """ ucode_str = \ """\ i₀\n\ A \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(-i) ascii_str = \ """\ \n\ A \n\ i\ """ ucode_str = \ """\ \n\ A \n\ i\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -3*A(-i) ascii_str = \ """\ \n\ -3*A \n\ i\ """ ucode_str = \ """\ \n\ -3⋅A \n\ i\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = H(i, -j) ascii_str = \ """\ i \n\ H \n\ j\ """ ucode_str = \ """\ i \n\ H \n\ j\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = H(i, -i) ascii_str = \ """\ L_0 \n\ H \n\ L_0\ """ ucode_str = \ """\ L₀ \n\ H \n\ L₀\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = H(i, -j)*A(j)*B(k) ascii_str = \ """\ i L_0 k\n\ H *A *B \n\ L_0 \ """ ucode_str = \ """\ i L₀ k\n\ H ⋅A ⋅B \n\ L₀ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (1+x)*A(i) ascii_str = \ """\ i\n\ (x + 1)*A \n\ \ """ ucode_str = \ """\ i\n\ (x + 1)⋅A \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(i) + 3*B(i) ascii_str = \ """\ i i\n\ 3*B + A \n\ \ """ ucode_str = \ """\ i i\n\ 3⋅B + A \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_print_tensor_partial_deriv(): from sympy.tensor.toperators import PartialDerivative L = TensorIndexType("L") i, j, k = tensor_indices("i j k", L) A, B, C, D = tensor_heads("A B C D", [L]) H = TensorHead("H", [L, L]) expr = PartialDerivative(A(i), A(j)) ascii_str = \ """\ d / i\\\n\ ---|A |\n\ j\\ /\n\ dA \n\ \ """ ucode_str = \ """\ ∂ ⎛ i⎞\n\ ───⎜A ⎟\n\ j⎝ ⎠\n\ ∂A \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(i)*PartialDerivative(H(k, -i), A(j)) ascii_str = \ """\ L_0 d / k \\\n\ A *---|H |\n\ j\\ L_0/\n\ dA \n\ \ """ ucode_str = \ """\ L₀ ∂ ⎛ k ⎞\n\ A ⋅───⎜H ⎟\n\ j⎝ L₀⎠\n\ ∂A \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(i)*PartialDerivative(B(k)*C(-i) + 3*H(k, -i), A(j)) ascii_str = \ """\ L_0 d / k k \\\n\ A *---|3*H + B *C |\n\ j\\ L_0 L_0/\n\ dA \n\ \ """ ucode_str = \ """\ L₀ ∂ ⎛ k k ⎞\n\ A ⋅───⎜3⋅H + B ⋅C ⎟\n\ j⎝ L₀ L₀⎠\n\ ∂A \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (A(i) + B(i))*PartialDerivative(C(j), D(j)) ascii_str = \ """\ / i i\\ d / L_0\\\n\ |A + B |*-----|C |\n\ \\ / L_0\\ /\n\ dD \n\ \ """ ucode_str = \ """\ ⎛ i i⎞ ∂ ⎛ L₀⎞\n\ ⎜A + B ⎟⋅────⎜C ⎟\n\ ⎝ ⎠ L₀⎝ ⎠\n\ ∂D \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (A(i) + B(i))*PartialDerivative(C(-i), D(j)) ascii_str = \ """\ / L_0 L_0\\ d / \\\n\ |A + B |*---|C |\n\ \\ / j\\ L_0/\n\ dD \n\ \ """ ucode_str = \ """\ ⎛ L₀ L₀⎞ ∂ ⎛ ⎞\n\ ⎜A + B ⎟⋅───⎜C ⎟\n\ ⎝ ⎠ j⎝ L₀⎠\n\ ∂D \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = PartialDerivative(B(-i) + A(-i), A(-j), A(-n)) ucode_str = """\ 2 \n\ ∂ ⎛ ⎞\n\ ───────⎜A + B ⎟\n\ ⎝ i i⎠\n\ ∂A ∂A \n\ n j \ """ assert upretty(expr) == ucode_str expr = PartialDerivative(3*A(-i), A(-j), A(-n)) ucode_str = """\ 2 \n\ ∂ ⎛ ⎞\n\ ───────⎜3⋅A ⎟\n\ ⎝ i⎠\n\ ∂A ∂A \n\ n j \ """ assert upretty(expr) == ucode_str expr = TensorElement(H(i, j), {i:1}) ascii_str = \ """\ i=1,j\n\ H \n\ \ """ ucode_str = ascii_str assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = TensorElement(H(i, j), {i: 1, j: 1}) ascii_str = \ """\ i=1,j=1\n\ H \n\ \ """ ucode_str = ascii_str assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = TensorElement(H(i, j), {j: 1}) ascii_str = \ """\ i,j=1\n\ H \n\ \ """ ucode_str = ascii_str expr = TensorElement(H(-i, j), {-i: 1}) ascii_str = \ """\ j\n\ H \n\ i=1 \ """ ucode_str = ascii_str assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_issue_15560(): a = MatrixSymbol('a', 1, 1) e = pretty(a*(KroneckerProduct(a, a))) result = 'a*(a x a)' assert e == result def test_print_lerchphi(): # Part of issue 6013 a = Symbol('a') pretty(lerchphi(a, 1, 2)) uresult = 'Φ(a, 1, 2)' aresult = 'lerchphi(a, 1, 2)' assert pretty(lerchphi(a, 1, 2)) == aresult assert upretty(lerchphi(a, 1, 2)) == uresult def test_issue_15583(): N = mechanics.ReferenceFrame('N') result = '(n_x, n_y, n_z)' e = pretty((N.x, N.y, N.z)) assert e == result def test_matrixSymbolBold(): # Issue 15871 def boldpretty(expr): return xpretty(expr, use_unicode=True, wrap_line=False, mat_symbol_style="bold") from sympy.matrices.expressions.trace import trace A = MatrixSymbol("A", 2, 2) assert boldpretty(trace(A)) == 'tr(𝐀)' A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) C = MatrixSymbol("C", 3, 3) assert boldpretty(-A) == '-𝐀' assert boldpretty(A - A*B - B) == '-𝐁 -𝐀⋅𝐁 + 𝐀' assert boldpretty(-A*B - A*B*C - B) == '-𝐁 -𝐀⋅𝐁 -𝐀⋅𝐁⋅𝐂' A = MatrixSymbol("Addot", 3, 3) assert boldpretty(A) == '𝐀̈' omega = MatrixSymbol("omega", 3, 3) assert boldpretty(omega) == 'ω' omega = MatrixSymbol("omeganorm", 3, 3) assert boldpretty(omega) == '‖ω‖' a = Symbol('alpha') b = Symbol('b') c = MatrixSymbol("c", 3, 1) d = MatrixSymbol("d", 3, 1) assert boldpretty(a*B*c+b*d) == 'b⋅𝐝 + α⋅𝐁⋅𝐜' d = MatrixSymbol("delta", 3, 1) B = MatrixSymbol("Beta", 3, 3) assert boldpretty(a*B*c+b*d) == 'b⋅δ + α⋅Β⋅𝐜' A = MatrixSymbol("A_2", 3, 3) assert boldpretty(A) == '𝐀₂' def test_center_accent(): assert center_accent('a', '\N{COMBINING TILDE}') == 'ã' assert center_accent('aa', '\N{COMBINING TILDE}') == 'aã' assert center_accent('aaa', '\N{COMBINING TILDE}') == 'aãa' assert center_accent('aaaa', '\N{COMBINING TILDE}') == 'aaãa' assert center_accent('aaaaa', '\N{COMBINING TILDE}') == 'aaãaa' assert center_accent('abcdefg', '\N{COMBINING FOUR DOTS ABOVE}') == 'abcd⃜efg' def test_imaginary_unit(): from sympy.printing.pretty import pretty # b/c it was redefined above assert pretty(1 + I, use_unicode=False) == '1 + I' assert pretty(1 + I, use_unicode=True) == '1 + ⅈ' assert pretty(1 + I, use_unicode=False, imaginary_unit='j') == '1 + I' assert pretty(1 + I, use_unicode=True, imaginary_unit='j') == '1 + ⅉ' raises(TypeError, lambda: pretty(I, imaginary_unit=I)) raises(ValueError, lambda: pretty(I, imaginary_unit="kkk")) def test_str_special_matrices(): from sympy.matrices import Identity, ZeroMatrix, OneMatrix assert pretty(Identity(4)) == 'I' assert upretty(Identity(4)) == '𝕀' assert pretty(ZeroMatrix(2, 2)) == '0' assert upretty(ZeroMatrix(2, 2)) == '𝟘' assert pretty(OneMatrix(2, 2)) == '1' assert upretty(OneMatrix(2, 2)) == '𝟙' def test_pretty_misc_functions(): assert pretty(LambertW(x)) == 'W(x)' assert upretty(LambertW(x)) == 'W(x)' assert pretty(LambertW(x, y)) == 'W(x, y)' assert upretty(LambertW(x, y)) == 'W(x, y)' assert pretty(airyai(x)) == 'Ai(x)' assert upretty(airyai(x)) == 'Ai(x)' assert pretty(airybi(x)) == 'Bi(x)' assert upretty(airybi(x)) == 'Bi(x)' assert pretty(airyaiprime(x)) == "Ai'(x)" assert upretty(airyaiprime(x)) == "Ai'(x)" assert pretty(airybiprime(x)) == "Bi'(x)" assert upretty(airybiprime(x)) == "Bi'(x)" assert pretty(fresnelc(x)) == 'C(x)' assert upretty(fresnelc(x)) == 'C(x)' assert pretty(fresnels(x)) == 'S(x)' assert upretty(fresnels(x)) == 'S(x)' assert pretty(Heaviside(x)) == 'Heaviside(x)' assert upretty(Heaviside(x)) == 'θ(x)' assert pretty(Heaviside(x, y)) == 'Heaviside(x, y)' assert upretty(Heaviside(x, y)) == 'θ(x, y)' assert pretty(dirichlet_eta(x)) == 'dirichlet_eta(x)' assert upretty(dirichlet_eta(x)) == 'η(x)' def test_hadamard_power(): m, n, p = symbols('m, n, p', integer=True) A = MatrixSymbol('A', m, n) B = MatrixSymbol('B', m, n) # Testing printer: expr = hadamard_power(A, n) ascii_str = \ """\ .n\n\ A \ """ ucode_str = \ """\ ∘n\n\ A \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hadamard_power(A, 1+n) ascii_str = \ """\ .(n + 1)\n\ A \ """ ucode_str = \ """\ ∘(n + 1)\n\ A \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hadamard_power(A*B.T, 1+n) ascii_str = \ """\ .(n + 1)\n\ / T\\ \n\ \\A*B / \ """ ucode_str = \ """\ ∘(n + 1)\n\ ⎛ T⎞ \n\ ⎝A⋅B ⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_issue_17258(): n = Symbol('n', integer=True) assert pretty(Sum(n, (n, -oo, 1))) == \ ' 1 \n'\ ' __ \n'\ ' \\ ` \n'\ ' ) n\n'\ ' /_, \n'\ 'n = -oo ' assert upretty(Sum(n, (n, -oo, 1))) == \ """\ 1 \n\ ___ \n\ ╲ \n\ ╲ \n\ ╱ n\n\ ╱ \n\ ‾‾‾ \n\ n = -∞ \ """ def test_is_combining(): line = "v̇_m" assert [is_combining(sym) for sym in line] == \ [False, True, False, False] def test_issue_17616(): assert pretty(pi**(1/exp(1))) == \ ' / -1\\\n'\ ' \\e /\n'\ 'pi ' assert upretty(pi**(1/exp(1))) == \ ' ⎛ -1⎞\n'\ ' ⎝ℯ ⎠\n'\ 'π ' assert pretty(pi**(1/pi)) == \ ' 1 \n'\ ' --\n'\ ' pi\n'\ 'pi ' assert upretty(pi**(1/pi)) == \ ' 1\n'\ ' ─\n'\ ' π\n'\ 'π ' assert pretty(pi**(1/EulerGamma)) == \ ' 1 \n'\ ' ----------\n'\ ' EulerGamma\n'\ 'pi ' assert upretty(pi**(1/EulerGamma)) == \ ' 1\n'\ ' ─\n'\ ' γ\n'\ 'π ' z = Symbol("x_17") assert upretty(7**(1/z)) == \ 'x₁₇___\n'\ ' ╲╱ 7 ' assert pretty(7**(1/z)) == \ 'x_17___\n'\ ' \\/ 7 ' def test_issue_17857(): assert pretty(Range(-oo, oo)) == '{..., -1, 0, 1, ...}' assert pretty(Range(oo, -oo, -1)) == '{..., 1, 0, -1, ...}' def test_issue_18272(): x = Symbol('x') n = Symbol('n') assert upretty(ConditionSet(x, Eq(-x + exp(x), 0), S.Complexes)) == \ '⎧ │ ⎛ x ⎞⎫\n'\ '⎨x │ x ∊ ℂ ∧ ⎝-x + ℯ = 0⎠⎬\n'\ '⎩ │ ⎭' assert upretty(ConditionSet(x, Contains(n/2, Interval(0, oo)), FiniteSet(-n/2, n/2))) == \ '⎧ │ ⎧-n n⎫ ⎛n ⎞⎫\n'\ '⎨x │ x ∊ ⎨───, ─⎬ ∧ ⎜─ ∈ [0, ∞)⎟⎬\n'\ '⎩ │ ⎩ 2 2⎭ ⎝2 ⎠⎭' assert upretty(ConditionSet(x, Eq(Piecewise((1, x >= 3), (x/2 - 1/2, x >= 2), (1/2, x >= 1), (x/2, True)) - 1/2, 0), Interval(0, 3))) == \ '⎧ │ ⎛⎛⎧ 1 for x ≥ 3⎞ ⎞⎫\n'\ '⎪ │ ⎜⎜⎪ ⎟ ⎟⎪\n'\ '⎪ │ ⎜⎜⎪x ⎟ ⎟⎪\n'\ '⎪ │ ⎜⎜⎪─ - 0.5 for x ≥ 2⎟ ⎟⎪\n'\ '⎪ │ ⎜⎜⎪2 ⎟ ⎟⎪\n'\ '⎨x │ x ∊ [0, 3] ∧ ⎜⎜⎨ ⎟ - 0.5 = 0⎟⎬\n'\ '⎪ │ ⎜⎜⎪ 0.5 for x ≥ 1⎟ ⎟⎪\n'\ '⎪ │ ⎜⎜⎪ ⎟ ⎟⎪\n'\ '⎪ │ ⎜⎜⎪ x ⎟ ⎟⎪\n'\ '⎪ │ ⎜⎜⎪ ─ otherwise⎟ ⎟⎪\n'\ '⎩ │ ⎝⎝⎩ 2 ⎠ ⎠⎭' def test_Str(): from sympy.core.symbol import Str assert pretty(Str('x')) == 'x' def test_symbolic_probability(): mu = symbols("mu") sigma = symbols("sigma", positive=True) X = Normal("X", mu, sigma) assert pretty(Expectation(X)) == r'E[X]' assert pretty(Variance(X)) == r'Var(X)' assert pretty(Probability(X > 0)) == r'P(X > 0)' Y = Normal("Y", mu, sigma) assert pretty(Covariance(X, Y)) == 'Cov(X, Y)' def test_diffgeom(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField x,y = symbols('x y', real=True) m = Manifold('M', 2) assert pretty(m) == 'M' p = Patch('P', m) assert pretty(p) == "P" rect = CoordSystem('rect', p, [x, y]) assert pretty(rect) == "rect" b = BaseScalarField(rect, 0) assert pretty(b) == "x"
fbefd0237fbeafdb1d1806c91a8b8f70589be96de52608772a941fc18f24089e
""" Utility functions for Rubi integration. See: http://www.apmaths.uwo.ca/~arich/IntegrationRules/PortableDocumentFiles/Integration%20utility%20functions.pdf """ from sympy.external import import_module matchpy = import_module("matchpy") from sympy.concrete.summations import Sum from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.containers import Dict from sympy.core.evalf import N from sympy.core.expr import UnevaluatedExpr from sympy.core.exprtools import factor_terms from sympy.core.function import (Function, WildFunction, expand, expand_trig) from sympy.core.mul import Mul from sympy.core.numbers import (E, Float, I, Integer, Rational, oo, pi, zoo) from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, Wild, symbols) from sympy.core.sympify import sympify from sympy.core.traversal import postorder_traversal from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.complexes import im, re, Abs, sign from sympy.functions.elementary.exponential import exp as sym_exp, log as sym_log, LambertW from sympy.functions.elementary.hyperbolic import acosh, asinh, atanh, acoth, acsch, asech, cosh, sinh, tanh, coth, sech, csch from sympy.functions.elementary.integers import floor, frac from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt) from sympy.functions.elementary.trigonometric import atan, acsc, asin, acot, acos, asec, atan2, sin, cos, tan, cot, csc, sec from sympy.functions.special.elliptic_integrals import elliptic_f, elliptic_e, elliptic_pi from sympy.functions.special.error_functions import erf, fresnelc, fresnels, erfc, erfi, Ei, expint, li, Si, Ci, Shi, Chi from sympy.functions.special.gamma_functions import (digamma, gamma, loggamma, polygamma, uppergamma) from sympy.functions.special.hyper import (appellf1, hyper, TupleArg) from sympy.functions.special.zeta_functions import polylog, zeta from sympy.integrals.integrals import Integral from sympy.logic.boolalg import And, Or from sympy.ntheory.factor_ import (factorint, factorrat) from sympy.polys.partfrac import apart from sympy.polys.polyerrors import (PolynomialDivisionFailed, PolynomialError, UnificationFailed) from sympy.polys.polytools import (discriminant, factor, gcd, lcm, poly, sqf, sqf_list, Poly, degree, quo, rem, total_degree) from sympy.sets.sets import FiniteSet from sympy.simplify.powsimp import powdenest from sympy.simplify.radsimp import collect from sympy.simplify.simplify import fraction, simplify, cancel, powsimp, nsimplify from sympy.utilities.decorator import doctest_depends_on from sympy.utilities.iterables import flatten from sympy.core.random import randint class rubi_unevaluated_expr(UnevaluatedExpr): """ This is needed to convert `exp` as `Pow`. SymPy's UnevaluatedExpr has an issue with `is_commutative`. """ @property def is_commutative(self): from sympy.core.logic import fuzzy_and return fuzzy_and(a.is_commutative for a in self.args) _E = rubi_unevaluated_expr(E) class rubi_exp(Function): """ SymPy's exp is not identified as `Pow`. So it is not matched with `Pow`. Like `a = exp(2)` is not identified as `Pow(E, 2)`. Rubi rules need it. So, another exp has been created only for rubi module. Examples ======== >>> from sympy import Pow, exp as sym_exp >>> isinstance(sym_exp(2), Pow) False >>> from sympy.integrals.rubi.utility_function import rubi_exp >>> isinstance(rubi_exp(2), Pow) True """ @classmethod def eval(cls, *args): return Pow(_E, args[0]) class rubi_log(Function): """ For rule matching different `exp` has been used. So for proper results, `log` is modified little only for case when it encounters rubi's `exp`. For other cases it is same. Examples ======== >>> from sympy.integrals.rubi.utility_function import rubi_exp, rubi_log >>> a = rubi_exp(2) >>> rubi_log(a) 2 """ @classmethod def eval(cls, *args): if args[0].has(_E): return sym_log(args[0]).doit() else: return sym_log(args[0]) if matchpy: from matchpy import Arity, Operation, CustomConstraint, Pattern, ReplacementRule, ManyToOneReplacer from sympy.integrals.rubi.symbol import WC from matchpy import is_match, replace_all class UtilityOperator(Operation): name = 'UtilityOperator' arity = Arity.variadic commutative = False associative = True Operation.register(rubi_log) Operation.register(rubi_exp) A_, B_, C_, F_, G_, a_, b_, c_, d_, e_, f_, g_, h_, i_, j_, k_, l_, m_, \ n_, p_, q_, r_, t_, u_, v_, s_, w_, x_, z_ = [WC(i) for i in 'ABCFGabcdefghijklmnpqrtuvswxz'] a, b, c, d, e = symbols('a b c d e') Int = Integral def replace_pow_exp(z): """ This function converts back rubi's `exp` to general SymPy's `exp`. Examples ======== >>> from sympy.integrals.rubi.utility_function import rubi_exp, replace_pow_exp >>> expr = rubi_exp(5) >>> expr E**5 >>> replace_pow_exp(expr) exp(5) """ z = S(z) if z.has(_E): z = z.replace(_E, E) return z def Simplify(expr): expr = simplify(expr) return expr def Set(expr, value): return {expr: value} def With(subs, expr): if isinstance(subs, dict): k = list(subs.keys())[0] expr = expr.xreplace({k: subs[k]}) else: for i in subs: k = list(i.keys())[0] expr = expr.xreplace({k: i[k]}) return expr def Module(subs, expr): return With(subs, expr) def Scan(f, expr): # evaluates f applied to each element of expr in turn. for i in expr: yield f(i) def MapAnd(f, l, x=None): # MapAnd[f,l] applies f to the elements of list l until False is returned; else returns True if x: for i in l: if f(i, x) == False: return False return True else: for i in l: if f(i) == False: return False return True def FalseQ(u): if isinstance(u, (Dict, dict)): return FalseQ(*list(u.values())) return u == False def ZeroQ(*expr): if len(expr) == 1: if isinstance(expr[0], list): return list(ZeroQ(i) for i in expr[0]) else: return Simplify(expr[0]) == 0 else: return all(ZeroQ(i) for i in expr) def OneQ(a): if a == S(1): return True return False def NegativeQ(u): u = Simplify(u) if u in (zoo, oo): return False if u.is_comparable: res = u < 0 if not res.is_Relational: return res return False def NonzeroQ(expr): return Simplify(expr) != 0 def FreeQ(nodes, var): if isinstance(nodes, list): return not any(S(expr).has(var) for expr in nodes) else: nodes = S(nodes) return not nodes.has(var) def NFreeQ(nodes, var): """ Note that in rubi 4.10.8 this function was not defined in `Integration Utility Functions.m`, but was used in rules. So explicitly its returning `False` """ return False # return not FreeQ(nodes, var) def List(*var): return list(var) def PositiveQ(var): var = Simplify(var) if var in (zoo, oo): return False if var.is_comparable: res = var > 0 if not res.is_Relational: return res return False def PositiveIntegerQ(*args): return all(var.is_Integer and PositiveQ(var) for var in args) def NegativeIntegerQ(*args): return all(var.is_Integer and NegativeQ(var) for var in args) def IntegerQ(var): var = Simplify(var) if isinstance(var, (int, Integer)): return True else: return var.is_Integer def IntegersQ(*var): return all(IntegerQ(i) for i in var) def _ComplexNumberQ(var): i = S(im(var)) if isinstance(i, (Integer, Float)): return i != 0 else: return False def ComplexNumberQ(*var): """ ComplexNumberQ(m, n,...) returns True if m, n, ... are all explicit complex numbers, else it returns False. Examples ======== >>> from sympy.integrals.rubi.utility_function import ComplexNumberQ >>> from sympy import I >>> ComplexNumberQ(1 + I*2, I) True >>> ComplexNumberQ(2, I) False """ return all(_ComplexNumberQ(i) for i in var) def PureComplexNumberQ(*var): return all((_ComplexNumberQ(i) and re(i)==0) for i in var) def RealNumericQ(u): return u.is_real def PositiveOrZeroQ(u): return u.is_real and u >= 0 def NegativeOrZeroQ(u): return u.is_real and u <= 0 def FractionOrNegativeQ(u): return FractionQ(u) or NegativeQ(u) def NegQ(var): return Not(PosQ(var)) and NonzeroQ(var) def Equal(a, b): return a == b def Unequal(a, b): return a != b def IntPart(u): # IntPart[u] returns the sum of the integer terms of u. if ProductQ(u): if IntegerQ(First(u)): return First(u)*IntPart(Rest(u)) elif IntegerQ(u): return u elif FractionQ(u): return IntegerPart(u) elif SumQ(u): res = 0 for i in u.args: res += IntPart(i) return res return 0 def FracPart(u): # FracPart[u] returns the sum of the non-integer terms of u. if ProductQ(u): if IntegerQ(First(u)): return First(u)*FracPart(Rest(u)) if IntegerQ(u): return 0 elif FractionQ(u): return FractionalPart(u) elif SumQ(u): res = 0 for i in u.args: res += FracPart(i) return res else: return u def RationalQ(*nodes): return all(var.is_Rational for var in nodes) def ProductQ(expr): return S(expr).is_Mul def SumQ(expr): return expr.is_Add def NonsumQ(expr): return not SumQ(expr) def Subst(a, x, y): if None in [a, x, y]: return None if a.has(Function('Integrate')): # substituting in `Function(Integrate)` won't take care of properties of Integral a = a.replace(Function('Integrate'), Integral) return a.subs(x, y) # return a.xreplace({x: y}) def First(expr, d=None): """ Gives the first element if it exists, or d otherwise. Examples ======== >>> from sympy.integrals.rubi.utility_function import First >>> from sympy.abc import a, b, c >>> First(a + b + c) a >>> First(a*b*c) a """ if isinstance(expr, list): return expr[0] if isinstance(expr, Symbol): return expr else: if SumQ(expr) or ProductQ(expr): l = Sort(expr.args) return l[0] else: return expr.args[0] def Rest(expr): """ Gives rest of the elements if it exists Examples ======== >>> from sympy.integrals.rubi.utility_function import Rest >>> from sympy.abc import a, b, c >>> Rest(a + b + c) b + c >>> Rest(a*b*c) b*c """ if isinstance(expr, list): return expr[1:] else: if SumQ(expr) or ProductQ(expr): l = Sort(expr.args) return expr.func(*l[1:]) else: return expr.args[1] def SqrtNumberQ(expr): # SqrtNumberQ[u] returns True if u^2 is a rational number; else it returns False. if PowerQ(expr): m = expr.base n = expr.exp return (IntegerQ(n) and SqrtNumberQ(m)) or (IntegerQ(n-S(1)/2) and RationalQ(m)) elif expr.is_Mul: return all(SqrtNumberQ(i) for i in expr.args) else: return RationalQ(expr) or expr == I def SqrtNumberSumQ(u): return SumQ(u) and SqrtNumberQ(First(u)) and SqrtNumberQ(Rest(u)) or ProductQ(u) and SqrtNumberQ(First(u)) and SqrtNumberSumQ(Rest(u)) def LinearQ(expr, x): """ LinearQ(expr, x) returns True iff u is a polynomial of degree 1. Examples ======== >>> from sympy.integrals.rubi.utility_function import LinearQ >>> from sympy.abc import x, y, a >>> LinearQ(a, x) False >>> LinearQ(3*x + y**2, x) True >>> LinearQ(3*x + y**2, y) False """ if isinstance(expr, list): return all(LinearQ(i, x) for i in expr) elif expr.is_polynomial(x): if degree(Poly(expr, x), gen=x) == 1: return True return False def Sqrt(a): return sqrt(a) def ArcCosh(a): return acosh(a) class Util_Coefficient(Function): def doit(self): if len(self.args) == 2: n = 1 else: n = Simplify(self.args[2]) if NumericQ(n): expr = expand(self.args[0]) if isinstance(n, (int, Integer)): return expr.coeff(self.args[1], n) else: return expr.coeff(self.args[1]**n) else: return self def Coefficient(expr, var, n=1): """ Coefficient(expr, var) gives the coefficient of form in the polynomial expr. Coefficient(expr, var, n) gives the coefficient of var**n in expr. Examples ======== >>> from sympy.integrals.rubi.utility_function import Coefficient >>> from sympy.abc import x, a, b, c >>> Coefficient(7 + 2*x + 4*x**3, x, 1) 2 >>> Coefficient(a + b*x + c*x**3, x, 0) a >>> Coefficient(a + b*x + c*x**3, x, 4) 0 >>> Coefficient(b*x + c*x**3, x, 3) c """ if NumericQ(n): if expr == 0 or n in (zoo, oo): return 0 expr = expand(expr) if isinstance(n, (int, Integer)): return expr.coeff(var, n) else: return expr.coeff(var**n) return Util_Coefficient(expr, var, n) def Denominator(var): var = Simplify(var) if isinstance(var, Pow): if isinstance(var.exp, Integer): if var.exp > 0: return Pow(Denominator(var.base), var.exp) elif var.exp < 0: return Pow(Numerator(var.base), -1*var.exp) elif isinstance(var, Add): var = factor(var) return fraction(var)[1] def Hypergeometric2F1(a, b, c, z): return hyper([a, b], [c], z) def Not(var): if isinstance(var, bool): return not var elif var.is_Relational: var = False return not var def FractionalPart(a): return frac(a) def IntegerPart(a): return floor(a) def AppellF1(a, b1, b2, c, x, y): return appellf1(a, b1, b2, c, x, y) def EllipticPi(*args): return elliptic_pi(*args) def EllipticE(*args): return elliptic_e(*args) def EllipticF(Phi, m): return elliptic_f(Phi, m) def ArcTan(a, b = None): if b is None: return atan(a) else: return atan2(a, b) def ArcCot(a): return acot(a) def ArcCoth(a): return acoth(a) def ArcTanh(a): return atanh(a) def ArcSin(a): return asin(a) def ArcSinh(a): return asinh(a) def ArcCos(a): return acos(a) def ArcCsc(a): return acsc(a) def ArcSec(a): return asec(a) def ArcCsch(a): return acsch(a) def ArcSech(a): return asech(a) def Sinh(u): return sinh(u) def Tanh(u): return tanh(u) def Cosh(u): return cosh(u) def Sech(u): return sech(u) def Csch(u): return csch(u) def Coth(u): return coth(u) def LessEqual(*args): for i in range(0, len(args) - 1): try: if args[i] > args[i + 1]: return False except (IndexError, NotImplementedError): return False return True def Less(*args): for i in range(0, len(args) - 1): try: if args[i] >= args[i + 1]: return False except (IndexError, NotImplementedError): return False return True def Greater(*args): for i in range(0, len(args) - 1): try: if args[i] <= args[i + 1]: return False except (IndexError, NotImplementedError): return False return True def GreaterEqual(*args): for i in range(0, len(args) - 1): try: if args[i] < args[i + 1]: return False except (IndexError, NotImplementedError): return False return True def FractionQ(*args): """ FractionQ(m, n,...) returns True if m, n, ... are all explicit fractions, else it returns False. Examples ======== >>> from sympy import S >>> from sympy.integrals.rubi.utility_function import FractionQ >>> FractionQ(S('3')) False >>> FractionQ(S('3')/S('2')) True """ return all(i.is_Rational for i in args) and all(Denominator(i) != S(1) for i in args) def IntLinearcQ(a, b, c, d, m, n, x): # returns True iff (a+b*x)^m*(c+d*x)^n is integrable wrt x in terms of non-hypergeometric functions. return IntegerQ(m) or IntegerQ(n) or IntegersQ(S(3)*m, S(3)*n) or IntegersQ(S(4)*m, S(4)*n) or IntegersQ(S(2)*m, S(6)*n) or IntegersQ(S(6)*m, S(2)*n) or IntegerQ(m + n) Defer = UnevaluatedExpr def Expand(expr): return expr.expand() def IndependentQ(u, x): """ If u is free from x IndependentQ(u, x) returns True else False. Examples ======== >>> from sympy.integrals.rubi.utility_function import IndependentQ >>> from sympy.abc import x, a, b >>> IndependentQ(a + b*x, x) False >>> IndependentQ(a + b, x) True """ return FreeQ(u, x) def PowerQ(expr): return expr.is_Pow or ExpQ(expr) def IntegerPowerQ(u): if isinstance(u, sym_exp): #special case for exp return IntegerQ(u.args[0]) return PowerQ(u) and IntegerQ(u.args[1]) def PositiveIntegerPowerQ(u): if isinstance(u, sym_exp): return IntegerQ(u.args[0]) and PositiveQ(u.args[0]) return PowerQ(u) and IntegerQ(u.args[1]) and PositiveQ(u.args[1]) def FractionalPowerQ(u): if isinstance(u, sym_exp): return FractionQ(u.args[0]) return PowerQ(u) and FractionQ(u.args[1]) def AtomQ(expr): expr = sympify(expr) if isinstance(expr, list): return False if expr in [None, True, False, _E]: # [None, True, False] are atoms in mathematica and _E is also an atom return True # elif isinstance(expr, list): # return all(AtomQ(i) for i in expr) else: return expr.is_Atom def ExpQ(u): u = replace_pow_exp(u) return Head(u) in (sym_exp, rubi_exp) def LogQ(u): return u.func in (sym_log, Log) def Head(u): return u.func def MemberQ(l, u): if isinstance(l, list): return u in l else: return u in l.args def TrigQ(u): if AtomQ(u): x = u else: x = Head(u) return MemberQ([sin, cos, tan, cot, sec, csc], x) def SinQ(u): return Head(u) == sin def CosQ(u): return Head(u) == cos def TanQ(u): return Head(u) == tan def CotQ(u): return Head(u) == cot def SecQ(u): return Head(u) == sec def CscQ(u): return Head(u) == csc def Sin(u): return sin(u) def Cos(u): return cos(u) def Tan(u): return tan(u) def Cot(u): return cot(u) def Sec(u): return sec(u) def Csc(u): return csc(u) def HyperbolicQ(u): if AtomQ(u): x = u else: x = Head(u) return MemberQ([sinh, cosh, tanh, coth, sech, csch], x) def SinhQ(u): return Head(u) == sinh def CoshQ(u): return Head(u) == cosh def TanhQ(u): return Head(u) == tanh def CothQ(u): return Head(u) == coth def SechQ(u): return Head(u) == sech def CschQ(u): return Head(u) == csch def InverseTrigQ(u): if AtomQ(u): x = u else: x = Head(u) return MemberQ([asin, acos, atan, acot, asec, acsc], x) def SinCosQ(f): return MemberQ([sin, cos, sec, csc], Head(f)) def SinhCoshQ(f): return MemberQ([sinh, cosh, sech, csch], Head(f)) def LeafCount(expr): return len(list(postorder_traversal(expr))) def Numerator(u): u = Simplify(u) if isinstance(u, Pow): if isinstance(u.exp, Integer): if u.exp > 0: return Pow(Numerator(u.base), u.exp) elif u.exp < 0: return Pow(Denominator(u.base), -1*u.exp) elif isinstance(u, Add): u = factor(u) return fraction(u)[0] def NumberQ(u): if isinstance(u, (int, float)): return True return u.is_number def NumericQ(u): return N(u).is_number def Length(expr): """ Returns number of elements in the expression just as SymPy's len. Examples ======== >>> from sympy.integrals.rubi.utility_function import Length >>> from sympy.abc import x, a, b >>> from sympy import cos, sin >>> Length(a + b) 2 >>> Length(sin(a)*cos(a)) 2 """ if isinstance(expr, list): return len(expr) return len(expr.args) def ListQ(u): return isinstance(u, list) def Im(u): u = S(u) return im(u.doit()) def Re(u): u = S(u) return re(u.doit()) def InverseHyperbolicQ(u): if not u.is_Atom: u = Head(u) return u in [acosh, asinh, atanh, acoth, acsch, acsch] def InverseFunctionQ(u): # returns True if u is a call on an inverse function; else returns False. return LogQ(u) or InverseTrigQ(u) and Length(u) <= 1 or InverseHyperbolicQ(u) or u.func == polylog def TrigHyperbolicFreeQ(u, x): # If u is free of trig, hyperbolic and calculus functions involving x, TrigHyperbolicFreeQ[u,x] returns true; else it returns False. if AtomQ(u): return True else: if TrigQ(u) | HyperbolicQ(u) | CalculusQ(u): return FreeQ(u, x) else: for i in u.args: if not TrigHyperbolicFreeQ(i, x): return False return True def InverseFunctionFreeQ(u, x): # If u is free of inverse, calculus and hypergeometric functions involving x, InverseFunctionFreeQ[u,x] returns true; else it returns False. if AtomQ(u): return True else: if InverseFunctionQ(u) or CalculusQ(u) or u.func in (hyper, appellf1): return FreeQ(u, x) else: for i in u.args: if not ElementaryFunctionQ(i): return False return True def RealQ(u): if ListQ(u): return MapAnd(RealQ, u) elif NumericQ(u): return ZeroQ(Im(N(u))) elif PowerQ(u): u = u.base v = u.exp return RealQ(u) & RealQ(v) & (IntegerQ(v) | PositiveOrZeroQ(u)) elif u.is_Mul: return all(RealQ(i) for i in u.args) elif u.is_Add: return all(RealQ(i) for i in u.args) elif u.is_Function: f = u.func u = u.args[0] if f in [sin, cos, tan, cot, sec, csc, atan, acot, erf]: return RealQ(u) else: if f in [asin, acos]: return LE(-1, u, 1) else: if f == sym_log: return PositiveOrZeroQ(u) else: return False else: return False def EqQ(u, v): return ZeroQ(u - v) def FractionalPowerFreeQ(u): if AtomQ(u): return True elif FractionalPowerQ(u): return False def ComplexFreeQ(u): if AtomQ(u) and Not(ComplexNumberQ(u)): return True else: return False def PolynomialQ(u, x = None): if x is None : return u.is_polynomial() if isinstance(x, Pow): if isinstance(x.exp, Integer): deg = degree(u, x.base) if u.is_polynomial(x): if deg % x.exp !=0 : return False try: p = Poly(u, x.base) except PolynomialError: return False c_list = p.all_coeffs() coeff_list = c_list[:-1:x.exp] coeff_list += [c_list[-1]] for i in coeff_list: if not i == 0: index = c_list.index(i) c_list[index] = 0 if all(i == 0 for i in c_list): return True else: return False else: return False elif isinstance(x.exp, (Float, Rational)): #not full - proof if FreeQ(simplify(u), x.base) and Exponent(u, x.base) == 0: if not all(FreeQ(u, i) for i in x.base.free_symbols): return False if isinstance(x, Mul): return all(PolynomialQ(u, i) for i in x.args) return u.is_polynomial(x) def FactorSquareFree(u): return sqf(u) def PowerOfLinearQ(expr, x): u = Wild('u') w = Wild('w') m = Wild('m') n = Wild('n') Match = expr.match(u**m) if PolynomialQ(Match[u], x) and FreeQ(Match[m], x): if IntegerQ(Match[m]): e = FactorSquareFree(Match[u]).match(w**n) if FreeQ(e[n], x) and LinearQ(e[w], x): return True else: return False else: return LinearQ(Match[u], x) else: return False def Exponent(expr, x): expr = Expand(S(expr)) if S(expr).is_number or (not expr.has(x)): return 0 if PolynomialQ(expr, x): if isinstance(x, Rational): return degree(Poly(expr, x), x) return degree(expr, gen = x) else: return 0 def ExponentList(expr, x): expr = Expand(S(expr)) if S(expr).is_number or (not expr.has(x)): return [0] if expr.is_Add: expr = collect(expr, x) lst = [] k = 1 for t in expr.args: if t.has(x): if isinstance(x, Rational): lst += [degree(Poly(t, x), x)] else: lst += [degree(t, gen = x)] else: if k == 1: lst += [0] k += 1 lst.sort() return lst else: if isinstance(x, Rational): return [degree(Poly(expr, x), x)] else: return [degree(expr, gen = x)] def QuadraticQ(u, x): # QuadraticQ(u, x) returns True iff u is a polynomial of degree 2 and not a monomial of the form a x^2 if ListQ(u): for expr in u: if Not(PolyQ(expr, x, 2) and Not(Coefficient(expr, x, 0) == 0 and Coefficient(expr, x, 1) == 0)): return False return True else: return PolyQ(u, x, 2) and Not(Coefficient(u, x, 0) == 0 and Coefficient(u, x, 1) == 0) def LinearPairQ(u, v, x): # LinearPairQ(u, v, x) returns True iff u and v are linear not equal x but u/v is a constant wrt x return LinearQ(u, x) and LinearQ(v, x) and NonzeroQ(u-x) and ZeroQ(Coefficient(u, x, 0)*Coefficient(v, x, 1)-Coefficient(u, x, 1)*Coefficient(v, x, 0)) def BinomialParts(u, x): if PolynomialQ(u, x): if Exponent(u, x) > 0: lst = ExponentList(u, x) if len(lst)==1: return [0, Coefficient(u, x, Exponent(u, x)), Exponent(u, x)] elif len(lst) == 2 and lst[0] == 0: return [Coefficient(u, x, 0), Coefficient(u, x, Exponent(u, x)), Exponent(u, x)] else: return False else: return False elif PowerQ(u): if u.base == x and FreeQ(u.exp, x): return [0, 1, u.exp] else: return False elif ProductQ(u): if FreeQ(First(u), x): lst2 = BinomialParts(Rest(u), x) if AtomQ(lst2): return False else: return [First(u)*lst2[0], First(u)*lst2[1], lst2[2]] elif FreeQ(Rest(u), x): lst1 = BinomialParts(First(u), x) if AtomQ(lst1): return False else: return [Rest(u)*lst1[0], Rest(u)*lst1[1], lst1[2]] lst1 = BinomialParts(First(u), x) if AtomQ(lst1): return False lst2 = BinomialParts(Rest(u), x) if AtomQ(lst2): return False a = lst1[0] b = lst1[1] m = lst1[2] c = lst2[0] d = lst2[1] n = lst2[2] if ZeroQ(a): if ZeroQ(c): return [0, b*d, m + n] elif ZeroQ(m + n): return [b*d, b*c, m] else: return False if ZeroQ(c): if ZeroQ(m + n): return [b*d, a*d, n] else: return False if EqQ(m, n) and ZeroQ(a*d + b*c): return [a*c, b*d, 2*m] else: return False elif SumQ(u): if FreeQ(First(u),x): lst2 = BinomialParts(Rest(u), x) if AtomQ(lst2): return False else: return [First(u) + lst2[0], lst2[1], lst2[2]] elif FreeQ(Rest(u), x): lst1 = BinomialParts(First(u), x) if AtomQ(lst1): return False else: return[Rest(u) + lst1[0], lst1[1], lst1[2]] lst1 = BinomialParts(First(u), x) if AtomQ(lst1): return False lst2 = BinomialParts(Rest(u),x) if AtomQ(lst2): return False if EqQ(lst1[2], lst2[2]): return [lst1[0] + lst2[0], lst1[1] + lst2[1], lst1[2]] else: return False else: return False def TrinomialParts(u, x): # If u is equivalent to a trinomial of the form a + b*x^n + c*x^(2*n) where n!=0, b!=0 and c!=0, TrinomialParts[u,x] returns the list {a,b,c,n}; else it returns False. u = sympify(u) if PolynomialQ(u, x): lst = CoefficientList(u, x) if len(lst)<3 or EvenQ(sympify(len(lst))) or ZeroQ((len(lst)+1)/2): return False #Catch( # Scan(Function(if ZeroQ(lst), Null, Throw(False), Drop(Drop(Drop(lst, [(len(lst)+1)/2]), 1), -1]; # [First(lst), lst[(len(lst)+1)/2], Last(lst), (len(lst)-1)/2]): if PowerQ(u): if EqQ(u.exp, 2): lst = BinomialParts(u.base, x) if not lst or ZeroQ(lst[0]): return False else: return [lst[0]**2, 2*lst[0]*lst[1], lst[1]**2, lst[2]] else: return False if ProductQ(u): if FreeQ(First(u), x): lst2 = TrinomialParts(Rest(u), x) if not lst2: return False else: return [First(u)*lst2[0], First(u)*lst2[1], First(u)*lst2[2], lst2[3]] if FreeQ(Rest(u), x): lst1 = TrinomialParts(First(u), x) if not lst1: return False else: return [Rest(u)*lst1[0], Rest(u)*lst1[1], Rest(u)*lst1[2], lst1[3]] lst1 = BinomialParts(First(u), x) if not lst1: return False lst2 = BinomialParts(Rest(u), x) if not lst2: return False a = lst1[0] b = lst1[1] m = lst1[2] c = lst2[0] d = lst2[1] n = lst2[2] if EqQ(m, n) and NonzeroQ(a*d+b*c): return [a*c, a*d + b*c, b*d, m] else: return False if SumQ(u): if FreeQ(First(u), x): lst2 = TrinomialParts(Rest(u), x) if not lst2: return False else: return [First(u)+lst2[0], lst2[1], lst2[2], lst2[3]] if FreeQ(Rest(u), x): lst1 = TrinomialParts(First(u), x) if not lst1: return False else: return [Rest(u)+lst1[0], lst1[1], lst1[2], lst1[3]] lst1 = TrinomialParts(First(u), x) if not lst1: lst3 = BinomialParts(First(u), x) if not lst3: return False lst2 = TrinomialParts(Rest(u), x) if not lst2: lst4 = BinomialParts(Rest(u), x) if not lst4: return False if EqQ(lst3[2], 2*lst4[2]): return [lst3[0]+lst4[0], lst4[1], lst3[1], lst4[2]] if EqQ(lst4[2], 2*lst3[2]): return [lst3[0]+lst4[0], lst3[1], lst4[1], lst3[2]] else: return False if EqQ(lst3[2], lst2[3]) and NonzeroQ(lst3[1]+lst2[1]): return [lst3[0]+lst2[0], lst3[1]+lst2[1], lst2[2], lst2[3]] if EqQ(lst3[2], 2*lst2[3]) and NonzeroQ(lst3[1]+lst2[2]): return [lst3[0]+lst2[0], lst2[1], lst3[1]+lst2[2], lst2[3]] else: return False lst2 = TrinomialParts(Rest(u), x) if AtomQ(lst2): lst4 = BinomialParts(Rest(u), x) if not lst4: return False if EqQ(lst4[2], lst1[3]) and NonzeroQ(lst1[1]+lst4[0]): return [lst1[0]+lst4[0], lst1[1]+lst4[1], lst1[2], lst1[3]] if EqQ(lst4[2], 2*lst1[3]) and NonzeroQ(lst1[2]+lst4[1]): return [lst1[0]+lst4[0], lst1[1], lst1[2]+lst4[1], lst1[3]] else: return False if EqQ(lst1[3], lst2[3]) and NonzeroQ(lst1[1]+lst2[1]) and NonzeroQ(lst1[2]+lst2[2]): return [lst1[0]+lst2[0], lst1[1]+lst2[1], lst1[2]+lst2[2], lst1[3]] else: return False else: return False def PolyQ(u, x, n=None): # returns True iff u is a polynomial of degree n. if ListQ(u): return all(PolyQ(i, x) for i in u) if n is None: if u == x: return False elif isinstance(x, Pow): n = x.exp x_base = x.base if FreeQ(n, x_base): if PositiveIntegerQ(n): return PolyQ(u, x_base) and (PolynomialQ(u, x) or PolynomialQ(Together(u), x)) elif AtomQ(n): return PolynomialQ(u, x) and FreeQ(CoefficientList(u, x), x_base) else: return False return PolynomialQ(u, x) or PolynomialQ(u, Together(x)) else: return PolynomialQ(u, x) and Coefficient(u, x, n) != 0 and Exponent(u, x) == n def EvenQ(u): # gives True if expr is an even integer, and False otherwise. return isinstance(u, (Integer, int)) and u%2 == 0 def OddQ(u): # gives True if expr is an odd integer, and False otherwise. return isinstance(u, (Integer, int)) and u%2 == 1 def PerfectSquareQ(u): # (* If u is a rational number whose squareroot is rational or if u is of the form u1^n1 u2^n2 ... # and n1, n2, ... are even, PerfectSquareQ[u] returns True; else it returns False. *) if RationalQ(u): return Greater(u, 0) and RationalQ(Sqrt(u)) elif PowerQ(u): return EvenQ(u.exp) elif ProductQ(u): return PerfectSquareQ(First(u)) and PerfectSquareQ(Rest(u)) elif SumQ(u): s = Simplify(u) if NonsumQ(s): return PerfectSquareQ(s) return False else: return False def NiceSqrtAuxQ(u): if RationalQ(u): return u > 0 elif PowerQ(u): return EvenQ(u.exp) elif ProductQ(u): return NiceSqrtAuxQ(First(u)) and NiceSqrtAuxQ(Rest(u)) elif SumQ(u): s = Simplify(u) return NonsumQ(s) and NiceSqrtAuxQ(s) else: return False def NiceSqrtQ(u): return Not(NegativeQ(u)) and NiceSqrtAuxQ(u) def Together(u): return factor(u) def PosAux(u): if RationalQ(u): return u>0 elif NumberQ(u): if ZeroQ(Re(u)): return Im(u) > 0 else: return Re(u) > 0 elif NumericQ(u): v = N(u) if ZeroQ(Re(v)): return Im(v) > 0 else: return Re(v) > 0 elif PowerQ(u): if OddQ(u.exp): return PosAux(u.base) else: return True elif ProductQ(u): if PosAux(First(u)): return PosAux(Rest(u)) else: return not PosAux(Rest(u)) elif SumQ(u): return PosAux(First(u)) else: res = u > 0 if res in(True, False): return res return True def PosQ(u): # If u is not 0 and has a positive form, PosQ[u] returns True, else it returns False. return PosAux(TogetherSimplify(u)) def CoefficientList(u, x): if PolynomialQ(u, x): return list(reversed(Poly(u, x).all_coeffs())) else: return [] def ReplaceAll(expr, args): if isinstance(args, list): n_args = {} for i in args: n_args.update(i) return expr.subs(n_args) return expr.subs(args) def ExpandLinearProduct(v, u, a, b, x): # If u is a polynomial in x, ExpandLinearProduct[v,u,a,b,x] expands v*u into a sum of terms of the form c*v*(a+b*x)^n. if FreeQ([a, b], x) and PolynomialQ(u, x): lst = CoefficientList(ReplaceAll(u, {x: (x - a)/b}), x) lst = [SimplifyTerm(i, x) for i in lst] res = 0 for k in range(1, len(lst)+1): res = res + Simplify(v*lst[k-1]*(a + b*x)**(k - 1)) return res return u*v def GCD(*args): args = S(args) if len(args) == 1: if isinstance(args[0], (int, Integer)): return args[0] else: return S(1) return gcd(*args) def ContentFactor(expn): return factor_terms(expn) def NumericFactor(u): # returns the real numeric factor of u. if NumberQ(u): if ZeroQ(Im(u)): return u elif ZeroQ(Re(u)): return Im(u) else: return S(1) elif PowerQ(u): if RationalQ(u.base) and RationalQ(u.exp): if u.exp > 0: return 1/Denominator(u.base) else: return 1/(1/Denominator(u.base)) else: return S(1) elif ProductQ(u): return Mul(*[NumericFactor(i) for i in u.args]) elif SumQ(u): if LeafCount(u) < 50: c = ContentFactor(u) if SumQ(c): return S(1) else: return NumericFactor(c) else: m = NumericFactor(First(u)) n = NumericFactor(Rest(u)) if m < 0 and n < 0: return -GCD(-m, -n) else: return GCD(m, n) return S(1) def NonnumericFactors(u): if NumberQ(u): if ZeroQ(Im(u)): return S(1) elif ZeroQ(Re(u)): return I return u elif PowerQ(u): if RationalQ(u.base) and FractionQ(u.exp): return u/NumericFactor(u) return u elif ProductQ(u): result = 1 for i in u.args: result *= NonnumericFactors(i) return result elif SumQ(u): if LeafCount(u) < 50: i = ContentFactor(u) if SumQ(i): return u else: return NonnumericFactors(i) n = NumericFactor(u) result = 0 for i in u.args: result += i/n return result return u def MakeAssocList(u, x, alst=None): # (* MakeAssocList[u,x,alst] returns an association list of gensymed symbols with the nonatomic # parameters of a u that are not integer powers, products or sums. *) if alst is None: alst = [] u = replace_pow_exp(u) x = replace_pow_exp(x) if AtomQ(u): return alst elif IntegerPowerQ(u): return MakeAssocList(u.base, x, alst) elif ProductQ(u) or SumQ(u): return MakeAssocList(Rest(u), x, MakeAssocList(First(u), x, alst)) elif FreeQ(u, x): tmp = [] for i in alst: if PowerQ(i): if i.exp == u: tmp.append(i) break elif len(i.args) > 1: # make sure args has length > 1, else causes index error some times if i.args[1] == u: tmp.append(i) break if tmp == []: alst.append(u) return alst return alst def GensymSubst(u, x, alst=None): # (* GensymSubst[u,x,alst] returns u with the kernels in alst free of x replaced by gensymed names. *) if alst is None: alst =[] u = replace_pow_exp(u) x = replace_pow_exp(x) if AtomQ(u): return u elif IntegerPowerQ(u): return GensymSubst(u.base, x, alst)**u.exp elif ProductQ(u) or SumQ(u): return u.func(*[GensymSubst(i, x, alst) for i in u.args]) elif FreeQ(u, x): tmp = [] for i in alst: if PowerQ(i): if i.exp == u: tmp.append(i) break elif len(i.args) > 1: # make sure args has length > 1, else causes index error some times if i.args[1] == u: tmp.append(i) break if tmp == []: return u return tmp[0][0] return u def KernelSubst(u, x, alst): # (* KernelSubst[u,x,alst] returns u with the gensymed names in alst replaced by kernels free of x. *) if AtomQ(u): tmp = [] for i in alst: if i.args[0] == u: tmp.append(i) break if tmp == []: return u elif len(tmp[0].args) > 1: # make sure args has length > 1, else causes index error some times return tmp[0].args[1] elif IntegerPowerQ(u): tmp = KernelSubst(u.base, x, alst) if u.exp < 0 and ZeroQ(tmp): return 'Indeterminate' return tmp**u.exp elif ProductQ(u) or SumQ(u): return u.func(*[KernelSubst(i, x, alst) for i in u.args]) return u def ExpandExpression(u, x): if AlgebraicFunctionQ(u, x) and Not(RationalFunctionQ(u, x)): v = ExpandAlgebraicFunction(u, x) else: v = S(0) if SumQ(v): return ExpandCleanup(v, x) v = SmartApart(u, x) if SumQ(v): return ExpandCleanup(v, x) v = SmartApart(RationalFunctionFactors(u, x), x, x) if SumQ(v): w = NonrationalFunctionFactors(u, x) return ExpandCleanup(v.func(*[i*w for i in v.args]), x) v = Expand(u) if SumQ(v): return ExpandCleanup(v, x) v = Expand(u) if SumQ(v): return ExpandCleanup(v, x) return SimplifyTerm(u, x) def Apart(u, x): if RationalFunctionQ(u, x): return apart(u, x) return u def SmartApart(*args): if len(args) == 2: u, x = args alst = MakeAssocList(u, x) tmp = KernelSubst(Apart(GensymSubst(u, x, alst), x), x, alst) if tmp == 'Indeterminate': return u return tmp u, v, x = args alst = MakeAssocList(u, x) tmp = KernelSubst(Apart(GensymSubst(u, x, alst), x), x, alst) if tmp == 'Indeterminate': return u return tmp def MatchQ(expr, pattern, *var): # returns the matched arguments after matching pattern with expression match = expr.match(pattern) if match: return tuple(match[i] for i in var) else: return None def PolynomialQuotientRemainder(p, q, x): return [PolynomialQuotient(p, q, x), PolynomialRemainder(p, q, x)] def FreeFactors(u, x): # returns the product of the factors of u free of x. if ProductQ(u): result = 1 for i in u.args: if FreeQ(i, x): result *= i return result elif FreeQ(u, x): return u else: return S(1) def NonfreeFactors(u, x): """ Returns the product of the factors of u not free of x. Examples ======== >>> from sympy.integrals.rubi.utility_function import NonfreeFactors >>> from sympy.abc import x, a, b >>> NonfreeFactors(a, x) 1 >>> NonfreeFactors(x + a, x) a + x >>> NonfreeFactors(a*b*x, x) x """ if ProductQ(u): result = 1 for i in u.args: if not FreeQ(i, x): result *= i return result elif FreeQ(u, x): return 1 else: return u def RemoveContentAux(expr, x): return RemoveContentAux_replacer.replace(UtilityOperator(expr, x)) def RemoveContent(u, x): v = NonfreeFactors(u, x) w = Together(v) if EqQ(FreeFactors(w, x), 1): return RemoveContentAux(v, x) else: return RemoveContentAux(NonfreeFactors(w, x), x) def FreeTerms(u, x): """ Returns the sum of the terms of u free of x. Examples ======== >>> from sympy.integrals.rubi.utility_function import FreeTerms >>> from sympy.abc import x, a, b >>> FreeTerms(a, x) a >>> FreeTerms(x*a, x) 0 >>> FreeTerms(a*x + b, x) b """ if SumQ(u): result = 0 for i in u.args: if FreeQ(i, x): result += i return result elif FreeQ(u, x): return u else: return 0 def NonfreeTerms(u, x): # returns the sum of the terms of u free of x. if SumQ(u): result = S(0) for i in u.args: if not FreeQ(i, x): result += i return result elif not FreeQ(u, x): return u else: return S(0) def ExpandAlgebraicFunction(expr, x): if ProductQ(expr): u_ = Wild('u', exclude=[x]) n_ = Wild('n', exclude=[x]) v_ = Wild('v') pattern = u_*v_ match = expr.match(pattern) if match: keys = [u_, v_] if len(keys) == len(match): u, v = tuple([match[i] for i in keys]) if SumQ(v): u, v = v, u if not FreeQ(u, x) and SumQ(u): result = 0 for i in u.args: result += i*v return result pattern = u_**n_*v_ match = expr.match(pattern) if match: keys = [u_, n_, v_] if len(keys) == len(match): u, n, v = tuple([match[i] for i in keys]) if PositiveIntegerQ(n) and SumQ(u): w = Expand(u**n) result = 0 for i in w.args: result += i*v return result return expr def CollectReciprocals(expr, x): # Basis: e/(a+b x)+f/(c+d x)==(c e+a f+(d e+b f) x)/(a c+(b c+a d) x+b d x^2) if SumQ(expr): u_ = Wild('u') a_ = Wild('a', exclude=[x]) b_ = Wild('b', exclude=[x]) c_ = Wild('c', exclude=[x]) d_ = Wild('d', exclude=[x]) e_ = Wild('e', exclude=[x]) f_ = Wild('f', exclude=[x]) pattern = u_ + e_/(a_ + b_*x) + f_/(c_+d_*x) match = expr.match(pattern) if match: try: # .match() does not work peoperly always keys = [u_, a_, b_, c_, d_, e_, f_] u, a, b, c, d, e, f = tuple([match[i] for i in keys]) if ZeroQ(b*c + a*d) & ZeroQ(d*e + b*f): return CollectReciprocals(u + (c*e + a*f)/(a*c + b*d*x**2),x) elif ZeroQ(b*c + a*d) & ZeroQ(c*e + a*f): return CollectReciprocals(u + (d*e + b*f)*x/(a*c + b*d*x**2),x) except: pass return expr def ExpandCleanup(u, x): v = CollectReciprocals(u, x) if SumQ(v): res = 0 for i in v.args: res += SimplifyTerm(i, x) v = res if SumQ(v): return UnifySum(v, x) else: return v else: return v def AlgebraicFunctionQ(u, x, flag=False): if ListQ(u): if u == []: return True elif AlgebraicFunctionQ(First(u), x, flag): return AlgebraicFunctionQ(Rest(u), x, flag) else: return False elif AtomQ(u) or FreeQ(u, x): return True elif PowerQ(u): if RationalQ(u.exp) | flag & FreeQ(u.exp, x): return AlgebraicFunctionQ(u.base, x, flag) elif ProductQ(u) | SumQ(u): for i in u.args: if not AlgebraicFunctionQ(i, x, flag): return False return True return False def Coeff(expr, form, n=1): if n == 1: return Coefficient(Together(expr), form, n) else: coef1 = Coefficient(expr, form, n) coef2 = Coefficient(Together(expr), form, n) if Simplify(coef1 - coef2) == 0: return coef1 else: return coef2 def LeadTerm(u): if SumQ(u): return First(u) return u def RemainingTerms(u): if SumQ(u): return Rest(u) return u def LeadFactor(u): # returns the leading factor of u. if ComplexNumberQ(u) and Re(u) == 0: if Im(u) == S(1): return u else: return LeadFactor(Im(u)) elif ProductQ(u): return LeadFactor(First(u)) return u def RemainingFactors(u): # returns the remaining factors of u. if ComplexNumberQ(u) and Re(u) == 0: if Im(u) == 1: return S(1) else: return I*RemainingFactors(Im(u)) elif ProductQ(u): return RemainingFactors(First(u))*Rest(u) return S(1) def LeadBase(u): """ returns the base of the leading factor of u. Examples ======== >>> from sympy.integrals.rubi.utility_function import LeadBase >>> from sympy.abc import a, b, c >>> LeadBase(a**b) a >>> LeadBase(a**b*c) a """ v = LeadFactor(u) if PowerQ(v): return v.base return v def LeadDegree(u): # returns the degree of the leading factor of u. v = LeadFactor(u) if PowerQ(v): return v.exp return v def Numer(expr): # returns the numerator of u. if PowerQ(expr): if expr.exp < 0: return 1 if ProductQ(expr): return Mul(*[Numer(i) for i in expr.args]) return Numerator(expr) def Denom(u): # returns the denominator of u if PowerQ(u): if u.exp < 0: return u.args[0]**(-u.args[1]) elif ProductQ(u): return Mul(*[Denom(i) for i in u.args]) return Denominator(u) def hypergeom(n, d, z): return hyper(n, d, z) def Expon(expr, form): return Exponent(Together(expr), form) def MergeMonomials(expr, x): u_ = Wild('u') p_ = Wild('p', exclude=[x, 1, 0]) a_ = Wild('a', exclude=[x]) b_ = Wild('b', exclude=[x, 0]) c_ = Wild('c', exclude=[x]) d_ = Wild('d', exclude=[x, 0]) n_ = Wild('n', exclude=[x]) m_ = Wild('m', exclude=[x]) # Basis: If m/n\[Element]\[DoubleStruckCapitalZ], then z^m (c z^n)^p==(c z^n)^(m/n+p)/c^(m/n) pattern = u_*(a_ + b_*x)**m_*(c_*(a_ + b_*x)**n_)**p_ match = expr.match(pattern) if match: keys = [u_, a_, b_, m_, c_, n_, p_] if len(keys) == len(match): u, a, b, m, c, n, p = tuple([match[i] for i in keys]) if IntegerQ(m/n): if u*(c*(a + b*x)**n)**(m/n + p)/c**(m/n) is S.NaN: return expr else: return u*(c*(a + b*x)**n)**(m/n + p)/c**(m/n) # Basis: If m\[Element]\[DoubleStruckCapitalZ] \[And] b c-a d==0, then (a+b z)^m==b^m/d^m (c+d z)^m pattern = u_*(a_ + b_*x)**m_*(c_ + d_*x)**n_ match = expr.match(pattern) if match: keys = [u_, a_, b_, m_, c_, d_, n_] if len(keys) == len(match): u, a, b, m, c, d, n = tuple([match[i] for i in keys]) if IntegerQ(m) and ZeroQ(b*c - a*d): if u*b**m/d**m*(c + d*x)**(m + n) is S.NaN: return expr else: return u*b**m/d**m*(c + d*x)**(m + n) return expr def PolynomialDivide(u, v, x): quo = PolynomialQuotient(u, v, x) rem = PolynomialRemainder(u, v, x) s = 0 for i in ExponentList(quo, x): s += Simp(Together(Coefficient(quo, x, i)*x**i), x) quo = s rem = Together(rem) free = FreeFactors(rem, x) rem = NonfreeFactors(rem, x) monomial = x**Min(ExponentList(rem, x)) if NegQ(Coefficient(rem, x, 0)): monomial = -monomial s = 0 for i in ExponentList(rem, x): s += Simp(Together(Coefficient(rem, x, i)*x**i/monomial), x) rem = s if BinomialQ(v, x): return quo + free*monomial*rem/ExpandToSum(v, x) else: return quo + free*monomial*rem/v def BinomialQ(u, x, n=None): """ If u is equivalent to an expression of the form a + b*x**n, BinomialQ(u, x, n) returns True, else it returns False. Examples ======== >>> from sympy.integrals.rubi.utility_function import BinomialQ >>> from sympy.abc import x >>> BinomialQ(x**9, x) True >>> BinomialQ((1 + x)**3, x) False """ if ListQ(u): for i in u: if Not(BinomialQ(i, x, n)): return False return True elif NumberQ(x): return False return ListQ(BinomialParts(u, x)) def TrinomialQ(u, x): """ If u is equivalent to an expression of the form a + b*x**n + c*x**(2*n) where n, b and c are not 0, TrinomialQ(u, x) returns True, else it returns False. Examples ======== >>> from sympy.integrals.rubi.utility_function import TrinomialQ >>> from sympy.abc import x >>> TrinomialQ((7 + 2*x**6 + 3*x**12), x) True >>> TrinomialQ(x**2, x) False """ if ListQ(u): for i in u.args: if Not(TrinomialQ(i, x)): return False return True check = False u = replace_pow_exp(u) if PowerQ(u): if u.exp == 2 and BinomialQ(u.base, x): check = True return ListQ(TrinomialParts(u,x)) and Not(QuadraticQ(u, x)) and Not(check) def GeneralizedBinomialQ(u, x): """ If u is equivalent to an expression of the form a*x**q+b*x**n where n, q and b are not 0, GeneralizedBinomialQ(u, x) returns True, else it returns False. Examples ======== >>> from sympy.integrals.rubi.utility_function import GeneralizedBinomialQ >>> from sympy.abc import a, x, q, b, n >>> GeneralizedBinomialQ(a*x**q, x) False """ if ListQ(u): return all(GeneralizedBinomialQ(i, x) for i in u) return ListQ(GeneralizedBinomialParts(u, x)) def GeneralizedTrinomialQ(u, x): """ If u is equivalent to an expression of the form a*x**q+b*x**n+c*x**(2*n-q) where n, q, b and c are not 0, GeneralizedTrinomialQ(u, x) returns True, else it returns False. Examples ======== >>> from sympy.integrals.rubi.utility_function import GeneralizedTrinomialQ >>> from sympy.abc import x >>> GeneralizedTrinomialQ(7 + 2*x**6 + 3*x**12, x) False """ if ListQ(u): return all(GeneralizedTrinomialQ(i, x) for i in u) return ListQ(GeneralizedTrinomialParts(u, x)) def FactorSquareFreeList(poly): r = sqf_list(poly) result = [[1, 1]] for i in r[1]: result.append(list(i)) return result def PerfectPowerTest(u, x): # If u (x) is equivalent to a polynomial raised to an integer power greater than 1, # PerfectPowerTest[u,x] returns u (x) as an expanded polynomial raised to the power; # else it returns False. if PolynomialQ(u, x): lst = FactorSquareFreeList(u) gcd = 0 v = 1 if lst[0] == [1, 1]: lst = Rest(lst) for i in lst: gcd = GCD(gcd, i[1]) if gcd > 1: for i in lst: v = v*i[0]**(i[1]/gcd) return Expand(v)**gcd else: return False return False def SquareFreeFactorTest(u, x): # If u (x) can be square free factored, SquareFreeFactorTest[u,x] returns u (x) in # factored form; else it returns False. if PolynomialQ(u, x): v = FactorSquareFree(u) if PowerQ(v) or ProductQ(v): return v return False return False def RationalFunctionQ(u, x): # If u is a rational function of x, RationalFunctionQ[u,x] returns True; else it returns False. if AtomQ(u) or FreeQ(u, x): return True elif IntegerPowerQ(u): return RationalFunctionQ(u.base, x) elif ProductQ(u) or SumQ(u): for i in u.args: if Not(RationalFunctionQ(i, x)): return False return True return False def RationalFunctionFactors(u, x): # RationalFunctionFactors[u,x] returns the product of the factors of u that are rational functions of x. if ProductQ(u): res = 1 for i in u.args: if RationalFunctionQ(i, x): res *= i return res elif RationalFunctionQ(u, x): return u return S(1) def NonrationalFunctionFactors(u, x): if ProductQ(u): res = 1 for i in u.args: if not RationalFunctionQ(i, x): res *= i return res elif RationalFunctionQ(u, x): return S(1) return u def Reverse(u): if isinstance(u, list): return list(reversed(u)) else: l = list(u.args) return u.func(*list(reversed(l))) def RationalFunctionExponents(u, x): """ u is a polynomial or rational function of x. RationalFunctionExponents(u, x) returns a list of the exponent of the numerator of u and the exponent of the denominator of u. Examples ======== >>> from sympy.integrals.rubi.utility_function import RationalFunctionExponents >>> from sympy.abc import x, a >>> RationalFunctionExponents(x, x) [1, 0] >>> RationalFunctionExponents(x**(-1), x) [0, 1] >>> RationalFunctionExponents(x**(-1)*a, x) [0, 1] """ if PolynomialQ(u, x): return [Exponent(u, x), 0] elif IntegerPowerQ(u): if PositiveQ(u.exp): return u.exp*RationalFunctionExponents(u.base, x) return (-u.exp)*Reverse(RationalFunctionExponents(u.base, x)) elif ProductQ(u): lst1 = RationalFunctionExponents(First(u), x) lst2 = RationalFunctionExponents(Rest(u), x) return [lst1[0] + lst2[0], lst1[1] + lst2[1]] elif SumQ(u): v = Together(u) if SumQ(v): lst1 = RationalFunctionExponents(First(u), x) lst2 = RationalFunctionExponents(Rest(u), x) return [Max(lst1[0] + lst2[1], lst2[0] + lst1[1]), lst1[1] + lst2[1]] else: return RationalFunctionExponents(v, x) return [0, 0] def RationalFunctionExpand(expr, x): # expr is a polynomial or rational function of x. # RationalFunctionExpand[u,x] returns the expansion of the factors of u that are rational functions times the other factors. def cons_f1(n): return FractionQ(n) cons1 = CustomConstraint(cons_f1) def cons_f2(x, v): if not isinstance(x, Symbol): return False return UnsameQ(v, x) cons2 = CustomConstraint(cons_f2) def With1(n, u, x, v): w = RationalFunctionExpand(u, x) return If(SumQ(w), Add(*[i*v**n for i in w.args]), v**n*w) pattern1 = Pattern(UtilityOperator(u_*v_**n_, x_), cons1, cons2) rule1 = ReplacementRule(pattern1, With1) def With2(u, x): v = ExpandIntegrand(u, x) def _consf_u(a, b, c, d, p, m, n, x): return And(FreeQ(List(a, b, c, d, p), x), IntegersQ(m, n), Equal(m, Add(n, S(-1)))) cons_u = CustomConstraint(_consf_u) pat = Pattern(UtilityOperator(x_**WC('m', S(1))*(x_*WC('d', S(1)) + c_)**p_/(x_**n_*WC('b', S(1)) + a_), x_), cons_u) result_matchq = is_match(UtilityOperator(u, x), pat) if UnsameQ(v, u) and not result_matchq: return v else: v = ExpandIntegrand(RationalFunctionFactors(u, x), x) w = NonrationalFunctionFactors(u, x) if SumQ(v): return Add(*[i*w for i in v.args]) else: return v*w pattern2 = Pattern(UtilityOperator(u_, x_)) rule2 = ReplacementRule(pattern2, With2) expr = expr.replace(sym_exp, rubi_exp) res = replace_all(UtilityOperator(expr, x), [rule1, rule2]) return replace_pow_exp(res) def ExpandIntegrand(expr, x, extra=None): expr = replace_pow_exp(expr) if extra is not None: extra, x = x, extra w = ExpandIntegrand(extra, x) r = NonfreeTerms(w, x) if SumQ(r): result = [expr*FreeTerms(w, x)] for i in r.args: result.append(MergeMonomials(expr*i, x)) return r.func(*result) else: return expr*FreeTerms(w, x) + MergeMonomials(expr*r, x) else: u_ = Wild('u', exclude=[0, 1]) a_ = Wild('a', exclude=[x]) b_ = Wild('b', exclude=[x, 0]) F_ = Wild('F', exclude=[0]) c_ = Wild('c', exclude=[x]) d_ = Wild('d', exclude=[x, 0]) n_ = Wild('n', exclude=[0, 1]) pattern = u_*(a_ + b_*F_)**n_ match = expr.match(pattern) if match: if MemberQ([asin, acos, asinh, acosh], match[F_].func): keys = [u_, a_, b_, F_, n_] if len(match) == len(keys): u, a, b, F, n = tuple([match[i] for i in keys]) match = F.args[0].match(c_ + d_*x) if match: keys = c_, d_ if len(keys) == len(match): c, d = tuple([match[i] for i in keys]) if PolynomialQ(u, x): F = F.func return ExpandLinearProduct((a + b*F(c + d*x))**n, u, c, d, x) expr = expr.replace(sym_exp, rubi_exp) res = replace_all(UtilityOperator(expr, x), ExpandIntegrand_rules, max_count = 1) return replace_pow_exp(res) def SimplerQ(u, v): # If u is simpler than v, SimplerQ(u, v) returns True, else it returns False. SimplerQ(u, u) returns False if IntegerQ(u): if IntegerQ(v): if Abs(u)==Abs(v): return v<0 else: return Abs(u)<Abs(v) else: return True elif IntegerQ(v): return False elif FractionQ(u): if FractionQ(v): if Denominator(u) == Denominator(v): return SimplerQ(Numerator(u), Numerator(v)) else: return Denominator(u)<Denominator(v) else: return True elif FractionQ(v): return False elif (Re(u)==0 or Re(u) == 0) and (Re(v)==0 or Re(v) == 0): return SimplerQ(Im(u), Im(v)) elif ComplexNumberQ(u): if ComplexNumberQ(v): if Re(u) == Re(v): return SimplerQ(Im(u), Im(v)) else: return SimplerQ(Re(u),Re(v)) else: return False elif NumberQ(u): if NumberQ(v): return OrderedQ([u,v]) else: return True elif NumberQ(v): return False elif AtomQ(u) or (Head(u) == re) or (Head(u) == im): if AtomQ(v) or (Head(u) == re) or (Head(u) == im): return OrderedQ([u,v]) else: return True elif AtomQ(v) or (Head(u) == re) or (Head(u) == im): return False elif Head(u) == Head(v): if Length(u) == Length(v): for i in range(len(u.args)): if not u.args[i] == v.args[i]: return SimplerQ(u.args[i], v.args[i]) return False return Length(u) < Length(v) elif LeafCount(u) < LeafCount(v): return True elif LeafCount(v) < LeafCount(u): return False return Not(OrderedQ([v,u])) def SimplerSqrtQ(u, v): # If Rt(u, 2) is simpler than Rt(v, 2), SimplerSqrtQ(u, v) returns True, else it returns False. SimplerSqrtQ(u, u) returns False if NegativeQ(v) and Not(NegativeQ(u)): return True if NegativeQ(u) and Not(NegativeQ(v)): return False sqrtu = Rt(u, S(2)) sqrtv = Rt(v, S(2)) if IntegerQ(sqrtu): if IntegerQ(sqrtv): return sqrtu<sqrtv else: return True if IntegerQ(sqrtv): return False if RationalQ(sqrtu): if RationalQ(sqrtv): return sqrtu<sqrtv else: return True if RationalQ(sqrtv): return False if PosQ(u): if PosQ(v): return LeafCount(sqrtu)<LeafCount(sqrtv) else: return True if PosQ(v): return False if LeafCount(sqrtu)<LeafCount(sqrtv): return True if LeafCount(sqrtv)<LeafCount(sqrtu): return False else: return Not(OrderedQ([v, u])) def SumSimplerQ(u, v): """ If u + v is simpler than u, SumSimplerQ(u, v) returns True, else it returns False. If for every term w of v there is a term of u equal to n*w where n<-1/2, u + v will be simpler than u. Examples ======== >>> from sympy.integrals.rubi.utility_function import SumSimplerQ >>> from sympy.abc import x >>> from sympy import S >>> SumSimplerQ(S(4 + x),S(3 + x**3)) False """ if RationalQ(u, v): if v == S(0): return False elif v > S(0): return u < -S(1) else: return u >= -v else: return SumSimplerAuxQ(Expand(u), Expand(v)) def BinomialDegree(u, x): # if u is a binomial. BinomialDegree[u,x] returns the degree of x in u. bp = BinomialParts(u, x) if bp == False: return bp return bp[2] def TrinomialDegree(u, x): # If u is equivalent to a trinomial of the form a + b*x^n + c*x^(2*n) where n!=0, b!=0 and c!=0, TrinomialDegree[u,x] returns n t = TrinomialParts(u, x) if t: return t[3] return t def CancelCommonFactors(u, v): def _delete_cases(a, b): # only for CancelCommonFactors lst = [] deleted = False for i in a.args: if i == b and not deleted: deleted = True continue lst.append(i) return a.func(*lst) # CancelCommonFactors[u,v] returns {u',v'} are the noncommon factors of u and v respectively. if ProductQ(u): if ProductQ(v): if MemberQ(v, First(u)): return CancelCommonFactors(Rest(u), _delete_cases(v, First(u))) else: lst = CancelCommonFactors(Rest(u), v) return [First(u)*lst[0], lst[1]] else: if MemberQ(u, v): return [_delete_cases(u, v), 1] else: return[u, v] elif ProductQ(v): if MemberQ(v, u): return [1, _delete_cases(v, u)] else: return [u, v] return[u, v] def SimplerIntegrandQ(u, v, x): lst = CancelCommonFactors(u, v) u1 = lst[0] v1 = lst[1] if Head(u1) == Head(v1) and Length(u1) == 1 and Length(v1) == 1: return SimplerIntegrandQ(u1.args[0], v1.args[0], x) if 4*LeafCount(u1) < 3*LeafCount(v1): return True if RationalFunctionQ(u1, x): if RationalFunctionQ(v1, x): t1 = 0 t2 = 0 for i in RationalFunctionExponents(u1, x): t1 += i for i in RationalFunctionExponents(v1, x): t2 += i return t1 < t2 else: return True else: return False def GeneralizedBinomialDegree(u, x): b = GeneralizedBinomialParts(u, x) if b: return b[2] - b[3] def GeneralizedBinomialParts(expr, x): expr = Expand(expr) if GeneralizedBinomialMatchQ(expr, x): a = Wild('a', exclude=[x]) b = Wild('b', exclude=[x]) n = Wild('n', exclude=[x]) q = Wild('q', exclude=[x]) Match = expr.match(a*x**q + b*x**n) if Match and PosQ(Match[q] - Match[n]): return [Match[b], Match[a], Match[q], Match[n]] else: return False def GeneralizedTrinomialDegree(u, x): t = GeneralizedTrinomialParts(u, x) if t: return t[3] - t[4] def GeneralizedTrinomialParts(expr, x): expr = Expand(expr) if GeneralizedTrinomialMatchQ(expr, x): a = Wild('a', exclude=[x, 0]) b = Wild('b', exclude=[x, 0]) c = Wild('c', exclude=[x]) n = Wild('n', exclude=[x, 0]) q = Wild('q', exclude=[x]) Match = expr.match(a*x**q + b*x**n+c*x**(2*n-q)) if Match and expr.is_Add: return [Match[c], Match[b], Match[a], Match[n], 2*Match[n]-Match[q]] else: return False def MonomialQ(u, x): # If u is of the form a*x^n where n!=0 and a!=0, MonomialQ[u,x] returns True; else False if isinstance(u, list): return all(MonomialQ(i, x) for i in u) else: a = Wild('a', exclude=[x]) b = Wild('b', exclude=[x]) re = u.match(a*x**b) if re: return True return False def MonomialSumQ(u, x): # if u(x) is a sum and each term is free of x or an expression of the form a*x^n, MonomialSumQ(u, x) returns True; else it returns False if SumQ(u): for i in u.args: if Not(FreeQ(i, x) or MonomialQ(i, x)): return False return True @doctest_depends_on(modules=('matchpy',)) def MinimumMonomialExponent(u, x): """ u is sum whose terms are monomials. MinimumMonomialExponent(u, x) returns the exponent of the term having the smallest exponent Examples ======== >>> from sympy.integrals.rubi.utility_function import MinimumMonomialExponent >>> from sympy.abc import x >>> MinimumMonomialExponent(x**2 + 5*x**2 + 3*x**5, x) 2 >>> MinimumMonomialExponent(x**2 + 5*x**2 + 1, x) 0 """ n =MonomialExponent(First(u), x) for i in u.args: if PosQ(n - MonomialExponent(i, x)): n = MonomialExponent(i, x) return n def MonomialExponent(u, x): # u is a monomial. MonomialExponent(u, x) returns the exponent of x in u a = Wild('a', exclude=[x]) b = Wild('b', exclude=[x]) re = u.match(a*x**b) if re: return re[b] def LinearMatchQ(u, x): # LinearMatchQ(u, x) returns True iff u matches patterns of the form a+b*x where a and b are free of x if isinstance(u, list): return all(LinearMatchQ(i, x) for i in u) else: a = Wild('a', exclude=[x]) b = Wild('b', exclude=[x]) re = u.match(a + b*x) if re: return True return False def PowerOfLinearMatchQ(u, x): if isinstance(u, list): for i in u: if not PowerOfLinearMatchQ(i, x): return False return True else: a = Wild('a', exclude=[x]) b = Wild('b', exclude=[x, 0]) m = Wild('m', exclude=[x, 0]) Match = u.match((a + b*x)**m) if Match: return True else: return False def QuadraticMatchQ(u, x): if ListQ(u): return all(QuadraticMatchQ(i, x) for i in u) pattern1 = Pattern(UtilityOperator(x_**2*WC('c', 1) + x_*WC('b', 1) + WC('a', 0), x_), CustomConstraint(lambda a, b, c, x: FreeQ([a, b, c], x))) pattern2 = Pattern(UtilityOperator(x_**2*WC('c', 1) + WC('a', 0), x_), CustomConstraint(lambda a, c, x: FreeQ([a, c], x))) u1 = UtilityOperator(u, x) return is_match(u1, pattern1) or is_match(u1, pattern2) def CubicMatchQ(u, x): if isinstance(u, list): return all(CubicMatchQ(i, x) for i in u) else: pattern1 = Pattern(UtilityOperator(x_**3*WC('d', 1) + x_**2*WC('c', 1) + x_*WC('b', 1) + WC('a', 0), x_), CustomConstraint(lambda a, b, c, d, x: FreeQ([a, b, c, d], x))) pattern2 = Pattern(UtilityOperator(x_**3*WC('d', 1) + x_*WC('b', 1) + WC('a', 0), x_), CustomConstraint(lambda a, b, d, x: FreeQ([a, b, d], x))) pattern3 = Pattern(UtilityOperator(x_**3*WC('d', 1) + x_**2*WC('c', 1) + WC('a', 0), x_), CustomConstraint(lambda a, c, d, x: FreeQ([a, c, d], x))) pattern4 = Pattern(UtilityOperator(x_**3*WC('d', 1) + WC('a', 0), x_), CustomConstraint(lambda a, d, x: FreeQ([a, d], x))) u1 = UtilityOperator(u, x) if is_match(u1, pattern1) or is_match(u1, pattern2) or is_match(u1, pattern3) or is_match(u1, pattern4): return True else: return False def BinomialMatchQ(u, x): if isinstance(u, list): return all(BinomialMatchQ(i, x) for i in u) else: pattern = Pattern(UtilityOperator(x_**WC('n', S(1))*WC('b', S(1)) + WC('a', S(0)), x_) , CustomConstraint(lambda a, b, n, x: FreeQ([a,b,n],x))) u = UtilityOperator(u, x) return is_match(u, pattern) def TrinomialMatchQ(u, x): if isinstance(u, list): return all(TrinomialMatchQ(i, x) for i in u) else: pattern = Pattern(UtilityOperator(x_**WC('j', S(1))*WC('c', S(1)) + x_**WC('n', S(1))*WC('b', S(1)) + WC('a', S(0)), x_) , CustomConstraint(lambda a, b, c, n, x: FreeQ([a, b, c, n], x)), CustomConstraint(lambda j, n: ZeroQ(j-2*n) )) u = UtilityOperator(u, x) return is_match(u, pattern) def GeneralizedBinomialMatchQ(u, x): if isinstance(u, list): return all(GeneralizedBinomialMatchQ(i, x) for i in u) else: a = Wild('a', exclude=[x, 0]) b = Wild('b', exclude=[x, 0]) n = Wild('n', exclude=[x, 0]) q = Wild('q', exclude=[x, 0]) Match = u.match(a*x**q + b*x**n) if Match and len(Match) == 4 and Match[q] != 0 and Match[n] != 0: return True else: return False def GeneralizedTrinomialMatchQ(u, x): if isinstance(u, list): return all(GeneralizedTrinomialMatchQ(i, x) for i in u) else: a = Wild('a', exclude=[x, 0]) b = Wild('b', exclude=[x, 0]) n = Wild('n', exclude=[x, 0]) c = Wild('c', exclude=[x, 0]) q = Wild('q', exclude=[x, 0]) Match = u.match(a*x**q + b*x**n + c*x**(2*n - q)) if Match and len(Match) == 5 and 2*Match[n] - Match[q] != 0 and Match[n] != 0: return True else: return False def QuotientOfLinearsMatchQ(u, x): if isinstance(u, list): return all(QuotientOfLinearsMatchQ(i, x) for i in u) else: a = Wild('a', exclude=[x]) b = Wild('b', exclude=[x]) d = Wild('d', exclude=[x]) c = Wild('c', exclude=[x]) e = Wild('e') Match = u.match(e*(a + b*x)/(c + d*x)) if Match and len(Match) == 5: return True else: return False def PolynomialTermQ(u, x): a = Wild('a', exclude=[x]) n = Wild('n', exclude=[x]) Match = u.match(a*x**n) if Match and IntegerQ(Match[n]) and Greater(Match[n], S(0)): return True else: return False def PolynomialTerms(u, x): s = 0 for i in u.args: if PolynomialTermQ(i, x): s = s + i return s def NonpolynomialTerms(u, x): s = 0 for i in u.args: if not PolynomialTermQ(i, x): s = s + i return s def PseudoBinomialParts(u, x): if PolynomialQ(u, x) and Greater(Expon(u, x), S(2)): n = Expon(u, x) d = Rt(Coefficient(u, x, n), n) c = d**(-n + S(1))*Coefficient(u, x, n + S(-1))/n a = Simplify(u - (c + d*x)**n) if NonzeroQ(a) and FreeQ(a, x): return [a, S(1), c, d, n] else: return False else: return False def NormalizePseudoBinomial(u, x): lst = PseudoBinomialParts(u, x) if lst: return (lst[0] + lst[1]*(lst[2] + lst[3]*x)**lst[4]) def PseudoBinomialPairQ(u, v, x): lst1 = PseudoBinomialParts(u, x) if AtomQ(lst1): return False else: lst2 = PseudoBinomialParts(v, x) if AtomQ(lst2): return False else: return Drop(lst1, 2) == Drop(lst2, 2) def PseudoBinomialQ(u, x): lst = PseudoBinomialParts(u, x) if lst: return True else: return False def PolynomialGCD(f, g): return gcd(f, g) def PolyGCD(u, v, x): # (* u and v are polynomials in x. *) # (* PolyGCD[u,v,x] returns the factors of the gcd of u and v dependent on x. *) return NonfreeFactors(PolynomialGCD(u, v), x) def AlgebraicFunctionFactors(u, x, flag=False): # (* AlgebraicFunctionFactors[u,x] returns the product of the factors of u that are algebraic functions of x. *) if ProductQ(u): result = 1 for i in u.args: if AlgebraicFunctionQ(i, x, flag): result *= i return result if AlgebraicFunctionQ(u, x, flag): return u return 1 def NonalgebraicFunctionFactors(u, x): """ NonalgebraicFunctionFactors[u,x] returns the product of the factors of u that are not algebraic functions of x. Examples ======== >>> from sympy.integrals.rubi.utility_function import NonalgebraicFunctionFactors >>> from sympy.abc import x >>> from sympy import sin >>> NonalgebraicFunctionFactors(sin(x), x) sin(x) >>> NonalgebraicFunctionFactors(x, x) 1 """ if ProductQ(u): result = 1 for i in u.args: if not AlgebraicFunctionQ(i, x): result *= i return result if AlgebraicFunctionQ(u, x): return 1 return u def QuotientOfLinearsP(u, x): if LinearQ(u, x): return True elif SumQ(u): if FreeQ(u.args[0], x): return QuotientOfLinearsP(Rest(u), x) elif LinearQ(Numerator(u), x) and LinearQ(Denominator(u), x): return True elif ProductQ(u): if FreeQ(First(u), x): return QuotientOfLinearsP(Rest(u), x) elif Numerator(u) == 1 and PowerQ(u): return QuotientOfLinearsP(Denominator(u), x) return u == x or FreeQ(u, x) def QuotientOfLinearsParts(u, x): # If u is equivalent to an expression of the form (a+b*x)/(c+d*x), QuotientOfLinearsParts[u,x] # returns the list {a, b, c, d}. if LinearQ(u, x): return [Coefficient(u, x, 0), Coefficient(u, x, 1), 1, 0] elif PowerQ(u): if Numerator(u) == 1: u = Denominator(u) r = QuotientOfLinearsParts(u, x) return [r[2], r[3], r[0], r[1]] elif SumQ(u): a = First(u) if FreeQ(a, x): u = Rest(u) r = QuotientOfLinearsParts(u, x) return [r[0] + a*r[2], r[1] + a*r[3], r[2], r[3]] elif ProductQ(u): a = First(u) if FreeQ(a, x): r = QuotientOfLinearsParts(Rest(u), x) return [a*r[0], a*r[1], r[2], r[3]] a = Numerator(u) d = Denominator(u) if LinearQ(a, x) and LinearQ(d, x): return [Coefficient(a, x, 0), Coefficient(a, x, 1), Coefficient(d, x, 0), Coefficient(d, x, 1)] elif u == x: return [0, 1, 1, 0] elif FreeQ(u, x): return [u, 0, 1, 0] return [u, 0, 1, 0] def QuotientOfLinearsQ(u, x): # (*QuotientOfLinearsQ[u,x] returns True iff u is equivalent to an expression of the form (a+b x)/(c+d x) where b!=0 and d!=0.*) if ListQ(u): for i in u: if not QuotientOfLinearsQ(i, x): return False return True q = QuotientOfLinearsParts(u, x) return QuotientOfLinearsP(u, x) and NonzeroQ(q[1]) and NonzeroQ(q[3]) def Flatten(l): return flatten(l) def Sort(u, r=False): return sorted(u, key=lambda x: x.sort_key(), reverse=r) # (*Definition: A number is absurd if it is a rational number, a positive rational number raised to a fractional power, or a product of absurd numbers.*) def AbsurdNumberQ(u): # (* AbsurdNumberQ[u] returns True if u is an absurd number, else it returns False. *) if PowerQ(u): v = u.exp u = u.base return RationalQ(u) and u > 0 and FractionQ(v) elif ProductQ(u): return all(AbsurdNumberQ(i) for i in u.args) return RationalQ(u) def AbsurdNumberFactors(u): # (* AbsurdNumberFactors[u] returns the product of the factors of u that are absurd numbers. *) if AbsurdNumberQ(u): return u elif ProductQ(u): result = S(1) for i in u.args: if AbsurdNumberQ(i): result *= i return result return NumericFactor(u) def NonabsurdNumberFactors(u): # (* NonabsurdNumberFactors[u] returns the product of the factors of u that are not absurd numbers. *) if AbsurdNumberQ(u): return S(1) elif ProductQ(u): result = 1 for i in u.args: result *= NonabsurdNumberFactors(i) return result return NonnumericFactors(u) def SumSimplerAuxQ(u, v): if SumQ(v): return (RationalQ(First(v)) or SumSimplerAuxQ(u,First(v))) and (RationalQ(Rest(v)) or SumSimplerAuxQ(u,Rest(v))) elif SumQ(u): return SumSimplerAuxQ(First(u), v) or SumSimplerAuxQ(Rest(u), v) else: return v!=0 and NonnumericFactors(u)==NonnumericFactors(v) and (NumericFactor(u)/NumericFactor(v)<-1/2 or NumericFactor(u)/NumericFactor(v)==-1/2 and NumericFactor(u)<0) def Prepend(l1, l2): if not isinstance(l2, list): return [l2] + l1 return l2 + l1 def Drop(lst, n): if isinstance(lst, list): if isinstance(n, list): lst = lst[:(n[0]-1)] + lst[n[1]:] elif n > 0: lst = lst[n:] elif n < 0: lst = lst[:-n] else: return lst return lst return lst.func(*[i for i in Drop(list(lst.args), n)]) def CombineExponents(lst): if Length(lst) < 2: return lst elif lst[0][0] == lst[1][0]: return CombineExponents(Prepend(Drop(lst,2),[lst[0][0], lst[0][1] + lst[1][1]])) return Prepend(CombineExponents(Rest(lst)), First(lst)) def FactorInteger(n, l=None): if isinstance(n, (int, Integer)): return sorted(factorint(n, limit=l).items()) else: return sorted(factorrat(n, limit=l).items()) def FactorAbsurdNumber(m): # (* m must be an absurd number. FactorAbsurdNumber[m] returns the prime factorization of m *) # (* as list of base-degree pairs where the bases are prime numbers and the degrees are rational. *) if RationalQ(m): return FactorInteger(m) elif PowerQ(m): r = FactorInteger(m.base) return [r[0], r[1]*m.exp] # CombineExponents[Sort[Flatten[Map[FactorAbsurdNumber,Apply[List,m]],1], Function[i1[[1]]<i2[[1]]]]] return list((m.as_base_exp(),)) def SubstForInverseFunction(*args): """ SubstForInverseFunction(u, v, w, x) returns u with subexpressions equal to v replaced by x and x replaced by w. Examples ======== >>> from sympy.integrals.rubi.utility_function import SubstForInverseFunction >>> from sympy.abc import x, a, b >>> SubstForInverseFunction(a, a, b, x) a >>> SubstForInverseFunction(x**a, x**a, b, x) x >>> SubstForInverseFunction(a*x**a, a, b, x) a*b**a """ if len(args) == 3: u, v, x = args[0], args[1], args[2] return SubstForInverseFunction(u, v, (-Coefficient(v.args[0], x, 0) + InverseFunction(Head(v))(x))/Coefficient(v.args[0], x, 1), x) elif len(args) == 4: u, v, w, x = args[0], args[1], args[2], args[3] if AtomQ(u): if u == x: return w return u elif Head(u) == Head(v) and ZeroQ(u.args[0] - v.args[0]): return x res = [SubstForInverseFunction(i, v, w, x) for i in u.args] return u.func(*res) def SubstForFractionalPower(u, v, n, w, x): # (* SubstForFractionalPower[u,v,n,w,x] returns u with subexpressions equal to v^(m/n) replaced # by x^m and x replaced by w. *) if AtomQ(u): if u == x: return w return u elif FractionalPowerQ(u): if ZeroQ(u.base - v): return x**(n*u.exp) res = [SubstForFractionalPower(i, v, n, w, x) for i in u.args] return u.func(*res) def SubstForFractionalPowerOfQuotientOfLinears(u, x): # (* If u has a subexpression of the form ((a+b*x)/(c+d*x))^(m/n) where m and n>1 are integers, # SubstForFractionalPowerOfQuotientOfLinears[u,x] returns the list {v,n,(a+b*x)/(c+d*x),b*c-a*d} where v is u # with subexpressions of the form ((a+b*x)/(c+d*x))^(m/n) replaced by x^m and x replaced lst = FractionalPowerOfQuotientOfLinears(u, 1, False, x) if AtomQ(lst) or AtomQ(lst[1]): return False n = lst[0] tmp = lst[1] lst = QuotientOfLinearsParts(tmp, x) a, b, c, d = lst[0], lst[1], lst[2], lst[3] if ZeroQ(d): return False lst = Simplify(x**(n - 1)*SubstForFractionalPower(u, tmp, n, (-a + c*x**n)/(b - d*x**n), x)/(b - d*x**n)**2) return [NonfreeFactors(lst, x), n, tmp, FreeFactors(lst, x)*(b*c - a*d)] def FractionalPowerOfQuotientOfLinears(u, n, v, x): # (* If u has a subexpression of the form ((a+b*x)/(c+d*x))^(m/n), # FractionalPowerOfQuotientOfLinears[u,1,False,x] returns {n,(a+b*x)/(c+d*x)}; else it returns False. *) if AtomQ(u) or FreeQ(u, x): return [n, v] elif CalculusQ(u): return False elif FractionalPowerQ(u): if QuotientOfLinearsQ(u.base, x) and Not(LinearQ(u.base, x)) and (FalseQ(v) or ZeroQ(u.base - v)): return [LCM(Denominator(u.exp), n), u.base] lst = [n, v] for i in u.args: lst = FractionalPowerOfQuotientOfLinears(i, lst[0], lst[1],x) if AtomQ(lst): return False return lst def SubstForFractionalPowerQ(u, v, x): # (* If the substitution x=v^(1/n) will not complicate algebraic subexpressions of u, # SubstForFractionalPowerQ[u,v,x] returns True; else it returns False. *) if AtomQ(u) or FreeQ(u, x): return True elif FractionalPowerQ(u): return SubstForFractionalPowerAuxQ(u, v, x) return all(SubstForFractionalPowerQ(i, v, x) for i in u.args) def SubstForFractionalPowerAuxQ(u, v, x): if AtomQ(u): return False elif FractionalPowerQ(u): if ZeroQ(u.base - v): return True return any(SubstForFractionalPowerAuxQ(i, v, x) for i in u.args) def FractionalPowerOfSquareQ(u): # (* If a subexpression of u is of the form ((v+w)^2)^n where n is a fraction, *) # (* FractionalPowerOfSquareQ[u] returns (v+w)^2; else it returns False. *) if AtomQ(u): return False elif FractionalPowerQ(u): a_ = Wild('a', exclude=[0]) b_ = Wild('b', exclude=[0]) c_ = Wild('c', exclude=[0]) match = u.base.match(a_*(b_ + c_)**(S(2))) if match: keys = [a_, b_, c_] if len(keys) == len(match): a, b, c = tuple(match[i] for i in keys) if NonsumQ(a): return (b + c)**S(2) for i in u.args: tmp = FractionalPowerOfSquareQ(i) if Not(FalseQ(tmp)): return tmp return False def FractionalPowerSubexpressionQ(u, v, w): # (* If a subexpression of u is of the form w^n where n is a fraction but not equal to v, *) # (* FractionalPowerSubexpressionQ[u,v,w] returns True; else it returns False. *) if AtomQ(u): return False elif FractionalPowerQ(u): if PositiveQ(u.base/w): return Not(u.base == v) and LeafCount(w) < 3*LeafCount(v) for i in u.args: if FractionalPowerSubexpressionQ(i, v, w): return True return False def Apply(f, lst): return f(*lst) def FactorNumericGcd(u): # (* FactorNumericGcd[u] returns u with the gcd of the numeric coefficients of terms of sums factored out. *) if PowerQ(u): if RationalQ(u.exp): return FactorNumericGcd(u.base)**u.exp elif ProductQ(u): res = [FactorNumericGcd(i) for i in u.args] return Mul(*res) elif SumQ(u): g = GCD([NumericFactor(i) for i in u.args]) r = Add(*[i/g for i in u.args]) return g*r return u def MergeableFactorQ(bas, deg, v): # (* MergeableFactorQ[bas,deg,v] returns True iff bas equals the base of a factor of v or bas is a factor of every term of v. *) if bas == v: return RationalQ(deg + S(1)) and (deg + 1>=0 or RationalQ(deg) and deg>0) elif PowerQ(v): if bas == v.base: return RationalQ(deg+v.exp) and (deg+v.exp>=0 or RationalQ(deg) and deg>0) return SumQ(v.base) and IntegerQ(v.exp) and (Not(IntegerQ(deg) or IntegerQ(deg/v.exp))) and MergeableFactorQ(bas, deg/v.exp, v.base) elif ProductQ(v): return MergeableFactorQ(bas, deg, First(v)) or MergeableFactorQ(bas, deg, Rest(v)) return SumQ(v) and MergeableFactorQ(bas, deg, First(v)) and MergeableFactorQ(bas, deg, Rest(v)) def MergeFactor(bas, deg, v): # (* If MergeableFactorQ[bas,deg,v], MergeFactor[bas,deg,v] return the product of bas^deg and v, # but with bas^deg merged into the factor of v whose base equals bas. *) if bas == v: return bas**(deg + 1) elif PowerQ(v): if bas == v.base: return bas**(deg + v.exp) return MergeFactor(bas, deg/v.exp, v.base**v.exp) elif ProductQ(v): if MergeableFactorQ(bas, deg, First(v)): return MergeFactor(bas, deg, First(v))*Rest(v) return First(v)*MergeFactor(bas, deg, Rest(v)) return MergeFactor(bas, deg, First(v)) + MergeFactor(bas, deg, Rest(v)) def MergeFactors(u, v): # (* MergeFactors[u,v] returns the product of u and v, but with the mergeable factors of u merged into v. *) if ProductQ(u): return MergeFactors(Rest(u), MergeFactors(First(u), v)) elif PowerQ(u): if MergeableFactorQ(u.base, u.exp, v): return MergeFactor(u.base, u.exp, v) elif RationalQ(u.exp) and u.exp < -1 and MergeableFactorQ(u.base, -S(1), v): return MergeFactors(u.base**(u.exp + 1), MergeFactor(u.base, -S(1), v)) return u*v elif MergeableFactorQ(u, S(1), v): return MergeFactor(u, S(1), v) return u*v def TrigSimplifyQ(u): # (* TrigSimplifyQ[u] returns True if TrigSimplify[u] actually simplifies u; else False. *) return ActivateTrig(u) != TrigSimplify(u) def TrigSimplify(u): # (* TrigSimplify[u] returns a bottom-up trig simplification of u. *) return ActivateTrig(TrigSimplifyRecur(u)) def TrigSimplifyRecur(u): if AtomQ(u): return u return TrigSimplifyAux(u.func(*[TrigSimplifyRecur(i) for i in u.args])) def Order(expr1, expr2): if expr1 == expr2: return 0 elif expr1.sort_key() > expr2.sort_key(): return -1 return 1 def FactorOrder(u, v): if u == 1: if v == 1: return 0 return -1 elif v == 1: return 1 return Order(u, v) def Smallest(num1, num2=None): if num2 is None: lst = num1 num = lst[0] for i in Rest(lst): num = Smallest(num, i) return num return Min(num1, num2) def OrderedQ(l): return l == Sort(l) def MinimumDegree(deg1, deg2): if RationalQ(deg1): if RationalQ(deg2): return Min(deg1, deg2) return deg1 elif RationalQ(deg2): return deg2 deg = Simplify(deg1- deg2) if RationalQ(deg): if deg > 0: return deg2 return deg1 elif OrderedQ([deg1, deg2]): return deg1 return deg2 def PositiveFactors(u): # (* PositiveFactors[u] returns the positive factors of u *) if ZeroQ(u): return S(1) elif RationalQ(u): return Abs(u) elif PositiveQ(u): return u elif ProductQ(u): res = 1 for i in u.args: res *= PositiveFactors(i) return res return 1 def Sign(u): return sign(u) def NonpositiveFactors(u): # (* NonpositiveFactors[u] returns the nonpositive factors of u *) if ZeroQ(u): return u elif RationalQ(u): return Sign(u) elif PositiveQ(u): return S(1) elif ProductQ(u): res = S(1) for i in u.args: res *= NonpositiveFactors(i) return res return u def PolynomialInAuxQ(u, v, x): if u == v: return True elif AtomQ(u): return u != x elif PowerQ(u): if PowerQ(v): if u.base == v.base: return PositiveIntegerQ(u.exp/v.exp) return PositiveIntegerQ(u.exp) and PolynomialInAuxQ(u.base, v, x) elif SumQ(u) or ProductQ(u): for i in u.args: if Not(PolynomialInAuxQ(i, v, x)): return False return True return False def PolynomialInQ(u, v, x): """ If u is a polynomial in v(x), PolynomialInQ(u, v, x) returns True, else it returns False. Examples ======== >>> from sympy.integrals.rubi.utility_function import PolynomialInQ >>> from sympy.abc import x >>> from sympy import log, S >>> PolynomialInQ(S(1), log(x), x) True >>> PolynomialInQ(log(x), log(x), x) True >>> PolynomialInQ(1 + log(x)**2, log(x), x) True """ return PolynomialInAuxQ(u, NonfreeFactors(NonfreeTerms(v, x), x), x) def ExponentInAux(u, v, x): if u == v: return S(1) elif AtomQ(u): return S(0) elif PowerQ(u): if PowerQ(v): if u.base == v.base: return u.exp/v.exp return u.exp*ExponentInAux(u.base, v, x) elif ProductQ(u): return Add(*[ExponentInAux(i, v, x) for i in u.args]) return Max(*[ExponentInAux(i, v, x) for i in u.args]) def ExponentIn(u, v, x): return ExponentInAux(u, NonfreeFactors(NonfreeTerms(v, x), x), x) def PolynomialInSubstAux(u, v, x): if u == v: return x elif AtomQ(u): return u elif PowerQ(u): if PowerQ(v): if u.base == v.base: return x**(u.exp/v.exp) return PolynomialInSubstAux(u.base, v, x)**u.exp return u.func(*[PolynomialInSubstAux(i, v, x) for i in u.args]) def PolynomialInSubst(u, v, x): # If u is a polynomial in v[x], PolynomialInSubst[u,v,x] returns the polynomial u in x. w = NonfreeTerms(v, x) return ReplaceAll(PolynomialInSubstAux(u, NonfreeFactors(w, x), x), {x: x - FreeTerms(v, x)/FreeFactors(w, x)}) def Distrib(u, v): # Distrib[u,v] returns the sum of u times each term of v. if SumQ(v): return Add(*[u*i for i in v.args]) return u*v def DistributeDegree(u, m): # DistributeDegree[u,m] returns the product of the factors of u each raised to the mth degree. if AtomQ(u): return u**m elif PowerQ(u): return u.base**(u.exp*m) elif ProductQ(u): return Mul(*[DistributeDegree(i, m) for i in u.args]) return u**m def FunctionOfPower(*args): """ FunctionOfPower[u,x] returns the gcd of the integer degrees of x in u. Examples ======== >>> from sympy.integrals.rubi.utility_function import FunctionOfPower >>> from sympy.abc import x >>> FunctionOfPower(x, x) 1 >>> FunctionOfPower(x**3, x) 3 """ if len(args) == 2: return FunctionOfPower(args[0], None, args[1]) u, n, x = args if FreeQ(u, x): return n elif u == x: return S(1) elif PowerQ(u): if u.base == x and IntegerQ(u.exp): if n is None: return u.exp return GCD(n, u.exp) tmp = n for i in u.args: tmp = FunctionOfPower(i, tmp, x) return tmp def DivideDegreesOfFactors(u, n): """ DivideDegreesOfFactors[u,n] returns the product of the base of the factors of u raised to the degree of the factors divided by n. Examples ======== >>> from sympy import S >>> from sympy.integrals.rubi.utility_function import DivideDegreesOfFactors >>> from sympy.abc import a, b >>> DivideDegreesOfFactors(a**b, S(3)) a**(b/3) """ if ProductQ(u): return Mul(*[LeadBase(i)**(LeadDegree(i)/n) for i in u.args]) return LeadBase(u)**(LeadDegree(u)/n) def MonomialFactor(u, x): # MonomialFactor[u,x] returns the list {n,v} where x^n*v==u and n is free of x. if AtomQ(u): if u == x: return [S(1), S(1)] return [S(0), u] elif PowerQ(u): if IntegerQ(u.exp): lst = MonomialFactor(u.base, x) return [lst[0]*u.exp, lst[1]**u.exp] elif u.base == x and FreeQ(u.exp, x): return [u.exp, S(1)] return [S(0), u] elif ProductQ(u): lst1 = MonomialFactor(First(u), x) lst2 = MonomialFactor(Rest(u), x) return [lst1[0] + lst2[0], lst1[1]*lst2[1]] elif SumQ(u): lst = [MonomialFactor(i, x) for i in u.args] deg = lst[0][0] for i in Rest(lst): deg = MinimumDegree(deg, i[0]) if ZeroQ(deg) or RationalQ(deg) and deg < 0: return [S(0), u] return [deg, Add(*[x**(i[0] - deg)*i[1] for i in lst])] return [S(0), u] def FullSimplify(expr): return Simplify(expr) def FunctionOfLinearSubst(u, a, b, x): if FreeQ(u, x): return u elif LinearQ(u, x): tmp = Coefficient(u, x, 1) if tmp == b: tmp = S(1) else: tmp = tmp/b return Coefficient(u, x, S(0)) - a*tmp + tmp*x elif PowerQ(u): if FreeQ(u.base, x): return E**(FullSimplify(FunctionOfLinearSubst(Log(u.base)*u.exp, a, b, x))) lst = MonomialFactor(u, x) if ProductQ(u) and NonzeroQ(lst[0]): if RationalQ(LeadFactor(lst[1])) and LeadFactor(lst[1]) < 0: return -FunctionOfLinearSubst(DivideDegreesOfFactors(-lst[1], lst[0])*x, a, b, x)**lst[0] return FunctionOfLinearSubst(DivideDegreesOfFactors(lst[1], lst[0])*x, a, b, x)**lst[0] return u.func(*[FunctionOfLinearSubst(i, a, b, x) for i in u.args]) def FunctionOfLinear(*args): # (* If u (x) is equivalent to an expression of the form f (a+b*x) and not the case that a==0 and # b==1, FunctionOfLinear[u,x] returns the list {f (x),a,b}; else it returns False. *) if len(args) == 2: u, x = args lst = FunctionOfLinear(u, False, False, x, False) if AtomQ(lst) or FalseQ(lst[0]) or (lst[0] == 0 and lst[1] == 1): return False return [FunctionOfLinearSubst(u, lst[0], lst[1], x), lst[0], lst[1]] u, a, b, x, flag = args if FreeQ(u, x): return [a, b] elif CalculusQ(u): return False elif LinearQ(u, x): if FalseQ(a): return [Coefficient(u, x, 0), Coefficient(u, x, 1)] lst = CommonFactors([b, Coefficient(u, x, 1)]) if ZeroQ(Coefficient(u, x, 0)) and Not(flag): return [0, lst[0]] elif ZeroQ(b*Coefficient(u, x, 0) - a*Coefficient(u, x, 1)): return [a/lst[1], lst[0]] return [0, 1] elif PowerQ(u): if FreeQ(u.base, x): return FunctionOfLinear(Log(u.base)*u.exp, a, b, x, False) lst = MonomialFactor(u, x) if ProductQ(u) and NonzeroQ(lst[0]): if False and IntegerQ(lst[0]) and lst[0] != -1 and FreeQ(lst[1], x): if RationalQ(LeadFactor(lst[1])) and LeadFactor(lst[1]) < 0: return FunctionOfLinear(DivideDegreesOfFactors(-lst[1], lst[0])*x, a, b, x, False) return FunctionOfLinear(DivideDegreesOfFactors(lst[1], lst[0])*x, a, b, x, False) return False lst = [a, b] for i in u.args: lst = FunctionOfLinear(i, lst[0], lst[1], x, SumQ(u)) if AtomQ(lst): return False return lst def NormalizeIntegrand(u, x): v = NormalizeLeadTermSigns(NormalizeIntegrandAux(u, x)) if v == NormalizeLeadTermSigns(u): return u else: return v def NormalizeIntegrandAux(u, x): if SumQ(u): l = 0 for i in u.args: l += NormalizeIntegrandAux(i, x) return l if ProductQ(MergeMonomials(u, x)): l = 1 for i in MergeMonomials(u, x).args: l *= NormalizeIntegrandFactor(i, x) return l else: return NormalizeIntegrandFactor(MergeMonomials(u, x), x) def NormalizeIntegrandFactor(u, x): if PowerQ(u): if FreeQ(u.exp, x): bas = NormalizeIntegrandFactorBase(u.base, x) deg = u.exp if IntegerQ(deg) and SumQ(bas): if all(MonomialQ(i, x) for i in bas.args): mi = MinimumMonomialExponent(bas, x) q = 0 for i in bas.args: q += Simplify(i/x**mi) return x**(mi*deg)*q**deg else: return bas**deg else: return bas**deg if PowerQ(u): if FreeQ(u.base, x): return u.base**NormalizeIntegrandFactorBase(u.exp, x) bas = NormalizeIntegrandFactorBase(u, x) if SumQ(bas): if all(MonomialQ(i, x) for i in bas.args): mi = MinimumMonomialExponent(bas, x) z = 0 for j in bas.args: z += j/x**mi return x**mi*z else: return bas else: return bas def NormalizeIntegrandFactorBase(expr, x): m = Wild('m', exclude=[x]) u = Wild('u') match = expr.match(x**m*u) if match and SumQ(u): l = 0 for i in u.args: l += NormalizeIntegrandFactorBase((x**m*i), x) return l if BinomialQ(expr, x): if BinomialMatchQ(expr, x): return expr else: return ExpandToSum(expr, x) elif TrinomialQ(expr, x): if TrinomialMatchQ(expr, x): return expr else: return ExpandToSum(expr, x) elif ProductQ(expr): l = 1 for i in expr.args: l *= NormalizeIntegrandFactor(i, x) return l elif PolynomialQ(expr, x) and Exponent(expr, x) <= 4: return ExpandToSum(expr, x) elif SumQ(expr): w = Wild('w') m = Wild('m', exclude=[x]) v = TogetherSimplify(expr) if SumQ(v) or v.match(x**m*w) and SumQ(w) or LeafCount(v) > LeafCount(expr) + 2: return UnifySum(expr, x) else: return NormalizeIntegrandFactorBase(v, x) else: return expr def NormalizeTogether(u): return NormalizeLeadTermSigns(Together(u)) def NormalizeLeadTermSigns(u): if ProductQ(u): t = 1 for i in u.args: lst = SignOfFactor(i) if lst[0] == 1: t *= lst[1] else: t *= AbsorbMinusSign(lst[1]) return t else: lst = SignOfFactor(u) if lst[0] == 1: return lst[1] else: return AbsorbMinusSign(lst[1]) def AbsorbMinusSign(expr, *x): m = Wild('m', exclude=[x]) u = Wild('u') v = Wild('v') match = expr.match(u*v**m) if match: if len(match) == 3: if SumQ(match[v]) and OddQ(match[m]): return match[u]*(-match[v])**match[m] return -expr def NormalizeSumFactors(u): if AtomQ(u): return u elif ProductQ(u): k = 1 for i in u.args: k *= NormalizeSumFactors(i) return SignOfFactor(k)[0]*SignOfFactor(k)[1] elif SumQ(u): k = 0 for i in u.args: k += NormalizeSumFactors(i) return k else: return u def SignOfFactor(u): if RationalQ(u) and u < 0 or SumQ(u) and NumericFactor(First(u)) < 0: return [-1, -u] elif IntegerPowerQ(u): if SumQ(u.base) and NumericFactor(First(u.base)) < 0: return [(-1)**u.exp, (-u.base)**u.exp] elif ProductQ(u): k = 1 h = 1 for i in u.args: k *= SignOfFactor(i)[0] h *= SignOfFactor(i)[1] return [k, h] return [1, u] def NormalizePowerOfLinear(u, x): v = FactorSquareFree(u) if PowerQ(v): if LinearQ(v.base, x) and FreeQ(v.exp, x): return ExpandToSum(v.base, x)**v.exp return ExpandToSum(v, x) def SimplifyIntegrand(u, x): v = NormalizeLeadTermSigns(NormalizeIntegrandAux(Simplify(u), x)) if 5*LeafCount(v) < 4*LeafCount(u): return v if v != NormalizeLeadTermSigns(u): return v else: return u def SimplifyTerm(u, x): v = Simplify(u) w = Together(v) if LeafCount(v) < LeafCount(w): return NormalizeIntegrand(v, x) else: return NormalizeIntegrand(w, x) def TogetherSimplify(u): v = Together(Simplify(Together(u))) return FixSimplify(v) def SmartSimplify(u): v = Simplify(u) w = factor(v) if LeafCount(w) < LeafCount(v): v = w if Not(FalseQ(w == FractionalPowerOfSquareQ(v))) and FractionalPowerSubexpressionQ(u, w, Expand(w)): v = SubstForExpn(v, w, Expand(w)) else: v = FactorNumericGcd(v) return FixSimplify(v) def SubstForExpn(u, v, w): if u == v: return w if AtomQ(u): return u else: k = 0 for i in u.args: k += SubstForExpn(i, v, w) return k def ExpandToSum(u, *x): if len(x) == 1: x = x[0] expr = 0 if PolyQ(S(u), x): for t in ExponentList(u, x): expr += Coeff(u, x, t)*x**t return expr if BinomialQ(u, x): i = BinomialParts(u, x) expr += i[0] + i[1]*x**i[2] return expr if TrinomialQ(u, x): i = TrinomialParts(u, x) expr += i[0] + i[1]*x**i[3] + i[2]*x**(2*i[3]) return expr if GeneralizedBinomialMatchQ(u, x): i = GeneralizedBinomialParts(u, x) expr += i[0]*x**i[3] + i[1]*x**i[2] return expr if GeneralizedTrinomialMatchQ(u, x): i = GeneralizedTrinomialParts(u, x) expr += i[0]*x**i[4] + i[1]*x**i[3] + i[2]*x**(2*i[3]-i[4]) return expr else: return Expand(u) else: v = x[0] x = x[1] w = ExpandToSum(v, x) r = NonfreeTerms(w, x) if SumQ(r): k = u*FreeTerms(w, x) for i in r.args: k += MergeMonomials(u*i, x) return k else: return u*FreeTerms(w, x) + MergeMonomials(u*r, x) def UnifySum(u, x): if SumQ(u): t = 0 lst = [] for i in u.args: lst += [i] for j in UnifyTerms(lst, x): t += j return t else: return SimplifyTerm(u, x) def UnifyTerms(lst, x): if lst==[]: return lst else: return UnifyTerm(First(lst), UnifyTerms(Rest(lst), x), x) def UnifyTerm(term, lst, x): if lst==[]: return [term] tmp = Simplify(First(lst)/term) if FreeQ(tmp, x): return Prepend(Rest(lst), [(1+tmp)*term]) else: return Prepend(UnifyTerm(term, Rest(lst), x), [First(lst)]) def CalculusQ(u): return False def FunctionOfInverseLinear(*args): # (* If u is a function of an inverse linear binomial of the form 1/(a+b*x), # FunctionOfInverseLinear[u,x] returns the list {a,b}; else it returns False. *) if len(args) == 2: u, x = args return FunctionOfInverseLinear(u, None, x) u, lst, x = args if FreeQ(u, x): return lst elif u == x: return False elif QuotientOfLinearsQ(u, x): tmp = Drop(QuotientOfLinearsParts(u, x), 2) if tmp[1] == 0: return False elif lst is None: return tmp elif ZeroQ(lst[0]*tmp[1] - lst[1]*tmp[0]): return lst return False elif CalculusQ(u): return False tmp = lst for i in u.args: tmp = FunctionOfInverseLinear(i, tmp, x) if AtomQ(tmp): return False return tmp def PureFunctionOfSinhQ(u, v, x): # (* If u is a pure function of Sinh[v] and/or Csch[v], PureFunctionOfSinhQ[u,v,x] returns True; # else it returns False. *) if AtomQ(u): return u != x elif CalculusQ(u): return False elif HyperbolicQ(u) and ZeroQ(u.args[0] - v): return SinhQ(u) or CschQ(u) for i in u.args: if Not(PureFunctionOfSinhQ(i, v, x)): return False return True def PureFunctionOfTanhQ(u, v , x): # (* If u is a pure function of Tanh[v] and/or Coth[v], PureFunctionOfTanhQ[u,v,x] returns True; # else it returns False. *) if AtomQ(u): return u != x elif CalculusQ(u): return False elif HyperbolicQ(u) and ZeroQ(u.args[0] - v): return TanhQ(u) or CothQ(u) for i in u.args: if Not(PureFunctionOfTanhQ(i, v, x)): return False return True def PureFunctionOfCoshQ(u, v, x): # (* If u is a pure function of Cosh[v] and/or Sech[v], PureFunctionOfCoshQ[u,v,x] returns True; # else it returns False. *) if AtomQ(u): return u != x elif CalculusQ(u): return False elif HyperbolicQ(u) and ZeroQ(u.args[0] - v): return CoshQ(u) or SechQ(u) for i in u.args: if Not(PureFunctionOfCoshQ(i, v, x)): return False return True def IntegerQuotientQ(u, v): # (* If u/v is an integer, IntegerQuotientQ[u,v] returns True; else it returns False. *) return IntegerQ(Simplify(u/v)) def OddQuotientQ(u, v): # (* If u/v is odd, OddQuotientQ[u,v] returns True; else it returns False. *) return OddQ(Simplify(u/v)) def EvenQuotientQ(u, v): # (* If u/v is even, EvenQuotientQ[u,v] returns True; else it returns False. *) return EvenQ(Simplify(u/v)) def FindTrigFactor(func1, func2, u, v, flag): # (* If func[w]^m is a factor of u where m is odd and w is an integer multiple of v, # FindTrigFactor[func1,func2,u,v,True] returns the list {w,u/func[w]^n}; else it returns False. *) # (* If func[w]^m is a factor of u where m is odd and w is an integer multiple of v not equal to v, # FindTrigFactor[func1,func2,u,v,False] returns the list {w,u/func[w]^n}; else it returns False. *) if u == 1: return False elif (Head(LeadBase(u)) == func1 or Head(LeadBase(u)) == func2) and OddQ(LeadDegree(u)) and IntegerQuotientQ(LeadBase(u).args[0], v) and (flag or NonzeroQ(LeadBase(u).args[0] - v)): return [LeadBase[u].args[0], RemainingFactors(u)] lst = FindTrigFactor(func1, func2, RemainingFactors(u), v, flag) if AtomQ(lst): return False return [lst[0], LeadFactor(u)*lst[1]] def FunctionOfSinhQ(u, v, x): # (* If u is a function of Sinh[v], FunctionOfSinhQ[u,v,x] returns True; else it returns False. *) if AtomQ(u): return u != x elif CalculusQ(u): return False elif HyperbolicQ(u) and IntegerQuotientQ(u.args[0], v): if OddQuotientQ(u.args[0], v): # (* Basis: If m odd, Sinh[m*v]^n is a function of Sinh[v]. *) return SinhQ(u) or CschQ(u) # (* Basis: If m even, Cos[m*v]^n is a function of Sinh[v]. *) return CoshQ(u) or SechQ(u) elif IntegerPowerQ(u): if HyperbolicQ(u.base) and IntegerQuotientQ(u.base.args[0], v): if EvenQ(u.exp): # (* Basis: If m integer and n even, Hyper[m*v]^n is a function of Sinh[v]. *) return True return FunctionOfSinhQ(u.base, v, x) elif ProductQ(u): if CoshQ(u.args[0]) and SinhQ(u.args[1]) and ZeroQ(u.args[0].args[0] - v/2) and ZeroQ(u.args[1].args[0] - v/2): return FunctionOfSinhQ(Drop(u, 2), v, x) lst = FindTrigFactor(Sinh, Csch, u, v, False) if ListQ(lst) and EvenQuotientQ(lst[0], v): # (* Basis: If m even and n odd, Sinh[m*v]^n == Cosh[v]*u where u is a function of Sinh[v]. *) return FunctionOfSinhQ(Cosh(v)*lst[1], v, x) lst = FindTrigFactor(Cosh, Sech, u, v, False) if ListQ(lst) and OddQuotientQ(lst[0], v): # (* Basis: If m odd and n odd, Cosh[m*v]^n == Cosh[v]*u where u is a function of Sinh[v]. *) return FunctionOfSinhQ(Cosh(v)*lst[1], v, x) lst = FindTrigFactor(Tanh, Coth, u, v, True) if ListQ(lst): # (* Basis: If m integer and n odd, Tanh[m*v]^n == Cosh[v]*u where u is a function of Sinh[v]. *) return FunctionOfSinhQ(Cosh(v)*lst[1], v, x) return all(FunctionOfSinhQ(i, v, x) for i in u.args) return all(FunctionOfSinhQ(i, v, x) for i in u.args) def FunctionOfCoshQ(u, v, x): #(* If u is a function of Cosh[v], FunctionOfCoshQ[u,v,x] returns True; else it returns False. *) if AtomQ(u): return u != x elif CalculusQ(u): return False elif HyperbolicQ(u) and IntegerQuotientQ(u.args[0], v): # (* Basis: If m integer, Cosh[m*v]^n is a function of Cosh[v]. *) return CoshQ(u) or SechQ(u) elif IntegerPowerQ(u): if HyperbolicQ(u.base) and IntegerQuotientQ(u.base.args[0], v): if EvenQ(u.exp): # (* Basis: If m integer and n even, Hyper[m*v]^n is a function of Cosh[v]. *) return True return FunctionOfCoshQ(u.base, v, x) elif ProductQ(u): lst = FindTrigFactor(Sinh, Csch, u, v, False) if ListQ(lst): # (* Basis: If m integer and n odd, Sinh[m*v]^n == Sinh[v]*u where u is a function of Cosh[v]. *) return FunctionOfCoshQ(Sinh(v)*lst[1], v, x) lst = FindTrigFactor(Tanh, Coth, u, v, True) if ListQ(lst): # (* Basis: If m integer and n odd, Tanh[m*v]^n == Sinh[v]*u where u is a function of Cosh[v]. *) return FunctionOfCoshQ(Sinh(v)*lst[1], v, x) return all(FunctionOfCoshQ(i, v, x) for i in u.args) return all(FunctionOfCoshQ(i, v, x) for i in u.args) def OddHyperbolicPowerQ(u, v, x): if SinhQ(u) or CoshQ(u) or SechQ(u) or CschQ(u): return OddQuotientQ(u.args[0], v) if PowerQ(u): return OddQ(u.exp) and OddHyperbolicPowerQ(u.base, v, x) if ProductQ(u): if Not(EqQ(FreeFactors(u, x), 1)): return OddHyperbolicPowerQ(NonfreeFactors(u, x), v, x) lst = [] for i in u.args: if Not(FunctionOfTanhQ(i, v, x)): lst.append(i) if lst == []: return True return Length(lst)==1 and OddHyperbolicPowerQ(lst[0], v, x) if SumQ(u): return all(OddHyperbolicPowerQ(i, v, x) for i in u.args) return False def FunctionOfTanhQ(u, v, x): #(* If u is a function of the form f[Tanh[v],Coth[v]] where f is independent of x, # FunctionOfTanhQ[u,v,x] returns True; else it returns False. *) if AtomQ(u): return u != x elif CalculusQ(u): return False elif HyperbolicQ(u) and IntegerQuotientQ(u.args[0], v): return TanhQ(u) or CothQ(u) or EvenQuotientQ(u.args[0], v) elif PowerQ(u): if EvenQ(u.exp) and HyperbolicQ(u.base) and IntegerQuotientQ(u.base.args[0], v): return True elif EvenQ(u.args[1]) and SumQ(u.args[0]): return FunctionOfTanhQ(Expand(u.args[0]**2, v, x)) if ProductQ(u): lst = [] for i in u.args: if Not(FunctionOfTanhQ(i, v, x)): lst.append(i) if lst == []: return True return Length(lst)==2 and OddHyperbolicPowerQ(lst[0], v, x) and OddHyperbolicPowerQ(lst[1], v, x) return all(FunctionOfTanhQ(i, v, x) for i in u.args) def FunctionOfTanhWeight(u, v, x): """ u is a function of the form f(tanh(v), coth(v)) where f is independent of x. FunctionOfTanhWeight(u, v, x) returns a nonnegative number if u is best considered a function of tanh(v), else it returns a negative number. Examples ======== >>> from sympy import sinh, log, tanh >>> from sympy.abc import x >>> from sympy.integrals.rubi.utility_function import FunctionOfTanhWeight >>> FunctionOfTanhWeight(x, log(x), x) 0 >>> FunctionOfTanhWeight(sinh(log(x)), log(x), x) 0 >>> FunctionOfTanhWeight(tanh(log(x)), log(x), x) 1 """ if AtomQ(u): return S(0) elif CalculusQ(u): return S(0) elif HyperbolicQ(u) and IntegerQuotientQ(u.args[0], v): if TanhQ(u) and ZeroQ(u.args[0] - v): return S(1) elif CothQ(u) and ZeroQ(u.args[0] - v): return S(-1) return S(0) elif PowerQ(u): if EvenQ(u.exp) and HyperbolicQ(u.base) and IntegerQuotientQ(u.base.args[0], v): if TanhQ(u.base) or CoshQ(u.base) or SechQ(u.base): return S(1) return S(-1) if ProductQ(u): if all(FunctionOfTanhQ(i, v, x) for i in u.args): return Add(*[FunctionOfTanhWeight(i, v, x) for i in u.args]) return S(0) return Add(*[FunctionOfTanhWeight(i, v, x) for i in u.args]) def FunctionOfHyperbolicQ(u, v, x): # (* If u (x) is equivalent to a function of the form f (Sinh[v],Cosh[v],Tanh[v],Coth[v],Sech[v],Csch[v]) # where f is independent of x, FunctionOfHyperbolicQ[u,v,x] returns True; else it returns False. *) if AtomQ(u): return u != x elif CalculusQ(u): return False elif HyperbolicQ(u) and IntegerQuotientQ(u.args[0], v): return True return all(FunctionOfHyperbolicQ(i, v, x) for i in u.args) def SmartNumerator(expr): if PowerQ(expr): n = expr.exp u = expr.base if RationalQ(n) and n < 0: return SmartDenominator(u**(-n)) elif ProductQ(expr): return Mul(*[SmartNumerator(i) for i in expr.args]) return Numerator(expr) def SmartDenominator(expr): if PowerQ(expr): u = expr.base n = expr.exp if RationalQ(n) and n < 0: return SmartNumerator(u**(-n)) elif ProductQ(expr): return Mul(*[SmartDenominator(i) for i in expr.args]) return Denominator(expr) def ActivateTrig(u): return u def ExpandTrig(*args): if len(args) == 2: u, x = args return ActivateTrig(ExpandIntegrand(u, x)) u, v, x = args w = ExpandTrig(v, x) z = ActivateTrig(u) if SumQ(w): return w.func(*[z*i for i in w.args]) return z*w def TrigExpand(u): return expand_trig(u) # SubstForTrig[u_,sin_,cos_,v_,x_] := # If[AtomQ[u], # u, # If[TrigQ[u] && IntegerQuotientQ[u[[1]],v], # If[u[[1]]===v || ZeroQ[u[[1]]-v], # If[SinQ[u], # sin, # If[CosQ[u], # cos, # If[TanQ[u], # sin/cos, # If[CotQ[u], # cos/sin, # If[SecQ[u], # 1/cos, # 1/sin]]]]], # Map[Function[SubstForTrig[#,sin,cos,v,x]], # ReplaceAll[TrigExpand[Head[u][Simplify[u[[1]]/v]*x]],x->v]]], # If[ProductQ[u] && CosQ[u[[1]]] && SinQ[u[[2]]] && ZeroQ[u[[1,1]]-v/2] && ZeroQ[u[[2,1]]-v/2], # sin/2*SubstForTrig[Drop[u,2],sin,cos,v,x], # Map[Function[SubstForTrig[#,sin,cos,v,x]],u]]]] def SubstForTrig(u, sin_ , cos_, v, x): # (* u (v) is an expression of the form f (Sin[v],Cos[v],Tan[v],Cot[v],Sec[v],Csc[v]). *) # (* SubstForTrig[u,sin,cos,v,x] returns the expression f (sin,cos,sin/cos,cos/sin,1/cos,1/sin). *) if AtomQ(u): return u elif TrigQ(u) and IntegerQuotientQ(u.args[0], v): if u.args[0] == v or ZeroQ(u.args[0] - v): if SinQ(u): return sin_ elif CosQ(u): return cos_ elif TanQ(u): return sin_/cos_ elif CotQ(u): return cos_/sin_ elif SecQ(u): return 1/cos_ return 1/sin_ r = ReplaceAll(TrigExpand(Head(u)(Simplify(u.args[0]/v*x))), {x: v}) return r.func(*[SubstForTrig(i, sin_, cos_, v, x) for i in r.args]) if ProductQ(u) and CosQ(u.args[0]) and SinQ(u.args[1]) and ZeroQ(u.args[0].args[0] - v/2) and ZeroQ(u.args[1].args[0] - v/2): return sin(x)/2*SubstForTrig(Drop(u, 2), sin_, cos_, v, x) return u.func(*[SubstForTrig(i, sin_, cos_, v, x) for i in u.args]) def SubstForHyperbolic(u, sinh_, cosh_, v, x): # (* u (v) is an expression of the form f (Sinh[v],Cosh[v],Tanh[v],Coth[v],Sech[v],Csch[v]). *) # (* SubstForHyperbolic[u,sinh,cosh,v,x] returns the expression # f (sinh,cosh,sinh/cosh,cosh/sinh,1/cosh,1/sinh). *) if AtomQ(u): return u elif HyperbolicQ(u) and IntegerQuotientQ(u.args[0], v): if u.args[0] == v or ZeroQ(u.args[0] - v): if SinhQ(u): return sinh_ elif CoshQ(u): return cosh_ elif TanhQ(u): return sinh_/cosh_ elif CothQ(u): return cosh_/sinh_ if SechQ(u): return 1/cosh_ return 1/sinh_ r = ReplaceAll(TrigExpand(Head(u)(Simplify(u.args[0]/v)*x)), {x: v}) return r.func(*[SubstForHyperbolic(i, sinh_, cosh_, v, x) for i in r.args]) elif ProductQ(u) and CoshQ(u.args[0]) and SinhQ(u.args[1]) and ZeroQ(u.args[0].args[0] - v/2) and ZeroQ(u.args[1].args[0] - v/2): return sinh(x)/2*SubstForHyperbolic(Drop(u, 2), sinh_, cosh_, v, x) return u.func(*[SubstForHyperbolic(i, sinh_, cosh_, v, x) for i in u.args]) def InertTrigFreeQ(u): return FreeQ(u, sin) and FreeQ(u, cos) and FreeQ(u, tan) and FreeQ(u, cot) and FreeQ(u, sec) and FreeQ(u, csc) def LCM(a, b): return lcm(a, b) def SubstForFractionalPowerOfLinear(u, x): # (* If u has a subexpression of the form (a+b*x)^(m/n) where m and n>1 are integers, # SubstForFractionalPowerOfLinear[u,x] returns the list {v,n,a+b*x,1/b} where v is u # with subexpressions of the form (a+b*x)^(m/n) replaced by x^m and x replaced # by -a/b+x^n/b, and all times x^(n-1); else it returns False. *) lst = FractionalPowerOfLinear(u, S(1), False, x) if AtomQ(lst) or FalseQ(lst[1]): return False n = lst[0] a = Coefficient(lst[1], x, 0) b = Coefficient(lst[1], x, 1) tmp = Simplify(x**(n-1)*SubstForFractionalPower(u, lst[1], n, -a/b + x**n/b, x)) return [NonfreeFactors(tmp, x), n, lst[1], FreeFactors(tmp, x)/b] def FractionalPowerOfLinear(u, n, v, x): # If u has a subexpression of the form (a + b*x)**(m/n), FractionalPowerOfLinear(u, 1, False, x) returns [n, a + b*x], else it returns False. if AtomQ(u) or FreeQ(u, x): return [n, v] elif CalculusQ(u): return False elif FractionalPowerQ(u): if LinearQ(u.base, x) and (FalseQ(v) or ZeroQ(u.base - v)): return [LCM(Denominator(u.exp), n), u.base] lst = [n, v] for i in u.args: lst = FractionalPowerOfLinear(i, lst[0], lst[1], x) if AtomQ(lst): return False return lst def InverseFunctionOfLinear(u, x): # (* If u has a subexpression of the form g[a+b*x] where g is an inverse function, # InverseFunctionOfLinear[u,x] returns g[a+b*x]; else it returns False. *) if AtomQ(u) or CalculusQ(u) or FreeQ(u, x): return False elif InverseFunctionQ(u) and LinearQ(u.args[0], x): return u for i in u.args: tmp = InverseFunctionOfLinear(i, x) if Not(AtomQ(tmp)): return tmp return False def InertTrigQ(*args): if len(args) == 1: f = args[0] l = [sin,cos,tan,cot,sec,csc] return any(Head(f) == i for i in l) elif len(args) == 2: f, g = args if f == g: return InertTrigQ(f) return InertReciprocalQ(f, g) or InertReciprocalQ(g, f) else: f, g, h = args return InertTrigQ(g, f) and InertTrigQ(g, h) def InertReciprocalQ(f, g): return (f.func == sin and g.func == csc) or (f.func == cos and g.func == sec) or (f.func == tan and g.func == cot) def DeactivateTrig(u, x): # (* u is a function of trig functions of a linear function of x. *) # (* DeactivateTrig[u,x] returns u with the trig functions replaced with inert trig functions. *) return FixInertTrigFunction(DeactivateTrigAux(u, x), x) def FixInertTrigFunction(u, x): return u def DeactivateTrigAux(u, x): if AtomQ(u): return u elif TrigQ(u) and LinearQ(u.args[0], x): v = ExpandToSum(u.args[0], x) if SinQ(u): return sin(v) elif CosQ(u): return cos(v) elif TanQ(u): return tan(u) elif CotQ(u): return cot(v) elif SecQ(u): return sec(v) return csc(v) elif HyperbolicQ(u) and LinearQ(u.args[0], x): v = ExpandToSum(I*u.args[0], x) if SinhQ(u): return -I*sin(v) elif CoshQ(u): return cos(v) elif TanhQ(u): return -I*tan(v) elif CothQ(u): I*cot(v) elif SechQ(u): return sec(v) return I*csc(v) return u.func(*[DeactivateTrigAux(i, x) for i in u.args]) def PowerOfInertTrigSumQ(u, func, x): p_ = Wild('p', exclude=[x]) q_ = Wild('q', exclude=[x]) a_ = Wild('a', exclude=[x]) b_ = Wild('b', exclude=[x]) c_ = Wild('c', exclude=[x]) d_ = Wild('d', exclude=[x]) n_ = Wild('n', exclude=[x]) w_ = Wild('w') pattern = (a_ + b_*(c_*func(w_))**p_)**n_ match = u.match(pattern) if match: keys = [a_, b_, c_, n_, p_, w_] if len(keys) == len(match): return True pattern = (a_ + b_*(d_*func(w_))**p_ + c_*(d_*func(w_))**q_)**n_ match = u.match(pattern) if match: keys = [a_, b_, c_, d_, n_, p_, q_, w_] if len(keys) == len(match): return True return False def PiecewiseLinearQ(*args): # (* If the derivative of u wrt x is a constant wrt x, PiecewiseLinearQ[u,x] returns True; # else it returns False. *) if len(args) == 3: u, v, x = args return PiecewiseLinearQ(u, x) and PiecewiseLinearQ(v, x) u, x = args if LinearQ(u, x): return True c_ = Wild('c', exclude=[x]) F_ = Wild('F', exclude=[x]) v_ = Wild('v') match = u.match(Log(c_*F_**v_)) if match: if len(match) == 3: if LinearQ(match[v_], x): return True try: F = type(u) G = type(u.args[0]) v = u.args[0].args[0] if LinearQ(v, x): if MemberQ([[atanh, tanh], [atanh, coth], [acoth, coth], [acoth, tanh], [atan, tan], [atan, cot], [acot, cot], [acot, tan]], [F, G]): return True except: pass return False def KnownTrigIntegrandQ(lst, u, x): if u == 1: return True a_ = Wild('a', exclude=[x]) b_ = Wild('b', exclude=[x, 0]) func_ = WildFunction('func') m_ = Wild('m', exclude=[x]) A_ = Wild('A', exclude=[x]) B_ = Wild('B', exclude=[x, 0]) C_ = Wild('C', exclude=[x, 0]) match = u.match((a_ + b_*func_)**m_) if match: func = match[func_] if LinearQ(func.args[0], x) and MemberQ(lst, func.func): return True match = u.match((a_ + b_*func_)**m_*(A_ + B_*func_)) if match: func = match[func_] if LinearQ(func.args[0], x) and MemberQ(lst, func.func): return True match = u.match(A_ + C_*func_**2) if match: func = match[func_] if LinearQ(func.args[0], x) and MemberQ(lst, func.func): return True match = u.match(A_ + B_*func_ + C_*func_**2) if match: func = match[func_] if LinearQ(func.args[0], x) and MemberQ(lst, func.func): return True match = u.match((a_ + b_*func_)**m_*(A_ + C_*func_**2)) if match: func = match[func_] if LinearQ(func.args[0], x) and MemberQ(lst, func.func): return True match = u.match((a_ + b_*func_)**m_*(A_ + B_*func_ + C_*func_**2)) if match: func = match[func_] if LinearQ(func.args[0], x) and MemberQ(lst, func.func): return True return False def KnownSineIntegrandQ(u, x): return KnownTrigIntegrandQ([sin, cos], u, x) def KnownTangentIntegrandQ(u, x): return KnownTrigIntegrandQ([tan], u, x) def KnownCotangentIntegrandQ(u, x): return KnownTrigIntegrandQ([cot], u, x) def KnownSecantIntegrandQ(u, x): return KnownTrigIntegrandQ([sec, csc], u, x) def TryPureTanSubst(u, x): a_ = Wild('a', exclude=[x]) b_ = Wild('b', exclude=[x]) c_ = Wild('c', exclude=[x]) G_ = Wild('G') F = u.func try: if MemberQ([atan, acot, atanh, acoth], F): match = u.args[0].match(c_*(a_ + b_*G_)) if match: if len(match) == 4: G = match[G_] if MemberQ([tan, cot, tanh, coth], G.func): if LinearQ(G.args[0], x): return True except: pass return False def TryTanhSubst(u, x): if LogQ(u): return False elif not FalseQ(FunctionOfLinear(u, x)): return False a_ = Wild('a', exclude=[x]) m_ = Wild('m', exclude=[x]) p_ = Wild('p', exclude=[x]) r_, s_, t_, n_, b_, f_, g_ = map(Wild, 'rstnbfg') match = u.match(r_*(s_ + t_)**n_) if match: if len(match) == 4: r, s, t, n = [match[i] for i in [r_, s_, t_, n_]] if IntegerQ(n) and PositiveQ(n): return False match = u.match(1/(a_ + b_*f_**n_)) if match: if len(match) == 4: a, b, f, n = [match[i] for i in [a_, b_, f_, n_]] if SinhCoshQ(f) and IntegerQ(n) and n > 2: return False match = u.match(f_*g_) if match: if len(match) == 2: f, g = match[f_], match[g_] if SinhCoshQ(f) and SinhCoshQ(g): if IntegersQ(f.args[0]/x, g.args[0]/x): return False match = u.match(r_*(a_*s_**m_)**p_) if match: if len(match) == 5: r, a, s, m, p = [match[i] for i in [r_, a_, s_, m_, p_]] if Not(m==2 and (s == Sech(x) or s == Csch(x))): return False if u != ExpandIntegrand(u, x): return False return True def TryPureTanhSubst(u, x): F = u.func a_ = Wild('a', exclude=[x]) G_ = Wild('G') if F == sym_log: return False match = u.args[0].match(a_*G_) if match and len(match) == 2: G = match[G_].func if MemberQ([atanh, acoth], F) and MemberQ([tanh, coth], G): return False if u != ExpandIntegrand(u, x): return False return True def AbsurdNumberGCD(*seq): # (* m, n, ... must be absurd numbers. AbsurdNumberGCD[m,n,...] returns the gcd of m, n, ... *) lst = list(seq) if Length(lst) == 1: return First(lst) return AbsurdNumberGCDList(FactorAbsurdNumber(First(lst)), FactorAbsurdNumber(AbsurdNumberGCD(*Rest(lst)))) def AbsurdNumberGCDList(lst1, lst2): # (* lst1 and lst2 must be absurd number prime factorization lists. *) # (* AbsurdNumberGCDList[lst1,lst2] returns the gcd of the absurd numbers represented by lst1 and lst2. *) if lst1 == []: return Mul(*[i[0]**Min(i[1],0) for i in lst2]) elif lst2 == []: return Mul(*[i[0]**Min(i[1],0) for i in lst1]) elif lst1[0][0] == lst2[0][0]: if lst1[0][1] <= lst2[0][1]: return lst1[0][0]**lst1[0][1]*AbsurdNumberGCDList(Rest(lst1), Rest(lst2)) return lst1[0][0]**lst2[0][1]*AbsurdNumberGCDList(Rest(lst1), Rest(lst2)) elif lst1[0][0] < lst2[0][0]: if lst1[0][1] < 0: return lst1[0][0]**lst1[0][1]*AbsurdNumberGCDList(Rest(lst1), lst2) return AbsurdNumberGCDList(Rest(lst1), lst2) elif lst2[0][1] < 0: return lst2[0][0]**lst2[0][1]*AbsurdNumberGCDList(lst1, Rest(lst2)) return AbsurdNumberGCDList(lst1, Rest(lst2)) def ExpandTrigExpand(u, F, v, m, n, x): w = Expand(TrigExpand(F.xreplace({x: n*x}))**m).xreplace({x: v}) if SumQ(w): t = 0 for i in w.args: t += u*i return t else: return u*w def ExpandTrigReduce(*args): if len(args) == 3: u = args[0] v = args[1] x = args[2] w = ExpandTrigReduce(v, x) if SumQ(w): t = 0 for i in w.args: t += u*i return t else: return u*w else: u = args[0] x = args[1] return ExpandTrigReduceAux(u, x) def ExpandTrigReduceAux(u, x): v = TrigReduce(u).expand() if SumQ(v): t = 0 for i in v.args: t += NormalizeTrig(i, x) return t return NormalizeTrig(v, x) def NormalizeTrig(v, x): a = Wild('a', exclude=[x]) n = Wild('n', exclude=[x, 0]) F = Wild('F') expr = a*F**n M = v.match(expr) if M and len(M[F].args) == 1 and PolynomialQ(M[F].args[0], x) and Exponent(M[F].args[0], x) > 0: u = M[F].args[0] return M[a]*M[F].xreplace({u: ExpandToSum(u, x)})**M[n] else: return v #================================= def TrigToExp(expr): ex = expr.rewrite(sin, sym_exp).rewrite(cos, sym_exp).rewrite(tan, sym_exp).rewrite(sec, sym_exp).rewrite(csc, sym_exp).rewrite(cot, sym_exp) return ex.replace(sym_exp, rubi_exp) def ExpandTrigToExp(u, *args): if len(args) == 1: x = args[0] return ExpandTrigToExp(1, u, x) else: v = args[0] x = args[1] w = TrigToExp(v) k = 0 if SumQ(w): for i in w.args: k += SimplifyIntegrand(u*i, x) w = k else: w = SimplifyIntegrand(u*w, x) return ExpandIntegrand(FreeFactors(w, x), NonfreeFactors(w, x),x) #====================================== def TrigReduce(i): """ TrigReduce(expr) rewrites products and powers of trigonometric functions in expr in terms of trigonometric functions with combined arguments. Examples ======== >>> from sympy import sin, cos >>> from sympy.integrals.rubi.utility_function import TrigReduce >>> from sympy.abc import x >>> TrigReduce(cos(x)**2) cos(2*x)/2 + 1/2 >>> TrigReduce(cos(x)**2*sin(x)) sin(x)/4 + sin(3*x)/4 >>> TrigReduce(cos(x)**2+sin(x)) sin(x) + cos(2*x)/2 + 1/2 """ if SumQ(i): t = 0 for k in i.args: t += TrigReduce(k) return t if ProductQ(i): if any(PowerQ(k) for k in i.args): if (i.rewrite((sin, sinh), sym_exp).rewrite((cos, cosh), sym_exp).expand().rewrite(sym_exp, sin)).has(I, cosh, sinh): return i.rewrite((sin, sinh), sym_exp).rewrite((cos, cosh), sym_exp).expand().rewrite(sym_exp, sin).simplify() else: return i.rewrite((sin, sinh), sym_exp).rewrite((cos, cosh), sym_exp).expand().rewrite(sym_exp, sin) else: a = Wild('a') b = Wild('b') v = Wild('v') Match = i.match(v*sin(a)*cos(b)) if Match: a = Match[a] b = Match[b] v = Match[v] return i.subs(v*sin(a)*cos(b), v*S(1)/2*(sin(a + b) + sin(a - b))) Match = i.match(v*sin(a)*sin(b)) if Match: a = Match[a] b = Match[b] v = Match[v] return i.subs(v*sin(a)*sin(b), v*S(1)/2*cos(a - b) - cos(a + b)) Match = i.match(v*cos(a)*cos(b)) if Match: a = Match[a] b = Match[b] v = Match[v] return i.subs(v*cos(a)*cos(b), v*S(1)/2*cos(a + b) + cos(a - b)) Match = i.match(v*sinh(a)*cosh(b)) if Match: a = Match[a] b = Match[b] v = Match[v] return i.subs(v*sinh(a)*cosh(b), v*S(1)/2*(sinh(a + b) + sinh(a - b))) Match = i.match(v*sinh(a)*sinh(b)) if Match: a = Match[a] b = Match[b] v = Match[v] return i.subs(v*sinh(a)*sinh(b), v*S(1)/2*cosh(a - b) - cosh(a + b)) Match = i.match(v*cosh(a)*cosh(b)) if Match: a = Match[a] b = Match[b] v = Match[v] return i.subs(v*cosh(a)*cosh(b), v*S(1)/2*cosh(a + b) + cosh(a - b)) if PowerQ(i): if i.has(sin, sinh): if (i.rewrite((sin, sinh), sym_exp).expand().rewrite(sym_exp, sin)).has(I, cosh, sinh): return i.rewrite((sin, sinh), sym_exp).expand().rewrite(sym_exp, sin).simplify() else: return i.rewrite((sin, sinh), sym_exp).expand().rewrite(sym_exp, sin) if i.has(cos, cosh): if (i.rewrite((cos, cosh), sym_exp).expand().rewrite(sym_exp, cos)).has(I, cosh, sinh): return i.rewrite((cos, cosh), sym_exp).expand().rewrite(sym_exp, cos).simplify() else: return i.rewrite((cos, cosh), sym_exp).expand().rewrite(sym_exp, cos) return i def FunctionOfTrig(u, *args): # If u is a function of trig functions of v where v is a linear function of x, # FunctionOfTrig[u,x] returns v; else it returns False. if len(args) == 1: x = args[0] v = FunctionOfTrig(u, None, x) if v: return v else: return False else: v, x = args if AtomQ(u): if u == x: return False else: return v if TrigQ(u) and LinearQ(u.args[0], x): if v is None: return u.args[0] else: a = Coefficient(v, x, 0) b = Coefficient(v, x, 1) c = Coefficient(u.args[0], x, 0) d = Coefficient(u.args[0], x, 1) if ZeroQ(a*d - b*c) and RationalQ(b/d): return a/Numerator(b/d) + b*x/Numerator(b/d) else: return False if HyperbolicQ(u) and LinearQ(u.args[0], x): if v is None: return I*u.args[0] a = Coefficient(v, x, 0) b = Coefficient(v, x, 1) c = I*Coefficient(u.args[0], x, 0) d = I*Coefficient(u.args[0], x, 1) if ZeroQ(a*d - b*c) and RationalQ(b/d): return a/Numerator(b/d) + b*x/Numerator(b/d) else: return False if CalculusQ(u): return False else: w = v for i in u.args: w = FunctionOfTrig(i, w, x) if FalseQ(w): return False return w def AlgebraicTrigFunctionQ(u, x): # If u is algebraic function of trig functions, AlgebraicTrigFunctionQ(u,x) returns True; else it returns False. if AtomQ(u): return True elif TrigQ(u) and LinearQ(u.args[0], x): return True elif HyperbolicQ(u) and LinearQ(u.args[0], x): return True elif PowerQ(u): if FreeQ(u.exp, x): return AlgebraicTrigFunctionQ(u.base, x) elif ProductQ(u) or SumQ(u): for i in u.args: if not AlgebraicTrigFunctionQ(i, x): return False return True return False def FunctionOfHyperbolic(u, *x): # If u is a function of hyperbolic trig functions of v where v is linear in x, # FunctionOfHyperbolic(u,x) returns v; else it returns False. if len(x) == 1: x = x[0] v = FunctionOfHyperbolic(u, None, x) if v is None: return False else: return v else: v = x[0] x = x[1] if AtomQ(u): if u == x: return False return v if HyperbolicQ(u) and LinearQ(u.args[0], x): if v is None: return u.args[0] a = Coefficient(v, x, 0) b = Coefficient(v, x, 1) c = Coefficient(u.args[0], x, 0) d = Coefficient(u.args[0], x, 1) if ZeroQ(a*d - b*c) and RationalQ(b/d): return a/Numerator(b/d) + b*x/Numerator(b/d) else: return False if CalculusQ(u): return False w = v for i in u.args: if w == FunctionOfHyperbolic(i, w, x): return False return w def FunctionOfQ(v, u, x, PureFlag=False): # v is a function of x. If u is a function of v, FunctionOfQ(v, u, x) returns True; else it returns False. *) if FreeQ(u, x): return False elif AtomQ(v): return True elif ProductQ(v) and Not(EqQ(FreeFactors(v, x), 1)): return FunctionOfQ(NonfreeFactors(v, x), u, x, PureFlag) elif PureFlag: if SinQ(v) or CscQ(v): return PureFunctionOfSinQ(u, v.args[0], x) elif CosQ(v) or SecQ(v): return PureFunctionOfCosQ(u, v.args[0], x) elif TanQ(v): return PureFunctionOfTanQ(u, v.args[0], x) elif CotQ(v): return PureFunctionOfCotQ(u, v.args[0], x) elif SinhQ(v) or CschQ(v): return PureFunctionOfSinhQ(u, v.args[0], x) elif CoshQ(v) or SechQ(v): return PureFunctionOfCoshQ(u, v.args[0], x) elif TanhQ(v): return PureFunctionOfTanhQ(u, v.args[0], x) elif CothQ(v): return PureFunctionOfCothQ(u, v.args[0], x) else: return FunctionOfExpnQ(u, v, x) != False elif SinQ(v) or CscQ(v): return FunctionOfSinQ(u, v.args[0], x) elif CosQ(v) or SecQ(v): return FunctionOfCosQ(u, v.args[0], x) elif TanQ(v) or CotQ(v): FunctionOfTanQ(u, v.args[0], x) elif SinhQ(v) or CschQ(v): return FunctionOfSinhQ(u, v.args[0], x) elif CoshQ(v) or SechQ(v): return FunctionOfCoshQ(u, v.args[0], x) elif TanhQ(v) or CothQ(v): return FunctionOfTanhQ(u, v.args[0], x) return FunctionOfExpnQ(u, v, x) != False def FunctionOfExpnQ(u, v, x): if u == v: return 1 if AtomQ(u): if u == x: return False else: return 0 if CalculusQ(u): return False if PowerQ(u): if FreeQ(u.exp, x): if ZeroQ(u.base - v): if IntegerQ(u.exp): return u.exp else: return 1 if PowerQ(v): if FreeQ(v.exp, x) and ZeroQ(u.base-v.base): if RationalQ(v.exp): if RationalQ(u.exp) and IntegerQ(u.exp/v.exp) and (v.exp>0 or u.exp<0): return u.exp/v.exp else: return False if IntegerQ(Simplify(u.exp/v.exp)): return Simplify(u.exp/v.exp) else: return False return FunctionOfExpnQ(u.base, v, x) if ProductQ(u) and Not(EqQ(FreeFactors(u, x), 1)): return FunctionOfExpnQ(NonfreeFactors(u, x), v, x) if ProductQ(u) and ProductQ(v): deg1 = FunctionOfExpnQ(First(u), First(v), x) if deg1==False: return False deg2 = FunctionOfExpnQ(Rest(u), Rest(v), x); if deg1==deg2 and FreeQ(Simplify(u/v^deg1), x): return deg1 else: return False lst = [] for i in u.args: if FunctionOfExpnQ(i, v, x) is False: return False lst.append(FunctionOfExpnQ(i, v, x)) return Apply(GCD, lst) def PureFunctionOfSinQ(u, v, x): # If u is a pure function of Sin(v) and/or Csc(v), PureFunctionOfSinQ(u, v, x) returns True; else it returns False. if AtomQ(u): return u!=x if CalculusQ(u): return False if TrigQ(u) and ZeroQ(u.args[0]-v): return SinQ(u) or CscQ(u) for i in u.args: if Not(PureFunctionOfSinQ(i, v, x)): return False return True def PureFunctionOfCosQ(u, v, x): # If u is a pure function of Cos(v) and/or Sec(v), PureFunctionOfCosQ(u, v, x) returns True; else it returns False. if AtomQ(u): return u!=x if CalculusQ(u): return False if TrigQ(u) and ZeroQ(u.args[0]-v): return CosQ(u) or SecQ(u) for i in u.args: if Not(PureFunctionOfCosQ(i, v, x)): return False return True def PureFunctionOfTanQ(u, v, x): # If u is a pure function of Tan(v) and/or Cot(v), PureFunctionOfTanQ(u, v, x) returns True; else it returns False. if AtomQ(u): return u!=x if CalculusQ(u): return False if TrigQ(u) and ZeroQ(u.args[0]-v): return TanQ(u) or CotQ(u) for i in u.args: if Not(PureFunctionOfTanQ(i, v, x)): return False return True def PureFunctionOfCotQ(u, v, x): # If u is a pure function of Cot(v), PureFunctionOfCotQ(u, v, x) returns True; else it returns False. if AtomQ(u): return u!=x if CalculusQ(u): return False if TrigQ(u) and ZeroQ(u.args[0]-v): return CotQ(u) for i in u.args: if Not(PureFunctionOfCotQ(i, v, x)): return False return True def FunctionOfCosQ(u, v, x): # If u is a function of Cos[v], FunctionOfCosQ[u,v,x] returns True; else it returns False. if AtomQ(u): return u != x elif CalculusQ(u): return False elif TrigQ(u) and IntegerQuotientQ(u.args[0], v): # Basis: If m integer, Cos[m*v]^n is a function of Cos[v]. *) return CosQ(u) or SecQ(u) elif IntegerPowerQ(u): if TrigQ(u.base) and IntegerQuotientQ(u.base.args[0], v): if EvenQ(u.exp): # Basis: If m integer and n even, Trig[m*v]^n is a function of Cos[v]. *) return True return FunctionOfCosQ(u.base, v, x) elif ProductQ(u): lst = FindTrigFactor(sin, csc, u, v, False) if ListQ(lst): # (* Basis: If m integer and n odd, Sin[m*v]^n == Sin[v]*u where u is a function of Cos[v]. *) return FunctionOfCosQ(Sin(v)*lst[1], v, x) lst = FindTrigFactor(tan, cot, u, v, True) if ListQ(lst): # (* Basis: If m integer and n odd, Tan[m*v]^n == Sin[v]*u where u is a function of Cos[v]. *) return FunctionOfCosQ(Sin(v)*lst[1], v, x) return all(FunctionOfCosQ(i, v, x) for i in u.args) return all(FunctionOfCosQ(i, v, x) for i in u.args) def FunctionOfSinQ(u, v, x): # If u is a function of Sin[v], FunctionOfSinQ[u,v,x] returns True; else it returns False. if AtomQ(u): return u != x elif CalculusQ(u): return False elif TrigQ(u) and IntegerQuotientQ(u.args[0], v): if OddQuotientQ(u.args[0], v): # Basis: If m odd, Sin[m*v]^n is a function of Sin[v]. return SinQ(u) or CscQ(u) # Basis: If m even, Cos[m*v]^n is a function of Sin[v]. return CosQ(u) or SecQ(u) elif IntegerPowerQ(u): if TrigQ(u.base) and IntegerQuotientQ(u.base.args[0], v): if EvenQ(u.exp): # Basis: If m integer and n even, Hyper[m*v]^n is a function of Sin[v]. return True return FunctionOfSinQ(u.base, v, x) elif ProductQ(u): if CosQ(u.args[0]) and SinQ(u.args[1]) and ZeroQ(u.args[0].args[0] - v/2) and ZeroQ(u.args[1].args[0] - v/2): return FunctionOfSinQ(Drop(u, 2), v, x) lst = FindTrigFactor(sin, csch, u, v, False) if ListQ(lst) and EvenQuotientQ(lst[0], v): # Basis: If m even and n odd, Sin[m*v]^n == Cos[v]*u where u is a function of Sin[v]. return FunctionOfSinQ(Cos(v)*lst[1], v, x) lst = FindTrigFactor(cos, sec, u, v, False) if ListQ(lst) and OddQuotientQ(lst[0], v): # Basis: If m odd and n odd, Cos[m*v]^n == Cos[v]*u where u is a function of Sin[v]. return FunctionOfSinQ(Cos(v)*lst[1], v, x) lst = FindTrigFactor(tan, cot, u, v, True) if ListQ(lst): # Basis: If m integer and n odd, Tan[m*v]^n == Cos[v]*u where u is a function of Sin[v]. return FunctionOfSinQ(Cos(v)*lst[1], v, x) return all(FunctionOfSinQ(i, v, x) for i in u.args) return all(FunctionOfSinQ(i, v, x) for i in u.args) def OddTrigPowerQ(u, v, x): if SinQ(u) or CosQ(u) or SecQ(u) or CscQ(u): return OddQuotientQ(u.args[0], v) if PowerQ(u): return OddQ(u.exp) and OddTrigPowerQ(u.base, v, x) if ProductQ(u): if not FreeFactors(u, x) == 1: return OddTrigPowerQ(NonfreeFactors(u, x), v, x) lst = [] for i in u.args: if Not(FunctionOfTanQ(i, v, x)): lst.append(i) if lst == []: return True return Length(lst)==1 and OddTrigPowerQ(lst[0], v, x) if SumQ(u): return all(OddTrigPowerQ(i, v, x) for i in u.args) return False def FunctionOfTanQ(u, v, x): # If u is a function of the form f[Tan[v],Cot[v]] where f is independent of x, # FunctionOfTanQ[u,v,x] returns True; else it returns False. if AtomQ(u): return u != x elif CalculusQ(u): return False elif TrigQ(u) and IntegerQuotientQ(u.args[0], v): return TanQ(u) or CotQ(u) or EvenQuotientQ(u.args[0], v) elif PowerQ(u): if EvenQ(u.exp) and TrigQ(u.base) and IntegerQuotientQ(u.base.args[0], v): return True elif EvenQ(u.exp) and SumQ(u.base): return FunctionOfTanQ(Expand(u.base**2, v, x)) if ProductQ(u): lst = [] for i in u.args: if Not(FunctionOfTanQ(i, v, x)): lst.append(i) if lst == []: return True return Length(lst)==2 and OddTrigPowerQ(lst[0], v, x) and OddTrigPowerQ(lst[1], v, x) return all(FunctionOfTanQ(i, v, x) for i in u.args) def FunctionOfTanWeight(u, v, x): # (* u is a function of the form f[Tan[v],Cot[v]] where f is independent of x. # FunctionOfTanWeight[u,v,x] returns a nonnegative number if u is best considered a function # of Tan[v]; else it returns a negative number. *) if AtomQ(u): return S(0) elif CalculusQ(u): return S(0) elif TrigQ(u) and IntegerQuotientQ(u.args[0], v): if TanQ(u) and ZeroQ(u.args[0] - v): return S(1) elif CotQ(u) and ZeroQ(u.args[0] - v): return S(-1) return S(0) elif PowerQ(u): if EvenQ(u.exp) and TrigQ(u.base) and IntegerQuotientQ(u.base.args[0], v): if TanQ(u.base) or CosQ(u.base) or SecQ(u.base): return S(1) return S(-1) if ProductQ(u): if all(FunctionOfTanQ(i, v, x) for i in u.args): return Add(*[FunctionOfTanWeight(i, v, x) for i in u.args]) return S(0) return Add(*[FunctionOfTanWeight(i, v, x) for i in u.args]) def FunctionOfTrigQ(u, v, x): # If u (x) is equivalent to a function of the form f (Sin[v],Cos[v],Tan[v],Cot[v],Sec[v],Csc[v]) where f is independent of x, FunctionOfTrigQ[u,v,x] returns True; else it returns False. if AtomQ(u): return u != x elif CalculusQ(u): return False elif TrigQ(u) and IntegerQuotientQ(u.args[0], v): return True return all(FunctionOfTrigQ(i, v, x) for i in u.args) def FunctionOfDensePolynomialsQ(u, x): # If all occurrences of x in u (x) are in dense polynomials, FunctionOfDensePolynomialsQ[u,x] returns True; else it returns False. if FreeQ(u, x): return True if PolynomialQ(u, x): return Length(ExponentList(u, x)) > 1 return all(FunctionOfDensePolynomialsQ(i, x) for i in u.args) def FunctionOfLog(u, *args): # If u (x) is equivalent to an expression of the form f (Log[a*x^n]), FunctionOfLog[u,x] returns # the list {f (x),a*x^n,n}; else it returns False. if len(args) == 1: x = args[0] lst = FunctionOfLog(u, False, False, x) if AtomQ(lst) or FalseQ(lst[1]) or not isinstance(x, Symbol): return False else: return lst else: v = args[0] n = args[1] x = args[2] if AtomQ(u): if u==x: return False else: return [u, v, n] if CalculusQ(u): return False lst = BinomialParts(u.args[0], x) if LogQ(u) and ListQ(lst) and ZeroQ(lst[0]): if FalseQ(v) or u.args[0] == v: return [x, u.args[0], lst[2]] else: return False lst = [0, v, n] l = [] for i in u.args: lst = FunctionOfLog(i, lst[1], lst[2], x) if AtomQ(lst): return False else: l.append(lst[0]) return [u.func(*l), lst[1], lst[2]] def PowerVariableExpn(u, m, x): # If m is an integer, u is an expression of the form f((c*x)**n) and g=GCD(m,n)>1, # PowerVariableExpn(u,m,x) returns the list {x**(m/g)*f((c*x)**(n/g)),g,c}; else it returns False. if IntegerQ(m): lst = PowerVariableDegree(u, m, 1, x) if not lst: return False else: return [x**(m/lst[0])*PowerVariableSubst(u, lst[0], x), lst[0], lst[1]] else: return False def PowerVariableDegree(u, m, c, x): if FreeQ(u, x): return [m, c] if AtomQ(u) or CalculusQ(u): return False if PowerQ(u): if FreeQ(u.base/x, x): if ZeroQ(m) or m == u.exp and c == u.base/x: return [u.exp, u.base/x] if IntegerQ(u.exp) and IntegerQ(m) and GCD(m, u.exp)>1 and c==u.base/x: return [GCD(m, u.exp), c] else: return False lst = [m, c] for i in u.args: if PowerVariableDegree(i, lst[0], lst[1], x) == False: return False lst1 = PowerVariableDegree(i, lst[0], lst[1], x) if not lst1: return False else: return lst1 def PowerVariableSubst(u, m, x): if FreeQ(u, x) or AtomQ(u) or CalculusQ(u): return u if PowerQ(u): if FreeQ(u.base/x, x): return x**(u.exp/m) if ProductQ(u): l = 1 for i in u.args: l *= (PowerVariableSubst(i, m, x)) return l if SumQ(u): l = 0 for i in u.args: l += (PowerVariableSubst(i, m, x)) return l return u def EulerIntegrandQ(expr, x): a = Wild('a', exclude=[x]) b = Wild('b', exclude=[x]) n = Wild('n', exclude=[x, 0]) m = Wild('m', exclude=[x, 0]) p = Wild('p', exclude=[x, 0]) u = Wild('u') v = Wild('v') # Pattern 1 M = expr.match((a*x + b*u**n)**p) if M: if len(M) == 5 and FreeQ([M[a], M[b]], x) and IntegerQ(M[n] + 1/2) and QuadraticQ(M[u], x) and Not(RationalQ(M[p])) or NegativeIntegerQ(M[p]) and Not(BinomialQ(M[u], x)): return True # Pattern 2 M = expr.match(v**m*(a*x + b*u**n)**p) if M: if len(M) == 6 and FreeQ([M[a], M[b]], x) and ZeroQ(M[u] - M[v]) and IntegersQ(2*M[m], M[n] + 1/2) and QuadraticQ(M[u], x) and Not(RationalQ(M[p])) or NegativeIntegerQ(M[p]) and Not(BinomialQ(M[u], x)): return True # Pattern 3 M = expr.match(u**n*v**p) if M: if len(M) == 3 and NegativeIntegerQ(M[p]) and IntegerQ(M[n] + 1/2) and QuadraticQ(M[u], x) and QuadraticQ(M[v], x) and Not(BinomialQ(M[v], x)): return True else: return False def FunctionOfSquareRootOfQuadratic(u, *args): if len(args) == 1: x = args[0] pattern = Pattern(UtilityOperator(x_**WC('m', 1)*(a_ + x**WC('n', 1)*WC('b', 1))**p_, x), CustomConstraint(lambda a, b, m, n, p, x: FreeQ([a, b, m, n, p], x))) M = is_match(UtilityOperator(u, args[0]), pattern) if M: return False tmp = FunctionOfSquareRootOfQuadratic(u, False, x) if AtomQ(tmp) or FalseQ(tmp[0]): return False tmp = tmp[0] a = Coefficient(tmp, x, 0) b = Coefficient(tmp, x, 1) c = Coefficient(tmp, x, 2) if ZeroQ(a) and ZeroQ(b) or ZeroQ(b**2-4*a*c): return False if PosQ(c): sqrt = Rt(c, S(2)); q = a*sqrt + b*x + sqrt*x**2 r = b + 2*sqrt*x return [Simplify(SquareRootOfQuadraticSubst(u, q/r, (-a+x**2)/r, x)*q/r**2), Simplify(sqrt*x + Sqrt(tmp)), 2] if PosQ(a): sqrt = Rt(a, S(2)) q = c*sqrt - b*x + sqrt*x**2 r = c - x**2 return [Simplify(SquareRootOfQuadraticSubst(u, q/r, (-b+2*sqrt*x)/r, x)*q/r**2), Simplify((-sqrt+Sqrt(tmp))/x), 1] sqrt = Rt(b**2 - 4*a*c, S(2)) r = c - x**2 return[Simplify(-sqrt*SquareRootOfQuadraticSubst(u, -sqrt*x/r, -(b*c+c*sqrt+(-b+sqrt)*x**2)/(2*c*r), x)*x/r**2), FullSimplify(2*c*Sqrt(tmp)/(b-sqrt+2*c*x)), 3] else: v = args[0] x = args[1] if AtomQ(u) or FreeQ(u, x): return [v] if PowerQ(u): if FreeQ(u.exp, x): if FractionQ(u.exp) and Denominator(u.exp) == 2 and PolynomialQ(u.base, x) and Exponent(u.base, x) == 2: if FalseQ(v) or u.base == v: return [u.base] else: return False return FunctionOfSquareRootOfQuadratic(u.base, v, x) if ProductQ(u) or SumQ(u): lst = [v] lst1 = [] for i in u.args: if FunctionOfSquareRootOfQuadratic(i, lst[0], x) == False: return False lst1 = FunctionOfSquareRootOfQuadratic(i, lst[0], x) return lst1 else: return False def SquareRootOfQuadraticSubst(u, vv, xx, x): # SquareRootOfQuadraticSubst(u, vv, xx, x) returns u with fractional powers replaced by vv raised to the power and x replaced by xx. if AtomQ(u) or FreeQ(u, x): if u==x: return xx return u if PowerQ(u): if FreeQ(u.exp, x): if FractionQ(u.exp) and Denominator(u.exp)==2 and PolynomialQ(u.base, x) and Exponent(u.base, x)==2: return vv**Numerator(u.exp) return SquareRootOfQuadraticSubst(u.base, vv, xx, x)**u.exp elif SumQ(u): t = 0 for i in u.args: t += SquareRootOfQuadraticSubst(i, vv, xx, x) return t elif ProductQ(u): t = 1 for i in u.args: t *= SquareRootOfQuadraticSubst(i, vv, xx, x) return t def Divides(y, u, x): # If u divided by y is free of x, Divides[y,u,x] returns the quotient; else it returns False. v = Simplify(u/y) if FreeQ(v, x): return v else: return False def DerivativeDivides(y, u, x): """ If y not equal to x, y is easy to differentiate wrt x, and u divided by the derivative of y is free of x, DerivativeDivides[y,u,x] returns the quotient; else it returns False. """ from matchpy import is_match pattern0 = Pattern(Mul(a , b_), CustomConstraint(lambda a, b : FreeQ(a, b))) def f1(y, u, x): if PolynomialQ(y, x): return PolynomialQ(u, x) and Exponent(u, x) == Exponent(y, x) - 1 else: return EasyDQ(y, x) if is_match(y, pattern0): return False elif f1(y, u, x): v = D(y ,x) if EqQ(v, 0): return False else: v = Simplify(u/v) if FreeQ(v, x): return v else: return False else: return False def EasyDQ(expr, x): # If u is easy to differentiate wrt x, EasyDQ(u, x) returns True; else it returns False *) u = Wild('u',exclude=[1]) m = Wild('m',exclude=[x, 0]) M = expr.match(u*x**m) if M: return EasyDQ(M[u], x) if AtomQ(expr) or FreeQ(expr, x) or Length(expr)==0: return True elif CalculusQ(expr): return False elif Length(expr)==1: return EasyDQ(expr.args[0], x) elif BinomialQ(expr, x) or ProductOfLinearPowersQ(expr, x): return True elif RationalFunctionQ(expr, x) and RationalFunctionExponents(expr, x)==[1, 1]: return True elif ProductQ(expr): if FreeQ(First(expr), x): return EasyDQ(Rest(expr), x) elif FreeQ(Rest(expr), x): return EasyDQ(First(expr), x) else: return False elif SumQ(expr): return EasyDQ(First(expr), x) and EasyDQ(Rest(expr), x) elif Length(expr)==2: if FreeQ(expr.args[0], x): EasyDQ(expr.args[1], x) elif FreeQ(expr.args[1], x): return EasyDQ(expr.args[0], x) else: return False return False def ProductOfLinearPowersQ(u, x): # ProductOfLinearPowersQ(u, x) returns True iff u is a product of factors of the form v^n where v is linear in x v = Wild('v') n = Wild('n', exclude=[x]) M = u.match(v**n) return FreeQ(u, x) or M and LinearQ(M[v], x) or ProductQ(u) and ProductOfLinearPowersQ(First(u), x) and ProductOfLinearPowersQ(Rest(u), x) def Rt(u, n): return RtAux(TogetherSimplify(u), n) def NthRoot(u, n): return nsimplify(u**(S(1)/n)) def AtomBaseQ(u): # If u is an atom or an atom raised to an odd degree, AtomBaseQ(u) returns True; else it returns False return AtomQ(u) or PowerQ(u) and OddQ(u.args[1]) and AtomBaseQ(u.args[0]) def SumBaseQ(u): # If u is a sum or a sum raised to an odd degree, SumBaseQ(u) returns True; else it returns False return SumQ(u) or PowerQ(u) and OddQ(u.args[1]) and SumBaseQ(u.args[0]) def NegSumBaseQ(u): # If u is a sum or a sum raised to an odd degree whose lead term has a negative form, NegSumBaseQ(u) returns True; else it returns False return SumQ(u) and NegQ(First(u)) or PowerQ(u) and OddQ(u.args[1]) and NegSumBaseQ(u.args[0]) def AllNegTermQ(u): # If all terms of u have a negative form, AllNegTermQ(u) returns True; else it returns False if PowerQ(u): if OddQ(u.exp): return AllNegTermQ(u.base) if SumQ(u): return NegQ(First(u)) and AllNegTermQ(Rest(u)) return NegQ(u) def SomeNegTermQ(u): # If some term of u has a negative form, SomeNegTermQ(u) returns True; else it returns False if PowerQ(u): if OddQ(u.exp): return SomeNegTermQ(u.base) if SumQ(u): return NegQ(First(u)) or SomeNegTermQ(Rest(u)) return NegQ(u) def TrigSquareQ(u): # If u is an expression of the form Sin(z)^2 or Cos(z)^2, TrigSquareQ(u) returns True, else it returns False return PowerQ(u) and EqQ(u.args[1], 2) and MemberQ([sin, cos], Head(u.args[0])) def RtAux(u, n): if PowerQ(u): return u.base**(u.exp/n) if ComplexNumberQ(u): a = Re(u) b = Im(u) if Not(IntegerQ(a) and IntegerQ(b)) and IntegerQ(a/(a**2 + b**2)) and IntegerQ(b/(a**2 + b**2)): # Basis: a+b*I==1/(a/(a^2+b^2)-b/(a^2+b^2)*I) return S(1)/RtAux(a/(a**2 + b**2) - b/(a**2 + b**2)*I, n) else: return NthRoot(u, n) if ProductQ(u): lst = SplitProduct(PositiveQ, u) if ListQ(lst): return RtAux(lst[0], n)*RtAux(lst[1], n) lst = SplitProduct(NegativeQ, u) if ListQ(lst): if EqQ(lst[0], -1): v = lst[1] if PowerQ(v): if NegativeQ(v.exp): return 1/RtAux(-v.base**(-v.exp), n) if ProductQ(v): if ListQ(SplitProduct(SumBaseQ, v)): lst = SplitProduct(AllNegTermQ, v) if ListQ(lst): return RtAux(-lst[0], n)*RtAux(lst[1], n) lst = SplitProduct(NegSumBaseQ, v) if ListQ(lst): return RtAux(-lst[0], n)*RtAux(lst[1], n) lst = SplitProduct(SomeNegTermQ, v) if ListQ(lst): return RtAux(-lst[0], n)*RtAux(lst[1], n) lst = SplitProduct(SumBaseQ, v) return RtAux(-lst[0], n)*RtAux(lst[1], n) lst = SplitProduct(AtomBaseQ, v) if ListQ(lst): return RtAux(-lst[0], n)*RtAux(lst[1], n) else: return RtAux(-First(v), n)*RtAux(Rest(v), n) if OddQ(n): return -RtAux(v, n) else: return NthRoot(u, n) else: return RtAux(-lst[0], n)*RtAux(-lst[1], n) lst = SplitProduct(AllNegTermQ, u) if ListQ(lst) and ListQ(SplitProduct(SumBaseQ, lst[1])): return RtAux(-lst[0], n)*RtAux(-lst[1], n) lst = SplitProduct(NegSumBaseQ, u) if ListQ(lst) and ListQ(SplitProduct(NegSumBaseQ, lst[1])): return RtAux(-lst[0], n)*RtAux(-lst[1], n) return u.func(*[RtAux(i, n) for i in u.args]) v = TrigSquare(u) if Not(AtomQ(v)): return RtAux(v, n) if OddQ(n) and NegativeQ(u): return -RtAux(-u, n) if OddQ(n) and NegQ(u) and PosQ(-u): return -RtAux(-u, n) else: return NthRoot(u, n) def TrigSquare(u): # If u is an expression of the form a-a*Sin(z)^2 or a-a*Cos(z)^2, TrigSquare(u) returns Cos(z)^2 or Sin(z)^2 respectively, # else it returns False. if SumQ(u): for i in u.args: v = SplitProduct(TrigSquareQ, i) if v == False or SplitSum(v, u) == False: return False lst = SplitSum(SplitProduct(TrigSquareQ, i)) if lst and ZeroQ(lst[1][2] + lst[1]): if Head(lst[0][0].args[0]) == sin: return lst[1]*cos(lst[1][1][1][1])**2 return lst[1]*sin(lst[1][1][1][1])**2 else: return False else: return False def IntSum(u, x): # If u is free of x or of the form c*(a+b*x)^m, IntSum[u,x] returns the antiderivative of u wrt x; # else it returns d*Int[v,x] where d*v=u and d is free of x. return Add(*[Integral(i, x) for i in u.args]) def IntTerm(expr, x): # If u is of the form c*(a+b*x)**m, IntTerm(u,x) returns the antiderivative of u wrt x; # else it returns d*Int(v,x) where d*v=u and d is free of x. c = Wild('c', exclude=[x]) m = Wild('m', exclude=[x, 0]) v = Wild('v') M = expr.match(c/v) if M and len(M) == 2 and FreeQ(M[c], x) and LinearQ(M[v], x): return Simp(M[c]*Log(RemoveContent(M[v], x))/Coefficient(M[v], x, 1), x) M = expr.match(c*v**m) if M and len(M) == 3 and NonzeroQ(M[m] + 1) and LinearQ(M[v], x): return Simp(M[c]*M[v]**(M[m] + 1)/(Coefficient(M[v], x, 1)*(M[m] + 1)), x) if SumQ(expr): t = 0 for i in expr.args: t += IntTerm(i, x) return t else: u = expr return Dist(FreeFactors(u,x), Integral(NonfreeFactors(u, x), x), x) def Map2(f, lst1, lst2): result = [] for i in range(0, len(lst1)): result.append(f(lst1[i], lst2[i])) return result def ConstantFactor(u, x): # (* ConstantFactor[u,x] returns a 2-element list of the factors of u[x] free of x and the # factors not free of u[x]. Common constant factors of the terms of sums are also collected. *) if FreeQ(u, x): return [u, S(1)] elif AtomQ(u): return [S(1), u] elif PowerQ(u): if FreeQ(u.exp, x): lst = ConstantFactor(u.base, x) if IntegerQ(u.exp): return [lst[0]**u.exp, lst[1]**u.exp] tmp = PositiveFactors(lst[0]) if tmp == 1: return [S(1), u] return [tmp**u.exp, (NonpositiveFactors(lst[0])*lst[1])**u.exp] elif ProductQ(u): lst = [ConstantFactor(i, x) for i in u.args] return [Mul(*[First(i) for i in lst]), Mul(*[i[1] for i in lst])] elif SumQ(u): lst1 = [ConstantFactor(i, x) for i in u.args] if SameQ(*[i[1] for i in lst1]): return [Add(*[i[0] for i in lst]), lst1[0][1]] lst2 = CommonFactors([First(i) for i in lst1]) return [First(lst2), Add(*Map2(Mul, Rest(lst2), [i[1] for i in lst1]))] return [S(1), u] def SameQ(*args): for i in range(0, len(args) - 1): if args[i] != args[i+1]: return False return True def ReplacePart(lst, a, b): lst[b] = a return lst def CommonFactors(lst): # (* If lst is a list of n terms, CommonFactors[lst] returns a n+1-element list whose first # element is the product of the factors common to all terms of lst, and whose remaining # elements are quotients of each term divided by the common factor. *) lst1 = [NonabsurdNumberFactors(i) for i in lst] lst2 = [AbsurdNumberFactors(i) for i in lst] num = AbsurdNumberGCD(*lst2) common = num lst2 = [i/num for i in lst2] while (True): lst3 = [LeadFactor(i) for i in lst1] if SameQ(*lst3): common = common*lst3[0] lst1 = [RemainingFactors(i) for i in lst1] elif (all((LogQ(i) and IntegerQ(First(i)) and First(i) > 0) for i in lst3) and all(RationalQ(i) for i in [FullSimplify(j/First(lst3)) for j in lst3])): lst4 = [FullSimplify(j/First(lst3)) for j in lst3] num = GCD(*lst4) common = common*Log((First(lst3)[0])**num) lst2 = [lst2[i]*lst4[i]/num for i in range(0, len(lst2))] lst1 = [RemainingFactors(i) for i in lst1] lst4 = [LeadDegree(i) for i in lst1] if SameQ(*[LeadBase(i) for i in lst1]) and RationalQ(*lst4): num = Smallest(lst4) base = LeadBase(lst1[0]) if num != 0: common = common*base**num lst2 = [lst2[i]*base**(lst4[i] - num) for i in range(0, len(lst2))] lst1 = [RemainingFactors(i) for i in lst1] elif (Length(lst1) == 2 and ZeroQ(LeadBase(lst1[0]) + LeadBase(lst1[1])) and NonzeroQ(lst1[0] - 1) and IntegerQ(lst4[0]) and FractionQ(lst4[1])): num = Min(lst4) base = LeadBase(lst1[1]) if num != 0: common = common*base**num lst2 = [lst2[0]*(-1)**lst4[0], lst2[1]] lst2 = [lst2[i]*base**(lst4[i] - num) for i in range(0, len(lst2))] lst1 = [RemainingFactors(i) for i in lst1] elif (Length(lst1) == 2 and ZeroQ(lst1[0] + LeadBase(lst1[1])) and NonzeroQ(lst1[1] - 1) and IntegerQ(lst1[1]) and FractionQ(lst4[0])): num = Min(lst4) base = LeadBase(lst1[0]) if num != 0: common = common*base**num lst2 = [lst2[0], lst2[1]*(-1)**lst4[1]] lst2 = [lst2[i]*base**(lst4[i] - num) for i in range(0, len(lst2))] lst1 = [RemainingFactors(i) for i in lst1] else: num = MostMainFactorPosition(lst3) lst2 = ReplacePart(lst2, lst3[num]*lst2[num], num) lst1 = ReplacePart(lst1, RemainingFactors(lst1[num]), num) if all(i==1 for i in lst1): return Prepend(lst2, common) def MostMainFactorPosition(lst): factor = S(1) num = 0 for i in range(0, Length(lst)): if FactorOrder(lst[i], factor) > 0: factor = lst[i] num = i return num SbaseS, SexponS = None, None SexponFlagS = False def FunctionOfExponentialQ(u, x): # (* FunctionOfExponentialQ[u,x] returns True iff u is a function of F^v where F is a constant and v is linear in x, *) # (* and such an exponential explicitly occurs in u (i.e. not just implicitly in hyperbolic functions). *) global SbaseS, SexponS, SexponFlagS SbaseS, SexponS = None, None SexponFlagS = False res = FunctionOfExponentialTest(u, x) return res and SexponFlagS def FunctionOfExponential(u, x): global SbaseS, SexponS, SexponFlagS # (* u is a function of F^v where v is linear in x. FunctionOfExponential[u,x] returns F^v. *) SbaseS, SexponS = None, None SexponFlagS = False FunctionOfExponentialTest(u, x) return SbaseS**SexponS def FunctionOfExponentialFunction(u, x): global SbaseS, SexponS, SexponFlagS # (* u is a function of F^v where v is linear in x. FunctionOfExponentialFunction[u,x] returns u with F^v replaced by x. *) SbaseS, SexponS = None, None SexponFlagS = False FunctionOfExponentialTest(u, x) return SimplifyIntegrand(FunctionOfExponentialFunctionAux(u, x), x) def FunctionOfExponentialFunctionAux(u, x): # (* u is a function of F^v where v is linear in x, and the fluid variables $base$=F and $expon$=v. *) # (* FunctionOfExponentialFunctionAux[u,x] returns u with F^v replaced by x. *) global SbaseS, SexponS, SexponFlagS if AtomQ(u): return u elif PowerQ(u): if FreeQ(u.base, x) and LinearQ(u.exp, x): if ZeroQ(Coefficient(SexponS, x, 0)): return u.base**Coefficient(u.exp, x, 0)*x**FullSimplify(Log(u.base)*Coefficient(u.exp, x, 1)/(Log(SbaseS)*Coefficient(SexponS, x, 1))) return x**FullSimplify(Log(u.base)*Coefficient(u.exp, x, 1)/(Log(SbaseS)*Coefficient(SexponS, x, 1))) elif HyperbolicQ(u) and LinearQ(u.args[0], x): tmp = x**FullSimplify(Coefficient(u.args[0], x, 1)/(Log(SbaseS)*Coefficient(SexponS, x, 1))) if SinhQ(u): return tmp/2 - 1/(2*tmp) elif CoshQ(u): return tmp/2 + 1/(2*tmp) elif TanhQ(u): return (tmp - 1/tmp)/(tmp + 1/tmp) elif CothQ(u): return (tmp + 1/tmp)/(tmp - 1/tmp) elif SechQ(u): return 2/(tmp + 1/tmp) return 2/(tmp - 1/tmp) if PowerQ(u): if FreeQ(u.base, x) and SumQ(u.exp): return FunctionOfExponentialFunctionAux(u.base**First(u.exp), x)*FunctionOfExponentialFunctionAux(u.base**Rest(u.exp), x) return u.func(*[FunctionOfExponentialFunctionAux(i, x) for i in u.args]) def FunctionOfExponentialTest(u, x): # (* FunctionOfExponentialTest[u,x] returns True iff u is a function of F^v where F is a constant and v is linear in x. *) # (* Before it is called, the fluid variables $base$ and $expon$ should be set to Null and $exponFlag$ to False. *) # (* If u is a function of F^v, $base$ and $expon$ are set to F and v, respectively. *) # (* If an explicit exponential occurs in u, $exponFlag$ is set to True. *) global SbaseS, SexponS, SexponFlagS if FreeQ(u, x): return True elif u == x or CalculusQ(u): return False elif PowerQ(u): if FreeQ(u.base, x) and LinearQ(u.exp, x): SexponFlagS = True return FunctionOfExponentialTestAux(u.base, u.exp, x) elif HyperbolicQ(u) and LinearQ(u.args[0], x): return FunctionOfExponentialTestAux(E, u.args[0], x) if PowerQ(u): if FreeQ(u.base, x) and SumQ(u.exp): return FunctionOfExponentialTest(u.base**First(u.exp), x) and FunctionOfExponentialTest(u.base**Rest(u.exp), x) return all(FunctionOfExponentialTest(i, x) for i in u.args) def FunctionOfExponentialTestAux(base, expon, x): global SbaseS, SexponS, SexponFlagS if SbaseS is None: SbaseS = base SexponS = expon return True tmp = FullSimplify(Log(base)*Coefficient(expon, x, 1)/(Log(SbaseS)*Coefficient(SexponS, x, 1))) if Not(RationalQ(tmp)): return False elif ZeroQ(Coefficient(SexponS, x, 0)) or NonzeroQ(tmp - FullSimplify(Log(base)*Coefficient(expon, x, 0)/(Log(SbaseS)*Coefficient(SexponS, x, 0)))): if PositiveIntegerQ(base, SbaseS) and base < SbaseS: SbaseS = base SexponS = expon tmp = 1/tmp SexponS = Coefficient(SexponS, x, 1)*x/Denominator(tmp) if tmp < 0 and NegQ(Coefficient(SexponS, x, 1)): SexponS = -SexponS return True SexponS = SexponS/Denominator(tmp) if tmp < 0 and NegQ(Coefficient(SexponS, x, 1)): SexponS = -SexponS return True def stdev(lst): """Calculates the standard deviation for a list of numbers.""" num_items = len(lst) mean = sum(lst) / num_items differences = [x - mean for x in lst] sq_differences = [d ** 2 for d in differences] ssd = sum(sq_differences) variance = ssd / num_items sd = sqrt(variance) return sd def rubi_test(expr, x, optimal_output, expand=False, _hyper_check=False, _diff=False, _numerical=False): #Returns True if (expr - optimal_output) is equal to 0 or a constant #expr: integrated expression #x: integration variable #expand=True equates `expr` with `optimal_output` in expanded form #_hyper_check=True evaluates numerically #_diff=True differentiates the expressions before equating #_numerical=True equates the expressions at random `x`. Normally used for large expressions. from sympy.simplify.simplify import nsimplify if not expr.has(csc, sec, cot, csch, sech, coth): optimal_output = process_trig(optimal_output) if expr == optimal_output: return True if simplify(expr) == simplify(optimal_output): return True if nsimplify(expr) == nsimplify(optimal_output): return True if expr.has(sym_exp): expr = powsimp(powdenest(expr), force=True) if simplify(expr) == simplify(powsimp(optimal_output, force=True)): return True res = expr - optimal_output if _numerical: args = res.free_symbols rand_val = [] try: for i in range(0, 5): # check at 5 random points rand_x = randint(1, 40) substitutions = {s: rand_x for s in args} rand_val.append(float(abs(res.subs(substitutions).n()))) if stdev(rand_val) < Pow(10, -3): return True except: pass # return False dres = res.diff(x) if _numerical: args = dres.free_symbols rand_val = [] try: for i in range(0, 5): # check at 5 random points rand_x = randint(1, 40) substitutions = {s: rand_x for s in args} rand_val.append(float(abs(dres.subs(substitutions).n()))) if stdev(rand_val) < Pow(10, -3): return True # return False except: pass # return False r = Simplify(nsimplify(res)) if r == 0 or (not r.has(x)): return True if _diff: if dres == 0: return True elif Simplify(dres) == 0: return True if expand: # expands the expression and equates e = res.expand() if Simplify(e) == 0 or (not e.has(x)): return True return False def If(cond, t, f): # returns t if condition is true else f if cond: return t return f def IntQuadraticQ(a, b, c, d, e, m, p, x): # (* IntQuadraticQ[a,b,c,d,e,m,p,x] returns True iff (d+e*x)^m*(a+b*x+c*x^2)^p is integrable wrt x in terms of non-Appell functions. *) return IntegerQ(p) or PositiveIntegerQ(m) or IntegersQ(2*m, 2*p) or IntegersQ(m, 4*p) or IntegersQ(m, p + S(1)/3) and (ZeroQ(c**2*d**2 - b*c*d*e + b**2*e**2 - 3*a*c*e**2) or ZeroQ(c**2*d**2 - b*c*d*e - 2*b**2*e**2 + 9*a*c*e**2)) def IntBinomialQ(*args): #(* IntBinomialQ(a,b,c,n,m,p,x) returns True iff (c*x)^m*(a+b*x^n)^p is integrable wrt x in terms of non-hypergeometric functions. *) if len(args) == 8: a, b, c, d, n, p, q, x = args return IntegersQ(p,q) or PositiveIntegerQ(p) or PositiveIntegerQ(q) or (ZeroQ(n-2) or ZeroQ(n-4)) and (IntegersQ(p,4*q) or IntegersQ(4*p,q)) or ZeroQ(n-2) and (IntegersQ(2*p,2*q) or IntegersQ(3*p,q) and ZeroQ(b*c+3*a*d) or IntegersQ(p,3*q) and ZeroQ(3*b*c+a*d)) elif len(args) == 7: a, b, c, n, m, p, x = args return IntegerQ(2*p) or IntegerQ((m+1)/n + p) or (ZeroQ(n - 2) or ZeroQ(n - 4)) and IntegersQ(2*m, 4*p) or ZeroQ(n - 2) and IntegerQ(6*p) and (IntegerQ(m) or IntegerQ(m - p)) elif len(args) == 10: a, b, c, d, e, m, n, p, q, x = args return IntegersQ(p,q) or PositiveIntegerQ(p) or PositiveIntegerQ(q) or ZeroQ(n-2) and IntegerQ(m) and IntegersQ(2*p,2*q) or ZeroQ(n-4) and (IntegersQ(m,p,2*q) or IntegersQ(m,2*p,q)) def RectifyTangent(*args): # (* RectifyTangent(u,a,b,r,x) returns an expression whose derivative equals the derivative of r*ArcTan(a+b*Tan(u)) wrt x. *) if len(args) == 5: u, a, b, r, x = args t1 = Together(a) t2 = Together(b) if (PureComplexNumberQ(t1) or (ProductQ(t1) and any(PureComplexNumberQ(i) for i in t1.args))) and (PureComplexNumberQ(t2) or ProductQ(t2) and any(PureComplexNumberQ(i) for i in t2.args)): c = a/I d = b/I if NegativeQ(d): return RectifyTangent(u, -a, -b, -r, x) e = SmartDenominator(Together(c + d*x)) c = c*e d = d*e if EvenQ(Denominator(NumericFactor(Together(u)))): return I*r*Log(RemoveContent(Simplify((c+e)**2+d**2)+Simplify((c+e)**2-d**2)*Cos(2*u)+Simplify(2*(c+e)*d)*Sin(2*u),x))/4 - I*r*Log(RemoveContent(Simplify((c-e)**2+d**2)+Simplify((c-e)**2-d**2)*Cos(2*u)+Simplify(2*(c-e)*d)*Sin(2*u),x))/4 return I*r*Log(RemoveContent(Simplify((c+e)**2)+Simplify(2*(c+e)*d)*Cos(u)*Sin(u)-Simplify((c+e)**2-d**2)*Sin(u)**2,x))/4 - I*r*Log(RemoveContent(Simplify((c-e)**2)+Simplify(2*(c-e)*d)*Cos(u)*Sin(u)-Simplify((c-e)**2-d**2)*Sin(u)**2,x))/4 elif NegativeQ(b): return RectifyTangent(u, -a, -b, -r, x) elif EvenQ(Denominator(NumericFactor(Together(u)))): return r*SimplifyAntiderivative(u,x) + r*ArcTan(Simplify((2*a*b*Cos(2*u)-(1+a**2-b**2)*Sin(2*u))/(a**2+(1+b)**2+(1+a**2-b**2)*Cos(2*u)+2*a*b*Sin(2*u)))) return r*SimplifyAntiderivative(u,x) - r*ArcTan(ActivateTrig(Simplify((a*b-2*a*b*cos(u)**2+(1+a**2-b**2)*cos(u)*sin(u))/(b*(1+b)+(1+a**2-b**2)*cos(u)**2+2*a*b*cos(u)*sin(u))))) u, a, b, x = args t = Together(a) if PureComplexNumberQ(t) or (ProductQ(t) and any(PureComplexNumberQ(i) for i in t.args)): c = a/I if NegativeQ(c): return RectifyTangent(u, -a, -b, x) if ZeroQ(c - 1): if EvenQ(Denominator(NumericFactor(Together(u)))): return I*b*ArcTanh(Sin(2*u))/2 return I*b*ArcTanh(2*cos(u)*sin(u))/2 e = SmartDenominator(c) c = c*e return I*b*Log(RemoveContent(e*Cos(u)+c*Sin(u),x))/2 - I*b*Log(RemoveContent(e*Cos(u)-c*Sin(u),x))/2 elif NegativeQ(a): return RectifyTangent(u, -a, -b, x) elif ZeroQ(a - 1): return b*SimplifyAntiderivative(u, x) elif EvenQ(Denominator(NumericFactor(Together(u)))): c = Simplify((1 + a)/(1 - a)) numr = SmartNumerator(c) denr = SmartDenominator(c) return b*SimplifyAntiderivative(u,x) - b*ArcTan(NormalizeLeadTermSigns(denr*Sin(2*u)/(numr+denr*Cos(2*u)))), elif PositiveQ(a - 1): c = Simplify(1/(a - 1)) numr = SmartNumerator(c) denr = SmartDenominator(c) return b*SimplifyAntiderivative(u,x) + b*ArcTan(NormalizeLeadTermSigns(denr*Cos(u)*Sin(u)/(numr+denr*Sin(u)**2))), c = Simplify(a/(1 - a)) numr = SmartNumerator(c) denr = SmartDenominator(c) return b*SimplifyAntiderivative(u,x) - b*ArcTan(NormalizeLeadTermSigns(denr*Cos(u)*Sin(u)/(numr+denr*Cos(u)**2))) def RectifyCotangent(*args): #(* RectifyCotangent[u,a,b,r,x] returns an expression whose derivative equals the derivative of r*ArcTan[a+b*Cot[u]] wrt x. *) if len(args) == 5: u, a, b, r, x = args t1 = Together(a) t2 = Together(b) if (PureComplexNumberQ(t1) or (ProductQ(t1) and any(PureComplexNumberQ(i) for i in t1.args))) and (PureComplexNumberQ(t2) or ProductQ(t2) and any(PureComplexNumberQ(i) for i in t2.args)): c = a/I d = b/I if NegativeQ(d): return RectifyTangent(u,-a,-b,-r,x) e = SmartDenominator(Together(c + d*x)) c = c*e d = d*e if EvenQ(Denominator(NumericFactor(Together(u)))): return I*r*Log(RemoveContent(Simplify((c+e)**2+d**2)-Simplify((c+e)**2-d**2)*Cos(2*u)+Simplify(2*(c+e)*d)*Sin(2*u),x))/4 - I*r*Log(RemoveContent(Simplify((c-e)**2+d**2)-Simplify((c-e)**2-d**2)*Cos(2*u)+Simplify(2*(c-e)*d)*Sin(2*u),x))/4 return I*r*Log(RemoveContent(Simplify((c+e)**2)-Simplify((c+e)**2-d**2)*Cos(u)**2+Simplify(2*(c+e)*d)*Cos(u)*Sin(u),x))/4 - I*r*Log(RemoveContent(Simplify((c-e)**2)-Simplify((c-e)**2-d**2)*Cos(u)**2+Simplify(2*(c-e)*d)*Cos(u)*Sin(u),x))/4 elif NegativeQ(b): return RectifyCotangent(u,-a,-b,-r,x) elif EvenQ(Denominator(NumericFactor(Together(u)))): return -r*SimplifyAntiderivative(u,x) - r*ArcTan(Simplify((2*a*b*Cos(2*u)+(1+a**2-b**2)*Sin(2*u))/(a**2+(1+b)**2-(1+a**2-b**2)*Cos(2*u)+2*a*b*Sin(2*u)))) return -r*SimplifyAntiderivative(u,x) - r*ArcTan(ActivateTrig(Simplify((a*b-2*a*b*sin(u)**2+(1+a**2-b**2)*cos(u)*sin(u))/(b*(1+b)+(1+a**2-b**2)*sin(u)**2+2*a*b*cos(u)*sin(u))))) u, a, b, x = args t = Together(a) if PureComplexNumberQ(t) or (ProductQ(t) and any(PureComplexNumberQ(i) for i in t.args)): c = a/I if NegativeQ(c): return RectifyCotangent(u,-a,-b,x) elif ZeroQ(c - 1): if EvenQ(Denominator(NumericFactor(Together(u)))): return -I*b*ArcTanh(Sin(2*u))/2 return -I*b*ArcTanh(2*Cos(u)*Sin(u))/2 e = SmartDenominator(c) c = c*e return -I*b*Log(RemoveContent(c*Cos(u)+e*Sin(u),x))/2 + I*b*Log(RemoveContent(c*Cos(u)-e*Sin(u),x))/2 elif NegativeQ(a): return RectifyCotangent(u,-a,-b,x) elif ZeroQ(a-1): return b*SimplifyAntiderivative(u,x) elif EvenQ(Denominator(NumericFactor(Together(u)))): c = Simplify(a - 1) numr = SmartNumerator(c) denr = SmartDenominator(c) return b*SimplifyAntiderivative(u,x) - b*ArcTan(NormalizeLeadTermSigns(denr*Cos(u)*Sin(u)/(numr+denr*Cos(u)**2))) c = Simplify(a/(1-a)) numr = SmartNumerator(c) denr = SmartDenominator(c) return b*SimplifyAntiderivative(u,x) + b*ArcTan(NormalizeLeadTermSigns(denr*Cos(u)*Sin(u)/(numr+denr*Sin(u)**2))) def Inequality(*args): f = args[1::2] e = args[0::2] r = [] for i in range(0, len(f)): r.append(f[i](e[i], e[i + 1])) return all(r) def Condition(r, c): # returns r if c is True if c: return r else: raise NotImplementedError('In Condition()') def Simp(u, x): u = replace_pow_exp(u) return NormalizeSumFactors(SimpHelp(u, x)) def SimpHelp(u, x): if AtomQ(u): return u elif FreeQ(u, x): v = SmartSimplify(u) if LeafCount(v) <= LeafCount(u): return v return u elif ProductQ(u): #m = MatchQ[Rest[u],a_.+n_*Pi+b_.*v_ /; FreeQ[{a,b},x] && Not[FreeQ[v,x]] && EqQ[n^2,1/4]] #if EqQ(First(u), S(1)/2) and m: # if #If[EqQ[First[u],1/2] && MatchQ[Rest[u],a_.+n_*Pi+b_.*v_ /; FreeQ[{a,b},x] && Not[FreeQ[v,x]] && EqQ[n^2,1/4]], # If[MatchQ[Rest[u],n_*Pi+b_.*v_ /; FreeQ[b,x] && Not[FreeQ[v,x]] && EqQ[n^2,1/4]], # Map[Function[1/2*#],Rest[u]], # If[MatchQ[Rest[u],m_*a_.+n_*Pi+p_*b_.*v_ /; FreeQ[{a,b},x] && Not[FreeQ[v,x]] && IntegersQ[m/2,p/2]], # Map[Function[1/2*#],Rest[u]], # u]], v = FreeFactors(u, x) w = NonfreeFactors(u, x) v = NumericFactor(v)*SmartSimplify(NonnumericFactors(v)*x**2)/x**2 if ProductQ(w): w = Mul(*[SimpHelp(i,x) for i in w.args]) else: w = SimpHelp(w, x) w = FactorNumericGcd(w) v = MergeFactors(v, w) if ProductQ(v): return Mul(*[SimpFixFactor(i, x) for i in v.args]) return v elif SumQ(u): Pi = pi a_ = Wild('a', exclude=[x]) b_ = Wild('b', exclude=[x, 0]) n_ = Wild('n', exclude=[x, 0, 0]) pattern = a_ + n_*Pi + b_*x match = u.match(pattern) m = False if match: if EqQ(match[n_]**3, S(1)/16): m = True if m: return u elif PolynomialQ(u, x) and Exponent(u, x) <= 0: return SimpHelp(Coefficient(u, x, 0), x) elif PolynomialQ(u, x) and Exponent(u, x) == 1 and Coefficient(u, x, 0) == 0: return SimpHelp(Coefficient(u, x, 1), x)*x v = 0 w = 0 for i in u.args: if FreeQ(i, x): v = i + v else: w = i + w v = SmartSimplify(v) if SumQ(w): w = Add(*[SimpHelp(i, x) for i in w.args]) else: w = SimpHelp(w, x) return v + w return u.func(*[SimpHelp(i, x) for i in u.args]) def SplitProduct(func, u): #(* If func[v] is True for a factor v of u, SplitProduct[func,u] returns {v, u/v} where v is the first such factor; else it returns False. *) if ProductQ(u): if func(First(u)): return [First(u), Rest(u)] lst = SplitProduct(func, Rest(u)) if AtomQ(lst): return False return [lst[0], First(u)*lst[1]] if func(u): return [u, 1] return False def SplitSum(func, u): # (* If func[v] is nonatomic for a term v of u, SplitSum[func,u] returns {func[v], u-v} where v is the first such term; else it returns False. *) if SumQ(u): if Not(AtomQ(func(First(u)))): return [func(First(u)), Rest(u)] lst = SplitSum(func, Rest(u)) if AtomQ(lst): return False return [lst[0], First(u) + lst[1]] elif Not(AtomQ(func(u))): return [func(u), 0] return False def SubstFor(*args): if len(args) == 4: w, v, u, x = args # u is a function of v. SubstFor(w,v,u,x) returns w times u with v replaced by x. return SimplifyIntegrand(w*SubstFor(v, u, x), x) v, u, x = args # u is a function of v. SubstFor(v, u, x) returns u with v replaced by x. if AtomQ(v): return Subst(u, v, x) elif Not(EqQ(FreeFactors(v, x), 1)): return SubstFor(NonfreeFactors(v, x), u, x/FreeFactors(v, x)) elif SinQ(v): return SubstForTrig(u, x, Sqrt(1 - x**2), v.args[0], x) elif CosQ(v): return SubstForTrig(u, Sqrt(1 - x**2), x, v.args[0], x) elif TanQ(v): return SubstForTrig(u, x/Sqrt(1 + x**2), 1/Sqrt(1 + x**2), v.args[0], x) elif CotQ(v): return SubstForTrig(u, 1/Sqrt(1 + x**2), x/Sqrt(1 + x**2), v.args[0], x) elif SecQ(v): return SubstForTrig(u, 1/Sqrt(1 - x**2), 1/x, v.args[0], x) elif CscQ(v): return SubstForTrig(u, 1/x, 1/Sqrt(1 - x**2), v.args[0], x) elif SinhQ(v): return SubstForHyperbolic(u, x, Sqrt(1 + x**2), v.args[0], x) elif CoshQ(v): return SubstForHyperbolic(u, Sqrt( - 1 + x**2), x, v.args[0], x) elif TanhQ(v): return SubstForHyperbolic(u, x/Sqrt(1 - x**2), 1/Sqrt(1 - x**2), v.args[0], x) elif CothQ(v): return SubstForHyperbolic(u, 1/Sqrt( - 1 + x**2), x/Sqrt( - 1 + x**2), v.args[0], x) elif SechQ(v): return SubstForHyperbolic(u, 1/Sqrt( - 1 + x**2), 1/x, v.args[0], x) elif CschQ(v): return SubstForHyperbolic(u, 1/x, 1/Sqrt(1 + x**2), v.args[0], x) else: return SubstForAux(u, v, x) def SubstForAux(u, v, x): # u is a function of v. SubstForAux(u, v, x) returns u with v replaced by x. if u==v: return x elif AtomQ(u): if PowerQ(v): if FreeQ(v.exp, x) and ZeroQ(u - v.base): return x**Simplify(1/v.exp) return u elif PowerQ(u): if FreeQ(u.exp, x): if ZeroQ(u.base - v): return x**u.exp if PowerQ(v): if FreeQ(v.exp, x) and ZeroQ(u.base - v.base): return x**Simplify(u.exp/v.exp) return SubstForAux(u.base, v, x)**u.exp elif ProductQ(u) and Not(EqQ(FreeFactors(u, x), 1)): return FreeFactors(u, x)*SubstForAux(NonfreeFactors(u, x), v, x) elif ProductQ(u) and ProductQ(v): return SubstForAux(First(u), First(v), x) return u.func(*[SubstForAux(i, v, x) for i in u.args]) def FresnelS(x): return fresnels(x) def FresnelC(x): return fresnelc(x) def Erf(x): return erf(x) def Erfc(x): return erfc(x) def Erfi(x): return erfi(x) class Gamma(Function): @classmethod def eval(cls,*args): a = args[0] if len(args) == 1: return gamma(a) else: b = args[1] if (NumericQ(a) and NumericQ(b)) or a == 1: return uppergamma(a, b) def FunctionOfTrigOfLinearQ(u, x): # If u is an algebraic function of trig functions of a linear function of x, # FunctionOfTrigOfLinearQ[u,x] returns True; else it returns False. if FunctionOfTrig(u, None, x) and AlgebraicTrigFunctionQ(u, x) and FunctionOfLinear(FunctionOfTrig(u, None, x), x): return True else: return False def ElementaryFunctionQ(u): # ElementaryExpressionQ[u] returns True if u is a sum, product, or power and all the operands # are elementary expressions; or if u is a call on a trig, hyperbolic, or inverse function # and all the arguments are elementary expressions; else it returns False. if AtomQ(u): return True elif SumQ(u) or ProductQ(u) or PowerQ(u) or TrigQ(u) or HyperbolicQ(u) or InverseFunctionQ(u): for i in u.args: if not ElementaryFunctionQ(i): return False return True return False def Complex(a, b): return a + I*b def UnsameQ(a, b): return a != b @doctest_depends_on(modules=('matchpy',)) def _SimpFixFactor(): replacer = ManyToOneReplacer() pattern1 = Pattern(UtilityOperator(Pow(Add(Mul(Complex(S(0), c_), WC('a', S(1))), Mul(Complex(S(0), d_), WC('b', S(1)))), WC('p', S(1))), x_), CustomConstraint(lambda p: IntegerQ(p))) rule1 = ReplacementRule(pattern1, lambda b, c, x, a, p, d : Mul(Pow(I, p), SimpFixFactor(Pow(Add(Mul(a, c), Mul(b, d)), p), x))) replacer.add(rule1) pattern2 = Pattern(UtilityOperator(Pow(Add(Mul(Complex(S(0), d_), WC('a', S(1))), Mul(Complex(S(0), e_), WC('b', S(1))), Mul(Complex(S(0), f_), WC('c', S(1)))), WC('p', S(1))), x_), CustomConstraint(lambda p: IntegerQ(p))) rule2 = ReplacementRule(pattern2, lambda b, c, x, f, a, p, e, d : Mul(Pow(I, p), SimpFixFactor(Pow(Add(Mul(a, d), Mul(b, e), Mul(c, f)), p), x))) replacer.add(rule2) pattern3 = Pattern(UtilityOperator(Pow(Add(Mul(WC('a', S(1)), Pow(c_, r_)), Mul(WC('b', S(1)), Pow(x_, WC('n', S(1))))), WC('p', S(1))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda n, p: IntegersQ(n, p)), CustomConstraint(lambda c: AtomQ(c)), CustomConstraint(lambda r: RationalQ(r)), CustomConstraint(lambda r: Less(r, S(0)))) rule3 = ReplacementRule(pattern3, lambda b, c, r, n, x, a, p : Mul(Pow(c, Mul(r, p)), SimpFixFactor(Pow(Add(a, Mul(Mul(b, Pow(Pow(c, r), S(-1))), Pow(x, n))), p), x))) replacer.add(rule3) pattern4 = Pattern(UtilityOperator(Pow(Add(WC('a', S(0)), Mul(WC('b', S(1)), Pow(c_, r_), Pow(x_, WC('n', S(1))))), WC('p', S(1))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda n, p: IntegersQ(n, p)), CustomConstraint(lambda c: AtomQ(c)), CustomConstraint(lambda r: RationalQ(r)), CustomConstraint(lambda r: Less(r, S(0)))) rule4 = ReplacementRule(pattern4, lambda b, c, r, n, x, a, p : Mul(Pow(c, Mul(r, p)), SimpFixFactor(Pow(Add(Mul(a, Pow(Pow(c, r), S(-1))), Mul(b, Pow(x, n))), p), x))) replacer.add(rule4) pattern5 = Pattern(UtilityOperator(Pow(Add(Mul(WC('a', S(1)), Pow(c_, WC('s', S(1)))), Mul(WC('b', S(1)), Pow(c_, WC('r', S(1))), Pow(x_, WC('n', S(1))))), WC('p', S(1))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda n, p: IntegersQ(n, p)), CustomConstraint(lambda r, s: RationalQ(s, r)), CustomConstraint(lambda r, s: Inequality(S(0), Less, s, LessEqual, r)), CustomConstraint(lambda p, c, s: UnsameQ(Pow(c, Mul(s, p)), S(-1)))) rule5 = ReplacementRule(pattern5, lambda b, c, r, n, x, a, p, s : Mul(Pow(c, Mul(s, p)), SimpFixFactor(Pow(Add(a, Mul(b, Pow(c, Add(r, Mul(S(-1), s))), Pow(x, n))), p), x))) replacer.add(rule5) pattern6 = Pattern(UtilityOperator(Pow(Add(Mul(WC('a', S(1)), Pow(c_, WC('s', S(1)))), Mul(WC('b', S(1)), Pow(c_, WC('r', S(1))), Pow(x_, WC('n', S(1))))), WC('p', S(1))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda n, p: IntegersQ(n, p)), CustomConstraint(lambda r, s: RationalQ(s, r)), CustomConstraint(lambda s, r: Less(S(0), r, s)), CustomConstraint(lambda p, c, r: UnsameQ(Pow(c, Mul(r, p)), S(-1)))) rule6 = ReplacementRule(pattern6, lambda b, c, r, n, x, a, p, s : Mul(Pow(c, Mul(r, p)), SimpFixFactor(Pow(Add(Mul(a, Pow(c, Add(s, Mul(S(-1), r)))), Mul(b, Pow(x, n))), p), x))) replacer.add(rule6) return replacer @doctest_depends_on(modules=('matchpy',)) def SimpFixFactor(expr, x): r = SimpFixFactor_replacer.replace(UtilityOperator(expr, x)) if isinstance(r, UtilityOperator): return expr return r @doctest_depends_on(modules=('matchpy',)) def _FixSimplify(): Plus = Add def cons_f1(n): return OddQ(n) cons1 = CustomConstraint(cons_f1) def cons_f2(m): return RationalQ(m) cons2 = CustomConstraint(cons_f2) def cons_f3(n): return FractionQ(n) cons3 = CustomConstraint(cons_f3) def cons_f4(u): return SqrtNumberSumQ(u) cons4 = CustomConstraint(cons_f4) def cons_f5(v): return SqrtNumberSumQ(v) cons5 = CustomConstraint(cons_f5) def cons_f6(u): return PositiveQ(u) cons6 = CustomConstraint(cons_f6) def cons_f7(v): return PositiveQ(v) cons7 = CustomConstraint(cons_f7) def cons_f8(v): return SqrtNumberSumQ(S(1)/v) cons8 = CustomConstraint(cons_f8) def cons_f9(m): return IntegerQ(m) cons9 = CustomConstraint(cons_f9) def cons_f10(u): return NegativeQ(u) cons10 = CustomConstraint(cons_f10) def cons_f11(n, m, a, b): return RationalQ(a, b, m, n) cons11 = CustomConstraint(cons_f11) def cons_f12(a): return Greater(a, S(0)) cons12 = CustomConstraint(cons_f12) def cons_f13(b): return Greater(b, S(0)) cons13 = CustomConstraint(cons_f13) def cons_f14(p): return PositiveIntegerQ(p) cons14 = CustomConstraint(cons_f14) def cons_f15(p): return IntegerQ(p) cons15 = CustomConstraint(cons_f15) def cons_f16(p, n): return Greater(-n + p, S(0)) cons16 = CustomConstraint(cons_f16) def cons_f17(a, b): return SameQ(a + b, S(0)) cons17 = CustomConstraint(cons_f17) def cons_f18(n): return Not(IntegerQ(n)) cons18 = CustomConstraint(cons_f18) def cons_f19(c, a, b, d): return ZeroQ(-a*d + b*c) cons19 = CustomConstraint(cons_f19) def cons_f20(a): return Not(RationalQ(a)) cons20 = CustomConstraint(cons_f20) def cons_f21(t): return IntegerQ(t) cons21 = CustomConstraint(cons_f21) def cons_f22(n, m): return RationalQ(m, n) cons22 = CustomConstraint(cons_f22) def cons_f23(n, m): return Inequality(S(0), Less, m, LessEqual, n) cons23 = CustomConstraint(cons_f23) def cons_f24(p, n, m): return RationalQ(m, n, p) cons24 = CustomConstraint(cons_f24) def cons_f25(p, n, m): return Inequality(S(0), Less, m, LessEqual, n, LessEqual, p) cons25 = CustomConstraint(cons_f25) def cons_f26(p, n, m, q): return Inequality(S(0), Less, m, LessEqual, n, LessEqual, p, LessEqual, q) cons26 = CustomConstraint(cons_f26) def cons_f27(w): return Not(RationalQ(w)) cons27 = CustomConstraint(cons_f27) def cons_f28(n): return Less(n, S(0)) cons28 = CustomConstraint(cons_f28) def cons_f29(n, w, v): return ZeroQ(v + w**(-n)) cons29 = CustomConstraint(cons_f29) def cons_f30(n): return IntegerQ(n) cons30 = CustomConstraint(cons_f30) def cons_f31(w, v): return ZeroQ(v + w) cons31 = CustomConstraint(cons_f31) def cons_f32(p, n): return IntegerQ(n/p) cons32 = CustomConstraint(cons_f32) def cons_f33(w, v): return ZeroQ(v - w) cons33 = CustomConstraint(cons_f33) def cons_f34(p, n): return IntegersQ(n, n/p) cons34 = CustomConstraint(cons_f34) def cons_f35(a): return AtomQ(a) cons35 = CustomConstraint(cons_f35) def cons_f36(b): return AtomQ(b) cons36 = CustomConstraint(cons_f36) pattern1 = Pattern(UtilityOperator((w_ + Complex(S(0), b_)*WC('v', S(1)))**WC('n', S(1))*Complex(S(0), a_)*WC('u', S(1))), cons1) def replacement1(n, u, w, v, a, b): return (S(-1))**(n/S(2) + S(1)/2)*a*u*FixSimplify((b*v - w*Complex(S(0), S(1)))**n) rule1 = ReplacementRule(pattern1, replacement1) def With2(m, n, u, w, v): z = u**(m/GCD(m, n))*v**(n/GCD(m, n)) if Or(AbsurdNumberQ(z), SqrtNumberSumQ(z)): return True return False pattern2 = Pattern(UtilityOperator(u_**WC('m', S(1))*v_**n_*WC('w', S(1))), cons2, cons3, cons4, cons5, cons6, cons7, CustomConstraint(With2)) def replacement2(m, n, u, w, v): z = u**(m/GCD(m, n))*v**(n/GCD(m, n)) return FixSimplify(w*z**GCD(m, n)) rule2 = ReplacementRule(pattern2, replacement2) def With3(m, n, u, w, v): z = u**(m/GCD(m, -n))*v**(n/GCD(m, -n)) if Or(AbsurdNumberQ(z), SqrtNumberSumQ(z)): return True return False pattern3 = Pattern(UtilityOperator(u_**WC('m', S(1))*v_**n_*WC('w', S(1))), cons2, cons3, cons4, cons8, cons6, cons7, CustomConstraint(With3)) def replacement3(m, n, u, w, v): z = u**(m/GCD(m, -n))*v**(n/GCD(m, -n)) return FixSimplify(w*z**GCD(m, -n)) rule3 = ReplacementRule(pattern3, replacement3) def With4(m, n, u, w, v): z = v**(n/GCD(m, n))*(-u)**(m/GCD(m, n)) if Or(AbsurdNumberQ(z), SqrtNumberSumQ(z)): return True return False pattern4 = Pattern(UtilityOperator(u_**WC('m', S(1))*v_**n_*WC('w', S(1))), cons9, cons3, cons4, cons5, cons10, cons7, CustomConstraint(With4)) def replacement4(m, n, u, w, v): z = v**(n/GCD(m, n))*(-u)**(m/GCD(m, n)) return FixSimplify(-w*z**GCD(m, n)) rule4 = ReplacementRule(pattern4, replacement4) def With5(m, n, u, w, v): z = v**(n/GCD(m, -n))*(-u)**(m/GCD(m, -n)) if Or(AbsurdNumberQ(z), SqrtNumberSumQ(z)): return True return False pattern5 = Pattern(UtilityOperator(u_**WC('m', S(1))*v_**n_*WC('w', S(1))), cons9, cons3, cons4, cons8, cons10, cons7, CustomConstraint(With5)) def replacement5(m, n, u, w, v): z = v**(n/GCD(m, -n))*(-u)**(m/GCD(m, -n)) return FixSimplify(-w*z**GCD(m, -n)) rule5 = ReplacementRule(pattern5, replacement5) def With6(p, m, n, u, w, v, a, b): c = a**(m/p)*b**n if RationalQ(c): return True return False pattern6 = Pattern(UtilityOperator(a_**m_*(b_**n_*WC('v', S(1)) + u_)**WC('p', S(1))*WC('w', S(1))), cons11, cons12, cons13, cons14, CustomConstraint(With6)) def replacement6(p, m, n, u, w, v, a, b): c = a**(m/p)*b**n return FixSimplify(w*(a**(m/p)*u + c*v)**p) rule6 = ReplacementRule(pattern6, replacement6) pattern7 = Pattern(UtilityOperator(a_**WC('m', S(1))*(a_**n_*WC('u', S(1)) + b_**WC('p', S(1))*WC('v', S(1)))*WC('w', S(1))), cons2, cons3, cons15, cons16, cons17) def replacement7(p, m, n, u, w, v, a, b): return FixSimplify(a**(m + n)*w*((S(-1))**p*a**(-n + p)*v + u)) rule7 = ReplacementRule(pattern7, replacement7) def With8(m, d, n, w, c, a, b): q = b/d if FreeQ(q, Plus): return True return False pattern8 = Pattern(UtilityOperator((a_ + b_)**WC('m', S(1))*(c_ + d_)**n_*WC('w', S(1))), cons9, cons18, cons19, CustomConstraint(With8)) def replacement8(m, d, n, w, c, a, b): q = b/d return FixSimplify(q**m*w*(c + d)**(m + n)) rule8 = ReplacementRule(pattern8, replacement8) pattern9 = Pattern(UtilityOperator((a_**WC('m', S(1))*WC('u', S(1)) + a_**WC('n', S(1))*WC('v', S(1)))**WC('t', S(1))*WC('w', S(1))), cons20, cons21, cons22, cons23) def replacement9(m, n, u, w, v, a, t): return FixSimplify(a**(m*t)*w*(a**(-m + n)*v + u)**t) rule9 = ReplacementRule(pattern9, replacement9) pattern10 = Pattern(UtilityOperator((a_**WC('m', S(1))*WC('u', S(1)) + a_**WC('n', S(1))*WC('v', S(1)) + a_**WC('p', S(1))*WC('z', S(1)))**WC('t', S(1))*WC('w', S(1))), cons20, cons21, cons24, cons25) def replacement10(p, m, n, u, w, v, a, z, t): return FixSimplify(a**(m*t)*w*(a**(-m + n)*v + a**(-m + p)*z + u)**t) rule10 = ReplacementRule(pattern10, replacement10) pattern11 = Pattern(UtilityOperator((a_**WC('m', S(1))*WC('u', S(1)) + a_**WC('n', S(1))*WC('v', S(1)) + a_**WC('p', S(1))*WC('z', S(1)) + a_**WC('q', S(1))*WC('y', S(1)))**WC('t', S(1))*WC('w', S(1))), cons20, cons21, cons24, cons26) def replacement11(p, m, n, u, q, w, v, a, z, y, t): return FixSimplify(a**(m*t)*w*(a**(-m + n)*v + a**(-m + p)*z + a**(-m + q)*y + u)**t) rule11 = ReplacementRule(pattern11, replacement11) pattern12 = Pattern(UtilityOperator((sqrt(v_)*WC('b', S(1)) + sqrt(v_)*WC('c', S(1)) + sqrt(v_)*WC('d', S(1)) + sqrt(v_)*WC('a', S(1)) + WC('u', S(0)))*WC('w', S(1)))) def replacement12(d, u, w, v, c, a, b): return FixSimplify(w*(u + sqrt(v)*FixSimplify(a + b + c + d))) rule12 = ReplacementRule(pattern12, replacement12) pattern13 = Pattern(UtilityOperator((sqrt(v_)*WC('b', S(1)) + sqrt(v_)*WC('c', S(1)) + sqrt(v_)*WC('a', S(1)) + WC('u', S(0)))*WC('w', S(1)))) def replacement13(u, w, v, c, a, b): return FixSimplify(w*(u + sqrt(v)*FixSimplify(a + b + c))) rule13 = ReplacementRule(pattern13, replacement13) pattern14 = Pattern(UtilityOperator((sqrt(v_)*WC('b', S(1)) + sqrt(v_)*WC('a', S(1)) + WC('u', S(0)))*WC('w', S(1)))) def replacement14(u, w, v, a, b): return FixSimplify(w*(u + sqrt(v)*FixSimplify(a + b))) rule14 = ReplacementRule(pattern14, replacement14) pattern15 = Pattern(UtilityOperator(v_**m_*w_**n_*WC('u', S(1))), cons2, cons27, cons3, cons28, cons29) def replacement15(m, n, u, w, v): return -FixSimplify(u*v**(m + S(-1))) rule15 = ReplacementRule(pattern15, replacement15) pattern16 = Pattern(UtilityOperator(v_**m_*w_**WC('n', S(1))*WC('u', S(1))), cons2, cons27, cons30, cons31) def replacement16(m, n, u, w, v): return (S(-1))**n*FixSimplify(u*v**(m + n)) rule16 = ReplacementRule(pattern16, replacement16) pattern17 = Pattern(UtilityOperator(w_**WC('n', S(1))*(-v_**WC('p', S(1)))**m_*WC('u', S(1))), cons2, cons27, cons32, cons33) def replacement17(p, m, n, u, w, v): return (S(-1))**(n/p)*FixSimplify(u*(-v**p)**(m + n/p)) rule17 = ReplacementRule(pattern17, replacement17) pattern18 = Pattern(UtilityOperator(w_**WC('n', S(1))*(-v_**WC('p', S(1)))**m_*WC('u', S(1))), cons2, cons27, cons34, cons31) def replacement18(p, m, n, u, w, v): return (S(-1))**(n + n/p)*FixSimplify(u*(-v**p)**(m + n/p)) rule18 = ReplacementRule(pattern18, replacement18) pattern19 = Pattern(UtilityOperator((a_ - b_)**WC('m', S(1))*(a_ + b_)**WC('m', S(1))*WC('u', S(1))), cons9, cons35, cons36) def replacement19(m, u, a, b): return u*(a**S(2) - b**S(2))**m rule19 = ReplacementRule(pattern19, replacement19) pattern20 = Pattern(UtilityOperator((S(729)*c - e*(-S(20)*e + S(540)))**WC('m', S(1))*WC('u', S(1))), cons2) def replacement20(m, u): return u*(a*e**S(2) - b*d*e + c*d**S(2))**m rule20 = ReplacementRule(pattern20, replacement20) pattern21 = Pattern(UtilityOperator((S(729)*c + e*(S(20)*e + S(-540)))**WC('m', S(1))*WC('u', S(1))), cons2) def replacement21(m, u): return u*(a*e**S(2) - b*d*e + c*d**S(2))**m rule21 = ReplacementRule(pattern21, replacement21) pattern22 = Pattern(UtilityOperator(u_)) def replacement22(u): return u rule22 = ReplacementRule(pattern22, replacement22) return [rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9, rule10, rule11, rule12, rule13, rule14, rule15, rule16, rule17, rule18, rule19, rule20, rule21, rule22, ] @doctest_depends_on(modules=('matchpy',)) def FixSimplify(expr): if isinstance(expr, (list, tuple, TupleArg)): return [replace_all(UtilityOperator(i), FixSimplify_rules) for i in expr] return replace_all(UtilityOperator(expr), FixSimplify_rules) @doctest_depends_on(modules=('matchpy',)) def _SimplifyAntiderivativeSum(): replacer = ManyToOneReplacer() pattern1 = Pattern(UtilityOperator(Add(Mul(Log(Add(a_, Mul(WC('b', S(1)), Pow(Tan(u_), WC('n', S(1)))))), WC('A', S(1))), Mul(Log(Cos(u_)), WC('B', S(1))), WC('v', S(0))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda A, x: FreeQ(A, x)), CustomConstraint(lambda B, x: FreeQ(B, x)), CustomConstraint(lambda n: IntegerQ(n)), CustomConstraint(lambda B, A, n: ZeroQ(Add(Mul(n, A), Mul(S(1), B))))) rule1 = ReplacementRule(pattern1, lambda n, x, v, b, B, A, u, a : Add(SimplifyAntiderivativeSum(v, x), Mul(A, Log(RemoveContent(Add(Mul(a, Pow(Cos(u), n)), Mul(b, Pow(Sin(u), n))), x))))) replacer.add(rule1) pattern2 = Pattern(UtilityOperator(Add(Mul(Log(Add(Mul(Pow(Cot(u_), WC('n', S(1))), WC('b', S(1))), a_)), WC('A', S(1))), Mul(Log(Sin(u_)), WC('B', S(1))), WC('v', S(0))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda A, x: FreeQ(A, x)), CustomConstraint(lambda B, x: FreeQ(B, x)), CustomConstraint(lambda n: IntegerQ(n)), CustomConstraint(lambda B, A, n: ZeroQ(Add(Mul(n, A), Mul(S(1), B))))) rule2 = ReplacementRule(pattern2, lambda n, x, v, b, B, A, a, u : Add(SimplifyAntiderivativeSum(v, x), Mul(A, Log(RemoveContent(Add(Mul(a, Pow(Sin(u), n)), Mul(b, Pow(Cos(u), n))), x))))) replacer.add(rule2) pattern3 = Pattern(UtilityOperator(Add(Mul(Log(Add(a_, Mul(WC('b', S(1)), Pow(Tan(u_), WC('n', S(1)))))), WC('A', S(1))), Mul(Log(Add(c_, Mul(WC('d', S(1)), Pow(Tan(u_), WC('n', S(1)))))), WC('B', S(1))), WC('v', S(0))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda d, x: FreeQ(d, x)), CustomConstraint(lambda A, x: FreeQ(A, x)), CustomConstraint(lambda B, x: FreeQ(B, x)), CustomConstraint(lambda n: IntegerQ(n)), CustomConstraint(lambda B, A: ZeroQ(Add(A, B)))) rule3 = ReplacementRule(pattern3, lambda n, x, v, b, A, B, u, c, d, a : Add(SimplifyAntiderivativeSum(v, x), Mul(A, Log(RemoveContent(Add(Mul(a, Pow(Cos(u), n)), Mul(b, Pow(Sin(u), n))), x))), Mul(B, Log(RemoveContent(Add(Mul(c, Pow(Cos(u), n)), Mul(d, Pow(Sin(u), n))), x))))) replacer.add(rule3) pattern4 = Pattern(UtilityOperator(Add(Mul(Log(Add(Mul(Pow(Cot(u_), WC('n', S(1))), WC('b', S(1))), a_)), WC('A', S(1))), Mul(Log(Add(Mul(Pow(Cot(u_), WC('n', S(1))), WC('d', S(1))), c_)), WC('B', S(1))), WC('v', S(0))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda d, x: FreeQ(d, x)), CustomConstraint(lambda A, x: FreeQ(A, x)), CustomConstraint(lambda B, x: FreeQ(B, x)), CustomConstraint(lambda n: IntegerQ(n)), CustomConstraint(lambda B, A: ZeroQ(Add(A, B)))) rule4 = ReplacementRule(pattern4, lambda n, x, v, b, A, B, c, a, d, u : Add(SimplifyAntiderivativeSum(v, x), Mul(A, Log(RemoveContent(Add(Mul(b, Pow(Cos(u), n)), Mul(a, Pow(Sin(u), n))), x))), Mul(B, Log(RemoveContent(Add(Mul(d, Pow(Cos(u), n)), Mul(c, Pow(Sin(u), n))), x))))) replacer.add(rule4) pattern5 = Pattern(UtilityOperator(Add(Mul(Log(Add(a_, Mul(WC('b', S(1)), Pow(Tan(u_), WC('n', S(1)))))), WC('A', S(1))), Mul(Log(Add(c_, Mul(WC('d', S(1)), Pow(Tan(u_), WC('n', S(1)))))), WC('B', S(1))), Mul(Log(Add(e_, Mul(WC('f', S(1)), Pow(Tan(u_), WC('n', S(1)))))), WC('C', S(1))), WC('v', S(0))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda d, x: FreeQ(d, x)), CustomConstraint(lambda e, x: FreeQ(e, x)), CustomConstraint(lambda f, x: FreeQ(f, x)), CustomConstraint(lambda A, x: FreeQ(A, x)), CustomConstraint(lambda B, x: FreeQ(B, x)), CustomConstraint(lambda C, x: FreeQ(C, x)), CustomConstraint(lambda n: IntegerQ(n)), CustomConstraint(lambda B, A, C: ZeroQ(Add(A, B, C)))) rule5 = ReplacementRule(pattern5, lambda n, e, x, v, b, A, B, u, c, f, d, a, C : Add(SimplifyAntiderivativeSum(v, x), Mul(A, Log(RemoveContent(Add(Mul(a, Pow(Cos(u), n)), Mul(b, Pow(Sin(u), n))), x))), Mul(B, Log(RemoveContent(Add(Mul(c, Pow(Cos(u), n)), Mul(d, Pow(Sin(u), n))), x))), Mul(C, Log(RemoveContent(Add(Mul(e, Pow(Cos(u), n)), Mul(f, Pow(Sin(u), n))), x))))) replacer.add(rule5) pattern6 = Pattern(UtilityOperator(Add(Mul(Log(Add(Mul(Pow(Cot(u_), WC('n', S(1))), WC('b', S(1))), a_)), WC('A', S(1))), Mul(Log(Add(Mul(Pow(Cot(u_), WC('n', S(1))), WC('d', S(1))), c_)), WC('B', S(1))), Mul(Log(Add(Mul(Pow(Cot(u_), WC('n', S(1))), WC('f', S(1))), e_)), WC('C', S(1))), WC('v', S(0))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda d, x: FreeQ(d, x)), CustomConstraint(lambda e, x: FreeQ(e, x)), CustomConstraint(lambda f, x: FreeQ(f, x)), CustomConstraint(lambda A, x: FreeQ(A, x)), CustomConstraint(lambda B, x: FreeQ(B, x)), CustomConstraint(lambda C, x: FreeQ(C, x)), CustomConstraint(lambda n: IntegerQ(n)), CustomConstraint(lambda B, A, C: ZeroQ(Add(A, B, C)))) rule6 = ReplacementRule(pattern6, lambda n, e, x, v, b, A, B, c, a, f, d, u, C : Add(SimplifyAntiderivativeSum(v, x), Mul(A, Log(RemoveContent(Add(Mul(b, Pow(Cos(u), n)), Mul(a, Pow(Sin(u), n))), x))), Mul(B, Log(RemoveContent(Add(Mul(d, Pow(Cos(u), n)), Mul(c, Pow(Sin(u), n))), x))), Mul(C, Log(RemoveContent(Add(Mul(f, Pow(Cos(u), n)), Mul(e, Pow(Sin(u), n))), x))))) replacer.add(rule6) return replacer @doctest_depends_on(modules=('matchpy',)) def SimplifyAntiderivativeSum(expr, x): r = SimplifyAntiderivativeSum_replacer.replace(UtilityOperator(expr, x)) if isinstance(r, UtilityOperator): return expr return r @doctest_depends_on(modules=('matchpy',)) def _SimplifyAntiderivative(): replacer = ManyToOneReplacer() pattern2 = Pattern(UtilityOperator(Log(Mul(c_, u_)), x_), CustomConstraint(lambda c, x: FreeQ(c, x))) rule2 = ReplacementRule(pattern2, lambda x, c, u : SimplifyAntiderivative(Log(u), x)) replacer.add(rule2) pattern3 = Pattern(UtilityOperator(Log(Pow(u_, n_)), x_), CustomConstraint(lambda n, x: FreeQ(n, x))) rule3 = ReplacementRule(pattern3, lambda x, n, u : Mul(n, SimplifyAntiderivative(Log(u), x))) replacer.add(rule3) pattern7 = Pattern(UtilityOperator(Log(Pow(f_, u_)), x_), CustomConstraint(lambda f, x: FreeQ(f, x))) rule7 = ReplacementRule(pattern7, lambda x, f, u : Mul(Log(f), SimplifyAntiderivative(u, x))) replacer.add(rule7) pattern8 = Pattern(UtilityOperator(Log(Add(a_, Mul(WC('b', S(1)), Tan(u_)))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda b, a: ZeroQ(Add(Pow(a, S(2)), Pow(b, S(2)))))) rule8 = ReplacementRule(pattern8, lambda x, b, u, a : Add(Mul(Mul(b, Pow(a, S(1))), SimplifyAntiderivative(u, x)), Mul(S(1), SimplifyAntiderivative(Log(Cos(u)), x)))) replacer.add(rule8) pattern9 = Pattern(UtilityOperator(Log(Add(Mul(Cot(u_), WC('b', S(1))), a_)), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda b, a: ZeroQ(Add(Pow(a, S(2)), Pow(b, S(2)))))) rule9 = ReplacementRule(pattern9, lambda x, b, u, a : Add(Mul(Mul(Mul(S(1), b), Pow(a, S(1))), SimplifyAntiderivative(u, x)), Mul(S(1), SimplifyAntiderivative(Log(Sin(u)), x)))) replacer.add(rule9) pattern10 = Pattern(UtilityOperator(ArcTan(Mul(WC('a', S(1)), Tan(u_))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u))) rule10 = ReplacementRule(pattern10, lambda x, u, a : RectifyTangent(u, a, S(1), x)) replacer.add(rule10) pattern11 = Pattern(UtilityOperator(ArcCot(Mul(WC('a', S(1)), Tan(u_))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u))) rule11 = ReplacementRule(pattern11, lambda x, u, a : RectifyTangent(u, a, S(1), x)) replacer.add(rule11) pattern12 = Pattern(UtilityOperator(ArcCot(Mul(WC('a', S(1)), Tanh(u_))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda u: ComplexFreeQ(u))) rule12 = ReplacementRule(pattern12, lambda x, u, a : Mul(S(1), SimplifyAntiderivative(ArcTan(Mul(a, Tanh(u))), x))) replacer.add(rule12) pattern13 = Pattern(UtilityOperator(ArcTanh(Mul(WC('a', S(1)), Tan(u_))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u))) rule13 = ReplacementRule(pattern13, lambda x, u, a : RectifyTangent(u, Mul(I, a), Mul(S(1), I), x)) replacer.add(rule13) pattern14 = Pattern(UtilityOperator(ArcCoth(Mul(WC('a', S(1)), Tan(u_))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u))) rule14 = ReplacementRule(pattern14, lambda x, u, a : RectifyTangent(u, Mul(I, a), Mul(S(1), I), x)) replacer.add(rule14) pattern15 = Pattern(UtilityOperator(ArcTanh(Tanh(u_)), x_)) rule15 = ReplacementRule(pattern15, lambda x, u : SimplifyAntiderivative(u, x)) replacer.add(rule15) pattern16 = Pattern(UtilityOperator(ArcCoth(Tanh(u_)), x_)) rule16 = ReplacementRule(pattern16, lambda x, u : SimplifyAntiderivative(u, x)) replacer.add(rule16) pattern17 = Pattern(UtilityOperator(ArcCot(Mul(Cot(u_), WC('a', S(1)))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u))) rule17 = ReplacementRule(pattern17, lambda x, u, a : RectifyCotangent(u, a, S(1), x)) replacer.add(rule17) pattern18 = Pattern(UtilityOperator(ArcTan(Mul(Cot(u_), WC('a', S(1)))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u))) rule18 = ReplacementRule(pattern18, lambda x, u, a : RectifyCotangent(u, a, S(1), x)) replacer.add(rule18) pattern19 = Pattern(UtilityOperator(ArcTan(Mul(Coth(u_), WC('a', S(1)))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda u: ComplexFreeQ(u))) rule19 = ReplacementRule(pattern19, lambda x, u, a : Mul(S(1), SimplifyAntiderivative(ArcTan(Mul(Tanh(u), Pow(a, S(1)))), x))) replacer.add(rule19) pattern20 = Pattern(UtilityOperator(ArcCoth(Mul(Cot(u_), WC('a', S(1)))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u))) rule20 = ReplacementRule(pattern20, lambda x, u, a : RectifyCotangent(u, Mul(I, a), I, x)) replacer.add(rule20) pattern21 = Pattern(UtilityOperator(ArcTanh(Mul(Cot(u_), WC('a', S(1)))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u))) rule21 = ReplacementRule(pattern21, lambda x, u, a : RectifyCotangent(u, Mul(I, a), I, x)) replacer.add(rule21) pattern22 = Pattern(UtilityOperator(ArcCoth(Coth(u_)), x_)) rule22 = ReplacementRule(pattern22, lambda x, u : SimplifyAntiderivative(u, x)) replacer.add(rule22) pattern23 = Pattern(UtilityOperator(ArcTanh(Mul(Coth(u_), WC('a', S(1)))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda u: ComplexFreeQ(u))) rule23 = ReplacementRule(pattern23, lambda x, u, a : SimplifyAntiderivative(ArcTanh(Mul(Tanh(u), Pow(a, S(1)))), x)) replacer.add(rule23) pattern24 = Pattern(UtilityOperator(ArcTanh(Coth(u_)), x_)) rule24 = ReplacementRule(pattern24, lambda x, u : SimplifyAntiderivative(u, x)) replacer.add(rule24) pattern25 = Pattern(UtilityOperator(ArcTan(Mul(WC('c', S(1)), Add(a_, Mul(WC('b', S(1)), Tan(u_))))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda c, a: PositiveQ(Mul(Pow(a, S(2)), Pow(c, S(2))))), CustomConstraint(lambda c, b: PositiveQ(Mul(Pow(b, S(2)), Pow(c, S(2))))), CustomConstraint(lambda u: ComplexFreeQ(u))) rule25 = ReplacementRule(pattern25, lambda x, a, b, u, c : RectifyTangent(u, Mul(a, c), Mul(b, c), S(1), x)) replacer.add(rule25) pattern26 = Pattern(UtilityOperator(ArcTanh(Mul(WC('c', S(1)), Add(a_, Mul(WC('b', S(1)), Tan(u_))))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda c, a: PositiveQ(Mul(Pow(a, S(2)), Pow(c, S(2))))), CustomConstraint(lambda c, b: PositiveQ(Mul(Pow(b, S(2)), Pow(c, S(2))))), CustomConstraint(lambda u: ComplexFreeQ(u))) rule26 = ReplacementRule(pattern26, lambda x, a, b, u, c : RectifyTangent(u, Mul(I, a, c), Mul(I, b, c), Mul(S(1), I), x)) replacer.add(rule26) pattern27 = Pattern(UtilityOperator(ArcTan(Mul(WC('c', S(1)), Add(Mul(Cot(u_), WC('b', S(1))), a_))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda c, a: PositiveQ(Mul(Pow(a, S(2)), Pow(c, S(2))))), CustomConstraint(lambda c, b: PositiveQ(Mul(Pow(b, S(2)), Pow(c, S(2))))), CustomConstraint(lambda u: ComplexFreeQ(u))) rule27 = ReplacementRule(pattern27, lambda x, a, b, u, c : RectifyCotangent(u, Mul(a, c), Mul(b, c), S(1), x)) replacer.add(rule27) pattern28 = Pattern(UtilityOperator(ArcTanh(Mul(WC('c', S(1)), Add(Mul(Cot(u_), WC('b', S(1))), a_))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda c, a: PositiveQ(Mul(Pow(a, S(2)), Pow(c, S(2))))), CustomConstraint(lambda c, b: PositiveQ(Mul(Pow(b, S(2)), Pow(c, S(2))))), CustomConstraint(lambda u: ComplexFreeQ(u))) rule28 = ReplacementRule(pattern28, lambda x, a, b, u, c : RectifyCotangent(u, Mul(I, a, c), Mul(I, b, c), Mul(S(1), I), x)) replacer.add(rule28) pattern29 = Pattern(UtilityOperator(ArcTan(Add(WC('a', S(0)), Mul(WC('b', S(1)), Tan(u_)), Mul(WC('c', S(1)), Pow(Tan(u_), S(2))))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda u: ComplexFreeQ(u))) rule29 = ReplacementRule(pattern29, lambda x, a, b, u, c : If(EvenQ(Denominator(NumericFactor(Together(u)))), ArcTan(NormalizeTogether(Mul(Add(a, c, S(1), Mul(Add(a, Mul(S(1), c), S(1)), Cos(Mul(S(2), u))), Mul(b, Sin(Mul(S(2), u)))), Pow(Add(a, c, S(1), Mul(Add(a, Mul(S(1), c), S(1)), Cos(Mul(S(2), u))), Mul(b, Sin(Mul(S(2), u)))), S(1))))), ArcTan(NormalizeTogether(Mul(Add(c, Mul(Add(a, Mul(S(1), c), S(1)), Pow(Cos(u), S(2))), Mul(b, Cos(u), Sin(u))), Pow(Add(c, Mul(Add(a, Mul(S(1), c), S(1)), Pow(Cos(u), S(2))), Mul(b, Cos(u), Sin(u))), S(1))))))) replacer.add(rule29) pattern30 = Pattern(UtilityOperator(ArcTan(Add(WC('a', S(0)), Mul(WC('b', S(1)), Add(WC('d', S(0)), Mul(WC('e', S(1)), Tan(u_)))), Mul(WC('c', S(1)), Pow(Add(WC('f', S(0)), Mul(WC('g', S(1)), Tan(u_))), S(2))))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda u: ComplexFreeQ(u))) rule30 = ReplacementRule(pattern30, lambda x, d, a, e, f, b, u, c, g : SimplifyAntiderivative(ArcTan(Add(a, Mul(b, d), Mul(c, Pow(f, S(2))), Mul(Add(Mul(b, e), Mul(S(2), c, f, g)), Tan(u)), Mul(c, Pow(g, S(2)), Pow(Tan(u), S(2))))), x)) replacer.add(rule30) pattern31 = Pattern(UtilityOperator(ArcTan(Add(WC('a', S(0)), Mul(WC('c', S(1)), Pow(Tan(u_), S(2))))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda u: ComplexFreeQ(u))) rule31 = ReplacementRule(pattern31, lambda x, c, u, a : If(EvenQ(Denominator(NumericFactor(Together(u)))), ArcTan(NormalizeTogether(Mul(Add(a, c, S(1), Mul(Add(a, Mul(S(1), c), S(1)), Cos(Mul(S(2), u)))), Pow(Add(a, c, S(1), Mul(Add(a, Mul(S(1), c), S(1)), Cos(Mul(S(2), u)))), S(1))))), ArcTan(NormalizeTogether(Mul(Add(c, Mul(Add(a, Mul(S(1), c), S(1)), Pow(Cos(u), S(2)))), Pow(Add(c, Mul(Add(a, Mul(S(1), c), S(1)), Pow(Cos(u), S(2)))), S(1))))))) replacer.add(rule31) pattern32 = Pattern(UtilityOperator(ArcTan(Add(WC('a', S(0)), Mul(WC('c', S(1)), Pow(Add(WC('f', S(0)), Mul(WC('g', S(1)), Tan(u_))), S(2))))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda u: ComplexFreeQ(u))) rule32 = ReplacementRule(pattern32, lambda x, a, f, u, c, g : SimplifyAntiderivative(ArcTan(Add(a, Mul(c, Pow(f, S(2))), Mul(Mul(S(2), c, f, g), Tan(u)), Mul(c, Pow(g, S(2)), Pow(Tan(u), S(2))))), x)) replacer.add(rule32) return replacer @doctest_depends_on(modules=('matchpy',)) def SimplifyAntiderivative(expr, x): r = SimplifyAntiderivative_replacer.replace(UtilityOperator(expr, x)) if isinstance(r, UtilityOperator): if ProductQ(expr): u, c = S(1), S(1) for i in expr.args: if FreeQ(i, x): c *= i else: u *= i if FreeQ(c, x) and c != S(1): v = SimplifyAntiderivative(u, x) if SumQ(v) and NonsumQ(u): return Add(*[c*i for i in v.args]) return c*v elif LogQ(expr): F = expr.args[0] if MemberQ([cot, sec, csc, coth, sech, csch], Head(F)): return -SimplifyAntiderivative(Log(1/F), x) if MemberQ([Log, atan, acot], Head(expr)): F = Head(expr) G = expr.args[0] if MemberQ([cot, sec, csc, coth, sech, csch], Head(G)): return -SimplifyAntiderivative(F(1/G), x) if MemberQ([atanh, acoth], Head(expr)): F = Head(expr) G = expr.args[0] if MemberQ([cot, sec, csc, coth, sech, csch], Head(G)): return SimplifyAntiderivative(F(1/G), x) u = expr if FreeQ(u, x): return S(0) elif LogQ(u): return Log(RemoveContent(u.args[0], x)) elif SumQ(u): return SimplifyAntiderivativeSum(Add(*[SimplifyAntiderivative(i, x) for i in u.args]), x) return u else: return r @doctest_depends_on(modules=('matchpy',)) def _TrigSimplifyAux(): replacer = ManyToOneReplacer() pattern1 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(Add(Mul(WC('a', S(1)), Pow(v_, WC('m', S(1)))), Mul(WC('b', S(1)), Pow(v_, WC('n', S(1))))), p_))), CustomConstraint(lambda v: InertTrigQ(v)), CustomConstraint(lambda p: IntegerQ(p)), CustomConstraint(lambda n, m: RationalQ(m, n)), CustomConstraint(lambda n, m: Less(m, n))) rule1 = ReplacementRule(pattern1, lambda n, a, p, m, u, v, b : Mul(u, Pow(v, Mul(m, p)), Pow(TrigSimplifyAux(Add(a, Mul(b, Pow(v, Add(n, Mul(S(-1), m)))))), p))) replacer.add(rule1) pattern2 = Pattern(UtilityOperator(Add(Mul(Pow(cos(u_), S('2')), WC('a', S(1))), WC('v', S(0)), Mul(WC('b', S(1)), Pow(sin(u_), S('2'))))), CustomConstraint(lambda b, a: SameQ(a, b))) rule2 = ReplacementRule(pattern2, lambda u, v, b, a : Add(a, v)) replacer.add(rule2) pattern3 = Pattern(UtilityOperator(Add(WC('v', S(0)), Mul(WC('a', S(1)), Pow(sec(u_), S('2'))), Mul(WC('b', S(1)), Pow(tan(u_), S('2'))))), CustomConstraint(lambda b, a: SameQ(a, Mul(S(-1), b)))) rule3 = ReplacementRule(pattern3, lambda u, v, b, a : Add(a, v)) replacer.add(rule3) pattern4 = Pattern(UtilityOperator(Add(Mul(Pow(csc(u_), S('2')), WC('a', S(1))), Mul(Pow(cot(u_), S('2')), WC('b', S(1))), WC('v', S(0)))), CustomConstraint(lambda b, a: SameQ(a, Mul(S(-1), b)))) rule4 = ReplacementRule(pattern4, lambda u, v, b, a : Add(a, v)) replacer.add(rule4) pattern5 = Pattern(UtilityOperator(Pow(Add(Mul(Pow(cos(u_), S('2')), WC('a', S(1))), WC('v', S(0)), Mul(WC('b', S(1)), Pow(sin(u_), S('2')))), n_))) rule5 = ReplacementRule(pattern5, lambda n, a, u, v, b : Pow(Add(Mul(Add(b, Mul(S(-1), a)), Pow(Sin(u), S('2'))), a, v), n)) replacer.add(rule5) pattern6 = Pattern(UtilityOperator(Add(WC('w', S(0)), u_, Mul(WC('v', S(1)), Pow(sin(z_), S('2'))))), CustomConstraint(lambda u, v: SameQ(u, Mul(S(-1), v)))) rule6 = ReplacementRule(pattern6, lambda u, w, z, v : Add(Mul(u, Pow(Cos(z), S('2'))), w)) replacer.add(rule6) pattern7 = Pattern(UtilityOperator(Add(Mul(Pow(cos(z_), S('2')), WC('v', S(1))), WC('w', S(0)), u_)), CustomConstraint(lambda u, v: SameQ(u, Mul(S(-1), v)))) rule7 = ReplacementRule(pattern7, lambda z, w, v, u : Add(Mul(u, Pow(Sin(z), S('2'))), w)) replacer.add(rule7) pattern8 = Pattern(UtilityOperator(Add(WC('w', S(0)), u_, Mul(WC('v', S(1)), Pow(tan(z_), S('2'))))), CustomConstraint(lambda u, v: SameQ(u, v))) rule8 = ReplacementRule(pattern8, lambda u, w, z, v : Add(Mul(u, Pow(Sec(z), S('2'))), w)) replacer.add(rule8) pattern9 = Pattern(UtilityOperator(Add(Mul(Pow(cot(z_), S('2')), WC('v', S(1))), WC('w', S(0)), u_)), CustomConstraint(lambda u, v: SameQ(u, v))) rule9 = ReplacementRule(pattern9, lambda z, w, v, u : Add(Mul(u, Pow(Csc(z), S('2'))), w)) replacer.add(rule9) pattern10 = Pattern(UtilityOperator(Add(WC('w', S(0)), u_, Mul(WC('v', S(1)), Pow(sec(z_), S('2'))))), CustomConstraint(lambda u, v: SameQ(u, Mul(S(-1), v)))) rule10 = ReplacementRule(pattern10, lambda u, w, z, v : Add(Mul(v, Pow(Tan(z), S('2'))), w)) replacer.add(rule10) pattern11 = Pattern(UtilityOperator(Add(Mul(Pow(csc(z_), S('2')), WC('v', S(1))), WC('w', S(0)), u_)), CustomConstraint(lambda u, v: SameQ(u, Mul(S(-1), v)))) rule11 = ReplacementRule(pattern11, lambda z, w, v, u : Add(Mul(v, Pow(Cot(z), S('2'))), w)) replacer.add(rule11) pattern12 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(Add(Mul(cos(v_), WC('b', S(1))), a_), S(-1)), Pow(sin(v_), S('2')))), CustomConstraint(lambda b, a: ZeroQ(Add(Pow(a, S('2')), Mul(S(-1), Pow(b, S('2'))))))) rule12 = ReplacementRule(pattern12, lambda u, v, b, a : Mul(u, Add(Mul(S(1), Pow(a, S(-1))), Mul(S(-1), Mul(Cos(v), Pow(b, S(-1))))))) replacer.add(rule12) pattern13 = Pattern(UtilityOperator(Mul(Pow(cos(v_), S('2')), WC('u', S(1)), Pow(Add(a_, Mul(WC('b', S(1)), sin(v_))), S(-1)))), CustomConstraint(lambda b, a: ZeroQ(Add(Pow(a, S('2')), Mul(S(-1), Pow(b, S('2'))))))) rule13 = ReplacementRule(pattern13, lambda u, v, b, a : Mul(u, Add(Mul(S(1), Pow(a, S(-1))), Mul(S(-1), Mul(Sin(v), Pow(b, S(-1))))))) replacer.add(rule13) pattern14 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(tan(v_), WC('n', S(1))), Pow(Add(a_, Mul(WC('b', S(1)), Pow(tan(v_), WC('n', S(1))))), S(-1)))), CustomConstraint(lambda n: PositiveIntegerQ(n)), CustomConstraint(lambda a: NonsumQ(a))) rule14 = ReplacementRule(pattern14, lambda n, a, u, v, b : Mul(u, Pow(Add(b, Mul(a, Pow(Cot(v), n))), S(-1)))) replacer.add(rule14) pattern15 = Pattern(UtilityOperator(Mul(Pow(cot(v_), WC('n', S(1))), WC('u', S(1)), Pow(Add(Mul(Pow(cot(v_), WC('n', S(1))), WC('b', S(1))), a_), S(-1)))), CustomConstraint(lambda n: PositiveIntegerQ(n)), CustomConstraint(lambda a: NonsumQ(a))) rule15 = ReplacementRule(pattern15, lambda n, a, u, v, b : Mul(u, Pow(Add(b, Mul(a, Pow(Tan(v), n))), S(-1)))) replacer.add(rule15) pattern16 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(sec(v_), WC('n', S(1))), Pow(Add(a_, Mul(WC('b', S(1)), Pow(sec(v_), WC('n', S(1))))), S(-1)))), CustomConstraint(lambda n: PositiveIntegerQ(n)), CustomConstraint(lambda a: NonsumQ(a))) rule16 = ReplacementRule(pattern16, lambda n, a, u, v, b : Mul(u, Pow(Add(b, Mul(a, Pow(Cos(v), n))), S(-1)))) replacer.add(rule16) pattern17 = Pattern(UtilityOperator(Mul(Pow(csc(v_), WC('n', S(1))), WC('u', S(1)), Pow(Add(Mul(Pow(csc(v_), WC('n', S(1))), WC('b', S(1))), a_), S(-1)))), CustomConstraint(lambda n: PositiveIntegerQ(n)), CustomConstraint(lambda a: NonsumQ(a))) rule17 = ReplacementRule(pattern17, lambda n, a, u, v, b : Mul(u, Pow(Add(b, Mul(a, Pow(Sin(v), n))), S(-1)))) replacer.add(rule17) pattern18 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(Add(a_, Mul(WC('b', S(1)), Pow(sec(v_), WC('n', S(1))))), S(-1)), Pow(tan(v_), WC('n', S(1))))), CustomConstraint(lambda n: PositiveIntegerQ(n)), CustomConstraint(lambda a: NonsumQ(a))) rule18 = ReplacementRule(pattern18, lambda n, a, u, v, b : Mul(u, Mul(Pow(Sin(v), n), Pow(Add(b, Mul(a, Pow(Cos(v), n))), S(-1))))) replacer.add(rule18) pattern19 = Pattern(UtilityOperator(Mul(Pow(cot(v_), WC('n', S(1))), WC('u', S(1)), Pow(Add(Mul(Pow(csc(v_), WC('n', S(1))), WC('b', S(1))), a_), S(-1)))), CustomConstraint(lambda n: PositiveIntegerQ(n)), CustomConstraint(lambda a: NonsumQ(a))) rule19 = ReplacementRule(pattern19, lambda n, a, u, v, b : Mul(u, Mul(Pow(Cos(v), n), Pow(Add(b, Mul(a, Pow(Sin(v), n))), S(-1))))) replacer.add(rule19) pattern20 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(Add(Mul(WC('a', S(1)), Pow(sec(v_), WC('n', S(1)))), Mul(WC('b', S(1)), Pow(tan(v_), WC('n', S(1))))), WC('p', S(1))))), CustomConstraint(lambda n, p: IntegersQ(n, p))) rule20 = ReplacementRule(pattern20, lambda n, a, p, u, v, b : Mul(u, Pow(Sec(v), Mul(n, p)), Pow(Add(a, Mul(b, Pow(Sin(v), n))), p))) replacer.add(rule20) pattern21 = Pattern(UtilityOperator(Mul(Pow(Add(Mul(Pow(csc(v_), WC('n', S(1))), WC('a', S(1))), Mul(Pow(cot(v_), WC('n', S(1))), WC('b', S(1)))), WC('p', S(1))), WC('u', S(1)))), CustomConstraint(lambda n, p: IntegersQ(n, p))) rule21 = ReplacementRule(pattern21, lambda n, a, p, u, v, b : Mul(u, Pow(Csc(v), Mul(n, p)), Pow(Add(a, Mul(b, Pow(Cos(v), n))), p))) replacer.add(rule21) pattern22 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(Add(Mul(WC('b', S(1)), Pow(sin(v_), WC('n', S(1)))), Mul(WC('a', S(1)), Pow(tan(v_), WC('n', S(1))))), WC('p', S(1))))), CustomConstraint(lambda n, p: IntegersQ(n, p))) rule22 = ReplacementRule(pattern22, lambda n, a, p, u, v, b : Mul(u, Pow(Tan(v), Mul(n, p)), Pow(Add(a, Mul(b, Pow(Cos(v), n))), p))) replacer.add(rule22) pattern23 = Pattern(UtilityOperator(Mul(Pow(Add(Mul(Pow(cot(v_), WC('n', S(1))), WC('a', S(1))), Mul(Pow(cos(v_), WC('n', S(1))), WC('b', S(1)))), WC('p', S(1))), WC('u', S(1)))), CustomConstraint(lambda n, p: IntegersQ(n, p))) rule23 = ReplacementRule(pattern23, lambda n, a, p, u, v, b : Mul(u, Pow(Cot(v), Mul(n, p)), Pow(Add(a, Mul(b, Pow(Sin(v), n))), p))) replacer.add(rule23) pattern24 = Pattern(UtilityOperator(Mul(Pow(cos(v_), WC('m', S(1))), WC('u', S(1)), Pow(Add(WC('a', S(0)), Mul(WC('c', S(1)), Pow(sec(v_), WC('n', S(1)))), Mul(WC('b', S(1)), Pow(tan(v_), WC('n', S(1))))), WC('p', S(1))))), CustomConstraint(lambda n, p, m: IntegersQ(m, n, p))) rule24 = ReplacementRule(pattern24, lambda n, a, c, p, m, u, v, b : Mul(u, Pow(Cos(v), Add(m, Mul(S(-1), Mul(n, p)))), Pow(Add(c, Mul(b, Pow(Sin(v), n)), Mul(a, Pow(Cos(v), n))), p))) replacer.add(rule24) pattern25 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(sec(v_), WC('m', S(1))), Pow(Add(WC('a', S(0)), Mul(WC('c', S(1)), Pow(sec(v_), WC('n', S(1)))), Mul(WC('b', S(1)), Pow(tan(v_), WC('n', S(1))))), WC('p', S(1))))), CustomConstraint(lambda n, p, m: IntegersQ(m, n, p))) rule25 = ReplacementRule(pattern25, lambda n, a, c, p, m, u, v, b : Mul(u, Pow(Sec(v), Add(m, Mul(n, p))), Pow(Add(c, Mul(b, Pow(Sin(v), n)), Mul(a, Pow(Cos(v), n))), p))) replacer.add(rule25) pattern26 = Pattern(UtilityOperator(Mul(Pow(Add(WC('a', S(0)), Mul(Pow(cot(v_), WC('n', S(1))), WC('b', S(1))), Mul(Pow(csc(v_), WC('n', S(1))), WC('c', S(1)))), WC('p', S(1))), WC('u', S(1)), Pow(sin(v_), WC('m', S(1))))), CustomConstraint(lambda n, p, m: IntegersQ(m, n, p))) rule26 = ReplacementRule(pattern26, lambda n, a, c, p, m, u, v, b : Mul(u, Pow(Sin(v), Add(m, Mul(S(-1), Mul(n, p)))), Pow(Add(c, Mul(b, Pow(Cos(v), n)), Mul(a, Pow(Sin(v), n))), p))) replacer.add(rule26) pattern27 = Pattern(UtilityOperator(Mul(Pow(csc(v_), WC('m', S(1))), Pow(Add(WC('a', S(0)), Mul(Pow(cot(v_), WC('n', S(1))), WC('b', S(1))), Mul(Pow(csc(v_), WC('n', S(1))), WC('c', S(1)))), WC('p', S(1))), WC('u', S(1)))), CustomConstraint(lambda n, p, m: IntegersQ(m, n, p))) rule27 = ReplacementRule(pattern27, lambda n, a, c, p, m, u, v, b : Mul(u, Pow(Csc(v), Add(m, Mul(n, p))), Pow(Add(c, Mul(b, Pow(Cos(v), n)), Mul(a, Pow(Sin(v), n))), p))) replacer.add(rule27) pattern28 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(Add(Mul(Pow(csc(v_), WC('m', S(1))), WC('a', S(1))), Mul(WC('b', S(1)), Pow(sin(v_), WC('n', S(1))))), WC('p', S(1))))), CustomConstraint(lambda n, m: IntegersQ(m, n))) rule28 = ReplacementRule(pattern28, lambda n, a, p, m, u, v, b : If(And(ZeroQ(Add(m, n, S(-2))), ZeroQ(Add(a, b))), Mul(u, Pow(Mul(a, Mul(Pow(Cos(v), S('2')), Pow(Pow(Sin(v), m), S(-1)))), p)), Mul(u, Pow(Mul(Add(a, Mul(b, Pow(Sin(v), Add(m, n)))), Pow(Pow(Sin(v), m), S(-1))), p)))) replacer.add(rule28) pattern29 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(Add(Mul(Pow(cos(v_), WC('n', S(1))), WC('b', S(1))), Mul(WC('a', S(1)), Pow(sec(v_), WC('m', S(1))))), WC('p', S(1))))), CustomConstraint(lambda n, m: IntegersQ(m, n))) rule29 = ReplacementRule(pattern29, lambda n, a, p, m, u, v, b : If(And(ZeroQ(Add(m, n, S(-2))), ZeroQ(Add(a, b))), Mul(u, Pow(Mul(a, Mul(Pow(Sin(v), S('2')), Pow(Pow(Cos(v), m), S(-1)))), p)), Mul(u, Pow(Mul(Add(a, Mul(b, Pow(Cos(v), Add(m, n)))), Pow(Pow(Cos(v), m), S(-1))), p)))) replacer.add(rule29) pattern30 = Pattern(UtilityOperator(u_)) rule30 = ReplacementRule(pattern30, lambda u : u) replacer.add(rule30) return replacer @doctest_depends_on(modules=('matchpy',)) def TrigSimplifyAux(expr): return TrigSimplifyAux_replacer.replace(UtilityOperator(expr)) def Cancel(expr): return cancel(expr) class Util_Part(Function): def doit(self): i = Simplify(self.args[0]) if len(self.args) > 2 : lst = list(self.args[1:]) else: lst = self.args[1] if isinstance(i, (int, Integer)): if isinstance(lst, list): return lst[i - 1] elif AtomQ(lst): return lst return lst.args[i - 1] else: return self def Part(lst, i): #see i = -1 if isinstance(lst, list): return Util_Part(i, *lst).doit() return Util_Part(i, lst).doit() def PolyLog(n, p, z=None): return polylog(n, p) def D(f, x): try: return f.diff(x) except ValueError: return Function('D')(f, x) def IntegralFreeQ(u): return FreeQ(u, Integral) def Dist(u, v, x): #Dist(u,v) returns the sum of u times each term of v, provided v is free of Int u = replace_pow_exp(u) # to replace back to SymPy's exp v = replace_pow_exp(v) w = Simp(u*x**2, x)/x**2 if u == 1: return v elif u == 0: return 0 elif NumericFactor(u) < 0 and NumericFactor(-u) > 0: return -Dist(-u, v, x) elif SumQ(v): return Add(*[Dist(u, i, x) for i in v.args]) elif IntegralFreeQ(v): return Simp(u*v, x) elif w != u and FreeQ(w, x) and w == Simp(w, x) and w == Simp(w*x**2, x)/x**2: return Dist(w, v, x) else: return Simp(u*v, x) def PureFunctionOfCothQ(u, v, x): # If u is a pure function of Coth[v], PureFunctionOfCothQ[u,v,x] returns True; if AtomQ(u): return u != x elif CalculusQ(u): return False elif HyperbolicQ(u) and ZeroQ(u.args[0] - v): return CothQ(u) return all(PureFunctionOfCothQ(i, v, x) for i in u.args) def LogIntegral(z): return li(z) def ExpIntegralEi(z): return Ei(z) def ExpIntegralE(a, b): return expint(a, b).evalf() def SinIntegral(z): return Si(z) def CosIntegral(z): return Ci(z) def SinhIntegral(z): return Shi(z) def CoshIntegral(z): return Chi(z) class PolyGamma(Function): @classmethod def eval(cls, *args): if len(args) == 2: return polygamma(args[0], args[1]) return digamma(args[0]) def LogGamma(z): return loggamma(z) class ProductLog(Function): @classmethod def eval(cls, *args): if len(args) == 2: return LambertW(args[1], args[0]).evalf() return LambertW(args[0]).evalf() def Factorial(a): return factorial(a) def Zeta(*args): return zeta(*args) def HypergeometricPFQ(a, b, c): return hyper(a, b, c) def Sum_doit(exp, args): """ This function perform summation using SymPy's `Sum`. Examples ======== >>> from sympy.integrals.rubi.utility_function import Sum_doit >>> from sympy.abc import x >>> Sum_doit(2*x + 2, [x, 0, 1.7]) 6 """ exp = replace_pow_exp(exp) if not isinstance(args[2], (int, Integer)): new_args = [args[0], args[1], Floor(args[2])] return Sum(exp, new_args).doit() return Sum(exp, args).doit() def PolynomialQuotient(p, q, x): try: p = poly(p, x) q = poly(q, x) except: p = poly(p) q = poly(q) try: return quo(p, q).as_expr() except (PolynomialDivisionFailed, UnificationFailed): return p/q def PolynomialRemainder(p, q, x): try: p = poly(p, x) q = poly(q, x) except: p = poly(p) q = poly(q) try: return rem(p, q).as_expr() except (PolynomialDivisionFailed, UnificationFailed): return S(0) def Floor(x, a = None): if a is None: return floor(x) return a*floor(x/a) def Factor(var): return factor(var) def Rule(a, b): return {a: b} def Distribute(expr, *args): if len(args) == 1: if isinstance(expr, args[0]): return expr else: return expr.expand() if len(args) == 2: if isinstance(expr, args[1]): return expr.expand() else: return expr return expr.expand() def CoprimeQ(*args): args = S(args) g = gcd(*args) if g == 1: return True return False def Discriminant(a, b): try: return discriminant(a, b) except PolynomialError: return Function('Discriminant')(a, b) def Negative(x): return x < S(0) def Quotient(m, n): return Floor(m/n) def process_trig(expr): """ This function processes trigonometric expressions such that all `cot` is rewritten in terms of `tan`, `sec` in terms of `cos`, `csc` in terms of `sin` and similarly for `coth`, `sech` and `csch`. Examples ======== >>> from sympy.integrals.rubi.utility_function import process_trig >>> from sympy.abc import x >>> from sympy import coth, cot, csc >>> process_trig(x*cot(x)) x/tan(x) >>> process_trig(coth(x)*csc(x)) 1/(sin(x)*tanh(x)) """ expr = expr.replace(lambda x: isinstance(x, cot), lambda x: 1/tan(x.args[0])) expr = expr.replace(lambda x: isinstance(x, sec), lambda x: 1/cos(x.args[0])) expr = expr.replace(lambda x: isinstance(x, csc), lambda x: 1/sin(x.args[0])) expr = expr.replace(lambda x: isinstance(x, coth), lambda x: 1/tanh(x.args[0])) expr = expr.replace(lambda x: isinstance(x, sech), lambda x: 1/cosh(x.args[0])) expr = expr.replace(lambda x: isinstance(x, csch), lambda x: 1/sinh(x.args[0])) return expr def _ExpandIntegrand(): Plus = Add Times = Mul def cons_f1(m): return PositiveIntegerQ(m) cons1 = CustomConstraint(cons_f1) def cons_f2(d, c, b, a): return ZeroQ(-a*d + b*c) cons2 = CustomConstraint(cons_f2) def cons_f3(a, x): return FreeQ(a, x) cons3 = CustomConstraint(cons_f3) def cons_f4(b, x): return FreeQ(b, x) cons4 = CustomConstraint(cons_f4) def cons_f5(c, x): return FreeQ(c, x) cons5 = CustomConstraint(cons_f5) def cons_f6(d, x): return FreeQ(d, x) cons6 = CustomConstraint(cons_f6) def cons_f7(e, x): return FreeQ(e, x) cons7 = CustomConstraint(cons_f7) def cons_f8(f, x): return FreeQ(f, x) cons8 = CustomConstraint(cons_f8) def cons_f9(g, x): return FreeQ(g, x) cons9 = CustomConstraint(cons_f9) def cons_f10(h, x): return FreeQ(h, x) cons10 = CustomConstraint(cons_f10) def cons_f11(e, b, c, f, n, p, F, x, d, m): if not isinstance(x, Symbol): return False return FreeQ(List(F, b, c, d, e, f, m, n, p), x) cons11 = CustomConstraint(cons_f11) def cons_f12(F, x): return FreeQ(F, x) cons12 = CustomConstraint(cons_f12) def cons_f13(m, x): return FreeQ(m, x) cons13 = CustomConstraint(cons_f13) def cons_f14(n, x): return FreeQ(n, x) cons14 = CustomConstraint(cons_f14) def cons_f15(p, x): return FreeQ(p, x) cons15 = CustomConstraint(cons_f15) def cons_f16(e, b, c, f, n, a, p, F, x, d, m): if not isinstance(x, Symbol): return False return FreeQ(List(F, a, b, c, d, e, f, m, n, p), x) cons16 = CustomConstraint(cons_f16) def cons_f17(n, m): return IntegersQ(m, n) cons17 = CustomConstraint(cons_f17) def cons_f18(n): return Less(n, S(0)) cons18 = CustomConstraint(cons_f18) def cons_f19(x, u): if not isinstance(x, Symbol): return False return PolynomialQ(u, x) cons19 = CustomConstraint(cons_f19) def cons_f20(G, F, u): return SameQ(F(u)*G(u), S(1)) cons20 = CustomConstraint(cons_f20) def cons_f21(q, x): return FreeQ(q, x) cons21 = CustomConstraint(cons_f21) def cons_f22(F): return MemberQ(List(ArcSin, ArcCos, ArcSinh, ArcCosh), F) cons22 = CustomConstraint(cons_f22) def cons_f23(j, n): return ZeroQ(j - S(2)*n) cons23 = CustomConstraint(cons_f23) def cons_f24(A, x): return FreeQ(A, x) cons24 = CustomConstraint(cons_f24) def cons_f25(B, x): return FreeQ(B, x) cons25 = CustomConstraint(cons_f25) def cons_f26(m, u, x): if not isinstance(x, Symbol): return False def _cons_f_u(d, w, c, p, x): return And(FreeQ(List(c, d), x), IntegerQ(p), Greater(p, m)) cons_u = CustomConstraint(_cons_f_u) pat = Pattern(UtilityOperator((c_ + x_*WC('d', S(1)))**p_*WC('w', S(1)), x_), cons_u) result_matchq = is_match(UtilityOperator(u, x), pat) return Not(And(PositiveIntegerQ(m), result_matchq)) cons26 = CustomConstraint(cons_f26) def cons_f27(b, v, n, a, x, u, m): if not isinstance(x, Symbol): return False return And(FreeQ(List(a, b, m), x), NegativeIntegerQ(n), Not(IntegerQ(m)), PolynomialQ(u, x), PolynomialQ(v, x),\ RationalQ(m), Less(m, -1), GreaterEqual(Exponent(u, x), (-n - IntegerPart(m))*Exponent(v, x))) cons27 = CustomConstraint(cons_f27) def cons_f28(v, n, x, u, m): if not isinstance(x, Symbol): return False return And(FreeQ(List(a, b, m), x), NegativeIntegerQ(n), Not(IntegerQ(m)), PolynomialQ(u, x),\ PolynomialQ(v, x), GreaterEqual(Exponent(u, x), -n*Exponent(v, x))) cons28 = CustomConstraint(cons_f28) def cons_f29(n): return PositiveIntegerQ(n/S(4)) cons29 = CustomConstraint(cons_f29) def cons_f30(n): return IntegerQ(n) cons30 = CustomConstraint(cons_f30) def cons_f31(n): return Greater(n, S(1)) cons31 = CustomConstraint(cons_f31) def cons_f32(n, m): return Less(S(0), m, n) cons32 = CustomConstraint(cons_f32) def cons_f33(n, m): return OddQ(n/GCD(m, n)) cons33 = CustomConstraint(cons_f33) def cons_f34(a, b): return PosQ(a/b) cons34 = CustomConstraint(cons_f34) def cons_f35(n, m, p): return IntegersQ(m, n, p) cons35 = CustomConstraint(cons_f35) def cons_f36(n, m, p): return Less(S(0), m, p, n) cons36 = CustomConstraint(cons_f36) def cons_f37(q, n, m, p): return IntegersQ(m, n, p, q) cons37 = CustomConstraint(cons_f37) def cons_f38(n, q, m, p): return Less(S(0), m, p, q, n) cons38 = CustomConstraint(cons_f38) def cons_f39(n): return IntegerQ(n/S(2)) cons39 = CustomConstraint(cons_f39) def cons_f40(p): return NegativeIntegerQ(p) cons40 = CustomConstraint(cons_f40) def cons_f41(n, m): return IntegersQ(m, n/S(2)) cons41 = CustomConstraint(cons_f41) def cons_f42(n, m): return Unequal(m, n/S(2)) cons42 = CustomConstraint(cons_f42) def cons_f43(c, b, a): return NonzeroQ(-S(4)*a*c + b**S(2)) cons43 = CustomConstraint(cons_f43) def cons_f44(j, n, m): return IntegersQ(m, n, j) cons44 = CustomConstraint(cons_f44) def cons_f45(n, m): return Less(S(0), m, S(2)*n) cons45 = CustomConstraint(cons_f45) def cons_f46(n, m, p): return Not(And(Equal(m, n), Equal(p, S(-1)))) cons46 = CustomConstraint(cons_f46) def cons_f47(v, x): if not isinstance(x, Symbol): return False return PolynomialQ(v, x) cons47 = CustomConstraint(cons_f47) def cons_f48(v, x): if not isinstance(x, Symbol): return False return BinomialQ(v, x) cons48 = CustomConstraint(cons_f48) def cons_f49(v, x, u): if not isinstance(x, Symbol): return False return Inequality(Exponent(u, x), Equal, Exponent(v, x) + S(-1), GreaterEqual, S(2)) cons49 = CustomConstraint(cons_f49) def cons_f50(v, x, u): if not isinstance(x, Symbol): return False return GreaterEqual(Exponent(u, x), Exponent(v, x)) cons50 = CustomConstraint(cons_f50) def cons_f51(p): return Not(IntegerQ(p)) cons51 = CustomConstraint(cons_f51) def With2(e, b, c, f, n, a, g, h, x, d, m): tmp = a*h - b*g k = Symbol('k') return f**(e*(c + d*x)**n)*SimplifyTerm(h**(-m)*tmp**m, x)/(g + h*x) + Sum_doit(f**(e*(c + d*x)**n)*(a + b*x)**(-k + m)*SimplifyTerm(b*h**(-k)*tmp**(k - 1), x), List(k, 1, m)) pattern2 = Pattern(UtilityOperator(f_**((x_*WC('d', S(1)) + WC('c', S(0)))**WC('n', S(1))*WC('e', S(1)))*(x_*WC('b', S(1)) + WC('a', S(0)))**WC('m', S(1))/(x_*WC('h', S(1)) + WC('g', S(0))), x_), cons3, cons4, cons5, cons6, cons7, cons8, cons9, cons10, cons1, cons2) rule2 = ReplacementRule(pattern2, With2) pattern3 = Pattern(UtilityOperator(F_**((x_*WC('d', S(1)) + WC('c', S(0)))**WC('n', S(1))*WC('b', S(1)))*x_**WC('m', S(1))*(e_ + x_*WC('f', S(1)))**WC('p', S(1)), x_), cons12, cons4, cons5, cons6, cons7, cons8, cons13, cons14, cons15, cons11) def replacement3(e, b, c, f, n, p, F, x, d, m): return If(And(PositiveIntegerQ(m, p), LessEqual(m, p), Or(EqQ(n, S(1)), ZeroQ(-c*f + d*e))), ExpandLinearProduct(F**(b*(c + d*x)**n)*(e + f*x)**p, x**m, e, f, x), If(PositiveIntegerQ(p), Distribute(F**(b*(c + d*x)**n)*x**m*(e + f*x)**p, Plus, Times), ExpandIntegrand(F**(b*(c + d*x)**n), x**m*(e + f*x)**p, x))) rule3 = ReplacementRule(pattern3, replacement3) pattern4 = Pattern(UtilityOperator(F_**((x_*WC('d', S(1)) + WC('c', S(0)))**WC('n', S(1))*WC('b', S(1)) + WC('a', S(0)))*x_**WC('m', S(1))*(e_ + x_*WC('f', S(1)))**WC('p', S(1)), x_), cons12, cons3, cons4, cons5, cons6, cons7, cons8, cons13, cons14, cons15, cons16) def replacement4(e, b, c, f, n, a, p, F, x, d, m): return If(And(PositiveIntegerQ(m, p), LessEqual(m, p), Or(EqQ(n, S(1)), ZeroQ(-c*f + d*e))), ExpandLinearProduct(F**(a + b*(c + d*x)**n)*(e + f*x)**p, x**m, e, f, x), If(PositiveIntegerQ(p), Distribute(F**(a + b*(c + d*x)**n)*x**m*(e + f*x)**p, Plus, Times), ExpandIntegrand(F**(a + b*(c + d*x)**n), x**m*(e + f*x)**p, x))) rule4 = ReplacementRule(pattern4, replacement4) def With5(b, v, c, n, a, F, u, x, d, m): if not isinstance(x, Symbol) or not (FreeQ([F, a, b, c, d], x) and IntegersQ(m, n) and n < 0): return False w = ExpandIntegrand((a + b*x)**m*(c + d*x)**n, x) w = ReplaceAll(w, Rule(x, F**v)) if SumQ(w): return True return False pattern5 = Pattern(UtilityOperator((F_**v_*WC('b', S(1)) + a_)**WC('m', S(1))*(F_**v_*WC('d', S(1)) + c_)**n_*WC('u', S(1)), x_), cons12, cons3, cons4, cons5, cons6, cons17, cons18, CustomConstraint(With5)) def replacement5(b, v, c, n, a, F, u, x, d, m): w = ReplaceAll(ExpandIntegrand((a + b*x)**m*(c + d*x)**n, x), Rule(x, F**v)) return w.func(*[u*i for i in w.args]) rule5 = ReplacementRule(pattern5, replacement5) def With6(e, b, c, f, n, a, x, u, d, m): if not isinstance(x, Symbol) or not (FreeQ([a, b, c, d, e, f, m, n], x) and PolynomialQ(u,x)): return False v = ExpandIntegrand(u*(a + b*x)**m, x) if SumQ(v): return True return False pattern6 = Pattern(UtilityOperator(f_**((x_*WC('d', S(1)) + WC('c', S(0)))**WC('n', S(1))*WC('e', S(1)))*u_*(x_*WC('b', S(1)) + WC('a', S(0)))**WC('m', S(1)), x_), cons3, cons4, cons5, cons6, cons7, cons8, cons13, cons14, cons19, CustomConstraint(With6)) def replacement6(e, b, c, f, n, a, x, u, d, m): v = ExpandIntegrand(u*(a + b*x)**m, x) return Distribute(f**(e*(c + d*x)**n)*v, Plus, Times) rule6 = ReplacementRule(pattern6, replacement6) pattern7 = Pattern(UtilityOperator(u_*(x_*WC('b', S(1)) + WC('a', S(0)))**WC('m', S(1))*Log((x_**WC('n', S(1))*WC('e', S(1)) + WC('d', S(0)))**WC('p', S(1))*WC('c', S(1))), x_), cons3, cons4, cons5, cons6, cons7, cons13, cons14, cons15, cons19) def replacement7(e, b, c, n, a, p, x, u, d, m): return ExpandIntegrand(Log(c*(d + e*x**n)**p), u*(a + b*x)**m, x) rule7 = ReplacementRule(pattern7, replacement7) pattern8 = Pattern(UtilityOperator(f_**((x_*WC('d', S(1)) + WC('c', S(0)))**WC('n', S(1))*WC('e', S(1)))*u_, x_), cons5, cons6, cons7, cons8, cons14, cons19) def replacement8(e, c, f, n, x, u, d): return If(EqQ(n, S(1)), ExpandIntegrand(f**(e*(c + d*x)**n), u, x), ExpandLinearProduct(f**(e*(c + d*x)**n), u, c, d, x)) rule8 = ReplacementRule(pattern8, replacement8) # pattern9 = Pattern(UtilityOperator(F_**u_*(G_*u_*WC('b', S(1)) + a_)**WC('n', S(1)), x_), cons3, cons4, cons17, cons20) # def replacement9(b, G, n, a, F, u, x, m): # return ReplaceAll(ExpandIntegrand(x**(-m)*(a + b*x)**n, x), Rule(x, G(u))) # rule9 = ReplacementRule(pattern9, replacement9) pattern10 = Pattern(UtilityOperator(u_*(WC('a', S(0)) + WC('b', S(1))*Log(((x_*WC('f', S(1)) + WC('e', S(0)))**WC('p', S(1))*WC('d', S(1)))**WC('q', S(1))*WC('c', S(1))))**n_, x_), cons3, cons4, cons5, cons6, cons7, cons8, cons14, cons15, cons21, cons19) def replacement10(e, b, c, f, n, a, p, x, u, d, q): return ExpandLinearProduct((a + b*Log(c*(d*(e + f*x)**p)**q))**n, u, e, f, x) rule10 = ReplacementRule(pattern10, replacement10) # pattern11 = Pattern(UtilityOperator(u_*(F_*(x_*WC('d', S(1)) + WC('c', S(0)))*WC('b', S(1)) + WC('a', S(0)))**n_, x_), cons3, cons4, cons5, cons6, cons14, cons19, cons22) # def replacement11(b, c, n, a, F, u, x, d): # return ExpandLinearProduct((a + b*F(c + d*x))**n, u, c, d, x) # rule11 = ReplacementRule(pattern11, replacement11) pattern12 = Pattern(UtilityOperator(WC('u', S(1))/(x_**n_*WC('a', S(1)) + sqrt(c_ + x_**j_*WC('d', S(1)))*WC('b', S(1))), x_), cons3, cons4, cons5, cons6, cons14, cons23) def replacement12(b, c, n, a, x, u, d, j): return ExpandIntegrand(u*(a*x**n - b*sqrt(c + d*x**(S(2)*n)))/(-b**S(2)*c + x**(S(2)*n)*(a**S(2) - b**S(2)*d)), x) rule12 = ReplacementRule(pattern12, replacement12) pattern13 = Pattern(UtilityOperator((a_ + x_*WC('b', S(1)))**m_/(c_ + x_*WC('d', S(1))), x_), cons3, cons4, cons5, cons6, cons1) def replacement13(b, c, a, x, d, m): if RationalQ(a, b, c, d): return ExpandExpression((a + b*x)**m/(c + d*x), x) else: tmp = a*d - b*c k = Symbol("k") return Sum_doit((a + b*x)**(-k + m)*SimplifyTerm(b*d**(-k)*tmp**(k + S(-1)), x), List(k, S(1), m)) + SimplifyTerm(d**(-m)*tmp**m, x)/(c + d*x) rule13 = ReplacementRule(pattern13, replacement13) pattern14 = Pattern(UtilityOperator((A_ + x_*WC('B', S(1)))*(a_ + x_*WC('b', S(1)))**WC('m', S(1))/(c_ + x_*WC('d', S(1))), x_), cons3, cons4, cons5, cons6, cons24, cons25, cons1) def replacement14(b, B, A, c, a, x, d, m): if RationalQ(a, b, c, d, A, B): return ExpandExpression((A + B*x)*(a + b*x)**m/(c + d*x), x) else: tmp1 = (A*d - B*c)/d tmp2 = ExpandIntegrand((a + b*x)**m/(c + d*x), x) tmp2 = If(SumQ(tmp2), tmp2.func(*[SimplifyTerm(tmp1*i, x) for i in tmp2.args]), SimplifyTerm(tmp1*tmp2, x)) return SimplifyTerm(B/d, x)*(a + b*x)**m + tmp2 rule14 = ReplacementRule(pattern14, replacement14) def With15(b, a, x, u, m): tmp1 = ExpandLinearProduct((a + b*x)**m, u, a, b, x) if not IntegerQ(m): return tmp1 else: tmp2 = ExpandExpression(u*(a + b*x)**m, x) if SumQ(tmp2) and LessEqual(LeafCount(tmp2), LeafCount(tmp1) + S(2)): return tmp2 else: return tmp1 pattern15 = Pattern(UtilityOperator(u_*(a_ + x_*WC('b', S(1)))**m_, x_), cons3, cons4, cons13, cons19, cons26) rule15 = ReplacementRule(pattern15, With15) pattern16 = Pattern(UtilityOperator(u_*v_**n_*(a_ + x_*WC('b', S(1)))**m_, x_), cons27) def replacement16(b, v, n, a, x, u, m): s = PolynomialQuotientRemainder(u, v**(-n)*(a+b*x)**(-IntegerPart(m)), x) return ExpandIntegrand((a + b*x)**FractionalPart(m)*s[0], x) + ExpandIntegrand(v**n*(a + b*x)**m*s[1], x) rule16 = ReplacementRule(pattern16, replacement16) pattern17 = Pattern(UtilityOperator(u_*v_**n_*(a_ + x_*WC('b', S(1)))**m_, x_), cons28) def replacement17(b, v, n, a, x, u, m): s = PolynomialQuotientRemainder(u, v**(-n),x) return ExpandIntegrand((a + b*x)**(m)*s[0], x) + ExpandIntegrand(v**n*(a + b*x)**m*s[1], x) rule17 = ReplacementRule(pattern17, replacement17) def With18(b, n, a, x, u): r = Numerator(Rt(-a/b, S(2))) s = Denominator(Rt(-a/b, S(2))) return r/(S(2)*a*(r + s*u**(n/S(2)))) + r/(S(2)*a*(r - s*u**(n/S(2)))) pattern18 = Pattern(UtilityOperator(S(1)/(a_ + u_**n_*WC('b', S(1))), x_), cons3, cons4, cons29) rule18 = ReplacementRule(pattern18, With18) def With19(b, n, a, x, u): k = Symbol("k") r = Numerator(Rt(-a/b, n)) s = Denominator(Rt(-a/b, n)) return Sum_doit(r/(a*n*(-(-1)**(2*k/n)*s*u + r)), List(k, 1, n)) pattern19 = Pattern(UtilityOperator(S(1)/(a_ + u_**n_*WC('b', S(1))), x_), cons3, cons4, cons30, cons31) rule19 = ReplacementRule(pattern19, With19) def With20(b, n, a, x, u, m): k = Symbol("k") g = GCD(m, n) r = Numerator(Rt(a/b, n/GCD(m, n))) s = Denominator(Rt(a/b, n/GCD(m, n))) return If(CoprimeQ(g + m, n), Sum_doit((-1)**(-2*k*m/n)*r*(-r/s)**(m/g)/(a*n*((-1)**(2*g*k/n)*s*u**g + r)), List(k, 1, n/g)), Sum_doit((-1)**(2*k*(g + m)/n)*r*(-r/s)**(m/g)/(a*n*((-1)**(2*g*k/n)*r + s*u**g)), List(k, 1, n/g))) pattern20 = Pattern(UtilityOperator(u_**WC('m', S(1))/(a_ + u_**n_*WC('b', S(1))), x_), cons3, cons4, cons17, cons32, cons33, cons34) rule20 = ReplacementRule(pattern20, With20) def With21(b, n, a, x, u, m): k = Symbol("k") g = GCD(m, n) r = Numerator(Rt(-a/b, n/GCD(m, n))) s = Denominator(Rt(-a/b, n/GCD(m, n))) return If(Equal(n/g, S(2)), s/(S(2)*b*(r + s*u**g)) - s/(S(2)*b*(r - s*u**g)), If(CoprimeQ(g + m, n), Sum_doit((S(-1))**(-S(2)*k*m/n)*r*(r/s)**(m/g)/(a*n*(-(S(-1))**(S(2)*g*k/n)*s*u**g + r)), List(k, S(1), n/g)), Sum_doit((S(-1))**(S(2)*k*(g + m)/n)*r*(r/s)**(m/g)/(a*n*((S(-1))**(S(2)*g*k/n)*r - s*u**g)), List(k, S(1), n/g)))) pattern21 = Pattern(UtilityOperator(u_**WC('m', S(1))/(a_ + u_**n_*WC('b', S(1))), x_), cons3, cons4, cons17, cons32) rule21 = ReplacementRule(pattern21, With21) def With22(b, c, n, a, x, u, d, m): k = Symbol("k") r = Numerator(Rt(-a/b, n)) s = Denominator(Rt(-a/b, n)) return Sum_doit((c*r + (-1)**(-2*k*m/n)*d*r*(r/s)**m)/(a*n*(-(-1)**(2*k/n)*s*u + r)), List(k, 1, n)) pattern22 = Pattern(UtilityOperator((c_ + u_**WC('m', S(1))*WC('d', S(1)))/(a_ + u_**n_*WC('b', S(1))), x_), cons3, cons4, cons5, cons6, cons17, cons32) rule22 = ReplacementRule(pattern22, With22) def With23(e, b, c, n, a, p, x, u, d, m): k = Symbol("k") r = Numerator(Rt(-a/b, n)) s = Denominator(Rt(-a/b, n)) return Sum_doit((c*r + (-1)**(-2*k*p/n)*e*r*(r/s)**p + (-1)**(-2*k*m/n)*d*r*(r/s)**m)/(a*n*(-(-1)**(2*k/n)*s*u + r)), List(k, 1, n)) pattern23 = Pattern(UtilityOperator((u_**p_*WC('e', S(1)) + u_**WC('m', S(1))*WC('d', S(1)) + WC('c', S(0)))/(a_ + u_**n_*WC('b', S(1))), x_), cons3, cons4, cons5, cons6, cons7, cons35, cons36) rule23 = ReplacementRule(pattern23, With23) def With24(e, b, c, f, n, a, p, x, u, d, q, m): k = Symbol("k") r = Numerator(Rt(-a/b, n)) s = Denominator(Rt(-a/b, n)) return Sum_doit((c*r + (-1)**(-2*k*q/n)*f*r*(r/s)**q + (-1)**(-2*k*p/n)*e*r*(r/s)**p + (-1)**(-2*k*m/n)*d*r*(r/s)**m)/(a*n*(-(-1)**(2*k/n)*s*u + r)), List(k, 1, n)) pattern24 = Pattern(UtilityOperator((u_**p_*WC('e', S(1)) + u_**q_*WC('f', S(1)) + u_**WC('m', S(1))*WC('d', S(1)) + WC('c', S(0)))/(a_ + u_**n_*WC('b', S(1))), x_), cons3, cons4, cons5, cons6, cons7, cons8, cons37, cons38) rule24 = ReplacementRule(pattern24, With24) def With25(c, n, a, p, x, u): q = Symbol('q') return ReplaceAll(ExpandIntegrand(c**(-p), (c*x - q)**p*(c*x + q)**p, x), List(Rule(q, Rt(-a*c, S(2))), Rule(x, u**(n/S(2))))) pattern25 = Pattern(UtilityOperator((a_ + u_**WC('n', S(1))*WC('c', S(1)))**p_, x_), cons3, cons5, cons39, cons40) rule25 = ReplacementRule(pattern25, With25) def With26(c, n, a, p, x, u, m): q = Symbol('q') return ReplaceAll(ExpandIntegrand(c**(-p), x**m*(c*x**(n/S(2)) - q)**p*(c*x**(n/S(2)) + q)**p, x), List(Rule(q, Rt(-a*c, S(2))), Rule(x, u))) pattern26 = Pattern(UtilityOperator(u_**WC('m', S(1))*(u_**WC('n', S(1))*WC('c', S(1)) + WC('a', S(0)))**p_, x_), cons3, cons5, cons41, cons40, cons32, cons42) rule26 = ReplacementRule(pattern26, With26) def With27(b, c, n, a, p, x, u, j): q = Symbol('q') return ReplaceAll(ExpandIntegrand(S(4)**(-p)*c**(-p), (b + S(2)*c*x - q)**p*(b + S(2)*c*x + q)**p, x), List(Rule(q, Rt(-S(4)*a*c + b**S(2), S(2))), Rule(x, u**n))) pattern27 = Pattern(UtilityOperator((u_**WC('j', S(1))*WC('c', S(1)) + u_**WC('n', S(1))*WC('b', S(1)) + WC('a', S(0)))**p_, x_), cons3, cons4, cons5, cons30, cons23, cons40, cons43) rule27 = ReplacementRule(pattern27, With27) def With28(b, c, n, a, p, x, u, j, m): q = Symbol('q') return ReplaceAll(ExpandIntegrand(S(4)**(-p)*c**(-p), x**m*(b + S(2)*c*x**n - q)**p*(b + S(2)*c*x**n + q)**p, x), List(Rule(q, Rt(-S(4)*a*c + b**S(2), S(2))), Rule(x, u))) pattern28 = Pattern(UtilityOperator(u_**WC('m', S(1))*(u_**WC('j', S(1))*WC('c', S(1)) + u_**WC('n', S(1))*WC('b', S(1)) + WC('a', S(0)))**p_, x_), cons3, cons4, cons5, cons44, cons23, cons40, cons45, cons46, cons43) rule28 = ReplacementRule(pattern28, With28) def With29(b, c, n, a, x, u, d, j): q = Rt(-a/b, S(2)) return -(c - d*q)/(S(2)*b*q*(q + u**n)) - (c + d*q)/(S(2)*b*q*(q - u**n)) pattern29 = Pattern(UtilityOperator((u_**WC('n', S(1))*WC('d', S(1)) + WC('c', S(0)))/(a_ + u_**WC('j', S(1))*WC('b', S(1))), x_), cons3, cons4, cons5, cons6, cons14, cons23) rule29 = ReplacementRule(pattern29, With29) def With30(e, b, c, f, n, a, g, x, u, d, j): q = Rt(-S(4)*a*c + b**S(2), S(2)) r = TogetherSimplify((-b*e*g + S(2)*c*(d + e*f))/q) return (e*g - r)/(b + 2*c*u**n + q) + (e*g + r)/(b + 2*c*u**n - q) pattern30 = Pattern(UtilityOperator(((u_**WC('n', S(1))*WC('g', S(1)) + WC('f', S(0)))*WC('e', S(1)) + WC('d', S(0)))/(u_**WC('j', S(1))*WC('c', S(1)) + u_**WC('n', S(1))*WC('b', S(1)) + WC('a', S(0))), x_), cons3, cons4, cons5, cons6, cons7, cons8, cons9, cons14, cons23, cons43) rule30 = ReplacementRule(pattern30, With30) def With31(v, x, u): lst = CoefficientList(u, x) i = Symbol('i') return x**Exponent(u, x)*lst[-1]/v + Sum_doit(x**(i - 1)*Part(lst, i), List(i, 1, Exponent(u, x)))/v pattern31 = Pattern(UtilityOperator(u_/v_, x_), cons19, cons47, cons48, cons49) rule31 = ReplacementRule(pattern31, With31) pattern32 = Pattern(UtilityOperator(u_/v_, x_), cons19, cons47, cons50) def replacement32(v, x, u): return PolynomialDivide(u, v, x) rule32 = ReplacementRule(pattern32, replacement32) pattern33 = Pattern(UtilityOperator(u_*(x_*WC('a', S(1)))**p_, x_), cons51, cons19) def replacement33(x, a, u, p): return ExpandToSum((a*x)**p, u, x) rule33 = ReplacementRule(pattern33, replacement33) pattern34 = Pattern(UtilityOperator(v_**p_*WC('u', S(1)), x_), cons51) def replacement34(v, x, u, p): return ExpandIntegrand(NormalizeIntegrand(v**p, x), u, x) rule34 = ReplacementRule(pattern34, replacement34) pattern35 = Pattern(UtilityOperator(u_, x_)) def replacement35(x, u): return ExpandExpression(u, x) rule35 = ReplacementRule(pattern35, replacement35) return [ rule2,rule3, rule4, rule5, rule6, rule7, rule8, rule10, rule12, rule13, rule14, rule15, rule16, rule17, rule18, rule19, rule20, rule21, rule22, rule23, rule24, rule25, rule26, rule27, rule28, rule29, rule30, rule31, rule32, rule33, rule34, rule35] def _RemoveContentAux(): def cons_f1(b, a): return IntegersQ(a, b) cons1 = CustomConstraint(cons_f1) def cons_f2(b, a): return Equal(a + b, S(0)) cons2 = CustomConstraint(cons_f2) def cons_f3(m): return RationalQ(m) cons3 = CustomConstraint(cons_f3) def cons_f4(m, n): return RationalQ(m, n) cons4 = CustomConstraint(cons_f4) def cons_f5(m, n): return GreaterEqual(-m + n, S(0)) cons5 = CustomConstraint(cons_f5) def cons_f6(a, x): return FreeQ(a, x) cons6 = CustomConstraint(cons_f6) def cons_f7(m, n, p): return RationalQ(m, n, p) cons7 = CustomConstraint(cons_f7) def cons_f8(m, p): return GreaterEqual(-m + p, S(0)) cons8 = CustomConstraint(cons_f8) pattern1 = Pattern(UtilityOperator(a_**m_*WC('u', S(1)) + b_*WC('v', S(1)), x_), cons1, cons2, cons3) def replacement1(v, x, a, u, m, b): return If(Greater(m, S(1)), RemoveContentAux(a**(m + S(-1))*u - v, x), RemoveContentAux(-a**(-m + S(1))*v + u, x)) rule1 = ReplacementRule(pattern1, replacement1) pattern2 = Pattern(UtilityOperator(a_**WC('m', S(1))*WC('u', S(1)) + a_**WC('n', S(1))*WC('v', S(1)), x_), cons6, cons4, cons5) def replacement2(n, v, x, u, m, a): return RemoveContentAux(a**(-m + n)*v + u, x) rule2 = ReplacementRule(pattern2, replacement2) pattern3 = Pattern(UtilityOperator(a_**WC('m', S(1))*WC('u', S(1)) + a_**WC('n', S(1))*WC('v', S(1)) + a_**WC('p', S(1))*WC('w', S(1)), x_), cons6, cons7, cons5, cons8) def replacement3(n, v, x, p, u, w, m, a): return RemoveContentAux(a**(-m + n)*v + a**(-m + p)*w + u, x) rule3 = ReplacementRule(pattern3, replacement3) pattern4 = Pattern(UtilityOperator(u_, x_)) def replacement4(u, x): return If(And(SumQ(u), NegQ(First(u))), -u, u) rule4 = ReplacementRule(pattern4, replacement4) return [rule1, rule2, rule3, rule4, ] IntHide = Int Log = rubi_log Null = None if matchpy: RemoveContentAux_replacer = ManyToOneReplacer(* _RemoveContentAux()) ExpandIntegrand_rules = _ExpandIntegrand() TrigSimplifyAux_replacer = _TrigSimplifyAux() SimplifyAntiderivative_replacer = _SimplifyAntiderivative() SimplifyAntiderivativeSum_replacer = _SimplifyAntiderivativeSum() FixSimplify_rules = _FixSimplify() SimpFixFactor_replacer = _SimpFixFactor()
ad2bd192cd3f977ea814eb3c315abb8e0ddd9eb3b631348aac176d65ee63a138
from sympy.external import import_module matchpy = import_module("matchpy") from sympy.utilities.decorator import doctest_depends_on from sympy.core.symbol import Symbol from sympy.utilities.matchpy_connector import Wildcard @doctest_depends_on(modules=('matchpy',)) class matchpyWC(Wildcard, Symbol): def __init__(self, min_length, fixed_size, variable_name=None, optional=None, **assumptions): Wildcard.__init__(self, min_length, fixed_size, str(variable_name), optional) def __new__(cls, min_length, fixed_size, variable_name=None, optional=None, **assumptions): cls._sanitize(assumptions, cls) return matchpyWC.__xnew__(cls, min_length, fixed_size, variable_name, optional, **assumptions) def __getnewargs__(self): return (self.min_count, self.fixed_size, self.variable_name, self.optional) @staticmethod def __xnew__(cls, min_length, fixed_size, variable_name=None, optional=None, **assumptions): obj = Symbol.__xnew__(cls, variable_name, **assumptions) return obj def _hashable_content(self): if self.optional: return super()._hashable_content() + (self.min_count, self.fixed_size, self.variable_name, self.optional) else: return super()._hashable_content() + (self.min_count, self.fixed_size, self.variable_name) @doctest_depends_on(modules=('matchpy',)) def WC(variable_name=None, optional=None, **assumptions): return matchpyWC(1, True, variable_name, optional)
05c1257e15af23465da2b3bf1a482b5e0866caaf323152c654f32508b410c3ed
from sympy.concrete.summations import Sum from sympy.core.add import Add from sympy.core.function import (Derivative, Function, diff) from sympy.core.numbers import (I, Rational, pi) from sympy.core.relational import Ne from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.exponential import (LambertW, exp, log) from sympy.functions.elementary.hyperbolic import (asinh, cosh, sinh, tanh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, tan) from sympy.functions.special.bessel import (besselj, besselk, bessely, jn) from sympy.functions.special.error_functions import erf from sympy.integrals.integrals import Integral from sympy.simplify.ratsimp import ratsimp from sympy.simplify.simplify import simplify from sympy.integrals.heurisch import components, heurisch, heurisch_wrapper from sympy.testing.pytest import XFAIL, skip, slow, ON_TRAVIS from sympy.integrals.integrals import integrate x, y, z, nu = symbols('x,y,z,nu') f = Function('f') def test_components(): assert components(x*y, x) == {x} assert components(1/(x + y), x) == {x} assert components(sin(x), x) == {sin(x), x} assert components(sin(x)*sqrt(log(x)), x) == \ {log(x), sin(x), sqrt(log(x)), x} assert components(x*sin(exp(x)*y), x) == \ {sin(y*exp(x)), x, exp(x)} assert components(x**Rational(17, 54)/sqrt(sin(x)), x) == \ {sin(x), x**Rational(1, 54), sqrt(sin(x)), x} assert components(f(x), x) == \ {x, f(x)} assert components(Derivative(f(x), x), x) == \ {x, f(x), Derivative(f(x), x)} assert components(f(x)*diff(f(x), x), x) == \ {x, f(x), Derivative(f(x), x), Derivative(f(x), x)} def test_issue_10680(): assert isinstance(integrate(x**log(x**log(x**log(x))),x), Integral) def test_issue_21166(): assert integrate(sin(x/sqrt(abs(x))), (x, -1, 1)) == 0 def test_heurisch_polynomials(): assert heurisch(1, x) == x assert heurisch(x, x) == x**2/2 assert heurisch(x**17, x) == x**18/18 # For coverage assert heurisch_wrapper(y, x) == y*x def test_heurisch_fractions(): assert heurisch(1/x, x) == log(x) assert heurisch(1/(2 + x), x) == log(x + 2) assert heurisch(1/(x + sin(y)), x) == log(x + sin(y)) # Up to a constant, where C = pi*I*Rational(5, 12), Mathematica gives identical # result in the first case. The difference is because SymPy changes # signs of expressions without any care. # XXX ^ ^ ^ is this still correct? assert heurisch(5*x**5/( 2*x**6 - 5), x) in [5*log(2*x**6 - 5) / 12, 5*log(-2*x**6 + 5) / 12] assert heurisch(5*x**5/(2*x**6 + 5), x) == 5*log(2*x**6 + 5) / 12 assert heurisch(1/x**2, x) == -1/x assert heurisch(-1/x**5, x) == 1/(4*x**4) def test_heurisch_log(): assert heurisch(log(x), x) == x*log(x) - x assert heurisch(log(3*x), x) == -x + x*log(3) + x*log(x) assert heurisch(log(x**2), x) in [x*log(x**2) - 2*x, 2*x*log(x) - 2*x] def test_heurisch_exp(): assert heurisch(exp(x), x) == exp(x) assert heurisch(exp(-x), x) == -exp(-x) assert heurisch(exp(17*x), x) == exp(17*x) / 17 assert heurisch(x*exp(x), x) == x*exp(x) - exp(x) assert heurisch(x*exp(x**2), x) == exp(x**2) / 2 assert heurisch(exp(-x**2), x) is None assert heurisch(2**x, x) == 2**x/log(2) assert heurisch(x*2**x, x) == x*2**x/log(2) - 2**x*log(2)**(-2) assert heurisch(Integral(x**z*y, (y, 1, 2), (z, 2, 3)).function, x) == (x*x**z*y)/(z+1) assert heurisch(Sum(x**z, (z, 1, 2)).function, z) == x**z/log(x) def test_heurisch_trigonometric(): assert heurisch(sin(x), x) == -cos(x) assert heurisch(pi*sin(x) + 1, x) == x - pi*cos(x) assert heurisch(cos(x), x) == sin(x) assert heurisch(tan(x), x) in [ log(1 + tan(x)**2)/2, log(tan(x) + I) + I*x, log(tan(x) - I) - I*x, ] assert heurisch(sin(x)*sin(y), x) == -cos(x)*sin(y) assert heurisch(sin(x)*sin(y), y) == -cos(y)*sin(x) # gives sin(x) in answer when run via setup.py and cos(x) when run via py.test assert heurisch(sin(x)*cos(x), x) in [sin(x)**2 / 2, -cos(x)**2 / 2] assert heurisch(cos(x)/sin(x), x) == log(sin(x)) assert heurisch(x*sin(7*x), x) == sin(7*x) / 49 - x*cos(7*x) / 7 assert heurisch(1/pi/4 * x**2*cos(x), x) == 1/pi/4*(x**2*sin(x) - 2*sin(x) + 2*x*cos(x)) assert heurisch(acos(x/4) * asin(x/4), x) == 2*x - (sqrt(16 - x**2))*asin(x/4) \ + (sqrt(16 - x**2))*acos(x/4) + x*asin(x/4)*acos(x/4) assert heurisch(sin(x)/(cos(x)**2+1), x) == -atan(cos(x)) #fixes issue 13723 assert heurisch(1/(cos(x)+2), x) == 2*sqrt(3)*atan(sqrt(3)*tan(x/2)/3)/3 assert heurisch(2*sin(x)*cos(x)/(sin(x)**4 + 1), x) == atan(sqrt(2)*sin(x) - 1) - atan(sqrt(2)*sin(x) + 1) assert heurisch(1/cosh(x), x) == 2*atan(tanh(x/2)) def test_heurisch_hyperbolic(): assert heurisch(sinh(x), x) == cosh(x) assert heurisch(cosh(x), x) == sinh(x) assert heurisch(x*sinh(x), x) == x*cosh(x) - sinh(x) assert heurisch(x*cosh(x), x) == x*sinh(x) - cosh(x) assert heurisch( x*asinh(x/2), x) == x**2*asinh(x/2)/2 + asinh(x/2) - x*sqrt(4 + x**2)/4 def test_heurisch_mixed(): assert heurisch(sin(x)*exp(x), x) == exp(x)*sin(x)/2 - exp(x)*cos(x)/2 assert heurisch(sin(x/sqrt(-x)), x) == 2*x*cos(x/sqrt(-x))/sqrt(-x) - 2*sin(x/sqrt(-x)) def test_heurisch_radicals(): assert heurisch(1/sqrt(x), x) == 2*sqrt(x) assert heurisch(1/sqrt(x)**3, x) == -2/sqrt(x) assert heurisch(sqrt(x)**3, x) == 2*sqrt(x)**5/5 assert heurisch(sin(x)*sqrt(cos(x)), x) == -2*sqrt(cos(x))**3/3 y = Symbol('y') assert heurisch(sin(y*sqrt(x)), x) == 2/y**2*sin(y*sqrt(x)) - \ 2*sqrt(x)*cos(y*sqrt(x))/y assert heurisch_wrapper(sin(y*sqrt(x)), x) == Piecewise( (-2*sqrt(x)*cos(sqrt(x)*y)/y + 2*sin(sqrt(x)*y)/y**2, Ne(y, 0)), (0, True)) y = Symbol('y', positive=True) assert heurisch_wrapper(sin(y*sqrt(x)), x) == 2/y**2*sin(y*sqrt(x)) - \ 2*sqrt(x)*cos(y*sqrt(x))/y def test_heurisch_special(): assert heurisch(erf(x), x) == x*erf(x) + exp(-x**2)/sqrt(pi) assert heurisch(exp(-x**2)*erf(x), x) == sqrt(pi)*erf(x)**2 / 4 def test_heurisch_symbolic_coeffs(): assert heurisch(1/(x + y), x) == log(x + y) assert heurisch(1/(x + sqrt(2)), x) == log(x + sqrt(2)) assert simplify(diff(heurisch(log(x + y + z), y), y)) == log(x + y + z) def test_heurisch_symbolic_coeffs_1130(): y = Symbol('y') assert heurisch_wrapper(1/(x**2 + y), x) == Piecewise( (log(x - sqrt(-y))/(2*sqrt(-y)) - log(x + sqrt(-y))/(2*sqrt(-y)), Ne(y, 0)), (-1/x, True)) y = Symbol('y', positive=True) assert heurisch_wrapper(1/(x**2 + y), x) == (atan(x/sqrt(y))/sqrt(y)) def test_heurisch_hacking(): assert heurisch(sqrt(1 + 7*x**2), x, hints=[]) == \ x*sqrt(1 + 7*x**2)/2 + sqrt(7)*asinh(sqrt(7)*x)/14 assert heurisch(sqrt(1 - 7*x**2), x, hints=[]) == \ x*sqrt(1 - 7*x**2)/2 + sqrt(7)*asin(sqrt(7)*x)/14 assert heurisch(1/sqrt(1 + 7*x**2), x, hints=[]) == \ sqrt(7)*asinh(sqrt(7)*x)/7 assert heurisch(1/sqrt(1 - 7*x**2), x, hints=[]) == \ sqrt(7)*asin(sqrt(7)*x)/7 assert heurisch(exp(-7*x**2), x, hints=[]) == \ sqrt(7*pi)*erf(sqrt(7)*x)/14 assert heurisch(1/sqrt(9 - 4*x**2), x, hints=[]) == \ asin(x*Rational(2, 3))/2 assert heurisch(1/sqrt(9 + 4*x**2), x, hints=[]) == \ asinh(x*Rational(2, 3))/2 def test_heurisch_function(): assert heurisch(f(x), x) is None @XFAIL def test_heurisch_function_derivative(): # TODO: it looks like this used to work just by coincindence and # thanks to sloppy implementation. Investigate why this used to # work at all and if support for this can be restored. df = diff(f(x), x) assert heurisch(f(x)*df, x) == f(x)**2/2 assert heurisch(f(x)**2*df, x) == f(x)**3/3 assert heurisch(df/f(x), x) == log(f(x)) def test_heurisch_wrapper(): f = 1/(y + x) assert heurisch_wrapper(f, x) == log(x + y) f = 1/(y - x) assert heurisch_wrapper(f, x) == -log(x - y) f = 1/((y - x)*(y + x)) assert heurisch_wrapper(f, x) == Piecewise( (-log(x - y)/(2*y) + log(x + y)/(2*y), Ne(y, 0)), (1/x, True)) # issue 6926 f = sqrt(x**2/((y - x)*(y + x))) assert heurisch_wrapper(f, x) == x*sqrt(-x**2/(x**2 - y**2)) \ - y**2*sqrt(-x**2/(x**2 - y**2))/x def test_issue_3609(): assert heurisch(1/(x * (1 + log(x)**2)), x) == atan(log(x)) ### These are examples from the Poor Man's Integrator ### http://www-sop.inria.fr/cafe/Manuel.Bronstein/pmint/examples/ def test_pmint_rat(): # TODO: heurisch() is off by a constant: -3/4. Possibly different permutation # would give the optimal result? def drop_const(expr, x): if expr.is_Add: return Add(*[ arg for arg in expr.args if arg.has(x) ]) else: return expr f = (x**7 - 24*x**4 - 4*x**2 + 8*x - 8)/(x**8 + 6*x**6 + 12*x**4 + 8*x**2) g = (4 + 8*x**2 + 6*x + 3*x**3)/(x**5 + 4*x**3 + 4*x) + log(x) assert drop_const(ratsimp(heurisch(f, x)), x) == g def test_pmint_trig(): f = (x - tan(x)) / tan(x)**2 + tan(x) g = -x**2/2 - x/tan(x) + log(tan(x)**2 + 1)/2 assert heurisch(f, x) == g @slow # 8 seconds on 3.4 GHz def test_pmint_logexp(): if ON_TRAVIS: # See https://github.com/sympy/sympy/pull/12795 skip("Too slow for travis.") f = (1 + x + x*exp(x))*(x + log(x) + exp(x) - 1)/(x + log(x) + exp(x))**2/x g = log(x + exp(x) + log(x)) + 1/(x + exp(x) + log(x)) assert ratsimp(heurisch(f, x)) == g def test_pmint_erf(): f = exp(-x**2)*erf(x)/(erf(x)**3 - erf(x)**2 - erf(x) + 1) g = sqrt(pi)*log(erf(x) - 1)/8 - sqrt(pi)*log(erf(x) + 1)/8 - sqrt(pi)/(4*erf(x) - 4) assert ratsimp(heurisch(f, x)) == g def test_pmint_LambertW(): f = LambertW(x) g = x*LambertW(x) - x + x/LambertW(x) assert heurisch(f, x) == g def test_pmint_besselj(): f = besselj(nu + 1, x)/besselj(nu, x) g = nu*log(x) - log(besselj(nu, x)) assert heurisch(f, x) == g f = (nu*besselj(nu, x) - x*besselj(nu + 1, x))/x g = besselj(nu, x) assert heurisch(f, x) == g f = jn(nu + 1, x)/jn(nu, x) g = nu*log(x) - log(jn(nu, x)) assert heurisch(f, x) == g @slow def test_pmint_bessel_products(): # Note: Derivatives of Bessel functions have many forms. # Recurrence relations are needed for comparisons. if ON_TRAVIS: skip("Too slow for travis.") f = x*besselj(nu, x)*bessely(nu, 2*x) g = -2*x*besselj(nu, x)*bessely(nu - 1, 2*x)/3 + x*besselj(nu - 1, x)*bessely(nu, 2*x)/3 assert heurisch(f, x) == g f = x*besselj(nu, x)*besselk(nu, 2*x) g = -2*x*besselj(nu, x)*besselk(nu - 1, 2*x)/5 - x*besselj(nu - 1, x)*besselk(nu, 2*x)/5 assert heurisch(f, x) == g @slow # 110 seconds on 3.4 GHz def test_pmint_WrightOmega(): if ON_TRAVIS: skip("Too slow for travis.") def omega(x): return LambertW(exp(x)) f = (1 + omega(x) * (2 + cos(omega(x)) * (x + omega(x))))/(1 + omega(x))/(x + omega(x)) g = log(x + LambertW(exp(x))) + sin(LambertW(exp(x))) assert heurisch(f, x) == g def test_RR(): # Make sure the algorithm does the right thing if the ring is RR. See # issue 8685. assert heurisch(sqrt(1 + 0.25*x**2), x, hints=[]) == \ 0.5*x*sqrt(0.25*x**2 + 1) + 1.0*asinh(0.5*x) # TODO: convert the rest of PMINT tests: # Airy functions # f = (x - AiryAi(x)*AiryAi(1, x)) / (x**2 - AiryAi(x)**2) # g = Rational(1,2)*ln(x + AiryAi(x)) + Rational(1,2)*ln(x - AiryAi(x)) # f = x**2 * AiryAi(x) # g = -AiryAi(x) + AiryAi(1, x)*x # Whittaker functions # f = WhittakerW(mu + 1, nu, x) / (WhittakerW(mu, nu, x) * x) # g = x/2 - mu*ln(x) - ln(WhittakerW(mu, nu, x)) def test_issue_22527(): t, R = symbols(r't R') z = Function('z')(t) def f(x): return x/sqrt(R**2 - x**2) Uz = integrate(f(z), z) Ut = integrate(f(t), t) assert Ut == Uz.subs(z, t)
21c0fd9a06751f7f12e16691187e915ed69460479842c1d8fa6f5b3e40406338
from sympy.concrete.summations import (Sum, summation) from sympy.core.add import Add from sympy.core.containers import Tuple from sympy.core.expr import Expr from sympy.core.function import (Derivative, Function, Lambda, diff) from sympy.core import EulerGamma from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi) from sympy.core.relational import (Eq, Ne) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.core.sympify import sympify from sympy.functions.elementary.complexes import (Abs, im, polar_lift, re, sign) from sympy.functions.elementary.exponential import (LambertW, exp, exp_polar, log) from sympy.functions.elementary.hyperbolic import (acosh, asinh, cosh, sinh, tanh) from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt) from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, sinc, tan) from sympy.functions.special.delta_functions import DiracDelta from sympy.functions.special.error_functions import (Ci, Ei, Si, erf, erfc, erfi, fresnelc, li) from sympy.functions.special.gamma_functions import (gamma, polygamma) from sympy.functions.special.hyper import (hyper, meijerg) from sympy.functions.special.singularity_functions import SingularityFunction from sympy.functions.special.zeta_functions import lerchphi from sympy.integrals.integrals import integrate from sympy.logic.boolalg import And from sympy.matrices.dense import Matrix from sympy.polys.polytools import (Poly, factor) from sympy.printing.str import sstr from sympy.series.order import O from sympy.sets.sets import Interval from sympy.simplify.gammasimp import gammasimp from sympy.simplify.simplify import simplify from sympy.simplify.trigsimp import trigsimp from sympy.tensor.indexed import (Idx, IndexedBase) from sympy.core.expr import unchanged from sympy.functions.elementary.integers import floor from sympy.integrals.integrals import Integral from sympy.integrals.risch import NonElementaryIntegral from sympy.physics import units from sympy.testing.pytest import (raises, slow, skip, ON_TRAVIS, warns_deprecated_sympy) from sympy.core.random import verify_numerically x, y, a, t, x_1, x_2, z, s, b = symbols('x y a t x_1 x_2 z s b') n = Symbol('n', integer=True) f = Function('f') def NS(e, n=15, **options): return sstr(sympify(e).evalf(n, **options), full_prec=True) def test_poly_deprecated(): p = Poly(2*x, x) assert p.integrate(x) == Poly(x**2, x, domain='QQ') with warns_deprecated_sympy(): integrate(p, x) with warns_deprecated_sympy(): Integral(p, (x,)) @slow def test_principal_value(): g = 1 / x assert Integral(g, (x, -oo, oo)).principal_value() == 0 assert Integral(g, (y, -oo, oo)).principal_value() == oo * sign(1 / x) raises(ValueError, lambda: Integral(g, (x)).principal_value()) raises(ValueError, lambda: Integral(g).principal_value()) l = 1 / ((x ** 3) - 1) assert Integral(l, (x, -oo, oo)).principal_value().together() == -sqrt(3)*pi/3 raises(ValueError, lambda: Integral(l, (x, -oo, 1)).principal_value()) d = 1 / (x ** 2 - 1) assert Integral(d, (x, -oo, oo)).principal_value() == 0 assert Integral(d, (x, -2, 2)).principal_value() == -log(3) v = x / (x ** 2 - 1) assert Integral(v, (x, -oo, oo)).principal_value() == 0 assert Integral(v, (x, -2, 2)).principal_value() == 0 s = x ** 2 / (x ** 2 - 1) assert Integral(s, (x, -oo, oo)).principal_value() is oo assert Integral(s, (x, -2, 2)).principal_value() == -log(3) + 4 f = 1 / ((x ** 2 - 1) * (1 + x ** 2)) assert Integral(f, (x, -oo, oo)).principal_value() == -pi / 2 assert Integral(f, (x, -2, 2)).principal_value() == -atan(2) - log(3) / 2 def diff_test(i): """Return the set of symbols, s, which were used in testing that i.diff(s) agrees with i.doit().diff(s). If there is an error then the assertion will fail, causing the test to fail.""" syms = i.free_symbols for s in syms: assert (i.diff(s).doit() - i.doit().diff(s)).expand() == 0 return syms def test_improper_integral(): assert integrate(log(x), (x, 0, 1)) == -1 assert integrate(x**(-2), (x, 1, oo)) == 1 assert integrate(1/(1 + exp(x)), (x, 0, oo)) == log(2) def test_constructor(): # this is shared by Sum, so testing Integral's constructor # is equivalent to testing Sum's s1 = Integral(n, n) assert s1.limits == (Tuple(n),) s2 = Integral(n, (n,)) assert s2.limits == (Tuple(n),) s3 = Integral(Sum(x, (x, 1, y))) assert s3.limits == (Tuple(y),) s4 = Integral(n, Tuple(n,)) assert s4.limits == (Tuple(n),) s5 = Integral(n, (n, Interval(1, 2))) assert s5.limits == (Tuple(n, 1, 2),) # Testing constructor with inequalities: s6 = Integral(n, n > 10) assert s6.limits == (Tuple(n, 10, oo),) s7 = Integral(n, (n > 2) & (n < 5)) assert s7.limits == (Tuple(n, 2, 5),) def test_basics(): assert Integral(0, x) != 0 assert Integral(x, (x, 1, 1)) != 0 assert Integral(oo, x) != oo assert Integral(S.NaN, x) is S.NaN assert diff(Integral(y, y), x) == 0 assert diff(Integral(x, (x, 0, 1)), x) == 0 assert diff(Integral(x, x), x) == x assert diff(Integral(t, (t, 0, x)), x) == x e = (t + 1)**2 assert diff(integrate(e, (t, 0, x)), x) == \ diff(Integral(e, (t, 0, x)), x).doit().expand() == \ ((1 + x)**2).expand() assert diff(integrate(e, (t, 0, x)), t) == \ diff(Integral(e, (t, 0, x)), t) == 0 assert diff(integrate(e, (t, 0, x)), a) == \ diff(Integral(e, (t, 0, x)), a) == 0 assert diff(integrate(e, t), a) == diff(Integral(e, t), a) == 0 assert integrate(e, (t, a, x)).diff(x) == \ Integral(e, (t, a, x)).diff(x).doit().expand() assert Integral(e, (t, a, x)).diff(x).doit() == ((1 + x)**2) assert integrate(e, (t, x, a)).diff(x).doit() == (-(1 + x)**2).expand() assert integrate(t**2, (t, x, 2*x)).diff(x) == 7*x**2 assert Integral(x, x).atoms() == {x} assert Integral(f(x), (x, 0, 1)).atoms() == {S.Zero, S.One, x} assert diff_test(Integral(x, (x, 3*y))) == {y} assert diff_test(Integral(x, (a, 3*y))) == {x, y} assert integrate(x, (x, oo, oo)) == 0 #issue 8171 assert integrate(x, (x, -oo, -oo)) == 0 # sum integral of terms assert integrate(y + x + exp(x), x) == x*y + x**2/2 + exp(x) assert Integral(x).is_commutative n = Symbol('n', commutative=False) assert Integral(n + x, x).is_commutative is False def test_diff_wrt(): class Test(Expr): _diff_wrt = True is_commutative = True t = Test() assert integrate(t + 1, t) == t**2/2 + t assert integrate(t + 1, (t, 0, 1)) == Rational(3, 2) raises(ValueError, lambda: integrate(x + 1, x + 1)) raises(ValueError, lambda: integrate(x + 1, (x + 1, 0, 1))) def test_basics_multiple(): assert diff_test(Integral(x, (x, 3*x, 5*y), (y, x, 2*x))) == {x} assert diff_test(Integral(x, (x, 5*y), (y, x, 2*x))) == {x} assert diff_test(Integral(x, (x, 5*y), (y, y, 2*x))) == {x, y} assert diff_test(Integral(y, y, x)) == {x, y} assert diff_test(Integral(y*x, x, y)) == {x, y} assert diff_test(Integral(x + y, y, (y, 1, x))) == {x} assert diff_test(Integral(x + y, (x, x, y), (y, y, x))) == {x, y} def test_conjugate_transpose(): A, B = symbols("A B", commutative=False) x = Symbol("x", complex=True) p = Integral(A*B, (x,)) assert p.adjoint().doit() == p.doit().adjoint() assert p.conjugate().doit() == p.doit().conjugate() assert p.transpose().doit() == p.doit().transpose() x = Symbol("x", real=True) p = Integral(A*B, (x,)) assert p.adjoint().doit() == p.doit().adjoint() assert p.conjugate().doit() == p.doit().conjugate() assert p.transpose().doit() == p.doit().transpose() def test_integration(): assert integrate(0, (t, 0, x)) == 0 assert integrate(3, (t, 0, x)) == 3*x assert integrate(t, (t, 0, x)) == x**2/2 assert integrate(3*t, (t, 0, x)) == 3*x**2/2 assert integrate(3*t**2, (t, 0, x)) == x**3 assert integrate(1/t, (t, 1, x)) == log(x) assert integrate(-1/t**2, (t, 1, x)) == 1/x - 1 assert integrate(t**2 + 5*t - 8, (t, 0, x)) == x**3/3 + 5*x**2/2 - 8*x assert integrate(x**2, x) == x**3/3 assert integrate((3*t*x)**5, x) == (3*t)**5 * x**6 / 6 b = Symbol("b") c = Symbol("c") assert integrate(a*t, (t, 0, x)) == a*x**2/2 assert integrate(a*t**4, (t, 0, x)) == a*x**5/5 assert integrate(a*t**2 + b*t + c, (t, 0, x)) == a*x**3/3 + b*x**2/2 + c*x def test_multiple_integration(): assert integrate((x**2)*(y**2), (x, 0, 1), (y, -1, 2)) == Rational(1) assert integrate((y**2)*(x**2), x, y) == Rational(1, 9)*(x**3)*(y**3) assert integrate(1/(x + 3)/(1 + x)**3, x) == \ log(3 + x)*Rational(-1, 8) + log(1 + x)*Rational(1, 8) + x/(4 + 8*x + 4*x**2) assert integrate(sin(x*y)*y, (x, 0, 1), (y, 0, 1)) == -sin(1) + 1 def test_issue_3532(): assert integrate(exp(-x), (x, 0, oo)) == 1 def test_issue_3560(): assert integrate(sqrt(x)**3, x) == 2*sqrt(x)**5/5 assert integrate(sqrt(x), x) == 2*sqrt(x)**3/3 assert integrate(1/sqrt(x)**3, x) == -2/sqrt(x) def test_issue_18038(): raises(AttributeError, lambda: integrate((x, x))) def test_integrate_poly(): p = Poly(x + x**2*y + y**3, x, y) with warns_deprecated_sympy(): qx = integrate(p, x) with warns_deprecated_sympy(): qy = integrate(p, y) assert isinstance(qx, Poly) is True assert isinstance(qy, Poly) is True assert qx.gens == (x, y) assert qy.gens == (x, y) assert qx.as_expr() == x**2/2 + x**3*y/3 + x*y**3 assert qy.as_expr() == x*y + x**2*y**2/2 + y**4/4 def test_integrate_poly_defined(): p = Poly(x + x**2*y + y**3, x, y) with warns_deprecated_sympy(): Qx = integrate(p, (x, 0, 1)) with warns_deprecated_sympy(): Qy = integrate(p, (y, 0, pi)) assert isinstance(Qx, Poly) is True assert isinstance(Qy, Poly) is True assert Qx.gens == (y,) assert Qy.gens == (x,) assert Qx.as_expr() == S.Half + y/3 + y**3 assert Qy.as_expr() == pi**4/4 + pi*x + pi**2*x**2/2 def test_integrate_omit_var(): y = Symbol('y') assert integrate(x) == x**2/2 raises(ValueError, lambda: integrate(2)) raises(ValueError, lambda: integrate(x*y)) def test_integrate_poly_accurately(): y = Symbol('y') assert integrate(x*sin(y), x) == x**2*sin(y)/2 # when passed to risch_norman, this will be a CPU hog, so this really # checks, that integrated function is recognized as polynomial assert integrate(x**1000*sin(y), x) == x**1001*sin(y)/1001 def test_issue_3635(): y = Symbol('y') assert integrate(x**2, y) == x**2*y assert integrate(x**2, (y, -1, 1)) == 2*x**2 # works in SymPy and py.test but hangs in `setup.py test` def test_integrate_linearterm_pow(): # check integrate((a*x+b)^c, x) -- issue 3499 y = Symbol('y', positive=True) # TODO: Remove conds='none' below, let the assumption take care of it. assert integrate(x**y, x, conds='none') == x**(y + 1)/(y + 1) assert integrate((exp(y)*x + 1/y)**(1 + sin(y)), x, conds='none') == \ exp(-y)*(exp(y)*x + 1/y)**(2 + sin(y)) / (2 + sin(y)) def test_issue_3618(): assert integrate(pi*sqrt(x), x) == 2*pi*sqrt(x)**3/3 assert integrate(pi*sqrt(x) + E*sqrt(x)**3, x) == \ 2*pi*sqrt(x)**3/3 + 2*E *sqrt(x)**5/5 def test_issue_3623(): assert integrate(cos((n + 1)*x), x) == Piecewise( (sin(x*(n + 1))/(n + 1), Ne(n + 1, 0)), (x, True)) assert integrate(cos((n - 1)*x), x) == Piecewise( (sin(x*(n - 1))/(n - 1), Ne(n - 1, 0)), (x, True)) assert integrate(cos((n + 1)*x) + cos((n - 1)*x), x) == \ Piecewise((sin(x*(n - 1))/(n - 1), Ne(n - 1, 0)), (x, True)) + \ Piecewise((sin(x*(n + 1))/(n + 1), Ne(n + 1, 0)), (x, True)) def test_issue_3664(): n = Symbol('n', integer=True, nonzero=True) assert integrate(-1./2 * x * sin(n * pi * x/2), [x, -2, 0]) == \ 2.0*cos(pi*n)/(pi*n) assert integrate(x * sin(n * pi * x/2) * Rational(-1, 2), [x, -2, 0]) == \ 2*cos(pi*n)/(pi*n) def test_issue_3679(): # definite integration of rational functions gives wrong answers assert NS(Integral(1/(x**2 - 8*x + 17), (x, 2, 4))) == '1.10714871779409' def test_issue_3686(): # remove this when fresnel itegrals are implemented from sympy.core.function import expand_func from sympy.functions.special.error_functions import fresnels assert expand_func(integrate(sin(x**2), x)) == \ sqrt(2)*sqrt(pi)*fresnels(sqrt(2)*x/sqrt(pi))/2 def test_integrate_units(): m = units.m s = units.s assert integrate(x * m/s, (x, 1*s, 5*s)) == 12*m*s def test_transcendental_functions(): assert integrate(LambertW(2*x), x) == \ -x + x*LambertW(2*x) + x/LambertW(2*x) def test_log_polylog(): assert integrate(log(1 - x)/x, (x, 0, 1)) == -pi**2/6 assert integrate(log(x)*(1 - x)**(-1), (x, 0, 1)) == -pi**2/6 def test_issue_3740(): f = 4*log(x) - 2*log(x)**2 fid = diff(integrate(f, x), x) assert abs(f.subs(x, 42).evalf() - fid.subs(x, 42).evalf()) < 1e-10 def test_issue_3788(): assert integrate(1/(1 + x**2), x) == atan(x) def test_issue_3952(): f = sin(x) assert integrate(f, x) == -cos(x) raises(ValueError, lambda: integrate(f, 2*x)) def test_issue_4516(): assert integrate(2**x - 2*x, x) == 2**x/log(2) - x**2 def test_issue_7450(): ans = integrate(exp(-(1 + I)*x), (x, 0, oo)) assert re(ans) == S.Half and im(ans) == Rational(-1, 2) def test_issue_8623(): assert integrate((1 + cos(2*x)) / (3 - 2*cos(2*x)), (x, 0, pi)) == -pi/2 + sqrt(5)*pi/2 assert integrate((1 + cos(2*x))/(3 - 2*cos(2*x))) == -x/2 + sqrt(5)*(atan(sqrt(5)*tan(x)) + \ pi*floor((x - pi/2)/pi))/2 def test_issue_9569(): assert integrate(1 / (2 - cos(x)), (x, 0, pi)) == pi/sqrt(3) assert integrate(1/(2 - cos(x))) == 2*sqrt(3)*(atan(sqrt(3)*tan(x/2)) + pi*floor((x/2 - pi/2)/pi))/3 def test_issue_13733(): s = Symbol('s', positive=True) pz = exp(-(z - y)**2/(2*s*s))/sqrt(2*pi*s*s) pzgx = integrate(pz, (z, x, oo)) assert integrate(pzgx, (x, 0, oo)) == sqrt(2)*s*exp(-y**2/(2*s**2))/(2*sqrt(pi)) + \ y*erf(sqrt(2)*y/(2*s))/2 + y/2 def test_issue_13749(): assert integrate(1 / (2 + cos(x)), (x, 0, pi)) == pi/sqrt(3) assert integrate(1/(2 + cos(x))) == 2*sqrt(3)*(atan(sqrt(3)*tan(x/2)/3) + pi*floor((x/2 - pi/2)/pi))/3 def test_issue_18133(): assert integrate(exp(x)/(1 + x)**2, x) == NonElementaryIntegral(exp(x)/(x + 1)**2, x) def test_issue_21741(): a = Float('3999999.9999999995', precision=53) b = Float('2.5000000000000004e-7', precision=53) r = Piecewise((b*I*exp(-a*I*pi*t*y)*exp(-a*I*pi*x*z)/(pi*x), Ne(1.0*pi*x*exp(a*I*pi*t*y), 0)), (z*exp(-a*I*pi*t*y), True)) fun = E**((-2*I*pi*(z*x+t*y))/(500*10**(-9))) assert integrate(fun, z) == r def test_matrices(): M = Matrix(2, 2, lambda i, j: (i + j + 1)*sin((i + j + 1)*x)) assert integrate(M, x) == Matrix([ [-cos(x), -cos(2*x)], [-cos(2*x), -cos(3*x)], ]) def test_integrate_functions(): # issue 4111 assert integrate(f(x), x) == Integral(f(x), x) assert integrate(f(x), (x, 0, 1)) == Integral(f(x), (x, 0, 1)) assert integrate(f(x)*diff(f(x), x), x) == f(x)**2/2 assert integrate(diff(f(x), x) / f(x), x) == log(f(x)) def test_integrate_derivatives(): assert integrate(Derivative(f(x), x), x) == f(x) assert integrate(Derivative(f(y), y), x) == x*Derivative(f(y), y) assert integrate(Derivative(f(x), x)**2, x) == \ Integral(Derivative(f(x), x)**2, x) def test_transform(): a = Integral(x**2 + 1, (x, -1, 2)) fx = x fy = 3*y + 1 assert a.doit() == a.transform(fx, fy).doit() assert a.transform(fx, fy).transform(fy, fx) == a fx = 3*x + 1 fy = y assert a.transform(fx, fy).transform(fy, fx) == a a = Integral(sin(1/x), (x, 0, 1)) assert a.transform(x, 1/y) == Integral(sin(y)/y**2, (y, 1, oo)) assert a.transform(x, 1/y).transform(y, 1/x) == a a = Integral(exp(-x**2), (x, -oo, oo)) assert a.transform(x, 2*y) == Integral(2*exp(-4*y**2), (y, -oo, oo)) # < 3 arg limit handled properly assert Integral(x, x).transform(x, a*y).doit() == \ Integral(y*a**2, y).doit() _3 = S(3) assert Integral(x, (x, 0, -_3)).transform(x, 1/y).doit() == \ Integral(-1/x**3, (x, -oo, -1/_3)).doit() assert Integral(x, (x, 0, _3)).transform(x, 1/y) == \ Integral(y**(-3), (y, 1/_3, oo)) # issue 8400 i = Integral(x + y, (x, 1, 2), (y, 1, 2)) assert i.transform(x, (x + 2*y, x)).doit() == \ i.transform(x, (x + 2*z, x)).doit() == 3 i = Integral(x, (x, a, b)) assert i.transform(x, 2*s) == Integral(4*s, (s, a/2, b/2)) raises(ValueError, lambda: i.transform(x, 1)) raises(ValueError, lambda: i.transform(x, s*t)) raises(ValueError, lambda: i.transform(x, -s)) raises(ValueError, lambda: i.transform(x, (s, t))) raises(ValueError, lambda: i.transform(2*x, 2*s)) i = Integral(x**2, (x, 1, 2)) raises(ValueError, lambda: i.transform(x**2, s)) am = Symbol('a', negative=True) bp = Symbol('b', positive=True) i = Integral(x, (x, bp, am)) i.transform(x, 2*s) assert i.transform(x, 2*s) == Integral(-4*s, (s, am/2, bp/2)) i = Integral(x, (x, a)) assert i.transform(x, 2*s) == Integral(4*s, (s, a/2)) def test_issue_4052(): f = S.Half*asin(x) + x*sqrt(1 - x**2)/2 assert integrate(cos(asin(x)), x) == f assert integrate(sin(acos(x)), x) == f @slow def test_evalf_integrals(): assert NS(Integral(x, (x, 2, 5)), 15) == '10.5000000000000' gauss = Integral(exp(-x**2), (x, -oo, oo)) assert NS(gauss, 15) == '1.77245385090552' assert NS(gauss**2 - pi + E*Rational( 1, 10**20), 15) in ('2.71828182845904e-20', '2.71828182845905e-20') # A monster of an integral from http://mathworld.wolfram.com/DefiniteIntegral.html t = Symbol('t') a = 8*sqrt(3)/(1 + 3*t**2) b = 16*sqrt(2)*(3*t + 1)*sqrt(4*t**2 + t + 1)**3 c = (3*t**2 + 1)*(11*t**2 + 2*t + 3)**2 d = sqrt(2)*(249*t**2 + 54*t + 65)/(11*t**2 + 2*t + 3)**2 f = a - b/c - d assert NS(Integral(f, (t, 0, 1)), 50) == \ NS((3*sqrt(2) - 49*pi + 162*atan(sqrt(2)))/12, 50) # http://mathworld.wolfram.com/VardisIntegral.html assert NS(Integral(log(log(1/x))/(1 + x + x**2), (x, 0, 1)), 15) == \ NS('pi/sqrt(3) * log(2*pi**(5/6) / gamma(1/6))', 15) # http://mathworld.wolfram.com/AhmedsIntegral.html assert NS(Integral(atan(sqrt(x**2 + 2))/(sqrt(x**2 + 2)*(x**2 + 1)), (x, 0, 1)), 15) == NS(5*pi**2/96, 15) # http://mathworld.wolfram.com/AbelsIntegral.html assert NS(Integral(x/((exp(pi*x) - exp( -pi*x))*(x**2 + 1)), (x, 0, oo)), 15) == NS('log(2)/2-1/4', 15) # Complex part trimming # http://mathworld.wolfram.com/VardisIntegral.html assert NS(Integral(log(log(sin(x)/cos(x))), (x, pi/4, pi/2)), 15, chop=True) == \ NS('pi/4*log(4*pi**3/gamma(1/4)**4)', 15) # # Endpoints causing trouble (rounding error in integration points -> complex log) assert NS( 2 + Integral(log(2*cos(x/2)), (x, -pi, pi)), 17, chop=True) == NS(2, 17) assert NS( 2 + Integral(log(2*cos(x/2)), (x, -pi, pi)), 20, chop=True) == NS(2, 20) assert NS( 2 + Integral(log(2*cos(x/2)), (x, -pi, pi)), 22, chop=True) == NS(2, 22) # Needs zero handling assert NS(pi - 4*Integral( 'sqrt(1-x**2)', (x, 0, 1)), 15, maxn=30, chop=True) in ('0.0', '0') # Oscillatory quadrature a = Integral(sin(x)/x**2, (x, 1, oo)).evalf(maxn=15) assert 0.49 < a < 0.51 assert NS( Integral(sin(x)/x**2, (x, 1, oo)), quad='osc') == '0.504067061906928' assert NS(Integral( cos(pi*x + 1)/x, (x, -oo, -1)), quad='osc') == '0.276374705640365' # indefinite integrals aren't evaluated assert NS(Integral(x, x)) == 'Integral(x, x)' assert NS(Integral(x, (x, y))) == 'Integral(x, (x, y))' def test_evalf_issue_939(): # https://github.com/sympy/sympy/issues/4038 # The output form of an integral may differ by a step function between # revisions, making this test a bit useless. This can't be said about # other two tests. For now, all values of this evaluation are used here, # but in future this should be reconsidered. assert NS(integrate(1/(x**5 + 1), x).subs(x, 4), chop=True) in \ ['-0.000976138910649103', '0.965906660135753', '1.93278945918216'] assert NS(Integral(1/(x**5 + 1), (x, 2, 4))) == '0.0144361088886740' assert NS( integrate(1/(x**5 + 1), (x, 2, 4)), chop=True) == '0.0144361088886740' def test_double_previously_failing_integrals(): # Double integrals not implemented <- Sure it is! res = integrate(sqrt(x) + x*y, (x, 1, 2), (y, -1, 1)) # Old numerical test assert NS(res, 15) == '2.43790283299492' # Symbolic test assert res == Rational(-4, 3) + 8*sqrt(2)/3 # double integral + zero detection assert integrate(sin(x + x*y), (x, -1, 1), (y, -1, 1)) is S.Zero def test_integrate_SingularityFunction(): in_1 = SingularityFunction(x, a, 3) + SingularityFunction(x, 5, -1) out_1 = SingularityFunction(x, a, 4)/4 + SingularityFunction(x, 5, 0) assert integrate(in_1, x) == out_1 in_2 = 10*SingularityFunction(x, 4, 0) - 5*SingularityFunction(x, -6, -2) out_2 = 10*SingularityFunction(x, 4, 1) - 5*SingularityFunction(x, -6, -1) assert integrate(in_2, x) == out_2 in_3 = 2*x**2*y -10*SingularityFunction(x, -4, 7) - 2*SingularityFunction(y, 10, -2) out_3_1 = 2*x**3*y/3 - 2*x*SingularityFunction(y, 10, -2) - 5*SingularityFunction(x, -4, 8)/4 out_3_2 = x**2*y**2 - 10*y*SingularityFunction(x, -4, 7) - 2*SingularityFunction(y, 10, -1) assert integrate(in_3, x) == out_3_1 assert integrate(in_3, y) == out_3_2 assert unchanged(Integral, in_3, (x,)) assert Integral(in_3, x) == Integral(in_3, (x,)) assert Integral(in_3, x).doit() == out_3_1 in_4 = 10*SingularityFunction(x, -4, 7) - 2*SingularityFunction(x, 10, -2) out_4 = 5*SingularityFunction(x, -4, 8)/4 - 2*SingularityFunction(x, 10, -1) assert integrate(in_4, (x, -oo, x)) == out_4 assert integrate(SingularityFunction(x, 5, -1), x) == SingularityFunction(x, 5, 0) assert integrate(SingularityFunction(x, 0, -1), (x, -oo, oo)) == 1 assert integrate(5*SingularityFunction(x, 5, -1), (x, -oo, oo)) == 5 assert integrate(SingularityFunction(x, 5, -1) * f(x), (x, -oo, oo)) == f(5) def test_integrate_DiracDelta(): # This is here to check that deltaintegrate is being called, but also # to test definite integrals. More tests are in test_deltafunctions.py assert integrate(DiracDelta(x) * f(x), (x, -oo, oo)) == f(0) assert integrate(DiracDelta(x)**2, (x, -oo, oo)) == DiracDelta(0) # issue 4522 assert integrate(integrate((4 - 4*x + x*y - 4*y) * \ DiracDelta(x)*DiracDelta(y - 1), (x, 0, 1)), (y, 0, 1)) == 0 # issue 5729 p = exp(-(x**2 + y**2))/pi assert integrate(p*DiracDelta(x - 10*y), (x, -oo, oo), (y, -oo, oo)) == \ integrate(p*DiracDelta(x - 10*y), (y, -oo, oo), (x, -oo, oo)) == \ integrate(p*DiracDelta(10*x - y), (x, -oo, oo), (y, -oo, oo)) == \ integrate(p*DiracDelta(10*x - y), (y, -oo, oo), (x, -oo, oo)) == \ 1/sqrt(101*pi) def test_integrate_returns_piecewise(): assert integrate(x**y, x) == Piecewise( (x**(y + 1)/(y + 1), Ne(y, -1)), (log(x), True)) assert integrate(x**y, y) == Piecewise( (x**y/log(x), Ne(log(x), 0)), (y, True)) assert integrate(exp(n*x), x) == Piecewise( (exp(n*x)/n, Ne(n, 0)), (x, True)) assert integrate(x*exp(n*x), x) == Piecewise( ((n*x - 1)*exp(n*x)/n**2, Ne(n**2, 0)), (x**2/2, True)) assert integrate(x**(n*y), x) == Piecewise( (x**(n*y + 1)/(n*y + 1), Ne(n*y, -1)), (log(x), True)) assert integrate(x**(n*y), y) == Piecewise( (x**(n*y)/(n*log(x)), Ne(n*log(x), 0)), (y, True)) assert integrate(cos(n*x), x) == Piecewise( (sin(n*x)/n, Ne(n, 0)), (x, True)) assert integrate(cos(n*x)**2, x) == Piecewise( ((n*x/2 + sin(n*x)*cos(n*x)/2)/n, Ne(n, 0)), (x, True)) assert integrate(x*cos(n*x), x) == Piecewise( (x*sin(n*x)/n + cos(n*x)/n**2, Ne(n, 0)), (x**2/2, True)) assert integrate(sin(n*x), x) == Piecewise( (-cos(n*x)/n, Ne(n, 0)), (0, True)) assert integrate(sin(n*x)**2, x) == Piecewise( ((n*x/2 - sin(n*x)*cos(n*x)/2)/n, Ne(n, 0)), (0, True)) assert integrate(x*sin(n*x), x) == Piecewise( (-x*cos(n*x)/n + sin(n*x)/n**2, Ne(n, 0)), (0, True)) assert integrate(exp(x*y), (x, 0, z)) == Piecewise( (exp(y*z)/y - 1/y, (y > -oo) & (y < oo) & Ne(y, 0)), (z, True)) def test_integrate_max_min(): x = symbols('x', real=True) assert integrate(Min(x, 2), (x, 0, 3)) == 4 assert integrate(Max(x**2, x**3), (x, 0, 2)) == Rational(49, 12) assert integrate(Min(exp(x), exp(-x))**2, x) == Piecewise( \ (exp(2*x)/2, x <= 0), (1 - exp(-2*x)/2, True)) # issue 7907 c = symbols('c', extended_real=True) int1 = integrate(Max(c, x)*exp(-x**2), (x, -oo, oo)) int2 = integrate(c*exp(-x**2), (x, -oo, c)) int3 = integrate(x*exp(-x**2), (x, c, oo)) assert int1 == int2 + int3 == sqrt(pi)*c*erf(c)/2 + \ sqrt(pi)*c/2 + exp(-c**2)/2 def test_integrate_Abs_sign(): assert integrate(Abs(x), (x, -2, 1)) == Rational(5, 2) assert integrate(Abs(x), (x, 0, 1)) == S.Half assert integrate(Abs(x + 1), (x, 0, 1)) == Rational(3, 2) assert integrate(Abs(x**2 - 1), (x, -2, 2)) == 4 assert integrate(Abs(x**2 - 3*x), (x, -15, 15)) == 2259 assert integrate(sign(x), (x, -1, 2)) == 1 assert integrate(sign(x)*sin(x), (x, -pi, pi)) == 4 assert integrate(sign(x - 2) * x**2, (x, 0, 3)) == Rational(11, 3) t, s = symbols('t s', real=True) assert integrate(Abs(t), t) == Piecewise( (-t**2/2, t <= 0), (t**2/2, True)) assert integrate(Abs(2*t - 6), t) == Piecewise( (-t**2 + 6*t, t <= 3), (t**2 - 6*t + 18, True)) assert (integrate(abs(t - s**2), (t, 0, 2)) == 2*s**2*Min(2, s**2) - 2*s**2 - Min(2, s**2)**2 + 2) assert integrate(exp(-Abs(t)), t) == Piecewise( (exp(t), t <= 0), (2 - exp(-t), True)) assert integrate(sign(2*t - 6), t) == Piecewise( (-t, t < 3), (t - 6, True)) assert integrate(2*t*sign(t**2 - 1), t) == Piecewise( (t**2, t < -1), (-t**2 + 2, t < 1), (t**2, True)) assert integrate(sign(t), (t, s + 1)) == Piecewise( (s + 1, s + 1 > 0), (-s - 1, s + 1 < 0), (0, True)) def test_subs1(): e = Integral(exp(x - y), x) assert e.subs(y, 3) == Integral(exp(x - 3), x) e = Integral(exp(x - y), (x, 0, 1)) assert e.subs(y, 3) == Integral(exp(x - 3), (x, 0, 1)) f = Lambda(x, exp(-x**2)) conv = Integral(f(x - y)*f(y), (y, -oo, oo)) assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo)) def test_subs2(): e = Integral(exp(x - y), x, t) assert e.subs(y, 3) == Integral(exp(x - 3), x, t) e = Integral(exp(x - y), (x, 0, 1), (t, 0, 1)) assert e.subs(y, 3) == Integral(exp(x - 3), (x, 0, 1), (t, 0, 1)) f = Lambda(x, exp(-x**2)) conv = Integral(f(x - y)*f(y), (y, -oo, oo), (t, 0, 1)) assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo), (t, 0, 1)) def test_subs3(): e = Integral(exp(x - y), (x, 0, y), (t, y, 1)) assert e.subs(y, 3) == Integral(exp(x - 3), (x, 0, 3), (t, 3, 1)) f = Lambda(x, exp(-x**2)) conv = Integral(f(x - y)*f(y), (y, -oo, oo), (t, x, 1)) assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo), (t, 0, 1)) def test_subs4(): e = Integral(exp(x), (x, 0, y), (t, y, 1)) assert e.subs(y, 3) == Integral(exp(x), (x, 0, 3), (t, 3, 1)) f = Lambda(x, exp(-x**2)) conv = Integral(f(y)*f(y), (y, -oo, oo), (t, x, 1)) assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo), (t, 0, 1)) def test_subs5(): e = Integral(exp(-x**2), (x, -oo, oo)) assert e.subs(x, 5) == e e = Integral(exp(-x**2 + y), x) assert e.subs(y, 5) == Integral(exp(-x**2 + 5), x) e = Integral(exp(-x**2 + y), (x, x)) assert e.subs(x, 5) == Integral(exp(y - x**2), (x, 5)) assert e.subs(y, 5) == Integral(exp(-x**2 + 5), x) e = Integral(exp(-x**2 + y), (y, -oo, oo), (x, -oo, oo)) assert e.subs(x, 5) == e assert e.subs(y, 5) == e # Test evaluation of antiderivatives e = Integral(exp(-x**2), (x, x)) assert e.subs(x, 5) == Integral(exp(-x**2), (x, 5)) e = Integral(exp(x), x) assert (e.subs(x,1) - e.subs(x,0) - Integral(exp(x), (x, 0, 1)) ).doit().is_zero def test_subs6(): a, b = symbols('a b') e = Integral(x*y, (x, f(x), f(y))) assert e.subs(x, 1) == Integral(x*y, (x, f(1), f(y))) assert e.subs(y, 1) == Integral(x, (x, f(x), f(1))) e = Integral(x*y, (x, f(x), f(y)), (y, f(x), f(y))) assert e.subs(x, 1) == Integral(x*y, (x, f(1), f(y)), (y, f(1), f(y))) assert e.subs(y, 1) == Integral(x*y, (x, f(x), f(y)), (y, f(x), f(1))) e = Integral(x*y, (x, f(x), f(a)), (y, f(x), f(a))) assert e.subs(a, 1) == Integral(x*y, (x, f(x), f(1)), (y, f(x), f(1))) def test_subs7(): e = Integral(x, (x, 1, y), (y, 1, 2)) assert e.subs({x: 1, y: 2}) == e e = Integral(sin(x) + sin(y), (x, sin(x), sin(y)), (y, 1, 2)) assert e.subs(sin(y), 1) == e assert e.subs(sin(x), 1) == Integral(sin(x) + sin(y), (x, 1, sin(y)), (y, 1, 2)) def test_expand(): e = Integral(f(x)+f(x**2), (x, 1, y)) assert e.expand() == Integral(f(x), (x, 1, y)) + Integral(f(x**2), (x, 1, y)) def test_integration_variable(): raises(ValueError, lambda: Integral(exp(-x**2), 3)) raises(ValueError, lambda: Integral(exp(-x**2), (3, -oo, oo))) def test_expand_integral(): assert Integral(cos(x**2)*(sin(x**2) + 1), (x, 0, 1)).expand() == \ Integral(cos(x**2)*sin(x**2), (x, 0, 1)) + \ Integral(cos(x**2), (x, 0, 1)) assert Integral(cos(x**2)*(sin(x**2) + 1), x).expand() == \ Integral(cos(x**2)*sin(x**2), x) + \ Integral(cos(x**2), x) def test_as_sum_midpoint1(): e = Integral(sqrt(x**3 + 1), (x, 2, 10)) assert e.as_sum(1, method="midpoint") == 8*sqrt(217) assert e.as_sum(2, method="midpoint") == 4*sqrt(65) + 12*sqrt(57) assert e.as_sum(3, method="midpoint") == 8*sqrt(217)/3 + \ 8*sqrt(3081)/27 + 8*sqrt(52809)/27 assert e.as_sum(4, method="midpoint") == 2*sqrt(730) + \ 4*sqrt(7) + 4*sqrt(86) + 6*sqrt(14) assert abs(e.as_sum(4, method="midpoint").n() - e.n()) < 0.5 e = Integral(sqrt(x**3 + y**3), (x, 2, 10), (y, 0, 10)) raises(NotImplementedError, lambda: e.as_sum(4)) def test_as_sum_midpoint2(): e = Integral((x + y)**2, (x, 0, 1)) n = Symbol('n', positive=True, integer=True) assert e.as_sum(1, method="midpoint").expand() == Rational(1, 4) + y + y**2 assert e.as_sum(2, method="midpoint").expand() == Rational(5, 16) + y + y**2 assert e.as_sum(3, method="midpoint").expand() == Rational(35, 108) + y + y**2 assert e.as_sum(4, method="midpoint").expand() == Rational(21, 64) + y + y**2 assert e.as_sum(n, method="midpoint").expand() == \ y**2 + y + Rational(1, 3) - 1/(12*n**2) def test_as_sum_left(): e = Integral((x + y)**2, (x, 0, 1)) assert e.as_sum(1, method="left").expand() == y**2 assert e.as_sum(2, method="left").expand() == Rational(1, 8) + y/2 + y**2 assert e.as_sum(3, method="left").expand() == Rational(5, 27) + y*Rational(2, 3) + y**2 assert e.as_sum(4, method="left").expand() == Rational(7, 32) + y*Rational(3, 4) + y**2 assert e.as_sum(n, method="left").expand() == \ y**2 + y + Rational(1, 3) - y/n - 1/(2*n) + 1/(6*n**2) assert e.as_sum(10, method="left", evaluate=False).has(Sum) def test_as_sum_right(): e = Integral((x + y)**2, (x, 0, 1)) assert e.as_sum(1, method="right").expand() == 1 + 2*y + y**2 assert e.as_sum(2, method="right").expand() == Rational(5, 8) + y*Rational(3, 2) + y**2 assert e.as_sum(3, method="right").expand() == Rational(14, 27) + y*Rational(4, 3) + y**2 assert e.as_sum(4, method="right").expand() == Rational(15, 32) + y*Rational(5, 4) + y**2 assert e.as_sum(n, method="right").expand() == \ y**2 + y + Rational(1, 3) + y/n + 1/(2*n) + 1/(6*n**2) def test_as_sum_trapezoid(): e = Integral((x + y)**2, (x, 0, 1)) assert e.as_sum(1, method="trapezoid").expand() == y**2 + y + S.Half assert e.as_sum(2, method="trapezoid").expand() == y**2 + y + Rational(3, 8) assert e.as_sum(3, method="trapezoid").expand() == y**2 + y + Rational(19, 54) assert e.as_sum(4, method="trapezoid").expand() == y**2 + y + Rational(11, 32) assert e.as_sum(n, method="trapezoid").expand() == \ y**2 + y + Rational(1, 3) + 1/(6*n**2) assert Integral(sign(x), (x, 0, 1)).as_sum(1, 'trapezoid') == S.Half def test_as_sum_raises(): e = Integral((x + y)**2, (x, 0, 1)) raises(ValueError, lambda: e.as_sum(-1)) raises(ValueError, lambda: e.as_sum(0)) raises(ValueError, lambda: Integral(x).as_sum(3)) raises(ValueError, lambda: e.as_sum(oo)) raises(ValueError, lambda: e.as_sum(3, method='xxxx2')) def test_nested_doit(): e = Integral(Integral(x, x), x) f = Integral(x, x, x) assert e.doit() == f.doit() def test_issue_4665(): # Allow only upper or lower limit evaluation e = Integral(x**2, (x, None, 1)) f = Integral(x**2, (x, 1, None)) assert e.doit() == Rational(1, 3) assert f.doit() == Rational(-1, 3) assert Integral(x*y, (x, None, y)).subs(y, t) == Integral(x*t, (x, None, t)) assert Integral(x*y, (x, y, None)).subs(y, t) == Integral(x*t, (x, t, None)) assert integrate(x**2, (x, None, 1)) == Rational(1, 3) assert integrate(x**2, (x, 1, None)) == Rational(-1, 3) assert integrate("x**2", ("x", "1", None)) == Rational(-1, 3) def test_integral_reconstruct(): e = Integral(x**2, (x, -1, 1)) assert e == Integral(*e.args) def test_doit_integrals(): e = Integral(Integral(2*x), (x, 0, 1)) assert e.doit() == Rational(1, 3) assert e.doit(deep=False) == Rational(1, 3) f = Function('f') # doesn't matter if the integral can't be performed assert Integral(f(x), (x, 1, 1)).doit() == 0 # doesn't matter if the limits can't be evaluated assert Integral(0, (x, 1, Integral(f(x), x))).doit() == 0 assert Integral(x, (a, 0)).doit() == 0 limits = ((a, 1, exp(x)), (x, 0)) assert Integral(a, *limits).doit() == Rational(1, 4) assert Integral(a, *list(reversed(limits))).doit() == 0 def test_issue_4884(): assert integrate(sqrt(x)*(1 + x)) == \ Piecewise( (2*sqrt(x)*(x + 1)**2/5 - 2*sqrt(x)*(x + 1)/15 - 4*sqrt(x)/15, Abs(x + 1) > 1), (2*I*sqrt(-x)*(x + 1)**2/5 - 2*I*sqrt(-x)*(x + 1)/15 - 4*I*sqrt(-x)/15, True)) assert integrate(x**x*(1 + log(x))) == x**x def test_issue_18153(): assert integrate(x**n*log(x),x) == \ Piecewise( (n*x*x**n*log(x)/(n**2 + 2*n + 1) + x*x**n*log(x)/(n**2 + 2*n + 1) - x*x**n/(n**2 + 2*n + 1) , Ne(n, -1)), (log(x)**2/2, True) ) def test_is_number(): from sympy.abc import x, y, z assert Integral(x).is_number is False assert Integral(1, x).is_number is False assert Integral(1, (x, 1)).is_number is True assert Integral(1, (x, 1, 2)).is_number is True assert Integral(1, (x, 1, y)).is_number is False assert Integral(1, (x, y)).is_number is False assert Integral(x, y).is_number is False assert Integral(x, (y, 1, x)).is_number is False assert Integral(x, (y, 1, 2)).is_number is False assert Integral(x, (x, 1, 2)).is_number is True # `foo.is_number` should always be equivalent to `not foo.free_symbols` # in each of these cases, there are pseudo-free symbols i = Integral(x, (y, 1, 1)) assert i.is_number is False and i.n() == 0 i = Integral(x, (y, z, z)) assert i.is_number is False and i.n() == 0 i = Integral(1, (y, z, z + 2)) assert i.is_number is False and i.n() == 2 assert Integral(x*y, (x, 1, 2), (y, 1, 3)).is_number is True assert Integral(x*y, (x, 1, 2), (y, 1, z)).is_number is False assert Integral(x, (x, 1)).is_number is True assert Integral(x, (x, 1, Integral(y, (y, 1, 2)))).is_number is True assert Integral(Sum(z, (z, 1, 2)), (x, 1, 2)).is_number is True # it is possible to get a false negative if the integrand is # actually an unsimplified zero, but this is true of is_number in general. assert Integral(sin(x)**2 + cos(x)**2 - 1, x).is_number is False assert Integral(f(x), (x, 0, 1)).is_number is True def test_free_symbols(): from sympy.abc import x, y, z assert Integral(0, x).free_symbols == {x} assert Integral(x).free_symbols == {x} assert Integral(x, (x, None, y)).free_symbols == {y} assert Integral(x, (x, y, None)).free_symbols == {y} assert Integral(x, (x, 1, y)).free_symbols == {y} assert Integral(x, (x, y, 1)).free_symbols == {y} assert Integral(x, (x, x, y)).free_symbols == {x, y} assert Integral(x, x, y).free_symbols == {x, y} assert Integral(x, (x, 1, 2)).free_symbols == set() assert Integral(x, (y, 1, 2)).free_symbols == {x} # pseudo-free in this case assert Integral(x, (y, z, z)).free_symbols == {x, z} assert Integral(x, (y, 1, 2), (y, None, None) ).free_symbols == {x, y} assert Integral(x, (y, 1, 2), (x, 1, y) ).free_symbols == {y} assert Integral(2, (y, 1, 2), (y, 1, x), (x, 1, 2) ).free_symbols == set() assert Integral(2, (y, x, 2), (y, 1, x), (x, 1, 2) ).free_symbols == set() assert Integral(2, (x, 1, 2), (y, x, 2), (y, 1, 2) ).free_symbols == {x} assert Integral(f(x), (f(x), 1, y)).free_symbols == {y} assert Integral(f(x), (f(x), 1, x)).free_symbols == {x} def test_is_zero(): from sympy.abc import x, m assert Integral(0, (x, 1, x)).is_zero assert Integral(1, (x, 1, 1)).is_zero assert Integral(1, (x, 1, 2), (y, 2)).is_zero is False assert Integral(x, (m, 0)).is_zero assert Integral(x + m, (m, 0)).is_zero is None i = Integral(m, (m, 1, exp(x)), (x, 0)) assert i.is_zero is None assert Integral(m, (x, 0), (m, 1, exp(x))).is_zero is True assert Integral(x, (x, oo, oo)).is_zero # issue 8171 assert Integral(x, (x, -oo, -oo)).is_zero # this is zero but is beyond the scope of what is_zero # should be doing assert Integral(sin(x), (x, 0, 2*pi)).is_zero is None def test_series(): from sympy.abc import x i = Integral(cos(x), (x, x)) e = i.lseries(x) assert i.nseries(x, n=8).removeO() == Add(*[next(e) for j in range(4)]) def test_trig_nonelementary_integrals(): x = Symbol('x') assert integrate((1 + sin(x))/x, x) == log(x) + Si(x) # next one comes out as log(x) + log(x**2)/2 + Ci(x) # so not hardcoding this log ugliness assert integrate((cos(x) + 2)/x, x).has(Ci) def test_issue_4403(): x = Symbol('x') y = Symbol('y') z = Symbol('z', positive=True) assert integrate(sqrt(x**2 + z**2), x) == \ z**2*asinh(x/z)/2 + x*sqrt(x**2 + z**2)/2 assert integrate(sqrt(x**2 - z**2), x) == \ -z**2*acosh(x/z)/2 + x*sqrt(x**2 - z**2)/2 x = Symbol('x', real=True) y = Symbol('y', positive=True) assert integrate(1/(x**2 + y**2)**S('3/2'), x) == \ x/(y**2*sqrt(x**2 + y**2)) # If y is real and nonzero, we get x*Abs(y)/(y**3*sqrt(x**2 + y**2)), # which results from sqrt(1 + x**2/y**2) = sqrt(x**2 + y**2)/|y|. def test_issue_4403_2(): assert integrate(sqrt(-x**2 - 4), x) == \ -2*atan(x/sqrt(-4 - x**2)) + x*sqrt(-4 - x**2)/2 def test_issue_4100(): R = Symbol('R', positive=True) assert integrate(sqrt(R**2 - x**2), (x, 0, R)) == pi*R**2/4 def test_issue_5167(): from sympy.abc import w, x, y, z f = Function('f') assert Integral(Integral(f(x), x), x) == Integral(f(x), x, x) assert Integral(f(x)).args == (f(x), Tuple(x)) assert Integral(Integral(f(x))).args == (f(x), Tuple(x), Tuple(x)) assert Integral(Integral(f(x)), y).args == (f(x), Tuple(x), Tuple(y)) assert Integral(Integral(f(x), z), y).args == (f(x), Tuple(z), Tuple(y)) assert Integral(Integral(Integral(f(x), x), y), z).args == \ (f(x), Tuple(x), Tuple(y), Tuple(z)) assert integrate(Integral(f(x), x), x) == Integral(f(x), x, x) assert integrate(Integral(f(x), y), x) == y*Integral(f(x), x) assert integrate(Integral(f(x), x), y) in [Integral(y*f(x), x), y*Integral(f(x), x)] assert integrate(Integral(2, x), x) == x**2 assert integrate(Integral(2, x), y) == 2*x*y # don't re-order given limits assert Integral(1, x, y).args != Integral(1, y, x).args # do as many as possible assert Integral(f(x), y, x, y, x).doit() == y**2*Integral(f(x), x, x)/2 assert Integral(f(x), (x, 1, 2), (w, 1, x), (z, 1, y)).doit() == \ y*(x - 1)*Integral(f(x), (x, 1, 2)) - (x - 1)*Integral(f(x), (x, 1, 2)) def test_issue_4890(): z = Symbol('z', positive=True) assert integrate(exp(-log(x)**2), x) == \ sqrt(pi)*exp(Rational(1, 4))*erf(log(x) - S.Half)/2 assert integrate(exp(log(x)**2), x) == \ sqrt(pi)*exp(Rational(-1, 4))*erfi(log(x)+S.Half)/2 assert integrate(exp(-z*log(x)**2), x) == \ sqrt(pi)*exp(1/(4*z))*erf(sqrt(z)*log(x) - 1/(2*sqrt(z)))/(2*sqrt(z)) def test_issue_4551(): assert not integrate(1/(x*sqrt(1 - x**2)), x).has(Integral) def test_issue_4376(): n = Symbol('n', integer=True, positive=True) assert simplify(integrate(n*(x**(1/n) - 1), (x, 0, S.Half)) - (n**2 - 2**(1/n)*n**2 - n*2**(1/n))/(2**(1 + 1/n) + n*2**(1 + 1/n))) == 0 def test_issue_4517(): assert integrate((sqrt(x) - x**3)/x**Rational(1, 3), x) == \ 6*x**Rational(7, 6)/7 - 3*x**Rational(11, 3)/11 def test_issue_4527(): k, m = symbols('k m', integer=True) assert integrate(sin(k*x)*sin(m*x), (x, 0, pi)).simplify() == \ Piecewise((0, Eq(k, 0) | Eq(m, 0)), (-pi/2, Eq(k, -m) | (Eq(k, 0) & Eq(m, 0))), (pi/2, Eq(k, m) | (Eq(k, 0) & Eq(m, 0))), (0, True)) # Should be possible to further simplify to: # Piecewise( # (0, Eq(k, 0) | Eq(m, 0)), # (-pi/2, Eq(k, -m)), # (pi/2, Eq(k, m)), # (0, True)) assert integrate(sin(k*x)*sin(m*x), (x,)) == Piecewise( (0, And(Eq(k, 0), Eq(m, 0))), (-x*sin(m*x)**2/2 - x*cos(m*x)**2/2 + sin(m*x)*cos(m*x)/(2*m), Eq(k, -m)), (x*sin(m*x)**2/2 + x*cos(m*x)**2/2 - sin(m*x)*cos(m*x)/(2*m), Eq(k, m)), (m*sin(k*x)*cos(m*x)/(k**2 - m**2) - k*sin(m*x)*cos(k*x)/(k**2 - m**2), True)) def test_issue_4199(): ypos = Symbol('y', positive=True) # TODO: Remove conds='none' below, let the assumption take care of it. assert integrate(exp(-I*2*pi*ypos*x)*x, (x, -oo, oo), conds='none') == \ Integral(exp(-I*2*pi*ypos*x)*x, (x, -oo, oo)) def test_issue_3940(): a, b, c, d = symbols('a:d', positive=True) assert integrate(exp(-x**2 + I*c*x), x) == \ -sqrt(pi)*exp(-c**2/4)*erf(I*c/2 - x)/2 assert integrate(exp(a*x**2 + b*x + c), x) == \ sqrt(pi)*exp(c)*exp(-b**2/(4*a))*erfi(sqrt(a)*x + b/(2*sqrt(a)))/(2*sqrt(a)) from sympy.core.function import expand_mul from sympy.abc import k assert expand_mul(integrate(exp(-x**2)*exp(I*k*x), (x, -oo, oo))) == \ sqrt(pi)*exp(-k**2/4) a, d = symbols('a d', positive=True) assert expand_mul(integrate(exp(-a*x**2 + 2*d*x), (x, -oo, oo))) == \ sqrt(pi)*exp(d**2/a)/sqrt(a) def test_issue_5413(): # Note that this is not the same as testing ratint() because integrate() # pulls out the coefficient. assert integrate(-a/(a**2 + x**2), x) == I*log(-I*a + x)/2 - I*log(I*a + x)/2 def test_issue_4892a(): A, z = symbols('A z') c = Symbol('c', nonzero=True) P1 = -A*exp(-z) P2 = -A/(c*t)*(sin(x)**2 + cos(y)**2) h1 = -sin(x)**2 - cos(y)**2 h2 = -sin(x)**2 + sin(y)**2 - 1 # there is still some non-deterministic behavior in integrate # or trigsimp which permits one of the following assert integrate(c*(P2 - P1), t) in [ c*(-A*(-h1)*log(c*t)/c + A*t*exp(-z)), c*(-A*(-h2)*log(c*t)/c + A*t*exp(-z)), c*( A* h1 *log(c*t)/c + A*t*exp(-z)), c*( A* h2 *log(c*t)/c + A*t*exp(-z)), (A*c*t - A*(-h1)*log(t)*exp(z))*exp(-z), (A*c*t - A*(-h2)*log(t)*exp(z))*exp(-z), ] def test_issue_4892b(): # Issues relating to issue 4596 are making the actual result of this hard # to test. The answer should be something like # # (-sin(y) + sqrt(-72 + 48*cos(y) - 8*cos(y)**2)/2)*log(x + sqrt(-72 + # 48*cos(y) - 8*cos(y)**2)/(2*(3 - cos(y)))) + (-sin(y) - sqrt(-72 + # 48*cos(y) - 8*cos(y)**2)/2)*log(x - sqrt(-72 + 48*cos(y) - # 8*cos(y)**2)/(2*(3 - cos(y)))) + x**2*sin(y)/2 + 2*x*cos(y) expr = (sin(y)*x**3 + 2*cos(y)*x**2 + 12)/(x**2 + 2) assert trigsimp(factor(integrate(expr, x).diff(x) - expr)) == 0 def test_issue_5178(): assert integrate(sin(x)*f(y, z), (x, 0, pi), (y, 0, pi), (z, 0, pi)) == \ 2*Integral(f(y, z), (y, 0, pi), (z, 0, pi)) def test_integrate_series(): f = sin(x).series(x, 0, 10) g = x**2/2 - x**4/24 + x**6/720 - x**8/40320 + x**10/3628800 + O(x**11) assert integrate(f, x) == g assert diff(integrate(f, x), x) == f assert integrate(O(x**5), x) == O(x**6) def test_atom_bug(): from sympy.integrals.heurisch import heurisch assert heurisch(meijerg([], [], [1], [], x), x) is None def test_limit_bug(): z = Symbol('z', zero=False) assert integrate(sin(x*y*z), (x, 0, pi), (y, 0, pi)).together() == \ (log(z) - Ci(pi**2*z) + EulerGamma + 2*log(pi))/z def test_issue_4703(): g = Function('g') assert integrate(exp(x)*g(x), x).has(Integral) def test_issue_1888(): f = Function('f') assert integrate(f(x).diff(x)**2, x).has(Integral) # The following tests work using meijerint. def test_issue_3558(): assert integrate(cos(x*y), (x, -pi/2, pi/2), (y, 0, pi)) == 2*Si(pi**2/2) def test_issue_4422(): assert integrate(1/sqrt(16 + 4*x**2), x) == asinh(x/2) / 2 def test_issue_4493(): assert simplify(integrate(x*sqrt(1 + 2*x), x)) == \ sqrt(2*x + 1)*(6*x**2 + x - 1)/15 def test_issue_4737(): assert integrate(sin(x)/x, (x, -oo, oo)) == pi assert integrate(sin(x)/x, (x, 0, oo)) == pi/2 assert integrate(sin(x)/x, x) == Si(x) def test_issue_4992(): # Note: psi in _check_antecedents becomes NaN. from sympy.core.function import expand_func a = Symbol('a', positive=True) assert simplify(expand_func(integrate(exp(-x)*log(x)*x**a, (x, 0, oo)))) == \ (a*polygamma(0, a) + 1)*gamma(a) def test_issue_4487(): from sympy.functions.special.gamma_functions import lowergamma assert simplify(integrate(exp(-x)*x**y, x)) == lowergamma(y + 1, x) def test_issue_4215(): x = Symbol("x") assert integrate(1/(x**2), (x, -1, 1)) is oo def test_issue_4400(): n = Symbol('n', integer=True, positive=True) assert integrate((x**n)*log(x), x) == \ n*x*x**n*log(x)/(n**2 + 2*n + 1) + x*x**n*log(x)/(n**2 + 2*n + 1) - \ x*x**n/(n**2 + 2*n + 1) def test_issue_6253(): # Note: this used to raise NotImplementedError # Note: psi in _check_antecedents becomes NaN. assert integrate((sqrt(1 - x) + sqrt(1 + x))**2/x, x, meijerg=True) == \ Integral((sqrt(-x + 1) + sqrt(x + 1))**2/x, x) def test_issue_4153(): assert integrate(1/(1 + x + y + z), (x, 0, 1), (y, 0, 1), (z, 0, 1)) in [ -12*log(3) - 3*log(6)/2 + 3*log(8)/2 + 5*log(2) + 7*log(4), 6*log(2) + 8*log(4) - 27*log(3)/2, 22*log(2) - 27*log(3)/2, -12*log(3) - 3*log(6)/2 + 47*log(2)/2] def test_issue_4326(): R, b, h = symbols('R b h') # It doesn't matter if we can do the integral. Just make sure the result # doesn't contain nan. This is really a test against _eval_interval. e = integrate(((h*(x - R + b))/b)*sqrt(R**2 - x**2), (x, R - b, R)) assert not e.has(nan) # See that it evaluates assert not e.has(Integral) def test_powers(): assert integrate(2**x + 3**x, x) == 2**x/log(2) + 3**x/log(3) def test_manual_option(): raises(ValueError, lambda: integrate(1/x, x, manual=True, meijerg=True)) # an example of a function that manual integration cannot handle assert integrate(log(1+x)/x, (x, 0, 1), manual=True).has(Integral) def test_meijerg_option(): raises(ValueError, lambda: integrate(1/x, x, meijerg=True, risch=True)) # an example of a function that meijerg integration cannot handle assert integrate(tan(x), x, meijerg=True) == Integral(tan(x), x) def test_risch_option(): # risch=True only allowed on indefinite integrals raises(ValueError, lambda: integrate(1/log(x), (x, 0, oo), risch=True)) assert integrate(exp(-x**2), x, risch=True) == NonElementaryIntegral(exp(-x**2), x) assert integrate(log(1/x)*y, x, y, risch=True) == y**2*(x*log(1/x)/2 + x/2) assert integrate(erf(x), x, risch=True) == Integral(erf(x), x) # TODO: How to test risch=False? @slow def test_heurisch_option(): raises(ValueError, lambda: integrate(1/x, x, risch=True, heurisch=True)) # an integral that heurisch can handle assert integrate(exp(x**2), x, heurisch=True) == sqrt(pi)*erfi(x)/2 # an integral that heurisch currently cannot handle assert integrate(exp(x)/x, x, heurisch=True) == Integral(exp(x)/x, x) # an integral where heurisch currently hangs, issue 15471 assert integrate(log(x)*cos(log(x))/x**Rational(3, 4), x, heurisch=False) == ( -128*x**Rational(1, 4)*sin(log(x))/289 + 240*x**Rational(1, 4)*cos(log(x))/289 + (16*x**Rational(1, 4)*sin(log(x))/17 + 4*x**Rational(1, 4)*cos(log(x))/17)*log(x)) def test_issue_6828(): f = 1/(1.08*x**2 - 4.3) g = integrate(f, x).diff(x) assert verify_numerically(f, g, tol=1e-12) def test_issue_4803(): x_max = Symbol("x_max") assert integrate(y/pi*exp(-(x_max - x)/cos(a)), x) == \ y*exp((x - x_max)/cos(a))*cos(a)/pi def test_issue_4234(): assert integrate(1/sqrt(1 + tan(x)**2)) == tan(x)/sqrt(1 + tan(x)**2) def test_issue_4492(): assert simplify(integrate(x**2 * sqrt(5 - x**2), x)).factor( deep=True) == Piecewise( (I*(2*x**5 - 15*x**3 + 25*x - 25*sqrt(x**2 - 5)*acosh(sqrt(5)*x/5)) / (8*sqrt(x**2 - 5)), (x > sqrt(5)) | (x < -sqrt(5))), ((2*x**5 - 15*x**3 + 25*x - 25*sqrt(5 - x**2)*asin(sqrt(5)*x/5)) / (-8*sqrt(-x**2 + 5)), True)) def test_issue_2708(): # This test needs to use an integration function that can # not be evaluated in closed form. Update as needed. f = 1/(a + z + log(z)) integral_f = NonElementaryIntegral(f, (z, 2, 3)) assert Integral(f, (z, 2, 3)).doit() == integral_f assert integrate(f + exp(z), (z, 2, 3)) == integral_f - exp(2) + exp(3) assert integrate(2*f + exp(z), (z, 2, 3)) == \ 2*integral_f - exp(2) + exp(3) assert integrate(exp(1.2*n*s*z*(-t + z)/t), (z, 0, x)) == \ NonElementaryIntegral(exp(-1.2*n*s*z)*exp(1.2*n*s*z**2/t), (z, 0, x)) def test_issue_2884(): f = (4.000002016020*x + 4.000002016020*y + 4.000006024032)*exp(10.0*x) e = integrate(f, (x, 0.1, 0.2)) assert str(e) == '1.86831064982608*y + 2.16387491480008' def test_issue_8368i(): from sympy.functions.elementary.complexes import arg, Abs assert integrate(exp(-s*x)*cosh(x), (x, 0, oo)) == \ Piecewise( ( pi*Piecewise( ( -s/(pi*(-s**2 + 1)), Abs(s**2) < 1), ( 1/(pi*s*(1 - 1/s**2)), Abs(s**(-2)) < 1), ( meijerg( ((S.Half,), (0, 0)), ((0, S.Half), (0,)), polar_lift(s)**2), True) ), s**2 > 1 ), ( Integral(exp(-s*x)*cosh(x), (x, 0, oo)), True)) assert integrate(exp(-s*x)*sinh(x), (x, 0, oo)) == \ Piecewise( ( -1/(s + 1)/2 - 1/(-s + 1)/2, And( Abs(s) > 1, Abs(arg(s)) < pi/2, Abs(arg(s)) <= pi/2 )), ( Integral(exp(-s*x)*sinh(x), (x, 0, oo)), True)) def test_issue_8901(): assert integrate(sinh(1.0*x)) == 1.0*cosh(1.0*x) assert integrate(tanh(1.0*x)) == 1.0*x - 1.0*log(tanh(1.0*x) + 1) assert integrate(tanh(x)) == x - log(tanh(x) + 1) @slow def test_issue_8945(): assert integrate(sin(x)**3/x, (x, 0, 1)) == -Si(3)/4 + 3*Si(1)/4 assert integrate(sin(x)**3/x, (x, 0, oo)) == pi/4 assert integrate(cos(x)**2/x**2, x) == -Si(2*x) - cos(2*x)/(2*x) - 1/(2*x) @slow def test_issue_7130(): if ON_TRAVIS: skip("Too slow for travis.") i, L, a, b = symbols('i L a b') integrand = (cos(pi*i*x/L)**2 / (a + b*x)).rewrite(exp) assert x not in integrate(integrand, (x, 0, L)).free_symbols def test_issue_10567(): a, b, c, t = symbols('a b c t') vt = Matrix([a*t, b, c]) assert integrate(vt, t) == Integral(vt, t).doit() assert integrate(vt, t) == Matrix([[a*t**2/2], [b*t], [c*t]]) def test_issue_11856(): t = symbols('t') assert integrate(sinc(pi*t), t) == Si(pi*t)/pi @slow def test_issue_11876(): assert integrate(sqrt(log(1/x)), (x, 0, 1)) == sqrt(pi)/2 def test_issue_4950(): assert integrate((-60*exp(x) - 19.2*exp(4*x))*exp(4*x), x) ==\ -2.4*exp(8*x) - 12.0*exp(5*x) def test_issue_4968(): assert integrate(sin(log(x**2))) == x*sin(log(x**2))/5 - 2*x*cos(log(x**2))/5 def test_singularities(): assert integrate(1/x**2, (x, -oo, oo)) is oo assert integrate(1/x**2, (x, -1, 1)) is oo assert integrate(1/(x - 1)**2, (x, -2, 2)) is oo assert integrate(1/x**2, (x, 1, -1)) is -oo assert integrate(1/(x - 1)**2, (x, 2, -2)) is -oo def test_issue_12645(): x, y = symbols('x y', real=True) assert (integrate(sin(x*x*x + y*y), (x, -sqrt(pi - y*y), sqrt(pi - y*y)), (y, -sqrt(pi), sqrt(pi))) == Integral(sin(x**3 + y**2), (x, -sqrt(-y**2 + pi), sqrt(-y**2 + pi)), (y, -sqrt(pi), sqrt(pi)))) def test_issue_12677(): assert integrate(sin(x) / (cos(x)**3), (x, 0, pi/6)) == Rational(1, 6) def test_issue_14078(): assert integrate((cos(3*x)-cos(x))/x, (x, 0, oo)) == -log(3) def test_issue_14064(): assert integrate(1/cosh(x), (x, 0, oo)) == pi/2 def test_issue_14027(): assert integrate(1/(1 + exp(x - S.Half)/(1 + exp(x))), x) == \ x - exp(S.Half)*log(exp(x) + exp(S.Half)/(1 + exp(S.Half)))/(exp(S.Half) + E) def test_issue_8170(): assert integrate(tan(x), (x, 0, pi/2)) is S.Infinity def test_issue_8440_14040(): assert integrate(1/x, (x, -1, 1)) is S.NaN assert integrate(1/(x + 1), (x, -2, 3)) is S.NaN def test_issue_14096(): assert integrate(1/(x + y)**2, (x, 0, 1)) == -1/(y + 1) + 1/y assert integrate(1/(1 + x + y + z)**2, (x, 0, 1), (y, 0, 1), (z, 0, 1)) == \ -4*log(4) - 6*log(2) + 9*log(3) def test_issue_14144(): assert Abs(integrate(1/sqrt(1 - x**3), (x, 0, 1)).n() - 1.402182) < 1e-6 assert Abs(integrate(sqrt(1 - x**3), (x, 0, 1)).n() - 0.841309) < 1e-6 def test_issue_14375(): # This raised a TypeError. The antiderivative has exp_polar, which # may be possible to unpolarify, so the exact output is not asserted here. assert integrate(exp(I*x)*log(x), x).has(Ei) def test_issue_14437(): f = Function('f')(x, y, z) assert integrate(f, (x, 0, 1), (y, 0, 2), (z, 0, 3)) == \ Integral(f, (x, 0, 1), (y, 0, 2), (z, 0, 3)) def test_issue_14470(): assert integrate(1/sqrt(exp(x) + 1), x) == \ log(-1 + 1/sqrt(exp(x) + 1)) - log(1 + 1/sqrt(exp(x) + 1)) def test_issue_14877(): f = exp(1 - exp(x**2)*x + 2*x**2)*(2*x**3 + x)/(1 - exp(x**2)*x)**2 assert integrate(f, x) == \ -exp(2*x**2 - x*exp(x**2) + 1)/(x*exp(3*x**2) - exp(2*x**2)) def test_issue_14782(): f = sqrt(-x**2 + 1)*(-x**2 + x) assert integrate(f, [x, -1, 1]) == - pi / 8 @slow def test_issue_14782_slow(): f = sqrt(-x**2 + 1)*(-x**2 + x) assert integrate(f, [x, 0, 1]) == S.One / 3 - pi / 16 def test_issue_12081(): f = x**(Rational(-3, 2))*exp(-x) assert integrate(f, [x, 0, oo]) is oo def test_issue_15285(): y = 1/x - 1 f = 4*y*exp(-2*y)/x**2 assert integrate(f, [x, 0, 1]) == 1 def test_issue_15432(): assert integrate(x**n * exp(-x) * log(x), (x, 0, oo)).gammasimp() == Piecewise( (gamma(n + 1)*polygamma(0, n) + gamma(n + 1)/n, re(n) + 1 > 0), (Integral(x**n*exp(-x)*log(x), (x, 0, oo)), True)) def test_issue_15124(): omega = IndexedBase('omega') m, p = symbols('m p', cls=Idx) assert integrate(exp(x*I*(omega[m] + omega[p])), x, conds='none') == \ -I*exp(I*x*omega[m])*exp(I*x*omega[p])/(omega[m] + omega[p]) def test_issue_15218(): with warns_deprecated_sympy(): Integral(Eq(x, y)) with warns_deprecated_sympy(): assert Integral(Eq(x, y), x) == Eq(Integral(x, x), Integral(y, x)) with warns_deprecated_sympy(): assert Integral(Eq(x, y), x).doit() == Eq(x**2/2, x*y) with warns_deprecated_sympy(): assert Eq(x, y).integrate(x) == Eq(x**2/2, x*y) # These are not deprecated because they are definite integrals assert integrate(Eq(x, y), (x, 0, 1)) == Eq(S.Half, y) assert Eq(x, y).integrate((x, 0, 1)) == Eq(S.Half, y) def test_issue_15292(): res = integrate(exp(-x**2*cos(2*t)) * cos(x**2*sin(2*t)), (x, 0, oo)) assert isinstance(res, Piecewise) assert gammasimp((res - sqrt(pi)/2 * cos(t)).subs(t, pi/6)) == 0 def test_issue_4514(): assert integrate(sin(2*x)/sin(x), x) == 2*sin(x) def test_issue_15457(): x, a, b = symbols('x a b', real=True) definite = integrate(exp(Abs(x-2)), (x, a, b)) indefinite = integrate(exp(Abs(x-2)), x) assert definite.subs({a: 1, b: 3}) == -2 + 2*E assert indefinite.subs(x, 3) - indefinite.subs(x, 1) == -2 + 2*E assert definite.subs({a: -3, b: -1}) == -exp(3) + exp(5) assert indefinite.subs(x, -1) - indefinite.subs(x, -3) == -exp(3) + exp(5) def test_issue_15431(): assert integrate(x*exp(x)*log(x), x) == \ (x*exp(x) - exp(x))*log(x) - exp(x) + Ei(x) def test_issue_15640_log_substitutions(): f = x/log(x) F = Ei(2*log(x)) assert integrate(f, x) == F and F.diff(x) == f f = x**3/log(x)**2 F = -x**4/log(x) + 4*Ei(4*log(x)) assert integrate(f, x) == F and F.diff(x) == f f = sqrt(log(x))/x**2 F = -sqrt(pi)*erfc(sqrt(log(x)))/2 - sqrt(log(x))/x assert integrate(f, x) == F and F.diff(x) == f def test_issue_15509(): from sympy.vector import CoordSys3D N = CoordSys3D('N') x = N.x assert integrate(cos(a*x + b), (x, x_1, x_2), heurisch=True) == Piecewise( (-sin(a*x_1 + b)/a + sin(a*x_2 + b)/a, (a > -oo) & (a < oo) & Ne(a, 0)), \ (-x_1*cos(b) + x_2*cos(b), True)) def test_issue_4311_fast(): x = symbols('x', real=True) assert integrate(x*abs(9-x**2), x) == Piecewise( (x**4/4 - 9*x**2/2, x <= -3), (-x**4/4 + 9*x**2/2 - Rational(81, 2), x <= 3), (x**4/4 - 9*x**2/2, True)) def test_integrate_with_complex_constants(): K = Symbol('K', positive=True) x = Symbol('x', real=True) m = Symbol('m', real=True) t = Symbol('t', real=True) assert integrate(exp(-I*K*x**2+m*x), x) == sqrt(I)*sqrt(pi)*exp(-I*m**2 /(4*K))*erfi((-2*I*K*x + m)/(2*sqrt(K)*sqrt(-I)))/(2*sqrt(K)) assert integrate(1/(1 + I*x**2), x) == (-I*(sqrt(-I)*log(x - I*sqrt(-I))/2 - sqrt(-I)*log(x + I*sqrt(-I))/2)) assert integrate(exp(-I*x**2), x) == sqrt(pi)*erf(sqrt(I)*x)/(2*sqrt(I)) assert integrate((1/(exp(I*t)-2)), t) == -t/2 - I*log(exp(I*t) - 2)/2 assert integrate((1/(exp(I*t)-2)), (t, 0, 2*pi)) == -pi def test_issue_14241(): x = Symbol('x') n = Symbol('n', positive=True, integer=True) assert integrate(n * x ** (n - 1) / (x + 1), x) == \ n**2*x**n*lerchphi(x*exp_polar(I*pi), 1, n)*gamma(n)/gamma(n + 1) def test_issue_13112(): assert integrate(sin(t)**2 / (5 - 4*cos(t)), [t, 0, 2*pi]) == pi / 4 @slow def test_issue_14709b(): h = Symbol('h', positive=True) i = integrate(x*acos(1 - 2*x/h), (x, 0, h)) assert i == 5*h**2*pi/16 def test_issue_8614(): x = Symbol('x') t = Symbol('t') assert integrate(exp(t)/t, (t, -oo, x)) == Ei(x) assert integrate((exp(-x) - exp(-2*x))/x, (x, 0, oo)) == log(2) @slow def test_issue_15494(): s = symbols('s', positive=True) integrand = (exp(s/2) - 2*exp(1.6*s) + exp(s))*exp(s) solution = integrate(integrand, s) assert solution != S.NaN # Not sure how to test this properly as it is a symbolic expression with floats # assert str(solution) == '0.666666666666667*exp(1.5*s) + 0.5*exp(2.0*s) - 0.769230769230769*exp(2.6*s)' # Maybe assert abs(solution.subs(s, 1) - (-3.67440080236188)) <= 1e-8 integrand = (exp(s/2) - 2*exp(S(8)/5*s) + exp(s))*exp(s) assert integrate(integrand, s) == -10*exp(13*s/5)/13 + 2*exp(3*s/2)/3 + exp(2*s)/2 def test_li_integral(): y = Symbol('y') assert Integral(li(y*x**2), x).doit() == Piecewise((x*li(x**2*y) - \ x*Ei(3*log(x**2*y)/2)/sqrt(x**2*y), Ne(y, 0)), (0, True)) def test_issue_17473(): x = Symbol('x') n = Symbol('n') assert integrate(sin(x**n), x) == \ x*x**n*gamma(S(1)/2 + 1/(2*n))*hyper((S(1)/2 + 1/(2*n),), (S(3)/2, S(3)/2 + 1/(2*n)), -x**(2*n)/4)/(2*n*gamma(S(3)/2 + 1/(2*n))) def test_issue_17671(): assert integrate(log(log(x)) / x**2, [x, 1, oo]) == -EulerGamma assert integrate(log(log(x)) / x**3, [x, 1, oo]) == -log(2)/2 - EulerGamma/2 assert integrate(log(log(x)) / x**10, [x, 1, oo]) == -2*log(3)/9 - EulerGamma/9 def test_issue_2975(): w = Symbol('w') C = Symbol('C') y = Symbol('y') assert integrate(1/(y**2+C)**(S(3)/2), (y, -w/2, w/2)) == w/(C**(S(3)/2)*sqrt(1 + w**2/(4*C))) def test_issue_7827(): x, n, M = symbols('x n M') N = Symbol('N', integer=True) assert integrate(summation(x*n, (n, 1, N)), x) == x**2*(N**2/4 + N/4) assert integrate(summation(x*sin(n), (n,1,N)), x) == \ Sum(x**2*sin(n)/2, (n, 1, N)) assert integrate(summation(sin(n*x), (n,1,N)), x) == \ Sum(Piecewise((-cos(n*x)/n, Ne(n, 0)), (0, True)), (n, 1, N)) assert integrate(integrate(summation(sin(n*x), (n,1,N)), x), x) == \ Piecewise((Sum(Piecewise((-sin(n*x)/n**2, Ne(n, 0)), (-x/n, True)), (n, 1, N)), (n > -oo) & (n < oo) & Ne(n, 0)), (0, True)) assert integrate(Sum(x, (n, 1, M)), x) == M*x**2/2 raises(ValueError, lambda: integrate(Sum(x, (x, y, n)), y)) raises(ValueError, lambda: integrate(Sum(x, (x, 1, n)), n)) raises(ValueError, lambda: integrate(Sum(x, (x, 1, y)), x)) def test_issue_4231(): f = (1 + 2*x + sqrt(x + log(x))*(1 + 3*x) + x**2)/(x*(x + sqrt(x + log(x)))*sqrt(x + log(x))) assert integrate(f, x) == 2*sqrt(x + log(x)) + 2*log(x + sqrt(x + log(x))) def test_issue_17841(): f = diff(1/(x**2+x+I), x) assert integrate(f, x) == 1/(x**2 + x + I) def test_issue_21034(): x = Symbol('x', real=True, nonzero=True) f1 = x*(-x**4/asin(5)**4 - x*sinh(x + log(asin(5))) + 5) f2 = (x + cosh(cos(4)))/(x*(x + 1/(12*x))) assert integrate(f1, x) == \ -x**6/(6*asin(5)**4) - x**2*cosh(x + log(asin(5))) + 5*x**2/2 + 2*x*sinh(x + log(asin(5))) - 2*cosh(x + log(asin(5))) assert integrate(f2, x) == \ log(x**2 + S(1)/12)/2 + 2*sqrt(3)*cosh(cos(4))*atan(2*sqrt(3)*x) def test_issue_4187(): assert integrate(log(x)*exp(-x), x) == Ei(-x) - exp(-x)*log(x) assert integrate(log(x)*exp(-x), (x, 0, oo)) == -EulerGamma def test_issue_5547(): L = Symbol('L') z = Symbol('z') r0 = Symbol('r0') R0 = Symbol('R0') assert integrate(r0**2*cos(z)**2, (z, -L/2, L/2)) == -r0**2*(-L/4 - sin(L/2)*cos(L/2)/2) + r0**2*(L/4 + sin(L/2)*cos(L/2)/2) assert integrate(r0**2*cos(R0*z)**2, (z, -L/2, L/2)) == Piecewise( (-r0**2*(-L*R0/4 - sin(L*R0/2)*cos(L*R0/2)/2)/R0 + r0**2*(L*R0/4 + sin(L*R0/2)*cos(L*R0/2)/2)/R0, (R0 > -oo) & (R0 < oo) & Ne(R0, 0)), (L*r0**2, True)) w = 2*pi*z/L sol = sqrt(2)*sqrt(L)*r0**2*fresnelc(sqrt(2)*sqrt(L))*gamma(S.One/4)/(16*gamma(S(5)/4)) + L*r0**2/2 assert integrate(r0**2*cos(w*z)**2, (z, -L/2, L/2)) == sol def test_issue_15810(): assert integrate(1/(2**(2*x/3) + 1), (x, 0, oo)) == Rational(3, 2) def test_issue_21024(): x = Symbol('x', real=True, nonzero=True) f = log(x)*log(4*x) + log(3*x + exp(2)) F = x*log(x)**2 + x*(1 - 2*log(2)) + (-2*x + 2*x*log(2))*log(x) + \ (x + exp(2)/6)*log(3*x + exp(2)) + exp(2)*log(3*x + exp(2))/6 assert F == integrate(f, x) f = (x + exp(3))/x**2 F = log(x) - exp(3)/x assert F == integrate(f, x) f = (x**2 + exp(5))/x F = x**2/2 + exp(5)*log(x) assert F == integrate(f, x) f = x/(2*x + tanh(1)) F = x/2 - log(2*x + tanh(1))*tanh(1)/4 assert F == integrate(f, x) f = x - sinh(4)/x F = x**2/2 - log(x)*sinh(4) assert F == integrate(f, x) f = log(x + exp(5)/x) F = x*log(x + exp(5)/x) - x + 2*exp(Rational(5, 2))*atan(x*exp(Rational(-5, 2))) assert F == integrate(f, x) f = x**5/(x + E) F = x**5/5 - E*x**4/4 + x**3*exp(2)/3 - x**2*exp(3)/2 + x*exp(4) - exp(5)*log(x + E) assert F == integrate(f, x) f = 4*x/(x + sinh(5)) F = 4*x - 4*log(x + sinh(5))*sinh(5) assert F == integrate(f, x) f = x**2/(2*x + sinh(2)) F = x**2/4 - x*sinh(2)/4 + log(2*x + sinh(2))*sinh(2)**2/8 assert F == integrate(f, x) f = -x**2/(x + E) F = -x**2/2 + E*x - exp(2)*log(x + E) assert F == integrate(f, x) f = (2*x + 3)*exp(5)/x F = 2*x*exp(5) + 3*exp(5)*log(x) assert F == integrate(f, x) f = x + 2 + cosh(3)/x F = x**2/2 + 2*x + log(x)*cosh(3) assert F == integrate(f, x) f = x - tanh(1)/x**3 F = x**2/2 + tanh(1)/(2*x**2) assert F == integrate(f, x) f = (3*x - exp(6))/x F = 3*x - exp(6)*log(x) assert F == integrate(f, x) f = x**4/(x + exp(5))**2 + x F = x**3/3 + x**2*(Rational(1, 2) - exp(5)) + 3*x*exp(10) - 4*exp(15)*log(x + exp(5)) - exp(20)/(x + exp(5)) assert F == integrate(f, x) f = x*(x + exp(10)/x**2) + x F = x**3/3 + x**2/2 + exp(10)*log(x) assert F == integrate(f, x) f = x + x/(5*x + sinh(3)) F = x**2/2 + x/5 - log(5*x + sinh(3))*sinh(3)/25 assert F == integrate(f, x) f = (x + exp(3))/(2*x**2 + 2*x) F = exp(3)*log(x)/2 - exp(3)*log(x + 1)/2 + log(x + 1)/2 assert F == integrate(f, x).expand() f = log(x + 4*sinh(4)) F = x*log(x + 4*sinh(4)) - x + 4*log(x + 4*sinh(4))*sinh(4) assert F == integrate(f, x) f = -x + 20*(exp(-5) - atan(4)/x)**3*sin(4)/x F = (-x**2*exp(15)/2 + 20*log(x)*sin(4) - (-180*x**2*exp(5)*sin(4)*atan(4) + 90*x*exp(10)*sin(4)*atan(4)**2 - \ 20*exp(15)*sin(4)*atan(4)**3)/(3*x**3))*exp(-15) assert F == integrate(f, x) f = 2*x**2*exp(-4) + 6/x F_true = (2*x**3/3 + 6*exp(4)*log(x))*exp(-4) assert F_true == integrate(f, x) def test_issue_21831(): theta = symbols('theta') assert integrate(cos(3*theta)/(5-4*cos(theta)), (theta, 0, 2*pi)) == pi/12 @slow def test_issue_22033_integral(): assert integrate((x**2 - Rational(1, 4))**2 * sqrt(1 - x**2), (x, -1, 1)) == pi/32 @slow def test_issue_21671(): assert integrate(1,(z,x**2+y**2,2-x**2-y**2),(y,-sqrt(1-x**2),sqrt(1-x**2)),(x,-1,1)) == pi assert integrate(-4*(1 - x**2)**(S(3)/2)/3 + 2*sqrt(1 - x**2)*(2 - 2*x**2), (x, -1, 1)) == pi def test_issue_18527(): # The manual integrator can not currently solve this. Assert that it does # not give an incorrect result involving Abs when x has real assumptions. xr = symbols('xr', real=True) expr = (cos(x)/(4+(sin(x))**2)) res_real = integrate(expr.subs(x, xr), xr, manual=True).subs(xr, x) assert integrate(expr, x, manual=True) == res_real == Integral(expr, x)
60ea54a0419fb0714cbe1ef7bdc7253e798d630b2abeaab3410c6dc8ca645bf2
from sympy.core.function import expand_func from sympy.core.numbers import (I, Rational, oo, pi) from sympy.core.singleton import S from sympy.core.sorting import default_sort_key from sympy.functions.elementary.exponential import (exp, exp_polar, log) from sympy.functions.elementary.hyperbolic import cosh from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin, sinc) from sympy.functions.special.error_functions import (erf, erfc) from sympy.functions.special.gamma_functions import (gamma, polygamma) from sympy.functions.special.hyper import (hyper, meijerg) from sympy.integrals.integrals import (Integral, integrate) from sympy.simplify.hyperexpand import hyperexpand from sympy.simplify.simplify import simplify from sympy.integrals.meijerint import (_rewrite_single, _rewrite1, meijerint_indefinite, _inflate_g, _create_lookup_table, meijerint_definite, meijerint_inversion) from sympy.testing.pytest import slow from sympy.core.random import (verify_numerically, random_complex_number as randcplx) from sympy.abc import x, y, a, b, c, d, s, t, z def test_rewrite_single(): def t(expr, c, m): e = _rewrite_single(meijerg([a], [b], [c], [d], expr), x) assert e is not None assert isinstance(e[0][0][2], meijerg) assert e[0][0][2].argument.as_coeff_mul(x) == (c, (m,)) def tn(expr): assert _rewrite_single(meijerg([a], [b], [c], [d], expr), x) is None t(x, 1, x) t(x**2, 1, x**2) t(x**2 + y*x**2, y + 1, x**2) tn(x**2 + x) tn(x**y) def u(expr, x): from sympy.core.add import Add r = _rewrite_single(expr, x) e = Add(*[res[0]*res[2] for res in r[0]]).replace( exp_polar, exp) # XXX Hack? assert verify_numerically(e, expr, x) u(exp(-x)*sin(x), x) # The following has stopped working because hyperexpand changed slightly. # It is probably not worth fixing #u(exp(-x)*sin(x)*cos(x), x) # This one cannot be done numerically, since it comes out as a g-function # of argument 4*pi # NOTE This also tests a bug in inverse mellin transform (which used to # turn exp(4*pi*I*t) into a factor of exp(4*pi*I)**t instead of # exp_polar). #u(exp(x)*sin(x), x) assert _rewrite_single(exp(x)*sin(x), x) == \ ([(-sqrt(2)/(2*sqrt(pi)), 0, meijerg(((Rational(-1, 2), 0, Rational(1, 4), S.Half, Rational(3, 4)), (1,)), ((), (Rational(-1, 2), 0)), 64*exp_polar(-4*I*pi)/x**4))], True) def test_rewrite1(): assert _rewrite1(x**3*meijerg([a], [b], [c], [d], x**2 + y*x**2)*5, x) == \ (5, x**3, [(1, 0, meijerg([a], [b], [c], [d], x**2*(y + 1)))], True) def test_meijerint_indefinite_numerically(): def t(fac, arg): g = meijerg([a], [b], [c], [d], arg)*fac subs = {a: randcplx()/10, b: randcplx()/10 + I, c: randcplx(), d: randcplx()} integral = meijerint_indefinite(g, x) assert integral is not None assert verify_numerically(g.subs(subs), integral.diff(x).subs(subs), x) t(1, x) t(2, x) t(1, 2*x) t(1, x**2) t(5, x**S('3/2')) t(x**3, x) t(3*x**S('3/2'), 4*x**S('7/3')) def test_meijerint_definite(): v, b = meijerint_definite(x, x, 0, 0) assert v.is_zero and b is True v, b = meijerint_definite(x, x, oo, oo) assert v.is_zero and b is True def test_inflate(): subs = {a: randcplx()/10, b: randcplx()/10 + I, c: randcplx(), d: randcplx(), y: randcplx()/10} def t(a, b, arg, n): from sympy.core.mul import Mul m1 = meijerg(a, b, arg) m2 = Mul(*_inflate_g(m1, n)) # NOTE: (the random number)**9 must still be on the principal sheet. # Thus make b&d small to create random numbers of small imaginary part. return verify_numerically(m1.subs(subs), m2.subs(subs), x, b=0.1, d=-0.1) assert t([[a], [b]], [[c], [d]], x, 3) assert t([[a, y], [b]], [[c], [d]], x, 3) assert t([[a], [b]], [[c, y], [d]], 2*x**3, 3) def test_recursive(): from sympy.core.symbol import symbols a, b, c = symbols('a b c', positive=True) r = exp(-(x - a)**2)*exp(-(x - b)**2) e = integrate(r, (x, 0, oo), meijerg=True) assert simplify(e.expand()) == ( sqrt(2)*sqrt(pi)*( (erf(sqrt(2)*(a + b)/2) + 1)*exp(-a**2/2 + a*b - b**2/2))/4) e = integrate(exp(-(x - a)**2)*exp(-(x - b)**2)*exp(c*x), (x, 0, oo), meijerg=True) assert simplify(e) == ( sqrt(2)*sqrt(pi)*(erf(sqrt(2)*(2*a + 2*b + c)/4) + 1)*exp(-a**2 - b**2 + (2*a + 2*b + c)**2/8)/4) assert simplify(integrate(exp(-(x - a - b - c)**2), (x, 0, oo), meijerg=True)) == \ sqrt(pi)/2*(1 + erf(a + b + c)) assert simplify(integrate(exp(-(x + a + b + c)**2), (x, 0, oo), meijerg=True)) == \ sqrt(pi)/2*(1 - erf(a + b + c)) @slow def test_meijerint(): from sympy.core.function import expand from sympy.core.symbol import symbols from sympy.functions.elementary.complexes import arg s, t, mu = symbols('s t mu', real=True) assert integrate(meijerg([], [], [0], [], s*t) *meijerg([], [], [mu/2], [-mu/2], t**2/4), (t, 0, oo)).is_Piecewise s = symbols('s', positive=True) assert integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo)) == \ gamma(s + 1) assert integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo), meijerg=True) == gamma(s + 1) assert isinstance(integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo), meijerg=False), Integral) assert meijerint_indefinite(exp(x), x) == exp(x) # TODO what simplifications should be done automatically? # This tests "extra case" for antecedents_1. a, b = symbols('a b', positive=True) assert simplify(meijerint_definite(x**a, x, 0, b)[0]) == \ b**(a + 1)/(a + 1) # This tests various conditions and expansions: assert meijerint_definite((x + 1)**3*exp(-x), x, 0, oo) == (16, True) # Again, how about simplifications? sigma, mu = symbols('sigma mu', positive=True) i, c = meijerint_definite(exp(-((x - mu)/(2*sigma))**2), x, 0, oo) assert simplify(i) == sqrt(pi)*sigma*(2 - erfc(mu/(2*sigma))) assert c == True i, _ = meijerint_definite(exp(-mu*x)*exp(sigma*x), x, 0, oo) # TODO it would be nice to test the condition assert simplify(i) == 1/(mu - sigma) # Test substitutions to change limits assert meijerint_definite(exp(x), x, -oo, 2) == (exp(2), True) # Note: causes a NaN in _check_antecedents assert expand(meijerint_definite(exp(x), x, 0, I)[0]) == exp(I) - 1 assert expand(meijerint_definite(exp(-x), x, 0, x)[0]) == \ 1 - exp(-exp(I*arg(x))*abs(x)) # Test -oo to oo assert meijerint_definite(exp(-x**2), x, -oo, oo) == (sqrt(pi), True) assert meijerint_definite(exp(-abs(x)), x, -oo, oo) == (2, True) assert meijerint_definite(exp(-(2*x - 3)**2), x, -oo, oo) == \ (sqrt(pi)/2, True) assert meijerint_definite(exp(-abs(2*x - 3)), x, -oo, oo) == (1, True) assert meijerint_definite(exp(-((x - mu)/sigma)**2/2)/sqrt(2*pi*sigma**2), x, -oo, oo) == (1, True) assert meijerint_definite(sinc(x)**2, x, -oo, oo) == (pi, True) # Test one of the extra conditions for 2 g-functinos assert meijerint_definite(exp(-x)*sin(x), x, 0, oo) == (S.Half, True) # Test a bug def res(n): return (1/(1 + x**2)).diff(x, n).subs(x, 1)*(-1)**n for n in range(6): assert integrate(exp(-x)*sin(x)*x**n, (x, 0, oo), meijerg=True) == \ res(n) # This used to test trigexpand... now it is done by linear substitution assert simplify(integrate(exp(-x)*sin(x + a), (x, 0, oo), meijerg=True) ) == sqrt(2)*sin(a + pi/4)/2 # Test the condition 14 from prudnikov. # (This is besselj*besselj in disguise, to stop the product from being # recognised in the tables.) a, b, s = symbols('a b s') from sympy.functions.elementary.complexes import re assert meijerint_definite(meijerg([], [], [a/2], [-a/2], x/4) *meijerg([], [], [b/2], [-b/2], x/4)*x**(s - 1), x, 0, oo ) == ( (4*2**(2*s - 2)*gamma(-2*s + 1)*gamma(a/2 + b/2 + s) /(gamma(-a/2 + b/2 - s + 1)*gamma(a/2 - b/2 - s + 1) *gamma(a/2 + b/2 - s + 1)), (re(s) < 1) & (re(s) < S(1)/2) & (re(a)/2 + re(b)/2 + re(s) > 0))) # test a bug assert integrate(sin(x**a)*sin(x**b), (x, 0, oo), meijerg=True) == \ Integral(sin(x**a)*sin(x**b), (x, 0, oo)) # test better hyperexpand assert integrate(exp(-x**2)*log(x), (x, 0, oo), meijerg=True) == \ (sqrt(pi)*polygamma(0, S.Half)/4).expand() # Test hyperexpand bug. from sympy.functions.special.gamma_functions import lowergamma n = symbols('n', integer=True) assert simplify(integrate(exp(-x)*x**n, x, meijerg=True)) == \ lowergamma(n + 1, x) # Test a bug with argument 1/x alpha = symbols('alpha', positive=True) assert meijerint_definite((2 - x)**alpha*sin(alpha/x), x, 0, 2) == \ (sqrt(pi)*alpha*gamma(alpha + 1)*meijerg(((), (alpha/2 + S.Half, alpha/2 + 1)), ((0, 0, S.Half), (Rational(-1, 2),)), alpha**2/16)/4, True) # test a bug related to 3016 a, s = symbols('a s', positive=True) assert simplify(integrate(x**s*exp(-a*x**2), (x, -oo, oo))) == \ a**(-s/2 - S.Half)*((-1)**s + 1)*gamma(s/2 + S.Half)/2 def test_bessel(): from sympy.functions.special.bessel import (besseli, besselj) assert simplify(integrate(besselj(a, z)*besselj(b, z)/z, (z, 0, oo), meijerg=True, conds='none')) == \ 2*sin(pi*(a/2 - b/2))/(pi*(a - b)*(a + b)) assert simplify(integrate(besselj(a, z)*besselj(a, z)/z, (z, 0, oo), meijerg=True, conds='none')) == 1/(2*a) # TODO more orthogonality integrals assert simplify(integrate(sin(z*x)*(x**2 - 1)**(-(y + S.Half)), (x, 1, oo), meijerg=True, conds='none') *2/((z/2)**y*sqrt(pi)*gamma(S.Half - y))) == \ besselj(y, z) # Werner Rosenheinrich # SOME INDEFINITE INTEGRALS OF BESSEL FUNCTIONS assert integrate(x*besselj(0, x), x, meijerg=True) == x*besselj(1, x) assert integrate(x*besseli(0, x), x, meijerg=True) == x*besseli(1, x) # TODO can do higher powers, but come out as high order ... should they be # reduced to order 0, 1? assert integrate(besselj(1, x), x, meijerg=True) == -besselj(0, x) assert integrate(besselj(1, x)**2/x, x, meijerg=True) == \ -(besselj(0, x)**2 + besselj(1, x)**2)/2 # TODO more besseli when tables are extended or recursive mellin works assert integrate(besselj(0, x)**2/x**2, x, meijerg=True) == \ -2*x*besselj(0, x)**2 - 2*x*besselj(1, x)**2 \ + 2*besselj(0, x)*besselj(1, x) - besselj(0, x)**2/x assert integrate(besselj(0, x)*besselj(1, x), x, meijerg=True) == \ -besselj(0, x)**2/2 assert integrate(x**2*besselj(0, x)*besselj(1, x), x, meijerg=True) == \ x**2*besselj(1, x)**2/2 assert integrate(besselj(0, x)*besselj(1, x)/x, x, meijerg=True) == \ (x*besselj(0, x)**2 + x*besselj(1, x)**2 - besselj(0, x)*besselj(1, x)) # TODO how does besselj(0, a*x)*besselj(0, b*x) work? # TODO how does besselj(0, x)**2*besselj(1, x)**2 work? # TODO sin(x)*besselj(0, x) etc come out a mess # TODO can x*log(x)*besselj(0, x) be done? # TODO how does besselj(1, x)*besselj(0, x+a) work? # TODO more indefinite integrals when struve functions etc are implemented # test a substitution assert integrate(besselj(1, x**2)*x, x, meijerg=True) == \ -besselj(0, x**2)/2 def test_inversion(): from sympy.functions.elementary.piecewise import piecewise_fold from sympy.functions.special.bessel import besselj from sympy.functions.special.delta_functions import Heaviside def inv(f): return piecewise_fold(meijerint_inversion(f, s, t)) assert inv(1/(s**2 + 1)) == sin(t)*Heaviside(t) assert inv(s/(s**2 + 1)) == cos(t)*Heaviside(t) assert inv(exp(-s)/s) == Heaviside(t - 1) assert inv(1/sqrt(1 + s**2)) == besselj(0, t)*Heaviside(t) # Test some antcedents checking. assert meijerint_inversion(sqrt(s)/sqrt(1 + s**2), s, t) is None assert inv(exp(s**2)) is None assert meijerint_inversion(exp(-s**2), s, t) is None def test_inversion_conditional_output(): from sympy.core.symbol import Symbol from sympy.integrals.transforms import InverseLaplaceTransform a = Symbol('a', positive=True) F = sqrt(pi/a)*exp(-2*sqrt(a)*sqrt(s)) f = meijerint_inversion(F, s, t) assert not f.is_Piecewise b = Symbol('b', real=True) F = F.subs(a, b) f2 = meijerint_inversion(F, s, t) assert f2.is_Piecewise # first piece is same as f assert f2.args[0][0] == f.subs(a, b) # last piece is an unevaluated transform assert f2.args[-1][1] ILT = InverseLaplaceTransform(F, s, t, None) assert f2.args[-1][0] == ILT or f2.args[-1][0] == ILT.as_integral def test_inversion_exp_real_nonreal_shift(): from sympy.core.symbol import Symbol from sympy.functions.special.delta_functions import DiracDelta r = Symbol('r', real=True) c = Symbol('c', extended_real=False) a = 1 + 2*I z = Symbol('z') assert not meijerint_inversion(exp(r*s), s, t).is_Piecewise assert meijerint_inversion(exp(a*s), s, t) is None assert meijerint_inversion(exp(c*s), s, t) is None f = meijerint_inversion(exp(z*s), s, t) assert f.is_Piecewise assert isinstance(f.args[0][0], DiracDelta) @slow def test_lookup_table(): from sympy.core.random import uniform, randrange from sympy.core.add import Add from sympy.integrals.meijerint import z as z_dummy table = {} _create_lookup_table(table) for _, l in sorted(table.items()): for formula, terms, cond, hint in sorted(l, key=default_sort_key): subs = {} for ai in list(formula.free_symbols) + [z_dummy]: if hasattr(ai, 'properties') and ai.properties: # these Wilds match positive integers subs[ai] = randrange(1, 10) else: subs[ai] = uniform(1.5, 2.0) if not isinstance(terms, list): terms = terms(subs) # First test that hyperexpand can do this. expanded = [hyperexpand(g) for (_, g) in terms] assert all(x.is_Piecewise or not x.has(meijerg) for x in expanded) # Now test that the meijer g-function is indeed as advertised. expanded = Add(*[f*x for (f, x) in terms]) a, b = formula.n(subs=subs), expanded.n(subs=subs) r = min(abs(a), abs(b)) if r < 1: assert abs(a - b).n() <= 1e-10 else: assert (abs(a - b)/r).n() <= 1e-10 def test_branch_bug(): from sympy.functions.special.gamma_functions import lowergamma from sympy.simplify.powsimp import powdenest # TODO gammasimp cannot prove that the factor is unity assert powdenest(integrate(erf(x**3), x, meijerg=True).diff(x), polar=True) == 2*erf(x**3)*gamma(Rational(2, 3))/3/gamma(Rational(5, 3)) assert integrate(erf(x**3), x, meijerg=True) == \ 2*x*erf(x**3)*gamma(Rational(2, 3))/(3*gamma(Rational(5, 3))) \ - 2*gamma(Rational(2, 3))*lowergamma(Rational(2, 3), x**6)/(3*sqrt(pi)*gamma(Rational(5, 3))) def test_linear_subs(): from sympy.functions.special.bessel import besselj assert integrate(sin(x - 1), x, meijerg=True) == -cos(1 - x) assert integrate(besselj(1, x - 1), x, meijerg=True) == -besselj(0, 1 - x) @slow def test_probability(): # various integrals from probability theory from sympy.core.function import expand_mul from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import Abs from sympy.simplify.gammasimp import gammasimp from sympy.simplify.powsimp import powsimp mu1, mu2 = symbols('mu1 mu2', nonzero=True) sigma1, sigma2 = symbols('sigma1 sigma2', positive=True) rate = Symbol('lambda', positive=True) def normal(x, mu, sigma): return 1/sqrt(2*pi*sigma**2)*exp(-(x - mu)**2/2/sigma**2) def exponential(x, rate): return rate*exp(-rate*x) assert integrate(normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) == 1 assert integrate(x*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) == \ mu1 assert integrate(x**2*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) \ == mu1**2 + sigma1**2 assert integrate(x**3*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) \ == mu1**3 + 3*mu1*sigma1**2 assert integrate(normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == 1 assert integrate(x*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == mu1 assert integrate(y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == mu2 assert integrate(x*y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == mu1*mu2 assert integrate((x + y + 1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == 1 + mu1 + mu2 assert integrate((x + y - 1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == \ -1 + mu1 + mu2 i = integrate(x**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) assert not i.has(Abs) assert simplify(i) == mu1**2 + sigma1**2 assert integrate(y**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == \ sigma2**2 + mu2**2 assert integrate(exponential(x, rate), (x, 0, oo), meijerg=True) == 1 assert integrate(x*exponential(x, rate), (x, 0, oo), meijerg=True) == \ 1/rate assert integrate(x**2*exponential(x, rate), (x, 0, oo), meijerg=True) == \ 2/rate**2 def E(expr): res1 = integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1), (x, 0, oo), (y, -oo, oo), meijerg=True) res2 = integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1), (y, -oo, oo), (x, 0, oo), meijerg=True) assert expand_mul(res1) == expand_mul(res2) return res1 assert E(1) == 1 assert E(x*y) == mu1/rate assert E(x*y**2) == mu1**2/rate + sigma1**2/rate ans = sigma1**2 + 1/rate**2 assert simplify(E((x + y + 1)**2) - E(x + y + 1)**2) == ans assert simplify(E((x + y - 1)**2) - E(x + y - 1)**2) == ans assert simplify(E((x + y)**2) - E(x + y)**2) == ans # Beta' distribution alpha, beta = symbols('alpha beta', positive=True) betadist = x**(alpha - 1)*(1 + x)**(-alpha - beta)*gamma(alpha + beta) \ /gamma(alpha)/gamma(beta) assert integrate(betadist, (x, 0, oo), meijerg=True) == 1 i = integrate(x*betadist, (x, 0, oo), meijerg=True, conds='separate') assert (gammasimp(i[0]), i[1]) == (alpha/(beta - 1), 1 < beta) j = integrate(x**2*betadist, (x, 0, oo), meijerg=True, conds='separate') assert j[1] == (beta > 2) assert gammasimp(j[0] - i[0]**2) == (alpha + beta - 1)*alpha \ /(beta - 2)/(beta - 1)**2 # Beta distribution # NOTE: this is evaluated using antiderivatives. It also tests that # meijerint_indefinite returns the simplest possible answer. a, b = symbols('a b', positive=True) betadist = x**(a - 1)*(-x + 1)**(b - 1)*gamma(a + b)/(gamma(a)*gamma(b)) assert simplify(integrate(betadist, (x, 0, 1), meijerg=True)) == 1 assert simplify(integrate(x*betadist, (x, 0, 1), meijerg=True)) == \ a/(a + b) assert simplify(integrate(x**2*betadist, (x, 0, 1), meijerg=True)) == \ a*(a + 1)/(a + b)/(a + b + 1) assert simplify(integrate(x**y*betadist, (x, 0, 1), meijerg=True)) == \ gamma(a + b)*gamma(a + y)/gamma(a)/gamma(a + b + y) # Chi distribution k = Symbol('k', integer=True, positive=True) chi = 2**(1 - k/2)*x**(k - 1)*exp(-x**2/2)/gamma(k/2) assert powsimp(integrate(chi, (x, 0, oo), meijerg=True)) == 1 assert simplify(integrate(x*chi, (x, 0, oo), meijerg=True)) == \ sqrt(2)*gamma((k + 1)/2)/gamma(k/2) assert simplify(integrate(x**2*chi, (x, 0, oo), meijerg=True)) == k # Chi^2 distribution chisquared = 2**(-k/2)/gamma(k/2)*x**(k/2 - 1)*exp(-x/2) assert powsimp(integrate(chisquared, (x, 0, oo), meijerg=True)) == 1 assert simplify(integrate(x*chisquared, (x, 0, oo), meijerg=True)) == k assert simplify(integrate(x**2*chisquared, (x, 0, oo), meijerg=True)) == \ k*(k + 2) assert gammasimp(integrate(((x - k)/sqrt(2*k))**3*chisquared, (x, 0, oo), meijerg=True)) == 2*sqrt(2)/sqrt(k) # Dagum distribution a, b, p = symbols('a b p', positive=True) # XXX (x/b)**a does not work dagum = a*p/x*(x/b)**(a*p)/(1 + x**a/b**a)**(p + 1) assert simplify(integrate(dagum, (x, 0, oo), meijerg=True)) == 1 # XXX conditions are a mess arg = x*dagum assert simplify(integrate(arg, (x, 0, oo), meijerg=True, conds='none') ) == a*b*gamma(1 - 1/a)*gamma(p + 1 + 1/a)/( (a*p + 1)*gamma(p)) assert simplify(integrate(x*arg, (x, 0, oo), meijerg=True, conds='none') ) == a*b**2*gamma(1 - 2/a)*gamma(p + 1 + 2/a)/( (a*p + 2)*gamma(p)) # F-distribution d1, d2 = symbols('d1 d2', positive=True) f = sqrt(((d1*x)**d1 * d2**d2)/(d1*x + d2)**(d1 + d2))/x \ /gamma(d1/2)/gamma(d2/2)*gamma((d1 + d2)/2) assert simplify(integrate(f, (x, 0, oo), meijerg=True)) == 1 # TODO conditions are a mess assert simplify(integrate(x*f, (x, 0, oo), meijerg=True, conds='none') ) == d2/(d2 - 2) assert simplify(integrate(x**2*f, (x, 0, oo), meijerg=True, conds='none') ) == d2**2*(d1 + 2)/d1/(d2 - 4)/(d2 - 2) # TODO gamma, rayleigh # inverse gaussian lamda, mu = symbols('lamda mu', positive=True) dist = sqrt(lamda/2/pi)*x**(Rational(-3, 2))*exp(-lamda*(x - mu)**2/x/2/mu**2) mysimp = lambda expr: simplify(expr.rewrite(exp)) assert mysimp(integrate(dist, (x, 0, oo))) == 1 assert mysimp(integrate(x*dist, (x, 0, oo))) == mu assert mysimp(integrate((x - mu)**2*dist, (x, 0, oo))) == mu**3/lamda assert mysimp(integrate((x - mu)**3*dist, (x, 0, oo))) == 3*mu**5/lamda**2 # Levi c = Symbol('c', positive=True) assert integrate(sqrt(c/2/pi)*exp(-c/2/(x - mu))/(x - mu)**S('3/2'), (x, mu, oo)) == 1 # higher moments oo # log-logistic alpha, beta = symbols('alpha beta', positive=True) distn = (beta/alpha)*x**(beta - 1)/alpha**(beta - 1)/ \ (1 + x**beta/alpha**beta)**2 # FIXME: If alpha, beta are not declared as finite the line below hangs # after the changes in: # https://github.com/sympy/sympy/pull/16603 assert simplify(integrate(distn, (x, 0, oo))) == 1 # NOTE the conditions are a mess, but correctly state beta > 1 assert simplify(integrate(x*distn, (x, 0, oo), conds='none')) == \ pi*alpha/beta/sin(pi/beta) # (similar comment for conditions applies) assert simplify(integrate(x**y*distn, (x, 0, oo), conds='none')) == \ pi*alpha**y*y/beta/sin(pi*y/beta) # weibull k = Symbol('k', positive=True) n = Symbol('n', positive=True) distn = k/lamda*(x/lamda)**(k - 1)*exp(-(x/lamda)**k) assert simplify(integrate(distn, (x, 0, oo))) == 1 assert simplify(integrate(x**n*distn, (x, 0, oo))) == \ lamda**n*gamma(1 + n/k) # rice distribution from sympy.functions.special.bessel import besseli nu, sigma = symbols('nu sigma', positive=True) rice = x/sigma**2*exp(-(x**2 + nu**2)/2/sigma**2)*besseli(0, x*nu/sigma**2) assert integrate(rice, (x, 0, oo), meijerg=True) == 1 # can someone verify higher moments? # Laplace distribution mu = Symbol('mu', real=True) b = Symbol('b', positive=True) laplace = exp(-abs(x - mu)/b)/2/b assert integrate(laplace, (x, -oo, oo), meijerg=True) == 1 assert integrate(x*laplace, (x, -oo, oo), meijerg=True) == mu assert integrate(x**2*laplace, (x, -oo, oo), meijerg=True) == \ 2*b**2 + mu**2 # TODO are there other distributions supported on (-oo, oo) that we can do? # misc tests k = Symbol('k', positive=True) assert gammasimp(expand_mul(integrate(log(x)*x**(k - 1)*exp(-x)/gamma(k), (x, 0, oo)))) == polygamma(0, k) @slow def test_expint(): """ Test various exponential integrals. """ from sympy.core.symbol import Symbol from sympy.functions.elementary.complexes import unpolarify from sympy.functions.elementary.hyperbolic import sinh from sympy.functions.special.error_functions import (Chi, Ci, Ei, Shi, Si, expint) assert simplify(unpolarify(integrate(exp(-z*x)/x**y, (x, 1, oo), meijerg=True, conds='none' ).rewrite(expint).expand(func=True))) == expint(y, z) assert integrate(exp(-z*x)/x, (x, 1, oo), meijerg=True, conds='none').rewrite(expint).expand() == \ expint(1, z) assert integrate(exp(-z*x)/x**2, (x, 1, oo), meijerg=True, conds='none').rewrite(expint).expand() == \ expint(2, z).rewrite(Ei).rewrite(expint) assert integrate(exp(-z*x)/x**3, (x, 1, oo), meijerg=True, conds='none').rewrite(expint).expand() == \ expint(3, z).rewrite(Ei).rewrite(expint).expand() t = Symbol('t', positive=True) assert integrate(-cos(x)/x, (x, t, oo), meijerg=True).expand() == Ci(t) assert integrate(-sin(x)/x, (x, t, oo), meijerg=True).expand() == \ Si(t) - pi/2 assert integrate(sin(x)/x, (x, 0, z), meijerg=True) == Si(z) assert integrate(sinh(x)/x, (x, 0, z), meijerg=True) == Shi(z) assert integrate(exp(-x)/x, x, meijerg=True).expand().rewrite(expint) == \ I*pi - expint(1, x) assert integrate(exp(-x)/x**2, x, meijerg=True).rewrite(expint).expand() \ == expint(1, x) - exp(-x)/x - I*pi u = Symbol('u', polar=True) assert integrate(cos(u)/u, u, meijerg=True).expand().as_independent(u)[1] \ == Ci(u) assert integrate(cosh(u)/u, u, meijerg=True).expand().as_independent(u)[1] \ == Chi(u) assert integrate(expint(1, x), x, meijerg=True ).rewrite(expint).expand() == x*expint(1, x) - exp(-x) assert integrate(expint(2, x), x, meijerg=True ).rewrite(expint).expand() == \ -x**2*expint(1, x)/2 + x*exp(-x)/2 - exp(-x)/2 assert simplify(unpolarify(integrate(expint(y, x), x, meijerg=True).rewrite(expint).expand(func=True))) == \ -expint(y + 1, x) assert integrate(Si(x), x, meijerg=True) == x*Si(x) + cos(x) assert integrate(Ci(u), u, meijerg=True).expand() == u*Ci(u) - sin(u) assert integrate(Shi(x), x, meijerg=True) == x*Shi(x) - cosh(x) assert integrate(Chi(u), u, meijerg=True).expand() == u*Chi(u) - sinh(u) assert integrate(Si(x)*exp(-x), (x, 0, oo), meijerg=True) == pi/4 assert integrate(expint(1, x)*sin(x), (x, 0, oo), meijerg=True) == log(2)/2 def test_messy(): from sympy.functions.elementary.complexes import re from sympy.functions.elementary.hyperbolic import (acosh, acoth) from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (asin, atan) from sympy.functions.special.bessel import besselj from sympy.functions.special.error_functions import (Chi, E1, Shi, Si) from sympy.integrals.transforms import (fourier_transform, laplace_transform) assert laplace_transform(Si(x), x, s) == ((-atan(s) + pi/2)/s, 0, True) assert laplace_transform(Shi(x), x, s) == ( acoth(s)/s, -oo, s**2 > 1) # where should the logs be simplified? assert laplace_transform(Chi(x), x, s) == ( (log(s**(-2)) - log(1 - 1/s**2))/(2*s), -oo, s**2 > 1) # TODO maybe simplify the inequalities? when the simplification # allows for generators instead of symbols this will work assert laplace_transform(besselj(a, x), x, s)[1:] == \ (0, (re(a) > -2) & (re(a) > -1)) # NOTE s < 0 can be done, but argument reduction is not good enough yet ans = fourier_transform(besselj(1, x)/x, x, s, noconds=False) assert tuple([ans[0].factor(deep=True).expand(), ans[1]]) == \ (Piecewise((0, (s > 1/(2*pi)) | (s < -1/(2*pi))), (2*sqrt(-4*pi**2*s**2 + 1), True)), s > 0) # TODO FT(besselj(0,x)) - conditions are messy (but for acceptable reasons) # - folding could be better assert integrate(E1(x)*besselj(0, x), (x, 0, oo), meijerg=True) == \ log(1 + sqrt(2)) assert integrate(E1(x)*besselj(1, x), (x, 0, oo), meijerg=True) == \ log(S.Half + sqrt(2)/2) assert integrate(1/x/sqrt(1 - x**2), x, meijerg=True) == \ Piecewise((-acosh(1/x), abs(x**(-2)) > 1), (I*asin(1/x), True)) def test_issue_6122(): assert integrate(exp(-I*x**2), (x, -oo, oo), meijerg=True) == \ -I*sqrt(pi)*exp(I*pi/4) def test_issue_6252(): expr = 1/x/(a + b*x)**Rational(1, 3) anti = integrate(expr, x, meijerg=True) assert not anti.has(hyper) # XXX the expression is a mess, but actually upon differentiation and # putting in numerical values seems to work... def test_issue_6348(): assert integrate(exp(I*x)/(1 + x**2), (x, -oo, oo)).simplify().rewrite(exp) \ == pi*exp(-1) def test_fresnel(): from sympy.functions.special.error_functions import (fresnelc, fresnels) assert expand_func(integrate(sin(pi*x**2/2), x)) == fresnels(x) assert expand_func(integrate(cos(pi*x**2/2), x)) == fresnelc(x) def test_issue_6860(): assert meijerint_indefinite(x**x**x, x) is None def test_issue_7337(): f = meijerint_indefinite(x*sqrt(2*x + 3), x).together() assert f == sqrt(2*x + 3)*(2*x**2 + x - 3)/5 assert f._eval_interval(x, S.NegativeOne, S.One) == Rational(2, 5) def test_issue_8368(): assert meijerint_indefinite(cosh(x)*exp(-x*t), x) == ( (-t - 1)*exp(x) + (-t + 1)*exp(-x))*exp(-t*x)/2/(t**2 - 1) def test_issue_10211(): from sympy.abc import h, w assert integrate((1/sqrt((y-x)**2 + h**2)**3), (x,0,w), (y,0,w)) == \ 2*sqrt(1 + w**2/h**2)/h - 2/h def test_issue_11806(): from sympy.core.symbol import symbols y, L = symbols('y L', positive=True) assert integrate(1/sqrt(x**2 + y**2)**3, (x, -L, L)) == \ 2*L/(y**2*sqrt(L**2 + y**2)) def test_issue_10681(): from sympy.polys.domains.realfield import RR from sympy.abc import R, r f = integrate(r**2*(R**2-r**2)**0.5, r, meijerg=True) g = (1.0/3)*R**1.0*r**3*hyper((-0.5, Rational(3, 2)), (Rational(5, 2),), r**2*exp_polar(2*I*pi)/R**2) assert RR.almosteq((f/g).n(), 1.0, 1e-12) def test_issue_13536(): from sympy.core.symbol import Symbol a = Symbol('a', positive=True) assert integrate(1/x**2, (x, oo, a)) == -1/a def test_issue_6462(): from sympy.core.symbol import Symbol x = Symbol('x') n = Symbol('n') # Not the actual issue, still wrong answer for n = 1, but that there is no # exception assert integrate(cos(x**n)/x**n, x, meijerg=True).subs(n, 2).equals( integrate(cos(x**2)/x**2, x, meijerg=True)) def test_indefinite_1_bug(): assert integrate((b + t)**(-a), t, meijerg=True ) == -b/(b**a*(1 + t/b)**a*(a - 1) ) - t/(b**a*(1 + t/b)**a*(a - 1))
253aea386ba27e68af2d991a73f7ff0b1f406c83b262cc8a9ef01526e3d20550
from sympy.integrals.transforms import (mellin_transform, inverse_mellin_transform, laplace_transform, inverse_laplace_transform, fourier_transform, inverse_fourier_transform, sine_transform, inverse_sine_transform, cosine_transform, inverse_cosine_transform, hankel_transform, inverse_hankel_transform, LaplaceTransform, FourierTransform, SineTransform, CosineTransform, InverseLaplaceTransform, InverseFourierTransform, InverseSineTransform, InverseCosineTransform, IntegralTransformError) from sympy.core.function import (Function, expand_mul) from sympy.core import EulerGamma, Subs, Derivative, diff from sympy.core.numbers import (I, Rational, oo, pi) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.complexes import (Abs, re, unpolarify) from sympy.functions.elementary.exponential import (exp, exp_polar, log) from sympy.functions.elementary.hyperbolic import (cosh, sinh, coth, asinh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (atan, atan2, cos, sin, tan) from sympy.functions.special.bessel import (besseli, besselj, besselk, bessely) from sympy.functions.special.delta_functions import Heaviside from sympy.functions.special.error_functions import (erf, erfc, expint, Ei) from sympy.functions.special.gamma_functions import gamma from sympy.functions.special.hyper import meijerg from sympy.simplify.gammasimp import gammasimp from sympy.simplify.hyperexpand import hyperexpand from sympy.simplify.trigsimp import trigsimp from sympy.testing.pytest import XFAIL, slow, skip, raises, warns_deprecated_sympy from sympy.matrices import Matrix, eye from sympy.abc import x, s, a, b, c, d nu, beta, rho = symbols('nu beta rho') def test_undefined_function(): from sympy.integrals.transforms import MellinTransform f = Function('f') assert mellin_transform(f(x), x, s) == MellinTransform(f(x), x, s) assert mellin_transform(f(x) + exp(-x), x, s) == \ (MellinTransform(f(x), x, s) + gamma(s + 1)/s, (0, oo), True) def test_free_symbols(): f = Function('f') assert mellin_transform(f(x), x, s).free_symbols == {s} assert mellin_transform(f(x)*a, x, s).free_symbols == {s, a} def test_as_integral(): from sympy.integrals.integrals import Integral f = Function('f') assert mellin_transform(f(x), x, s).rewrite('Integral') == \ Integral(x**(s - 1)*f(x), (x, 0, oo)) assert fourier_transform(f(x), x, s).rewrite('Integral') == \ Integral(f(x)*exp(-2*I*pi*s*x), (x, -oo, oo)) assert laplace_transform(f(x), x, s).rewrite('Integral') == \ Integral(f(x)*exp(-s*x), (x, 0, oo)) assert str(2*pi*I*inverse_mellin_transform(f(s), s, x, (a, b)).rewrite('Integral')) \ == "Integral(f(s)/x**s, (s, _c - oo*I, _c + oo*I))" assert str(2*pi*I*inverse_laplace_transform(f(s), s, x).rewrite('Integral')) == \ "Integral(f(s)*exp(s*x), (s, _c - oo*I, _c + oo*I))" assert inverse_fourier_transform(f(s), s, x).rewrite('Integral') == \ Integral(f(s)*exp(2*I*pi*s*x), (s, -oo, oo)) # NOTE this is stuck in risch because meijerint cannot handle it @slow @XFAIL def test_mellin_transform_fail(): skip("Risch takes forever.") MT = mellin_transform bpos = symbols('b', positive=True) # bneg = symbols('b', negative=True) expr = (sqrt(x + b**2) + b)**a/sqrt(x + b**2) # TODO does not work with bneg, argument wrong. Needs changes to matching. assert MT(expr.subs(b, -bpos), x, s) == \ ((-1)**(a + 1)*2**(a + 2*s)*bpos**(a + 2*s - 1)*gamma(a + s) *gamma(1 - a - 2*s)/gamma(1 - s), (-re(a), -re(a)/2 + S.Half), True) expr = (sqrt(x + b**2) + b)**a assert MT(expr.subs(b, -bpos), x, s) == \ ( 2**(a + 2*s)*a*bpos**(a + 2*s)*gamma(-a - 2* s)*gamma(a + s)/gamma(-s + 1), (-re(a), -re(a)/2), True) # Test exponent 1: assert MT(expr.subs({b: -bpos, a: 1}), x, s) == \ (-bpos**(2*s + 1)*gamma(s)*gamma(-s - S.Half)/(2*sqrt(pi)), (-1, Rational(-1, 2)), True) def test_mellin_transform(): from sympy.functions.elementary.miscellaneous import (Max, Min) MT = mellin_transform bpos = symbols('b', positive=True) # 8.4.2 assert MT(x**nu*Heaviside(x - 1), x, s) == \ (-1/(nu + s), (-oo, -re(nu)), True) assert MT(x**nu*Heaviside(1 - x), x, s) == \ (1/(nu + s), (-re(nu), oo), True) assert MT((1 - x)**(beta - 1)*Heaviside(1 - x), x, s) == \ (gamma(beta)*gamma(s)/gamma(beta + s), (0, oo), re(beta) > 0) assert MT((x - 1)**(beta - 1)*Heaviside(x - 1), x, s) == \ (gamma(beta)*gamma(1 - beta - s)/gamma(1 - s), (-oo, 1 - re(beta)), re(beta) > 0) assert MT((1 + x)**(-rho), x, s) == \ (gamma(s)*gamma(rho - s)/gamma(rho), (0, re(rho)), True) assert MT(abs(1 - x)**(-rho), x, s) == ( 2*sin(pi*rho/2)*gamma(1 - rho)* cos(pi*(s - rho/2))*gamma(s)*gamma(rho-s)/pi, (0, re(rho)), re(rho) < 1) mt = MT((1 - x)**(beta - 1)*Heaviside(1 - x) + a*(x - 1)**(beta - 1)*Heaviside(x - 1), x, s) assert mt[1], mt[2] == ((0, -re(beta) + 1), re(beta) > 0) assert MT((x**a - b**a)/(x - b), x, s)[0] == \ pi*b**(a + s - 1)*sin(pi*a)/(sin(pi*s)*sin(pi*(a + s))) assert MT((x**a - bpos**a)/(x - bpos), x, s) == \ (pi*bpos**(a + s - 1)*sin(pi*a)/(sin(pi*s)*sin(pi*(a + s))), (Max(0, -re(a)), Min(1, 1 - re(a))), True) expr = (sqrt(x + b**2) + b)**a assert MT(expr.subs(b, bpos), x, s) == \ (-a*(2*bpos)**(a + 2*s)*gamma(s)*gamma(-a - 2*s)/gamma(-a - s + 1), (0, -re(a)/2), True) expr = (sqrt(x + b**2) + b)**a/sqrt(x + b**2) assert MT(expr.subs(b, bpos), x, s) == \ (2**(a + 2*s)*bpos**(a + 2*s - 1)*gamma(s) *gamma(1 - a - 2*s)/gamma(1 - a - s), (0, -re(a)/2 + S.Half), True) # 8.4.2 assert MT(exp(-x), x, s) == (gamma(s), (0, oo), True) assert MT(exp(-1/x), x, s) == (gamma(-s), (-oo, 0), True) # 8.4.5 assert MT(log(x)**4*Heaviside(1 - x), x, s) == (24/s**5, (0, oo), True) assert MT(log(x)**3*Heaviside(x - 1), x, s) == (6/s**4, (-oo, 0), True) assert MT(log(x + 1), x, s) == (pi/(s*sin(pi*s)), (-1, 0), True) assert MT(log(1/x + 1), x, s) == (pi/(s*sin(pi*s)), (0, 1), True) assert MT(log(abs(1 - x)), x, s) == (pi/(s*tan(pi*s)), (-1, 0), True) assert MT(log(abs(1 - 1/x)), x, s) == (pi/(s*tan(pi*s)), (0, 1), True) # 8.4.14 assert MT(erf(sqrt(x)), x, s) == \ (-gamma(s + S.Half)/(sqrt(pi)*s), (Rational(-1, 2), 0), True) def test_mellin_transform2(): MT = mellin_transform # TODO we cannot currently do these (needs summation of 3F2(-1)) # this also implies that they cannot be written as a single g-function # (although this is possible) mt = MT(log(x)/(x + 1), x, s) assert mt[1:] == ((0, 1), True) assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg) mt = MT(log(x)**2/(x + 1), x, s) assert mt[1:] == ((0, 1), True) assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg) mt = MT(log(x)/(x + 1)**2, x, s) assert mt[1:] == ((0, 2), True) assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg) @slow def test_mellin_transform_bessel(): from sympy.functions.elementary.miscellaneous import Max MT = mellin_transform # 8.4.19 assert MT(besselj(a, 2*sqrt(x)), x, s) == \ (gamma(a/2 + s)/gamma(a/2 - s + 1), (-re(a)/2, Rational(3, 4)), True) assert MT(sin(sqrt(x))*besselj(a, sqrt(x)), x, s) == \ (2**a*gamma(-2*s + S.Half)*gamma(a/2 + s + S.Half)/( gamma(-a/2 - s + 1)*gamma(a - 2*s + 1)), ( -re(a)/2 - S.Half, Rational(1, 4)), True) assert MT(cos(sqrt(x))*besselj(a, sqrt(x)), x, s) == \ (2**a*gamma(a/2 + s)*gamma(-2*s + S.Half)/( gamma(-a/2 - s + S.Half)*gamma(a - 2*s + 1)), ( -re(a)/2, Rational(1, 4)), True) assert MT(besselj(a, sqrt(x))**2, x, s) == \ (gamma(a + s)*gamma(S.Half - s) / (sqrt(pi)*gamma(1 - s)*gamma(1 + a - s)), (-re(a), S.Half), True) assert MT(besselj(a, sqrt(x))*besselj(-a, sqrt(x)), x, s) == \ (gamma(s)*gamma(S.Half - s) / (sqrt(pi)*gamma(1 - a - s)*gamma(1 + a - s)), (0, S.Half), True) # NOTE: prudnikov gives the strip below as (1/2 - re(a), 1). As far as # I can see this is wrong (since besselj(z) ~ 1/sqrt(z) for z large) assert MT(besselj(a - 1, sqrt(x))*besselj(a, sqrt(x)), x, s) == \ (gamma(1 - s)*gamma(a + s - S.Half) / (sqrt(pi)*gamma(Rational(3, 2) - s)*gamma(a - s + S.Half)), (S.Half - re(a), S.Half), True) assert MT(besselj(a, sqrt(x))*besselj(b, sqrt(x)), x, s) == \ (4**s*gamma(1 - 2*s)*gamma((a + b)/2 + s) / (gamma(1 - s + (b - a)/2)*gamma(1 - s + (a - b)/2) *gamma( 1 - s + (a + b)/2)), (-(re(a) + re(b))/2, S.Half), True) assert MT(besselj(a, sqrt(x))**2 + besselj(-a, sqrt(x))**2, x, s)[1:] == \ ((Max(re(a), -re(a)), S.Half), True) # Section 8.4.20 assert MT(bessely(a, 2*sqrt(x)), x, s) == \ (-cos(pi*(a/2 - s))*gamma(s - a/2)*gamma(s + a/2)/pi, (Max(-re(a)/2, re(a)/2), Rational(3, 4)), True) assert MT(sin(sqrt(x))*bessely(a, sqrt(x)), x, s) == \ (-4**s*sin(pi*(a/2 - s))*gamma(S.Half - 2*s) * gamma((1 - a)/2 + s)*gamma((1 + a)/2 + s) / (sqrt(pi)*gamma(1 - s - a/2)*gamma(1 - s + a/2)), (Max(-(re(a) + 1)/2, (re(a) - 1)/2), Rational(1, 4)), True) assert MT(cos(sqrt(x))*bessely(a, sqrt(x)), x, s) == \ (-4**s*cos(pi*(a/2 - s))*gamma(s - a/2)*gamma(s + a/2)*gamma(S.Half - 2*s) / (sqrt(pi)*gamma(S.Half - s - a/2)*gamma(S.Half - s + a/2)), (Max(-re(a)/2, re(a)/2), Rational(1, 4)), True) assert MT(besselj(a, sqrt(x))*bessely(a, sqrt(x)), x, s) == \ (-cos(pi*s)*gamma(s)*gamma(a + s)*gamma(S.Half - s) / (pi**S('3/2')*gamma(1 + a - s)), (Max(-re(a), 0), S.Half), True) assert MT(besselj(a, sqrt(x))*bessely(b, sqrt(x)), x, s) == \ (-4**s*cos(pi*(a/2 - b/2 + s))*gamma(1 - 2*s) * gamma(a/2 - b/2 + s)*gamma(a/2 + b/2 + s) / (pi*gamma(a/2 - b/2 - s + 1)*gamma(a/2 + b/2 - s + 1)), (Max((-re(a) + re(b))/2, (-re(a) - re(b))/2), S.Half), True) # NOTE bessely(a, sqrt(x))**2 and bessely(a, sqrt(x))*bessely(b, sqrt(x)) # are a mess (no matter what way you look at it ...) assert MT(bessely(a, sqrt(x))**2, x, s)[1:] == \ ((Max(-re(a), 0, re(a)), S.Half), True) # Section 8.4.22 # TODO we can't do any of these (delicate cancellation) # Section 8.4.23 assert MT(besselk(a, 2*sqrt(x)), x, s) == \ (gamma( s - a/2)*gamma(s + a/2)/2, (Max(-re(a)/2, re(a)/2), oo), True) assert MT(besselj(a, 2*sqrt(2*sqrt(x)))*besselk( a, 2*sqrt(2*sqrt(x))), x, s) == (4**(-s)*gamma(2*s)* gamma(a/2 + s)/(2*gamma(a/2 - s + 1)), (Max(0, -re(a)/2), oo), True) # TODO bessely(a, x)*besselk(a, x) is a mess assert MT(besseli(a, sqrt(x))*besselk(a, sqrt(x)), x, s) == \ (gamma(s)*gamma( a + s)*gamma(-s + S.Half)/(2*sqrt(pi)*gamma(a - s + 1)), (Max(-re(a), 0), S.Half), True) assert MT(besseli(b, sqrt(x))*besselk(a, sqrt(x)), x, s) == \ (2**(2*s - 1)*gamma(-2*s + 1)*gamma(-a/2 + b/2 + s)* \ gamma(a/2 + b/2 + s)/(gamma(-a/2 + b/2 - s + 1)* \ gamma(a/2 + b/2 - s + 1)), (Max(-re(a)/2 - re(b)/2, \ re(a)/2 - re(b)/2), S.Half), True) # TODO products of besselk are a mess mt = MT(exp(-x/2)*besselk(a, x/2), x, s) mt0 = gammasimp(trigsimp(gammasimp(mt[0].expand(func=True)))) assert mt0 == 2*pi**Rational(3, 2)*cos(pi*s)*gamma(S.Half - s)/( (cos(2*pi*a) - cos(2*pi*s))*gamma(-a - s + 1)*gamma(a - s + 1)) assert mt[1:] == ((Max(-re(a), re(a)), oo), True) # TODO exp(x/2)*besselk(a, x/2) [etc] cannot currently be done # TODO various strange products of special orders @slow def test_expint(): from sympy.functions.elementary.miscellaneous import Max from sympy.functions.special.error_functions import (Ci, E1, Ei, Si) from sympy.functions.special.zeta_functions import lerchphi from sympy.simplify.simplify import simplify aneg = Symbol('a', negative=True) u = Symbol('u', polar=True) assert mellin_transform(E1(x), x, s) == (gamma(s)/s, (0, oo), True) assert inverse_mellin_transform(gamma(s)/s, s, x, (0, oo)).rewrite(expint).expand() == E1(x) assert mellin_transform(expint(a, x), x, s) == \ (gamma(s)/(a + s - 1), (Max(1 - re(a), 0), oo), True) # XXX IMT has hickups with complicated strips ... assert simplify(unpolarify( inverse_mellin_transform(gamma(s)/(aneg + s - 1), s, x, (1 - aneg, oo)).rewrite(expint).expand(func=True))) == \ expint(aneg, x) assert mellin_transform(Si(x), x, s) == \ (-2**s*sqrt(pi)*gamma(s/2 + S.Half)/( 2*s*gamma(-s/2 + 1)), (-1, 0), True) assert inverse_mellin_transform(-2**s*sqrt(pi)*gamma((s + 1)/2) /(2*s*gamma(-s/2 + 1)), s, x, (-1, 0)) \ == Si(x) assert mellin_transform(Ci(sqrt(x)), x, s) == \ (-2**(2*s - 1)*sqrt(pi)*gamma(s)/(s*gamma(-s + S.Half)), (0, 1), True) assert inverse_mellin_transform( -4**s*sqrt(pi)*gamma(s)/(2*s*gamma(-s + S.Half)), s, u, (0, 1)).expand() == Ci(sqrt(u)) # TODO LT of Si, Shi, Chi is a mess ... assert laplace_transform(Ci(x), x, s) == (-log(1 + s**2)/2/s, 0, True) assert laplace_transform(expint(a, x), x, s) == \ (lerchphi(s*exp_polar(I*pi), 1, a), 0, re(a) > S.Zero) assert laplace_transform(expint(1, x), x, s) == (log(s + 1)/s, 0, True) assert laplace_transform(expint(2, x), x, s) == \ ((s - log(s + 1))/s**2, 0, True) assert inverse_laplace_transform(-log(1 + s**2)/2/s, s, u).expand() == \ Heaviside(u)*Ci(u) assert inverse_laplace_transform(log(s + 1)/s, s, x).rewrite(expint) == \ Heaviside(x)*E1(x) assert inverse_laplace_transform((s - log(s + 1))/s**2, s, x).rewrite(expint).expand() == \ (expint(2, x)*Heaviside(x)).rewrite(Ei).rewrite(expint).expand() @slow def test_inverse_mellin_transform(): from sympy.core.function import expand from sympy.functions.elementary.miscellaneous import (Max, Min) from sympy.functions.elementary.trigonometric import cot from sympy.simplify.powsimp import powsimp from sympy.simplify.simplify import simplify IMT = inverse_mellin_transform assert IMT(gamma(s), s, x, (0, oo)) == exp(-x) assert IMT(gamma(-s), s, x, (-oo, 0)) == exp(-1/x) assert simplify(IMT(s/(2*s**2 - 2), s, x, (2, oo))) == \ (x**2 + 1)*Heaviside(1 - x)/(4*x) # test passing "None" assert IMT(1/(s**2 - 1), s, x, (-1, None)) == \ -x*Heaviside(-x + 1)/2 - Heaviside(x - 1)/(2*x) assert IMT(1/(s**2 - 1), s, x, (None, 1)) == \ -x*Heaviside(-x + 1)/2 - Heaviside(x - 1)/(2*x) # test expansion of sums assert IMT(gamma(s) + gamma(s - 1), s, x, (1, oo)) == (x + 1)*exp(-x)/x # test factorisation of polys r = symbols('r', real=True) assert IMT(1/(s**2 + 1), s, exp(-x), (None, oo) ).subs(x, r).rewrite(sin).simplify() \ == sin(r)*Heaviside(1 - exp(-r)) # test multiplicative substitution _a, _b = symbols('a b', positive=True) assert IMT(_b**(-s/_a)*factorial(s/_a)/s, s, x, (0, oo)) == exp(-_b*x**_a) assert IMT(factorial(_a/_b + s/_b)/(_a + s), s, x, (-_a, oo)) == x**_a*exp(-x**_b) def simp_pows(expr): return simplify(powsimp(expand_mul(expr, deep=False), force=True)).replace(exp_polar, exp) # Now test the inverses of all direct transforms tested above # Section 8.4.2 nu = symbols('nu', real=True) assert IMT(-1/(nu + s), s, x, (-oo, None)) == x**nu*Heaviside(x - 1) assert IMT(1/(nu + s), s, x, (None, oo)) == x**nu*Heaviside(1 - x) assert simp_pows(IMT(gamma(beta)*gamma(s)/gamma(s + beta), s, x, (0, oo))) \ == (1 - x)**(beta - 1)*Heaviside(1 - x) assert simp_pows(IMT(gamma(beta)*gamma(1 - beta - s)/gamma(1 - s), s, x, (-oo, None))) \ == (x - 1)**(beta - 1)*Heaviside(x - 1) assert simp_pows(IMT(gamma(s)*gamma(rho - s)/gamma(rho), s, x, (0, None))) \ == (1/(x + 1))**rho assert simp_pows(IMT(d**c*d**(s - 1)*sin(pi*c) *gamma(s)*gamma(s + c)*gamma(1 - s)*gamma(1 - s - c)/pi, s, x, (Max(-re(c), 0), Min(1 - re(c), 1)))) \ == (x**c - d**c)/(x - d) assert simplify(IMT(1/sqrt(pi)*(-c/2)*gamma(s)*gamma((1 - c)/2 - s) *gamma(-c/2 - s)/gamma(1 - c - s), s, x, (0, -re(c)/2))) == \ (1 + sqrt(x + 1))**c assert simplify(IMT(2**(a + 2*s)*b**(a + 2*s - 1)*gamma(s)*gamma(1 - a - 2*s) /gamma(1 - a - s), s, x, (0, (-re(a) + 1)/2))) == \ b**(a - 1)*(sqrt(1 + x/b**2) + 1)**(a - 1)*(b**2*sqrt(1 + x/b**2) + b**2 + x)/(b**2 + x) assert simplify(IMT(-2**(c + 2*s)*c*b**(c + 2*s)*gamma(s)*gamma(-c - 2*s) / gamma(-c - s + 1), s, x, (0, -re(c)/2))) == \ b**c*(sqrt(1 + x/b**2) + 1)**c # Section 8.4.5 assert IMT(24/s**5, s, x, (0, oo)) == log(x)**4*Heaviside(1 - x) assert expand(IMT(6/s**4, s, x, (-oo, 0)), force=True) == \ log(x)**3*Heaviside(x - 1) assert IMT(pi/(s*sin(pi*s)), s, x, (-1, 0)) == log(x + 1) assert IMT(pi/(s*sin(pi*s/2)), s, x, (-2, 0)) == log(x**2 + 1) assert IMT(pi/(s*sin(2*pi*s)), s, x, (Rational(-1, 2), 0)) == log(sqrt(x) + 1) assert IMT(pi/(s*sin(pi*s)), s, x, (0, 1)) == log(1 + 1/x) # TODO def mysimp(expr): from sympy.core.function import expand from sympy.simplify.powsimp import powsimp from sympy.simplify.simplify import logcombine return expand( powsimp(logcombine(expr, force=True), force=True, deep=True), force=True).replace(exp_polar, exp) assert mysimp(mysimp(IMT(pi/(s*tan(pi*s)), s, x, (-1, 0)))) in [ log(1 - x)*Heaviside(1 - x) + log(x - 1)*Heaviside(x - 1), log(x)*Heaviside(x - 1) + log(1 - 1/x)*Heaviside(x - 1) + log(-x + 1)*Heaviside(-x + 1)] # test passing cot assert mysimp(IMT(pi*cot(pi*s)/s, s, x, (0, 1))) in [ log(1/x - 1)*Heaviside(1 - x) + log(1 - 1/x)*Heaviside(x - 1), -log(x)*Heaviside(-x + 1) + log(1 - 1/x)*Heaviside(x - 1) + log(-x + 1)*Heaviside(-x + 1), ] # 8.4.14 assert IMT(-gamma(s + S.Half)/(sqrt(pi)*s), s, x, (Rational(-1, 2), 0)) == \ erf(sqrt(x)) # 8.4.19 assert simplify(IMT(gamma(a/2 + s)/gamma(a/2 - s + 1), s, x, (-re(a)/2, Rational(3, 4)))) \ == besselj(a, 2*sqrt(x)) assert simplify(IMT(2**a*gamma(S.Half - 2*s)*gamma(s + (a + 1)/2) / (gamma(1 - s - a/2)*gamma(1 - 2*s + a)), s, x, (-(re(a) + 1)/2, Rational(1, 4)))) == \ sin(sqrt(x))*besselj(a, sqrt(x)) assert simplify(IMT(2**a*gamma(a/2 + s)*gamma(S.Half - 2*s) / (gamma(S.Half - s - a/2)*gamma(1 - 2*s + a)), s, x, (-re(a)/2, Rational(1, 4)))) == \ cos(sqrt(x))*besselj(a, sqrt(x)) # TODO this comes out as an amazing mess, but simplifies nicely assert simplify(IMT(gamma(a + s)*gamma(S.Half - s) / (sqrt(pi)*gamma(1 - s)*gamma(1 + a - s)), s, x, (-re(a), S.Half))) == \ besselj(a, sqrt(x))**2 assert simplify(IMT(gamma(s)*gamma(S.Half - s) / (sqrt(pi)*gamma(1 - s - a)*gamma(1 + a - s)), s, x, (0, S.Half))) == \ besselj(-a, sqrt(x))*besselj(a, sqrt(x)) assert simplify(IMT(4**s*gamma(-2*s + 1)*gamma(a/2 + b/2 + s) / (gamma(-a/2 + b/2 - s + 1)*gamma(a/2 - b/2 - s + 1) *gamma(a/2 + b/2 - s + 1)), s, x, (-(re(a) + re(b))/2, S.Half))) == \ besselj(a, sqrt(x))*besselj(b, sqrt(x)) # Section 8.4.20 # TODO this can be further simplified! assert simplify(IMT(-2**(2*s)*cos(pi*a/2 - pi*b/2 + pi*s)*gamma(-2*s + 1) * gamma(a/2 - b/2 + s)*gamma(a/2 + b/2 + s) / (pi*gamma(a/2 - b/2 - s + 1)*gamma(a/2 + b/2 - s + 1)), s, x, (Max(-re(a)/2 - re(b)/2, -re(a)/2 + re(b)/2), S.Half))) == \ besselj(a, sqrt(x))*-(besselj(-b, sqrt(x)) - besselj(b, sqrt(x))*cos(pi*b))/sin(pi*b) # TODO more # for coverage assert IMT(pi/cos(pi*s), s, x, (0, S.Half)) == sqrt(x)/(x + 1) @slow def test_laplace_transform(): from sympy import lowergamma from sympy.functions.special.delta_functions import DiracDelta from sympy.functions.special.error_functions import (fresnelc, fresnels) LT = laplace_transform a, b, c, = symbols('a, b, c', positive=True) t, w, x = symbols('t, w, x') f = Function("f") g = Function("g") # Test rule-base evaluation according to # http://eqworld.ipmnet.ru/en/auxiliary/inttrans/ # Power-law functions (laplace2.pdf) assert LT(a*t+t**2+t**(S(5)/2), t, s) ==\ (a/s**2 + 2/s**3 + 15*sqrt(pi)/(8*s**(S(7)/2)), 0, True) assert LT(b/(t+a), t, s) == (-b*exp(-a*s)*Ei(-a*s), 0, True) assert LT(1/sqrt(t+a), t, s) ==\ (sqrt(pi)*sqrt(1/s)*exp(a*s)*erfc(sqrt(a)*sqrt(s)), 0, True) assert LT(sqrt(t)/(t+a), t, s) ==\ (-pi*sqrt(a)*exp(a*s)*erfc(sqrt(a)*sqrt(s)) + sqrt(pi)*sqrt(1/s), 0, True) assert LT((t+a)**(-S(3)/2), t, s) ==\ (-2*sqrt(pi)*sqrt(s)*exp(a*s)*erfc(sqrt(a)*sqrt(s)) + 2/sqrt(a), 0, True) assert LT(t**(S(1)/2)*(t+a)**(-1), t, s) ==\ (-pi*sqrt(a)*exp(a*s)*erfc(sqrt(a)*sqrt(s)) + sqrt(pi)*sqrt(1/s), 0, True) assert LT(1/(a*sqrt(t) + t**(3/2)), t, s) ==\ (pi*sqrt(a)*exp(a*s)*erfc(sqrt(a)*sqrt(s)), 0, True) assert LT((t+a)**b, t, s) ==\ (s**(-b - 1)*exp(-a*s)*lowergamma(b + 1, a*s), 0, True) assert LT(t**5/(t+a), t, s) == (120*a**5*lowergamma(-5, a*s), 0, True) # Exponential functions (laplace3.pdf) assert LT(exp(t), t, s) == (1/(s - 1), 1, True) assert LT(exp(2*t), t, s) == (1/(s - 2), 2, True) assert LT(exp(a*t), t, s) == (1/(s - a), a, True) assert LT(exp(a*(t-b)), t, s) == (exp(-a*b)/(-a + s), a, True) assert LT(t*exp(-a*(t)), t, s) == ((a + s)**(-2), -a, True) assert LT(t*exp(-a*(t-b)), t, s) == (exp(a*b)/(a + s)**2, -a, True) assert LT(b*t*exp(-a*t), t, s) == (b/(a + s)**2, -a, True) assert LT(t**(S(7)/4)*exp(-8*t)/gamma(S(11)/4), t, s) ==\ ((s + 8)**(-S(11)/4), -8, True) assert LT(t**(S(3)/2)*exp(-8*t), t, s) ==\ (3*sqrt(pi)/(4*(s + 8)**(S(5)/2)), -8, True) assert LT(t**a*exp(-a*t), t, s) == ((a+s)**(-a-1)*gamma(a+1), -a, True) assert LT(b*exp(-a*t**2), t, s) ==\ (sqrt(pi)*b*exp(s**2/(4*a))*erfc(s/(2*sqrt(a)))/(2*sqrt(a)), 0, True) assert LT(exp(-2*t**2), t, s) ==\ (sqrt(2)*sqrt(pi)*exp(s**2/8)*erfc(sqrt(2)*s/4)/4, 0, True) assert LT(b*exp(2*t**2), t, s) == b*LaplaceTransform(exp(2*t**2), t, s) assert LT(t*exp(-a*t**2), t, s) ==\ (1/(2*a) - s*erfc(s/(2*sqrt(a)))/(4*sqrt(pi)*a**(S(3)/2)), 0, True) assert LT(exp(-a/t), t, s) ==\ (2*sqrt(a)*sqrt(1/s)*besselk(1, 2*sqrt(a)*sqrt(s)), 0, True) assert LT(sqrt(t)*exp(-a/t), t, s) ==\ (sqrt(pi)*(2*sqrt(a)*sqrt(s) + 1)*sqrt(s**(-3))*exp(-2*sqrt(a)*\ sqrt(s))/2, 0, True) assert LT(exp(-a/t)/sqrt(t), t, s) ==\ (sqrt(pi)*sqrt(1/s)*exp(-2*sqrt(a)*sqrt(s)), 0, True) assert LT( exp(-a/t)/(t*sqrt(t)), t, s) ==\ (sqrt(pi)*sqrt(1/a)*exp(-2*sqrt(a)*sqrt(s)), 0, True) assert LT(exp(-2*sqrt(a*t)), t, s) ==\ ( 1/s -sqrt(pi)*sqrt(a) * exp(a/s)*erfc(sqrt(a)*sqrt(1/s))/\ s**(S(3)/2), 0, True) assert LT(exp(-2*sqrt(a*t))/sqrt(t), t, s) == (exp(a/s)*erfc(sqrt(a)*\ sqrt(1/s))*(sqrt(pi)*sqrt(1/s)), 0, True) assert LT(t**4*exp(-2/t), t, s) ==\ (8*sqrt(2)*(1/s)**(S(5)/2)*besselk(5, 2*sqrt(2)*sqrt(s)), 0, True) # Hyperbolic functions (laplace4.pdf) assert LT(sinh(a*t), t, s) == (a/(-a**2 + s**2), a, True) assert LT(b*sinh(a*t)**2, t, s) == (2*a**2*b/(-4*a**2*s**2 + s**3), 2*a, True) # The following line confirms that issue #21202 is solved assert LT(cosh(2*t), t, s) == (s/(-4 + s**2), 2, True) assert LT(cosh(a*t), t, s) == (s/(-a**2 + s**2), a, True) assert LT(cosh(a*t)**2, t, s) == ((-2*a**2 + s**2)/(-4*a**2*s**2 + s**3), 2*a, True) assert LT(sinh(x + 3), x, s) == ( (-s + (s + 1)*exp(6) + 1)*exp(-3)/(s - 1)/(s + 1)/2, 0, Abs(s) > 1) # The following line replaces the old test test_issue_7173() assert LT(sinh(a*t)*cosh(a*t), t, s) == (a/(-4*a**2 + s**2), 2*a, True) assert LT(sinh(a*t)/t, t, s) == (log((a + s)/(-a + s))/2, a, True) assert LT(t**(-S(3)/2)*sinh(a*t), t, s) ==\ (-sqrt(pi)*(sqrt(-a + s) - sqrt(a + s)), a, True) assert LT(sinh(2*sqrt(a*t)), t, s) ==\ (sqrt(pi)*sqrt(a)*exp(a/s)/s**(S(3)/2), 0, True) assert LT(sqrt(t)*sinh(2*sqrt(a*t)), t, s) ==\ (-sqrt(a)/s**2 + sqrt(pi)*(a + s/2)*exp(a/s)*erf(sqrt(a)*\ sqrt(1/s))/s**(S(5)/2), 0, True) assert LT(sinh(2*sqrt(a*t))/sqrt(t), t, s) ==\ (sqrt(pi)*exp(a/s)*erf(sqrt(a)*sqrt(1/s))/sqrt(s), 0, True) assert LT(sinh(sqrt(a*t))**2/sqrt(t), t, s) ==\ (sqrt(pi)*(exp(a/s) - 1)/(2*sqrt(s)), 0, True) assert LT(t**(S(3)/7)*cosh(a*t), t, s) ==\ (((a + s)**(-S(10)/7) + (-a+s)**(-S(10)/7))*gamma(S(10)/7)/2, a, True) assert LT(cosh(2*sqrt(a*t)), t, s) ==\ (sqrt(pi)*sqrt(a)*exp(a/s)*erf(sqrt(a)*sqrt(1/s))/s**(S(3)/2) + 1/s, 0, True) assert LT(sqrt(t)*cosh(2*sqrt(a*t)), t, s) ==\ (sqrt(pi)*(a + s/2)*exp(a/s)/s**(S(5)/2), 0, True) assert LT(cosh(2*sqrt(a*t))/sqrt(t), t, s) ==\ (sqrt(pi)*exp(a/s)/sqrt(s), 0, True) assert LT(cosh(sqrt(a*t))**2/sqrt(t), t, s) ==\ (sqrt(pi)*(exp(a/s) + 1)/(2*sqrt(s)), 0, True) # logarithmic functions (laplace5.pdf) assert LT(log(t), t, s) == (-log(s+S.EulerGamma)/s, 0, True) assert LT(log(t/a), t, s) == (-log(a*s + S.EulerGamma)/s, 0, True) assert LT(log(1+a*t), t, s) == (-exp(s/a)*Ei(-s/a)/s, 0, True) assert LT(log(t+a), t, s) == ((log(a) - exp(s/a)*Ei(-s/a)/s)/s, 0, True) assert LT(log(t)/sqrt(t), t, s) ==\ (sqrt(pi)*(-log(s) - 2*log(2) - S.EulerGamma)/sqrt(s), 0, True) assert LT(t**(S(5)/2)*log(t), t, s) ==\ (15*sqrt(pi)*(-log(s)-2*log(2)-S.EulerGamma+S(46)/15)/(8*s**(S(7)/2)), 0, True) assert (LT(t**3*log(t), t, s, noconds=True)-6*(-log(s) - S.EulerGamma\ + S(11)/6)/s**4).simplify() == S.Zero assert LT(log(t)**2, t, s) ==\ (((log(s) + EulerGamma)**2 + pi**2/6)/s, 0, True) assert LT(exp(-a*t)*log(t), t, s) ==\ ((-log(a + s) - S.EulerGamma)/(a + s), -a, True) # Trigonometric functions (laplace6.pdf) assert LT(sin(a*t), t, s) == (a/(a**2 + s**2), 0, True) assert LT(Abs(sin(a*t)), t, s) ==\ (a*coth(pi*s/(2*a))/(a**2 + s**2), 0, True) assert LT(sin(a*t)/t, t, s) == (atan(a/s), 0, True) assert LT(sin(a*t)**2/t, t, s) == (log(4*a**2/s**2 + 1)/4, 0, True) assert LT(sin(a*t)**2/t**2, t, s) ==\ (a*atan(2*a/s) - s*log(4*a**2/s**2 + 1)/4, 0, True) assert LT(sin(2*sqrt(a*t)), t, s) ==\ (sqrt(pi)*sqrt(a)*exp(-a/s)/s**(S(3)/2), 0, True) assert LT(sin(2*sqrt(a*t))/t, t, s) == (pi*erf(sqrt(a)*sqrt(1/s)), 0, True) assert LT(cos(a*t), t, s) == (s/(a**2 + s**2), 0, True) assert LT(cos(a*t)**2, t, s) ==\ ((2*a**2 + s**2)/(s*(4*a**2 + s**2)), 0, True) assert LT(sqrt(t)*cos(2*sqrt(a*t)), t, s) ==\ (sqrt(pi)*(-2*a + s)*exp(-a/s)/(2*s**(S(5)/2)), 0, True) assert LT(cos(2*sqrt(a*t))/sqrt(t), t, s) ==\ (sqrt(pi)*sqrt(1/s)*exp(-a/s), 0, True) assert LT(sin(a*t)*sin(b*t), t, s) ==\ (2*a*b*s/((s**2 + (a - b)**2)*(s**2 + (a + b)**2)), 0, True) assert LT(cos(a*t)*sin(b*t), t, s) ==\ (b*(-a**2 + b**2 + s**2)/((s**2 + (a - b)**2)*(s**2 + (a + b)**2)), 0, True) assert LT(cos(a*t)*cos(b*t), t, s) ==\ (s*(a**2 + b**2 + s**2)/((s**2 + (a - b)**2)*(s**2 + (a + b)**2)), 0, True) assert LT(c*exp(-b*t)*sin(a*t), t, s) == (a*c/(a**2 + (b + s)**2), -b, True) assert LT(c*exp(-b*t)*cos(a*t), t, s) == ((b + s)*c/(a**2 + (b + s)**2), -b, True) assert LT(cos(x + 3), x, s) == ((s*cos(3) - sin(3))/(s**2 + 1), 0, True) # Error functions (laplace7.pdf) assert LT(erf(a*t), t, s) == (exp(s**2/(4*a**2))*erfc(s/(2*a))/s, 0, True) assert LT(erf(sqrt(a*t)), t, s) == (sqrt(a)/(s*sqrt(a + s)), 0, True) assert LT(exp(a*t)*erf(sqrt(a*t)), t, s) ==\ (sqrt(a)/(sqrt(s)*(-a + s)), a, True) assert LT(erf(sqrt(a/t)/2), t, s) == ((1-exp(-sqrt(a)*sqrt(s)))/s, 0, True) assert LT(erfc(sqrt(a*t)), t, s) ==\ ((-sqrt(a) + sqrt(a + s))/(s*sqrt(a + s)), 0, True) assert LT(exp(a*t)*erfc(sqrt(a*t)), t, s) ==\ (1/(sqrt(a)*sqrt(s) + s), 0, True) assert LT(erfc(sqrt(a/t)/2), t, s) == (exp(-sqrt(a)*sqrt(s))/s, 0, True) # Bessel functions (laplace8.pdf) assert LT(besselj(0, a*t), t, s) == (1/sqrt(a**2 + s**2), 0, True) assert LT(besselj(1, a*t), t, s) ==\ (a/(sqrt(a**2 + s**2)*(s + sqrt(a**2 + s**2))), 0, True) assert LT(besselj(2, a*t), t, s) ==\ (a**2/(sqrt(a**2 + s**2)*(s + sqrt(a**2 + s**2))**2), 0, True) assert LT(t*besselj(0, a*t), t, s) ==\ (s/(a**2 + s**2)**(S(3)/2), 0, True) assert LT(t*besselj(1, a*t), t, s) ==\ (a/(a**2 + s**2)**(S(3)/2), 0, True) assert LT(t**2*besselj(2, a*t), t, s) ==\ (3*a**2/(a**2 + s**2)**(S(5)/2), 0, True) assert LT(besselj(0, 2*sqrt(a*t)), t, s) == (exp(-a/s)/s, 0, True) assert LT(t**(S(3)/2)*besselj(3, 2*sqrt(a*t)), t, s) ==\ (a**(S(3)/2)*exp(-a/s)/s**4, 0, True) assert LT(besselj(0, a*sqrt(t**2+b*t)), t, s) ==\ (exp(b*s - b*sqrt(a**2 + s**2))/sqrt(a**2 + s**2), 0, True) assert LT(besseli(0, a*t), t, s) == (1/sqrt(-a**2 + s**2), a, True) assert LT(besseli(1, a*t), t, s) ==\ (a/(sqrt(-a**2 + s**2)*(s + sqrt(-a**2 + s**2))), a, True) assert LT(besseli(2, a*t), t, s) ==\ (a**2/(sqrt(-a**2 + s**2)*(s + sqrt(-a**2 + s**2))**2), a, True) assert LT(t*besseli(0, a*t), t, s) == (s/(-a**2 + s**2)**(S(3)/2), a, True) assert LT(t*besseli(1, a*t), t, s) == (a/(-a**2 + s**2)**(S(3)/2), a, True) assert LT(t**2*besseli(2, a*t), t, s) ==\ (3*a**2/(-a**2 + s**2)**(S(5)/2), a, True) assert LT(t**(S(3)/2)*besseli(3, 2*sqrt(a*t)), t, s) ==\ (a**(S(3)/2)*exp(a/s)/s**4, 0, True) assert LT(bessely(0, a*t), t, s) ==\ (-2*asinh(s/a)/(pi*sqrt(a**2 + s**2)), 0, True) assert LT(besselk(0, a*t), t, s) ==\ (log(s + sqrt(-a**2 + s**2))/sqrt(-a**2 + s**2), a, True) assert LT(sin(a*t)**8, t, s) ==\ (40320*a**8/(s*(147456*a**8 + 52480*a**6*s**2 + 4368*a**4*s**4 +\ 120*a**2*s**6 + s**8)), 0, True) # Test general rules and unevaluated forms # These all also test whether issue #7219 is solved. assert LT(Heaviside(t-1)*cos(t-1), t, s) == (s*exp(-s)/(s**2 + 1), 0, True) assert LT(a*f(t), t, w) == a*LaplaceTransform(f(t), t, w) assert LT(a*Heaviside(t+1)*f(t+1), t, s) ==\ a*LaplaceTransform(f(t + 1)*Heaviside(t + 1), t, s) assert LT(a*Heaviside(t-1)*f(t-1), t, s) ==\ a*LaplaceTransform(f(t), t, s)*exp(-s) assert LT(b*f(t/a), t, s) == a*b*LaplaceTransform(f(t), t, a*s) assert LT(exp(-f(x)*t), t, s) == (1/(s + f(x)), -f(x), True) assert LT(exp(-a*t)*f(t), t, s) == LaplaceTransform(f(t), t, a + s) assert LT(exp(-a*t)*erfc(sqrt(b/t)/2), t, s) ==\ (exp(-sqrt(b)*sqrt(a + s))/(a + s), -a, True) assert LT(sinh(a*t)*f(t), t, s) ==\ LaplaceTransform(f(t), t, -a+s)/2 - LaplaceTransform(f(t), t, a+s)/2 assert LT(sinh(a*t)*t, t, s) ==\ (-1/(2*(a + s)**2) + 1/(2*(-a + s)**2), a, True) assert LT(cosh(a*t)*f(t), t, s) ==\ LaplaceTransform(f(t), t, -a+s)/2 + LaplaceTransform(f(t), t, a+s)/2 assert LT(cosh(a*t)*t, t, s) ==\ (1/(2*(a + s)**2) + 1/(2*(-a + s)**2), a, True) assert LT(sin(a*t)*f(t), t, s) ==\ I*(-LaplaceTransform(f(t), t, -I*a + s) +\ LaplaceTransform(f(t), t, I*a + s))/2 assert LT(sin(a*t)*t, t, s) ==\ (2*a*s/(a**4 + 2*a**2*s**2 + s**4), 0, True) assert LT(cos(a*t)*f(t), t, s) ==\ LaplaceTransform(f(t), t, -I*a + s)/2 +\ LaplaceTransform(f(t), t, I*a + s)/2 assert LT(cos(a*t)*t, t, s) ==\ ((-a**2 + s**2)/(a**4 + 2*a**2*s**2 + s**4), 0, True) # The following two lines test whether issues #5813 and #7176 are solved. assert LT(diff(f(t), (t, 1)), t, s) == s*LaplaceTransform(f(t), t, s)\ - f(0) assert LT(diff(f(t), (t, 3)), t, s) == s**3*LaplaceTransform(f(t), t, s)\ - s**2*f(0) - s*Subs(Derivative(f(t), t), t, 0)\ - Subs(Derivative(f(t), (t, 2)), t, 0) assert LT(a*f(b*t)+g(c*t), t, s) == a*LaplaceTransform(f(t), t, s/b)/b +\ LaplaceTransform(g(t), t, s/c)/c assert inverse_laplace_transform( f(w), w, t, plane=0) == InverseLaplaceTransform(f(w), w, t, 0) assert LT(f(t)*g(t), t, s) == LaplaceTransform(f(t)*g(t), t, s) # additional basic tests from wikipedia assert LT((t - a)**b*exp(-c*(t - a))*Heaviside(t - a), t, s) == \ ((s + c)**(-b - 1)*exp(-a*s)*gamma(b + 1), -c, True) assert LT((exp(2*t) - 1)*exp(-b - t)*Heaviside(t)/2, t, s, noconds=True) \ == exp(-b)/(s**2 - 1) # DiracDelta function: standard cases assert LT(DiracDelta(t), t, s) == (1, 0, True) assert LT(DiracDelta(a*t), t, s) == (1/a, 0, True) assert LT(DiracDelta(t/42), t, s) == (42, 0, True) assert LT(DiracDelta(t+42), t, s) == (0, 0, True) assert LT(DiracDelta(t)+DiracDelta(t-42), t, s) == \ (1 + exp(-42*s), 0, True) assert LT(DiracDelta(t)-a*exp(-a*t), t, s) == (s/(a + s), 0, True) assert LT(exp(-t)*(DiracDelta(t)+DiracDelta(t-42)), t, s) == \ (exp(-42*s - 42) + 1, -oo, True) # Collection of cases that cannot be fully evaluated and/or would catch # some common implementation errors assert LT(DiracDelta(t**2), t, s) == LaplaceTransform(DiracDelta(t**2), t, s) assert LT(DiracDelta(t**2 - 1), t, s) == (exp(-s)/2, -oo, True) assert LT(DiracDelta(t*(1 - t)), t, s) == \ LaplaceTransform(DiracDelta(-t**2 + t), t, s) assert LT((DiracDelta(t) + 1)*(DiracDelta(t - 1) + 1), t, s) == \ (LaplaceTransform(DiracDelta(t)*DiracDelta(t - 1), t, s) + \ 1 + exp(-s) + 1/s, 0, True) assert LT(DiracDelta(2*t-2*exp(a)), t, s) == (exp(-s*exp(a))/2, 0, True) assert LT(DiracDelta(-2*t+2*exp(a)), t, s) == (exp(-s*exp(a))/2, 0, True) # Heaviside tests assert LT(Heaviside(t), t, s) == (1/s, 0, True) assert LT(Heaviside(t - a), t, s) == (exp(-a*s)/s, 0, True) assert LT(Heaviside(t-1), t, s) == (exp(-s)/s, 0, True) assert LT(Heaviside(2*t-4), t, s) == (exp(-2*s)/s, 0, True) assert LT(Heaviside(-2*t+4), t, s) == ((1 - exp(-2*s))/s, 0, True) assert LT(Heaviside(2*t+4), t, s) == (1/s, 0, True) assert LT(Heaviside(-2*t+4), t, s) == ((1 - exp(-2*s))/s, 0, True) # Fresnel functions assert laplace_transform(fresnels(t), t, s) == \ ((-sin(s**2/(2*pi))*fresnels(s/pi) + sin(s**2/(2*pi))/2 - cos(s**2/(2*pi))*fresnelc(s/pi) + cos(s**2/(2*pi))/2)/s, 0, True) assert laplace_transform(fresnelc(t), t, s) == ( ((2*sin(s**2/(2*pi))*fresnelc(s/pi) - 2*cos(s**2/(2*pi))*fresnels(s/pi) + sqrt(2)*cos(s**2/(2*pi) + pi/4))/(2*s), 0, True)) # Matrix tests Mt = Matrix([[exp(t), t*exp(-t)], [t*exp(-t), exp(t)]]) Ms = Matrix([[ 1/(s - 1), (s + 1)**(-2)], [(s + 1)**(-2), 1/(s - 1)]]) # The default behaviour for Laplace tranform of a Matrix returns a Matrix # of Tuples and is deprecated: with warns_deprecated_sympy(): Ms_conds = Matrix([[(1/(s - 1), 1, True), ((s + 1)**(-2), -1, True)], [((s + 1)**(-2), -1, True), (1/(s - 1), 1, True)]]) with warns_deprecated_sympy(): assert LT(Mt, t, s) == Ms_conds # The new behavior is to return a tuple of a Matrix and the convergence # conditions for the matrix as a whole: assert LT(Mt, t, s, legacy_matrix=False) == (Ms, 1, True) # With noconds=True the transformed matrix is returned without conditions # either way: assert LT(Mt, t, s, noconds=True) == Ms assert LT(Mt, t, s, legacy_matrix=False, noconds=True) == Ms @slow def test_inverse_laplace_transform(): from sympy.core.exprtools import factor_terms from sympy.functions.special.delta_functions import DiracDelta from sympy.simplify.simplify import simplify ILT = inverse_laplace_transform a, b, c, = symbols('a b c', positive=True) t = symbols('t') def simp_hyp(expr): return factor_terms(expand_mul(expr)).rewrite(sin) assert ILT(1, s, t) == DiracDelta(t) assert ILT(1/s, s, t) == Heaviside(t) assert ILT(a/(a + s), s, t) == a*exp(-a*t)*Heaviside(t) assert ILT(s/(a + s), s, t) == -a*exp(-a*t)*Heaviside(t) + DiracDelta(t) assert ILT((a + s)**(-2), s, t) == t*exp(-a*t)*Heaviside(t) assert ILT((a + s)**(-5), s, t) == t**4*exp(-a*t)*Heaviside(t)/24 assert ILT(a/(a**2 + s**2), s, t) == sin(a*t)*Heaviside(t) assert ILT(s/(s**2 + a**2), s, t) == cos(a*t)*Heaviside(t) assert ILT(b/(b**2 + (a + s)**2), s, t) == exp(-a*t)*sin(b*t)*Heaviside(t) assert ILT(b*s/(b**2 + (a + s)**2), s, t) +\ (a*sin(b*t) - b*cos(b*t))*exp(-a*t)*Heaviside(t) == 0 assert ILT(exp(-a*s)/s, s, t) == Heaviside(-a + t) assert ILT(exp(-a*s)/(b + s), s, t) == exp(b*(a - t))*Heaviside(-a + t) assert ILT((b + s)/(a**2 + (b + s)**2), s, t) == \ exp(-b*t)*cos(a*t)*Heaviside(t) assert ILT(exp(-a*s)/s**b, s, t) == \ (-a + t)**(b - 1)*Heaviside(-a + t)/gamma(b) assert ILT(exp(-a*s)/sqrt(s**2 + 1), s, t) == \ Heaviside(-a + t)*besselj(0, a - t) assert ILT(1/(s*sqrt(s + 1)), s, t) == Heaviside(t)*erf(sqrt(t)) assert ILT(1/(s**2*(s**2 + 1)), s, t) == (t - sin(t))*Heaviside(t) assert ILT(s**2/(s**2 + 1), s, t) == -sin(t)*Heaviside(t) + DiracDelta(t) assert ILT(1 - 1/(s**2 + 1), s, t) == -sin(t)*Heaviside(t) + DiracDelta(t) assert ILT(1/s**2, s, t) == t*Heaviside(t) assert ILT(1/s**5, s, t) == t**4*Heaviside(t)/24 assert simp_hyp(ILT(a/(s**2 - a**2), s, t)) == sinh(a*t)*Heaviside(t) assert simp_hyp(ILT(s/(s**2 - a**2), s, t)) == cosh(a*t)*Heaviside(t) # TODO sinh/cosh shifted come out a mess. also delayed trig is a mess # TODO should this simplify further? assert ILT(exp(-a*s)/s**b, s, t) == \ (t - a)**(b - 1)*Heaviside(t - a)/gamma(b) assert ILT(exp(-a*s)/sqrt(1 + s**2), s, t) == \ Heaviside(t - a)*besselj(0, a - t) # note: besselj(0, x) is even # XXX ILT turns these branch factor into trig functions ... assert simplify(ILT(a**b*(s + sqrt(s**2 - a**2))**(-b)/sqrt(s**2 - a**2), s, t).rewrite(exp)) == \ Heaviside(t)*besseli(b, a*t) assert ILT(a**b*(s + sqrt(s**2 + a**2))**(-b)/sqrt(s**2 + a**2), s, t).rewrite(exp) == \ Heaviside(t)*besselj(b, a*t) assert ILT(1/(s*sqrt(s + 1)), s, t) == Heaviside(t)*erf(sqrt(t)) # TODO can we make erf(t) work? assert ILT(1/(s**2*(s**2 + 1)),s,t) == (t - sin(t))*Heaviside(t) assert ILT( (s * eye(2) - Matrix([[1, 0], [0, 2]])).inv(), s, t) ==\ Matrix([[exp(t)*Heaviside(t), 0], [0, exp(2*t)*Heaviside(t)]]) def test_inverse_laplace_transform_delta(): from sympy.functions.special.delta_functions import DiracDelta ILT = inverse_laplace_transform t = symbols('t') assert ILT(2, s, t) == 2*DiracDelta(t) assert ILT(2*exp(3*s) - 5*exp(-7*s), s, t) == \ 2*DiracDelta(t + 3) - 5*DiracDelta(t - 7) a = cos(sin(7)/2) assert ILT(a*exp(-3*s), s, t) == a*DiracDelta(t - 3) assert ILT(exp(2*s), s, t) == DiracDelta(t + 2) r = Symbol('r', real=True) assert ILT(exp(r*s), s, t) == DiracDelta(t + r) def test_inverse_laplace_transform_delta_cond(): from sympy.functions.elementary.complexes import im from sympy.functions.special.delta_functions import DiracDelta ILT = inverse_laplace_transform t = symbols('t') r = Symbol('r', real=True) assert ILT(exp(r*s), s, t, noconds=False) == (DiracDelta(t + r), True) z = Symbol('z') assert ILT(exp(z*s), s, t, noconds=False) == \ (DiracDelta(t + z), Eq(im(z), 0)) # inversion does not exist: verify it doesn't evaluate to DiracDelta for z in (Symbol('z', extended_real=False), Symbol('z', imaginary=True, zero=False)): f = ILT(exp(z*s), s, t, noconds=False) f = f[0] if isinstance(f, tuple) else f assert f.func != DiracDelta # issue 15043 assert ILT(1/s + exp(r*s)/s, s, t, noconds=False) == ( Heaviside(t) + Heaviside(r + t), True) def test_fourier_transform(): from sympy.core.function import (expand, expand_complex, expand_trig) from sympy.polys.polytools import factor from sympy.simplify.simplify import simplify FT = fourier_transform IFT = inverse_fourier_transform def simp(x): return simplify(expand_trig(expand_complex(expand(x)))) def sinc(x): return sin(pi*x)/(pi*x) k = symbols('k', real=True) f = Function("f") # TODO for this to work with real a, need to expand abs(a*x) to abs(a)*abs(x) a = symbols('a', positive=True) b = symbols('b', positive=True) posk = symbols('posk', positive=True) # Test unevaluated form assert fourier_transform(f(x), x, k) == FourierTransform(f(x), x, k) assert inverse_fourier_transform( f(k), k, x) == InverseFourierTransform(f(k), k, x) # basic examples from wikipedia assert simp(FT(Heaviside(1 - abs(2*a*x)), x, k)) == sinc(k/a)/a # TODO IFT is a *mess* assert simp(FT(Heaviside(1 - abs(a*x))*(1 - abs(a*x)), x, k)) == sinc(k/a)**2/a # TODO IFT assert factor(FT(exp(-a*x)*Heaviside(x), x, k), extension=I) == \ 1/(a + 2*pi*I*k) # NOTE: the ift comes out in pieces assert IFT(1/(a + 2*pi*I*x), x, posk, noconds=False) == (exp(-a*posk), True) assert IFT(1/(a + 2*pi*I*x), x, -posk, noconds=False) == (0, True) assert IFT(1/(a + 2*pi*I*x), x, symbols('k', negative=True), noconds=False) == (0, True) # TODO IFT without factoring comes out as meijer g assert factor(FT(x*exp(-a*x)*Heaviside(x), x, k), extension=I) == \ 1/(a + 2*pi*I*k)**2 assert FT(exp(-a*x)*sin(b*x)*Heaviside(x), x, k) == \ b/(b**2 + (a + 2*I*pi*k)**2) assert FT(exp(-a*x**2), x, k) == sqrt(pi)*exp(-pi**2*k**2/a)/sqrt(a) assert IFT(sqrt(pi/a)*exp(-(pi*k)**2/a), k, x) == exp(-a*x**2) assert FT(exp(-a*abs(x)), x, k) == 2*a/(a**2 + 4*pi**2*k**2) # TODO IFT (comes out as meijer G) # TODO besselj(n, x), n an integer > 0 actually can be done... # TODO are there other common transforms (no distributions!)? def test_sine_transform(): t = symbols("t") w = symbols("w") a = symbols("a") f = Function("f") # Test unevaluated form assert sine_transform(f(t), t, w) == SineTransform(f(t), t, w) assert inverse_sine_transform( f(w), w, t) == InverseSineTransform(f(w), w, t) assert sine_transform(1/sqrt(t), t, w) == 1/sqrt(w) assert inverse_sine_transform(1/sqrt(w), w, t) == 1/sqrt(t) assert sine_transform((1/sqrt(t))**3, t, w) == 2*sqrt(w) assert sine_transform(t**(-a), t, w) == 2**( -a + S.Half)*w**(a - 1)*gamma(-a/2 + 1)/gamma((a + 1)/2) assert inverse_sine_transform(2**(-a + S( 1)/2)*w**(a - 1)*gamma(-a/2 + 1)/gamma(a/2 + S.Half), w, t) == t**(-a) assert sine_transform( exp(-a*t), t, w) == sqrt(2)*w/(sqrt(pi)*(a**2 + w**2)) assert inverse_sine_transform( sqrt(2)*w/(sqrt(pi)*(a**2 + w**2)), w, t) == exp(-a*t) assert sine_transform( log(t)/t, t, w) == sqrt(2)*sqrt(pi)*-(log(w**2) + 2*EulerGamma)/4 assert sine_transform( t*exp(-a*t**2), t, w) == sqrt(2)*w*exp(-w**2/(4*a))/(4*a**Rational(3, 2)) assert inverse_sine_transform( sqrt(2)*w*exp(-w**2/(4*a))/(4*a**Rational(3, 2)), w, t) == t*exp(-a*t**2) def test_cosine_transform(): from sympy.functions.special.error_functions import (Ci, Si) t = symbols("t") w = symbols("w") a = symbols("a") f = Function("f") # Test unevaluated form assert cosine_transform(f(t), t, w) == CosineTransform(f(t), t, w) assert inverse_cosine_transform( f(w), w, t) == InverseCosineTransform(f(w), w, t) assert cosine_transform(1/sqrt(t), t, w) == 1/sqrt(w) assert inverse_cosine_transform(1/sqrt(w), w, t) == 1/sqrt(t) assert cosine_transform(1/( a**2 + t**2), t, w) == sqrt(2)*sqrt(pi)*exp(-a*w)/(2*a) assert cosine_transform(t**( -a), t, w) == 2**(-a + S.Half)*w**(a - 1)*gamma((-a + 1)/2)/gamma(a/2) assert inverse_cosine_transform(2**(-a + S( 1)/2)*w**(a - 1)*gamma(-a/2 + S.Half)/gamma(a/2), w, t) == t**(-a) assert cosine_transform( exp(-a*t), t, w) == sqrt(2)*a/(sqrt(pi)*(a**2 + w**2)) assert inverse_cosine_transform( sqrt(2)*a/(sqrt(pi)*(a**2 + w**2)), w, t) == exp(-a*t) assert cosine_transform(exp(-a*sqrt(t))*cos(a*sqrt( t)), t, w) == a*exp(-a**2/(2*w))/(2*w**Rational(3, 2)) assert cosine_transform(1/(a + t), t, w) == sqrt(2)*( (-2*Si(a*w) + pi)*sin(a*w)/2 - cos(a*w)*Ci(a*w))/sqrt(pi) assert inverse_cosine_transform(sqrt(2)*meijerg(((S.Half, 0), ()), ( (S.Half, 0, 0), (S.Half,)), a**2*w**2/4)/(2*pi), w, t) == 1/(a + t) assert cosine_transform(1/sqrt(a**2 + t**2), t, w) == sqrt(2)*meijerg( ((S.Half,), ()), ((0, 0), (S.Half,)), a**2*w**2/4)/(2*sqrt(pi)) assert inverse_cosine_transform(sqrt(2)*meijerg(((S.Half,), ()), ((0, 0), (S.Half,)), a**2*w**2/4)/(2*sqrt(pi)), w, t) == 1/(t*sqrt(a**2/t**2 + 1)) def test_hankel_transform(): r = Symbol("r") k = Symbol("k") nu = Symbol("nu") m = Symbol("m") a = symbols("a") assert hankel_transform(1/r, r, k, 0) == 1/k assert inverse_hankel_transform(1/k, k, r, 0) == 1/r assert hankel_transform( 1/r**m, r, k, 0) == 2**(-m + 1)*k**(m - 2)*gamma(-m/2 + 1)/gamma(m/2) assert inverse_hankel_transform( 2**(-m + 1)*k**(m - 2)*gamma(-m/2 + 1)/gamma(m/2), k, r, 0) == r**(-m) assert hankel_transform(1/r**m, r, k, nu) == ( 2*2**(-m)*k**(m - 2)*gamma(-m/2 + nu/2 + 1)/gamma(m/2 + nu/2)) assert inverse_hankel_transform(2**(-m + 1)*k**( m - 2)*gamma(-m/2 + nu/2 + 1)/gamma(m/2 + nu/2), k, r, nu) == r**(-m) assert hankel_transform(r**nu*exp(-a*r), r, k, nu) == \ 2**(nu + 1)*a*k**(-nu - 3)*(a**2/k**2 + 1)**(-nu - S( 3)/2)*gamma(nu + Rational(3, 2))/sqrt(pi) assert inverse_hankel_transform( 2**(nu + 1)*a*k**(-nu - 3)*(a**2/k**2 + 1)**(-nu - Rational(3, 2))*gamma( nu + Rational(3, 2))/sqrt(pi), k, r, nu) == r**nu*exp(-a*r) def test_issue_7181(): assert mellin_transform(1/(1 - x), x, s) != None def test_issue_8882(): # This is the original test. # from sympy import diff, Integral, integrate # r = Symbol('r') # psi = 1/r*sin(r)*exp(-(a0*r)) # h = -1/2*diff(psi, r, r) - 1/r*psi # f = 4*pi*psi*h*r**2 # assert integrate(f, (r, -oo, 3), meijerg=True).has(Integral) == True # To save time, only the critical part is included. F = -a**(-s + 1)*(4 + 1/a**2)**(-s/2)*sqrt(1/a**2)*exp(-s*I*pi)* \ sin(s*atan(sqrt(1/a**2)/2))*gamma(s) raises(IntegralTransformError, lambda: inverse_mellin_transform(F, s, x, (-1, oo), **{'as_meijerg': True, 'needeval': True})) def test_issue_8514(): from sympy.simplify.simplify import simplify a, b, c, = symbols('a b c', positive=True) t = symbols('t', positive=True) ft = simplify(inverse_laplace_transform(1/(a*s**2+b*s+c),s, t)) assert ft == (I*exp(t*cos(atan2(0, -4*a*c + b**2)/2)*sqrt(Abs(4*a*c - b**2))/a)*sin(t*sin(atan2(0, -4*a*c + b**2)/2)*sqrt(Abs( 4*a*c - b**2))/(2*a)) + exp(t*cos(atan2(0, -4*a*c + b**2) /2)*sqrt(Abs(4*a*c - b**2))/a)*cos(t*sin(atan2(0, -4*a*c + b**2)/2)*sqrt(Abs(4*a*c - b**2))/(2*a)) + I*sin(t*sin( atan2(0, -4*a*c + b**2)/2)*sqrt(Abs(4*a*c - b**2))/(2*a)) - cos(t*sin(atan2(0, -4*a*c + b**2)/2)*sqrt(Abs(4*a*c - b**2))/(2*a)))*exp(-t*(b + cos(atan2(0, -4*a*c + b**2)/2) *sqrt(Abs(4*a*c - b**2)))/(2*a))/sqrt(-4*a*c + b**2) def test_issue_12591(): x, y = symbols("x y", real=True) assert fourier_transform(exp(x), x, y) == FourierTransform(exp(x), x, y) def test_issue_14692(): b = Symbol('b', negative=True) assert laplace_transform(1/(I*x - b), x, s) == \ (-I*exp(I*b*s)*expint(1, b*s*exp_polar(I*pi/2)), 0, True)
eac34e9246663af0803d3c17add53a85e8431657976326a485e5f62906941d66
from sympy.core.numbers import (I, Rational) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, symbols) from sympy.functions.elementary.exponential import log from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import atan from sympy.integrals.integrals import integrate from sympy.polys.polytools import Poly from sympy.simplify.simplify import simplify from sympy.integrals.rationaltools import ratint, ratint_logpart, log_to_atan from sympy.abc import a, b, x, t half = S.Half def test_ratint(): assert ratint(S.Zero, x) == 0 assert ratint(S(7), x) == 7*x assert ratint(x, x) == x**2/2 assert ratint(2*x, x) == x**2 assert ratint(-2*x, x) == -x**2 assert ratint(8*x**7 + 2*x + 1, x) == x**8 + x**2 + x f = S.One g = x + 1 assert ratint(f / g, x) == log(x + 1) assert ratint((f, g), x) == log(x + 1) f = x**3 - x g = x - 1 assert ratint(f/g, x) == x**3/3 + x**2/2 f = x g = (x - a)*(x + a) assert ratint(f/g, x) == log(x**2 - a**2)/2 f = S.One g = x**2 + 1 assert ratint(f/g, x, real=None) == atan(x) assert ratint(f/g, x, real=True) == atan(x) assert ratint(f/g, x, real=False) == I*log(x + I)/2 - I*log(x - I)/2 f = S(36) g = x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2 assert ratint(f/g, x) == \ -4*log(x + 1) + 4*log(x - 2) + (12*x + 6)/(x**2 - 1) f = x**4 - 3*x**2 + 6 g = x**6 - 5*x**4 + 5*x**2 + 4 assert ratint(f/g, x) == \ atan(x) + atan(x**3) + atan(x/2 - Rational(3, 2)*x**3 + S.Half*x**5) f = x**7 - 24*x**4 - 4*x**2 + 8*x - 8 g = x**8 + 6*x**6 + 12*x**4 + 8*x**2 assert ratint(f/g, x) == \ (4 + 6*x + 8*x**2 + 3*x**3)/(4*x + 4*x**3 + x**5) + log(x) assert ratint((x**3*f)/(x*g), x) == \ -(12 - 16*x + 6*x**2 - 14*x**3)/(4 + 4*x**2 + x**4) - \ 5*sqrt(2)*atan(x*sqrt(2)/2) + S.Half*x**2 - 3*log(2 + x**2) f = x**5 - x**4 + 4*x**3 + x**2 - x + 5 g = x**4 - 2*x**3 + 5*x**2 - 4*x + 4 assert ratint(f/g, x) == \ x + S.Half*x**2 + S.Half*log(2 - x + x**2) + (9 - 4*x)/(7*x**2 - 7*x + 14) + \ 13*sqrt(7)*atan(Rational(-1, 7)*sqrt(7) + 2*x*sqrt(7)/7)/49 assert ratint(1/(x**2 + x + 1), x) == \ 2*sqrt(3)*atan(sqrt(3)/3 + 2*x*sqrt(3)/3)/3 assert ratint(1/(x**3 + 1), x) == \ -log(1 - x + x**2)/6 + log(1 + x)/3 + sqrt(3)*atan(-sqrt(3) /3 + 2*x*sqrt(3)/3)/3 assert ratint(1/(x**2 + x + 1), x, real=False) == \ -I*3**half*log(half + x - half*I*3**half)/3 + \ I*3**half*log(half + x + half*I*3**half)/3 assert ratint(1/(x**3 + 1), x, real=False) == log(1 + x)/3 + \ (Rational(-1, 6) + I*3**half/6)*log(-half + x + I*3**half/2) + \ (Rational(-1, 6) - I*3**half/6)*log(-half + x - I*3**half/2) # issue 4991 assert ratint(1/(x*(a + b*x)**3), x) == \ (3*a + 2*b*x)/(2*a**4 + 4*a**3*b*x + 2*a**2*b**2*x**2) + ( log(x) - log(a/b + x))/a**3 assert ratint(x/(1 - x**2), x) == -log(x**2 - 1)/2 assert ratint(-x/(1 - x**2), x) == log(x**2 - 1)/2 assert ratint((x/4 - 4/(1 - x)).diff(x), x) == x/4 + 4/(x - 1) ans = atan(x) assert ratint(1/(x**2 + 1), x, symbol=x) == ans assert ratint(1/(x**2 + 1), x, symbol='x') == ans assert ratint(1/(x**2 + 1), x, symbol=a) == ans # this asserts that as_dummy must return a unique symbol # even if the symbol is already a Dummy d = Dummy() assert ratint(1/(d**2 + 1), d, symbol=d) == atan(d) def test_ratint_logpart(): assert ratint_logpart(x, x**2 - 9, x, t) == \ [(Poly(x**2 - 9, x), Poly(-2*t + 1, t))] assert ratint_logpart(x**2, x**3 - 5, x, t) == \ [(Poly(x**3 - 5, x), Poly(-3*t + 1, t))] def test_issue_5414(): assert ratint(1/(x**2 + 16), x) == atan(x/4)/4 def test_issue_5249(): assert ratint( 1/(x**2 + a**2), x) == (-I*log(-I*a + x)/2 + I*log(I*a + x)/2)/a def test_issue_5817(): a, b, c = symbols('a,b,c', positive=True) assert simplify(ratint(a/(b*c*x**2 + a**2 + b*a), x)) == \ sqrt(a)*atan(sqrt( b)*sqrt(c)*x/(sqrt(a)*sqrt(a + b)))/(sqrt(b)*sqrt(c)*sqrt(a + b)) def test_issue_5981(): u = symbols('u') assert integrate(1/(u**2 + 1)) == atan(u) def test_issue_10488(): a,b,c,x = symbols('a b c x', positive=True) assert integrate(x/(a*x+b),x) == x/a - b*log(a*x + b)/a**2 def test_issues_8246_12050_13501_14080(): a = symbols('a', nonzero=True) assert integrate(a/(x**2 + a**2), x) == atan(x/a) assert integrate(1/(x**2 + a**2), x) == atan(x/a)/a assert integrate(1/(1 + a**2*x**2), x) == atan(a*x)/a def test_issue_6308(): k, a0 = symbols('k a0', real=True) assert integrate((x**2 + 1 - k**2)/(x**2 + 1 + a0**2), x) == \ x - (a0**2 + k**2)*atan(x/sqrt(a0**2 + 1))/sqrt(a0**2 + 1) def test_issue_5907(): a = symbols('a', nonzero=True) assert integrate(1/(x**2 + a**2)**2, x) == \ x/(2*a**4 + 2*a**2*x**2) + atan(x/a)/(2*a**3) def test_log_to_atan(): f, g = (Poly(x + S.Half, x, domain='QQ'), Poly(sqrt(3)/2, x, domain='EX')) fg_ans = 2*atan(2*sqrt(3)*x/3 + sqrt(3)/3) assert log_to_atan(f, g) == fg_ans assert log_to_atan(g, f) == -fg_ans
d816661036ac771ff797ae3ef618a802bcac0e3e8d979db41a940ddb19c413f0
"""Most of these tests come from the examples in Bronstein's book.""" from sympy.integrals.risch import DifferentialExtension, derivation from sympy.integrals.prde import (prde_normal_denom, prde_special_denom, prde_linear_constraints, constant_system, prde_spde, prde_no_cancel_b_large, prde_no_cancel_b_small, limited_integrate_reduce, limited_integrate, is_deriv_k, is_log_deriv_k_t_radical, parametric_log_deriv_heu, is_log_deriv_k_t_radical_in_field, param_poly_rischDE, param_rischDE, prde_cancel_liouvillian) from sympy.polys.polymatrix import PolyMatrix as Matrix from sympy.core.numbers import Rational from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.polys.domains.rationalfield import QQ from sympy.polys.polytools import Poly from sympy.abc import x, t, n t0, t1, t2, t3, k = symbols('t:4 k') def test_prde_normal_denom(): DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]}) fa = Poly(1, t) fd = Poly(x, t) G = [(Poly(t, t), Poly(1 + t**2, t)), (Poly(1, t), Poly(x + x*t**2, t))] assert prde_normal_denom(fa, fd, G, DE) == \ (Poly(x, t, domain='ZZ(x)'), (Poly(1, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')), [(Poly(x*t, t, domain='ZZ(x)'), Poly(t**2 + 1, t, domain='ZZ(x)')), (Poly(1, t, domain='ZZ(x)'), Poly(t**2 + 1, t, domain='ZZ(x)'))], Poly(1, t, domain='ZZ(x)')) G = [(Poly(t, t), Poly(t**2 + 2*t + 1, t)), (Poly(x*t, t), Poly(t**2 + 2*t + 1, t)), (Poly(x*t**2, t), Poly(t**2 + 2*t + 1, t))] DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]}) assert prde_normal_denom(Poly(x, t), Poly(1, t), G, DE) == \ (Poly(t + 1, t), (Poly((-1 + x)*t + x, t), Poly(1, t, domain='ZZ[x]')), [(Poly(t, t), Poly(1, t)), (Poly(x*t, t), Poly(1, t, domain='ZZ[x]')), (Poly(x*t**2, t), Poly(1, t, domain='ZZ[x]'))], Poly(t + 1, t)) def test_prde_special_denom(): a = Poly(t + 1, t) ba = Poly(t**2, t) bd = Poly(1, t) G = [(Poly(t, t), Poly(1, t)), (Poly(t**2, t), Poly(1, t)), (Poly(t**3, t), Poly(1, t))] DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]}) assert prde_special_denom(a, ba, bd, G, DE) == \ (Poly(t + 1, t), Poly(t**2, t), [(Poly(t, t), Poly(1, t)), (Poly(t**2, t), Poly(1, t)), (Poly(t**3, t), Poly(1, t))], Poly(1, t)) G = [(Poly(t, t), Poly(1, t)), (Poly(1, t), Poly(t, t))] assert prde_special_denom(Poly(1, t), Poly(t**2, t), Poly(1, t), G, DE) == \ (Poly(1, t), Poly(t**2 - 1, t), [(Poly(t**2, t), Poly(1, t)), (Poly(1, t), Poly(1, t))], Poly(t, t)) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-2*x*t0, t0)]}) DE.decrement_level() G = [(Poly(t, t), Poly(t**2, t)), (Poly(2*t, t), Poly(t, t))] assert prde_special_denom(Poly(5*x*t + 1, t), Poly(t**2 + 2*x**3*t, t), Poly(t**3 + 2, t), G, DE) == \ (Poly(5*x*t + 1, t), Poly(0, t, domain='ZZ[x]'), [(Poly(t, t), Poly(t**2, t)), (Poly(2*t, t), Poly(t, t))], Poly(1, x)) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly((t**2 + 1)*2*x, t)]}) G = [(Poly(t + x, t), Poly(t*x, t)), (Poly(2*t, t), Poly(x**2, x))] assert prde_special_denom(Poly(5*x*t + 1, t), Poly(t**2 + 2*x**3*t, t), Poly(t**3, t), G, DE) == \ (Poly(5*x*t + 1, t), Poly(0, t, domain='ZZ[x]'), [(Poly(t + x, t), Poly(x*t, t)), (Poly(2*t, t, x), Poly(x**2, t, x))], Poly(1, t)) assert prde_special_denom(Poly(t + 1, t), Poly(t**2, t), Poly(t**3, t), G, DE) == \ (Poly(t + 1, t), Poly(0, t, domain='ZZ[x]'), [(Poly(t + x, t), Poly(x*t, t)), (Poly(2*t, t, x), Poly(x**2, t, x))], Poly(1, t)) def test_prde_linear_constraints(): DE = DifferentialExtension(extension={'D': [Poly(1, x)]}) G = [(Poly(2*x**3 + 3*x + 1, x), Poly(x**2 - 1, x)), (Poly(1, x), Poly(x - 1, x)), (Poly(1, x), Poly(x + 1, x))] assert prde_linear_constraints(Poly(1, x), Poly(0, x), G, DE) == \ ((Poly(2*x, x, domain='QQ'), Poly(0, x, domain='QQ'), Poly(0, x, domain='QQ')), Matrix([[1, 1, -1], [5, 1, 1]], x)) G = [(Poly(t, t), Poly(1, t)), (Poly(t**2, t), Poly(1, t)), (Poly(t**3, t), Poly(1, t))] DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]}) assert prde_linear_constraints(Poly(t + 1, t), Poly(t**2, t), G, DE) == \ ((Poly(t, t, domain='QQ'), Poly(t**2, t, domain='QQ'), Poly(t**3, t, domain='QQ')), Matrix(0, 3, [], t)) G = [(Poly(2*x, t), Poly(t, t)), (Poly(-x, t), Poly(t, t))] DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]}) assert prde_linear_constraints(Poly(1, t), Poly(0, t), G, DE) == \ ((Poly(0, t, domain='QQ[x]'), Poly(0, t, domain='QQ[x]')), Matrix([[2*x, -x]], t)) def test_constant_system(): A = Matrix([[-(x + 3)/(x - 1), (x + 1)/(x - 1), 1], [-x - 3, x + 1, x - 1], [2*(x + 3)/(x - 1), 0, 0]], t) u = Matrix([[(x + 1)/(x - 1)], [x + 1], [0]], t) DE = DifferentialExtension(extension={'D': [Poly(1, x)]}) R = QQ.frac_field(x)[t] assert constant_system(A, u, DE) == \ (Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 0], [0, 0, 1]], ring=R), Matrix([0, 1, 0, 0], ring=R)) def test_prde_spde(): D = [Poly(x, t), Poly(-x*t, t)] DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]}) # TODO: when bound_degree() can handle this, test degree bound from that too assert prde_spde(Poly(t, t), Poly(-1/x, t), D, n, DE) == \ (Poly(t, t), Poly(0, t, domain='ZZ(x)'), [Poly(2*x, t, domain='ZZ(x)'), Poly(-x, t, domain='ZZ(x)')], [Poly(-x**2, t, domain='ZZ(x)'), Poly(0, t, domain='ZZ(x)')], n - 1) def test_prde_no_cancel(): # b large DE = DifferentialExtension(extension={'D': [Poly(1, x)]}) assert prde_no_cancel_b_large(Poly(1, x), [Poly(x**2, x), Poly(1, x)], 2, DE) == \ ([Poly(x**2 - 2*x + 2, x), Poly(1, x)], Matrix([[1, 0, -1, 0], [0, 1, 0, -1]], x)) assert prde_no_cancel_b_large(Poly(1, x), [Poly(x**3, x), Poly(1, x)], 3, DE) == \ ([Poly(x**3 - 3*x**2 + 6*x - 6, x), Poly(1, x)], Matrix([[1, 0, -1, 0], [0, 1, 0, -1]], x)) assert prde_no_cancel_b_large(Poly(x, x), [Poly(x**2, x), Poly(1, x)], 1, DE) == \ ([Poly(x, x, domain='ZZ'), Poly(0, x, domain='ZZ')], Matrix([[1, -1, 0, 0], [1, 0, -1, 0], [0, 1, 0, -1]], x)) # b small # XXX: Is there a better example of a monomial with D.degree() > 2? DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**3 + 1, t)]}) # My original q was t**4 + t + 1, but this solution implies q == t**4 # (c1 = 4), with some of the ci for the original q equal to 0. G = [Poly(t**6, t), Poly(x*t**5, t), Poly(t**3, t), Poly(x*t**2, t), Poly(1 + x, t)] R = QQ.frac_field(x)[t] assert prde_no_cancel_b_small(Poly(x*t, t), G, 4, DE) == \ ([Poly(t**4/4 - x/12*t**3 + x**2/24*t**2 + (Rational(-11, 12) - x**3/24)*t + x/24, t), Poly(x/3*t**3 - x**2/6*t**2 + (Rational(-1, 3) + x**3/6)*t - x/6, t), Poly(t, t), Poly(0, t), Poly(0, t)], Matrix([[1, 0, -1, 0, 0, 0, 0, 0, 0, 0], [0, 1, Rational(-1, 4), 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, -1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, -1, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, -1, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, -1, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, -1]], ring=R)) # TODO: Add test for deg(b) <= 0 with b small DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]}) b = Poly(-1/x**2, t, field=True) # deg(b) == 0 q = [Poly(x**i*t**j, t, field=True) for i in range(2) for j in range(3)] h, A = prde_no_cancel_b_small(b, q, 3, DE) V = A.nullspace() R = QQ.frac_field(x)[t] assert len(V) == 1 assert V[0] == Matrix([Rational(-1, 2), 0, 0, 1, 0, 0]*3, ring=R) assert (Matrix([h])*V[0][6:, :])[0] == Poly(x**2/2, t, domain='QQ(x)') assert (Matrix([q])*V[0][:6, :])[0] == Poly(x - S.Half, t, domain='QQ(x)') def test_prde_cancel_liouvillian(): ### 1. case == 'primitive' # used when integrating f = log(x) - log(x - 1) # Not taken from 'the' book DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]}) p0 = Poly(0, t, field=True) p1 = Poly((x - 1)*t, t, domain='ZZ(x)') p2 = Poly(x - 1, t, domain='ZZ(x)') p3 = Poly(-x**2 + x, t, domain='ZZ(x)') h, A = prde_cancel_liouvillian(Poly(-1/(x - 1), t), [Poly(-x + 1, t), Poly(1, t)], 1, DE) V = A.nullspace() assert h == [p0, p0, p1, p0, p0, p0, p0, p0, p0, p0, p2, p3, p0, p0, p0, p0] assert A.rank() == 16 assert (Matrix([h])*V[0][:16, :]) == Matrix([[Poly(0, t, domain='QQ(x)')]]) ### 2. case == 'exp' # used when integrating log(x/exp(x) + 1) # Not taken from book DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t, t)]}) assert prde_cancel_liouvillian(Poly(0, t, domain='QQ[x]'), [Poly(1, t, domain='QQ(x)')], 0, DE) == \ ([Poly(1, t, domain='QQ'), Poly(x, t, domain='ZZ(x)')], Matrix([[-1, 0, 1]], DE.t)) def test_param_poly_rischDE(): DE = DifferentialExtension(extension={'D': [Poly(1, x)]}) a = Poly(x**2 - x, x, field=True) b = Poly(1, x, field=True) q = [Poly(x, x, field=True), Poly(x**2, x, field=True)] h, A = param_poly_rischDE(a, b, q, 3, DE) assert A.nullspace() == [Matrix([0, 1, 1, 1], DE.t)] # c1, c2, d1, d2 # Solution of a*Dp + b*p = c1*q1 + c2*q2 = q2 = x**2 # is d1*h1 + d2*h2 = h1 + h2 = x. assert h[0] + h[1] == Poly(x, x, domain='QQ') # a*Dp + b*p = q1 = x has no solution. a = Poly(x**2 - x, x, field=True) b = Poly(x**2 - 5*x + 3, x, field=True) q = [Poly(1, x, field=True), Poly(x, x, field=True), Poly(x**2, x, field=True)] h, A = param_poly_rischDE(a, b, q, 3, DE) assert A.nullspace() == [Matrix([3, -5, 1, -5, 1, 1], DE.t)] p = -Poly(5, DE.t)*h[0] + h[1] + h[2] # Poly(1, x) assert a*derivation(p, DE) + b*p == Poly(x**2 - 5*x + 3, x, domain='QQ') def test_param_rischDE(): DE = DifferentialExtension(extension={'D': [Poly(1, x)]}) p1, px = Poly(1, x, field=True), Poly(x, x, field=True) G = [(p1, px), (p1, p1), (px, p1)] # [1/x, 1, x] h, A = param_rischDE(-p1, Poly(x**2, x, field=True), G, DE) assert len(h) == 3 p = [hi[0].as_expr()/hi[1].as_expr() for hi in h] V = A.nullspace() assert len(V) == 2 assert V[0] == Matrix([-1, 1, 0, -1, 1, 0], DE.t) y = -p[0] + p[1] + 0*p[2] # x assert y.diff(x) - y/x**2 == 1 - 1/x # Dy + f*y == -G0 + G1 + 0*G2 # the below test computation takes place while computing the integral # of 'f = log(log(x + exp(x)))' DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]}) G = [(Poly(t + x, t, domain='ZZ(x)'), Poly(1, t, domain='QQ')), (Poly(0, t, domain='QQ'), Poly(1, t, domain='QQ'))] h, A = param_rischDE(Poly(-t - 1, t, field=True), Poly(t + x, t, field=True), G, DE) assert len(h) == 5 p = [hi[0].as_expr()/hi[1].as_expr() for hi in h] V = A.nullspace() assert len(V) == 3 assert V[0] == Matrix([0, 0, 0, 0, 1, 0, 0], DE.t) y = 0*p[0] + 0*p[1] + 1*p[2] + 0*p[3] + 0*p[4] assert y.diff(t) - y/(t + x) == 0 # Dy + f*y = 0*G0 + 0*G1 def test_limited_integrate_reduce(): DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]}) assert limited_integrate_reduce(Poly(x, t), Poly(t**2, t), [(Poly(x, t), Poly(t, t))], DE) == \ (Poly(t, t), Poly(-1/x, t), Poly(t, t), 1, (Poly(x, t), Poly(1, t, domain='ZZ[x]')), [(Poly(-x*t, t), Poly(1, t, domain='ZZ[x]'))]) def test_limited_integrate(): DE = DifferentialExtension(extension={'D': [Poly(1, x)]}) G = [(Poly(x, x), Poly(x + 1, x))] assert limited_integrate(Poly(-(1 + x + 5*x**2 - 3*x**3), x), Poly(1 - x - x**2 + x**3, x), G, DE) == \ ((Poly(x**2 - x + 2, x), Poly(x - 1, x, domain='QQ')), [2]) G = [(Poly(1, x), Poly(x, x))] assert limited_integrate(Poly(5*x**2, x), Poly(3, x), G, DE) == \ ((Poly(5*x**3/9, x), Poly(1, x, domain='QQ')), [0]) def test_is_log_deriv_k_t_radical(): DE = DifferentialExtension(extension={'D': [Poly(1, x)], 'exts': [None], 'extargs': [None]}) assert is_log_deriv_k_t_radical(Poly(2*x, x), Poly(1, x), DE) is None DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(2*t1, t1), Poly(1/x, t2)], 'exts': [None, 'exp', 'log'], 'extargs': [None, 2*x, x]}) assert is_log_deriv_k_t_radical(Poly(x + t2/2, t2), Poly(1, t2), DE) == \ ([(t1, 1), (x, 1)], t1*x, 2, 0) # TODO: Add more tests DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t0, t0), Poly(1/x, t)], 'exts': [None, 'exp', 'log'], 'extargs': [None, x, x]}) assert is_log_deriv_k_t_radical(Poly(x + t/2 + 3, t), Poly(1, t), DE) == \ ([(t0, 2), (x, 1)], x*t0**2, 2, 3) def test_is_deriv_k(): DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t1), Poly(1/(x + 1), t2)], 'exts': [None, 'log', 'log'], 'extargs': [None, x, x + 1]}) assert is_deriv_k(Poly(2*x**2 + 2*x, t2), Poly(1, t2), DE) == \ ([(t1, 1), (t2, 1)], t1 + t2, 2) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t1), Poly(t2, t2)], 'exts': [None, 'log', 'exp'], 'extargs': [None, x, x]}) assert is_deriv_k(Poly(x**2*t2**3, t2), Poly(1, t2), DE) == \ ([(x, 3), (t1, 2)], 2*t1 + 3*x, 1) # TODO: Add more tests, including ones with exponentials DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(2/x, t1)], 'exts': [None, 'log'], 'extargs': [None, x**2]}) assert is_deriv_k(Poly(x, t1), Poly(1, t1), DE) == \ ([(t1, S.Half)], t1/2, 1) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(2/(1 + x), t0)], 'exts': [None, 'log'], 'extargs': [None, x**2 + 2*x + 1]}) assert is_deriv_k(Poly(1 + x, t0), Poly(1, t0), DE) == \ ([(t0, S.Half)], t0/2, 1) # Issue 10798 # DE = DifferentialExtension(log(1/x), x) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-1/x, t)], 'exts': [None, 'log'], 'extargs': [None, 1/x]}) assert is_deriv_k(Poly(1, t), Poly(x, t), DE) == ([(t, 1)], t, 1) def test_is_log_deriv_k_t_radical_in_field(): # NOTE: any potential constant factor in the second element of the result # doesn't matter, because it cancels in Da/a. DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]}) assert is_log_deriv_k_t_radical_in_field(Poly(5*t + 1, t), Poly(2*t*x, t), DE) == \ (2, t*x**5) assert is_log_deriv_k_t_radical_in_field(Poly(2 + 3*t, t), Poly(5*x*t, t), DE) == \ (5, x**3*t**2) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t/x**2, t)]}) assert is_log_deriv_k_t_radical_in_field(Poly(-(1 + 2*t), t), Poly(2*x**2 + 2*x**2*t, t), DE) == \ (2, t + t**2) assert is_log_deriv_k_t_radical_in_field(Poly(-1, t), Poly(x**2, t), DE) == \ (1, t) assert is_log_deriv_k_t_radical_in_field(Poly(1, t), Poly(2*x**2, t), DE) == \ (2, 1/t) def test_parametric_log_deriv(): DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]}) assert parametric_log_deriv_heu(Poly(5*t**2 + t - 6, t), Poly(2*x*t**2, t), Poly(-1, t), Poly(x*t**2, t), DE) == \ (2, 6, t*x**5)
d83148dad81132c8c76f0dad4184418802ffc2f7ccdc88065fdcf139bb2f9343
""" Parser for FullForm[Downvalues[]] of Mathematica rules. This parser is customised to parse the output in MatchPy rules format. Multiple `Constraints` are divided into individual `Constraints` because it helps the MatchPy's `ManyToOneReplacer` to backtrack earlier and improve the speed. Parsed output is formatted into readable format by using `sympify` and print the expression using `sstr`. This replaces `And`, `Mul`, 'Pow' by their respective symbols. Mathematica =========== To get the full form from Wolfram Mathematica, type: ``` ShowSteps = False Import["RubiLoader.m"] Export["output.txt", ToString@FullForm@DownValues@Int] ``` The file ``output.txt`` will then contain the rules in parseable format. References ========== [1] http://reference.wolfram.com/language/ref/FullForm.html [2] http://reference.wolfram.com/language/ref/DownValues.html [3] https://gist.github.com/Upabjojr/bc07c49262944f9c1eb0 """ import re import os import inspect from sympy.core.function import Function from sympy.core.symbol import Symbol from sympy.core.sympify import sympify from sympy.sets.sets import Set from sympy.printing import StrPrinter from sympy.utilities.misc import debug class RubiStrPrinter(StrPrinter): def _print_Not(self, expr): return "Not(%s)" % self._print(expr.args[0]) def rubi_printer(expr, **settings): return RubiStrPrinter(settings).doprint(expr) replacements = dict( # Mathematica equivalent functions in SymPy Times="Mul", Plus="Add", Power="Pow", Log='log', Exp='exp', Sqrt='sqrt', Cos='cos', Sin='sin', Tan='tan', Cot='1/tan', cot='1/tan', Sec='1/cos', sec='1/cos', Csc='1/sin', csc='1/sin', ArcSin='asin', ArcCos='acos', # ArcTan='atan', ArcCot='acot', ArcSec='asec', ArcCsc='acsc', Sinh='sinh', Cosh='cosh', Tanh='tanh', Coth='1/tanh', coth='1/tanh', Sech='1/cosh', sech='1/cosh', Csch='1/sinh', csch='1/sinh', ArcSinh='asinh', ArcCosh='acosh', ArcTanh='atanh', ArcCoth='acoth', ArcSech='asech', ArcCsch='acsch', Expand='expand', Im='im', Re='re', Flatten='flatten', Polylog='polylog', Cancel='cancel', #Gamma='gamma', TrigExpand='expand_trig', Sign='sign', Simplify='simplify', Defer='UnevaluatedExpr', Identity = 'S', Sum = 'Sum_doit', Module = 'With', Block = 'With', Null = 'None' ) temporary_variable_replacement = { # Temporarily rename because it can raise errors while sympifying 'gcd' : "_gcd", 'jn' : "_jn", } permanent_variable_replacement = { # Permamenely rename these variables r"\[ImaginaryI]" : 'ImaginaryI', "$UseGamma": '_UseGamma', } # These functions have different return type in different cases. So better to use a try and except in the constraints, when any of these appear f_diff_return_type = ['BinomialParts', 'BinomialDegree', 'TrinomialParts', 'GeneralizedBinomialParts', 'GeneralizedTrinomialParts', 'PseudoBinomialParts', 'PerfectPowerTest', 'SquareFreeFactorTest', 'SubstForFractionalPowerOfQuotientOfLinears', 'FractionalPowerOfQuotientOfLinears', 'InverseFunctionOfQuotientOfLinears', 'FractionalPowerOfSquareQ', 'FunctionOfLinear', 'FunctionOfInverseLinear', 'FunctionOfTrig', 'FindTrigFactor', 'FunctionOfLog', 'PowerVariableExpn', 'FunctionOfSquareRootOfQuadratic', 'SubstForFractionalPowerOfLinear', 'FractionalPowerOfLinear', 'InverseFunctionOfLinear', 'Divides', 'DerivativeDivides', 'TrigSquare', 'SplitProduct', 'SubstForFractionalPowerOfQuotientOfLinears', 'InverseFunctionOfQuotientOfLinears', 'FunctionOfHyperbolic', 'SplitSum'] def contains_diff_return_type(a): """ This function returns whether an expression contains functions which have different return types in diiferent cases. """ if isinstance(a, list): for i in a: if contains_diff_return_type(i): return True elif type(a) == Function('With') or type(a) == Function('Module'): for i in f_diff_return_type: if a.has(Function(i)): return True else: if a in f_diff_return_type: return True return False def parse_full_form(wmexpr): """ Parses FullForm[Downvalues[]] generated by Mathematica """ out = [] stack = [out] generator = re.finditer(r'[\[\],]', wmexpr) last_pos = 0 for match in generator: if match is None: break position = match.start() last_expr = wmexpr[last_pos:position].replace(',', '').replace(']', '').replace('[', '').strip() if match.group() == ',': if last_expr != '': stack[-1].append(last_expr) elif match.group() == ']': if last_expr != '': stack[-1].append(last_expr) stack.pop() elif match.group() == '[': stack[-1].append([last_expr]) stack.append(stack[-1][-1]) last_pos = match.end() return out[0] def get_default_values(parsed, default_values={}): """ Returns Optional variables and their values in the pattern """ if not isinstance(parsed, list): return default_values if parsed[0] == "Times": # find Default arguments for "Times" for i in parsed[1:]: if i[0] == "Optional": default_values[(i[1][1])] = 1 if parsed[0] == "Plus": # find Default arguments for "Plus" for i in parsed[1:]: if i[0] == "Optional": default_values[(i[1][1])] = 0 if parsed[0] == "Power": # find Default arguments for "Power" for i in parsed[1:]: if i[0] == "Optional": default_values[(i[1][1])] = 1 if len(parsed) == 1: return default_values for i in parsed: default_values = get_default_values(i, default_values) return default_values def add_wildcards(string, optional={}): """ Replaces `Pattern(variable)` by `variable` in `string`. Returns the free symbols present in the string. """ symbols = [] # stores symbols present in the expression p = r'(Optional\(Pattern\((\w+), Blank\)\))' matches = re.findall(p, string) for i in matches: string = string.replace(i[0], "WC('{}', S({}))".format(i[1], optional[i[1]])) symbols.append(i[1]) p = r'(Pattern\((\w+), Blank\))' matches = re.findall(p, string) for i in matches: string = string.replace(i[0], i[1] + '_') symbols.append(i[1]) p = r'(Pattern\((\w+), Blank\(Symbol\)\))' matches = re.findall(p, string) for i in matches: string = string.replace(i[0], i[1] + '_') symbols.append(i[1]) return string, symbols def seperate_freeq(s, variables=[], x=None): """ Returns list of symbols in FreeQ. """ if s[0] == 'FreeQ': if len(s[1]) == 1: variables = [s[1]] else: variables = s[1][1:] x = s[2] else: for i in s[1:]: variables, x = seperate_freeq(i, variables, x) return variables, x return variables, x def parse_freeq(l, x, cons_index, cons_dict, cons_import, symbols=None): """ Converts FreeQ constraints into MatchPy constraint """ res = [] cons = '' for i in l: if isinstance(i, str): r = ' return FreeQ({}, {})'.format(i, x) # First it checks if a constraint is already present in `cons_dict`, If yes, use it else create a new one. if r not in cons_dict.values(): cons_index += 1 c = '\n def cons_f{}({}, {}):\n'.format(cons_index, i, x) c += r c += '\n\n cons{} = CustomConstraint({})\n'.format(cons_index, 'cons_f{}'.format(cons_index)) cons_name = 'cons{}'.format(cons_index) cons_dict[cons_name] = r else: c = '' cons_name = next(key for key, value in sorted(cons_dict.items()) if value == r) elif isinstance(i, list): s = sorted(set(get_free_symbols(i, symbols))) s = ', '.join(s) r = ' return FreeQ({}, {})'.format(generate_sympy_from_parsed(i), x) if r not in cons_dict.values(): cons_index += 1 c = '\n def cons_f{}({}):\n'.format(cons_index, s) c += r c += '\n\n cons{} = CustomConstraint({})\n'.format(cons_index, 'cons_f{}'.format(cons_index)) cons_name = 'cons{}'.format(cons_index) cons_dict[cons_name] = r else: c = '' cons_name = next(key for key, value in cons_dict.items() if value == r) if cons_name not in cons_import: cons_import.append(cons_name) res.append(cons_name) cons += c if res != []: return ', ' + ', '.join(res), cons, cons_index return '', cons, cons_index def generate_sympy_from_parsed(parsed, wild=False, symbols=(), replace_Int=False): """ Parses list into Python syntax. Parameters ========== wild : When set to True, the symbols are replaced as wild symbols. symbols : Symbols already present in the pattern. replace_Int: when set to True, `Int` is replaced by `Integral`(used to parse pattern). """ out = "" if not isinstance(parsed, list): try: # return S(number) if parsed is Number float(parsed) return "S({})".format(parsed) except: pass if parsed in symbols: if wild: return parsed + '_' return parsed if parsed[0] == 'Rational': return 'S({})/S({})'.format(generate_sympy_from_parsed(parsed[1], wild=wild, symbols=symbols, replace_Int=replace_Int), generate_sympy_from_parsed(parsed[2], wild=wild, symbols=symbols, replace_Int=replace_Int)) if parsed[0] in replacements: out += replacements[parsed[0]] elif parsed[0] == 'Int' and replace_Int: out += 'Integral' else: out += parsed[0] if len(parsed) == 1: return out result = [generate_sympy_from_parsed(i, wild=wild, symbols=symbols, replace_Int=replace_Int) for i in parsed[1:]] if '' in result: result.remove('') out += "(" out += ", ".join(result) out += ")" return out def get_free_symbols(s, symbols, free_symbols=None): """ Returns free_symbols present in `s`. """ free_symbols = free_symbols or [] if not isinstance(s, list): if s in symbols: free_symbols.append(s) return free_symbols for i in s: free_symbols = get_free_symbols(i, symbols, free_symbols) return free_symbols def set_matchq_in_constraint(a, cons_index): """ Takes care of the case, when a pattern matching has to be done inside a constraint. """ lst = [] res = '' if isinstance(a, list): if a[0] == 'MatchQ': s = a optional = get_default_values(s, {}) r = generate_sympy_from_parsed(s, replace_Int=True) r, free_symbols = add_wildcards(r, optional=optional) free_symbols = sorted(set(free_symbols)) # remove common symbols r = sympify(r, locals={"Or": Function("Or"), "And": Function("And"), "Not":Function("Not")}) pattern = r.args[1].args[0] cons = r.args[1].args[1] pattern = rubi_printer(pattern, sympy_integers=True) pattern = setWC(pattern) res = ' def _cons_f_{}({}):\n return {}\n'.format(cons_index, ', '.join(free_symbols), cons) res += ' _cons_{} = CustomConstraint(_cons_f_{})\n'.format(cons_index, cons_index) res += ' pat = Pattern(UtilityOperator({}, x), _cons_{})\n'.format(pattern, cons_index) res += ' result_matchq = is_match(UtilityOperator({}, x), pat)'.format(r.args[0]) return "result_matchq", res else: for i in a: if isinstance(i, list): r = set_matchq_in_constraint(i, cons_index) lst.append(r[0]) res = r[1] else: lst.append(i) return lst, res def _divide_constriant(s, symbols, cons_index, cons_dict, cons_import): # Creates a CustomConstraint of the form `CustomConstraint(lambda a, x: FreeQ(a, x))` lambda_symbols = sorted(set(get_free_symbols(s, symbols, []))) r = generate_sympy_from_parsed(s) r = sympify(r, locals={"Or": Function("Or"), "And": Function("And"), "Not":Function("Not")}) if r.has(Function('MatchQ')): match_res = set_matchq_in_constraint(s, cons_index) res = match_res[1] res += '\n return {}'.format(rubi_printer(sympify(generate_sympy_from_parsed(match_res[0]), locals={"Or": Function("Or"), "And": Function("And"), "Not":Function("Not")}), sympy_integers = True)) elif contains_diff_return_type(s): res = ' try:\n return {}\n except (TypeError, AttributeError):\n return False'.format(rubi_printer(r, sympy_integers=True)) else: res = ' return {}'.format(rubi_printer(r, sympy_integers=True)) # First it checks if a constraint is already present in `cons_dict`, If yes, use it else create a new one. if res not in cons_dict.values(): cons_index += 1 cons = '\n def cons_f{}({}):\n'.format(cons_index, ', '.join(lambda_symbols)) if 'x' in lambda_symbols: cons += ' if isinstance(x, (int, Integer, float, Float)):\n return False\n' cons += res cons += '\n\n cons{} = CustomConstraint({})\n'.format(cons_index, 'cons_f{}'.format(cons_index)) cons_name = 'cons{}'.format(cons_index) cons_dict[cons_name] = res else: cons = '' cons_name = next(key for key, value in cons_dict.items() if value == res) if cons_name not in cons_import: cons_import.append(cons_name) return cons_name, cons, cons_index def divide_constraint(s, symbols, cons_index, cons_dict, cons_import): """ Divides multiple constraints into smaller constraints. Parameters ========== s : constraint as list symbols : all the symbols present in the expression """ result =[] cons = '' if s[0] == 'And': for i in s[1:]: if i[0]!= 'FreeQ': a = _divide_constriant(i, symbols, cons_index, cons_dict, cons_import) result.append(a[0]) cons += a[1] cons_index = a[2] else: a = _divide_constriant(s, symbols, cons_index, cons_dict, cons_import) result.append(a[0]) cons += a[1] cons_index = a[2] r = [''] for i in result: if i != '': r.append(i) return ', '.join(r),cons, cons_index def setWC(string): """ Replaces `WC(a, b)` by `WC('a', S(b))` """ p = r'(WC\((\w+), S\(([-+]?\d)\)\))' matches = re.findall(p, string) for i in matches: string = string.replace(i[0], "WC('{}', S({}))".format(i[1], i[2])) return string def process_return_type(a1, L): """ Functions like `Set`, `With` and `CompoundExpression` has to be taken special care. """ a = sympify(a1[1]) x = '' processed = False return_value = '' if type(a) == Function('With') or type(a) == Function('Module'): for i in a.args: for s in i.args: if isinstance(s, Set) and s not in L: x += '\n {} = {}'.format(s.args[0], rubi_printer(s.args[1], sympy_integers=True)) if not type(i) in (Function('List'), Function('CompoundExpression')) and not i.has(Function('CompoundExpression')): return_value = i processed = True elif type(i) == Function('CompoundExpression'): return_value = i.args[-1] processed = True elif type(i.args[0]) == Function('CompoundExpression'): C = i.args[0] return_value = '{}({}, {})'.format(i.func, C.args[-1], i.args[1]) processed = True return x, return_value, processed def extract_set(s, L): """ this function extracts all `Set` functions """ lst = [] if isinstance(s, Set) and s not in L: lst.append(s) else: try: for i in s.args: lst += extract_set(i, L) except: # when s has no attribute args (like `bool`) pass return lst def replaceWith(s, symbols, index): """ Replaces `With` and `Module by python functions` """ return_type = None with_value = '' if type(s) == Function('With') or type(s) == Function('Module'): constraints = ' ' result = '\n\n\ndef With{}({}):'.format(index, ', '.join(symbols)) if type(s.args[0]) == Function('List'): # get all local variables of With and Module L = list(s.args[0].args) else: L = [s.args[0]] lst = [] for i in s.args[1:]: lst += extract_set(i, L) L += lst for i in L: # define local variables if isinstance(i, Set): with_value += '\n {} = {}'.format(i.args[0], rubi_printer(i.args[1], sympy_integers=True)) elif isinstance(i, Symbol): with_value += "\n {} = Symbol('{}')".format(i, i) #result += with_value if type(s.args[1]) == Function('CompoundExpression'): # Expand CompoundExpression C = s.args[1] result += with_value if isinstance(C.args[0], Set): result += '\n {} = {}'.format(C.args[0].args[0], C.args[0].args[1]) result += '\n return {}'.format(rubi_printer(C.args[1], sympy_integers=True)) return result, constraints, return_type elif type(s.args[1]) == Function('Condition'): C = s.args[1] if len(C.args) == 2: if all(j in symbols for j in [str(i) for i in C.free_symbols]): result += with_value #constraints += 'CustomConstraint(lambda {}: {})'.format(', '.join([str(i) for i in C.free_symbols]), sstr(C.args[1], sympy_integers=True)) result += '\n return {}'.format(rubi_printer(C.args[0], sympy_integers=True)) else: if 'x' in symbols: result += '\n if isinstance(x, (int, Integer, float, Float)):\n return False' if contains_diff_return_type(s): n_with_value = with_value.replace('\n', '\n ') result += '\n try:{}\n res = {}'.format(n_with_value, rubi_printer(C.args[1], sympy_integers=True)) result += '\n except (TypeError, AttributeError):\n return False' result += '\n if res:' else: result+=with_value result += '\n if {}:'.format(rubi_printer(C.args[1], sympy_integers=True)) return_type = (with_value, rubi_printer(C.args[0], sympy_integers=True)) return_type1 = process_return_type(return_type, L) if return_type1[2]: return_type = (with_value+return_type1[0], rubi_printer(return_type1[1])) result += '\n return True' result += '\n return False' constraints = ', CustomConstraint(With{})'.format(index) return result, constraints, return_type elif type(s.args[1]) == Function('Module') or type(s.args[1]) == Function('With'): C = s.args[1] result += with_value return_type = (with_value, rubi_printer(C, sympy_integers=True)) return_type1 = process_return_type(return_type, L) if return_type1[2]: return_type = (with_value+return_type1[0], rubi_printer(return_type1[1])) result += return_type1[0] result += '\n return {}'.format(rubi_printer(return_type1[1])) return result, constraints, None elif s.args[1].has(Function("CompoundExpression")): C = s.args[1].args[0] result += with_value if isinstance(C.args[0], Set): result += '\n {} = {}'.format(C.args[0].args[0], C.args[0].args[1]) result += '\n return {}({}, {})'.format(s.args[1].func, C.args[-1], s.args[1].args[1]) return result, constraints, None result += with_value result += '\n return {}'.format(rubi_printer(s.args[1], sympy_integers=True)) return result, constraints, return_type else: return rubi_printer(s, sympy_integers=True), '', return_type def downvalues_rules(r, header, cons_dict, cons_index, index): """ Function which generates parsed rules by substituting all possible combinations of default values. """ rules = '[' parsed = '\n\n' repl_funcs = '\n\n' cons = '' cons_import = [] # it contains name of constraints that need to be imported for rules. for i in r: debug('parsing rule {}'.format(r.index(i) + 1)) # Parse Pattern if i[1][1][0] == 'Condition': p = i[1][1][1].copy() else: p = i[1][1].copy() optional = get_default_values(p, {}) pattern = generate_sympy_from_parsed(p.copy(), replace_Int=True) pattern, free_symbols = add_wildcards(pattern, optional=optional) free_symbols = sorted(set(free_symbols)) #remove common symbols # Parse Transformed Expression and Constraints if i[2][0] == 'Condition': # parse rules without constraints separately constriant, constraint_def, cons_index = divide_constraint(i[2][2], free_symbols, cons_index, cons_dict, cons_import) # separate And constraints into individual constraints FreeQ_vars, FreeQ_x = seperate_freeq(i[2][2].copy()) # separate FreeQ into individual constraints transformed = generate_sympy_from_parsed(i[2][1].copy(), symbols=free_symbols) else: constriant = '' constraint_def = '' FreeQ_vars, FreeQ_x = [], [] transformed = generate_sympy_from_parsed(i[2].copy(), symbols=free_symbols) FreeQ_constraint, free_cons_def, cons_index = parse_freeq(FreeQ_vars, FreeQ_x, cons_index, cons_dict, cons_import, free_symbols) pattern = sympify(pattern, locals={"Or": Function("Or"), "And": Function("And"), "Not":Function("Not") }) pattern = rubi_printer(pattern, sympy_integers=True) pattern = setWC(pattern) transformed = sympify(transformed, locals={"Or": Function("Or"), "And": Function("And"), "Not":Function("Not") }) constraint_def = constraint_def + free_cons_def cons += constraint_def index += 1 # below are certain if - else condition depending on various situation that may be encountered if type(transformed) == Function('With') or type(transformed) == Function('Module'): # define separate function when With appears transformed, With_constraints, return_type = replaceWith(transformed, free_symbols, index) if return_type is None: repl_funcs += '{}'.format(transformed) parsed += '\n pattern' + str(index) + ' = Pattern(' + pattern + '' + FreeQ_constraint + '' + constriant + ')' parsed += '\n ' + 'rule' + str(index) + ' = ReplacementRule(' + 'pattern' + rubi_printer(index, sympy_integers=True) + ', With{}'.format(index) + ')\n' else: repl_funcs += '{}'.format(transformed) parsed += '\n pattern' + str(index) + ' = Pattern(' + pattern + '' + FreeQ_constraint + '' + constriant + With_constraints + ')' repl_funcs += '\n\n\ndef replacement{}({}):\n'.format( index, ', '.join(free_symbols) ) + return_type[0] + '\n return '.format(index) + return_type[1] parsed += '\n ' + 'rule' + str(index) + ' = ReplacementRule(' + 'pattern' + rubi_printer(index, sympy_integers=True) + ', replacement{}'.format(index) + ')\n' else: transformed = rubi_printer(transformed, sympy_integers=True) parsed += '\n pattern' + str(index) + ' = Pattern(' + pattern + '' + FreeQ_constraint + '' + constriant + ')' repl_funcs += '\n\n\ndef replacement{}({}):\n return '.format(index, ', '.join(free_symbols), index) + transformed parsed += '\n ' + 'rule' + str(index) + ' = ReplacementRule(' + 'pattern' + rubi_printer(index, sympy_integers=True) + ', replacement{}'.format(index) + ')\n' rules += 'rule{}, '.format(index) rules += ']' parsed += ' return ' + rules +'\n' header += ' from sympy.integrals.rubi.constraints import ' + ', '.join(word for word in cons_import) parsed = header + parsed + repl_funcs return parsed, cons_index, cons, index def rubi_rule_parser(fullform, header=None, module_name='rubi_object'): """ Parses rules in MatchPy format. Parameters ========== fullform : FullForm of the rule as string. header : Header imports for the file. Uses default imports if None. module_name : name of RUBI module References ========== [1] http://reference.wolfram.com/language/ref/FullForm.html [2] http://reference.wolfram.com/language/ref/DownValues.html [3] https://gist.github.com/Upabjojr/bc07c49262944f9c1eb0 """ if header is None: # use default header values path_header = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) header = open(os.path.join(path_header, "header.py.txt")).read() header = header.format(module_name) cons_dict = {} # dict keeps track of constraints that has been encountered, thus avoids repetition of constraints. cons_index = 0 # for index of a constraint index = 0 # indicates the number of a rule. cons = '' # Temporarily rename these variables because it # can raise errors while sympifying for i in temporary_variable_replacement: fullform = fullform.replace(i, temporary_variable_replacement[i]) # Permanently rename these variables for i in permanent_variable_replacement: fullform = fullform.replace(i, permanent_variable_replacement[i]) rules = [] for i in parse_full_form(fullform): # separate all rules if i[0] == 'RuleDelayed': rules.append(i) parsed = downvalues_rules(rules, header, cons_dict, cons_index, index) result = parsed[0].strip() + '\n' cons += parsed[2] # Replace temporary variables by actual values for i in temporary_variable_replacement: cons = cons.replace(temporary_variable_replacement[i], i) result = result.replace(temporary_variable_replacement[i], i) cons = "\n".join(header.split("\n")[:-2]) + '\n' + cons return result, cons
e2c87f04565d3247edc337d536b94a8401b5742569c18a62f8e9997e5f4e8307
from sympy.core.basic import Basic from sympy.core.containers import Tuple from sympy.core.sorting import default_sort_key from sympy.core.symbol import symbols from sympy.core.singleton import S from sympy.core.function import expand, Function from sympy.core.numbers import I from sympy.integrals.integrals import Integral from sympy.polys.polytools import factor from sympy.core.traversal import preorder_traversal, use, postorder_traversal, iterargs, iterfreeargs from sympy.functions.elementary.piecewise import ExprCondPair, Piecewise b1 = Basic() b2 = Basic(b1) b3 = Basic(b2) b21 = Basic(b2, b1) def test_preorder_traversal(): expr = Basic(b21, b3) assert list( preorder_traversal(expr)) == [expr, b21, b2, b1, b1, b3, b2, b1] assert list(preorder_traversal(('abc', ('d', 'ef')))) == [ ('abc', ('d', 'ef')), 'abc', ('d', 'ef'), 'd', 'ef'] result = [] pt = preorder_traversal(expr) for i in pt: result.append(i) if i == b2: pt.skip() assert result == [expr, b21, b2, b1, b3, b2] w, x, y, z = symbols('w:z') expr = z + w*(x + y) assert list(preorder_traversal([expr], keys=default_sort_key)) == \ [[w*(x + y) + z], w*(x + y) + z, z, w*(x + y), w, x + y, x, y] assert list(preorder_traversal((x + y)*z, keys=True)) == \ [z*(x + y), z, x + y, x, y] def test_use(): x, y = symbols('x y') assert use(0, expand) == 0 f = (x + y)**2*x + 1 assert use(f, expand, level=0) == x**3 + 2*x**2*y + x*y**2 + + 1 assert use(f, expand, level=1) == x**3 + 2*x**2*y + x*y**2 + + 1 assert use(f, expand, level=2) == 1 + x*(2*x*y + x**2 + y**2) assert use(f, expand, level=3) == (x + y)**2*x + 1 f = (x**2 + 1)**2 - 1 kwargs = {'gaussian': True} assert use(f, factor, level=0, kwargs=kwargs) == x**2*(x**2 + 2) assert use(f, factor, level=1, kwargs=kwargs) == (x + I)**2*(x - I)**2 - 1 assert use(f, factor, level=2, kwargs=kwargs) == (x + I)**2*(x - I)**2 - 1 assert use(f, factor, level=3, kwargs=kwargs) == (x**2 + 1)**2 - 1 def test_postorder_traversal(): x, y, z, w = symbols('x y z w') expr = z + w*(x + y) expected = [z, w, x, y, x + y, w*(x + y), w*(x + y) + z] assert list(postorder_traversal(expr, keys=default_sort_key)) == expected assert list(postorder_traversal(expr, keys=True)) == expected expr = Piecewise((x, x < 1), (x**2, True)) expected = [ x, 1, x, x < 1, ExprCondPair(x, x < 1), 2, x, x**2, S.true, ExprCondPair(x**2, True), Piecewise((x, x < 1), (x**2, True)) ] assert list(postorder_traversal(expr, keys=default_sort_key)) == expected assert list(postorder_traversal( [expr], keys=default_sort_key)) == expected + [[expr]] assert list(postorder_traversal(Integral(x**2, (x, 0, 1)), keys=default_sort_key)) == [ 2, x, x**2, 0, 1, x, Tuple(x, 0, 1), Integral(x**2, Tuple(x, 0, 1)) ] assert list(postorder_traversal(('abc', ('d', 'ef')))) == [ 'abc', 'd', 'ef', ('d', 'ef'), ('abc', ('d', 'ef'))] def test_iterargs(): f = Function('f') x = symbols('x') assert list(iterfreeargs(Integral(f(x), (f(x), 1)))) == [ Integral(f(x), (f(x), 1)), 1] assert list(iterargs(Integral(f(x), (f(x), 1)))) == [ Integral(f(x), (f(x), 1)), f(x), (f(x), 1), x, f(x), 1, x]
3e551eae58a3293c5898cdc6011069d5030b933565cf4b4ca264ba4e66703728
from sympy.calculus.accumulationbounds import AccumBounds from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.containers import (Dict, Tuple) from sympy.core.function import (Derivative, Function, Lambda, Subs) from sympy.core.mul import Mul from sympy.core.numbers import (Float, I, Integer, Rational, oo, pi, zoo) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Symbol, Wild, symbols) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (atan2, cos, cot, sin, tan) from sympy.matrices.dense import (Matrix, zeros) from sympy.matrices.expressions.special import ZeroMatrix from sympy.polys.polytools import factor from sympy.polys.rootoftools import RootOf from sympy.simplify.cse_main import cse from sympy.simplify.simplify import nsimplify from sympy.core.basic import _aresame from sympy.testing.pytest import XFAIL from sympy.abc import a, x, y, z, t def test_subs(): n3 = Rational(3) e = x e = e.subs(x, n3) assert e == Rational(3) e = 2*x assert e == 2*x e = e.subs(x, n3) assert e == Rational(6) def test_subs_Matrix(): z = zeros(2) z1 = ZeroMatrix(2, 2) assert (x*y).subs({x:z, y:0}) in [z, z1] assert (x*y).subs({y:z, x:0}) == 0 assert (x*y).subs({y:z, x:0}, simultaneous=True) in [z, z1] assert (x + y).subs({x: z, y: z}, simultaneous=True) in [z, z1] assert (x + y).subs({x: z, y: z}) in [z, z1] # Issue #15528 assert Mul(Matrix([[3]]), x).subs(x, 2.0) == Matrix([[6.0]]) # Does not raise a TypeError, see comment on the MatAdd postprocessor assert Add(Matrix([[3]]), x).subs(x, 2.0) == Add(Matrix([[3]]), 2.0) def test_subs_AccumBounds(): e = x e = e.subs(x, AccumBounds(1, 3)) assert e == AccumBounds(1, 3) e = 2*x e = e.subs(x, AccumBounds(1, 3)) assert e == AccumBounds(2, 6) e = x + x**2 e = e.subs(x, AccumBounds(-1, 1)) assert e == AccumBounds(-1, 2) def test_trigonometric(): n3 = Rational(3) e = (sin(x)**2).diff(x) assert e == 2*sin(x)*cos(x) e = e.subs(x, n3) assert e == 2*cos(n3)*sin(n3) e = (sin(x)**2).diff(x) assert e == 2*sin(x)*cos(x) e = e.subs(sin(x), cos(x)) assert e == 2*cos(x)**2 assert exp(pi).subs(exp, sin) == 0 assert cos(exp(pi)).subs(exp, sin) == 1 i = Symbol('i', integer=True) zoo = S.ComplexInfinity assert tan(x).subs(x, pi/2) is zoo assert cot(x).subs(x, pi) is zoo assert cot(i*x).subs(x, pi) is zoo assert tan(i*x).subs(x, pi/2) == tan(i*pi/2) assert tan(i*x).subs(x, pi/2).subs(i, 1) is zoo o = Symbol('o', odd=True) assert tan(o*x).subs(x, pi/2) == tan(o*pi/2) def test_powers(): assert sqrt(1 - sqrt(x)).subs(x, 4) == I assert (sqrt(1 - x**2)**3).subs(x, 2) == - 3*I*sqrt(3) assert (x**Rational(1, 3)).subs(x, 27) == 3 assert (x**Rational(1, 3)).subs(x, -27) == 3*(-1)**Rational(1, 3) assert ((-x)**Rational(1, 3)).subs(x, 27) == 3*(-1)**Rational(1, 3) n = Symbol('n', negative=True) assert (x**n).subs(x, 0) is S.ComplexInfinity assert exp(-1).subs(S.Exp1, 0) is S.ComplexInfinity assert (x**(4.0*y)).subs(x**(2.0*y), n) == n**2.0 assert (2**(x + 2)).subs(2, 3) == 3**(x + 3) def test_logexppow(): # no eval() x = Symbol('x', real=True) w = Symbol('w') e = (3**(1 + x) + 2**(1 + x))/(3**x + 2**x) assert e.subs(2**x, w) != e assert e.subs(exp(x*log(Rational(2))), w) != e def test_bug(): x1 = Symbol('x1') x2 = Symbol('x2') y = x1*x2 assert y.subs(x1, Float(3.0)) == Float(3.0)*x2 def test_subbug1(): # see that they don't fail (x**x).subs(x, 1) (x**x).subs(x, 1.0) def test_subbug2(): # Ensure this does not cause infinite recursion assert Float(7.7).epsilon_eq(abs(x).subs(x, -7.7)) def test_dict_set(): a, b, c = map(Wild, 'abc') f = 3*cos(4*x) r = f.match(a*cos(b*x)) assert r == {a: 3, b: 4} e = a/b*sin(b*x) assert e.subs(r) == r[a]/r[b]*sin(r[b]*x) assert e.subs(r) == 3*sin(4*x) / 4 s = set(r.items()) assert e.subs(s) == r[a]/r[b]*sin(r[b]*x) assert e.subs(s) == 3*sin(4*x) / 4 assert e.subs(r) == r[a]/r[b]*sin(r[b]*x) assert e.subs(r) == 3*sin(4*x) / 4 assert x.subs(Dict((x, 1))) == 1 def test_dict_ambigous(): # see issue 3566 f = x*exp(x) g = z*exp(z) df = {x: y, exp(x): y} dg = {z: y, exp(z): y} assert f.subs(df) == y**2 assert g.subs(dg) == y**2 # and this is how order can affect the result assert f.subs(x, y).subs(exp(x), y) == y*exp(y) assert f.subs(exp(x), y).subs(x, y) == y**2 # length of args and count_ops are the same so # default_sort_key resolves ordering...if one # doesn't want this result then an unordered # sequence should not be used. e = 1 + x*y assert e.subs({x: y, y: 2}) == 5 # here, there are no obviously clashing keys or values # but the results depend on the order assert exp(x/2 + y).subs({exp(y + 1): 2, x: 2}) == exp(y + 1) def test_deriv_sub_bug3(): f = Function('f') pat = Derivative(f(x), x, x) assert pat.subs(y, y**2) == Derivative(f(x), x, x) assert pat.subs(y, y**2) != Derivative(f(x), x) def test_equality_subs1(): f = Function('f') eq = Eq(f(x)**2, x) res = Eq(Integer(16), x) assert eq.subs(f(x), 4) == res def test_equality_subs2(): f = Function('f') eq = Eq(f(x)**2, 16) assert bool(eq.subs(f(x), 3)) is False assert bool(eq.subs(f(x), 4)) is True def test_issue_3742(): e = sqrt(x)*exp(y) assert e.subs(sqrt(x), 1) == exp(y) def test_subs_dict1(): assert (1 + x*y).subs(x, pi) == 1 + pi*y assert (1 + x*y).subs({x: pi, y: 2}) == 1 + 2*pi c2, c3, q1p, q2p, c1, s1, s2, s3 = symbols('c2 c3 q1p q2p c1 s1 s2 s3') test = (c2**2*q2p*c3 + c1**2*s2**2*q2p*c3 + s1**2*s2**2*q2p*c3 - c1**2*q1p*c2*s3 - s1**2*q1p*c2*s3) assert (test.subs({c1**2: 1 - s1**2, c2**2: 1 - s2**2, c3**3: 1 - s3**2}) == c3*q2p*(1 - s2**2) + c3*q2p*s2**2*(1 - s1**2) - c2*q1p*s3*(1 - s1**2) + c3*q2p*s1**2*s2**2 - c2*q1p*s3*s1**2) def test_mul(): x, y, z, a, b, c = symbols('x y z a b c') A, B, C = symbols('A B C', commutative=0) assert (x*y*z).subs(z*x, y) == y**2 assert (z*x).subs(1/x, z) == 1 assert (x*y/z).subs(1/z, a) == a*x*y assert (x*y/z).subs(x/z, a) == a*y assert (x*y/z).subs(y/z, a) == a*x assert (x*y/z).subs(x/z, 1/a) == y/a assert (x*y/z).subs(x, 1/a) == y/(z*a) assert (2*x*y).subs(5*x*y, z) != z*Rational(2, 5) assert (x*y*A).subs(x*y, a) == a*A assert (x**2*y**(x*Rational(3, 2))).subs(x*y**(x/2), 2) == 4*y**(x/2) assert (x*exp(x*2)).subs(x*exp(x), 2) == 2*exp(x) assert ((x**(2*y))**3).subs(x**y, 2) == 64 assert (x*A*B).subs(x*A, y) == y*B assert (x*y*(1 + x)*(1 + x*y)).subs(x*y, 2) == 6*(1 + x) assert ((1 + A*B)*A*B).subs(A*B, x*A*B) assert (x*a/z).subs(x/z, A) == a*A assert (x**3*A).subs(x**2*A, a) == a*x assert (x**2*A*B).subs(x**2*B, a) == a*A assert (x**2*A*B).subs(x**2*A, a) == a*B assert (b*A**3/(a**3*c**3)).subs(a**4*c**3*A**3/b**4, z) == \ b*A**3/(a**3*c**3) assert (6*x).subs(2*x, y) == 3*y assert (y*exp(x*Rational(3, 2))).subs(y*exp(x), 2) == 2*exp(x/2) assert (y*exp(x*Rational(3, 2))).subs(y*exp(x), 2) == 2*exp(x/2) assert (A**2*B*A**2*B*A**2).subs(A*B*A, C) == A*C**2*A assert (x*A**3).subs(x*A, y) == y*A**2 assert (x**2*A**3).subs(x*A, y) == y**2*A assert (x*A**3).subs(x*A, B) == B*A**2 assert (x*A*B*A*exp(x*A*B)).subs(x*A, B) == B**2*A*exp(B*B) assert (x**2*A*B*A*exp(x*A*B)).subs(x*A, B) == B**3*exp(B**2) assert (x**3*A*exp(x*A*B)*A*exp(x*A*B)).subs(x*A, B) == \ x*B*exp(B**2)*B*exp(B**2) assert (x*A*B*C*A*B).subs(x*A*B, C) == C**2*A*B assert (-I*a*b).subs(a*b, 2) == -2*I # issue 6361 assert (-8*I*a).subs(-2*a, 1) == 4*I assert (-I*a).subs(-a, 1) == I # issue 6441 assert (4*x**2).subs(2*x, y) == y**2 assert (2*4*x**2).subs(2*x, y) == 2*y**2 assert (-x**3/9).subs(-x/3, z) == -z**2*x assert (-x**3/9).subs(x/3, z) == -z**2*x assert (-2*x**3/9).subs(x/3, z) == -2*x*z**2 assert (-2*x**3/9).subs(-x/3, z) == -2*x*z**2 assert (-2*x**3/9).subs(-2*x, z) == z*x**2/9 assert (-2*x**3/9).subs(2*x, z) == -z*x**2/9 assert (2*(3*x/5/7)**2).subs(3*x/5, z) == 2*(Rational(1, 7))**2*z**2 assert (4*x).subs(-2*x, z) == 4*x # try keep subs literal def test_subs_simple(): a = symbols('a', commutative=True) x = symbols('x', commutative=False) assert (2*a).subs(1, 3) == 2*a assert (2*a).subs(2, 3) == 3*a assert (2*a).subs(a, 3) == 6 assert sin(2).subs(1, 3) == sin(2) assert sin(2).subs(2, 3) == sin(3) assert sin(a).subs(a, 3) == sin(3) assert (2*x).subs(1, 3) == 2*x assert (2*x).subs(2, 3) == 3*x assert (2*x).subs(x, 3) == 6 assert sin(x).subs(x, 3) == sin(3) def test_subs_constants(): a, b = symbols('a b', commutative=True) x, y = symbols('x y', commutative=False) assert (a*b).subs(2*a, 1) == a*b assert (1.5*a*b).subs(a, 1) == 1.5*b assert (2*a*b).subs(2*a, 1) == b assert (2*a*b).subs(4*a, 1) == 2*a*b assert (x*y).subs(2*x, 1) == x*y assert (1.5*x*y).subs(x, 1) == 1.5*y assert (2*x*y).subs(2*x, 1) == y assert (2*x*y).subs(4*x, 1) == 2*x*y def test_subs_commutative(): a, b, c, d, K = symbols('a b c d K', commutative=True) assert (a*b).subs(a*b, K) == K assert (a*b*a*b).subs(a*b, K) == K**2 assert (a*a*b*b).subs(a*b, K) == K**2 assert (a*b*c*d).subs(a*b*c, K) == d*K assert (a*b**c).subs(a, K) == K*b**c assert (a*b**c).subs(b, K) == a*K**c assert (a*b**c).subs(c, K) == a*b**K assert (a*b*c*b*a).subs(a*b, K) == c*K**2 assert (a**3*b**2*a).subs(a*b, K) == a**2*K**2 def test_subs_noncommutative(): w, x, y, z, L = symbols('w x y z L', commutative=False) alpha = symbols('alpha', commutative=True) someint = symbols('someint', commutative=True, integer=True) assert (x*y).subs(x*y, L) == L assert (w*y*x).subs(x*y, L) == w*y*x assert (w*x*y*z).subs(x*y, L) == w*L*z assert (x*y*x*y).subs(x*y, L) == L**2 assert (x*x*y).subs(x*y, L) == x*L assert (x*x*y*y).subs(x*y, L) == x*L*y assert (w*x*y).subs(x*y*z, L) == w*x*y assert (x*y**z).subs(x, L) == L*y**z assert (x*y**z).subs(y, L) == x*L**z assert (x*y**z).subs(z, L) == x*y**L assert (w*x*y*z*x*y).subs(x*y*z, L) == w*L*x*y assert (w*x*y*y*w*x*x*y*x*y*y*x*y).subs(x*y, L) == w*L*y*w*x*L**2*y*L # Check fractional power substitutions. It should not do # substitutions that choose a value for noncommutative log, # or inverses that don't already appear in the expressions. assert (x*x*x).subs(x*x, L) == L*x assert (x*x*x*y*x*x*x*x).subs(x*x, L) == L*x*y*L**2 for p in range(1, 5): for k in range(10): assert (y * x**k).subs(x**p, L) == y * L**(k//p) * x**(k % p) assert (x**Rational(3, 2)).subs(x**S.Half, L) == x**Rational(3, 2) assert (x**S.Half).subs(x**S.Half, L) == L assert (x**Rational(-1, 2)).subs(x**S.Half, L) == x**Rational(-1, 2) assert (x**Rational(-1, 2)).subs(x**Rational(-1, 2), L) == L assert (x**(2*someint)).subs(x**someint, L) == L**2 assert (x**(2*someint + 3)).subs(x**someint, L) == L**2*x**3 assert (x**(3*someint + 3)).subs(x**someint, L) == L**3*x**3 assert (x**(3*someint)).subs(x**(2*someint), L) == L * x**someint assert (x**(4*someint)).subs(x**(2*someint), L) == L**2 assert (x**(4*someint + 1)).subs(x**(2*someint), L) == L**2 * x assert (x**(4*someint)).subs(x**(3*someint), L) == L * x**someint assert (x**(4*someint + 1)).subs(x**(3*someint), L) == L * x**(someint + 1) assert (x**(2*alpha)).subs(x**alpha, L) == x**(2*alpha) assert (x**(2*alpha + 2)).subs(x**2, L) == x**(2*alpha + 2) assert ((2*z)**alpha).subs(z**alpha, y) == (2*z)**alpha assert (x**(2*someint*alpha)).subs(x**someint, L) == x**(2*someint*alpha) assert (x**(2*someint + alpha)).subs(x**someint, L) == x**(2*someint + alpha) # This could in principle be substituted, but is not currently # because it requires recognizing that someint**2 is divisible by # someint. assert (x**(someint**2 + 3)).subs(x**someint, L) == x**(someint**2 + 3) # alpha**z := exp(log(alpha) z) is usually well-defined assert (4**z).subs(2**z, y) == y**2 # Negative powers assert (x**(-1)).subs(x**3, L) == x**(-1) assert (x**(-2)).subs(x**3, L) == x**(-2) assert (x**(-3)).subs(x**3, L) == L**(-1) assert (x**(-4)).subs(x**3, L) == L**(-1) * x**(-1) assert (x**(-5)).subs(x**3, L) == L**(-1) * x**(-2) assert (x**(-1)).subs(x**(-3), L) == x**(-1) assert (x**(-2)).subs(x**(-3), L) == x**(-2) assert (x**(-3)).subs(x**(-3), L) == L assert (x**(-4)).subs(x**(-3), L) == L * x**(-1) assert (x**(-5)).subs(x**(-3), L) == L * x**(-2) assert (x**1).subs(x**(-3), L) == x assert (x**2).subs(x**(-3), L) == x**2 assert (x**3).subs(x**(-3), L) == L**(-1) assert (x**4).subs(x**(-3), L) == L**(-1) * x assert (x**5).subs(x**(-3), L) == L**(-1) * x**2 def test_subs_basic_funcs(): a, b, c, d, K = symbols('a b c d K', commutative=True) w, x, y, z, L = symbols('w x y z L', commutative=False) assert (x + y).subs(x + y, L) == L assert (x - y).subs(x - y, L) == L assert (x/y).subs(x, L) == L/y assert (x**y).subs(x, L) == L**y assert (x**y).subs(y, L) == x**L assert ((a - c)/b).subs(b, K) == (a - c)/K assert (exp(x*y - z)).subs(x*y, L) == exp(L - z) assert (a*exp(x*y - w*z) + b*exp(x*y + w*z)).subs(z, 0) == \ a*exp(x*y) + b*exp(x*y) assert ((a - b)/(c*d - a*b)).subs(c*d - a*b, K) == (a - b)/K assert (w*exp(a*b - c)*x*y/4).subs(x*y, L) == w*exp(a*b - c)*L/4 def test_subs_wild(): R, S, T, U = symbols('R S T U', cls=Wild) assert (R*S).subs(R*S, T) == T assert (S*R).subs(R*S, T) == T assert (R + S).subs(R + S, T) == T assert (R**S).subs(R, T) == T**S assert (R**S).subs(S, T) == R**T assert (R*S**T).subs(R, U) == U*S**T assert (R*S**T).subs(S, U) == R*U**T assert (R*S**T).subs(T, U) == R*S**U def test_subs_mixed(): a, b, c, d, K = symbols('a b c d K', commutative=True) w, x, y, z, L = symbols('w x y z L', commutative=False) R, S, T, U = symbols('R S T U', cls=Wild) assert (a*x*y).subs(x*y, L) == a*L assert (a*b*x*y*x).subs(x*y, L) == a*b*L*x assert (R*x*y*exp(x*y)).subs(x*y, L) == R*L*exp(L) assert (a*x*y*y*x - x*y*z*exp(a*b)).subs(x*y, L) == a*L*y*x - L*z*exp(a*b) e = c*y*x*y*x**(R*S - a*b) - T*(a*R*b*S) assert e.subs(x*y, L).subs(a*b, K).subs(R*S, U) == \ c*y*L*x**(U - K) - T*(U*K) def test_division(): a, b, c = symbols('a b c', commutative=True) x, y, z = symbols('x y z', commutative=True) assert (1/a).subs(a, c) == 1/c assert (1/a**2).subs(a, c) == 1/c**2 assert (1/a**2).subs(a, -2) == Rational(1, 4) assert (-(1/a**2)).subs(a, -2) == Rational(-1, 4) assert (1/x).subs(x, z) == 1/z assert (1/x**2).subs(x, z) == 1/z**2 assert (1/x**2).subs(x, -2) == Rational(1, 4) assert (-(1/x**2)).subs(x, -2) == Rational(-1, 4) #issue 5360 assert (1/x).subs(x, 0) == 1/S.Zero def test_add(): a, b, c, d, x, y, t = symbols('a b c d x y t') assert (a**2 - b - c).subs(a**2 - b, d) in [d - c, a**2 - b - c] assert (a**2 - c).subs(a**2 - c, d) == d assert (a**2 - b - c).subs(a**2 - c, d) in [d - b, a**2 - b - c] assert (a**2 - x - c).subs(a**2 - c, d) in [d - x, a**2 - x - c] assert (a**2 - b - sqrt(a)).subs(a**2 - sqrt(a), c) == c - b assert (a + b + exp(a + b)).subs(a + b, c) == c + exp(c) assert (c + b + exp(c + b)).subs(c + b, a) == a + exp(a) assert (a + b + c + d).subs(b + c, x) == a + d + x assert (a + b + c + d).subs(-b - c, x) == a + d - x assert ((x + 1)*y).subs(x + 1, t) == t*y assert ((-x - 1)*y).subs(x + 1, t) == -t*y assert ((x - 1)*y).subs(x + 1, t) == y*(t - 2) assert ((-x + 1)*y).subs(x + 1, t) == y*(-t + 2) # this should work every time: e = a**2 - b - c assert e.subs(Add(*e.args[:2]), d) == d + e.args[2] assert e.subs(a**2 - c, d) == d - b # the fallback should recognize when a change has # been made; while .1 == Rational(1, 10) they are not the same # and the change should be made assert (0.1 + a).subs(0.1, Rational(1, 10)) == Rational(1, 10) + a e = (-x*(-y + 1) - y*(y - 1)) ans = (-x*(x) - y*(-x)).expand() assert e.subs(-y + 1, x) == ans #Test issue 18747 assert (exp(x) + cos(x)).subs(x, oo) == oo assert Add(*[AccumBounds(-1, 1), oo]) == oo assert Add(*[oo, AccumBounds(-1, 1)]) == oo def test_subs_issue_4009(): assert (I*Symbol('a')).subs(1, 2) == I*Symbol('a') def test_functions_subs(): f, g = symbols('f g', cls=Function) l = Lambda((x, y), sin(x) + y) assert (g(y, x) + cos(x)).subs(g, l) == sin(y) + x + cos(x) assert (f(x)**2).subs(f, sin) == sin(x)**2 assert (f(x, y)).subs(f, log) == log(x, y) assert (f(x, y)).subs(f, sin) == f(x, y) assert (sin(x) + atan2(x, y)).subs([[atan2, f], [sin, g]]) == \ f(x, y) + g(x) assert (g(f(x + y, x))).subs([[f, l], [g, exp]]) == exp(x + sin(x + y)) def test_derivative_subs(): f = Function('f') g = Function('g') assert Derivative(f(x), x).subs(f(x), y) != 0 # need xreplace to put the function back, see #13803 assert Derivative(f(x), x).subs(f(x), y).xreplace({y: f(x)}) == \ Derivative(f(x), x) # issues 5085, 5037 assert cse(Derivative(f(x), x) + f(x))[1][0].has(Derivative) assert cse(Derivative(f(x, y), x) + Derivative(f(x, y), y))[1][0].has(Derivative) eq = Derivative(g(x), g(x)) assert eq.subs(g, f) == Derivative(f(x), f(x)) assert eq.subs(g(x), f(x)) == Derivative(f(x), f(x)) assert eq.subs(g, cos) == Subs(Derivative(y, y), y, cos(x)) def test_derivative_subs2(): f_func, g_func = symbols('f g', cls=Function) f, g = f_func(x, y, z), g_func(x, y, z) assert Derivative(f, x, y).subs(Derivative(f, x, y), g) == g assert Derivative(f, y, x).subs(Derivative(f, x, y), g) == g assert Derivative(f, x, y).subs(Derivative(f, x), g) == Derivative(g, y) assert Derivative(f, x, y).subs(Derivative(f, y), g) == Derivative(g, x) assert (Derivative(f, x, y, z).subs( Derivative(f, x, z), g) == Derivative(g, y)) assert (Derivative(f, x, y, z).subs( Derivative(f, z, y), g) == Derivative(g, x)) assert (Derivative(f, x, y, z).subs( Derivative(f, z, y, x), g) == g) # Issue 9135 assert (Derivative(f, x, x, y).subs( Derivative(f, y, y), g) == Derivative(f, x, x, y)) assert (Derivative(f, x, y, y, z).subs( Derivative(f, x, y, y, y), g) == Derivative(f, x, y, y, z)) assert Derivative(f, x, y).subs(Derivative(f_func(x), x, y), g) == Derivative(f, x, y) def test_derivative_subs3(): dex = Derivative(exp(x), x) assert Derivative(dex, x).subs(dex, exp(x)) == dex assert dex.subs(exp(x), dex) == Derivative(exp(x), x, x) def test_issue_5284(): A, B = symbols('A B', commutative=False) assert (x*A).subs(x**2*A, B) == x*A assert (A**2).subs(A**3, B) == A**2 assert (A**6).subs(A**3, B) == B**2 def test_subs_iter(): assert x.subs(reversed([[x, y]])) == y it = iter([[x, y]]) assert x.subs(it) == y assert x.subs(Tuple((x, y))) == y def test_subs_dict(): a, b, c, d, e = symbols('a b c d e') assert (2*x + y + z).subs(dict(x=1, y=2)) == 4 + z l = [(sin(x), 2), (x, 1)] assert (sin(x)).subs(l) == \ (sin(x)).subs(dict(l)) == 2 assert sin(x).subs(reversed(l)) == sin(1) expr = sin(2*x) + sqrt(sin(2*x))*cos(2*x)*sin(exp(x)*x) reps = dict([ (sin(2*x), c), (sqrt(sin(2*x)), a), (cos(2*x), b), (exp(x), e), (x, d), ]) assert expr.subs(reps) == c + a*b*sin(d*e) l = [(x, 3), (y, x**2)] assert (x + y).subs(l) == 3 + x**2 assert (x + y).subs(reversed(l)) == 12 # If changes are made to convert lists into dictionaries and do # a dictionary-lookup replacement, these tests will help to catch # some logical errors that might occur l = [(y, z + 2), (1 + z, 5), (z, 2)] assert (y - 1 + 3*x).subs(l) == 5 + 3*x l = [(y, z + 2), (z, 3)] assert (y - 2).subs(l) == 3 def test_no_arith_subs_on_floats(): assert (x + 3).subs(x + 3, a) == a assert (x + 3).subs(x + 2, a) == a + 1 assert (x + y + 3).subs(x + 3, a) == a + y assert (x + y + 3).subs(x + 2, a) == a + y + 1 assert (x + 3.0).subs(x + 3.0, a) == a assert (x + 3.0).subs(x + 2.0, a) == x + 3.0 assert (x + y + 3.0).subs(x + 3.0, a) == a + y assert (x + y + 3.0).subs(x + 2.0, a) == x + y + 3.0 def test_issue_5651(): a, b, c, K = symbols('a b c K', commutative=True) assert (a/(b*c)).subs(b*c, K) == a/K assert (a/(b**2*c**3)).subs(b*c, K) == a/(c*K**2) assert (1/(x*y)).subs(x*y, 2) == S.Half assert ((1 + x*y)/(x*y)).subs(x*y, 1) == 2 assert (x*y*z).subs(x*y, 2) == 2*z assert ((1 + x*y)/(x*y)/z).subs(x*y, 1) == 2/z def test_issue_6075(): assert Tuple(1, True).subs(1, 2) == Tuple(2, True) def test_issue_6079(): # since x + 2.0 == x + 2 we can't do a simple equality test assert _aresame((x + 2.0).subs(2, 3), x + 2.0) assert _aresame((x + 2.0).subs(2.0, 3), x + 3) assert not _aresame(x + 2, x + 2.0) assert not _aresame(Basic(cos(x), S(1)), Basic(cos(x), S(1.))) assert _aresame(cos, cos) assert not _aresame(1, S.One) assert not _aresame(x, symbols('x', positive=True)) def test_issue_4680(): N = Symbol('N') assert N.subs(dict(N=3)) == 3 def test_issue_6158(): assert (x - 1).subs(1, y) == x - y assert (x - 1).subs(-1, y) == x + y assert (x - oo).subs(oo, y) == x - y assert (x - oo).subs(-oo, y) == x + y def test_Function_subs(): f, g, h, i = symbols('f g h i', cls=Function) p = Piecewise((g(f(x, y)), x < -1), (g(x), x <= 1)) assert p.subs(g, h) == Piecewise((h(f(x, y)), x < -1), (h(x), x <= 1)) assert (f(y) + g(x)).subs({f: h, g: i}) == i(x) + h(y) def test_simultaneous_subs(): reps = {x: 0, y: 0} assert (x/y).subs(reps) != (y/x).subs(reps) assert (x/y).subs(reps, simultaneous=True) == \ (y/x).subs(reps, simultaneous=True) reps = reps.items() assert (x/y).subs(reps) != (y/x).subs(reps) assert (x/y).subs(reps, simultaneous=True) == \ (y/x).subs(reps, simultaneous=True) assert Derivative(x, y, z).subs(reps, simultaneous=True) == \ Subs(Derivative(0, y, z), y, 0) def test_issue_6419_6421(): assert (1/(1 + x/y)).subs(x/y, x) == 1/(1 + x) assert (-2*I).subs(2*I, x) == -x assert (-I*x).subs(I*x, x) == -x assert (-3*I*y**4).subs(3*I*y**2, x) == -x*y**2 def test_issue_6559(): assert (-12*x + y).subs(-x, 1) == 12 + y # though this involves cse it generated a failure in Mul._eval_subs x0, x1 = symbols('x0 x1') e = -log(-12*sqrt(2) + 17)/24 - log(-2*sqrt(2) + 3)/12 + sqrt(2)/3 # XXX modify cse so x1 is eliminated and x0 = -sqrt(2)? assert cse(e) == ( [(x0, sqrt(2))], [x0/3 - log(-12*x0 + 17)/24 - log(-2*x0 + 3)/12]) def test_issue_5261(): x = symbols('x', real=True) e = I*x assert exp(e).subs(exp(x), y) == y**I assert (2**e).subs(2**x, y) == y**I eq = (-2)**e assert eq.subs((-2)**x, y) == eq def test_issue_6923(): assert (-2*x*sqrt(2)).subs(2*x, y) == -sqrt(2)*y def test_2arg_hack(): N = Symbol('N', commutative=False) ans = Mul(2, y + 1, evaluate=False) assert (2*x*(y + 1)).subs(x, 1, hack2=True) == ans assert (2*(y + 1 + N)).subs(N, 0, hack2=True) == ans @XFAIL def test_mul2(): """When this fails, remove things labelled "2-arg hack" 1) remove special handling in the fallback of subs that was added in the same commit as this test 2) remove the special handling in Mul.flatten """ assert (2*(x + 1)).is_Mul def test_noncommutative_subs(): x,y = symbols('x,y', commutative=False) assert (x*y*x).subs([(x, x*y), (y, x)], simultaneous=True) == (x*y*x**2*y) def test_issue_2877(): f = Float(2.0) assert (x + f).subs({f: 2}) == x + 2 def r(a, b, c): return factor(a*x**2 + b*x + c) e = r(5.0/6, 10, 5) assert nsimplify(e) == 5*x**2/6 + 10*x + 5 def test_issue_5910(): t = Symbol('t') assert (1/(1 - t)).subs(t, 1) is zoo n = t d = t - 1 assert (n/d).subs(t, 1) is zoo assert (-n/-d).subs(t, 1) is zoo def test_issue_5217(): s = Symbol('s') z = (1 - 2*x*x) w = (1 + 2*x*x) q = 2*x*x*2*y*y sub = {2*x*x: s} assert w.subs(sub) == 1 + s assert z.subs(sub) == 1 - s assert q == 4*x**2*y**2 assert q.subs(sub) == 2*y**2*s def test_issue_10829(): assert (4**x).subs(2**x, y) == y**2 assert (9**x).subs(3**x, y) == y**2 def test_pow_eval_subs_no_cache(): # Tests pull request 9376 is working from sympy.core.cache import clear_cache s = 1/sqrt(x**2) # This bug only appeared when the cache was turned off. # We need to approximate running this test without the cache. # This creates approximately the same situation. clear_cache() # This used to fail with a wrong result. # It incorrectly returned 1/sqrt(x**2) before this pull request. result = s.subs(sqrt(x**2), y) assert result == 1/y def test_RootOf_issue_10092(): x = Symbol('x', real=True) eq = x**3 - 17*x**2 + 81*x - 118 r = RootOf(eq, 0) assert (x < r).subs(x, r) is S.false def test_issue_8886(): from sympy.physics.mechanics import ReferenceFrame as R # if something can't be sympified we assume that it # doesn't play well with SymPy and disallow the # substitution v = R('A').x assert x.subs(x, v) == x assert v.subs(v, x) == v assert v.__eq__(x) is False def test_issue_12657(): # treat -oo like the atom that it is reps = [(-oo, 1), (oo, 2)] assert (x < -oo).subs(reps) == (x < 1) assert (x < -oo).subs(list(reversed(reps))) == (x < 1) reps = [(-oo, 2), (oo, 1)] assert (x < oo).subs(reps) == (x < 1) assert (x < oo).subs(list(reversed(reps))) == (x < 1) def test_recurse_Application_args(): F = Lambda((x, y), exp(2*x + 3*y)) f = Function('f') A = f(x, f(x, x)) C = F(x, F(x, x)) assert A.subs(f, F) == A.replace(f, F) == C def test_Subs_subs(): assert Subs(x*y, x, x).subs(x, y) == Subs(x*y, x, y) assert Subs(x*y, x, x + 1).subs(x, y) == \ Subs(x*y, x, y + 1) assert Subs(x*y, y, x + 1).subs(x, y) == \ Subs(y**2, y, y + 1) a = Subs(x*y*z, (y, x, z), (x + 1, x + z, x)) b = Subs(x*y*z, (y, x, z), (x + 1, y + z, y)) assert a.subs(x, y) == b and \ a.doit().subs(x, y) == a.subs(x, y).doit() f = Function('f') g = Function('g') assert Subs(2*f(x, y) + g(x), f(x, y), 1).subs(y, 2) == Subs( 2*f(x, y) + g(x), (f(x, y), y), (1, 2)) def test_issue_13333(): eq = 1/x assert eq.subs(dict(x='1/2')) == 2 assert eq.subs(dict(x='(1/2)')) == 2 def test_issue_15234(): x, y = symbols('x y', real=True) p = 6*x**5 + x**4 - 4*x**3 + 4*x**2 - 2*x + 3 p_subbed = 6*x**5 - 4*x**3 - 2*x + y**4 + 4*y**2 + 3 assert p.subs([(x**i, y**i) for i in [2, 4]]) == p_subbed x, y = symbols('x y', complex=True) p = 6*x**5 + x**4 - 4*x**3 + 4*x**2 - 2*x + 3 p_subbed = 6*x**5 - 4*x**3 - 2*x + y**4 + 4*y**2 + 3 assert p.subs([(x**i, y**i) for i in [2, 4]]) == p_subbed def test_issue_6976(): x, y = symbols('x y') assert (sqrt(x)**3 + sqrt(x) + x + x**2).subs(sqrt(x), y) == \ y**4 + y**3 + y**2 + y assert (x**4 + x**3 + x**2 + x + sqrt(x)).subs(x**2, y) == \ sqrt(x) + x**3 + x + y**2 + y assert x.subs(x**3, y) == x assert x.subs(x**Rational(1, 3), y) == y**3 # More substitutions are possible with nonnegative symbols x, y = symbols('x y', nonnegative=True) assert (x**4 + x**3 + x**2 + x + sqrt(x)).subs(x**2, y) == \ y**Rational(1, 4) + y**Rational(3, 2) + sqrt(y) + y**2 + y assert x.subs(x**3, y) == y**Rational(1, 3) def test_issue_11746(): assert (1/x).subs(x**2, 1) == 1/x assert (1/(x**3)).subs(x**2, 1) == x**(-3) assert (1/(x**4)).subs(x**2, 1) == 1 assert (1/(x**3)).subs(x**4, 1) == x**(-3) assert (1/(y**5)).subs(x**5, 1) == y**(-5) def test_issue_17823(): from sympy.physics.mechanics import dynamicsymbols q1, q2 = dynamicsymbols('q1, q2') expr = q1.diff().diff()**2*q1 + q1.diff()*q2.diff() reps={q1: a, q1.diff(): a*x*y, q1.diff().diff(): z} assert expr.subs(reps) == a*x*y*Derivative(q2, t) + a*z**2 def test_issue_19326(): x, y = [i(t) for i in map(Function, 'xy')] assert (x*y).subs({x: 1 + x, y: x}) == (1 + x)*x def test_issue_19558(): e = (7*x*cos(x) - 12*log(x)**3)*(-log(x)**4 + 2*sin(x) + 1)**2/ \ (2*(x*cos(x) - 2*log(x)**3)*(3*log(x)**4 - 7*sin(x) + 3)**2) assert e.subs(x, oo) == AccumBounds(-oo, oo) assert (sin(x) + cos(x)).subs(x, oo) == AccumBounds(-2, 2) def test_issue_22033(): xr = Symbol('xr', real=True) e = (1/xr) assert e.subs(xr**2, y) == e def test_guard_against_indeterminate_evaluation(): eq = x**y assert eq.subs([(x, 1), (y, oo)]) == 1 # because 1**y == 1 assert eq.subs([(y, oo), (x, 1)]) is S.NaN assert eq.subs({x: 1, y: oo}) is S.NaN assert eq.subs([(x, 1), (y, oo)], simultaneous=True) is S.NaN
e0570590bc92058184396fe1bff9e2424be673f51c8aa42df5a00866b96f7412
from sympy.assumptions.refine import refine from sympy.concrete.summations import Sum from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.containers import Tuple from sympy.core.expr import (ExprBuilder, unchanged, Expr, UnevaluatedExpr) from sympy.core.function import (Function, expand, WildFunction, AppliedUndef, Derivative, diff) from sympy.core.mul import Mul from sympy.core.numbers import (NumberSymbol, E, zoo, oo, Float, I, Rational, nan, Integer, Number, pi) from sympy.core.power import Pow from sympy.core.relational import Ge, Lt, Gt, Le from sympy.core.singleton import S from sympy.core.sorting import default_sort_key from sympy.core.symbol import Symbol, symbols, Dummy, Wild from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.exponential import exp_polar, exp, log from sympy.functions.elementary.miscellaneous import sqrt, Max from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import tan, sin, cos from sympy.functions.special.delta_functions import (Heaviside, DiracDelta) from sympy.functions.special.error_functions import Si from sympy.functions.special.gamma_functions import gamma from sympy.integrals.integrals import integrate, Integral from sympy.physics.secondquant import FockState from sympy.polys.partfrac import apart from sympy.polys.polytools import factor, cancel, Poly from sympy.polys.rationaltools import together from sympy.series.order import O from sympy.simplify.combsimp import combsimp from sympy.simplify.gammasimp import gammasimp from sympy.simplify.powsimp import powsimp from sympy.simplify.radsimp import collect, radsimp from sympy.simplify.ratsimp import ratsimp from sympy.simplify.simplify import simplify, nsimplify from sympy.simplify.trigsimp import trigsimp from sympy.physics.units import meter from sympy.testing.pytest import raises, XFAIL from sympy.abc import a, b, c, n, t, u, x, y, z f, g, h = symbols('f,g,h', cls=Function) class DummyNumber: """ Minimal implementation of a number that works with SymPy. If one has a Number class (e.g. Sage Integer, or some other custom class) that one wants to work well with SymPy, one has to implement at least the methods of this class DummyNumber, resp. its subclasses I5 and F1_1. Basically, one just needs to implement either __int__() or __float__() and then one needs to make sure that the class works with Python integers and with itself. """ def __radd__(self, a): if isinstance(a, (int, float)): return a + self.number return NotImplemented def __add__(self, a): if isinstance(a, (int, float, DummyNumber)): return self.number + a return NotImplemented def __rsub__(self, a): if isinstance(a, (int, float)): return a - self.number return NotImplemented def __sub__(self, a): if isinstance(a, (int, float, DummyNumber)): return self.number - a return NotImplemented def __rmul__(self, a): if isinstance(a, (int, float)): return a * self.number return NotImplemented def __mul__(self, a): if isinstance(a, (int, float, DummyNumber)): return self.number * a return NotImplemented def __rtruediv__(self, a): if isinstance(a, (int, float)): return a / self.number return NotImplemented def __truediv__(self, a): if isinstance(a, (int, float, DummyNumber)): return self.number / a return NotImplemented def __rpow__(self, a): if isinstance(a, (int, float)): return a ** self.number return NotImplemented def __pow__(self, a): if isinstance(a, (int, float, DummyNumber)): return self.number ** a return NotImplemented def __pos__(self): return self.number def __neg__(self): return - self.number class I5(DummyNumber): number = 5 def __int__(self): return self.number class F1_1(DummyNumber): number = 1.1 def __float__(self): return self.number i5 = I5() f1_1 = F1_1() # basic SymPy objects basic_objs = [ Rational(2), Float("1.3"), x, y, pow(x, y)*y, ] # all supported objects all_objs = basic_objs + [ 5, 5.5, i5, f1_1 ] def dotest(s): for xo in all_objs: for yo in all_objs: s(xo, yo) return True def test_basic(): def j(a, b): x = a x = +a x = -a x = a + b x = a - b x = a*b x = a/b x = a**b del x assert dotest(j) def test_ibasic(): def s(a, b): x = a x += b x = a x -= b x = a x *= b x = a x /= b assert dotest(s) class NonBasic: '''This class represents an object that knows how to implement binary operations like +, -, etc with Expr but is not a subclass of Basic itself. The NonExpr subclass below does subclass Basic but not Expr. For both NonBasic and NonExpr it should be possible for them to override Expr.__add__ etc because Expr.__add__ should be returning NotImplemented for non Expr classes. Otherwise Expr.__add__ would create meaningless objects like Add(Integer(1), FiniteSet(2)) and it wouldn't be possible for other classes to override these operations when interacting with Expr. ''' def __add__(self, other): return SpecialOp('+', self, other) def __radd__(self, other): return SpecialOp('+', other, self) def __sub__(self, other): return SpecialOp('-', self, other) def __rsub__(self, other): return SpecialOp('-', other, self) def __mul__(self, other): return SpecialOp('*', self, other) def __rmul__(self, other): return SpecialOp('*', other, self) def __truediv__(self, other): return SpecialOp('/', self, other) def __rtruediv__(self, other): return SpecialOp('/', other, self) def __floordiv__(self, other): return SpecialOp('//', self, other) def __rfloordiv__(self, other): return SpecialOp('//', other, self) def __mod__(self, other): return SpecialOp('%', self, other) def __rmod__(self, other): return SpecialOp('%', other, self) def __divmod__(self, other): return SpecialOp('divmod', self, other) def __rdivmod__(self, other): return SpecialOp('divmod', other, self) def __pow__(self, other): return SpecialOp('**', self, other) def __rpow__(self, other): return SpecialOp('**', other, self) def __lt__(self, other): return SpecialOp('<', self, other) def __gt__(self, other): return SpecialOp('>', self, other) def __le__(self, other): return SpecialOp('<=', self, other) def __ge__(self, other): return SpecialOp('>=', self, other) class NonExpr(Basic, NonBasic): '''Like NonBasic above except this is a subclass of Basic but not Expr''' pass class SpecialOp(): '''Represents the results of operations with NonBasic and NonExpr''' def __new__(cls, op, arg1, arg2): obj = object.__new__(cls) obj.args = (op, arg1, arg2) return obj class NonArithmetic(Basic): '''Represents a Basic subclass that does not support arithmetic operations''' pass def test_cooperative_operations(): '''Tests that Expr uses binary operations cooperatively. In particular it should be possible for non-Expr classes to override binary operators like +, - etc when used with Expr instances. This should work for non-Expr classes whether they are Basic subclasses or not. Also non-Expr classes that do not define binary operators with Expr should give TypeError. ''' # A bunch of instances of Expr subclasses exprs = [ Expr(), S.Zero, S.One, S.Infinity, S.NegativeInfinity, S.ComplexInfinity, S.Half, Float(0.5), Integer(2), Symbol('x'), Mul(2, Symbol('x')), Add(2, Symbol('x')), Pow(2, Symbol('x')), ] for e in exprs: # Test that these classes can override arithmetic operations in # combination with various Expr types. for ne in [NonBasic(), NonExpr()]: results = [ (ne + e, ('+', ne, e)), (e + ne, ('+', e, ne)), (ne - e, ('-', ne, e)), (e - ne, ('-', e, ne)), (ne * e, ('*', ne, e)), (e * ne, ('*', e, ne)), (ne / e, ('/', ne, e)), (e / ne, ('/', e, ne)), (ne // e, ('//', ne, e)), (e // ne, ('//', e, ne)), (ne % e, ('%', ne, e)), (e % ne, ('%', e, ne)), (divmod(ne, e), ('divmod', ne, e)), (divmod(e, ne), ('divmod', e, ne)), (ne ** e, ('**', ne, e)), (e ** ne, ('**', e, ne)), (e < ne, ('>', ne, e)), (ne < e, ('<', ne, e)), (e > ne, ('<', ne, e)), (ne > e, ('>', ne, e)), (e <= ne, ('>=', ne, e)), (ne <= e, ('<=', ne, e)), (e >= ne, ('<=', ne, e)), (ne >= e, ('>=', ne, e)), ] for res, args in results: assert type(res) is SpecialOp and res.args == args # These classes do not support binary operators with Expr. Every # operation should raise in combination with any of the Expr types. for na in [NonArithmetic(), object()]: raises(TypeError, lambda : e + na) raises(TypeError, lambda : na + e) raises(TypeError, lambda : e - na) raises(TypeError, lambda : na - e) raises(TypeError, lambda : e * na) raises(TypeError, lambda : na * e) raises(TypeError, lambda : e / na) raises(TypeError, lambda : na / e) raises(TypeError, lambda : e // na) raises(TypeError, lambda : na // e) raises(TypeError, lambda : e % na) raises(TypeError, lambda : na % e) raises(TypeError, lambda : divmod(e, na)) raises(TypeError, lambda : divmod(na, e)) raises(TypeError, lambda : e ** na) raises(TypeError, lambda : na ** e) raises(TypeError, lambda : e > na) raises(TypeError, lambda : na > e) raises(TypeError, lambda : e < na) raises(TypeError, lambda : na < e) raises(TypeError, lambda : e >= na) raises(TypeError, lambda : na >= e) raises(TypeError, lambda : e <= na) raises(TypeError, lambda : na <= e) def test_relational(): from sympy.core.relational import Lt assert (pi < 3) is S.false assert (pi <= 3) is S.false assert (pi > 3) is S.true assert (pi >= 3) is S.true assert (-pi < 3) is S.true assert (-pi <= 3) is S.true assert (-pi > 3) is S.false assert (-pi >= 3) is S.false r = Symbol('r', real=True) assert (r - 2 < r - 3) is S.false assert Lt(x + I, x + I + 2).func == Lt # issue 8288 def test_relational_assumptions(): m1 = Symbol("m1", nonnegative=False) m2 = Symbol("m2", positive=False) m3 = Symbol("m3", nonpositive=False) m4 = Symbol("m4", negative=False) assert (m1 < 0) == Lt(m1, 0) assert (m2 <= 0) == Le(m2, 0) assert (m3 > 0) == Gt(m3, 0) assert (m4 >= 0) == Ge(m4, 0) m1 = Symbol("m1", nonnegative=False, real=True) m2 = Symbol("m2", positive=False, real=True) m3 = Symbol("m3", nonpositive=False, real=True) m4 = Symbol("m4", negative=False, real=True) assert (m1 < 0) is S.true assert (m2 <= 0) is S.true assert (m3 > 0) is S.true assert (m4 >= 0) is S.true m1 = Symbol("m1", negative=True) m2 = Symbol("m2", nonpositive=True) m3 = Symbol("m3", positive=True) m4 = Symbol("m4", nonnegative=True) assert (m1 < 0) is S.true assert (m2 <= 0) is S.true assert (m3 > 0) is S.true assert (m4 >= 0) is S.true m1 = Symbol("m1", negative=False, real=True) m2 = Symbol("m2", nonpositive=False, real=True) m3 = Symbol("m3", positive=False, real=True) m4 = Symbol("m4", nonnegative=False, real=True) assert (m1 < 0) is S.false assert (m2 <= 0) is S.false assert (m3 > 0) is S.false assert (m4 >= 0) is S.false # See https://github.com/sympy/sympy/issues/17708 #def test_relational_noncommutative(): # from sympy import Lt, Gt, Le, Ge # A, B = symbols('A,B', commutative=False) # assert (A < B) == Lt(A, B) # assert (A <= B) == Le(A, B) # assert (A > B) == Gt(A, B) # assert (A >= B) == Ge(A, B) def test_basic_nostr(): for obj in basic_objs: raises(TypeError, lambda: obj + '1') raises(TypeError, lambda: obj - '1') if obj == 2: assert obj * '1' == '11' else: raises(TypeError, lambda: obj * '1') raises(TypeError, lambda: obj / '1') raises(TypeError, lambda: obj ** '1') def test_series_expansion_for_uniform_order(): assert (1/x + y + x).series(x, 0, 0) == 1/x + O(1, x) assert (1/x + y + x).series(x, 0, 1) == 1/x + y + O(x) assert (1/x + 1 + x).series(x, 0, 0) == 1/x + O(1, x) assert (1/x + 1 + x).series(x, 0, 1) == 1/x + 1 + O(x) assert (1/x + x).series(x, 0, 0) == 1/x + O(1, x) assert (1/x + y + y*x + x).series(x, 0, 0) == 1/x + O(1, x) assert (1/x + y + y*x + x).series(x, 0, 1) == 1/x + y + O(x) def test_leadterm(): assert (3 + 2*x**(log(3)/log(2) - 1)).leadterm(x) == (3, 0) assert (1/x**2 + 1 + x + x**2).leadterm(x)[1] == -2 assert (1/x + 1 + x + x**2).leadterm(x)[1] == -1 assert (x**2 + 1/x).leadterm(x)[1] == -1 assert (1 + x**2).leadterm(x)[1] == 0 assert (x + 1).leadterm(x)[1] == 0 assert (x + x**2).leadterm(x)[1] == 1 assert (x**2).leadterm(x)[1] == 2 def test_as_leading_term(): assert (3 + 2*x**(log(3)/log(2) - 1)).as_leading_term(x) == 3 assert (1/x**2 + 1 + x + x**2).as_leading_term(x) == 1/x**2 assert (1/x + 1 + x + x**2).as_leading_term(x) == 1/x assert (x**2 + 1/x).as_leading_term(x) == 1/x assert (1 + x**2).as_leading_term(x) == 1 assert (x + 1).as_leading_term(x) == 1 assert (x + x**2).as_leading_term(x) == x assert (x**2).as_leading_term(x) == x**2 assert (x + oo).as_leading_term(x) is oo raises(ValueError, lambda: (x + 1).as_leading_term(1)) # https://github.com/sympy/sympy/issues/21177 e = -3*x + (x + Rational(3, 2) - sqrt(3)*S.ImaginaryUnit/2)**2\ - Rational(3, 2) + 3*sqrt(3)*S.ImaginaryUnit/2 assert e.as_leading_term(x) == \ (12*sqrt(3)*x - 12*S.ImaginaryUnit*x)/(4*sqrt(3) + 12*S.ImaginaryUnit) # https://github.com/sympy/sympy/issues/21245 e = 1 - x - x**2 d = (1 + sqrt(5))/2 assert e.subs(x, y + 1/d).as_leading_term(y) == \ (-576*sqrt(5)*y - 1280*y)/(256*sqrt(5) + 576) def test_leadterm2(): assert (x*cos(1)*cos(1 + sin(1)) + sin(1 + sin(1))).leadterm(x) == \ (sin(1 + sin(1)), 0) def test_leadterm3(): assert (y + z + x).leadterm(x) == (y + z, 0) def test_as_leading_term2(): assert (x*cos(1)*cos(1 + sin(1)) + sin(1 + sin(1))).as_leading_term(x) == \ sin(1 + sin(1)) def test_as_leading_term3(): assert (2 + pi + x).as_leading_term(x) == 2 + pi assert (2*x + pi*x + x**2).as_leading_term(x) == 2*x + pi*x def test_as_leading_term4(): # see issue 6843 n = Symbol('n', integer=True, positive=True) r = -n**3/(2*n**2 + 4*n + 2) - n**2/(n**2 + 2*n + 1) + \ n**2/(n + 1) - n/(2*n**2 + 4*n + 2) + n/(n*x + x) + 2*n/(n + 1) - \ 1 + 1/(n*x + x) + 1/(n + 1) - 1/x assert r.as_leading_term(x).cancel() == n/2 def test_as_leading_term_stub(): class foo(Function): pass assert foo(1/x).as_leading_term(x) == foo(1/x) assert foo(1).as_leading_term(x) == foo(1) raises(NotImplementedError, lambda: foo(x).as_leading_term(x)) def test_as_leading_term_deriv_integral(): # related to issue 11313 assert Derivative(x ** 3, x).as_leading_term(x) == 3*x**2 assert Derivative(x ** 3, y).as_leading_term(x) == 0 assert Integral(x ** 3, x).as_leading_term(x) == x**4/4 assert Integral(x ** 3, y).as_leading_term(x) == y*x**3 assert Derivative(exp(x), x).as_leading_term(x) == 1 assert Derivative(log(x), x).as_leading_term(x) == (1/x).as_leading_term(x) def test_atoms(): assert x.atoms() == {x} assert (1 + x).atoms() == {x, S.One} assert (1 + 2*cos(x)).atoms(Symbol) == {x} assert (1 + 2*cos(x)).atoms(Symbol, Number) == {S.One, S(2), x} assert (2*(x**(y**x))).atoms() == {S(2), x, y} assert S.Half.atoms() == {S.Half} assert S.Half.atoms(Symbol) == set() assert sin(oo).atoms(oo) == set() assert Poly(0, x).atoms() == {S.Zero, x} assert Poly(1, x).atoms() == {S.One, x} assert Poly(x, x).atoms() == {x} assert Poly(x, x, y).atoms() == {x, y} assert Poly(x + y, x, y).atoms() == {x, y} assert Poly(x + y, x, y, z).atoms() == {x, y, z} assert Poly(x + y*t, x, y, z).atoms() == {t, x, y, z} assert (I*pi).atoms(NumberSymbol) == {pi} assert (I*pi).atoms(NumberSymbol, I) == \ (I*pi).atoms(I, NumberSymbol) == {pi, I} assert exp(exp(x)).atoms(exp) == {exp(exp(x)), exp(x)} assert (1 + x*(2 + y) + exp(3 + z)).atoms(Add) == \ {1 + x*(2 + y) + exp(3 + z), 2 + y, 3 + z} # issue 6132 e = (f(x) + sin(x) + 2) assert e.atoms(AppliedUndef) == \ {f(x)} assert e.atoms(AppliedUndef, Function) == \ {f(x), sin(x)} assert e.atoms(Function) == \ {f(x), sin(x)} assert e.atoms(AppliedUndef, Number) == \ {f(x), S(2)} assert e.atoms(Function, Number) == \ {S(2), sin(x), f(x)} def test_is_polynomial(): k = Symbol('k', nonnegative=True, integer=True) assert Rational(2).is_polynomial(x, y, z) is True assert (S.Pi).is_polynomial(x, y, z) is True assert x.is_polynomial(x) is True assert x.is_polynomial(y) is True assert (x**2).is_polynomial(x) is True assert (x**2).is_polynomial(y) is True assert (x**(-2)).is_polynomial(x) is False assert (x**(-2)).is_polynomial(y) is True assert (2**x).is_polynomial(x) is False assert (2**x).is_polynomial(y) is True assert (x**k).is_polynomial(x) is False assert (x**k).is_polynomial(k) is False assert (x**x).is_polynomial(x) is False assert (k**k).is_polynomial(k) is False assert (k**x).is_polynomial(k) is False assert (x**(-k)).is_polynomial(x) is False assert ((2*x)**k).is_polynomial(x) is False assert (x**2 + 3*x - 8).is_polynomial(x) is True assert (x**2 + 3*x - 8).is_polynomial(y) is True assert (x**2 + 3*x - 8).is_polynomial() is True assert sqrt(x).is_polynomial(x) is False assert (sqrt(x)**3).is_polynomial(x) is False assert (x**2 + 3*x*sqrt(y) - 8).is_polynomial(x) is True assert (x**2 + 3*x*sqrt(y) - 8).is_polynomial(y) is False assert ((x**2)*(y**2) + x*(y**2) + y*x + exp(2)).is_polynomial() is True assert ((x**2)*(y**2) + x*(y**2) + y*x + exp(x)).is_polynomial() is False assert ( (x**2)*(y**2) + x*(y**2) + y*x + exp(2)).is_polynomial(x, y) is True assert ( (x**2)*(y**2) + x*(y**2) + y*x + exp(x)).is_polynomial(x, y) is False assert (1/f(x) + 1).is_polynomial(f(x)) is False def test_is_rational_function(): assert Integer(1).is_rational_function() is True assert Integer(1).is_rational_function(x) is True assert Rational(17, 54).is_rational_function() is True assert Rational(17, 54).is_rational_function(x) is True assert (12/x).is_rational_function() is True assert (12/x).is_rational_function(x) is True assert (x/y).is_rational_function() is True assert (x/y).is_rational_function(x) is True assert (x/y).is_rational_function(x, y) is True assert (x**2 + 1/x/y).is_rational_function() is True assert (x**2 + 1/x/y).is_rational_function(x) is True assert (x**2 + 1/x/y).is_rational_function(x, y) is True assert (sin(y)/x).is_rational_function() is False assert (sin(y)/x).is_rational_function(y) is False assert (sin(y)/x).is_rational_function(x) is True assert (sin(y)/x).is_rational_function(x, y) is False assert (S.NaN).is_rational_function() is False assert (S.Infinity).is_rational_function() is False assert (S.NegativeInfinity).is_rational_function() is False assert (S.ComplexInfinity).is_rational_function() is False def test_is_meromorphic(): f = a/x**2 + b + x + c*x**2 assert f.is_meromorphic(x, 0) is True assert f.is_meromorphic(x, 1) is True assert f.is_meromorphic(x, zoo) is True g = 3 + 2*x**(log(3)/log(2) - 1) assert g.is_meromorphic(x, 0) is False assert g.is_meromorphic(x, 1) is True assert g.is_meromorphic(x, zoo) is False n = Symbol('n', integer=True) e = sin(1/x)**n*x assert e.is_meromorphic(x, 0) is False assert e.is_meromorphic(x, 1) is True assert e.is_meromorphic(x, zoo) is False e = log(x)**pi assert e.is_meromorphic(x, 0) is False assert e.is_meromorphic(x, 1) is False assert e.is_meromorphic(x, 2) is True assert e.is_meromorphic(x, zoo) is False assert (log(x)**a).is_meromorphic(x, 0) is False assert (log(x)**a).is_meromorphic(x, 1) is False assert (a**log(x)).is_meromorphic(x, 0) is None assert (3**log(x)).is_meromorphic(x, 0) is False assert (3**log(x)).is_meromorphic(x, 1) is True def test_is_algebraic_expr(): assert sqrt(3).is_algebraic_expr(x) is True assert sqrt(3).is_algebraic_expr() is True eq = ((1 + x**2)/(1 - y**2))**(S.One/3) assert eq.is_algebraic_expr(x) is True assert eq.is_algebraic_expr(y) is True assert (sqrt(x) + y**(S(2)/3)).is_algebraic_expr(x) is True assert (sqrt(x) + y**(S(2)/3)).is_algebraic_expr(y) is True assert (sqrt(x) + y**(S(2)/3)).is_algebraic_expr() is True assert (cos(y)/sqrt(x)).is_algebraic_expr() is False assert (cos(y)/sqrt(x)).is_algebraic_expr(x) is True assert (cos(y)/sqrt(x)).is_algebraic_expr(y) is False assert (cos(y)/sqrt(x)).is_algebraic_expr(x, y) is False def test_SAGE1(): #see https://github.com/sympy/sympy/issues/3346 class MyInt: def _sympy_(self): return Integer(5) m = MyInt() e = Rational(2)*m assert e == 10 raises(TypeError, lambda: Rational(2)*MyInt) def test_SAGE2(): class MyInt: def __int__(self): return 5 assert sympify(MyInt()) == 5 e = Rational(2)*MyInt() assert e == 10 raises(TypeError, lambda: Rational(2)*MyInt) def test_SAGE3(): class MySymbol: def __rmul__(self, other): return ('mys', other, self) o = MySymbol() e = x*o assert e == ('mys', x, o) def test_len(): e = x*y assert len(e.args) == 2 e = x + y + z assert len(e.args) == 3 def test_doit(): a = Integral(x**2, x) assert isinstance(a.doit(), Integral) is False assert isinstance(a.doit(integrals=True), Integral) is False assert isinstance(a.doit(integrals=False), Integral) is True assert (2*Integral(x, x)).doit() == x**2 def test_attribute_error(): raises(AttributeError, lambda: x.cos()) raises(AttributeError, lambda: x.sin()) raises(AttributeError, lambda: x.exp()) def test_args(): assert (x*y).args in ((x, y), (y, x)) assert (x + y).args in ((x, y), (y, x)) assert (x*y + 1).args in ((x*y, 1), (1, x*y)) assert sin(x*y).args == (x*y,) assert sin(x*y).args[0] == x*y assert (x**y).args == (x, y) assert (x**y).args[0] == x assert (x**y).args[1] == y def test_noncommutative_expand_issue_3757(): A, B, C = symbols('A,B,C', commutative=False) assert A*B - B*A != 0 assert (A*(A + B)*B).expand() == A**2*B + A*B**2 assert (A*(A + B + C)*B).expand() == A**2*B + A*B**2 + A*C*B def test_as_numer_denom(): a, b, c = symbols('a, b, c') assert nan.as_numer_denom() == (nan, 1) assert oo.as_numer_denom() == (oo, 1) assert (-oo).as_numer_denom() == (-oo, 1) assert zoo.as_numer_denom() == (zoo, 1) assert (-zoo).as_numer_denom() == (zoo, 1) assert x.as_numer_denom() == (x, 1) assert (1/x).as_numer_denom() == (1, x) assert (x/y).as_numer_denom() == (x, y) assert (x/2).as_numer_denom() == (x, 2) assert (x*y/z).as_numer_denom() == (x*y, z) assert (x/(y*z)).as_numer_denom() == (x, y*z) assert S.Half.as_numer_denom() == (1, 2) assert (1/y**2).as_numer_denom() == (1, y**2) assert (x/y**2).as_numer_denom() == (x, y**2) assert ((x**2 + 1)/y).as_numer_denom() == (x**2 + 1, y) assert (x*(y + 1)/y**7).as_numer_denom() == (x*(y + 1), y**7) assert (x**-2).as_numer_denom() == (1, x**2) assert (a/x + b/2/x + c/3/x).as_numer_denom() == \ (6*a + 3*b + 2*c, 6*x) assert (a/x + b/2/x + c/3/y).as_numer_denom() == \ (2*c*x + y*(6*a + 3*b), 6*x*y) assert (a/x + b/2/x + c/.5/x).as_numer_denom() == \ (2*a + b + 4.0*c, 2*x) # this should take no more than a few seconds assert int(log(Add(*[Dummy()/i/x for i in range(1, 705)] ).as_numer_denom()[1]/x).n(4)) == 705 for i in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]: assert (i + x/3).as_numer_denom() == \ (x + i, 3) assert (S.Infinity + x/3 + y/4).as_numer_denom() == \ (4*x + 3*y + S.Infinity, 12) assert (oo*x + zoo*y).as_numer_denom() == \ (zoo*y + oo*x, 1) A, B, C = symbols('A,B,C', commutative=False) assert (A*B*C**-1).as_numer_denom() == (A*B*C**-1, 1) assert (A*B*C**-1/x).as_numer_denom() == (A*B*C**-1, x) assert (C**-1*A*B).as_numer_denom() == (C**-1*A*B, 1) assert (C**-1*A*B/x).as_numer_denom() == (C**-1*A*B, x) assert ((A*B*C)**-1).as_numer_denom() == ((A*B*C)**-1, 1) assert ((A*B*C)**-1/x).as_numer_denom() == ((A*B*C)**-1, x) def test_trunc(): import math x, y = symbols('x y') assert math.trunc(2) == 2 assert math.trunc(4.57) == 4 assert math.trunc(-5.79) == -5 assert math.trunc(pi) == 3 assert math.trunc(log(7)) == 1 assert math.trunc(exp(5)) == 148 assert math.trunc(cos(pi)) == -1 assert math.trunc(sin(5)) == 0 raises(TypeError, lambda: math.trunc(x)) raises(TypeError, lambda: math.trunc(x + y**2)) raises(TypeError, lambda: math.trunc(oo)) def test_as_independent(): assert S.Zero.as_independent(x, as_Add=True) == (0, 0) assert S.Zero.as_independent(x, as_Add=False) == (0, 0) assert (2*x*sin(x) + y + x).as_independent(x) == (y, x + 2*x*sin(x)) assert (2*x*sin(x) + y + x).as_independent(y) == (x + 2*x*sin(x), y) assert (2*x*sin(x) + y + x).as_independent(x, y) == (0, y + x + 2*x*sin(x)) assert (x*sin(x)*cos(y)).as_independent(x) == (cos(y), x*sin(x)) assert (x*sin(x)*cos(y)).as_independent(y) == (x*sin(x), cos(y)) assert (x*sin(x)*cos(y)).as_independent(x, y) == (1, x*sin(x)*cos(y)) assert (sin(x)).as_independent(x) == (1, sin(x)) assert (sin(x)).as_independent(y) == (sin(x), 1) assert (2*sin(x)).as_independent(x) == (2, sin(x)) assert (2*sin(x)).as_independent(y) == (2*sin(x), 1) # issue 4903 = 1766b n1, n2, n3 = symbols('n1 n2 n3', commutative=False) assert (n1 + n1*n2).as_independent(n2) == (n1, n1*n2) assert (n2*n1 + n1*n2).as_independent(n2) == (0, n1*n2 + n2*n1) assert (n1*n2*n1).as_independent(n2) == (n1, n2*n1) assert (n1*n2*n1).as_independent(n1) == (1, n1*n2*n1) assert (3*x).as_independent(x, as_Add=True) == (0, 3*x) assert (3*x).as_independent(x, as_Add=False) == (3, x) assert (3 + x).as_independent(x, as_Add=True) == (3, x) assert (3 + x).as_independent(x, as_Add=False) == (1, 3 + x) # issue 5479 assert (3*x).as_independent(Symbol) == (3, x) # issue 5648 assert (n1*x*y).as_independent(x) == (n1*y, x) assert ((x + n1)*(x - y)).as_independent(x) == (1, (x + n1)*(x - y)) assert ((x + n1)*(x - y)).as_independent(y) == (x + n1, x - y) assert (DiracDelta(x - n1)*DiracDelta(x - y)).as_independent(x) \ == (1, DiracDelta(x - n1)*DiracDelta(x - y)) assert (x*y*n1*n2*n3).as_independent(n2) == (x*y*n1, n2*n3) assert (x*y*n1*n2*n3).as_independent(n1) == (x*y, n1*n2*n3) assert (x*y*n1*n2*n3).as_independent(n3) == (x*y*n1*n2, n3) assert (DiracDelta(x - n1)*DiracDelta(y - n1)*DiracDelta(x - n2)).as_independent(y) == \ (DiracDelta(x - n1)*DiracDelta(x - n2), DiracDelta(y - n1)) # issue 5784 assert (x + Integral(x, (x, 1, 2))).as_independent(x, strict=True) == \ (Integral(x, (x, 1, 2)), x) eq = Add(x, -x, 2, -3, evaluate=False) assert eq.as_independent(x) == (-1, Add(x, -x, evaluate=False)) eq = Mul(x, 1/x, 2, -3, evaluate=False) assert eq.as_independent(x) == (-6, Mul(x, 1/x, evaluate=False)) assert (x*y).as_independent(z, as_Add=True) == (x*y, 0) @XFAIL def test_call_2(): # TODO UndefinedFunction does not subclass Expr assert (2*f)(x) == 2*f(x) def test_replace(): e = log(sin(x)) + tan(sin(x**2)) assert e.replace(sin, cos) == log(cos(x)) + tan(cos(x**2)) assert e.replace( sin, lambda a: sin(2*a)) == log(sin(2*x)) + tan(sin(2*x**2)) a = Wild('a') b = Wild('b') assert e.replace(sin(a), cos(a)) == log(cos(x)) + tan(cos(x**2)) assert e.replace( sin(a), lambda a: sin(2*a)) == log(sin(2*x)) + tan(sin(2*x**2)) # test exact assert (2*x).replace(a*x + b, b - a, exact=True) == 2*x assert (2*x).replace(a*x + b, b - a) == 2*x assert (2*x).replace(a*x + b, b - a, exact=False) == 2/x assert (2*x).replace(a*x + b, lambda a, b: b - a, exact=True) == 2*x assert (2*x).replace(a*x + b, lambda a, b: b - a) == 2*x assert (2*x).replace(a*x + b, lambda a, b: b - a, exact=False) == 2/x g = 2*sin(x**3) assert g.replace( lambda expr: expr.is_Number, lambda expr: expr**2) == 4*sin(x**9) assert cos(x).replace(cos, sin, map=True) == (sin(x), {cos(x): sin(x)}) assert sin(x).replace(cos, sin) == sin(x) cond, func = lambda x: x.is_Mul, lambda x: 2*x assert (x*y).replace(cond, func, map=True) == (2*x*y, {x*y: 2*x*y}) assert (x*(1 + x*y)).replace(cond, func, map=True) == \ (2*x*(2*x*y + 1), {x*(2*x*y + 1): 2*x*(2*x*y + 1), x*y: 2*x*y}) assert (y*sin(x)).replace(sin, lambda expr: sin(expr)/y, map=True) == \ (sin(x), {sin(x): sin(x)/y}) # if not simultaneous then y*sin(x) -> y*sin(x)/y = sin(x) -> sin(x)/y assert (y*sin(x)).replace(sin, lambda expr: sin(expr)/y, simultaneous=False) == sin(x)/y assert (x**2 + O(x**3)).replace(Pow, lambda b, e: b**e/e ) == x**2/2 + O(x**3) assert (x**2 + O(x**3)).replace(Pow, lambda b, e: b**e/e, simultaneous=False) == x**2/2 + O(x**3) assert (x*(x*y + 3)).replace(lambda x: x.is_Mul, lambda x: 2 + x) == \ x*(x*y + 5) + 2 e = (x*y + 1)*(2*x*y + 1) + 1 assert e.replace(cond, func, map=True) == ( 2*((2*x*y + 1)*(4*x*y + 1)) + 1, {2*x*y: 4*x*y, x*y: 2*x*y, (2*x*y + 1)*(4*x*y + 1): 2*((2*x*y + 1)*(4*x*y + 1))}) assert x.replace(x, y) == y assert (x + 1).replace(1, 2) == x + 2 # https://groups.google.com/forum/#!topic/sympy/8wCgeC95tz0 n1, n2, n3 = symbols('n1:4', commutative=False) assert (n1*f(n2)).replace(f, lambda x: x) == n1*n2 assert (n3*f(n2)).replace(f, lambda x: x) == n3*n2 # issue 16725 assert S.Zero.replace(Wild('x'), 1) == 1 # let the user override the default decision of False assert S.Zero.replace(Wild('x'), 1, exact=True) == 0 def test_find(): expr = (x + y + 2 + sin(3*x)) assert expr.find(lambda u: u.is_Integer) == {S(2), S(3)} assert expr.find(lambda u: u.is_Symbol) == {x, y} assert expr.find(lambda u: u.is_Integer, group=True) == {S(2): 1, S(3): 1} assert expr.find(lambda u: u.is_Symbol, group=True) == {x: 2, y: 1} assert expr.find(Integer) == {S(2), S(3)} assert expr.find(Symbol) == {x, y} assert expr.find(Integer, group=True) == {S(2): 1, S(3): 1} assert expr.find(Symbol, group=True) == {x: 2, y: 1} a = Wild('a') expr = sin(sin(x)) + sin(x) + cos(x) + x assert expr.find(lambda u: type(u) is sin) == {sin(x), sin(sin(x))} assert expr.find( lambda u: type(u) is sin, group=True) == {sin(x): 2, sin(sin(x)): 1} assert expr.find(sin(a)) == {sin(x), sin(sin(x))} assert expr.find(sin(a), group=True) == {sin(x): 2, sin(sin(x)): 1} assert expr.find(sin) == {sin(x), sin(sin(x))} assert expr.find(sin, group=True) == {sin(x): 2, sin(sin(x)): 1} def test_count(): expr = (x + y + 2 + sin(3*x)) assert expr.count(lambda u: u.is_Integer) == 2 assert expr.count(lambda u: u.is_Symbol) == 3 assert expr.count(Integer) == 2 assert expr.count(Symbol) == 3 assert expr.count(2) == 1 a = Wild('a') assert expr.count(sin) == 1 assert expr.count(sin(a)) == 1 assert expr.count(lambda u: type(u) is sin) == 1 assert f(x).count(f(x)) == 1 assert f(x).diff(x).count(f(x)) == 1 assert f(x).diff(x).count(x) == 2 def test_has_basics(): p = Wild('p') assert sin(x).has(x) assert sin(x).has(sin) assert not sin(x).has(y) assert not sin(x).has(cos) assert f(x).has(x) assert f(x).has(f) assert not f(x).has(y) assert not f(x).has(g) assert f(x).diff(x).has(x) assert f(x).diff(x).has(f) assert f(x).diff(x).has(Derivative) assert not f(x).diff(x).has(y) assert not f(x).diff(x).has(g) assert not f(x).diff(x).has(sin) assert (x**2).has(Symbol) assert not (x**2).has(Wild) assert (2*p).has(Wild) assert not x.has() def test_has_multiple(): f = x**2*y + sin(2**t + log(z)) assert f.has(x) assert f.has(y) assert f.has(z) assert f.has(t) assert not f.has(u) assert f.has(x, y, z, t) assert f.has(x, y, z, t, u) i = Integer(4400) assert not i.has(x) assert (i*x**i).has(x) assert not (i*y**i).has(x) assert (i*y**i).has(x, y) assert not (i*y**i).has(x, z) def test_has_piecewise(): f = (x*y + 3/y)**(3 + 2) p = Piecewise((g(x), x < -1), (1, x <= 1), (f, True)) assert p.has(x) assert p.has(y) assert not p.has(z) assert p.has(1) assert p.has(3) assert not p.has(4) assert p.has(f) assert p.has(g) assert not p.has(h) def test_has_iterative(): A, B, C = symbols('A,B,C', commutative=False) f = x*gamma(x)*sin(x)*exp(x*y)*A*B*C*cos(x*A*B) assert f.has(x) assert f.has(x*y) assert f.has(x*sin(x)) assert not f.has(x*sin(y)) assert f.has(x*A) assert f.has(x*A*B) assert not f.has(x*A*C) assert f.has(x*A*B*C) assert not f.has(x*A*C*B) assert f.has(x*sin(x)*A*B*C) assert not f.has(x*sin(x)*A*C*B) assert not f.has(x*sin(y)*A*B*C) assert f.has(x*gamma(x)) assert not f.has(x + sin(x)) assert (x & y & z).has(x & z) def test_has_integrals(): f = Integral(x**2 + sin(x*y*z), (x, 0, x + y + z)) assert f.has(x + y) assert f.has(x + z) assert f.has(y + z) assert f.has(x*y) assert f.has(x*z) assert f.has(y*z) assert not f.has(2*x + y) assert not f.has(2*x*y) def test_has_tuple(): assert Tuple(x, y).has(x) assert not Tuple(x, y).has(z) assert Tuple(f(x), g(x)).has(x) assert not Tuple(f(x), g(x)).has(y) assert Tuple(f(x), g(x)).has(f) assert Tuple(f(x), g(x)).has(f(x)) # XXX to be deprecated #assert not Tuple(f, g).has(x) #assert Tuple(f, g).has(f) #assert not Tuple(f, g).has(h) assert Tuple(True).has(True) assert Tuple(True).has(S.true) assert not Tuple(True).has(1) def test_has_units(): from sympy.physics.units import m, s assert (x*m/s).has(x) assert (x*m/s).has(y, z) is False def test_has_polys(): poly = Poly(x**2 + x*y*sin(z), x, y, t) assert poly.has(x) assert poly.has(x, y, z) assert poly.has(x, y, z, t) def test_has_physics(): assert FockState((x, y)).has(x) def test_as_poly_as_expr(): f = x**2 + 2*x*y assert f.as_poly().as_expr() == f assert f.as_poly(x, y).as_expr() == f assert (f + sin(x)).as_poly(x, y) is None p = Poly(f, x, y) assert p.as_poly() == p # https://github.com/sympy/sympy/issues/20610 assert S(2).as_poly() is None assert sqrt(2).as_poly(extension=True) is None raises(AttributeError, lambda: Tuple(x, x).as_poly(x)) raises(AttributeError, lambda: Tuple(x ** 2, x, y).as_poly(x)) def test_nonzero(): assert bool(S.Zero) is False assert bool(S.One) is True assert bool(x) is True assert bool(x + y) is True assert bool(x - x) is False assert bool(x*y) is True assert bool(x*1) is True assert bool(x*0) is False def test_is_number(): assert Float(3.14).is_number is True assert Integer(737).is_number is True assert Rational(3, 2).is_number is True assert Rational(8).is_number is True assert x.is_number is False assert (2*x).is_number is False assert (x + y).is_number is False assert log(2).is_number is True assert log(x).is_number is False assert (2 + log(2)).is_number is True assert (8 + log(2)).is_number is True assert (2 + log(x)).is_number is False assert (8 + log(2) + x).is_number is False assert (1 + x**2/x - x).is_number is True assert Tuple(Integer(1)).is_number is False assert Add(2, x).is_number is False assert Mul(3, 4).is_number is True assert Pow(log(2), 2).is_number is True assert oo.is_number is True g = WildFunction('g') assert g.is_number is False assert (2*g).is_number is False assert (x**2).subs(x, 3).is_number is True # test extensibility of .is_number # on subinstances of Basic class A(Basic): pass a = A() assert a.is_number is False def test_as_coeff_add(): assert S(2).as_coeff_add() == (2, ()) assert S(3.0).as_coeff_add() == (0, (S(3.0),)) assert S(-3.0).as_coeff_add() == (0, (S(-3.0),)) assert x.as_coeff_add() == (0, (x,)) assert (x - 1).as_coeff_add() == (-1, (x,)) assert (x + 1).as_coeff_add() == (1, (x,)) assert (x + 2).as_coeff_add() == (2, (x,)) assert (x + y).as_coeff_add(y) == (x, (y,)) assert (3*x).as_coeff_add(y) == (3*x, ()) # don't do expansion e = (x + y)**2 assert e.as_coeff_add(y) == (0, (e,)) def test_as_coeff_mul(): assert S(2).as_coeff_mul() == (2, ()) assert S(3.0).as_coeff_mul() == (1, (S(3.0),)) assert S(-3.0).as_coeff_mul() == (-1, (S(3.0),)) assert S(-3.0).as_coeff_mul(rational=False) == (-S(3.0), ()) assert x.as_coeff_mul() == (1, (x,)) assert (-x).as_coeff_mul() == (-1, (x,)) assert (2*x).as_coeff_mul() == (2, (x,)) assert (x*y).as_coeff_mul(y) == (x, (y,)) assert (3 + x).as_coeff_mul() == (1, (3 + x,)) assert (3 + x).as_coeff_mul(y) == (3 + x, ()) # don't do expansion e = exp(x + y) assert e.as_coeff_mul(y) == (1, (e,)) e = 2**(x + y) assert e.as_coeff_mul(y) == (1, (e,)) assert (1.1*x).as_coeff_mul(rational=False) == (1.1, (x,)) assert (1.1*x).as_coeff_mul() == (1, (1.1, x)) assert (-oo*x).as_coeff_mul(rational=True) == (-1, (oo, x)) def test_as_coeff_exponent(): assert (3*x**4).as_coeff_exponent(x) == (3, 4) assert (2*x**3).as_coeff_exponent(x) == (2, 3) assert (4*x**2).as_coeff_exponent(x) == (4, 2) assert (6*x**1).as_coeff_exponent(x) == (6, 1) assert (3*x**0).as_coeff_exponent(x) == (3, 0) assert (2*x**0).as_coeff_exponent(x) == (2, 0) assert (1*x**0).as_coeff_exponent(x) == (1, 0) assert (0*x**0).as_coeff_exponent(x) == (0, 0) assert (-1*x**0).as_coeff_exponent(x) == (-1, 0) assert (-2*x**0).as_coeff_exponent(x) == (-2, 0) assert (2*x**3 + pi*x**3).as_coeff_exponent(x) == (2 + pi, 3) assert (x*log(2)/(2*x + pi*x)).as_coeff_exponent(x) == \ (log(2)/(2 + pi), 0) # issue 4784 D = Derivative fx = D(f(x), x) assert fx.as_coeff_exponent(f(x)) == (fx, 0) def test_extractions(): for base in (2, S.Exp1): assert Pow(base**x, 3, evaluate=False ).extract_multiplicatively(base**x) == base**(2*x) assert (base**(5*x)).extract_multiplicatively( base**(3*x)) == base**(2*x) assert ((x*y)**3).extract_multiplicatively(x**2 * y) == x*y**2 assert ((x*y)**3).extract_multiplicatively(x**4 * y) is None assert (2*x).extract_multiplicatively(2) == x assert (2*x).extract_multiplicatively(3) is None assert (2*x).extract_multiplicatively(-1) is None assert (S.Half*x).extract_multiplicatively(3) == x/6 assert (sqrt(x)).extract_multiplicatively(x) is None assert (sqrt(x)).extract_multiplicatively(1/x) is None assert x.extract_multiplicatively(-x) is None assert (-2 - 4*I).extract_multiplicatively(-2) == 1 + 2*I assert (-2 - 4*I).extract_multiplicatively(3) is None assert (-2*x - 4*y - 8).extract_multiplicatively(-2) == x + 2*y + 4 assert (-2*x*y - 4*x**2*y).extract_multiplicatively(-2*y) == 2*x**2 + x assert (2*x*y + 4*x**2*y).extract_multiplicatively(2*y) == 2*x**2 + x assert (-4*y**2*x).extract_multiplicatively(-3*y) is None assert (2*x).extract_multiplicatively(1) == 2*x assert (-oo).extract_multiplicatively(5) is -oo assert (oo).extract_multiplicatively(5) is oo assert ((x*y)**3).extract_additively(1) is None assert (x + 1).extract_additively(x) == 1 assert (x + 1).extract_additively(2*x) is None assert (x + 1).extract_additively(-x) is None assert (-x + 1).extract_additively(2*x) is None assert (2*x + 3).extract_additively(x) == x + 3 assert (2*x + 3).extract_additively(2) == 2*x + 1 assert (2*x + 3).extract_additively(3) == 2*x assert (2*x + 3).extract_additively(-2) is None assert (2*x + 3).extract_additively(3*x) is None assert (2*x + 3).extract_additively(2*x) == 3 assert x.extract_additively(0) == x assert S(2).extract_additively(x) is None assert S(2.).extract_additively(2) is S.Zero assert S(2*x + 3).extract_additively(x + 1) == x + 2 assert S(2*x + 3).extract_additively(y + 1) is None assert S(2*x - 3).extract_additively(x + 1) is None assert S(2*x - 3).extract_additively(y + z) is None assert ((a + 1)*x*4 + y).extract_additively(x).expand() == \ 4*a*x + 3*x + y assert ((a + 1)*x*4 + 3*y).extract_additively(x + 2*y).expand() == \ 4*a*x + 3*x + y assert (y*(x + 1)).extract_additively(x + 1) is None assert ((y + 1)*(x + 1) + 3).extract_additively(x + 1) == \ y*(x + 1) + 3 assert ((x + y)*(x + 1) + x + y + 3).extract_additively(x + y) == \ x*(x + y) + 3 assert (x + y + 2*((x + y)*(x + 1)) + 3).extract_additively((x + y)*(x + 1)) == \ x + y + (x + 1)*(x + y) + 3 assert ((y + 1)*(x + 2*y + 1) + 3).extract_additively(y + 1) == \ (x + 2*y)*(y + 1) + 3 n = Symbol("n", integer=True) assert (Integer(-3)).could_extract_minus_sign() is True assert (-n*x + x).could_extract_minus_sign() != \ (n*x - x).could_extract_minus_sign() assert (x - y).could_extract_minus_sign() != \ (-x + y).could_extract_minus_sign() assert (1 - x - y).could_extract_minus_sign() is True assert (1 - x + y).could_extract_minus_sign() is False assert ((-x - x*y)/y).could_extract_minus_sign() is False assert ((x + x*y)/(-y)).could_extract_minus_sign() is True assert ((x + x*y)/y).could_extract_minus_sign() is False assert ((-x - y)/(x + y)).could_extract_minus_sign() is False class sign_invariant(Function, Expr): nargs = 1 def __neg__(self): return self foo = sign_invariant(x) assert foo == -foo assert foo.could_extract_minus_sign() is False assert (x - y).could_extract_minus_sign() is False assert (-x + y).could_extract_minus_sign() is True assert (x - 1).could_extract_minus_sign() is False assert (1 - x).could_extract_minus_sign() is True assert (sqrt(2) - 1).could_extract_minus_sign() is True assert (1 - sqrt(2)).could_extract_minus_sign() is False # check that result is canonical eq = (3*x + 15*y).extract_multiplicatively(3) assert eq.args == eq.func(*eq.args).args def test_nan_extractions(): for r in (1, 0, I, nan): assert nan.extract_additively(r) is None assert nan.extract_multiplicatively(r) is None def test_coeff(): assert (x + 1).coeff(x + 1) == 1 assert (3*x).coeff(0) == 0 assert (z*(1 + x)*x**2).coeff(1 + x) == z*x**2 assert (1 + 2*x*x**(1 + x)).coeff(x*x**(1 + x)) == 2 assert (1 + 2*x**(y + z)).coeff(x**(y + z)) == 2 assert (3 + 2*x + 4*x**2).coeff(1) == 0 assert (3 + 2*x + 4*x**2).coeff(-1) == 0 assert (3 + 2*x + 4*x**2).coeff(x) == 2 assert (3 + 2*x + 4*x**2).coeff(x**2) == 4 assert (3 + 2*x + 4*x**2).coeff(x**3) == 0 assert (-x/8 + x*y).coeff(x) == Rational(-1, 8) + y assert (-x/8 + x*y).coeff(-x) == S.One/8 assert (4*x).coeff(2*x) == 0 assert (2*x).coeff(2*x) == 1 assert (-oo*x).coeff(x*oo) == -1 assert (10*x).coeff(x, 0) == 0 assert (10*x).coeff(10*x, 0) == 0 n1, n2 = symbols('n1 n2', commutative=False) assert (n1*n2).coeff(n1) == 1 assert (n1*n2).coeff(n2) == n1 assert (n1*n2 + x*n1).coeff(n1) == 1 # 1*n1*(n2+x) assert (n2*n1 + x*n1).coeff(n1) == n2 + x assert (n2*n1 + x*n1**2).coeff(n1) == n2 assert (n1**x).coeff(n1) == 0 assert (n1*n2 + n2*n1).coeff(n1) == 0 assert (2*(n1 + n2)*n2).coeff(n1 + n2, right=1) == n2 assert (2*(n1 + n2)*n2).coeff(n1 + n2, right=0) == 2 assert (2*f(x) + 3*f(x).diff(x)).coeff(f(x)) == 2 expr = z*(x + y)**2 expr2 = z*(x + y)**2 + z*(2*x + 2*y)**2 assert expr.coeff(z) == (x + y)**2 assert expr.coeff(x + y) == 0 assert expr2.coeff(z) == (x + y)**2 + (2*x + 2*y)**2 assert (x + y + 3*z).coeff(1) == x + y assert (-x + 2*y).coeff(-1) == x assert (x - 2*y).coeff(-1) == 2*y assert (3 + 2*x + 4*x**2).coeff(1) == 0 assert (-x - 2*y).coeff(2) == -y assert (x + sqrt(2)*x).coeff(sqrt(2)) == x assert (3 + 2*x + 4*x**2).coeff(x) == 2 assert (3 + 2*x + 4*x**2).coeff(x**2) == 4 assert (3 + 2*x + 4*x**2).coeff(x**3) == 0 assert (z*(x + y)**2).coeff((x + y)**2) == z assert (z*(x + y)**2).coeff(x + y) == 0 assert (2 + 2*x + (x + 1)*y).coeff(x + 1) == y assert (x + 2*y + 3).coeff(1) == x assert (x + 2*y + 3).coeff(x, 0) == 2*y + 3 assert (x**2 + 2*y + 3*x).coeff(x**2, 0) == 2*y + 3*x assert x.coeff(0, 0) == 0 assert x.coeff(x, 0) == 0 n, m, o, l = symbols('n m o l', commutative=False) assert n.coeff(n) == 1 assert y.coeff(n) == 0 assert (3*n).coeff(n) == 3 assert (2 + n).coeff(x*m) == 0 assert (2*x*n*m).coeff(x) == 2*n*m assert (2 + n).coeff(x*m*n + y) == 0 assert (2*x*n*m).coeff(3*n) == 0 assert (n*m + m*n*m).coeff(n) == 1 + m assert (n*m + m*n*m).coeff(n, right=True) == m # = (1 + m)*n*m assert (n*m + m*n).coeff(n) == 0 assert (n*m + o*m*n).coeff(m*n) == o assert (n*m + o*m*n).coeff(m*n, right=True) == 1 assert (n*m + n*m*n).coeff(n*m, right=True) == 1 + n # = n*m*(n + 1) assert (x*y).coeff(z, 0) == x*y assert (x*n + y*n + z*m).coeff(n) == x + y assert (n*m + n*o + o*l).coeff(n, right=True) == m + o assert (x*n*m*n + y*n*m*o + z*l).coeff(m, right=True) == x*n + y*o assert (x*n*m*n + x*n*m*o + z*l).coeff(m, right=True) == n + o assert (x*n*m*n + x*n*m*o + z*l).coeff(m) == x*n def test_coeff2(): r, kappa = symbols('r, kappa') psi = Function("psi") g = 1/r**2 * (2*r*psi(r).diff(r, 1) + r**2 * psi(r).diff(r, 2)) g = g.expand() assert g.coeff(psi(r).diff(r)) == 2/r def test_coeff2_0(): r, kappa = symbols('r, kappa') psi = Function("psi") g = 1/r**2 * (2*r*psi(r).diff(r, 1) + r**2 * psi(r).diff(r, 2)) g = g.expand() assert g.coeff(psi(r).diff(r, 2)) == 1 def test_coeff_expand(): expr = z*(x + y)**2 expr2 = z*(x + y)**2 + z*(2*x + 2*y)**2 assert expr.coeff(z) == (x + y)**2 assert expr2.coeff(z) == (x + y)**2 + (2*x + 2*y)**2 def test_integrate(): assert x.integrate(x) == x**2/2 assert x.integrate((x, 0, 1)) == S.Half def test_as_base_exp(): assert x.as_base_exp() == (x, S.One) assert (x*y*z).as_base_exp() == (x*y*z, S.One) assert (x + y + z).as_base_exp() == (x + y + z, S.One) assert ((x + y)**z).as_base_exp() == (x + y, z) def test_issue_4963(): assert hasattr(Mul(x, y), "is_commutative") assert hasattr(Mul(x, y, evaluate=False), "is_commutative") assert hasattr(Pow(x, y), "is_commutative") assert hasattr(Pow(x, y, evaluate=False), "is_commutative") expr = Mul(Pow(2, 2, evaluate=False), 3, evaluate=False) + 1 assert hasattr(expr, "is_commutative") def test_action_verbs(): assert nsimplify(1/(exp(3*pi*x/5) + 1)) == \ (1/(exp(3*pi*x/5) + 1)).nsimplify() assert ratsimp(1/x + 1/y) == (1/x + 1/y).ratsimp() assert trigsimp(log(x), deep=True) == (log(x)).trigsimp(deep=True) assert radsimp(1/(2 + sqrt(2))) == (1/(2 + sqrt(2))).radsimp() assert radsimp(1/(a + b*sqrt(c)), symbolic=False) == \ (1/(a + b*sqrt(c))).radsimp(symbolic=False) assert powsimp(x**y*x**z*y**z, combine='all') == \ (x**y*x**z*y**z).powsimp(combine='all') assert (x**t*y**t).powsimp(force=True) == (x*y)**t assert simplify(x**y*x**z*y**z) == (x**y*x**z*y**z).simplify() assert together(1/x + 1/y) == (1/x + 1/y).together() assert collect(a*x**2 + b*x**2 + a*x - b*x + c, x) == \ (a*x**2 + b*x**2 + a*x - b*x + c).collect(x) assert apart(y/(y + 2)/(y + 1), y) == (y/(y + 2)/(y + 1)).apart(y) assert combsimp(y/(x + 2)/(x + 1)) == (y/(x + 2)/(x + 1)).combsimp() assert gammasimp(gamma(x)/gamma(x-5)) == (gamma(x)/gamma(x-5)).gammasimp() assert factor(x**2 + 5*x + 6) == (x**2 + 5*x + 6).factor() assert refine(sqrt(x**2)) == sqrt(x**2).refine() assert cancel((x**2 + 5*x + 6)/(x + 2)) == ((x**2 + 5*x + 6)/(x + 2)).cancel() def test_as_powers_dict(): assert x.as_powers_dict() == {x: 1} assert (x**y*z).as_powers_dict() == {x: y, z: 1} assert Mul(2, 2, evaluate=False).as_powers_dict() == {S(2): S(2)} assert (x*y).as_powers_dict()[z] == 0 assert (x + y).as_powers_dict()[z] == 0 def test_as_coefficients_dict(): check = [S.One, x, y, x*y, 1] assert [Add(3*x, 2*x, y, 3).as_coefficients_dict()[i] for i in check] == \ [3, 5, 1, 0, 3] assert [Add(3*x, 2*x, y, 3, evaluate=False).as_coefficients_dict()[i] for i in check] == [3, 5, 1, 0, 3] assert [(3*x*y).as_coefficients_dict()[i] for i in check] == \ [0, 0, 0, 3, 0] assert [(3.0*x*y).as_coefficients_dict()[i] for i in check] == \ [0, 0, 0, 3.0, 0] assert (3.0*x*y).as_coefficients_dict()[3.0*x*y] == 0 def test_args_cnc(): A = symbols('A', commutative=False) assert (x + A).args_cnc() == \ [[], [x + A]] assert (x + a).args_cnc() == \ [[a + x], []] assert (x*a).args_cnc() == \ [[a, x], []] assert (x*y*A*(A + 1)).args_cnc(cset=True) == \ [{x, y}, [A, 1 + A]] assert Mul(x, x, evaluate=False).args_cnc(cset=True, warn=False) == \ [{x}, []] assert Mul(x, x**2, evaluate=False).args_cnc(cset=True, warn=False) == \ [{x, x**2}, []] raises(ValueError, lambda: Mul(x, x, evaluate=False).args_cnc(cset=True)) assert Mul(x, y, x, evaluate=False).args_cnc() == \ [[x, y, x], []] # always split -1 from leading number assert (-1.*x).args_cnc() == [[-1, 1.0, x], []] def test_new_rawargs(): n = Symbol('n', commutative=False) a = x + n assert a.is_commutative is False assert a._new_rawargs(x).is_commutative assert a._new_rawargs(x, y).is_commutative assert a._new_rawargs(x, n).is_commutative is False assert a._new_rawargs(x, y, n).is_commutative is False m = x*n assert m.is_commutative is False assert m._new_rawargs(x).is_commutative assert m._new_rawargs(n).is_commutative is False assert m._new_rawargs(x, y).is_commutative assert m._new_rawargs(x, n).is_commutative is False assert m._new_rawargs(x, y, n).is_commutative is False assert m._new_rawargs(x, n, reeval=False).is_commutative is False assert m._new_rawargs(S.One) is S.One def test_issue_5226(): assert Add(evaluate=False) == 0 assert Mul(evaluate=False) == 1 assert Mul(x + y, evaluate=False).is_Add def test_free_symbols(): # free_symbols should return the free symbols of an object assert S.One.free_symbols == set() assert x.free_symbols == {x} assert Integral(x, (x, 1, y)).free_symbols == {y} assert (-Integral(x, (x, 1, y))).free_symbols == {y} assert meter.free_symbols == set() assert (meter**x).free_symbols == {x} def test_has_free(): assert x.has_free(x) assert not x.has_free(y) assert (x + y).has_free(x) assert (x + y).has_free(*(x, z)) assert f(x).has_free(x) assert f(x).has_free(f(x)) assert Integral(f(x), (f(x), 1, y)).has_free(y) assert not Integral(f(x), (f(x), 1, y)).has_free(x) assert not Integral(f(x), (f(x), 1, y)).has_free(f(x)) def test_issue_5300(): x = Symbol('x', commutative=False) assert x*sqrt(2)/sqrt(6) == x*sqrt(3)/3 def test_floordiv(): from sympy.functions.elementary.integers import floor assert x // y == floor(x / y) def test_as_coeff_Mul(): assert Integer(3).as_coeff_Mul() == (Integer(3), Integer(1)) assert Rational(3, 4).as_coeff_Mul() == (Rational(3, 4), Integer(1)) assert Float(5.0).as_coeff_Mul() == (Float(5.0), Integer(1)) assert (Integer(3)*x).as_coeff_Mul() == (Integer(3), x) assert (Rational(3, 4)*x).as_coeff_Mul() == (Rational(3, 4), x) assert (Float(5.0)*x).as_coeff_Mul() == (Float(5.0), x) assert (Integer(3)*x*y).as_coeff_Mul() == (Integer(3), x*y) assert (Rational(3, 4)*x*y).as_coeff_Mul() == (Rational(3, 4), x*y) assert (Float(5.0)*x*y).as_coeff_Mul() == (Float(5.0), x*y) assert (x).as_coeff_Mul() == (S.One, x) assert (x*y).as_coeff_Mul() == (S.One, x*y) assert (-oo*x).as_coeff_Mul(rational=True) == (-1, oo*x) def test_as_coeff_Add(): assert Integer(3).as_coeff_Add() == (Integer(3), Integer(0)) assert Rational(3, 4).as_coeff_Add() == (Rational(3, 4), Integer(0)) assert Float(5.0).as_coeff_Add() == (Float(5.0), Integer(0)) assert (Integer(3) + x).as_coeff_Add() == (Integer(3), x) assert (Rational(3, 4) + x).as_coeff_Add() == (Rational(3, 4), x) assert (Float(5.0) + x).as_coeff_Add() == (Float(5.0), x) assert (Float(5.0) + x).as_coeff_Add(rational=True) == (0, Float(5.0) + x) assert (Integer(3) + x + y).as_coeff_Add() == (Integer(3), x + y) assert (Rational(3, 4) + x + y).as_coeff_Add() == (Rational(3, 4), x + y) assert (Float(5.0) + x + y).as_coeff_Add() == (Float(5.0), x + y) assert (x).as_coeff_Add() == (S.Zero, x) assert (x*y).as_coeff_Add() == (S.Zero, x*y) def test_expr_sorting(): exprs = [1/x**2, 1/x, sqrt(sqrt(x)), sqrt(x), x, sqrt(x)**3, x**2] assert sorted(exprs, key=default_sort_key) == exprs exprs = [x, 2*x, 2*x**2, 2*x**3, x**n, 2*x**n, sin(x), sin(x)**n, sin(x**2), cos(x), cos(x**2), tan(x)] assert sorted(exprs, key=default_sort_key) == exprs exprs = [x + 1, x**2 + x + 1, x**3 + x**2 + x + 1] assert sorted(exprs, key=default_sort_key) == exprs exprs = [S(4), x - 3*I/2, x + 3*I/2, x - 4*I + 1, x + 4*I + 1] assert sorted(exprs, key=default_sort_key) == exprs exprs = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)] assert sorted(exprs, key=default_sort_key) == exprs exprs = [f(x), g(x), exp(x), sin(x), cos(x), factorial(x)] assert sorted(exprs, key=default_sort_key) == exprs exprs = [Tuple(x, y), Tuple(x, z), Tuple(x, y, z)] assert sorted(exprs, key=default_sort_key) == exprs exprs = [[3], [1, 2]] assert sorted(exprs, key=default_sort_key) == exprs exprs = [[1, 2], [2, 3]] assert sorted(exprs, key=default_sort_key) == exprs exprs = [[1, 2], [1, 2, 3]] assert sorted(exprs, key=default_sort_key) == exprs exprs = [{x: -y}, {x: y}] assert sorted(exprs, key=default_sort_key) == exprs exprs = [{1}, {1, 2}] assert sorted(exprs, key=default_sort_key) == exprs a, b = exprs = [Dummy('x'), Dummy('x')] assert sorted([b, a], key=default_sort_key) == exprs def test_as_ordered_factors(): assert x.as_ordered_factors() == [x] assert (2*x*x**n*sin(x)*cos(x)).as_ordered_factors() \ == [Integer(2), x, x**n, sin(x), cos(x)] args = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)] expr = Mul(*args) assert expr.as_ordered_factors() == args A, B = symbols('A,B', commutative=False) assert (A*B).as_ordered_factors() == [A, B] assert (B*A).as_ordered_factors() == [B, A] def test_as_ordered_terms(): assert x.as_ordered_terms() == [x] assert (sin(x)**2*cos(x) + sin(x)*cos(x)**2 + 1).as_ordered_terms() \ == [sin(x)**2*cos(x), sin(x)*cos(x)**2, 1] args = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)] expr = Add(*args) assert expr.as_ordered_terms() == args assert (1 + 4*sqrt(3)*pi*x).as_ordered_terms() == [4*pi*x*sqrt(3), 1] assert ( 2 + 3*I).as_ordered_terms() == [2, 3*I] assert (-2 + 3*I).as_ordered_terms() == [-2, 3*I] assert ( 2 - 3*I).as_ordered_terms() == [2, -3*I] assert (-2 - 3*I).as_ordered_terms() == [-2, -3*I] assert ( 4 + 3*I).as_ordered_terms() == [4, 3*I] assert (-4 + 3*I).as_ordered_terms() == [-4, 3*I] assert ( 4 - 3*I).as_ordered_terms() == [4, -3*I] assert (-4 - 3*I).as_ordered_terms() == [-4, -3*I] e = x**2*y**2 + x*y**4 + y + 2 assert e.as_ordered_terms(order="lex") == [x**2*y**2, x*y**4, y, 2] assert e.as_ordered_terms(order="grlex") == [x*y**4, x**2*y**2, y, 2] assert e.as_ordered_terms(order="rev-lex") == [2, y, x*y**4, x**2*y**2] assert e.as_ordered_terms(order="rev-grlex") == [2, y, x**2*y**2, x*y**4] k = symbols('k') assert k.as_ordered_terms(data=True) == ([(k, ((1.0, 0.0), (1,), ()))], [k]) def test_sort_key_atomic_expr(): from sympy.physics.units import m, s assert sorted([-m, s], key=lambda arg: arg.sort_key()) == [-m, s] def test_eval_interval(): assert exp(x)._eval_interval(*Tuple(x, 0, 1)) == exp(1) - exp(0) # issue 4199 a = x/y raises(NotImplementedError, lambda: a._eval_interval(x, S.Zero, oo)._eval_interval(y, oo, S.Zero)) raises(NotImplementedError, lambda: a._eval_interval(x, S.Zero, oo)._eval_interval(y, S.Zero, oo)) a = x - y raises(NotImplementedError, lambda: a._eval_interval(x, S.One, oo)._eval_interval(y, oo, S.One)) raises(ValueError, lambda: x._eval_interval(x, None, None)) a = -y*Heaviside(x - y) assert a._eval_interval(x, -oo, oo) == -y assert a._eval_interval(x, oo, -oo) == y def test_eval_interval_zoo(): # Test that limit is used when zoo is returned assert Si(1/x)._eval_interval(x, S.Zero, S.One) == -pi/2 + Si(1) def test_primitive(): assert (3*(x + 1)**2).primitive() == (3, (x + 1)**2) assert (6*x + 2).primitive() == (2, 3*x + 1) assert (x/2 + 3).primitive() == (S.Half, x + 6) eq = (6*x + 2)*(x/2 + 3) assert eq.primitive()[0] == 1 eq = (2 + 2*x)**2 assert eq.primitive()[0] == 1 assert (4.0*x).primitive() == (1, 4.0*x) assert (4.0*x + y/2).primitive() == (S.Half, 8.0*x + y) assert (-2*x).primitive() == (2, -x) assert Add(5*z/7, 0.5*x, 3*y/2, evaluate=False).primitive() == \ (S.One/14, 7.0*x + 21*y + 10*z) for i in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]: assert (i + x/3).primitive() == \ (S.One/3, i + x) assert (S.Infinity + 2*x/3 + 4*y/7).primitive() == \ (S.One/21, 14*x + 12*y + oo) assert S.Zero.primitive() == (S.One, S.Zero) def test_issue_5843(): a = 1 + x assert (2*a).extract_multiplicatively(a) == 2 assert (4*a).extract_multiplicatively(2*a) == 2 assert ((3*a)*(2*a)).extract_multiplicatively(a) == 6*a def test_is_constant(): from sympy.solvers.solvers import checksol assert Sum(x, (x, 1, 10)).is_constant() is True assert Sum(x, (x, 1, n)).is_constant() is False assert Sum(x, (x, 1, n)).is_constant(y) is True assert Sum(x, (x, 1, n)).is_constant(n) is False assert Sum(x, (x, 1, n)).is_constant(x) is True eq = a*cos(x)**2 + a*sin(x)**2 - a assert eq.is_constant() is True assert eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0 assert x.is_constant() is False assert x.is_constant(y) is True assert log(x/y).is_constant() is False assert checksol(x, x, Sum(x, (x, 1, n))) is False assert checksol(x, x, Sum(x, (x, 1, n))) is False assert f(1).is_constant assert checksol(x, x, f(x)) is False assert Pow(x, S.Zero, evaluate=False).is_constant() is True # == 1 assert Pow(S.Zero, x, evaluate=False).is_constant() is False # == 0 or 1 assert (2**x).is_constant() is False assert Pow(S(2), S(3), evaluate=False).is_constant() is True z1, z2 = symbols('z1 z2', zero=True) assert (z1 + 2*z2).is_constant() is True assert meter.is_constant() is True assert (3*meter).is_constant() is True assert (x*meter).is_constant() is False def test_equals(): assert (-3 - sqrt(5) + (-sqrt(10)/2 - sqrt(2)/2)**2).equals(0) assert (x**2 - 1).equals((x + 1)*(x - 1)) assert (cos(x)**2 + sin(x)**2).equals(1) assert (a*cos(x)**2 + a*sin(x)**2).equals(a) r = sqrt(2) assert (-1/(r + r*x) + 1/r/(1 + x)).equals(0) assert factorial(x + 1).equals((x + 1)*factorial(x)) assert sqrt(3).equals(2*sqrt(3)) is False assert (sqrt(5)*sqrt(3)).equals(sqrt(3)) is False assert (sqrt(5) + sqrt(3)).equals(0) is False assert (sqrt(5) + pi).equals(0) is False assert meter.equals(0) is False assert (3*meter**2).equals(0) is False eq = -(-1)**(S(3)/4)*6**(S.One/4) + (-6)**(S.One/4)*I if eq != 0: # if canonicalization makes this zero, skip the test assert eq.equals(0) assert sqrt(x).equals(0) is False # from integrate(x*sqrt(1 + 2*x), x); # diff is zero only when assumptions allow i = 2*sqrt(2)*x**(S(5)/2)*(1 + 1/(2*x))**(S(5)/2)/5 + \ 2*sqrt(2)*x**(S(3)/2)*(1 + 1/(2*x))**(S(5)/2)/(-6 - 3/x) ans = sqrt(2*x + 1)*(6*x**2 + x - 1)/15 diff = i - ans assert diff.equals(0) is None # should be False, but previously this was False due to wrong intermediate result assert diff.subs(x, Rational(-1, 2)/2) == 7*sqrt(2)/120 # there are regions for x for which the expression is True, for # example, when x < -1/2 or x > 0 the expression is zero p = Symbol('p', positive=True) assert diff.subs(x, p).equals(0) is True assert diff.subs(x, -1).equals(0) is True # prove via minimal_polynomial or self-consistency eq = sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3)) - sqrt(10 + 6*sqrt(3)) assert eq.equals(0) q = 3**Rational(1, 3) + 3 p = expand(q**3)**Rational(1, 3) assert (p - q).equals(0) # issue 6829 # eq = q*x + q/4 + x**4 + x**3 + 2*x**2 - S.One/3 # z = eq.subs(x, solve(eq, x)[0]) q = symbols('q') z = (q*(-sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q - S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/6)/2 - S.One/4) + q/4 + (-sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q - S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/6)/2 - S.One/4)**4 + (-sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q - S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/6)/2 - S.One/4)**3 + 2*(-sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q - S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/6)/2 - S.One/4)**2 - Rational(1, 3)) assert z.equals(0) def test_random(): from sympy.functions.combinatorial.numbers import lucas from sympy.simplify.simplify import posify assert posify(x)[0]._random() is not None assert lucas(n)._random(2, -2, 0, -1, 1) is None # issue 8662 assert Piecewise((Max(x, y), z))._random() is None def test_round(): assert str(Float('0.1249999').round(2)) == '0.12' d20 = 12345678901234567890 ans = S(d20).round(2) assert ans.is_Integer and ans == d20 ans = S(d20).round(-2) assert ans.is_Integer and ans == 12345678901234567900 assert str(S('1/7').round(4)) == '0.1429' assert str(S('.[12345]').round(4)) == '0.1235' assert str(S('.1349').round(2)) == '0.13' n = S(12345) ans = n.round() assert ans.is_Integer assert ans == n ans = n.round(1) assert ans.is_Integer assert ans == n ans = n.round(4) assert ans.is_Integer assert ans == n assert n.round(-1) == 12340 r = Float(str(n)).round(-4) assert r == 10000 assert n.round(-5) == 0 assert str((pi + sqrt(2)).round(2)) == '4.56' assert (10*(pi + sqrt(2))).round(-1) == 50 raises(TypeError, lambda: round(x + 2, 2)) assert str(S(2.3).round(1)) == '2.3' # rounding in SymPy (as in Decimal) should be # exact for the given precision; we check here # that when a 5 follows the last digit that # the rounded digit will be even. for i in range(-99, 100): # construct a decimal that ends in 5, e.g. 123 -> 0.1235 s = str(abs(i)) p = len(s) # we are going to round to the last digit of i n = '0.%s5' % s # put a 5 after i's digits j = p + 2 # 2 for '0.' if i < 0: # 1 for '-' j += 1 n = '-' + n v = str(Float(n).round(p))[:j] # pertinent digits if v.endswith('.'): continue # it ends with 0 which is even L = int(v[-1]) # last digit assert L % 2 == 0, (n, '->', v) assert (Float(.3, 3) + 2*pi).round() == 7 assert (Float(.3, 3) + 2*pi*100).round() == 629 assert (pi + 2*E*I).round() == 3 + 5*I # don't let request for extra precision give more than # what is known (in this case, only 3 digits) assert str((Float(.03, 3) + 2*pi/100).round(5)) == '0.0928' assert str((Float(.03, 3) + 2*pi/100).round(4)) == '0.0928' assert S.Zero.round() == 0 a = (Add(1, Float('1.' + '9'*27, ''), evaluate=0)) assert a.round(10) == Float('3.0000000000', '') assert a.round(25) == Float('3.0000000000000000000000000', '') assert a.round(26) == Float('3.00000000000000000000000000', '') assert a.round(27) == Float('2.999999999999999999999999999', '') assert a.round(30) == Float('2.999999999999999999999999999', '') raises(TypeError, lambda: x.round()) raises(TypeError, lambda: f(1).round()) # exact magnitude of 10 assert str(S.One.round()) == '1' assert str(S(100).round()) == '100' # applied to real and imaginary portions assert (2*pi + E*I).round() == 6 + 3*I assert (2*pi + I/10).round() == 6 assert (pi/10 + 2*I).round() == 2*I # the lhs re and im parts are Float with dps of 2 # and those on the right have dps of 15 so they won't compare # equal unless we use string or compare components (which will # then coerce the floats to the same precision) or re-create # the floats assert str((pi/10 + E*I).round(2)) == '0.31 + 2.72*I' assert str((pi/10 + E*I).round(2).as_real_imag()) == '(0.31, 2.72)' assert str((pi/10 + E*I).round(2)) == '0.31 + 2.72*I' # issue 6914 assert (I**(I + 3)).round(3) == Float('-0.208', '')*I # issue 8720 assert S(-123.6).round() == -124 assert S(-1.5).round() == -2 assert S(-100.5).round() == -100 assert S(-1.5 - 10.5*I).round() == -2 - 10*I # issue 7961 assert str(S(0.006).round(2)) == '0.01' assert str(S(0.00106).round(4)) == '0.0011' # issue 8147 assert S.NaN.round() is S.NaN assert S.Infinity.round() is S.Infinity assert S.NegativeInfinity.round() is S.NegativeInfinity assert S.ComplexInfinity.round() is S.ComplexInfinity # check that types match for i in range(2): fi = float(i) # 2 args assert all(type(round(i, p)) is int for p in (-1, 0, 1)) assert all(S(i).round(p).is_Integer for p in (-1, 0, 1)) assert all(type(round(fi, p)) is float for p in (-1, 0, 1)) assert all(S(fi).round(p).is_Float for p in (-1, 0, 1)) # 1 arg (p is None) assert type(round(i)) is int assert S(i).round().is_Integer assert type(round(fi)) is int assert S(fi).round().is_Integer def test_held_expression_UnevaluatedExpr(): x = symbols("x") he = UnevaluatedExpr(1/x) e1 = x*he assert isinstance(e1, Mul) assert e1.args == (x, he) assert e1.doit() == 1 assert UnevaluatedExpr(Derivative(x, x)).doit(deep=False ) == Derivative(x, x) assert UnevaluatedExpr(Derivative(x, x)).doit() == 1 xx = Mul(x, x, evaluate=False) assert xx != x**2 ue2 = UnevaluatedExpr(xx) assert isinstance(ue2, UnevaluatedExpr) assert ue2.args == (xx,) assert ue2.doit() == x**2 assert ue2.doit(deep=False) == xx x2 = UnevaluatedExpr(2)*2 assert type(x2) is Mul assert x2.args == (2, UnevaluatedExpr(2)) def test_round_exception_nostr(): # Don't use the string form of the expression in the round exception, as # it's too slow s = Symbol('bad') try: s.round() except TypeError as e: assert 'bad' not in str(e) else: # Did not raise raise AssertionError("Did not raise") def test_extract_branch_factor(): assert exp_polar(2.0*I*pi).extract_branch_factor() == (1, 1) def test_identity_removal(): assert Add.make_args(x + 0) == (x,) assert Mul.make_args(x*1) == (x,) def test_float_0(): assert Float(0.0) + 1 == Float(1.0) @XFAIL def test_float_0_fail(): assert Float(0.0)*x == Float(0.0) assert (x + Float(0.0)).is_Add def test_issue_6325(): ans = (b**2 + z**2 - (b*(a + b*t) + z*(c + t*z))**2/( (a + b*t)**2 + (c + t*z)**2))/sqrt((a + b*t)**2 + (c + t*z)**2) e = sqrt((a + b*t)**2 + (c + z*t)**2) assert diff(e, t, 2) == ans assert e.diff(t, 2) == ans assert diff(e, t, 2, simplify=False) != ans def test_issue_7426(): f1 = a % c f2 = x % z assert f1.equals(f2) is None def test_issue_11122(): x = Symbol('x', extended_positive=False) assert unchanged(Gt, x, 0) # (x > 0) # (x > 0) should remain unevaluated after PR #16956 x = Symbol('x', positive=False, real=True) assert (x > 0) is S.false def test_issue_10651(): x = Symbol('x', real=True) e1 = (-1 + x)/(1 - x) e3 = (4*x**2 - 4)/((1 - x)*(1 + x)) e4 = 1/(cos(x)**2) - (tan(x))**2 x = Symbol('x', positive=True) e5 = (1 + x)/x assert e1.is_constant() is None assert e3.is_constant() is None assert e4.is_constant() is None assert e5.is_constant() is False def test_issue_10161(): x = symbols('x', real=True) assert x*abs(x)*abs(x) == x**3 def test_issue_10755(): x = symbols('x') raises(TypeError, lambda: int(log(x))) raises(TypeError, lambda: log(x).round(2)) def test_issue_11877(): x = symbols('x') assert integrate(log(S.Half - x), (x, 0, S.Half)) == Rational(-1, 2) -log(2)/2 def test_normal(): x = symbols('x') e = Mul(S.Half, 1 + x, evaluate=False) assert e.normal() == e def test_expr(): x = symbols('x') raises(TypeError, lambda: tan(x).series(x, 2, oo, "+")) def test_ExprBuilder(): eb = ExprBuilder(Mul) eb.args.extend([x, x]) assert eb.build() == x**2 def test_issue_22020(): from sympy.parsing.sympy_parser import parse_expr x = parse_expr("log((2*V/3-V)/C)/-(R+r)*C") y = parse_expr("log((2*V/3-V)/C)/-(R+r)*2") assert x.equals(y) is False def test_non_string_equality(): # Expressions should not compare equal to strings x = symbols('x') one = sympify(1) assert (x == 'x') is False assert (x != 'x') is True assert (one == '1') is False assert (one != '1') is True assert (x + 1 == 'x + 1') is False assert (x + 1 != 'x + 1') is True # Make sure == doesn't try to convert the resulting expression to a string # (e.g., by calling sympify() instead of _sympify()) class BadRepr: def __repr__(self): raise RuntimeError assert (x == BadRepr()) is False assert (x != BadRepr()) is True def test_21494(): from sympy.testing.pytest import warns_deprecated_sympy with warns_deprecated_sympy(): assert x.expr_free_symbols == {x} def test_Expr__eq__iterable_handling(): assert x != range(3)
68e27a2008b166c34fc9e89b4e8ea27bfb50a4de1febd050381a384619f65d76
"""Test whether all elements of cls.args are instances of Basic. """ # NOTE: keep tests sorted by (module, class name) key. If a class can't # be instantiated, add it here anyway with @SKIP("abstract class) (see # e.g. Function). import os import re from sympy.assumptions.ask import Q from sympy.core.basic import Basic from sympy.core.function import (Function, Lambda) from sympy.core.numbers import (Rational, oo, pi) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import sin from sympy.testing.pytest import XFAIL, SKIP a, b, c, x, y, z = symbols('a,b,c,x,y,z') whitelist = [ "sympy.assumptions.predicates", # tested by test_predicates() "sympy.assumptions.relation.equality", # tested by test_predicates() ] def test_all_classes_are_tested(): this = os.path.split(__file__)[0] path = os.path.join(this, os.pardir, os.pardir) sympy_path = os.path.abspath(path) prefix = os.path.split(sympy_path)[0] + os.sep re_cls = re.compile(r"^class ([A-Za-z][A-Za-z0-9_]*)\s*\(", re.MULTILINE) modules = {} for root, dirs, files in os.walk(sympy_path): module = root.replace(prefix, "").replace(os.sep, ".") for file in files: if file.startswith(("_", "test_", "bench_")): continue if not file.endswith(".py"): continue with open(os.path.join(root, file), encoding='utf-8') as f: text = f.read() submodule = module + '.' + file[:-3] if any(submodule.startswith(wpath) for wpath in whitelist): continue names = re_cls.findall(text) if not names: continue try: mod = __import__(submodule, fromlist=names) except ImportError: continue def is_Basic(name): cls = getattr(mod, name) if hasattr(cls, '_sympy_deprecated_func'): cls = cls._sympy_deprecated_func if not isinstance(cls, type): # check instance of singleton class with same name cls = type(cls) return issubclass(cls, Basic) names = list(filter(is_Basic, names)) if names: modules[submodule] = names ns = globals() failed = [] for module, names in modules.items(): mod = module.replace('.', '__') for name in names: test = 'test_' + mod + '__' + name if test not in ns: failed.append(module + '.' + name) assert not failed, "Missing classes: %s. Please add tests for these to sympy/core/tests/test_args.py." % ", ".join(failed) def _test_args(obj): all_basic = all(isinstance(arg, Basic) for arg in obj.args) # Ideally obj.func(*obj.args) would always recreate the object, but for # now, we only require it for objects with non-empty .args recreatable = not obj.args or obj.func(*obj.args) == obj return all_basic and recreatable def test_sympy__algebras__quaternion__Quaternion(): from sympy.algebras.quaternion import Quaternion assert _test_args(Quaternion(x, 1, 2, 3)) def test_sympy__assumptions__assume__AppliedPredicate(): from sympy.assumptions.assume import AppliedPredicate, Predicate assert _test_args(AppliedPredicate(Predicate("test"), 2)) assert _test_args(Q.is_true(True)) @SKIP("abstract class") def test_sympy__assumptions__assume__Predicate(): pass def test_predicates(): predicates = [ getattr(Q, attr) for attr in Q.__class__.__dict__ if not attr.startswith('__')] for p in predicates: assert _test_args(p) def test_sympy__assumptions__assume__UndefinedPredicate(): from sympy.assumptions.assume import Predicate assert _test_args(Predicate("test")) @SKIP('abstract class') def test_sympy__assumptions__relation__binrel__BinaryRelation(): pass def test_sympy__assumptions__relation__binrel__AppliedBinaryRelation(): assert _test_args(Q.eq(1, 2)) def test_sympy__assumptions__wrapper__AssumptionsWrapper(): from sympy.assumptions.wrapper import AssumptionsWrapper assert _test_args(AssumptionsWrapper(x, Q.positive(x))) @SKIP("abstract Class") def test_sympy__codegen__ast__CodegenAST(): from sympy.codegen.ast import CodegenAST assert _test_args(CodegenAST()) @SKIP("abstract Class") def test_sympy__codegen__ast__AssignmentBase(): from sympy.codegen.ast import AssignmentBase assert _test_args(AssignmentBase(x, 1)) @SKIP("abstract Class") def test_sympy__codegen__ast__AugmentedAssignment(): from sympy.codegen.ast import AugmentedAssignment assert _test_args(AugmentedAssignment(x, 1)) def test_sympy__codegen__ast__AddAugmentedAssignment(): from sympy.codegen.ast import AddAugmentedAssignment assert _test_args(AddAugmentedAssignment(x, 1)) def test_sympy__codegen__ast__SubAugmentedAssignment(): from sympy.codegen.ast import SubAugmentedAssignment assert _test_args(SubAugmentedAssignment(x, 1)) def test_sympy__codegen__ast__MulAugmentedAssignment(): from sympy.codegen.ast import MulAugmentedAssignment assert _test_args(MulAugmentedAssignment(x, 1)) def test_sympy__codegen__ast__DivAugmentedAssignment(): from sympy.codegen.ast import DivAugmentedAssignment assert _test_args(DivAugmentedAssignment(x, 1)) def test_sympy__codegen__ast__ModAugmentedAssignment(): from sympy.codegen.ast import ModAugmentedAssignment assert _test_args(ModAugmentedAssignment(x, 1)) def test_sympy__codegen__ast__CodeBlock(): from sympy.codegen.ast import CodeBlock, Assignment assert _test_args(CodeBlock(Assignment(x, 1), Assignment(y, 2))) def test_sympy__codegen__ast__For(): from sympy.codegen.ast import For, CodeBlock, AddAugmentedAssignment from sympy.sets import Range assert _test_args(For(x, Range(10), CodeBlock(AddAugmentedAssignment(y, 1)))) def test_sympy__codegen__ast__Token(): from sympy.codegen.ast import Token assert _test_args(Token()) def test_sympy__codegen__ast__ContinueToken(): from sympy.codegen.ast import ContinueToken assert _test_args(ContinueToken()) def test_sympy__codegen__ast__BreakToken(): from sympy.codegen.ast import BreakToken assert _test_args(BreakToken()) def test_sympy__codegen__ast__NoneToken(): from sympy.codegen.ast import NoneToken assert _test_args(NoneToken()) def test_sympy__codegen__ast__String(): from sympy.codegen.ast import String assert _test_args(String('foobar')) def test_sympy__codegen__ast__QuotedString(): from sympy.codegen.ast import QuotedString assert _test_args(QuotedString('foobar')) def test_sympy__codegen__ast__Comment(): from sympy.codegen.ast import Comment assert _test_args(Comment('this is a comment')) def test_sympy__codegen__ast__Node(): from sympy.codegen.ast import Node assert _test_args(Node()) assert _test_args(Node(attrs={1, 2, 3})) def test_sympy__codegen__ast__Type(): from sympy.codegen.ast import Type assert _test_args(Type('float128')) def test_sympy__codegen__ast__IntBaseType(): from sympy.codegen.ast import IntBaseType assert _test_args(IntBaseType('bigint')) def test_sympy__codegen__ast___SizedIntType(): from sympy.codegen.ast import _SizedIntType assert _test_args(_SizedIntType('int128', 128)) def test_sympy__codegen__ast__SignedIntType(): from sympy.codegen.ast import SignedIntType assert _test_args(SignedIntType('int128_with_sign', 128)) def test_sympy__codegen__ast__UnsignedIntType(): from sympy.codegen.ast import UnsignedIntType assert _test_args(UnsignedIntType('unt128', 128)) def test_sympy__codegen__ast__FloatBaseType(): from sympy.codegen.ast import FloatBaseType assert _test_args(FloatBaseType('positive_real')) def test_sympy__codegen__ast__FloatType(): from sympy.codegen.ast import FloatType assert _test_args(FloatType('float242', 242, nmant=142, nexp=99)) def test_sympy__codegen__ast__ComplexBaseType(): from sympy.codegen.ast import ComplexBaseType assert _test_args(ComplexBaseType('positive_cmplx')) def test_sympy__codegen__ast__ComplexType(): from sympy.codegen.ast import ComplexType assert _test_args(ComplexType('complex42', 42, nmant=15, nexp=5)) def test_sympy__codegen__ast__Attribute(): from sympy.codegen.ast import Attribute assert _test_args(Attribute('noexcept')) def test_sympy__codegen__ast__Variable(): from sympy.codegen.ast import Variable, Type, value_const assert _test_args(Variable(x)) assert _test_args(Variable(y, Type('float32'), {value_const})) assert _test_args(Variable(z, type=Type('float64'))) def test_sympy__codegen__ast__Pointer(): from sympy.codegen.ast import Pointer, Type, pointer_const assert _test_args(Pointer(x)) assert _test_args(Pointer(y, type=Type('float32'))) assert _test_args(Pointer(z, Type('float64'), {pointer_const})) def test_sympy__codegen__ast__Declaration(): from sympy.codegen.ast import Declaration, Variable, Type vx = Variable(x, type=Type('float')) assert _test_args(Declaration(vx)) def test_sympy__codegen__ast__While(): from sympy.codegen.ast import While, AddAugmentedAssignment assert _test_args(While(abs(x) < 1, [AddAugmentedAssignment(x, -1)])) def test_sympy__codegen__ast__Scope(): from sympy.codegen.ast import Scope, AddAugmentedAssignment assert _test_args(Scope([AddAugmentedAssignment(x, -1)])) def test_sympy__codegen__ast__Stream(): from sympy.codegen.ast import Stream assert _test_args(Stream('stdin')) def test_sympy__codegen__ast__Print(): from sympy.codegen.ast import Print assert _test_args(Print([x, y])) assert _test_args(Print([x, y], "%d %d")) def test_sympy__codegen__ast__FunctionPrototype(): from sympy.codegen.ast import FunctionPrototype, real, Declaration, Variable inp_x = Declaration(Variable(x, type=real)) assert _test_args(FunctionPrototype(real, 'pwer', [inp_x])) def test_sympy__codegen__ast__FunctionDefinition(): from sympy.codegen.ast import FunctionDefinition, real, Declaration, Variable, Assignment inp_x = Declaration(Variable(x, type=real)) assert _test_args(FunctionDefinition(real, 'pwer', [inp_x], [Assignment(x, x**2)])) def test_sympy__codegen__ast__Return(): from sympy.codegen.ast import Return assert _test_args(Return(x)) def test_sympy__codegen__ast__FunctionCall(): from sympy.codegen.ast import FunctionCall assert _test_args(FunctionCall('pwer', [x])) def test_sympy__codegen__ast__Element(): from sympy.codegen.ast import Element assert _test_args(Element('x', range(3))) def test_sympy__codegen__cnodes__CommaOperator(): from sympy.codegen.cnodes import CommaOperator assert _test_args(CommaOperator(1, 2)) def test_sympy__codegen__cnodes__goto(): from sympy.codegen.cnodes import goto assert _test_args(goto('early_exit')) def test_sympy__codegen__cnodes__Label(): from sympy.codegen.cnodes import Label assert _test_args(Label('early_exit')) def test_sympy__codegen__cnodes__PreDecrement(): from sympy.codegen.cnodes import PreDecrement assert _test_args(PreDecrement(x)) def test_sympy__codegen__cnodes__PostDecrement(): from sympy.codegen.cnodes import PostDecrement assert _test_args(PostDecrement(x)) def test_sympy__codegen__cnodes__PreIncrement(): from sympy.codegen.cnodes import PreIncrement assert _test_args(PreIncrement(x)) def test_sympy__codegen__cnodes__PostIncrement(): from sympy.codegen.cnodes import PostIncrement assert _test_args(PostIncrement(x)) def test_sympy__codegen__cnodes__struct(): from sympy.codegen.ast import real, Variable from sympy.codegen.cnodes import struct assert _test_args(struct(declarations=[ Variable(x, type=real), Variable(y, type=real) ])) def test_sympy__codegen__cnodes__union(): from sympy.codegen.ast import float32, int32, Variable from sympy.codegen.cnodes import union assert _test_args(union(declarations=[ Variable(x, type=float32), Variable(y, type=int32) ])) def test_sympy__codegen__cxxnodes__using(): from sympy.codegen.cxxnodes import using assert _test_args(using('std::vector')) assert _test_args(using('std::vector', 'vec')) def test_sympy__codegen__fnodes__Program(): from sympy.codegen.fnodes import Program assert _test_args(Program('foobar', [])) def test_sympy__codegen__fnodes__Module(): from sympy.codegen.fnodes import Module assert _test_args(Module('foobar', [], [])) def test_sympy__codegen__fnodes__Subroutine(): from sympy.codegen.fnodes import Subroutine x = symbols('x', real=True) assert _test_args(Subroutine('foo', [x], [])) def test_sympy__codegen__fnodes__GoTo(): from sympy.codegen.fnodes import GoTo assert _test_args(GoTo([10])) assert _test_args(GoTo([10, 20], x > 1)) def test_sympy__codegen__fnodes__FortranReturn(): from sympy.codegen.fnodes import FortranReturn assert _test_args(FortranReturn(10)) def test_sympy__codegen__fnodes__Extent(): from sympy.codegen.fnodes import Extent assert _test_args(Extent()) assert _test_args(Extent(None)) assert _test_args(Extent(':')) assert _test_args(Extent(-3, 4)) assert _test_args(Extent(x, y)) def test_sympy__codegen__fnodes__use_rename(): from sympy.codegen.fnodes import use_rename assert _test_args(use_rename('loc', 'glob')) def test_sympy__codegen__fnodes__use(): from sympy.codegen.fnodes import use assert _test_args(use('modfoo', only='bar')) def test_sympy__codegen__fnodes__SubroutineCall(): from sympy.codegen.fnodes import SubroutineCall assert _test_args(SubroutineCall('foo', ['bar', 'baz'])) def test_sympy__codegen__fnodes__Do(): from sympy.codegen.fnodes import Do assert _test_args(Do([], 'i', 1, 42)) def test_sympy__codegen__fnodes__ImpliedDoLoop(): from sympy.codegen.fnodes import ImpliedDoLoop assert _test_args(ImpliedDoLoop('i', 'i', 1, 42)) def test_sympy__codegen__fnodes__ArrayConstructor(): from sympy.codegen.fnodes import ArrayConstructor assert _test_args(ArrayConstructor([1, 2, 3])) from sympy.codegen.fnodes import ImpliedDoLoop idl = ImpliedDoLoop('i', 'i', 1, 42) assert _test_args(ArrayConstructor([1, idl, 3])) def test_sympy__codegen__fnodes__sum_(): from sympy.codegen.fnodes import sum_ assert _test_args(sum_('arr')) def test_sympy__codegen__fnodes__product_(): from sympy.codegen.fnodes import product_ assert _test_args(product_('arr')) def test_sympy__codegen__numpy_nodes__logaddexp(): from sympy.codegen.numpy_nodes import logaddexp assert _test_args(logaddexp(x, y)) def test_sympy__codegen__numpy_nodes__logaddexp2(): from sympy.codegen.numpy_nodes import logaddexp2 assert _test_args(logaddexp2(x, y)) def test_sympy__codegen__pynodes__List(): from sympy.codegen.pynodes import List assert _test_args(List(1, 2, 3)) def test_sympy__codegen__scipy_nodes__cosm1(): from sympy.codegen.scipy_nodes import cosm1 assert _test_args(cosm1(x)) def test_sympy__codegen__abstract_nodes__List(): from sympy.codegen.abstract_nodes import List assert _test_args(List(1, 2, 3)) def test_sympy__combinatorics__graycode__GrayCode(): from sympy.combinatorics.graycode import GrayCode # an integer is given and returned from GrayCode as the arg assert _test_args(GrayCode(3, start='100')) assert _test_args(GrayCode(3, rank=1)) def test_sympy__combinatorics__permutations__Permutation(): from sympy.combinatorics.permutations import Permutation assert _test_args(Permutation([0, 1, 2, 3])) def test_sympy__combinatorics__permutations__AppliedPermutation(): from sympy.combinatorics.permutations import Permutation from sympy.combinatorics.permutations import AppliedPermutation p = Permutation([0, 1, 2, 3]) assert _test_args(AppliedPermutation(p, 1)) def test_sympy__combinatorics__perm_groups__PermutationGroup(): from sympy.combinatorics.permutations import Permutation from sympy.combinatorics.perm_groups import PermutationGroup assert _test_args(PermutationGroup([Permutation([0, 1])])) def test_sympy__combinatorics__polyhedron__Polyhedron(): from sympy.combinatorics.permutations import Permutation from sympy.combinatorics.polyhedron import Polyhedron from sympy.abc import w, x, y, z pgroup = [Permutation([[0, 1, 2], [3]]), Permutation([[0, 1, 3], [2]]), Permutation([[0, 2, 3], [1]]), Permutation([[1, 2, 3], [0]]), Permutation([[0, 1], [2, 3]]), Permutation([[0, 2], [1, 3]]), Permutation([[0, 3], [1, 2]]), Permutation([[0, 1, 2, 3]])] corners = [w, x, y, z] faces = [(w, x, y), (w, y, z), (w, z, x), (x, y, z)] assert _test_args(Polyhedron(corners, faces, pgroup)) def test_sympy__combinatorics__prufer__Prufer(): from sympy.combinatorics.prufer import Prufer assert _test_args(Prufer([[0, 1], [0, 2], [0, 3]], 4)) def test_sympy__combinatorics__partitions__Partition(): from sympy.combinatorics.partitions import Partition assert _test_args(Partition([1])) def test_sympy__combinatorics__partitions__IntegerPartition(): from sympy.combinatorics.partitions import IntegerPartition assert _test_args(IntegerPartition([1])) def test_sympy__concrete__products__Product(): from sympy.concrete.products import Product assert _test_args(Product(x, (x, 0, 10))) assert _test_args(Product(x, (x, 0, y), (y, 0, 10))) @SKIP("abstract Class") def test_sympy__concrete__expr_with_limits__ExprWithLimits(): from sympy.concrete.expr_with_limits import ExprWithLimits assert _test_args(ExprWithLimits(x, (x, 0, 10))) assert _test_args(ExprWithLimits(x*y, (x, 0, 10.),(y,1.,3))) @SKIP("abstract Class") def test_sympy__concrete__expr_with_limits__AddWithLimits(): from sympy.concrete.expr_with_limits import AddWithLimits assert _test_args(AddWithLimits(x, (x, 0, 10))) assert _test_args(AddWithLimits(x*y, (x, 0, 10),(y,1,3))) @SKIP("abstract Class") def test_sympy__concrete__expr_with_intlimits__ExprWithIntLimits(): from sympy.concrete.expr_with_intlimits import ExprWithIntLimits assert _test_args(ExprWithIntLimits(x, (x, 0, 10))) assert _test_args(ExprWithIntLimits(x*y, (x, 0, 10),(y,1,3))) def test_sympy__concrete__summations__Sum(): from sympy.concrete.summations import Sum assert _test_args(Sum(x, (x, 0, 10))) assert _test_args(Sum(x, (x, 0, y), (y, 0, 10))) def test_sympy__core__add__Add(): from sympy.core.add import Add assert _test_args(Add(x, y, z, 2)) def test_sympy__core__basic__Atom(): from sympy.core.basic import Atom assert _test_args(Atom()) def test_sympy__core__basic__Basic(): from sympy.core.basic import Basic assert _test_args(Basic()) def test_sympy__core__containers__Dict(): from sympy.core.containers import Dict assert _test_args(Dict({x: y, y: z})) def test_sympy__core__containers__Tuple(): from sympy.core.containers import Tuple assert _test_args(Tuple(x, y, z, 2)) def test_sympy__core__expr__AtomicExpr(): from sympy.core.expr import AtomicExpr assert _test_args(AtomicExpr()) def test_sympy__core__expr__Expr(): from sympy.core.expr import Expr assert _test_args(Expr()) def test_sympy__core__expr__UnevaluatedExpr(): from sympy.core.expr import UnevaluatedExpr from sympy.abc import x assert _test_args(UnevaluatedExpr(x)) def test_sympy__core__function__Application(): from sympy.core.function import Application assert _test_args(Application(1, 2, 3)) def test_sympy__core__function__AppliedUndef(): from sympy.core.function import AppliedUndef assert _test_args(AppliedUndef(1, 2, 3)) def test_sympy__core__function__Derivative(): from sympy.core.function import Derivative assert _test_args(Derivative(2, x, y, 3)) @SKIP("abstract class") def test_sympy__core__function__Function(): pass def test_sympy__core__function__Lambda(): assert _test_args(Lambda((x, y), x + y + z)) def test_sympy__core__function__Subs(): from sympy.core.function import Subs assert _test_args(Subs(x + y, x, 2)) def test_sympy__core__function__WildFunction(): from sympy.core.function import WildFunction assert _test_args(WildFunction('f')) def test_sympy__core__mod__Mod(): from sympy.core.mod import Mod assert _test_args(Mod(x, 2)) def test_sympy__core__mul__Mul(): from sympy.core.mul import Mul assert _test_args(Mul(2, x, y, z)) def test_sympy__core__numbers__Catalan(): from sympy.core.numbers import Catalan assert _test_args(Catalan()) def test_sympy__core__numbers__ComplexInfinity(): from sympy.core.numbers import ComplexInfinity assert _test_args(ComplexInfinity()) def test_sympy__core__numbers__EulerGamma(): from sympy.core.numbers import EulerGamma assert _test_args(EulerGamma()) def test_sympy__core__numbers__Exp1(): from sympy.core.numbers import Exp1 assert _test_args(Exp1()) def test_sympy__core__numbers__Float(): from sympy.core.numbers import Float assert _test_args(Float(1.23)) def test_sympy__core__numbers__GoldenRatio(): from sympy.core.numbers import GoldenRatio assert _test_args(GoldenRatio()) def test_sympy__core__numbers__TribonacciConstant(): from sympy.core.numbers import TribonacciConstant assert _test_args(TribonacciConstant()) def test_sympy__core__numbers__Half(): from sympy.core.numbers import Half assert _test_args(Half()) def test_sympy__core__numbers__ImaginaryUnit(): from sympy.core.numbers import ImaginaryUnit assert _test_args(ImaginaryUnit()) def test_sympy__core__numbers__Infinity(): from sympy.core.numbers import Infinity assert _test_args(Infinity()) def test_sympy__core__numbers__Integer(): from sympy.core.numbers import Integer assert _test_args(Integer(7)) @SKIP("abstract class") def test_sympy__core__numbers__IntegerConstant(): pass def test_sympy__core__numbers__NaN(): from sympy.core.numbers import NaN assert _test_args(NaN()) def test_sympy__core__numbers__NegativeInfinity(): from sympy.core.numbers import NegativeInfinity assert _test_args(NegativeInfinity()) def test_sympy__core__numbers__NegativeOne(): from sympy.core.numbers import NegativeOne assert _test_args(NegativeOne()) def test_sympy__core__numbers__Number(): from sympy.core.numbers import Number assert _test_args(Number(1, 7)) def test_sympy__core__numbers__NumberSymbol(): from sympy.core.numbers import NumberSymbol assert _test_args(NumberSymbol()) def test_sympy__core__numbers__One(): from sympy.core.numbers import One assert _test_args(One()) def test_sympy__core__numbers__Pi(): from sympy.core.numbers import Pi assert _test_args(Pi()) def test_sympy__core__numbers__Rational(): from sympy.core.numbers import Rational assert _test_args(Rational(1, 7)) @SKIP("abstract class") def test_sympy__core__numbers__RationalConstant(): pass def test_sympy__core__numbers__Zero(): from sympy.core.numbers import Zero assert _test_args(Zero()) @SKIP("abstract class") def test_sympy__core__operations__AssocOp(): pass @SKIP("abstract class") def test_sympy__core__operations__LatticeOp(): pass def test_sympy__core__power__Pow(): from sympy.core.power import Pow assert _test_args(Pow(x, 2)) def test_sympy__core__relational__Equality(): from sympy.core.relational import Equality assert _test_args(Equality(x, 2)) def test_sympy__core__relational__GreaterThan(): from sympy.core.relational import GreaterThan assert _test_args(GreaterThan(x, 2)) def test_sympy__core__relational__LessThan(): from sympy.core.relational import LessThan assert _test_args(LessThan(x, 2)) @SKIP("abstract class") def test_sympy__core__relational__Relational(): pass def test_sympy__core__relational__StrictGreaterThan(): from sympy.core.relational import StrictGreaterThan assert _test_args(StrictGreaterThan(x, 2)) def test_sympy__core__relational__StrictLessThan(): from sympy.core.relational import StrictLessThan assert _test_args(StrictLessThan(x, 2)) def test_sympy__core__relational__Unequality(): from sympy.core.relational import Unequality assert _test_args(Unequality(x, 2)) @SKIP("deprecated class") def test_sympy__core__trace__Tr(): pass def test_sympy__sandbox__indexed_integrals__IndexedIntegral(): from sympy.tensor import IndexedBase, Idx from sympy.sandbox.indexed_integrals import IndexedIntegral A = IndexedBase('A') i, j = symbols('i j', integer=True) a1, a2 = symbols('a1:3', cls=Idx) assert _test_args(IndexedIntegral(A[a1], A[a2])) assert _test_args(IndexedIntegral(A[i], A[j])) def test_sympy__calculus__accumulationbounds__AccumulationBounds(): from sympy.calculus.accumulationbounds import AccumulationBounds assert _test_args(AccumulationBounds(0, 1)) def test_sympy__sets__ordinals__OmegaPower(): from sympy.sets.ordinals import OmegaPower assert _test_args(OmegaPower(1, 1)) def test_sympy__sets__ordinals__Ordinal(): from sympy.sets.ordinals import Ordinal, OmegaPower assert _test_args(Ordinal(OmegaPower(2, 1))) def test_sympy__sets__ordinals__OrdinalOmega(): from sympy.sets.ordinals import OrdinalOmega assert _test_args(OrdinalOmega()) def test_sympy__sets__ordinals__OrdinalZero(): from sympy.sets.ordinals import OrdinalZero assert _test_args(OrdinalZero()) def test_sympy__sets__powerset__PowerSet(): from sympy.sets.powerset import PowerSet from sympy.core.singleton import S assert _test_args(PowerSet(S.EmptySet)) def test_sympy__sets__sets__EmptySet(): from sympy.sets.sets import EmptySet assert _test_args(EmptySet()) def test_sympy__sets__sets__UniversalSet(): from sympy.sets.sets import UniversalSet assert _test_args(UniversalSet()) def test_sympy__sets__sets__FiniteSet(): from sympy.sets.sets import FiniteSet assert _test_args(FiniteSet(x, y, z)) def test_sympy__sets__sets__Interval(): from sympy.sets.sets import Interval assert _test_args(Interval(0, 1)) def test_sympy__sets__sets__ProductSet(): from sympy.sets.sets import ProductSet, Interval assert _test_args(ProductSet(Interval(0, 1), Interval(0, 1))) @SKIP("does it make sense to test this?") def test_sympy__sets__sets__Set(): from sympy.sets.sets import Set assert _test_args(Set()) def test_sympy__sets__sets__Intersection(): from sympy.sets.sets import Intersection, Interval from sympy.core.symbol import Symbol x = Symbol('x') y = Symbol('y') S = Intersection(Interval(0, x), Interval(y, 1)) assert isinstance(S, Intersection) assert _test_args(S) def test_sympy__sets__sets__Union(): from sympy.sets.sets import Union, Interval assert _test_args(Union(Interval(0, 1), Interval(2, 3))) def test_sympy__sets__sets__Complement(): from sympy.sets.sets import Complement, Interval assert _test_args(Complement(Interval(0, 2), Interval(0, 1))) def test_sympy__sets__sets__SymmetricDifference(): from sympy.sets.sets import FiniteSet, SymmetricDifference assert _test_args(SymmetricDifference(FiniteSet(1, 2, 3), \ FiniteSet(2, 3, 4))) def test_sympy__sets__sets__DisjointUnion(): from sympy.sets.sets import FiniteSet, DisjointUnion assert _test_args(DisjointUnion(FiniteSet(1, 2, 3), \ FiniteSet(2, 3, 4))) def test_sympy__physics__quantum__trace__Tr(): from sympy.physics.quantum.trace import Tr a, b = symbols('a b') assert _test_args(Tr(a + b)) def test_sympy__sets__setexpr__SetExpr(): from sympy.sets.setexpr import SetExpr from sympy.sets.sets import Interval assert _test_args(SetExpr(Interval(0, 1))) def test_sympy__sets__fancysets__Rationals(): from sympy.sets.fancysets import Rationals assert _test_args(Rationals()) def test_sympy__sets__fancysets__Naturals(): from sympy.sets.fancysets import Naturals assert _test_args(Naturals()) def test_sympy__sets__fancysets__Naturals0(): from sympy.sets.fancysets import Naturals0 assert _test_args(Naturals0()) def test_sympy__sets__fancysets__Integers(): from sympy.sets.fancysets import Integers assert _test_args(Integers()) def test_sympy__sets__fancysets__Reals(): from sympy.sets.fancysets import Reals assert _test_args(Reals()) def test_sympy__sets__fancysets__Complexes(): from sympy.sets.fancysets import Complexes assert _test_args(Complexes()) def test_sympy__sets__fancysets__ComplexRegion(): from sympy.sets.fancysets import ComplexRegion from sympy.core.singleton import S from sympy.sets import Interval a = Interval(0, 1) b = Interval(2, 3) theta = Interval(0, 2*S.Pi) assert _test_args(ComplexRegion(a*b)) assert _test_args(ComplexRegion(a*theta, polar=True)) def test_sympy__sets__fancysets__CartesianComplexRegion(): from sympy.sets.fancysets import CartesianComplexRegion from sympy.sets import Interval a = Interval(0, 1) b = Interval(2, 3) assert _test_args(CartesianComplexRegion(a*b)) def test_sympy__sets__fancysets__PolarComplexRegion(): from sympy.sets.fancysets import PolarComplexRegion from sympy.core.singleton import S from sympy.sets import Interval a = Interval(0, 1) theta = Interval(0, 2*S.Pi) assert _test_args(PolarComplexRegion(a*theta)) def test_sympy__sets__fancysets__ImageSet(): from sympy.sets.fancysets import ImageSet from sympy.core.singleton import S from sympy.core.symbol import Symbol x = Symbol('x') assert _test_args(ImageSet(Lambda(x, x**2), S.Naturals)) def test_sympy__sets__fancysets__Range(): from sympy.sets.fancysets import Range assert _test_args(Range(1, 5, 1)) def test_sympy__sets__conditionset__ConditionSet(): from sympy.sets.conditionset import ConditionSet from sympy.core.singleton import S from sympy.core.symbol import Symbol x = Symbol('x') assert _test_args(ConditionSet(x, Eq(x**2, 1), S.Reals)) def test_sympy__sets__contains__Contains(): from sympy.sets.fancysets import Range from sympy.sets.contains import Contains assert _test_args(Contains(x, Range(0, 10, 2))) # STATS from sympy.stats.crv_types import NormalDistribution nd = NormalDistribution(0, 1) from sympy.stats.frv_types import DieDistribution die = DieDistribution(6) def test_sympy__stats__crv__ContinuousDomain(): from sympy.sets.sets import Interval from sympy.stats.crv import ContinuousDomain assert _test_args(ContinuousDomain({x}, Interval(-oo, oo))) def test_sympy__stats__crv__SingleContinuousDomain(): from sympy.sets.sets import Interval from sympy.stats.crv import SingleContinuousDomain assert _test_args(SingleContinuousDomain(x, Interval(-oo, oo))) def test_sympy__stats__crv__ProductContinuousDomain(): from sympy.sets.sets import Interval from sympy.stats.crv import SingleContinuousDomain, ProductContinuousDomain D = SingleContinuousDomain(x, Interval(-oo, oo)) E = SingleContinuousDomain(y, Interval(0, oo)) assert _test_args(ProductContinuousDomain(D, E)) def test_sympy__stats__crv__ConditionalContinuousDomain(): from sympy.sets.sets import Interval from sympy.stats.crv import (SingleContinuousDomain, ConditionalContinuousDomain) D = SingleContinuousDomain(x, Interval(-oo, oo)) assert _test_args(ConditionalContinuousDomain(D, x > 0)) def test_sympy__stats__crv__ContinuousPSpace(): from sympy.sets.sets import Interval from sympy.stats.crv import ContinuousPSpace, SingleContinuousDomain D = SingleContinuousDomain(x, Interval(-oo, oo)) assert _test_args(ContinuousPSpace(D, nd)) def test_sympy__stats__crv__SingleContinuousPSpace(): from sympy.stats.crv import SingleContinuousPSpace assert _test_args(SingleContinuousPSpace(x, nd)) @SKIP("abstract class") def test_sympy__stats__rv__Distribution(): pass @SKIP("abstract class") def test_sympy__stats__crv__SingleContinuousDistribution(): pass def test_sympy__stats__drv__SingleDiscreteDomain(): from sympy.stats.drv import SingleDiscreteDomain assert _test_args(SingleDiscreteDomain(x, S.Naturals)) def test_sympy__stats__drv__ProductDiscreteDomain(): from sympy.stats.drv import SingleDiscreteDomain, ProductDiscreteDomain X = SingleDiscreteDomain(x, S.Naturals) Y = SingleDiscreteDomain(y, S.Integers) assert _test_args(ProductDiscreteDomain(X, Y)) def test_sympy__stats__drv__SingleDiscretePSpace(): from sympy.stats.drv import SingleDiscretePSpace from sympy.stats.drv_types import PoissonDistribution assert _test_args(SingleDiscretePSpace(x, PoissonDistribution(1))) def test_sympy__stats__drv__DiscretePSpace(): from sympy.stats.drv import DiscretePSpace, SingleDiscreteDomain density = Lambda(x, 2**(-x)) domain = SingleDiscreteDomain(x, S.Naturals) assert _test_args(DiscretePSpace(domain, density)) def test_sympy__stats__drv__ConditionalDiscreteDomain(): from sympy.stats.drv import ConditionalDiscreteDomain, SingleDiscreteDomain X = SingleDiscreteDomain(x, S.Naturals0) assert _test_args(ConditionalDiscreteDomain(X, x > 2)) def test_sympy__stats__joint_rv__JointPSpace(): from sympy.stats.joint_rv import JointPSpace, JointDistribution assert _test_args(JointPSpace('X', JointDistribution(1))) def test_sympy__stats__joint_rv__JointRandomSymbol(): from sympy.stats.joint_rv import JointRandomSymbol assert _test_args(JointRandomSymbol(x)) def test_sympy__stats__joint_rv_types__JointDistributionHandmade(): from sympy.tensor.indexed import Indexed from sympy.stats.joint_rv_types import JointDistributionHandmade x1, x2 = (Indexed('x', i) for i in (1, 2)) assert _test_args(JointDistributionHandmade(x1 + x2, S.Reals**2)) def test_sympy__stats__joint_rv__MarginalDistribution(): from sympy.stats.rv import RandomSymbol from sympy.stats.joint_rv import MarginalDistribution r = RandomSymbol(S('r')) assert _test_args(MarginalDistribution(r, (r,))) def test_sympy__stats__compound_rv__CompoundDistribution(): from sympy.stats.compound_rv import CompoundDistribution from sympy.stats.drv_types import PoissonDistribution, Poisson r = Poisson('r', 10) assert _test_args(CompoundDistribution(PoissonDistribution(r))) def test_sympy__stats__compound_rv__CompoundPSpace(): from sympy.stats.compound_rv import CompoundPSpace, CompoundDistribution from sympy.stats.drv_types import PoissonDistribution, Poisson r = Poisson('r', 5) C = CompoundDistribution(PoissonDistribution(r)) assert _test_args(CompoundPSpace('C', C)) @SKIP("abstract class") def test_sympy__stats__drv__SingleDiscreteDistribution(): pass @SKIP("abstract class") def test_sympy__stats__drv__DiscreteDistribution(): pass @SKIP("abstract class") def test_sympy__stats__drv__DiscreteDomain(): pass def test_sympy__stats__rv__RandomDomain(): from sympy.stats.rv import RandomDomain from sympy.sets.sets import FiniteSet assert _test_args(RandomDomain(FiniteSet(x), FiniteSet(1, 2, 3))) def test_sympy__stats__rv__SingleDomain(): from sympy.stats.rv import SingleDomain from sympy.sets.sets import FiniteSet assert _test_args(SingleDomain(x, FiniteSet(1, 2, 3))) def test_sympy__stats__rv__ConditionalDomain(): from sympy.stats.rv import ConditionalDomain, RandomDomain from sympy.sets.sets import FiniteSet D = RandomDomain(FiniteSet(x), FiniteSet(1, 2)) assert _test_args(ConditionalDomain(D, x > 1)) def test_sympy__stats__rv__MatrixDomain(): from sympy.stats.rv import MatrixDomain from sympy.matrices import MatrixSet from sympy.core.singleton import S assert _test_args(MatrixDomain(x, MatrixSet(2, 2, S.Reals))) def test_sympy__stats__rv__PSpace(): from sympy.stats.rv import PSpace, RandomDomain from sympy.sets.sets import FiniteSet D = RandomDomain(FiniteSet(x), FiniteSet(1, 2, 3, 4, 5, 6)) assert _test_args(PSpace(D, die)) @SKIP("abstract Class") def test_sympy__stats__rv__SinglePSpace(): pass def test_sympy__stats__rv__RandomSymbol(): from sympy.stats.rv import RandomSymbol from sympy.stats.crv import SingleContinuousPSpace A = SingleContinuousPSpace(x, nd) assert _test_args(RandomSymbol(x, A)) @SKIP("abstract Class") def test_sympy__stats__rv__ProductPSpace(): pass def test_sympy__stats__rv__IndependentProductPSpace(): from sympy.stats.rv import IndependentProductPSpace from sympy.stats.crv import SingleContinuousPSpace A = SingleContinuousPSpace(x, nd) B = SingleContinuousPSpace(y, nd) assert _test_args(IndependentProductPSpace(A, B)) def test_sympy__stats__rv__ProductDomain(): from sympy.sets.sets import Interval from sympy.stats.rv import ProductDomain, SingleDomain D = SingleDomain(x, Interval(-oo, oo)) E = SingleDomain(y, Interval(0, oo)) assert _test_args(ProductDomain(D, E)) def test_sympy__stats__symbolic_probability__Probability(): from sympy.stats.symbolic_probability import Probability from sympy.stats import Normal X = Normal('X', 0, 1) assert _test_args(Probability(X > 0)) def test_sympy__stats__symbolic_probability__Expectation(): from sympy.stats.symbolic_probability import Expectation from sympy.stats import Normal X = Normal('X', 0, 1) assert _test_args(Expectation(X > 0)) def test_sympy__stats__symbolic_probability__Covariance(): from sympy.stats.symbolic_probability import Covariance from sympy.stats import Normal X = Normal('X', 0, 1) Y = Normal('Y', 0, 3) assert _test_args(Covariance(X, Y)) def test_sympy__stats__symbolic_probability__Variance(): from sympy.stats.symbolic_probability import Variance from sympy.stats import Normal X = Normal('X', 0, 1) assert _test_args(Variance(X)) def test_sympy__stats__symbolic_probability__Moment(): from sympy.stats.symbolic_probability import Moment from sympy.stats import Normal X = Normal('X', 0, 1) assert _test_args(Moment(X, 3, 2, X > 3)) def test_sympy__stats__symbolic_probability__CentralMoment(): from sympy.stats.symbolic_probability import CentralMoment from sympy.stats import Normal X = Normal('X', 0, 1) assert _test_args(CentralMoment(X, 2, X > 1)) def test_sympy__stats__frv_types__DiscreteUniformDistribution(): from sympy.stats.frv_types import DiscreteUniformDistribution from sympy.core.containers import Tuple assert _test_args(DiscreteUniformDistribution(Tuple(*list(range(6))))) def test_sympy__stats__frv_types__DieDistribution(): assert _test_args(die) def test_sympy__stats__frv_types__BernoulliDistribution(): from sympy.stats.frv_types import BernoulliDistribution assert _test_args(BernoulliDistribution(S.Half, 0, 1)) def test_sympy__stats__frv_types__BinomialDistribution(): from sympy.stats.frv_types import BinomialDistribution assert _test_args(BinomialDistribution(5, S.Half, 1, 0)) def test_sympy__stats__frv_types__BetaBinomialDistribution(): from sympy.stats.frv_types import BetaBinomialDistribution assert _test_args(BetaBinomialDistribution(5, 1, 1)) def test_sympy__stats__frv_types__HypergeometricDistribution(): from sympy.stats.frv_types import HypergeometricDistribution assert _test_args(HypergeometricDistribution(10, 5, 3)) def test_sympy__stats__frv_types__RademacherDistribution(): from sympy.stats.frv_types import RademacherDistribution assert _test_args(RademacherDistribution()) def test_sympy__stats__frv_types__IdealSolitonDistribution(): from sympy.stats.frv_types import IdealSolitonDistribution assert _test_args(IdealSolitonDistribution(10)) def test_sympy__stats__frv_types__RobustSolitonDistribution(): from sympy.stats.frv_types import RobustSolitonDistribution assert _test_args(RobustSolitonDistribution(1000, 0.5, 0.1)) def test_sympy__stats__frv__FiniteDomain(): from sympy.stats.frv import FiniteDomain assert _test_args(FiniteDomain({(x, 1), (x, 2)})) # x can be 1 or 2 def test_sympy__stats__frv__SingleFiniteDomain(): from sympy.stats.frv import SingleFiniteDomain assert _test_args(SingleFiniteDomain(x, {1, 2})) # x can be 1 or 2 def test_sympy__stats__frv__ProductFiniteDomain(): from sympy.stats.frv import SingleFiniteDomain, ProductFiniteDomain xd = SingleFiniteDomain(x, {1, 2}) yd = SingleFiniteDomain(y, {1, 2}) assert _test_args(ProductFiniteDomain(xd, yd)) def test_sympy__stats__frv__ConditionalFiniteDomain(): from sympy.stats.frv import SingleFiniteDomain, ConditionalFiniteDomain xd = SingleFiniteDomain(x, {1, 2}) assert _test_args(ConditionalFiniteDomain(xd, x > 1)) def test_sympy__stats__frv__FinitePSpace(): from sympy.stats.frv import FinitePSpace, SingleFiniteDomain xd = SingleFiniteDomain(x, {1, 2, 3, 4, 5, 6}) assert _test_args(FinitePSpace(xd, {(x, 1): S.Half, (x, 2): S.Half})) xd = SingleFiniteDomain(x, {1, 2}) assert _test_args(FinitePSpace(xd, {(x, 1): S.Half, (x, 2): S.Half})) def test_sympy__stats__frv__SingleFinitePSpace(): from sympy.stats.frv import SingleFinitePSpace from sympy.core.symbol import Symbol assert _test_args(SingleFinitePSpace(Symbol('x'), die)) def test_sympy__stats__frv__ProductFinitePSpace(): from sympy.stats.frv import SingleFinitePSpace, ProductFinitePSpace from sympy.core.symbol import Symbol xp = SingleFinitePSpace(Symbol('x'), die) yp = SingleFinitePSpace(Symbol('y'), die) assert _test_args(ProductFinitePSpace(xp, yp)) @SKIP("abstract class") def test_sympy__stats__frv__SingleFiniteDistribution(): pass @SKIP("abstract class") def test_sympy__stats__crv__ContinuousDistribution(): pass def test_sympy__stats__frv_types__FiniteDistributionHandmade(): from sympy.stats.frv_types import FiniteDistributionHandmade from sympy.core.containers import Dict assert _test_args(FiniteDistributionHandmade(Dict({1: 1}))) def test_sympy__stats__crv_types__ContinuousDistributionHandmade(): from sympy.stats.crv_types import ContinuousDistributionHandmade from sympy.core.function import Lambda from sympy.sets.sets import Interval from sympy.abc import x assert _test_args(ContinuousDistributionHandmade(Lambda(x, 2*x), Interval(0, 1))) def test_sympy__stats__drv_types__DiscreteDistributionHandmade(): from sympy.stats.drv_types import DiscreteDistributionHandmade from sympy.core.function import Lambda from sympy.sets.sets import FiniteSet from sympy.abc import x assert _test_args(DiscreteDistributionHandmade(Lambda(x, Rational(1, 10)), FiniteSet(*range(10)))) def test_sympy__stats__rv__Density(): from sympy.stats.rv import Density from sympy.stats.crv_types import Normal assert _test_args(Density(Normal('x', 0, 1))) def test_sympy__stats__crv_types__ArcsinDistribution(): from sympy.stats.crv_types import ArcsinDistribution assert _test_args(ArcsinDistribution(0, 1)) def test_sympy__stats__crv_types__BeniniDistribution(): from sympy.stats.crv_types import BeniniDistribution assert _test_args(BeniniDistribution(1, 1, 1)) def test_sympy__stats__crv_types__BetaDistribution(): from sympy.stats.crv_types import BetaDistribution assert _test_args(BetaDistribution(1, 1)) def test_sympy__stats__crv_types__BetaNoncentralDistribution(): from sympy.stats.crv_types import BetaNoncentralDistribution assert _test_args(BetaNoncentralDistribution(1, 1, 1)) def test_sympy__stats__crv_types__BetaPrimeDistribution(): from sympy.stats.crv_types import BetaPrimeDistribution assert _test_args(BetaPrimeDistribution(1, 1)) def test_sympy__stats__crv_types__BoundedParetoDistribution(): from sympy.stats.crv_types import BoundedParetoDistribution assert _test_args(BoundedParetoDistribution(1, 1, 2)) def test_sympy__stats__crv_types__CauchyDistribution(): from sympy.stats.crv_types import CauchyDistribution assert _test_args(CauchyDistribution(0, 1)) def test_sympy__stats__crv_types__ChiDistribution(): from sympy.stats.crv_types import ChiDistribution assert _test_args(ChiDistribution(1)) def test_sympy__stats__crv_types__ChiNoncentralDistribution(): from sympy.stats.crv_types import ChiNoncentralDistribution assert _test_args(ChiNoncentralDistribution(1,1)) def test_sympy__stats__crv_types__ChiSquaredDistribution(): from sympy.stats.crv_types import ChiSquaredDistribution assert _test_args(ChiSquaredDistribution(1)) def test_sympy__stats__crv_types__DagumDistribution(): from sympy.stats.crv_types import DagumDistribution assert _test_args(DagumDistribution(1, 1, 1)) def test_sympy__stats__crv_types__ExGaussianDistribution(): from sympy.stats.crv_types import ExGaussianDistribution assert _test_args(ExGaussianDistribution(1, 1, 1)) def test_sympy__stats__crv_types__ExponentialDistribution(): from sympy.stats.crv_types import ExponentialDistribution assert _test_args(ExponentialDistribution(1)) def test_sympy__stats__crv_types__ExponentialPowerDistribution(): from sympy.stats.crv_types import ExponentialPowerDistribution assert _test_args(ExponentialPowerDistribution(0, 1, 1)) def test_sympy__stats__crv_types__FDistributionDistribution(): from sympy.stats.crv_types import FDistributionDistribution assert _test_args(FDistributionDistribution(1, 1)) def test_sympy__stats__crv_types__FisherZDistribution(): from sympy.stats.crv_types import FisherZDistribution assert _test_args(FisherZDistribution(1, 1)) def test_sympy__stats__crv_types__FrechetDistribution(): from sympy.stats.crv_types import FrechetDistribution assert _test_args(FrechetDistribution(1, 1, 1)) def test_sympy__stats__crv_types__GammaInverseDistribution(): from sympy.stats.crv_types import GammaInverseDistribution assert _test_args(GammaInverseDistribution(1, 1)) def test_sympy__stats__crv_types__GammaDistribution(): from sympy.stats.crv_types import GammaDistribution assert _test_args(GammaDistribution(1, 1)) def test_sympy__stats__crv_types__GumbelDistribution(): from sympy.stats.crv_types import GumbelDistribution assert _test_args(GumbelDistribution(1, 1, False)) def test_sympy__stats__crv_types__GompertzDistribution(): from sympy.stats.crv_types import GompertzDistribution assert _test_args(GompertzDistribution(1, 1)) def test_sympy__stats__crv_types__KumaraswamyDistribution(): from sympy.stats.crv_types import KumaraswamyDistribution assert _test_args(KumaraswamyDistribution(1, 1)) def test_sympy__stats__crv_types__LaplaceDistribution(): from sympy.stats.crv_types import LaplaceDistribution assert _test_args(LaplaceDistribution(0, 1)) def test_sympy__stats__crv_types__LevyDistribution(): from sympy.stats.crv_types import LevyDistribution assert _test_args(LevyDistribution(0, 1)) def test_sympy__stats__crv_types__LogCauchyDistribution(): from sympy.stats.crv_types import LogCauchyDistribution assert _test_args(LogCauchyDistribution(0, 1)) def test_sympy__stats__crv_types__LogisticDistribution(): from sympy.stats.crv_types import LogisticDistribution assert _test_args(LogisticDistribution(0, 1)) def test_sympy__stats__crv_types__LogLogisticDistribution(): from sympy.stats.crv_types import LogLogisticDistribution assert _test_args(LogLogisticDistribution(1, 1)) def test_sympy__stats__crv_types__LogitNormalDistribution(): from sympy.stats.crv_types import LogitNormalDistribution assert _test_args(LogitNormalDistribution(0, 1)) def test_sympy__stats__crv_types__LogNormalDistribution(): from sympy.stats.crv_types import LogNormalDistribution assert _test_args(LogNormalDistribution(0, 1)) def test_sympy__stats__crv_types__LomaxDistribution(): from sympy.stats.crv_types import LomaxDistribution assert _test_args(LomaxDistribution(1, 2)) def test_sympy__stats__crv_types__MaxwellDistribution(): from sympy.stats.crv_types import MaxwellDistribution assert _test_args(MaxwellDistribution(1)) def test_sympy__stats__crv_types__MoyalDistribution(): from sympy.stats.crv_types import MoyalDistribution assert _test_args(MoyalDistribution(1,2)) def test_sympy__stats__crv_types__NakagamiDistribution(): from sympy.stats.crv_types import NakagamiDistribution assert _test_args(NakagamiDistribution(1, 1)) def test_sympy__stats__crv_types__NormalDistribution(): from sympy.stats.crv_types import NormalDistribution assert _test_args(NormalDistribution(0, 1)) def test_sympy__stats__crv_types__GaussianInverseDistribution(): from sympy.stats.crv_types import GaussianInverseDistribution assert _test_args(GaussianInverseDistribution(1, 1)) def test_sympy__stats__crv_types__ParetoDistribution(): from sympy.stats.crv_types import ParetoDistribution assert _test_args(ParetoDistribution(1, 1)) def test_sympy__stats__crv_types__PowerFunctionDistribution(): from sympy.stats.crv_types import PowerFunctionDistribution assert _test_args(PowerFunctionDistribution(2,0,1)) def test_sympy__stats__crv_types__QuadraticUDistribution(): from sympy.stats.crv_types import QuadraticUDistribution assert _test_args(QuadraticUDistribution(1, 2)) def test_sympy__stats__crv_types__RaisedCosineDistribution(): from sympy.stats.crv_types import RaisedCosineDistribution assert _test_args(RaisedCosineDistribution(1, 1)) def test_sympy__stats__crv_types__RayleighDistribution(): from sympy.stats.crv_types import RayleighDistribution assert _test_args(RayleighDistribution(1)) def test_sympy__stats__crv_types__ReciprocalDistribution(): from sympy.stats.crv_types import ReciprocalDistribution assert _test_args(ReciprocalDistribution(5, 30)) def test_sympy__stats__crv_types__ShiftedGompertzDistribution(): from sympy.stats.crv_types import ShiftedGompertzDistribution assert _test_args(ShiftedGompertzDistribution(1, 1)) def test_sympy__stats__crv_types__StudentTDistribution(): from sympy.stats.crv_types import StudentTDistribution assert _test_args(StudentTDistribution(1)) def test_sympy__stats__crv_types__TrapezoidalDistribution(): from sympy.stats.crv_types import TrapezoidalDistribution assert _test_args(TrapezoidalDistribution(1, 2, 3, 4)) def test_sympy__stats__crv_types__TriangularDistribution(): from sympy.stats.crv_types import TriangularDistribution assert _test_args(TriangularDistribution(-1, 0, 1)) def test_sympy__stats__crv_types__UniformDistribution(): from sympy.stats.crv_types import UniformDistribution assert _test_args(UniformDistribution(0, 1)) def test_sympy__stats__crv_types__UniformSumDistribution(): from sympy.stats.crv_types import UniformSumDistribution assert _test_args(UniformSumDistribution(1)) def test_sympy__stats__crv_types__VonMisesDistribution(): from sympy.stats.crv_types import VonMisesDistribution assert _test_args(VonMisesDistribution(1, 1)) def test_sympy__stats__crv_types__WeibullDistribution(): from sympy.stats.crv_types import WeibullDistribution assert _test_args(WeibullDistribution(1, 1)) def test_sympy__stats__crv_types__WignerSemicircleDistribution(): from sympy.stats.crv_types import WignerSemicircleDistribution assert _test_args(WignerSemicircleDistribution(1)) def test_sympy__stats__drv_types__GeometricDistribution(): from sympy.stats.drv_types import GeometricDistribution assert _test_args(GeometricDistribution(.5)) def test_sympy__stats__drv_types__HermiteDistribution(): from sympy.stats.drv_types import HermiteDistribution assert _test_args(HermiteDistribution(1, 2)) def test_sympy__stats__drv_types__LogarithmicDistribution(): from sympy.stats.drv_types import LogarithmicDistribution assert _test_args(LogarithmicDistribution(.5)) def test_sympy__stats__drv_types__NegativeBinomialDistribution(): from sympy.stats.drv_types import NegativeBinomialDistribution assert _test_args(NegativeBinomialDistribution(.5, .5)) def test_sympy__stats__drv_types__FlorySchulzDistribution(): from sympy.stats.drv_types import FlorySchulzDistribution assert _test_args(FlorySchulzDistribution(.5)) def test_sympy__stats__drv_types__PoissonDistribution(): from sympy.stats.drv_types import PoissonDistribution assert _test_args(PoissonDistribution(1)) def test_sympy__stats__drv_types__SkellamDistribution(): from sympy.stats.drv_types import SkellamDistribution assert _test_args(SkellamDistribution(1, 1)) def test_sympy__stats__drv_types__YuleSimonDistribution(): from sympy.stats.drv_types import YuleSimonDistribution assert _test_args(YuleSimonDistribution(.5)) def test_sympy__stats__drv_types__ZetaDistribution(): from sympy.stats.drv_types import ZetaDistribution assert _test_args(ZetaDistribution(1.5)) def test_sympy__stats__joint_rv__JointDistribution(): from sympy.stats.joint_rv import JointDistribution assert _test_args(JointDistribution(1, 2, 3, 4)) def test_sympy__stats__joint_rv_types__MultivariateNormalDistribution(): from sympy.stats.joint_rv_types import MultivariateNormalDistribution assert _test_args( MultivariateNormalDistribution([0, 1], [[1, 0],[0, 1]])) def test_sympy__stats__joint_rv_types__MultivariateLaplaceDistribution(): from sympy.stats.joint_rv_types import MultivariateLaplaceDistribution assert _test_args(MultivariateLaplaceDistribution([0, 1], [[1, 0],[0, 1]])) def test_sympy__stats__joint_rv_types__MultivariateTDistribution(): from sympy.stats.joint_rv_types import MultivariateTDistribution assert _test_args(MultivariateTDistribution([0, 1], [[1, 0],[0, 1]], 1)) def test_sympy__stats__joint_rv_types__NormalGammaDistribution(): from sympy.stats.joint_rv_types import NormalGammaDistribution assert _test_args(NormalGammaDistribution(1, 2, 3, 4)) def test_sympy__stats__joint_rv_types__GeneralizedMultivariateLogGammaDistribution(): from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGammaDistribution v, l, mu = (4, [1, 2, 3, 4], [1, 2, 3, 4]) assert _test_args(GeneralizedMultivariateLogGammaDistribution(S.Half, v, l, mu)) def test_sympy__stats__joint_rv_types__MultivariateBetaDistribution(): from sympy.stats.joint_rv_types import MultivariateBetaDistribution assert _test_args(MultivariateBetaDistribution([1, 2, 3])) def test_sympy__stats__joint_rv_types__MultivariateEwensDistribution(): from sympy.stats.joint_rv_types import MultivariateEwensDistribution assert _test_args(MultivariateEwensDistribution(5, 1)) def test_sympy__stats__joint_rv_types__MultinomialDistribution(): from sympy.stats.joint_rv_types import MultinomialDistribution assert _test_args(MultinomialDistribution(5, [0.5, 0.1, 0.3])) def test_sympy__stats__joint_rv_types__NegativeMultinomialDistribution(): from sympy.stats.joint_rv_types import NegativeMultinomialDistribution assert _test_args(NegativeMultinomialDistribution(5, [0.5, 0.1, 0.3])) def test_sympy__stats__rv__RandomIndexedSymbol(): from sympy.stats.rv import RandomIndexedSymbol, pspace from sympy.stats.stochastic_process_types import DiscreteMarkovChain X = DiscreteMarkovChain("X") assert _test_args(RandomIndexedSymbol(X[0].symbol, pspace(X[0]))) def test_sympy__stats__rv__RandomMatrixSymbol(): from sympy.stats.rv import RandomMatrixSymbol from sympy.stats.random_matrix import RandomMatrixPSpace pspace = RandomMatrixPSpace('P') assert _test_args(RandomMatrixSymbol('M', 3, 3, pspace)) def test_sympy__stats__stochastic_process__StochasticPSpace(): from sympy.stats.stochastic_process import StochasticPSpace from sympy.stats.stochastic_process_types import StochasticProcess from sympy.stats.frv_types import BernoulliDistribution assert _test_args(StochasticPSpace("Y", StochasticProcess("Y", [1, 2, 3]), BernoulliDistribution(S.Half, 1, 0))) def test_sympy__stats__stochastic_process_types__StochasticProcess(): from sympy.stats.stochastic_process_types import StochasticProcess assert _test_args(StochasticProcess("Y", [1, 2, 3])) def test_sympy__stats__stochastic_process_types__MarkovProcess(): from sympy.stats.stochastic_process_types import MarkovProcess assert _test_args(MarkovProcess("Y", [1, 2, 3])) def test_sympy__stats__stochastic_process_types__DiscreteTimeStochasticProcess(): from sympy.stats.stochastic_process_types import DiscreteTimeStochasticProcess assert _test_args(DiscreteTimeStochasticProcess("Y", [1, 2, 3])) def test_sympy__stats__stochastic_process_types__ContinuousTimeStochasticProcess(): from sympy.stats.stochastic_process_types import ContinuousTimeStochasticProcess assert _test_args(ContinuousTimeStochasticProcess("Y", [1, 2, 3])) def test_sympy__stats__stochastic_process_types__TransitionMatrixOf(): from sympy.stats.stochastic_process_types import TransitionMatrixOf, DiscreteMarkovChain from sympy.matrices.expressions.matexpr import MatrixSymbol DMC = DiscreteMarkovChain("Y") assert _test_args(TransitionMatrixOf(DMC, MatrixSymbol('T', 3, 3))) def test_sympy__stats__stochastic_process_types__GeneratorMatrixOf(): from sympy.stats.stochastic_process_types import GeneratorMatrixOf, ContinuousMarkovChain from sympy.matrices.expressions.matexpr import MatrixSymbol DMC = ContinuousMarkovChain("Y") assert _test_args(GeneratorMatrixOf(DMC, MatrixSymbol('T', 3, 3))) def test_sympy__stats__stochastic_process_types__StochasticStateSpaceOf(): from sympy.stats.stochastic_process_types import StochasticStateSpaceOf, DiscreteMarkovChain DMC = DiscreteMarkovChain("Y") assert _test_args(StochasticStateSpaceOf(DMC, [0, 1, 2])) def test_sympy__stats__stochastic_process_types__DiscreteMarkovChain(): from sympy.stats.stochastic_process_types import DiscreteMarkovChain from sympy.matrices.expressions.matexpr import MatrixSymbol assert _test_args(DiscreteMarkovChain("Y", [0, 1, 2], MatrixSymbol('T', 3, 3))) def test_sympy__stats__stochastic_process_types__ContinuousMarkovChain(): from sympy.stats.stochastic_process_types import ContinuousMarkovChain from sympy.matrices.expressions.matexpr import MatrixSymbol assert _test_args(ContinuousMarkovChain("Y", [0, 1, 2], MatrixSymbol('T', 3, 3))) def test_sympy__stats__stochastic_process_types__BernoulliProcess(): from sympy.stats.stochastic_process_types import BernoulliProcess assert _test_args(BernoulliProcess("B", 0.5, 1, 0)) def test_sympy__stats__stochastic_process_types__CountingProcess(): from sympy.stats.stochastic_process_types import CountingProcess assert _test_args(CountingProcess("C")) def test_sympy__stats__stochastic_process_types__PoissonProcess(): from sympy.stats.stochastic_process_types import PoissonProcess assert _test_args(PoissonProcess("X", 2)) def test_sympy__stats__stochastic_process_types__WienerProcess(): from sympy.stats.stochastic_process_types import WienerProcess assert _test_args(WienerProcess("X")) def test_sympy__stats__stochastic_process_types__GammaProcess(): from sympy.stats.stochastic_process_types import GammaProcess assert _test_args(GammaProcess("X", 1, 2)) def test_sympy__stats__random_matrix__RandomMatrixPSpace(): from sympy.stats.random_matrix import RandomMatrixPSpace from sympy.stats.random_matrix_models import RandomMatrixEnsembleModel model = RandomMatrixEnsembleModel('R', 3) assert _test_args(RandomMatrixPSpace('P', model=model)) def test_sympy__stats__random_matrix_models__RandomMatrixEnsembleModel(): from sympy.stats.random_matrix_models import RandomMatrixEnsembleModel assert _test_args(RandomMatrixEnsembleModel('R', 3)) def test_sympy__stats__random_matrix_models__GaussianEnsembleModel(): from sympy.stats.random_matrix_models import GaussianEnsembleModel assert _test_args(GaussianEnsembleModel('G', 3)) def test_sympy__stats__random_matrix_models__GaussianUnitaryEnsembleModel(): from sympy.stats.random_matrix_models import GaussianUnitaryEnsembleModel assert _test_args(GaussianUnitaryEnsembleModel('U', 3)) def test_sympy__stats__random_matrix_models__GaussianOrthogonalEnsembleModel(): from sympy.stats.random_matrix_models import GaussianOrthogonalEnsembleModel assert _test_args(GaussianOrthogonalEnsembleModel('U', 3)) def test_sympy__stats__random_matrix_models__GaussianSymplecticEnsembleModel(): from sympy.stats.random_matrix_models import GaussianSymplecticEnsembleModel assert _test_args(GaussianSymplecticEnsembleModel('U', 3)) def test_sympy__stats__random_matrix_models__CircularEnsembleModel(): from sympy.stats.random_matrix_models import CircularEnsembleModel assert _test_args(CircularEnsembleModel('C', 3)) def test_sympy__stats__random_matrix_models__CircularUnitaryEnsembleModel(): from sympy.stats.random_matrix_models import CircularUnitaryEnsembleModel assert _test_args(CircularUnitaryEnsembleModel('U', 3)) def test_sympy__stats__random_matrix_models__CircularOrthogonalEnsembleModel(): from sympy.stats.random_matrix_models import CircularOrthogonalEnsembleModel assert _test_args(CircularOrthogonalEnsembleModel('O', 3)) def test_sympy__stats__random_matrix_models__CircularSymplecticEnsembleModel(): from sympy.stats.random_matrix_models import CircularSymplecticEnsembleModel assert _test_args(CircularSymplecticEnsembleModel('S', 3)) def test_sympy__stats__symbolic_multivariate_probability__ExpectationMatrix(): from sympy.stats import ExpectationMatrix from sympy.stats.rv import RandomMatrixSymbol assert _test_args(ExpectationMatrix(RandomMatrixSymbol('R', 2, 1))) def test_sympy__stats__symbolic_multivariate_probability__VarianceMatrix(): from sympy.stats import VarianceMatrix from sympy.stats.rv import RandomMatrixSymbol assert _test_args(VarianceMatrix(RandomMatrixSymbol('R', 3, 1))) def test_sympy__stats__symbolic_multivariate_probability__CrossCovarianceMatrix(): from sympy.stats import CrossCovarianceMatrix from sympy.stats.rv import RandomMatrixSymbol assert _test_args(CrossCovarianceMatrix(RandomMatrixSymbol('R', 3, 1), RandomMatrixSymbol('X', 3, 1))) def test_sympy__stats__matrix_distributions__MatrixPSpace(): from sympy.stats.matrix_distributions import MatrixDistribution, MatrixPSpace from sympy.matrices.dense import Matrix M = MatrixDistribution(1, Matrix([[1, 0], [0, 1]])) assert _test_args(MatrixPSpace('M', M, 2, 2)) def test_sympy__stats__matrix_distributions__MatrixDistribution(): from sympy.stats.matrix_distributions import MatrixDistribution from sympy.matrices.dense import Matrix assert _test_args(MatrixDistribution(1, Matrix([[1, 0], [0, 1]]))) def test_sympy__stats__matrix_distributions__MatrixGammaDistribution(): from sympy.stats.matrix_distributions import MatrixGammaDistribution from sympy.matrices.dense import Matrix assert _test_args(MatrixGammaDistribution(3, 4, Matrix([[1, 0], [0, 1]]))) def test_sympy__stats__matrix_distributions__WishartDistribution(): from sympy.stats.matrix_distributions import WishartDistribution from sympy.matrices.dense import Matrix assert _test_args(WishartDistribution(3, Matrix([[1, 0], [0, 1]]))) def test_sympy__stats__matrix_distributions__MatrixNormalDistribution(): from sympy.stats.matrix_distributions import MatrixNormalDistribution from sympy.matrices.expressions.matexpr import MatrixSymbol L = MatrixSymbol('L', 1, 2) S1 = MatrixSymbol('S1', 1, 1) S2 = MatrixSymbol('S2', 2, 2) assert _test_args(MatrixNormalDistribution(L, S1, S2)) def test_sympy__stats__matrix_distributions__MatrixStudentTDistribution(): from sympy.stats.matrix_distributions import MatrixStudentTDistribution from sympy.matrices.expressions.matexpr import MatrixSymbol v = symbols('v', positive=True) Omega = MatrixSymbol('Omega', 3, 3) Sigma = MatrixSymbol('Sigma', 1, 1) Location = MatrixSymbol('Location', 1, 3) assert _test_args(MatrixStudentTDistribution(v, Location, Omega, Sigma)) def test_sympy__utilities__matchpy_connector__WildDot(): from sympy.utilities.matchpy_connector import WildDot assert _test_args(WildDot("w_")) def test_sympy__utilities__matchpy_connector__WildPlus(): from sympy.utilities.matchpy_connector import WildPlus assert _test_args(WildPlus("w__")) def test_sympy__utilities__matchpy_connector__WildStar(): from sympy.utilities.matchpy_connector import WildStar assert _test_args(WildStar("w___")) def test_sympy__core__symbol__Str(): from sympy.core.symbol import Str assert _test_args(Str('t')) def test_sympy__core__symbol__Dummy(): from sympy.core.symbol import Dummy assert _test_args(Dummy('t')) def test_sympy__core__symbol__Symbol(): from sympy.core.symbol import Symbol assert _test_args(Symbol('t')) def test_sympy__core__symbol__Wild(): from sympy.core.symbol import Wild assert _test_args(Wild('x', exclude=[x])) @SKIP("abstract class") def test_sympy__functions__combinatorial__factorials__CombinatorialFunction(): pass def test_sympy__functions__combinatorial__factorials__FallingFactorial(): from sympy.functions.combinatorial.factorials import FallingFactorial assert _test_args(FallingFactorial(2, x)) def test_sympy__functions__combinatorial__factorials__MultiFactorial(): from sympy.functions.combinatorial.factorials import MultiFactorial assert _test_args(MultiFactorial(x)) def test_sympy__functions__combinatorial__factorials__RisingFactorial(): from sympy.functions.combinatorial.factorials import RisingFactorial assert _test_args(RisingFactorial(2, x)) def test_sympy__functions__combinatorial__factorials__binomial(): from sympy.functions.combinatorial.factorials import binomial assert _test_args(binomial(2, x)) def test_sympy__functions__combinatorial__factorials__subfactorial(): from sympy.functions.combinatorial.factorials import subfactorial assert _test_args(subfactorial(1)) def test_sympy__functions__combinatorial__factorials__factorial(): from sympy.functions.combinatorial.factorials import factorial assert _test_args(factorial(x)) def test_sympy__functions__combinatorial__factorials__factorial2(): from sympy.functions.combinatorial.factorials import factorial2 assert _test_args(factorial2(x)) def test_sympy__functions__combinatorial__numbers__bell(): from sympy.functions.combinatorial.numbers import bell assert _test_args(bell(x, y)) def test_sympy__functions__combinatorial__numbers__bernoulli(): from sympy.functions.combinatorial.numbers import bernoulli assert _test_args(bernoulli(x)) def test_sympy__functions__combinatorial__numbers__catalan(): from sympy.functions.combinatorial.numbers import catalan assert _test_args(catalan(x)) def test_sympy__functions__combinatorial__numbers__genocchi(): from sympy.functions.combinatorial.numbers import genocchi assert _test_args(genocchi(x)) def test_sympy__functions__combinatorial__numbers__euler(): from sympy.functions.combinatorial.numbers import euler assert _test_args(euler(x)) def test_sympy__functions__combinatorial__numbers__carmichael(): from sympy.functions.combinatorial.numbers import carmichael assert _test_args(carmichael(x)) def test_sympy__functions__combinatorial__numbers__motzkin(): from sympy.functions.combinatorial.numbers import motzkin assert _test_args(motzkin(5)) def test_sympy__functions__combinatorial__numbers__fibonacci(): from sympy.functions.combinatorial.numbers import fibonacci assert _test_args(fibonacci(x)) def test_sympy__functions__combinatorial__numbers__tribonacci(): from sympy.functions.combinatorial.numbers import tribonacci assert _test_args(tribonacci(x)) def test_sympy__functions__combinatorial__numbers__harmonic(): from sympy.functions.combinatorial.numbers import harmonic assert _test_args(harmonic(x, 2)) def test_sympy__functions__combinatorial__numbers__lucas(): from sympy.functions.combinatorial.numbers import lucas assert _test_args(lucas(x)) def test_sympy__functions__combinatorial__numbers__partition(): from sympy.core.symbol import Symbol from sympy.functions.combinatorial.numbers import partition assert _test_args(partition(Symbol('a', integer=True))) def test_sympy__functions__elementary__complexes__Abs(): from sympy.functions.elementary.complexes import Abs assert _test_args(Abs(x)) def test_sympy__functions__elementary__complexes__adjoint(): from sympy.functions.elementary.complexes import adjoint assert _test_args(adjoint(x)) def test_sympy__functions__elementary__complexes__arg(): from sympy.functions.elementary.complexes import arg assert _test_args(arg(x)) def test_sympy__functions__elementary__complexes__conjugate(): from sympy.functions.elementary.complexes import conjugate assert _test_args(conjugate(x)) def test_sympy__functions__elementary__complexes__im(): from sympy.functions.elementary.complexes import im assert _test_args(im(x)) def test_sympy__functions__elementary__complexes__re(): from sympy.functions.elementary.complexes import re assert _test_args(re(x)) def test_sympy__functions__elementary__complexes__sign(): from sympy.functions.elementary.complexes import sign assert _test_args(sign(x)) def test_sympy__functions__elementary__complexes__polar_lift(): from sympy.functions.elementary.complexes import polar_lift assert _test_args(polar_lift(x)) def test_sympy__functions__elementary__complexes__periodic_argument(): from sympy.functions.elementary.complexes import periodic_argument assert _test_args(periodic_argument(x, y)) def test_sympy__functions__elementary__complexes__principal_branch(): from sympy.functions.elementary.complexes import principal_branch assert _test_args(principal_branch(x, y)) def test_sympy__functions__elementary__complexes__transpose(): from sympy.functions.elementary.complexes import transpose assert _test_args(transpose(x)) def test_sympy__functions__elementary__exponential__LambertW(): from sympy.functions.elementary.exponential import LambertW assert _test_args(LambertW(2)) @SKIP("abstract class") def test_sympy__functions__elementary__exponential__ExpBase(): pass def test_sympy__functions__elementary__exponential__exp(): from sympy.functions.elementary.exponential import exp assert _test_args(exp(2)) def test_sympy__functions__elementary__exponential__exp_polar(): from sympy.functions.elementary.exponential import exp_polar assert _test_args(exp_polar(2)) def test_sympy__functions__elementary__exponential__log(): from sympy.functions.elementary.exponential import log assert _test_args(log(2)) @SKIP("abstract class") def test_sympy__functions__elementary__hyperbolic__HyperbolicFunction(): pass @SKIP("abstract class") def test_sympy__functions__elementary__hyperbolic__ReciprocalHyperbolicFunction(): pass @SKIP("abstract class") def test_sympy__functions__elementary__hyperbolic__InverseHyperbolicFunction(): pass def test_sympy__functions__elementary__hyperbolic__acosh(): from sympy.functions.elementary.hyperbolic import acosh assert _test_args(acosh(2)) def test_sympy__functions__elementary__hyperbolic__acoth(): from sympy.functions.elementary.hyperbolic import acoth assert _test_args(acoth(2)) def test_sympy__functions__elementary__hyperbolic__asinh(): from sympy.functions.elementary.hyperbolic import asinh assert _test_args(asinh(2)) def test_sympy__functions__elementary__hyperbolic__atanh(): from sympy.functions.elementary.hyperbolic import atanh assert _test_args(atanh(2)) def test_sympy__functions__elementary__hyperbolic__asech(): from sympy.functions.elementary.hyperbolic import asech assert _test_args(asech(2)) def test_sympy__functions__elementary__hyperbolic__acsch(): from sympy.functions.elementary.hyperbolic import acsch assert _test_args(acsch(2)) def test_sympy__functions__elementary__hyperbolic__cosh(): from sympy.functions.elementary.hyperbolic import cosh assert _test_args(cosh(2)) def test_sympy__functions__elementary__hyperbolic__coth(): from sympy.functions.elementary.hyperbolic import coth assert _test_args(coth(2)) def test_sympy__functions__elementary__hyperbolic__csch(): from sympy.functions.elementary.hyperbolic import csch assert _test_args(csch(2)) def test_sympy__functions__elementary__hyperbolic__sech(): from sympy.functions.elementary.hyperbolic import sech assert _test_args(sech(2)) def test_sympy__functions__elementary__hyperbolic__sinh(): from sympy.functions.elementary.hyperbolic import sinh assert _test_args(sinh(2)) def test_sympy__functions__elementary__hyperbolic__tanh(): from sympy.functions.elementary.hyperbolic import tanh assert _test_args(tanh(2)) @SKIP("does this work at all?") def test_sympy__functions__elementary__integers__RoundFunction(): from sympy.functions.elementary.integers import RoundFunction assert _test_args(RoundFunction()) def test_sympy__functions__elementary__integers__ceiling(): from sympy.functions.elementary.integers import ceiling assert _test_args(ceiling(x)) def test_sympy__functions__elementary__integers__floor(): from sympy.functions.elementary.integers import floor assert _test_args(floor(x)) def test_sympy__functions__elementary__integers__frac(): from sympy.functions.elementary.integers import frac assert _test_args(frac(x)) def test_sympy__functions__elementary__miscellaneous__IdentityFunction(): from sympy.functions.elementary.miscellaneous import IdentityFunction assert _test_args(IdentityFunction()) def test_sympy__functions__elementary__miscellaneous__Max(): from sympy.functions.elementary.miscellaneous import Max assert _test_args(Max(x, 2)) def test_sympy__functions__elementary__miscellaneous__Min(): from sympy.functions.elementary.miscellaneous import Min assert _test_args(Min(x, 2)) @SKIP("abstract class") def test_sympy__functions__elementary__miscellaneous__MinMaxBase(): pass def test_sympy__functions__elementary__miscellaneous__Rem(): from sympy.functions.elementary.miscellaneous import Rem assert _test_args(Rem(x, 2)) def test_sympy__functions__elementary__piecewise__ExprCondPair(): from sympy.functions.elementary.piecewise import ExprCondPair assert _test_args(ExprCondPair(1, True)) def test_sympy__functions__elementary__piecewise__Piecewise(): from sympy.functions.elementary.piecewise import Piecewise assert _test_args(Piecewise((1, x >= 0), (0, True))) @SKIP("abstract class") def test_sympy__functions__elementary__trigonometric__TrigonometricFunction(): pass @SKIP("abstract class") def test_sympy__functions__elementary__trigonometric__ReciprocalTrigonometricFunction(): pass @SKIP("abstract class") def test_sympy__functions__elementary__trigonometric__InverseTrigonometricFunction(): pass def test_sympy__functions__elementary__trigonometric__acos(): from sympy.functions.elementary.trigonometric import acos assert _test_args(acos(2)) def test_sympy__functions__elementary__trigonometric__acot(): from sympy.functions.elementary.trigonometric import acot assert _test_args(acot(2)) def test_sympy__functions__elementary__trigonometric__asin(): from sympy.functions.elementary.trigonometric import asin assert _test_args(asin(2)) def test_sympy__functions__elementary__trigonometric__asec(): from sympy.functions.elementary.trigonometric import asec assert _test_args(asec(2)) def test_sympy__functions__elementary__trigonometric__acsc(): from sympy.functions.elementary.trigonometric import acsc assert _test_args(acsc(2)) def test_sympy__functions__elementary__trigonometric__atan(): from sympy.functions.elementary.trigonometric import atan assert _test_args(atan(2)) def test_sympy__functions__elementary__trigonometric__atan2(): from sympy.functions.elementary.trigonometric import atan2 assert _test_args(atan2(2, 3)) def test_sympy__functions__elementary__trigonometric__cos(): from sympy.functions.elementary.trigonometric import cos assert _test_args(cos(2)) def test_sympy__functions__elementary__trigonometric__csc(): from sympy.functions.elementary.trigonometric import csc assert _test_args(csc(2)) def test_sympy__functions__elementary__trigonometric__cot(): from sympy.functions.elementary.trigonometric import cot assert _test_args(cot(2)) def test_sympy__functions__elementary__trigonometric__sin(): assert _test_args(sin(2)) def test_sympy__functions__elementary__trigonometric__sinc(): from sympy.functions.elementary.trigonometric import sinc assert _test_args(sinc(2)) def test_sympy__functions__elementary__trigonometric__sec(): from sympy.functions.elementary.trigonometric import sec assert _test_args(sec(2)) def test_sympy__functions__elementary__trigonometric__tan(): from sympy.functions.elementary.trigonometric import tan assert _test_args(tan(2)) @SKIP("abstract class") def test_sympy__functions__special__bessel__BesselBase(): pass @SKIP("abstract class") def test_sympy__functions__special__bessel__SphericalBesselBase(): pass @SKIP("abstract class") def test_sympy__functions__special__bessel__SphericalHankelBase(): pass def test_sympy__functions__special__bessel__besseli(): from sympy.functions.special.bessel import besseli assert _test_args(besseli(x, 1)) def test_sympy__functions__special__bessel__besselj(): from sympy.functions.special.bessel import besselj assert _test_args(besselj(x, 1)) def test_sympy__functions__special__bessel__besselk(): from sympy.functions.special.bessel import besselk assert _test_args(besselk(x, 1)) def test_sympy__functions__special__bessel__bessely(): from sympy.functions.special.bessel import bessely assert _test_args(bessely(x, 1)) def test_sympy__functions__special__bessel__hankel1(): from sympy.functions.special.bessel import hankel1 assert _test_args(hankel1(x, 1)) def test_sympy__functions__special__bessel__hankel2(): from sympy.functions.special.bessel import hankel2 assert _test_args(hankel2(x, 1)) def test_sympy__functions__special__bessel__jn(): from sympy.functions.special.bessel import jn assert _test_args(jn(0, x)) def test_sympy__functions__special__bessel__yn(): from sympy.functions.special.bessel import yn assert _test_args(yn(0, x)) def test_sympy__functions__special__bessel__hn1(): from sympy.functions.special.bessel import hn1 assert _test_args(hn1(0, x)) def test_sympy__functions__special__bessel__hn2(): from sympy.functions.special.bessel import hn2 assert _test_args(hn2(0, x)) def test_sympy__functions__special__bessel__AiryBase(): pass def test_sympy__functions__special__bessel__airyai(): from sympy.functions.special.bessel import airyai assert _test_args(airyai(2)) def test_sympy__functions__special__bessel__airybi(): from sympy.functions.special.bessel import airybi assert _test_args(airybi(2)) def test_sympy__functions__special__bessel__airyaiprime(): from sympy.functions.special.bessel import airyaiprime assert _test_args(airyaiprime(2)) def test_sympy__functions__special__bessel__airybiprime(): from sympy.functions.special.bessel import airybiprime assert _test_args(airybiprime(2)) def test_sympy__functions__special__bessel__marcumq(): from sympy.functions.special.bessel import marcumq assert _test_args(marcumq(x, y, z)) def test_sympy__functions__special__elliptic_integrals__elliptic_k(): from sympy.functions.special.elliptic_integrals import elliptic_k as K assert _test_args(K(x)) def test_sympy__functions__special__elliptic_integrals__elliptic_f(): from sympy.functions.special.elliptic_integrals import elliptic_f as F assert _test_args(F(x, y)) def test_sympy__functions__special__elliptic_integrals__elliptic_e(): from sympy.functions.special.elliptic_integrals import elliptic_e as E assert _test_args(E(x)) assert _test_args(E(x, y)) def test_sympy__functions__special__elliptic_integrals__elliptic_pi(): from sympy.functions.special.elliptic_integrals import elliptic_pi as P assert _test_args(P(x, y)) assert _test_args(P(x, y, z)) def test_sympy__functions__special__delta_functions__DiracDelta(): from sympy.functions.special.delta_functions import DiracDelta assert _test_args(DiracDelta(x, 1)) def test_sympy__functions__special__singularity_functions__SingularityFunction(): from sympy.functions.special.singularity_functions import SingularityFunction assert _test_args(SingularityFunction(x, y, z)) def test_sympy__functions__special__delta_functions__Heaviside(): from sympy.functions.special.delta_functions import Heaviside assert _test_args(Heaviside(x)) def test_sympy__functions__special__error_functions__erf(): from sympy.functions.special.error_functions import erf assert _test_args(erf(2)) def test_sympy__functions__special__error_functions__erfc(): from sympy.functions.special.error_functions import erfc assert _test_args(erfc(2)) def test_sympy__functions__special__error_functions__erfi(): from sympy.functions.special.error_functions import erfi assert _test_args(erfi(2)) def test_sympy__functions__special__error_functions__erf2(): from sympy.functions.special.error_functions import erf2 assert _test_args(erf2(2, 3)) def test_sympy__functions__special__error_functions__erfinv(): from sympy.functions.special.error_functions import erfinv assert _test_args(erfinv(2)) def test_sympy__functions__special__error_functions__erfcinv(): from sympy.functions.special.error_functions import erfcinv assert _test_args(erfcinv(2)) def test_sympy__functions__special__error_functions__erf2inv(): from sympy.functions.special.error_functions import erf2inv assert _test_args(erf2inv(2, 3)) @SKIP("abstract class") def test_sympy__functions__special__error_functions__FresnelIntegral(): pass def test_sympy__functions__special__error_functions__fresnels(): from sympy.functions.special.error_functions import fresnels assert _test_args(fresnels(2)) def test_sympy__functions__special__error_functions__fresnelc(): from sympy.functions.special.error_functions import fresnelc assert _test_args(fresnelc(2)) def test_sympy__functions__special__error_functions__erfs(): from sympy.functions.special.error_functions import _erfs assert _test_args(_erfs(2)) def test_sympy__functions__special__error_functions__Ei(): from sympy.functions.special.error_functions import Ei assert _test_args(Ei(2)) def test_sympy__functions__special__error_functions__li(): from sympy.functions.special.error_functions import li assert _test_args(li(2)) def test_sympy__functions__special__error_functions__Li(): from sympy.functions.special.error_functions import Li assert _test_args(Li(2)) @SKIP("abstract class") def test_sympy__functions__special__error_functions__TrigonometricIntegral(): pass def test_sympy__functions__special__error_functions__Si(): from sympy.functions.special.error_functions import Si assert _test_args(Si(2)) def test_sympy__functions__special__error_functions__Ci(): from sympy.functions.special.error_functions import Ci assert _test_args(Ci(2)) def test_sympy__functions__special__error_functions__Shi(): from sympy.functions.special.error_functions import Shi assert _test_args(Shi(2)) def test_sympy__functions__special__error_functions__Chi(): from sympy.functions.special.error_functions import Chi assert _test_args(Chi(2)) def test_sympy__functions__special__error_functions__expint(): from sympy.functions.special.error_functions import expint assert _test_args(expint(y, x)) def test_sympy__functions__special__gamma_functions__gamma(): from sympy.functions.special.gamma_functions import gamma assert _test_args(gamma(x)) def test_sympy__functions__special__gamma_functions__loggamma(): from sympy.functions.special.gamma_functions import loggamma assert _test_args(loggamma(2)) def test_sympy__functions__special__gamma_functions__lowergamma(): from sympy.functions.special.gamma_functions import lowergamma assert _test_args(lowergamma(x, 2)) def test_sympy__functions__special__gamma_functions__polygamma(): from sympy.functions.special.gamma_functions import polygamma assert _test_args(polygamma(x, 2)) def test_sympy__functions__special__gamma_functions__digamma(): from sympy.functions.special.gamma_functions import digamma assert _test_args(digamma(x)) def test_sympy__functions__special__gamma_functions__trigamma(): from sympy.functions.special.gamma_functions import trigamma assert _test_args(trigamma(x)) def test_sympy__functions__special__gamma_functions__uppergamma(): from sympy.functions.special.gamma_functions import uppergamma assert _test_args(uppergamma(x, 2)) def test_sympy__functions__special__gamma_functions__multigamma(): from sympy.functions.special.gamma_functions import multigamma assert _test_args(multigamma(x, 1)) def test_sympy__functions__special__beta_functions__beta(): from sympy.functions.special.beta_functions import beta assert _test_args(beta(x)) assert _test_args(beta(x, x)) def test_sympy__functions__special__beta_functions__betainc(): from sympy.functions.special.beta_functions import betainc assert _test_args(betainc(a, b, x, y)) def test_sympy__functions__special__beta_functions__betainc_regularized(): from sympy.functions.special.beta_functions import betainc_regularized assert _test_args(betainc_regularized(a, b, x, y)) def test_sympy__functions__special__mathieu_functions__MathieuBase(): pass def test_sympy__functions__special__mathieu_functions__mathieus(): from sympy.functions.special.mathieu_functions import mathieus assert _test_args(mathieus(1, 1, 1)) def test_sympy__functions__special__mathieu_functions__mathieuc(): from sympy.functions.special.mathieu_functions import mathieuc assert _test_args(mathieuc(1, 1, 1)) def test_sympy__functions__special__mathieu_functions__mathieusprime(): from sympy.functions.special.mathieu_functions import mathieusprime assert _test_args(mathieusprime(1, 1, 1)) def test_sympy__functions__special__mathieu_functions__mathieucprime(): from sympy.functions.special.mathieu_functions import mathieucprime assert _test_args(mathieucprime(1, 1, 1)) @SKIP("abstract class") def test_sympy__functions__special__hyper__TupleParametersBase(): pass @SKIP("abstract class") def test_sympy__functions__special__hyper__TupleArg(): pass def test_sympy__functions__special__hyper__hyper(): from sympy.functions.special.hyper import hyper assert _test_args(hyper([1, 2, 3], [4, 5], x)) def test_sympy__functions__special__hyper__meijerg(): from sympy.functions.special.hyper import meijerg assert _test_args(meijerg([1, 2, 3], [4, 5], [6], [], x)) @SKIP("abstract class") def test_sympy__functions__special__hyper__HyperRep(): pass def test_sympy__functions__special__hyper__HyperRep_power1(): from sympy.functions.special.hyper import HyperRep_power1 assert _test_args(HyperRep_power1(x, y)) def test_sympy__functions__special__hyper__HyperRep_power2(): from sympy.functions.special.hyper import HyperRep_power2 assert _test_args(HyperRep_power2(x, y)) def test_sympy__functions__special__hyper__HyperRep_log1(): from sympy.functions.special.hyper import HyperRep_log1 assert _test_args(HyperRep_log1(x)) def test_sympy__functions__special__hyper__HyperRep_atanh(): from sympy.functions.special.hyper import HyperRep_atanh assert _test_args(HyperRep_atanh(x)) def test_sympy__functions__special__hyper__HyperRep_asin1(): from sympy.functions.special.hyper import HyperRep_asin1 assert _test_args(HyperRep_asin1(x)) def test_sympy__functions__special__hyper__HyperRep_asin2(): from sympy.functions.special.hyper import HyperRep_asin2 assert _test_args(HyperRep_asin2(x)) def test_sympy__functions__special__hyper__HyperRep_sqrts1(): from sympy.functions.special.hyper import HyperRep_sqrts1 assert _test_args(HyperRep_sqrts1(x, y)) def test_sympy__functions__special__hyper__HyperRep_sqrts2(): from sympy.functions.special.hyper import HyperRep_sqrts2 assert _test_args(HyperRep_sqrts2(x, y)) def test_sympy__functions__special__hyper__HyperRep_log2(): from sympy.functions.special.hyper import HyperRep_log2 assert _test_args(HyperRep_log2(x)) def test_sympy__functions__special__hyper__HyperRep_cosasin(): from sympy.functions.special.hyper import HyperRep_cosasin assert _test_args(HyperRep_cosasin(x, y)) def test_sympy__functions__special__hyper__HyperRep_sinasin(): from sympy.functions.special.hyper import HyperRep_sinasin assert _test_args(HyperRep_sinasin(x, y)) def test_sympy__functions__special__hyper__appellf1(): from sympy.functions.special.hyper import appellf1 a, b1, b2, c, x, y = symbols('a b1 b2 c x y') assert _test_args(appellf1(a, b1, b2, c, x, y)) @SKIP("abstract class") def test_sympy__functions__special__polynomials__OrthogonalPolynomial(): pass def test_sympy__functions__special__polynomials__jacobi(): from sympy.functions.special.polynomials import jacobi assert _test_args(jacobi(x, 2, 2, 2)) def test_sympy__functions__special__polynomials__gegenbauer(): from sympy.functions.special.polynomials import gegenbauer assert _test_args(gegenbauer(x, 2, 2)) def test_sympy__functions__special__polynomials__chebyshevt(): from sympy.functions.special.polynomials import chebyshevt assert _test_args(chebyshevt(x, 2)) def test_sympy__functions__special__polynomials__chebyshevt_root(): from sympy.functions.special.polynomials import chebyshevt_root assert _test_args(chebyshevt_root(3, 2)) def test_sympy__functions__special__polynomials__chebyshevu(): from sympy.functions.special.polynomials import chebyshevu assert _test_args(chebyshevu(x, 2)) def test_sympy__functions__special__polynomials__chebyshevu_root(): from sympy.functions.special.polynomials import chebyshevu_root assert _test_args(chebyshevu_root(3, 2)) def test_sympy__functions__special__polynomials__hermite(): from sympy.functions.special.polynomials import hermite assert _test_args(hermite(x, 2)) def test_sympy__functions__special__polynomials__legendre(): from sympy.functions.special.polynomials import legendre assert _test_args(legendre(x, 2)) def test_sympy__functions__special__polynomials__assoc_legendre(): from sympy.functions.special.polynomials import assoc_legendre assert _test_args(assoc_legendre(x, 0, y)) def test_sympy__functions__special__polynomials__laguerre(): from sympy.functions.special.polynomials import laguerre assert _test_args(laguerre(x, 2)) def test_sympy__functions__special__polynomials__assoc_laguerre(): from sympy.functions.special.polynomials import assoc_laguerre assert _test_args(assoc_laguerre(x, 0, y)) def test_sympy__functions__special__spherical_harmonics__Ynm(): from sympy.functions.special.spherical_harmonics import Ynm assert _test_args(Ynm(1, 1, x, y)) def test_sympy__functions__special__spherical_harmonics__Znm(): from sympy.functions.special.spherical_harmonics import Znm assert _test_args(Znm(1, 1, x, y)) def test_sympy__functions__special__tensor_functions__LeviCivita(): from sympy.functions.special.tensor_functions import LeviCivita assert _test_args(LeviCivita(x, y, 2)) def test_sympy__functions__special__tensor_functions__KroneckerDelta(): from sympy.functions.special.tensor_functions import KroneckerDelta assert _test_args(KroneckerDelta(x, y)) def test_sympy__functions__special__zeta_functions__dirichlet_eta(): from sympy.functions.special.zeta_functions import dirichlet_eta assert _test_args(dirichlet_eta(x)) def test_sympy__functions__special__zeta_functions__riemann_xi(): from sympy.functions.special.zeta_functions import riemann_xi assert _test_args(riemann_xi(x)) def test_sympy__functions__special__zeta_functions__zeta(): from sympy.functions.special.zeta_functions import zeta assert _test_args(zeta(101)) def test_sympy__functions__special__zeta_functions__lerchphi(): from sympy.functions.special.zeta_functions import lerchphi assert _test_args(lerchphi(x, y, z)) def test_sympy__functions__special__zeta_functions__polylog(): from sympy.functions.special.zeta_functions import polylog assert _test_args(polylog(x, y)) def test_sympy__functions__special__zeta_functions__stieltjes(): from sympy.functions.special.zeta_functions import stieltjes assert _test_args(stieltjes(x, y)) def test_sympy__integrals__integrals__Integral(): from sympy.integrals.integrals import Integral assert _test_args(Integral(2, (x, 0, 1))) def test_sympy__integrals__risch__NonElementaryIntegral(): from sympy.integrals.risch import NonElementaryIntegral assert _test_args(NonElementaryIntegral(exp(-x**2), x)) @SKIP("abstract class") def test_sympy__integrals__transforms__IntegralTransform(): pass def test_sympy__integrals__transforms__MellinTransform(): from sympy.integrals.transforms import MellinTransform assert _test_args(MellinTransform(2, x, y)) def test_sympy__integrals__transforms__InverseMellinTransform(): from sympy.integrals.transforms import InverseMellinTransform assert _test_args(InverseMellinTransform(2, x, y, 0, 1)) def test_sympy__integrals__transforms__LaplaceTransform(): from sympy.integrals.transforms import LaplaceTransform assert _test_args(LaplaceTransform(2, x, y)) def test_sympy__integrals__transforms__InverseLaplaceTransform(): from sympy.integrals.transforms import InverseLaplaceTransform assert _test_args(InverseLaplaceTransform(2, x, y, 0)) @SKIP("abstract class") def test_sympy__integrals__transforms__FourierTypeTransform(): pass def test_sympy__integrals__transforms__InverseFourierTransform(): from sympy.integrals.transforms import InverseFourierTransform assert _test_args(InverseFourierTransform(2, x, y)) def test_sympy__integrals__transforms__FourierTransform(): from sympy.integrals.transforms import FourierTransform assert _test_args(FourierTransform(2, x, y)) @SKIP("abstract class") def test_sympy__integrals__transforms__SineCosineTypeTransform(): pass def test_sympy__integrals__transforms__InverseSineTransform(): from sympy.integrals.transforms import InverseSineTransform assert _test_args(InverseSineTransform(2, x, y)) def test_sympy__integrals__transforms__SineTransform(): from sympy.integrals.transforms import SineTransform assert _test_args(SineTransform(2, x, y)) def test_sympy__integrals__transforms__InverseCosineTransform(): from sympy.integrals.transforms import InverseCosineTransform assert _test_args(InverseCosineTransform(2, x, y)) def test_sympy__integrals__transforms__CosineTransform(): from sympy.integrals.transforms import CosineTransform assert _test_args(CosineTransform(2, x, y)) @SKIP("abstract class") def test_sympy__integrals__transforms__HankelTypeTransform(): pass def test_sympy__integrals__transforms__InverseHankelTransform(): from sympy.integrals.transforms import InverseHankelTransform assert _test_args(InverseHankelTransform(2, x, y, 0)) def test_sympy__integrals__transforms__HankelTransform(): from sympy.integrals.transforms import HankelTransform assert _test_args(HankelTransform(2, x, y, 0)) @XFAIL def test_sympy__liealgebras__cartan_type__CartanType_generator(): from sympy.liealgebras.cartan_type import CartanType_generator assert _test_args(CartanType_generator("A2")) def test_sympy__liealgebras__cartan_type__Standard_Cartan(): from sympy.liealgebras.cartan_type import Standard_Cartan assert _test_args(Standard_Cartan("A", 2)) def test_sympy__liealgebras__weyl_group__WeylGroup(): from sympy.liealgebras.weyl_group import WeylGroup assert _test_args(WeylGroup("B4")) def test_sympy__liealgebras__root_system__RootSystem(): from sympy.liealgebras.root_system import RootSystem assert _test_args(RootSystem("A2")) def test_sympy__liealgebras__type_a__TypeA(): from sympy.liealgebras.type_a import TypeA assert _test_args(TypeA(2)) def test_sympy__liealgebras__type_b__TypeB(): from sympy.liealgebras.type_b import TypeB assert _test_args(TypeB(4)) def test_sympy__liealgebras__type_c__TypeC(): from sympy.liealgebras.type_c import TypeC assert _test_args(TypeC(4)) def test_sympy__liealgebras__type_d__TypeD(): from sympy.liealgebras.type_d import TypeD assert _test_args(TypeD(4)) def test_sympy__liealgebras__type_e__TypeE(): from sympy.liealgebras.type_e import TypeE assert _test_args(TypeE(6)) def test_sympy__liealgebras__type_f__TypeF(): from sympy.liealgebras.type_f import TypeF assert _test_args(TypeF(4)) def test_sympy__liealgebras__type_g__TypeG(): from sympy.liealgebras.type_g import TypeG assert _test_args(TypeG(2)) def test_sympy__logic__boolalg__And(): from sympy.logic.boolalg import And assert _test_args(And(x, y, 1)) @SKIP("abstract class") def test_sympy__logic__boolalg__Boolean(): pass def test_sympy__logic__boolalg__BooleanFunction(): from sympy.logic.boolalg import BooleanFunction assert _test_args(BooleanFunction(1, 2, 3)) @SKIP("abstract class") def test_sympy__logic__boolalg__BooleanAtom(): pass def test_sympy__logic__boolalg__BooleanTrue(): from sympy.logic.boolalg import true assert _test_args(true) def test_sympy__logic__boolalg__BooleanFalse(): from sympy.logic.boolalg import false assert _test_args(false) def test_sympy__logic__boolalg__Equivalent(): from sympy.logic.boolalg import Equivalent assert _test_args(Equivalent(x, 2)) def test_sympy__logic__boolalg__ITE(): from sympy.logic.boolalg import ITE assert _test_args(ITE(x, y, 1)) def test_sympy__logic__boolalg__Implies(): from sympy.logic.boolalg import Implies assert _test_args(Implies(x, y)) def test_sympy__logic__boolalg__Nand(): from sympy.logic.boolalg import Nand assert _test_args(Nand(x, y, 1)) def test_sympy__logic__boolalg__Nor(): from sympy.logic.boolalg import Nor assert _test_args(Nor(x, y)) def test_sympy__logic__boolalg__Not(): from sympy.logic.boolalg import Not assert _test_args(Not(x)) def test_sympy__logic__boolalg__Or(): from sympy.logic.boolalg import Or assert _test_args(Or(x, y)) def test_sympy__logic__boolalg__Xor(): from sympy.logic.boolalg import Xor assert _test_args(Xor(x, y, 2)) def test_sympy__logic__boolalg__Xnor(): from sympy.logic.boolalg import Xnor assert _test_args(Xnor(x, y, 2)) def test_sympy__logic__boolalg__Exclusive(): from sympy.logic.boolalg import Exclusive assert _test_args(Exclusive(x, y, z)) def test_sympy__matrices__matrices__DeferredVector(): from sympy.matrices.matrices import DeferredVector assert _test_args(DeferredVector("X")) @SKIP("abstract class") def test_sympy__matrices__expressions__matexpr__MatrixBase(): pass @SKIP("abstract class") def test_sympy__matrices__immutable__ImmutableRepMatrix(): pass def test_sympy__matrices__immutable__ImmutableDenseMatrix(): from sympy.matrices.immutable import ImmutableDenseMatrix m = ImmutableDenseMatrix([[1, 2], [3, 4]]) assert _test_args(m) assert _test_args(Basic(*list(m))) m = ImmutableDenseMatrix(1, 1, [1]) assert _test_args(m) assert _test_args(Basic(*list(m))) m = ImmutableDenseMatrix(2, 2, lambda i, j: 1) assert m[0, 0] is S.One m = ImmutableDenseMatrix(2, 2, lambda i, j: 1/(1 + i) + 1/(1 + j)) assert m[1, 1] is S.One # true div. will give 1.0 if i,j not sympified assert _test_args(m) assert _test_args(Basic(*list(m))) def test_sympy__matrices__immutable__ImmutableSparseMatrix(): from sympy.matrices.immutable import ImmutableSparseMatrix m = ImmutableSparseMatrix([[1, 2], [3, 4]]) assert _test_args(m) assert _test_args(Basic(*list(m))) m = ImmutableSparseMatrix(1, 1, {(0, 0): 1}) assert _test_args(m) assert _test_args(Basic(*list(m))) m = ImmutableSparseMatrix(1, 1, [1]) assert _test_args(m) assert _test_args(Basic(*list(m))) m = ImmutableSparseMatrix(2, 2, lambda i, j: 1) assert m[0, 0] is S.One m = ImmutableSparseMatrix(2, 2, lambda i, j: 1/(1 + i) + 1/(1 + j)) assert m[1, 1] is S.One # true div. will give 1.0 if i,j not sympified assert _test_args(m) assert _test_args(Basic(*list(m))) def test_sympy__matrices__expressions__slice__MatrixSlice(): from sympy.matrices.expressions.slice import MatrixSlice from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', 4, 4) assert _test_args(MatrixSlice(X, (0, 2), (0, 2))) def test_sympy__matrices__expressions__applyfunc__ElementwiseApplyFunction(): from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol("X", x, x) func = Lambda(x, x**2) assert _test_args(ElementwiseApplyFunction(func, X)) def test_sympy__matrices__expressions__blockmatrix__BlockDiagMatrix(): from sympy.matrices.expressions.blockmatrix import BlockDiagMatrix from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', x, x) Y = MatrixSymbol('Y', y, y) assert _test_args(BlockDiagMatrix(X, Y)) def test_sympy__matrices__expressions__blockmatrix__BlockMatrix(): from sympy.matrices.expressions.blockmatrix import BlockMatrix from sympy.matrices.expressions import MatrixSymbol, ZeroMatrix X = MatrixSymbol('X', x, x) Y = MatrixSymbol('Y', y, y) Z = MatrixSymbol('Z', x, y) O = ZeroMatrix(y, x) assert _test_args(BlockMatrix([[X, Z], [O, Y]])) def test_sympy__matrices__expressions__inverse__Inverse(): from sympy.matrices.expressions.inverse import Inverse from sympy.matrices.expressions import MatrixSymbol assert _test_args(Inverse(MatrixSymbol('A', 3, 3))) def test_sympy__matrices__expressions__matadd__MatAdd(): from sympy.matrices.expressions.matadd import MatAdd from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', x, y) Y = MatrixSymbol('Y', x, y) assert _test_args(MatAdd(X, Y)) @SKIP("abstract class") def test_sympy__matrices__expressions__matexpr__MatrixExpr(): pass def test_sympy__matrices__expressions__matexpr__MatrixElement(): from sympy.matrices.expressions.matexpr import MatrixSymbol, MatrixElement from sympy.core.singleton import S assert _test_args(MatrixElement(MatrixSymbol('A', 3, 5), S(2), S(3))) def test_sympy__matrices__expressions__matexpr__MatrixSymbol(): from sympy.matrices.expressions.matexpr import MatrixSymbol assert _test_args(MatrixSymbol('A', 3, 5)) def test_sympy__matrices__expressions__special__OneMatrix(): from sympy.matrices.expressions.special import OneMatrix assert _test_args(OneMatrix(3, 5)) def test_sympy__matrices__expressions__special__ZeroMatrix(): from sympy.matrices.expressions.special import ZeroMatrix assert _test_args(ZeroMatrix(3, 5)) def test_sympy__matrices__expressions__special__GenericZeroMatrix(): from sympy.matrices.expressions.special import GenericZeroMatrix assert _test_args(GenericZeroMatrix()) def test_sympy__matrices__expressions__special__Identity(): from sympy.matrices.expressions.special import Identity assert _test_args(Identity(3)) def test_sympy__matrices__expressions__special__GenericIdentity(): from sympy.matrices.expressions.special import GenericIdentity assert _test_args(GenericIdentity()) def test_sympy__matrices__expressions__sets__MatrixSet(): from sympy.matrices.expressions.sets import MatrixSet from sympy.core.singleton import S assert _test_args(MatrixSet(2, 2, S.Reals)) def test_sympy__matrices__expressions__matmul__MatMul(): from sympy.matrices.expressions.matmul import MatMul from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', x, y) Y = MatrixSymbol('Y', y, x) assert _test_args(MatMul(X, Y)) def test_sympy__matrices__expressions__dotproduct__DotProduct(): from sympy.matrices.expressions.dotproduct import DotProduct from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', x, 1) Y = MatrixSymbol('Y', x, 1) assert _test_args(DotProduct(X, Y)) def test_sympy__matrices__expressions__diagonal__DiagonalMatrix(): from sympy.matrices.expressions.diagonal import DiagonalMatrix from sympy.matrices.expressions import MatrixSymbol x = MatrixSymbol('x', 10, 1) assert _test_args(DiagonalMatrix(x)) def test_sympy__matrices__expressions__diagonal__DiagonalOf(): from sympy.matrices.expressions.diagonal import DiagonalOf from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('x', 10, 10) assert _test_args(DiagonalOf(X)) def test_sympy__matrices__expressions__diagonal__DiagMatrix(): from sympy.matrices.expressions.diagonal import DiagMatrix from sympy.matrices.expressions import MatrixSymbol x = MatrixSymbol('x', 10, 1) assert _test_args(DiagMatrix(x)) def test_sympy__matrices__expressions__hadamard__HadamardProduct(): from sympy.matrices.expressions.hadamard import HadamardProduct from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', x, y) Y = MatrixSymbol('Y', x, y) assert _test_args(HadamardProduct(X, Y)) def test_sympy__matrices__expressions__hadamard__HadamardPower(): from sympy.matrices.expressions.hadamard import HadamardPower from sympy.matrices.expressions import MatrixSymbol from sympy.core.symbol import Symbol X = MatrixSymbol('X', x, y) n = Symbol("n") assert _test_args(HadamardPower(X, n)) def test_sympy__matrices__expressions__kronecker__KroneckerProduct(): from sympy.matrices.expressions.kronecker import KroneckerProduct from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', x, y) Y = MatrixSymbol('Y', x, y) assert _test_args(KroneckerProduct(X, Y)) def test_sympy__matrices__expressions__matpow__MatPow(): from sympy.matrices.expressions.matpow import MatPow from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', x, x) assert _test_args(MatPow(X, 2)) def test_sympy__matrices__expressions__transpose__Transpose(): from sympy.matrices.expressions.transpose import Transpose from sympy.matrices.expressions import MatrixSymbol assert _test_args(Transpose(MatrixSymbol('A', 3, 5))) def test_sympy__matrices__expressions__adjoint__Adjoint(): from sympy.matrices.expressions.adjoint import Adjoint from sympy.matrices.expressions import MatrixSymbol assert _test_args(Adjoint(MatrixSymbol('A', 3, 5))) def test_sympy__matrices__expressions__trace__Trace(): from sympy.matrices.expressions.trace import Trace from sympy.matrices.expressions import MatrixSymbol assert _test_args(Trace(MatrixSymbol('A', 3, 3))) def test_sympy__matrices__expressions__determinant__Determinant(): from sympy.matrices.expressions.determinant import Determinant from sympy.matrices.expressions import MatrixSymbol assert _test_args(Determinant(MatrixSymbol('A', 3, 3))) def test_sympy__matrices__expressions__determinant__Permanent(): from sympy.matrices.expressions.determinant import Permanent from sympy.matrices.expressions import MatrixSymbol assert _test_args(Permanent(MatrixSymbol('A', 3, 4))) def test_sympy__matrices__expressions__funcmatrix__FunctionMatrix(): from sympy.matrices.expressions.funcmatrix import FunctionMatrix from sympy.core.symbol import symbols i, j = symbols('i,j') assert _test_args(FunctionMatrix(3, 3, Lambda((i, j), i - j) )) def test_sympy__matrices__expressions__fourier__DFT(): from sympy.matrices.expressions.fourier import DFT from sympy.core.singleton import S assert _test_args(DFT(S(2))) def test_sympy__matrices__expressions__fourier__IDFT(): from sympy.matrices.expressions.fourier import IDFT from sympy.core.singleton import S assert _test_args(IDFT(S(2))) from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', 10, 10) def test_sympy__matrices__expressions__factorizations__LofLU(): from sympy.matrices.expressions.factorizations import LofLU assert _test_args(LofLU(X)) def test_sympy__matrices__expressions__factorizations__UofLU(): from sympy.matrices.expressions.factorizations import UofLU assert _test_args(UofLU(X)) def test_sympy__matrices__expressions__factorizations__QofQR(): from sympy.matrices.expressions.factorizations import QofQR assert _test_args(QofQR(X)) def test_sympy__matrices__expressions__factorizations__RofQR(): from sympy.matrices.expressions.factorizations import RofQR assert _test_args(RofQR(X)) def test_sympy__matrices__expressions__factorizations__LofCholesky(): from sympy.matrices.expressions.factorizations import LofCholesky assert _test_args(LofCholesky(X)) def test_sympy__matrices__expressions__factorizations__UofCholesky(): from sympy.matrices.expressions.factorizations import UofCholesky assert _test_args(UofCholesky(X)) def test_sympy__matrices__expressions__factorizations__EigenVectors(): from sympy.matrices.expressions.factorizations import EigenVectors assert _test_args(EigenVectors(X)) def test_sympy__matrices__expressions__factorizations__EigenValues(): from sympy.matrices.expressions.factorizations import EigenValues assert _test_args(EigenValues(X)) def test_sympy__matrices__expressions__factorizations__UofSVD(): from sympy.matrices.expressions.factorizations import UofSVD assert _test_args(UofSVD(X)) def test_sympy__matrices__expressions__factorizations__VofSVD(): from sympy.matrices.expressions.factorizations import VofSVD assert _test_args(VofSVD(X)) def test_sympy__matrices__expressions__factorizations__SofSVD(): from sympy.matrices.expressions.factorizations import SofSVD assert _test_args(SofSVD(X)) @SKIP("abstract class") def test_sympy__matrices__expressions__factorizations__Factorization(): pass def test_sympy__matrices__expressions__permutation__PermutationMatrix(): from sympy.combinatorics import Permutation from sympy.matrices.expressions.permutation import PermutationMatrix assert _test_args(PermutationMatrix(Permutation([2, 0, 1]))) def test_sympy__matrices__expressions__permutation__MatrixPermute(): from sympy.combinatorics import Permutation from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.expressions.permutation import MatrixPermute A = MatrixSymbol('A', 3, 3) assert _test_args(MatrixPermute(A, Permutation([2, 0, 1]))) def test_sympy__matrices__expressions__companion__CompanionMatrix(): from sympy.core.symbol import Symbol from sympy.matrices.expressions.companion import CompanionMatrix from sympy.polys.polytools import Poly x = Symbol('x') p = Poly([1, 2, 3], x) assert _test_args(CompanionMatrix(p)) def test_sympy__physics__vector__frame__CoordinateSym(): from sympy.physics.vector import CoordinateSym from sympy.physics.vector import ReferenceFrame assert _test_args(CoordinateSym('R_x', ReferenceFrame('R'), 0)) def test_sympy__physics__paulialgebra__Pauli(): from sympy.physics.paulialgebra import Pauli assert _test_args(Pauli(1)) def test_sympy__physics__quantum__anticommutator__AntiCommutator(): from sympy.physics.quantum.anticommutator import AntiCommutator assert _test_args(AntiCommutator(x, y)) def test_sympy__physics__quantum__cartesian__PositionBra3D(): from sympy.physics.quantum.cartesian import PositionBra3D assert _test_args(PositionBra3D(x, y, z)) def test_sympy__physics__quantum__cartesian__PositionKet3D(): from sympy.physics.quantum.cartesian import PositionKet3D assert _test_args(PositionKet3D(x, y, z)) def test_sympy__physics__quantum__cartesian__PositionState3D(): from sympy.physics.quantum.cartesian import PositionState3D assert _test_args(PositionState3D(x, y, z)) def test_sympy__physics__quantum__cartesian__PxBra(): from sympy.physics.quantum.cartesian import PxBra assert _test_args(PxBra(x, y, z)) def test_sympy__physics__quantum__cartesian__PxKet(): from sympy.physics.quantum.cartesian import PxKet assert _test_args(PxKet(x, y, z)) def test_sympy__physics__quantum__cartesian__PxOp(): from sympy.physics.quantum.cartesian import PxOp assert _test_args(PxOp(x, y, z)) def test_sympy__physics__quantum__cartesian__XBra(): from sympy.physics.quantum.cartesian import XBra assert _test_args(XBra(x)) def test_sympy__physics__quantum__cartesian__XKet(): from sympy.physics.quantum.cartesian import XKet assert _test_args(XKet(x)) def test_sympy__physics__quantum__cartesian__XOp(): from sympy.physics.quantum.cartesian import XOp assert _test_args(XOp(x)) def test_sympy__physics__quantum__cartesian__YOp(): from sympy.physics.quantum.cartesian import YOp assert _test_args(YOp(x)) def test_sympy__physics__quantum__cartesian__ZOp(): from sympy.physics.quantum.cartesian import ZOp assert _test_args(ZOp(x)) def test_sympy__physics__quantum__cg__CG(): from sympy.physics.quantum.cg import CG from sympy.core.singleton import S assert _test_args(CG(Rational(3, 2), Rational(3, 2), S.Half, Rational(-1, 2), 1, 1)) def test_sympy__physics__quantum__cg__Wigner3j(): from sympy.physics.quantum.cg import Wigner3j assert _test_args(Wigner3j(6, 0, 4, 0, 2, 0)) def test_sympy__physics__quantum__cg__Wigner6j(): from sympy.physics.quantum.cg import Wigner6j assert _test_args(Wigner6j(1, 2, 3, 2, 1, 2)) def test_sympy__physics__quantum__cg__Wigner9j(): from sympy.physics.quantum.cg import Wigner9j assert _test_args(Wigner9j(2, 1, 1, Rational(3, 2), S.Half, 1, S.Half, S.Half, 0)) def test_sympy__physics__quantum__circuitplot__Mz(): from sympy.physics.quantum.circuitplot import Mz assert _test_args(Mz(0)) def test_sympy__physics__quantum__circuitplot__Mx(): from sympy.physics.quantum.circuitplot import Mx assert _test_args(Mx(0)) def test_sympy__physics__quantum__commutator__Commutator(): from sympy.physics.quantum.commutator import Commutator A, B = symbols('A,B', commutative=False) assert _test_args(Commutator(A, B)) def test_sympy__physics__quantum__constants__HBar(): from sympy.physics.quantum.constants import HBar assert _test_args(HBar()) def test_sympy__physics__quantum__dagger__Dagger(): from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.state import Ket assert _test_args(Dagger(Dagger(Ket('psi')))) def test_sympy__physics__quantum__gate__CGate(): from sympy.physics.quantum.gate import CGate, Gate assert _test_args(CGate((0, 1), Gate(2))) def test_sympy__physics__quantum__gate__CGateS(): from sympy.physics.quantum.gate import CGateS, Gate assert _test_args(CGateS((0, 1), Gate(2))) def test_sympy__physics__quantum__gate__CNotGate(): from sympy.physics.quantum.gate import CNotGate assert _test_args(CNotGate(0, 1)) def test_sympy__physics__quantum__gate__Gate(): from sympy.physics.quantum.gate import Gate assert _test_args(Gate(0)) def test_sympy__physics__quantum__gate__HadamardGate(): from sympy.physics.quantum.gate import HadamardGate assert _test_args(HadamardGate(0)) def test_sympy__physics__quantum__gate__IdentityGate(): from sympy.physics.quantum.gate import IdentityGate assert _test_args(IdentityGate(0)) def test_sympy__physics__quantum__gate__OneQubitGate(): from sympy.physics.quantum.gate import OneQubitGate assert _test_args(OneQubitGate(0)) def test_sympy__physics__quantum__gate__PhaseGate(): from sympy.physics.quantum.gate import PhaseGate assert _test_args(PhaseGate(0)) def test_sympy__physics__quantum__gate__SwapGate(): from sympy.physics.quantum.gate import SwapGate assert _test_args(SwapGate(0, 1)) def test_sympy__physics__quantum__gate__TGate(): from sympy.physics.quantum.gate import TGate assert _test_args(TGate(0)) def test_sympy__physics__quantum__gate__TwoQubitGate(): from sympy.physics.quantum.gate import TwoQubitGate assert _test_args(TwoQubitGate(0)) def test_sympy__physics__quantum__gate__UGate(): from sympy.physics.quantum.gate import UGate from sympy.matrices.immutable import ImmutableDenseMatrix from sympy.core.containers import Tuple from sympy.core.numbers import Integer assert _test_args( UGate(Tuple(Integer(1)), ImmutableDenseMatrix([[1, 0], [0, 2]]))) def test_sympy__physics__quantum__gate__XGate(): from sympy.physics.quantum.gate import XGate assert _test_args(XGate(0)) def test_sympy__physics__quantum__gate__YGate(): from sympy.physics.quantum.gate import YGate assert _test_args(YGate(0)) def test_sympy__physics__quantum__gate__ZGate(): from sympy.physics.quantum.gate import ZGate assert _test_args(ZGate(0)) @SKIP("TODO: sympy.physics") def test_sympy__physics__quantum__grover__OracleGate(): from sympy.physics.quantum.grover import OracleGate assert _test_args(OracleGate()) def test_sympy__physics__quantum__grover__WGate(): from sympy.physics.quantum.grover import WGate assert _test_args(WGate(1)) def test_sympy__physics__quantum__hilbert__ComplexSpace(): from sympy.physics.quantum.hilbert import ComplexSpace assert _test_args(ComplexSpace(x)) def test_sympy__physics__quantum__hilbert__DirectSumHilbertSpace(): from sympy.physics.quantum.hilbert import DirectSumHilbertSpace, ComplexSpace, FockSpace c = ComplexSpace(2) f = FockSpace() assert _test_args(DirectSumHilbertSpace(c, f)) def test_sympy__physics__quantum__hilbert__FockSpace(): from sympy.physics.quantum.hilbert import FockSpace assert _test_args(FockSpace()) def test_sympy__physics__quantum__hilbert__HilbertSpace(): from sympy.physics.quantum.hilbert import HilbertSpace assert _test_args(HilbertSpace()) def test_sympy__physics__quantum__hilbert__L2(): from sympy.physics.quantum.hilbert import L2 from sympy.core.numbers import oo from sympy.sets.sets import Interval assert _test_args(L2(Interval(0, oo))) def test_sympy__physics__quantum__hilbert__TensorPowerHilbertSpace(): from sympy.physics.quantum.hilbert import TensorPowerHilbertSpace, FockSpace f = FockSpace() assert _test_args(TensorPowerHilbertSpace(f, 2)) def test_sympy__physics__quantum__hilbert__TensorProductHilbertSpace(): from sympy.physics.quantum.hilbert import TensorProductHilbertSpace, FockSpace, ComplexSpace c = ComplexSpace(2) f = FockSpace() assert _test_args(TensorProductHilbertSpace(f, c)) def test_sympy__physics__quantum__innerproduct__InnerProduct(): from sympy.physics.quantum import Bra, Ket, InnerProduct b = Bra('b') k = Ket('k') assert _test_args(InnerProduct(b, k)) def test_sympy__physics__quantum__operator__DifferentialOperator(): from sympy.physics.quantum.operator import DifferentialOperator from sympy.core.function import (Derivative, Function) f = Function('f') assert _test_args(DifferentialOperator(1/x*Derivative(f(x), x), f(x))) def test_sympy__physics__quantum__operator__HermitianOperator(): from sympy.physics.quantum.operator import HermitianOperator assert _test_args(HermitianOperator('H')) def test_sympy__physics__quantum__operator__IdentityOperator(): from sympy.physics.quantum.operator import IdentityOperator assert _test_args(IdentityOperator(5)) def test_sympy__physics__quantum__operator__Operator(): from sympy.physics.quantum.operator import Operator assert _test_args(Operator('A')) def test_sympy__physics__quantum__operator__OuterProduct(): from sympy.physics.quantum.operator import OuterProduct from sympy.physics.quantum import Ket, Bra b = Bra('b') k = Ket('k') assert _test_args(OuterProduct(k, b)) def test_sympy__physics__quantum__operator__UnitaryOperator(): from sympy.physics.quantum.operator import UnitaryOperator assert _test_args(UnitaryOperator('U')) def test_sympy__physics__quantum__piab__PIABBra(): from sympy.physics.quantum.piab import PIABBra assert _test_args(PIABBra('B')) def test_sympy__physics__quantum__boson__BosonOp(): from sympy.physics.quantum.boson import BosonOp assert _test_args(BosonOp('a')) assert _test_args(BosonOp('a', False)) def test_sympy__physics__quantum__boson__BosonFockKet(): from sympy.physics.quantum.boson import BosonFockKet assert _test_args(BosonFockKet(1)) def test_sympy__physics__quantum__boson__BosonFockBra(): from sympy.physics.quantum.boson import BosonFockBra assert _test_args(BosonFockBra(1)) def test_sympy__physics__quantum__boson__BosonCoherentKet(): from sympy.physics.quantum.boson import BosonCoherentKet assert _test_args(BosonCoherentKet(1)) def test_sympy__physics__quantum__boson__BosonCoherentBra(): from sympy.physics.quantum.boson import BosonCoherentBra assert _test_args(BosonCoherentBra(1)) def test_sympy__physics__quantum__fermion__FermionOp(): from sympy.physics.quantum.fermion import FermionOp assert _test_args(FermionOp('c')) assert _test_args(FermionOp('c', False)) def test_sympy__physics__quantum__fermion__FermionFockKet(): from sympy.physics.quantum.fermion import FermionFockKet assert _test_args(FermionFockKet(1)) def test_sympy__physics__quantum__fermion__FermionFockBra(): from sympy.physics.quantum.fermion import FermionFockBra assert _test_args(FermionFockBra(1)) def test_sympy__physics__quantum__pauli__SigmaOpBase(): from sympy.physics.quantum.pauli import SigmaOpBase assert _test_args(SigmaOpBase()) def test_sympy__physics__quantum__pauli__SigmaX(): from sympy.physics.quantum.pauli import SigmaX assert _test_args(SigmaX()) def test_sympy__physics__quantum__pauli__SigmaY(): from sympy.physics.quantum.pauli import SigmaY assert _test_args(SigmaY()) def test_sympy__physics__quantum__pauli__SigmaZ(): from sympy.physics.quantum.pauli import SigmaZ assert _test_args(SigmaZ()) def test_sympy__physics__quantum__pauli__SigmaMinus(): from sympy.physics.quantum.pauli import SigmaMinus assert _test_args(SigmaMinus()) def test_sympy__physics__quantum__pauli__SigmaPlus(): from sympy.physics.quantum.pauli import SigmaPlus assert _test_args(SigmaPlus()) def test_sympy__physics__quantum__pauli__SigmaZKet(): from sympy.physics.quantum.pauli import SigmaZKet assert _test_args(SigmaZKet(0)) def test_sympy__physics__quantum__pauli__SigmaZBra(): from sympy.physics.quantum.pauli import SigmaZBra assert _test_args(SigmaZBra(0)) def test_sympy__physics__quantum__piab__PIABHamiltonian(): from sympy.physics.quantum.piab import PIABHamiltonian assert _test_args(PIABHamiltonian('P')) def test_sympy__physics__quantum__piab__PIABKet(): from sympy.physics.quantum.piab import PIABKet assert _test_args(PIABKet('K')) def test_sympy__physics__quantum__qexpr__QExpr(): from sympy.physics.quantum.qexpr import QExpr assert _test_args(QExpr(0)) def test_sympy__physics__quantum__qft__Fourier(): from sympy.physics.quantum.qft import Fourier assert _test_args(Fourier(0, 1)) def test_sympy__physics__quantum__qft__IQFT(): from sympy.physics.quantum.qft import IQFT assert _test_args(IQFT(0, 1)) def test_sympy__physics__quantum__qft__QFT(): from sympy.physics.quantum.qft import QFT assert _test_args(QFT(0, 1)) def test_sympy__physics__quantum__qft__RkGate(): from sympy.physics.quantum.qft import RkGate assert _test_args(RkGate(0, 1)) def test_sympy__physics__quantum__qubit__IntQubit(): from sympy.physics.quantum.qubit import IntQubit assert _test_args(IntQubit(0)) def test_sympy__physics__quantum__qubit__IntQubitBra(): from sympy.physics.quantum.qubit import IntQubitBra assert _test_args(IntQubitBra(0)) def test_sympy__physics__quantum__qubit__IntQubitState(): from sympy.physics.quantum.qubit import IntQubitState, QubitState assert _test_args(IntQubitState(QubitState(0, 1))) def test_sympy__physics__quantum__qubit__Qubit(): from sympy.physics.quantum.qubit import Qubit assert _test_args(Qubit(0, 0, 0)) def test_sympy__physics__quantum__qubit__QubitBra(): from sympy.physics.quantum.qubit import QubitBra assert _test_args(QubitBra('1', 0)) def test_sympy__physics__quantum__qubit__QubitState(): from sympy.physics.quantum.qubit import QubitState assert _test_args(QubitState(0, 1)) def test_sympy__physics__quantum__density__Density(): from sympy.physics.quantum.density import Density from sympy.physics.quantum.state import Ket assert _test_args(Density([Ket(0), 0.5], [Ket(1), 0.5])) @SKIP("TODO: sympy.physics.quantum.shor: Cmod Not Implemented") def test_sympy__physics__quantum__shor__CMod(): from sympy.physics.quantum.shor import CMod assert _test_args(CMod()) def test_sympy__physics__quantum__spin__CoupledSpinState(): from sympy.physics.quantum.spin import CoupledSpinState assert _test_args(CoupledSpinState(1, 0, (1, 1))) assert _test_args(CoupledSpinState(1, 0, (1, S.Half, S.Half))) assert _test_args(CoupledSpinState( 1, 0, (1, S.Half, S.Half), ((2, 3, S.Half), (1, 2, 1)) )) j, m, j1, j2, j3, j12, x = symbols('j m j1:4 j12 x') assert CoupledSpinState( j, m, (j1, j2, j3)).subs(j2, x) == CoupledSpinState(j, m, (j1, x, j3)) assert CoupledSpinState(j, m, (j1, j2, j3), ((1, 3, j12), (1, 2, j)) ).subs(j12, x) == \ CoupledSpinState(j, m, (j1, j2, j3), ((1, 3, x), (1, 2, j)) ) def test_sympy__physics__quantum__spin__J2Op(): from sympy.physics.quantum.spin import J2Op assert _test_args(J2Op('J')) def test_sympy__physics__quantum__spin__JminusOp(): from sympy.physics.quantum.spin import JminusOp assert _test_args(JminusOp('J')) def test_sympy__physics__quantum__spin__JplusOp(): from sympy.physics.quantum.spin import JplusOp assert _test_args(JplusOp('J')) def test_sympy__physics__quantum__spin__JxBra(): from sympy.physics.quantum.spin import JxBra assert _test_args(JxBra(1, 0)) def test_sympy__physics__quantum__spin__JxBraCoupled(): from sympy.physics.quantum.spin import JxBraCoupled assert _test_args(JxBraCoupled(1, 0, (1, 1))) def test_sympy__physics__quantum__spin__JxKet(): from sympy.physics.quantum.spin import JxKet assert _test_args(JxKet(1, 0)) def test_sympy__physics__quantum__spin__JxKetCoupled(): from sympy.physics.quantum.spin import JxKetCoupled assert _test_args(JxKetCoupled(1, 0, (1, 1))) def test_sympy__physics__quantum__spin__JxOp(): from sympy.physics.quantum.spin import JxOp assert _test_args(JxOp('J')) def test_sympy__physics__quantum__spin__JyBra(): from sympy.physics.quantum.spin import JyBra assert _test_args(JyBra(1, 0)) def test_sympy__physics__quantum__spin__JyBraCoupled(): from sympy.physics.quantum.spin import JyBraCoupled assert _test_args(JyBraCoupled(1, 0, (1, 1))) def test_sympy__physics__quantum__spin__JyKet(): from sympy.physics.quantum.spin import JyKet assert _test_args(JyKet(1, 0)) def test_sympy__physics__quantum__spin__JyKetCoupled(): from sympy.physics.quantum.spin import JyKetCoupled assert _test_args(JyKetCoupled(1, 0, (1, 1))) def test_sympy__physics__quantum__spin__JyOp(): from sympy.physics.quantum.spin import JyOp assert _test_args(JyOp('J')) def test_sympy__physics__quantum__spin__JzBra(): from sympy.physics.quantum.spin import JzBra assert _test_args(JzBra(1, 0)) def test_sympy__physics__quantum__spin__JzBraCoupled(): from sympy.physics.quantum.spin import JzBraCoupled assert _test_args(JzBraCoupled(1, 0, (1, 1))) def test_sympy__physics__quantum__spin__JzKet(): from sympy.physics.quantum.spin import JzKet assert _test_args(JzKet(1, 0)) def test_sympy__physics__quantum__spin__JzKetCoupled(): from sympy.physics.quantum.spin import JzKetCoupled assert _test_args(JzKetCoupled(1, 0, (1, 1))) def test_sympy__physics__quantum__spin__JzOp(): from sympy.physics.quantum.spin import JzOp assert _test_args(JzOp('J')) def test_sympy__physics__quantum__spin__Rotation(): from sympy.physics.quantum.spin import Rotation assert _test_args(Rotation(pi, 0, pi/2)) def test_sympy__physics__quantum__spin__SpinState(): from sympy.physics.quantum.spin import SpinState assert _test_args(SpinState(1, 0)) def test_sympy__physics__quantum__spin__WignerD(): from sympy.physics.quantum.spin import WignerD assert _test_args(WignerD(0, 1, 2, 3, 4, 5)) def test_sympy__physics__quantum__state__Bra(): from sympy.physics.quantum.state import Bra assert _test_args(Bra(0)) def test_sympy__physics__quantum__state__BraBase(): from sympy.physics.quantum.state import BraBase assert _test_args(BraBase(0)) def test_sympy__physics__quantum__state__Ket(): from sympy.physics.quantum.state import Ket assert _test_args(Ket(0)) def test_sympy__physics__quantum__state__KetBase(): from sympy.physics.quantum.state import KetBase assert _test_args(KetBase(0)) def test_sympy__physics__quantum__state__State(): from sympy.physics.quantum.state import State assert _test_args(State(0)) def test_sympy__physics__quantum__state__StateBase(): from sympy.physics.quantum.state import StateBase assert _test_args(StateBase(0)) def test_sympy__physics__quantum__state__OrthogonalBra(): from sympy.physics.quantum.state import OrthogonalBra assert _test_args(OrthogonalBra(0)) def test_sympy__physics__quantum__state__OrthogonalKet(): from sympy.physics.quantum.state import OrthogonalKet assert _test_args(OrthogonalKet(0)) def test_sympy__physics__quantum__state__OrthogonalState(): from sympy.physics.quantum.state import OrthogonalState assert _test_args(OrthogonalState(0)) def test_sympy__physics__quantum__state__TimeDepBra(): from sympy.physics.quantum.state import TimeDepBra assert _test_args(TimeDepBra('psi', 't')) def test_sympy__physics__quantum__state__TimeDepKet(): from sympy.physics.quantum.state import TimeDepKet assert _test_args(TimeDepKet('psi', 't')) def test_sympy__physics__quantum__state__TimeDepState(): from sympy.physics.quantum.state import TimeDepState assert _test_args(TimeDepState('psi', 't')) def test_sympy__physics__quantum__state__Wavefunction(): from sympy.physics.quantum.state import Wavefunction from sympy.functions import sin from sympy.functions.elementary.piecewise import Piecewise n = 1 L = 1 g = Piecewise((0, x < 0), (0, x > L), (sqrt(2//L)*sin(n*pi*x/L), True)) assert _test_args(Wavefunction(g, x)) def test_sympy__physics__quantum__tensorproduct__TensorProduct(): from sympy.physics.quantum.tensorproduct import TensorProduct assert _test_args(TensorProduct(x, y)) def test_sympy__physics__quantum__identitysearch__GateIdentity(): from sympy.physics.quantum.gate import X from sympy.physics.quantum.identitysearch import GateIdentity assert _test_args(GateIdentity(X(0), X(0))) def test_sympy__physics__quantum__sho1d__SHOOp(): from sympy.physics.quantum.sho1d import SHOOp assert _test_args(SHOOp('a')) def test_sympy__physics__quantum__sho1d__RaisingOp(): from sympy.physics.quantum.sho1d import RaisingOp assert _test_args(RaisingOp('a')) def test_sympy__physics__quantum__sho1d__LoweringOp(): from sympy.physics.quantum.sho1d import LoweringOp assert _test_args(LoweringOp('a')) def test_sympy__physics__quantum__sho1d__NumberOp(): from sympy.physics.quantum.sho1d import NumberOp assert _test_args(NumberOp('N')) def test_sympy__physics__quantum__sho1d__Hamiltonian(): from sympy.physics.quantum.sho1d import Hamiltonian assert _test_args(Hamiltonian('H')) def test_sympy__physics__quantum__sho1d__SHOState(): from sympy.physics.quantum.sho1d import SHOState assert _test_args(SHOState(0)) def test_sympy__physics__quantum__sho1d__SHOKet(): from sympy.physics.quantum.sho1d import SHOKet assert _test_args(SHOKet(0)) def test_sympy__physics__quantum__sho1d__SHOBra(): from sympy.physics.quantum.sho1d import SHOBra assert _test_args(SHOBra(0)) def test_sympy__physics__secondquant__AnnihilateBoson(): from sympy.physics.secondquant import AnnihilateBoson assert _test_args(AnnihilateBoson(0)) def test_sympy__physics__secondquant__AnnihilateFermion(): from sympy.physics.secondquant import AnnihilateFermion assert _test_args(AnnihilateFermion(0)) @SKIP("abstract class") def test_sympy__physics__secondquant__Annihilator(): pass def test_sympy__physics__secondquant__AntiSymmetricTensor(): from sympy.physics.secondquant import AntiSymmetricTensor i, j = symbols('i j', below_fermi=True) a, b = symbols('a b', above_fermi=True) assert _test_args(AntiSymmetricTensor('v', (a, i), (b, j))) def test_sympy__physics__secondquant__BosonState(): from sympy.physics.secondquant import BosonState assert _test_args(BosonState((0, 1))) @SKIP("abstract class") def test_sympy__physics__secondquant__BosonicOperator(): pass def test_sympy__physics__secondquant__Commutator(): from sympy.physics.secondquant import Commutator assert _test_args(Commutator(x, y)) def test_sympy__physics__secondquant__CreateBoson(): from sympy.physics.secondquant import CreateBoson assert _test_args(CreateBoson(0)) def test_sympy__physics__secondquant__CreateFermion(): from sympy.physics.secondquant import CreateFermion assert _test_args(CreateFermion(0)) @SKIP("abstract class") def test_sympy__physics__secondquant__Creator(): pass def test_sympy__physics__secondquant__Dagger(): from sympy.physics.secondquant import Dagger from sympy.core.numbers import I assert _test_args(Dagger(2*I)) def test_sympy__physics__secondquant__FermionState(): from sympy.physics.secondquant import FermionState assert _test_args(FermionState((0, 1))) def test_sympy__physics__secondquant__FermionicOperator(): from sympy.physics.secondquant import FermionicOperator assert _test_args(FermionicOperator(0)) def test_sympy__physics__secondquant__FockState(): from sympy.physics.secondquant import FockState assert _test_args(FockState((0, 1))) def test_sympy__physics__secondquant__FockStateBosonBra(): from sympy.physics.secondquant import FockStateBosonBra assert _test_args(FockStateBosonBra((0, 1))) def test_sympy__physics__secondquant__FockStateBosonKet(): from sympy.physics.secondquant import FockStateBosonKet assert _test_args(FockStateBosonKet((0, 1))) def test_sympy__physics__secondquant__FockStateBra(): from sympy.physics.secondquant import FockStateBra assert _test_args(FockStateBra((0, 1))) def test_sympy__physics__secondquant__FockStateFermionBra(): from sympy.physics.secondquant import FockStateFermionBra assert _test_args(FockStateFermionBra((0, 1))) def test_sympy__physics__secondquant__FockStateFermionKet(): from sympy.physics.secondquant import FockStateFermionKet assert _test_args(FockStateFermionKet((0, 1))) def test_sympy__physics__secondquant__FockStateKet(): from sympy.physics.secondquant import FockStateKet assert _test_args(FockStateKet((0, 1))) def test_sympy__physics__secondquant__InnerProduct(): from sympy.physics.secondquant import InnerProduct from sympy.physics.secondquant import FockStateKet, FockStateBra assert _test_args(InnerProduct(FockStateBra((0, 1)), FockStateKet((0, 1)))) def test_sympy__physics__secondquant__NO(): from sympy.physics.secondquant import NO, F, Fd assert _test_args(NO(Fd(x)*F(y))) def test_sympy__physics__secondquant__PermutationOperator(): from sympy.physics.secondquant import PermutationOperator assert _test_args(PermutationOperator(0, 1)) def test_sympy__physics__secondquant__SqOperator(): from sympy.physics.secondquant import SqOperator assert _test_args(SqOperator(0)) def test_sympy__physics__secondquant__TensorSymbol(): from sympy.physics.secondquant import TensorSymbol assert _test_args(TensorSymbol(x)) def test_sympy__physics__control__lti__LinearTimeInvariant(): # Direct instances of LinearTimeInvariant class are not allowed. # func(*args) tests for its derived classes (TransferFunction, # Series, Parallel and TransferFunctionMatrix) should pass. pass def test_sympy__physics__control__lti__SISOLinearTimeInvariant(): # Direct instances of SISOLinearTimeInvariant class are not allowed. pass def test_sympy__physics__control__lti__MIMOLinearTimeInvariant(): # Direct instances of MIMOLinearTimeInvariant class are not allowed. pass def test_sympy__physics__control__lti__TransferFunction(): from sympy.physics.control.lti import TransferFunction assert _test_args(TransferFunction(2, 3, x)) def test_sympy__physics__control__lti__Series(): from sympy.physics.control import Series, TransferFunction tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) assert _test_args(Series(tf1, tf2)) def test_sympy__physics__control__lti__MIMOSeries(): from sympy.physics.control import MIMOSeries, TransferFunction, TransferFunctionMatrix tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) tfm_1 = TransferFunctionMatrix([[tf2, tf1]]) tfm_2 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) tfm_3 = TransferFunctionMatrix([[tf1], [tf2]]) assert _test_args(MIMOSeries(tfm_3, tfm_2, tfm_1)) def test_sympy__physics__control__lti__Parallel(): from sympy.physics.control import Parallel, TransferFunction tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) assert _test_args(Parallel(tf1, tf2)) def test_sympy__physics__control__lti__MIMOParallel(): from sympy.physics.control import MIMOParallel, TransferFunction, TransferFunctionMatrix tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]]) assert _test_args(MIMOParallel(tfm_1, tfm_2)) def test_sympy__physics__control__lti__Feedback(): from sympy.physics.control import TransferFunction, Feedback tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) assert _test_args(Feedback(tf1, tf2)) assert _test_args(Feedback(tf1, tf2, 1)) def test_sympy__physics__control__lti__MIMOFeedback(): from sympy.physics.control import TransferFunction, MIMOFeedback, TransferFunctionMatrix tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) tfm_1 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]]) tfm_2 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) assert _test_args(MIMOFeedback(tfm_1, tfm_2)) assert _test_args(MIMOFeedback(tfm_1, tfm_2, 1)) def test_sympy__physics__control__lti__TransferFunctionMatrix(): from sympy.physics.control import TransferFunction, TransferFunctionMatrix tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) assert _test_args(TransferFunctionMatrix([[tf1, tf2]])) def test_sympy__physics__units__dimensions__Dimension(): from sympy.physics.units.dimensions import Dimension assert _test_args(Dimension("length", "L")) def test_sympy__physics__units__dimensions__DimensionSystem(): from sympy.physics.units.dimensions import DimensionSystem from sympy.physics.units.definitions.dimension_definitions import length, time, velocity assert _test_args(DimensionSystem((length, time), (velocity,))) def test_sympy__physics__units__quantities__Quantity(): from sympy.physics.units.quantities import Quantity assert _test_args(Quantity("dam")) def test_sympy__physics__units__prefixes__Prefix(): from sympy.physics.units.prefixes import Prefix assert _test_args(Prefix('kilo', 'k', 3)) def test_sympy__core__numbers__AlgebraicNumber(): from sympy.core.numbers import AlgebraicNumber assert _test_args(AlgebraicNumber(sqrt(2), [1, 2, 3])) def test_sympy__polys__polytools__GroebnerBasis(): from sympy.polys.polytools import GroebnerBasis assert _test_args(GroebnerBasis([x, y, z], x, y, z)) def test_sympy__polys__polytools__Poly(): from sympy.polys.polytools import Poly assert _test_args(Poly(2, x, y)) def test_sympy__polys__polytools__PurePoly(): from sympy.polys.polytools import PurePoly assert _test_args(PurePoly(2, x, y)) @SKIP('abstract class') def test_sympy__polys__rootoftools__RootOf(): pass def test_sympy__polys__rootoftools__ComplexRootOf(): from sympy.polys.rootoftools import ComplexRootOf assert _test_args(ComplexRootOf(x**3 + x + 1, 0)) def test_sympy__polys__rootoftools__RootSum(): from sympy.polys.rootoftools import RootSum assert _test_args(RootSum(x**3 + x + 1, sin)) def test_sympy__series__limits__Limit(): from sympy.series.limits import Limit assert _test_args(Limit(x, x, 0, dir='-')) def test_sympy__series__order__Order(): from sympy.series.order import Order assert _test_args(Order(1, x, y)) @SKIP('Abstract Class') def test_sympy__series__sequences__SeqBase(): pass def test_sympy__series__sequences__EmptySequence(): # Need to imort the instance from series not the class from # series.sequence from sympy.series import EmptySequence assert _test_args(EmptySequence) @SKIP('Abstract Class') def test_sympy__series__sequences__SeqExpr(): pass def test_sympy__series__sequences__SeqPer(): from sympy.series.sequences import SeqPer assert _test_args(SeqPer((1, 2, 3), (0, 10))) def test_sympy__series__sequences__SeqFormula(): from sympy.series.sequences import SeqFormula assert _test_args(SeqFormula(x**2, (0, 10))) def test_sympy__series__sequences__RecursiveSeq(): from sympy.series.sequences import RecursiveSeq y = Function("y") n = symbols("n") assert _test_args(RecursiveSeq(y(n - 1) + y(n - 2), y(n), n, (0, 1))) assert _test_args(RecursiveSeq(y(n - 1) + y(n - 2), y(n), n)) def test_sympy__series__sequences__SeqExprOp(): from sympy.series.sequences import SeqExprOp, sequence s1 = sequence((1, 2, 3)) s2 = sequence(x**2) assert _test_args(SeqExprOp(s1, s2)) def test_sympy__series__sequences__SeqAdd(): from sympy.series.sequences import SeqAdd, sequence s1 = sequence((1, 2, 3)) s2 = sequence(x**2) assert _test_args(SeqAdd(s1, s2)) def test_sympy__series__sequences__SeqMul(): from sympy.series.sequences import SeqMul, sequence s1 = sequence((1, 2, 3)) s2 = sequence(x**2) assert _test_args(SeqMul(s1, s2)) @SKIP('Abstract Class') def test_sympy__series__series_class__SeriesBase(): pass def test_sympy__series__fourier__FourierSeries(): from sympy.series.fourier import fourier_series assert _test_args(fourier_series(x, (x, -pi, pi))) def test_sympy__series__fourier__FiniteFourierSeries(): from sympy.series.fourier import fourier_series assert _test_args(fourier_series(sin(pi*x), (x, -1, 1))) def test_sympy__series__formal__FormalPowerSeries(): from sympy.series.formal import fps assert _test_args(fps(log(1 + x), x)) def test_sympy__series__formal__Coeff(): from sympy.series.formal import fps assert _test_args(fps(x**2 + x + 1, x)) @SKIP('Abstract Class') def test_sympy__series__formal__FiniteFormalPowerSeries(): pass def test_sympy__series__formal__FormalPowerSeriesProduct(): from sympy.series.formal import fps f1, f2 = fps(sin(x)), fps(exp(x)) assert _test_args(f1.product(f2, x)) def test_sympy__series__formal__FormalPowerSeriesCompose(): from sympy.series.formal import fps f1, f2 = fps(exp(x)), fps(sin(x)) assert _test_args(f1.compose(f2, x)) def test_sympy__series__formal__FormalPowerSeriesInverse(): from sympy.series.formal import fps f1 = fps(exp(x)) assert _test_args(f1.inverse(x)) def test_sympy__simplify__hyperexpand__Hyper_Function(): from sympy.simplify.hyperexpand import Hyper_Function assert _test_args(Hyper_Function([2], [1])) def test_sympy__simplify__hyperexpand__G_Function(): from sympy.simplify.hyperexpand import G_Function assert _test_args(G_Function([2], [1], [], [])) @SKIP("abstract class") def test_sympy__tensor__array__ndim_array__ImmutableNDimArray(): pass def test_sympy__tensor__array__dense_ndim_array__ImmutableDenseNDimArray(): from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray densarr = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4)) assert _test_args(densarr) def test_sympy__tensor__array__sparse_ndim_array__ImmutableSparseNDimArray(): from sympy.tensor.array.sparse_ndim_array import ImmutableSparseNDimArray sparr = ImmutableSparseNDimArray(range(10, 34), (2, 3, 4)) assert _test_args(sparr) def test_sympy__tensor__array__array_comprehension__ArrayComprehension(): from sympy.tensor.array.array_comprehension import ArrayComprehension arrcom = ArrayComprehension(x, (x, 1, 5)) assert _test_args(arrcom) def test_sympy__tensor__array__array_comprehension__ArrayComprehensionMap(): from sympy.tensor.array.array_comprehension import ArrayComprehensionMap arrcomma = ArrayComprehensionMap(lambda: 0, (x, 1, 5)) assert _test_args(arrcomma) def test_sympy__tensor__array__array_derivatives__ArrayDerivative(): from sympy.tensor.array.array_derivatives import ArrayDerivative A = MatrixSymbol("A", 2, 2) arrder = ArrayDerivative(A, A, evaluate=False) assert _test_args(arrder) def test_sympy__tensor__array__expressions__array_expressions__ArraySymbol(): from sympy.tensor.array.expressions.array_expressions import ArraySymbol m, n, k = symbols("m n k") array = ArraySymbol("A", (m, n, k, 2)) assert _test_args(array) def test_sympy__tensor__array__expressions__array_expressions__ArrayElement(): from sympy.tensor.array.expressions.array_expressions import ArrayElement m, n, k = symbols("m n k") ae = ArrayElement("A", (m, n, k, 2)) assert _test_args(ae) def test_sympy__tensor__array__expressions__array_expressions__ZeroArray(): from sympy.tensor.array.expressions.array_expressions import ZeroArray m, n, k = symbols("m n k") za = ZeroArray(m, n, k, 2) assert _test_args(za) def test_sympy__tensor__array__expressions__array_expressions__OneArray(): from sympy.tensor.array.expressions.array_expressions import OneArray m, n, k = symbols("m n k") za = OneArray(m, n, k, 2) assert _test_args(za) def test_sympy__tensor__functions__TensorProduct(): from sympy.tensor.functions import TensorProduct A = MatrixSymbol('A', 3, 3) B = MatrixSymbol('B', 3, 3) tp = TensorProduct(A, B) assert _test_args(tp) def test_sympy__tensor__indexed__Idx(): from sympy.tensor.indexed import Idx assert _test_args(Idx('test')) assert _test_args(Idx(1, (0, 10))) def test_sympy__tensor__indexed__Indexed(): from sympy.tensor.indexed import Indexed, Idx assert _test_args(Indexed('A', Idx('i'), Idx('j'))) def test_sympy__tensor__indexed__IndexedBase(): from sympy.tensor.indexed import IndexedBase assert _test_args(IndexedBase('A', shape=(x, y))) assert _test_args(IndexedBase('A', 1)) assert _test_args(IndexedBase('A')[0, 1]) def test_sympy__tensor__tensor__TensorIndexType(): from sympy.tensor.tensor import TensorIndexType assert _test_args(TensorIndexType('Lorentz')) @SKIP("deprecated class") def test_sympy__tensor__tensor__TensorType(): pass def test_sympy__tensor__tensor__TensorSymmetry(): from sympy.tensor.tensor import TensorSymmetry, get_symmetric_group_sgs assert _test_args(TensorSymmetry(get_symmetric_group_sgs(2))) def test_sympy__tensor__tensor__TensorHead(): from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, TensorHead Lorentz = TensorIndexType('Lorentz', dummy_name='L') sym = TensorSymmetry(get_symmetric_group_sgs(1)) assert _test_args(TensorHead('p', [Lorentz], sym, 0)) def test_sympy__tensor__tensor__TensorIndex(): from sympy.tensor.tensor import TensorIndexType, TensorIndex Lorentz = TensorIndexType('Lorentz', dummy_name='L') assert _test_args(TensorIndex('i', Lorentz)) @SKIP("abstract class") def test_sympy__tensor__tensor__TensExpr(): pass def test_sympy__tensor__tensor__TensAdd(): from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, tensor_indices, TensAdd, tensor_heads Lorentz = TensorIndexType('Lorentz', dummy_name='L') a, b = tensor_indices('a,b', Lorentz) sym = TensorSymmetry(get_symmetric_group_sgs(1)) p, q = tensor_heads('p,q', [Lorentz], sym) t1 = p(a) t2 = q(a) assert _test_args(TensAdd(t1, t2)) def test_sympy__tensor__tensor__Tensor(): from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, tensor_indices, TensorHead Lorentz = TensorIndexType('Lorentz', dummy_name='L') a, b = tensor_indices('a,b', Lorentz) sym = TensorSymmetry(get_symmetric_group_sgs(1)) p = TensorHead('p', [Lorentz], sym) assert _test_args(p(a)) def test_sympy__tensor__tensor__TensMul(): from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, tensor_indices, tensor_heads Lorentz = TensorIndexType('Lorentz', dummy_name='L') a, b = tensor_indices('a,b', Lorentz) sym = TensorSymmetry(get_symmetric_group_sgs(1)) p, q = tensor_heads('p, q', [Lorentz], sym) assert _test_args(3*p(a)*q(b)) def test_sympy__tensor__tensor__TensorElement(): from sympy.tensor.tensor import TensorIndexType, TensorHead, TensorElement L = TensorIndexType("L") A = TensorHead("A", [L, L]) telem = TensorElement(A(x, y), {x: 1}) assert _test_args(telem) def test_sympy__tensor__toperators__PartialDerivative(): from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead from sympy.tensor.toperators import PartialDerivative Lorentz = TensorIndexType('Lorentz', dummy_name='L') a, b = tensor_indices('a,b', Lorentz) A = TensorHead("A", [Lorentz]) assert _test_args(PartialDerivative(A(a), A(b))) def test_as_coeff_add(): assert (7, (3*x, 4*x**2)) == (7 + 3*x + 4*x**2).as_coeff_add() def test_sympy__geometry__curve__Curve(): from sympy.geometry.curve import Curve assert _test_args(Curve((x, 1), (x, 0, 1))) def test_sympy__geometry__point__Point(): from sympy.geometry.point import Point assert _test_args(Point(0, 1)) def test_sympy__geometry__point__Point2D(): from sympy.geometry.point import Point2D assert _test_args(Point2D(0, 1)) def test_sympy__geometry__point__Point3D(): from sympy.geometry.point import Point3D assert _test_args(Point3D(0, 1, 2)) def test_sympy__geometry__ellipse__Ellipse(): from sympy.geometry.ellipse import Ellipse assert _test_args(Ellipse((0, 1), 2, 3)) def test_sympy__geometry__ellipse__Circle(): from sympy.geometry.ellipse import Circle assert _test_args(Circle((0, 1), 2)) def test_sympy__geometry__parabola__Parabola(): from sympy.geometry.parabola import Parabola from sympy.geometry.line import Line assert _test_args(Parabola((0, 0), Line((2, 3), (4, 3)))) @SKIP("abstract class") def test_sympy__geometry__line__LinearEntity(): pass def test_sympy__geometry__line__Line(): from sympy.geometry.line import Line assert _test_args(Line((0, 1), (2, 3))) def test_sympy__geometry__line__Ray(): from sympy.geometry.line import Ray assert _test_args(Ray((0, 1), (2, 3))) def test_sympy__geometry__line__Segment(): from sympy.geometry.line import Segment assert _test_args(Segment((0, 1), (2, 3))) @SKIP("abstract class") def test_sympy__geometry__line__LinearEntity2D(): pass def test_sympy__geometry__line__Line2D(): from sympy.geometry.line import Line2D assert _test_args(Line2D((0, 1), (2, 3))) def test_sympy__geometry__line__Ray2D(): from sympy.geometry.line import Ray2D assert _test_args(Ray2D((0, 1), (2, 3))) def test_sympy__geometry__line__Segment2D(): from sympy.geometry.line import Segment2D assert _test_args(Segment2D((0, 1), (2, 3))) @SKIP("abstract class") def test_sympy__geometry__line__LinearEntity3D(): pass def test_sympy__geometry__line__Line3D(): from sympy.geometry.line import Line3D assert _test_args(Line3D((0, 1, 1), (2, 3, 4))) def test_sympy__geometry__line__Segment3D(): from sympy.geometry.line import Segment3D assert _test_args(Segment3D((0, 1, 1), (2, 3, 4))) def test_sympy__geometry__line__Ray3D(): from sympy.geometry.line import Ray3D assert _test_args(Ray3D((0, 1, 1), (2, 3, 4))) def test_sympy__geometry__plane__Plane(): from sympy.geometry.plane import Plane assert _test_args(Plane((1, 1, 1), (-3, 4, -2), (1, 2, 3))) def test_sympy__geometry__polygon__Polygon(): from sympy.geometry.polygon import Polygon assert _test_args(Polygon((0, 1), (2, 3), (4, 5), (6, 7))) def test_sympy__geometry__polygon__RegularPolygon(): from sympy.geometry.polygon import RegularPolygon assert _test_args(RegularPolygon((0, 1), 2, 3, 4)) def test_sympy__geometry__polygon__Triangle(): from sympy.geometry.polygon import Triangle assert _test_args(Triangle((0, 1), (2, 3), (4, 5))) def test_sympy__geometry__entity__GeometryEntity(): from sympy.geometry.entity import GeometryEntity from sympy.geometry.point import Point assert _test_args(GeometryEntity(Point(1, 0), 1, [1, 2])) @SKIP("abstract class") def test_sympy__geometry__entity__GeometrySet(): pass def test_sympy__diffgeom__diffgeom__Manifold(): from sympy.diffgeom import Manifold assert _test_args(Manifold('name', 3)) def test_sympy__diffgeom__diffgeom__Patch(): from sympy.diffgeom import Manifold, Patch assert _test_args(Patch('name', Manifold('name', 3))) def test_sympy__diffgeom__diffgeom__CoordSystem(): from sympy.diffgeom import Manifold, Patch, CoordSystem assert _test_args(CoordSystem('name', Patch('name', Manifold('name', 3)))) assert _test_args(CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])) def test_sympy__diffgeom__diffgeom__CoordinateSymbol(): from sympy.diffgeom import Manifold, Patch, CoordSystem, CoordinateSymbol assert _test_args(CoordinateSymbol(CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]), 0)) def test_sympy__diffgeom__diffgeom__Point(): from sympy.diffgeom import Manifold, Patch, CoordSystem, Point assert _test_args(Point( CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]), [x, y])) def test_sympy__diffgeom__diffgeom__BaseScalarField(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) assert _test_args(BaseScalarField(cs, 0)) def test_sympy__diffgeom__diffgeom__BaseVectorField(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorField cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) assert _test_args(BaseVectorField(cs, 0)) def test_sympy__diffgeom__diffgeom__Differential(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) assert _test_args(Differential(BaseScalarField(cs, 0))) def test_sympy__diffgeom__diffgeom__Commutator(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorField, Commutator cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) cs1 = CoordSystem('name1', Patch('name', Manifold('name', 3)), [a, b, c]) v = BaseVectorField(cs, 0) v1 = BaseVectorField(cs1, 0) assert _test_args(Commutator(v, v1)) def test_sympy__diffgeom__diffgeom__TensorProduct(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, TensorProduct cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) d = Differential(BaseScalarField(cs, 0)) assert _test_args(TensorProduct(d, d)) def test_sympy__diffgeom__diffgeom__WedgeProduct(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, WedgeProduct cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) d = Differential(BaseScalarField(cs, 0)) d1 = Differential(BaseScalarField(cs, 1)) assert _test_args(WedgeProduct(d, d1)) def test_sympy__diffgeom__diffgeom__LieDerivative(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, BaseVectorField, LieDerivative cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) d = Differential(BaseScalarField(cs, 0)) v = BaseVectorField(cs, 0) assert _test_args(LieDerivative(v, d)) @XFAIL def test_sympy__diffgeom__diffgeom__BaseCovarDerivativeOp(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseCovarDerivativeOp cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) assert _test_args(BaseCovarDerivativeOp(cs, 0, [[[0, ]*3, ]*3, ]*3)) def test_sympy__diffgeom__diffgeom__CovarDerivativeOp(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorField, CovarDerivativeOp cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) v = BaseVectorField(cs, 0) _test_args(CovarDerivativeOp(v, [[[0, ]*3, ]*3, ]*3)) def test_sympy__categories__baseclasses__Class(): from sympy.categories.baseclasses import Class assert _test_args(Class()) def test_sympy__categories__baseclasses__Object(): from sympy.categories import Object assert _test_args(Object("A")) @XFAIL def test_sympy__categories__baseclasses__Morphism(): from sympy.categories import Object, Morphism assert _test_args(Morphism(Object("A"), Object("B"))) def test_sympy__categories__baseclasses__IdentityMorphism(): from sympy.categories import Object, IdentityMorphism assert _test_args(IdentityMorphism(Object("A"))) def test_sympy__categories__baseclasses__NamedMorphism(): from sympy.categories import Object, NamedMorphism assert _test_args(NamedMorphism(Object("A"), Object("B"), "f")) def test_sympy__categories__baseclasses__CompositeMorphism(): from sympy.categories import Object, NamedMorphism, CompositeMorphism A = Object("A") B = Object("B") C = Object("C") f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") assert _test_args(CompositeMorphism(f, g)) def test_sympy__categories__baseclasses__Diagram(): from sympy.categories import Object, NamedMorphism, Diagram A = Object("A") B = Object("B") f = NamedMorphism(A, B, "f") d = Diagram([f]) assert _test_args(d) def test_sympy__categories__baseclasses__Category(): from sympy.categories import Object, NamedMorphism, Diagram, Category A = Object("A") B = Object("B") C = Object("C") f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") d1 = Diagram([f, g]) d2 = Diagram([f]) K = Category("K", commutative_diagrams=[d1, d2]) assert _test_args(K) def test_sympy__ntheory__factor___totient(): from sympy.ntheory.factor_ import totient k = symbols('k', integer=True) t = totient(k) assert _test_args(t) def test_sympy__ntheory__factor___reduced_totient(): from sympy.ntheory.factor_ import reduced_totient k = symbols('k', integer=True) t = reduced_totient(k) assert _test_args(t) def test_sympy__ntheory__factor___divisor_sigma(): from sympy.ntheory.factor_ import divisor_sigma k = symbols('k', integer=True) n = symbols('n', integer=True) t = divisor_sigma(n, k) assert _test_args(t) def test_sympy__ntheory__factor___udivisor_sigma(): from sympy.ntheory.factor_ import udivisor_sigma k = symbols('k', integer=True) n = symbols('n', integer=True) t = udivisor_sigma(n, k) assert _test_args(t) def test_sympy__ntheory__factor___primenu(): from sympy.ntheory.factor_ import primenu n = symbols('n', integer=True) t = primenu(n) assert _test_args(t) def test_sympy__ntheory__factor___primeomega(): from sympy.ntheory.factor_ import primeomega n = symbols('n', integer=True) t = primeomega(n) assert _test_args(t) def test_sympy__ntheory__residue_ntheory__mobius(): from sympy.ntheory import mobius assert _test_args(mobius(2)) def test_sympy__ntheory__generate__primepi(): from sympy.ntheory import primepi n = symbols('n') t = primepi(n) assert _test_args(t) def test_sympy__physics__optics__waves__TWave(): from sympy.physics.optics import TWave A, f, phi = symbols('A, f, phi') assert _test_args(TWave(A, f, phi)) def test_sympy__physics__optics__gaussopt__BeamParameter(): from sympy.physics.optics import BeamParameter assert _test_args(BeamParameter(530e-9, 1, w=1e-3)) def test_sympy__physics__optics__medium__Medium(): from sympy.physics.optics import Medium assert _test_args(Medium('m')) def test_sympy__tensor__array__expressions__array_expressions__ArrayContraction(): from sympy.tensor.array.expressions.array_expressions import ArrayContraction from sympy.tensor.indexed import IndexedBase A = symbols("A", cls=IndexedBase) assert _test_args(ArrayContraction(A, (0, 1))) def test_sympy__tensor__array__expressions__array_expressions__ArrayDiagonal(): from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal from sympy.tensor.indexed import IndexedBase A = symbols("A", cls=IndexedBase) assert _test_args(ArrayDiagonal(A, (0, 1))) def test_sympy__tensor__array__expressions__array_expressions__ArrayTensorProduct(): from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct from sympy.tensor.indexed import IndexedBase A, B = symbols("A B", cls=IndexedBase) assert _test_args(ArrayTensorProduct(A, B)) def test_sympy__tensor__array__expressions__array_expressions__ArrayAdd(): from sympy.tensor.array.expressions.array_expressions import ArrayAdd from sympy.tensor.indexed import IndexedBase A, B = symbols("A B", cls=IndexedBase) assert _test_args(ArrayAdd(A, B)) def test_sympy__tensor__array__expressions__array_expressions__PermuteDims(): from sympy.tensor.array.expressions.array_expressions import PermuteDims A = MatrixSymbol("A", 4, 4) assert _test_args(PermuteDims(A, (1, 0))) def test_sympy__tensor__array__expressions__array_expressions__ArrayElementwiseApplyFunc(): from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayElementwiseApplyFunc A = ArraySymbol("A", (4,)) assert _test_args(ArrayElementwiseApplyFunc(exp, A)) def test_sympy__codegen__ast__Assignment(): from sympy.codegen.ast import Assignment assert _test_args(Assignment(x, y)) def test_sympy__codegen__cfunctions__expm1(): from sympy.codegen.cfunctions import expm1 assert _test_args(expm1(x)) def test_sympy__codegen__cfunctions__log1p(): from sympy.codegen.cfunctions import log1p assert _test_args(log1p(x)) def test_sympy__codegen__cfunctions__exp2(): from sympy.codegen.cfunctions import exp2 assert _test_args(exp2(x)) def test_sympy__codegen__cfunctions__log2(): from sympy.codegen.cfunctions import log2 assert _test_args(log2(x)) def test_sympy__codegen__cfunctions__fma(): from sympy.codegen.cfunctions import fma assert _test_args(fma(x, y, z)) def test_sympy__codegen__cfunctions__log10(): from sympy.codegen.cfunctions import log10 assert _test_args(log10(x)) def test_sympy__codegen__cfunctions__Sqrt(): from sympy.codegen.cfunctions import Sqrt assert _test_args(Sqrt(x)) def test_sympy__codegen__cfunctions__Cbrt(): from sympy.codegen.cfunctions import Cbrt assert _test_args(Cbrt(x)) def test_sympy__codegen__cfunctions__hypot(): from sympy.codegen.cfunctions import hypot assert _test_args(hypot(x, y)) def test_sympy__codegen__fnodes__FFunction(): from sympy.codegen.fnodes import FFunction assert _test_args(FFunction('f')) def test_sympy__codegen__fnodes__F95Function(): from sympy.codegen.fnodes import F95Function assert _test_args(F95Function('f')) def test_sympy__codegen__fnodes__isign(): from sympy.codegen.fnodes import isign assert _test_args(isign(1, x)) def test_sympy__codegen__fnodes__dsign(): from sympy.codegen.fnodes import dsign assert _test_args(dsign(1, x)) def test_sympy__codegen__fnodes__cmplx(): from sympy.codegen.fnodes import cmplx assert _test_args(cmplx(x, y)) def test_sympy__codegen__fnodes__kind(): from sympy.codegen.fnodes import kind assert _test_args(kind(x)) def test_sympy__codegen__fnodes__merge(): from sympy.codegen.fnodes import merge assert _test_args(merge(1, 2, Eq(x, 0))) def test_sympy__codegen__fnodes___literal(): from sympy.codegen.fnodes import _literal assert _test_args(_literal(1)) def test_sympy__codegen__fnodes__literal_sp(): from sympy.codegen.fnodes import literal_sp assert _test_args(literal_sp(1)) def test_sympy__codegen__fnodes__literal_dp(): from sympy.codegen.fnodes import literal_dp assert _test_args(literal_dp(1)) def test_sympy__codegen__matrix_nodes__MatrixSolve(): from sympy.matrices import MatrixSymbol from sympy.codegen.matrix_nodes import MatrixSolve A = MatrixSymbol('A', 3, 3) v = MatrixSymbol('x', 3, 1) assert _test_args(MatrixSolve(A, v)) def test_sympy__vector__coordsysrect__CoordSys3D(): from sympy.vector.coordsysrect import CoordSys3D assert _test_args(CoordSys3D('C')) def test_sympy__vector__point__Point(): from sympy.vector.point import Point assert _test_args(Point('P')) def test_sympy__vector__basisdependent__BasisDependent(): #from sympy.vector.basisdependent import BasisDependent #These classes have been created to maintain an OOP hierarchy #for Vectors and Dyadics. Are NOT meant to be initialized pass def test_sympy__vector__basisdependent__BasisDependentMul(): #from sympy.vector.basisdependent import BasisDependentMul #These classes have been created to maintain an OOP hierarchy #for Vectors and Dyadics. Are NOT meant to be initialized pass def test_sympy__vector__basisdependent__BasisDependentAdd(): #from sympy.vector.basisdependent import BasisDependentAdd #These classes have been created to maintain an OOP hierarchy #for Vectors and Dyadics. Are NOT meant to be initialized pass def test_sympy__vector__basisdependent__BasisDependentZero(): #from sympy.vector.basisdependent import BasisDependentZero #These classes have been created to maintain an OOP hierarchy #for Vectors and Dyadics. Are NOT meant to be initialized pass def test_sympy__vector__vector__BaseVector(): from sympy.vector.vector import BaseVector from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(BaseVector(0, C, ' ', ' ')) def test_sympy__vector__vector__VectorAdd(): from sympy.vector.vector import VectorAdd, VectorMul from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') from sympy.abc import a, b, c, x, y, z v1 = a*C.i + b*C.j + c*C.k v2 = x*C.i + y*C.j + z*C.k assert _test_args(VectorAdd(v1, v2)) assert _test_args(VectorMul(x, v1)) def test_sympy__vector__vector__VectorMul(): from sympy.vector.vector import VectorMul from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') from sympy.abc import a assert _test_args(VectorMul(a, C.i)) def test_sympy__vector__vector__VectorZero(): from sympy.vector.vector import VectorZero assert _test_args(VectorZero()) def test_sympy__vector__vector__Vector(): #from sympy.vector.vector import Vector #Vector is never to be initialized using args pass def test_sympy__vector__vector__Cross(): from sympy.vector.vector import Cross from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') _test_args(Cross(C.i, C.j)) def test_sympy__vector__vector__Dot(): from sympy.vector.vector import Dot from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') _test_args(Dot(C.i, C.j)) def test_sympy__vector__dyadic__Dyadic(): #from sympy.vector.dyadic import Dyadic #Dyadic is never to be initialized using args pass def test_sympy__vector__dyadic__BaseDyadic(): from sympy.vector.dyadic import BaseDyadic from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(BaseDyadic(C.i, C.j)) def test_sympy__vector__dyadic__DyadicMul(): from sympy.vector.dyadic import BaseDyadic, DyadicMul from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(DyadicMul(3, BaseDyadic(C.i, C.j))) def test_sympy__vector__dyadic__DyadicAdd(): from sympy.vector.dyadic import BaseDyadic, DyadicAdd from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(2 * DyadicAdd(BaseDyadic(C.i, C.i), BaseDyadic(C.i, C.j))) def test_sympy__vector__dyadic__DyadicZero(): from sympy.vector.dyadic import DyadicZero assert _test_args(DyadicZero()) def test_sympy__vector__deloperator__Del(): from sympy.vector.deloperator import Del assert _test_args(Del()) def test_sympy__vector__implicitregion__ImplicitRegion(): from sympy.vector.implicitregion import ImplicitRegion from sympy.abc import x, y assert _test_args(ImplicitRegion((x, y), y**3 - 4*x)) def test_sympy__vector__integrals__ParametricIntegral(): from sympy.vector.integrals import ParametricIntegral from sympy.vector.parametricregion import ParametricRegion from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(ParametricIntegral(C.y*C.i - 10*C.j,\ ParametricRegion((x, y), (x, 1, 3), (y, -2, 2)))) def test_sympy__vector__operators__Curl(): from sympy.vector.operators import Curl from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(Curl(C.i)) def test_sympy__vector__operators__Laplacian(): from sympy.vector.operators import Laplacian from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(Laplacian(C.i)) def test_sympy__vector__operators__Divergence(): from sympy.vector.operators import Divergence from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(Divergence(C.i)) def test_sympy__vector__operators__Gradient(): from sympy.vector.operators import Gradient from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(Gradient(C.x)) def test_sympy__vector__orienters__Orienter(): #from sympy.vector.orienters import Orienter #Not to be initialized pass def test_sympy__vector__orienters__ThreeAngleOrienter(): #from sympy.vector.orienters import ThreeAngleOrienter #Not to be initialized pass def test_sympy__vector__orienters__AxisOrienter(): from sympy.vector.orienters import AxisOrienter from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(AxisOrienter(x, C.i)) def test_sympy__vector__orienters__BodyOrienter(): from sympy.vector.orienters import BodyOrienter assert _test_args(BodyOrienter(x, y, z, '123')) def test_sympy__vector__orienters__SpaceOrienter(): from sympy.vector.orienters import SpaceOrienter assert _test_args(SpaceOrienter(x, y, z, '123')) def test_sympy__vector__orienters__QuaternionOrienter(): from sympy.vector.orienters import QuaternionOrienter a, b, c, d = symbols('a b c d') assert _test_args(QuaternionOrienter(a, b, c, d)) def test_sympy__vector__parametricregion__ParametricRegion(): from sympy.abc import t from sympy.vector.parametricregion import ParametricRegion assert _test_args(ParametricRegion((t, t**3), (t, 0, 2))) def test_sympy__vector__scalar__BaseScalar(): from sympy.vector.scalar import BaseScalar from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(BaseScalar(0, C, ' ', ' ')) def test_sympy__physics__wigner__Wigner3j(): from sympy.physics.wigner import Wigner3j assert _test_args(Wigner3j(0, 0, 0, 0, 0, 0)) def test_sympy__integrals__rubi__symbol__matchpyWC(): from sympy.integrals.rubi.symbol import matchpyWC assert _test_args(matchpyWC(1, True, 'a')) def test_sympy__integrals__rubi__utility_function__rubi_unevaluated_expr(): from sympy.integrals.rubi.utility_function import rubi_unevaluated_expr a = symbols('a') assert _test_args(rubi_unevaluated_expr(a)) def test_sympy__integrals__rubi__utility_function__rubi_exp(): from sympy.integrals.rubi.utility_function import rubi_exp assert _test_args(rubi_exp(5)) def test_sympy__integrals__rubi__utility_function__rubi_log(): from sympy.integrals.rubi.utility_function import rubi_log assert _test_args(rubi_log(5)) def test_sympy__integrals__rubi__utility_function__Int(): from sympy.integrals.rubi.utility_function import Int assert _test_args(Int(5, x)) def test_sympy__integrals__rubi__utility_function__Util_Coefficient(): from sympy.integrals.rubi.utility_function import Util_Coefficient a, x = symbols('a x') assert _test_args(Util_Coefficient(a, x)) def test_sympy__integrals__rubi__utility_function__Gamma(): from sympy.integrals.rubi.utility_function import Gamma assert _test_args(Gamma(5)) def test_sympy__integrals__rubi__utility_function__Util_Part(): from sympy.integrals.rubi.utility_function import Util_Part a, b = symbols('a b') assert _test_args(Util_Part(a + b, 0)) def test_sympy__integrals__rubi__utility_function__PolyGamma(): from sympy.integrals.rubi.utility_function import PolyGamma assert _test_args(PolyGamma(1, 1)) def test_sympy__integrals__rubi__utility_function__ProductLog(): from sympy.integrals.rubi.utility_function import ProductLog assert _test_args(ProductLog(1)) def test_sympy__combinatorics__schur_number__SchurNumber(): from sympy.combinatorics.schur_number import SchurNumber assert _test_args(SchurNumber(1)) def test_sympy__combinatorics__perm_groups__SymmetricPermutationGroup(): from sympy.combinatorics.perm_groups import SymmetricPermutationGroup assert _test_args(SymmetricPermutationGroup(5)) def test_sympy__combinatorics__perm_groups__Coset(): from sympy.combinatorics.permutations import Permutation from sympy.combinatorics.perm_groups import PermutationGroup, Coset a = Permutation(1, 2) b = Permutation(0, 1) G = PermutationGroup([a, b]) assert _test_args(Coset(a, G))
58800a5e77f76d033780e40219ac42d9b7f9e757a2bd8bae36dfa0420f29893c
import numbers as nums import decimal from sympy.concrete.summations import Sum from sympy.core import (EulerGamma, Catalan, TribonacciConstant, GoldenRatio) from sympy.core.containers import Tuple from sympy.core.logic import fuzzy_not from sympy.core.mul import Mul from sympy.core.numbers import (mpf_norm, mod_inverse, igcd, seterr, igcd_lehmer, Integer, I, pi, comp, ilcm, Rational, E, nan, igcd2, oo, AlgebraicNumber, igcdex, Number, Float, zoo) from sympy.core.power import Pow from sympy.core.relational import Ge, Gt, Le, Lt from sympy.core.singleton import S from sympy.core.symbol import Dummy, Symbol from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import factorial from sympy.functions.combinatorial.numbers import fibonacci from sympy.functions.elementary.exponential import exp, log from sympy.functions.elementary.miscellaneous import sqrt, cbrt from sympy.functions.elementary.trigonometric import cos, sin from sympy.polys.domains.realfield import RealField from sympy.printing.latex import latex from sympy.printing.repr import srepr from sympy.simplify import simplify from sympy.core.power import integer_nthroot, isqrt, integer_log from sympy.polys.domains.groundtypes import PythonRational from sympy.utilities.decorator import conserve_mpmath_dps from sympy.utilities.iterables import permutations from sympy.testing.pytest import XFAIL, raises, _both_exp_pow from mpmath import mpf from mpmath.rational import mpq import mpmath from sympy.core import numbers t = Symbol('t', real=False) _ninf = float(-oo) _inf = float(oo) def same_and_same_prec(a, b): # stricter matching for Floats return a == b and a._prec == b._prec def test_seterr(): seterr(divide=True) raises(ValueError, lambda: S.Zero/S.Zero) seterr(divide=False) assert S.Zero / S.Zero is S.NaN def test_mod(): x = S.Half y = Rational(3, 4) z = Rational(5, 18043) assert x % x == 0 assert x % y == S.Half assert x % z == Rational(3, 36086) assert y % x == Rational(1, 4) assert y % y == 0 assert y % z == Rational(9, 72172) assert z % x == Rational(5, 18043) assert z % y == Rational(5, 18043) assert z % z == 0 a = Float(2.6) assert (a % .2) == 0.0 assert (a % 2).round(15) == 0.6 assert (a % 0.5).round(15) == 0.1 p = Symbol('p', infinite=True) assert oo % oo is nan assert zoo % oo is nan assert 5 % oo is nan assert p % 5 is nan # In these two tests, if the precision of m does # not match the precision of the ans, then it is # likely that the change made now gives an answer # with degraded accuracy. r = Rational(500, 41) f = Float('.36', 3) m = r % f ans = Float(r % Rational(f), 3) assert m == ans and m._prec == ans._prec f = Float('8.36', 3) m = f % r ans = Float(Rational(f) % r, 3) assert m == ans and m._prec == ans._prec s = S.Zero assert s % float(1) == 0.0 # No rounding required since these numbers can be represented # exactly. assert Rational(3, 4) % Float(1.1) == 0.75 assert Float(1.5) % Rational(5, 4) == 0.25 assert Rational(5, 4).__rmod__(Float('1.5')) == 0.25 assert Float('1.5').__rmod__(Float('2.75')) == Float('1.25') assert 2.75 % Float('1.5') == Float('1.25') a = Integer(7) b = Integer(4) assert type(a % b) == Integer assert a % b == Integer(3) assert Integer(1) % Rational(2, 3) == Rational(1, 3) assert Rational(7, 5) % Integer(1) == Rational(2, 5) assert Integer(2) % 1.5 == 0.5 assert Integer(3).__rmod__(Integer(10)) == Integer(1) assert Integer(10) % 4 == Integer(2) assert 15 % Integer(4) == Integer(3) def test_divmod(): assert divmod(S(12), S(8)) == Tuple(1, 4) assert divmod(-S(12), S(8)) == Tuple(-2, 4) assert divmod(S.Zero, S.One) == Tuple(0, 0) raises(ZeroDivisionError, lambda: divmod(S.Zero, S.Zero)) raises(ZeroDivisionError, lambda: divmod(S.One, S.Zero)) assert divmod(S(12), 8) == Tuple(1, 4) assert divmod(12, S(8)) == Tuple(1, 4) assert divmod(S("2"), S("3/2")) == Tuple(S("1"), S("1/2")) assert divmod(S("3/2"), S("2")) == Tuple(S("0"), S("3/2")) assert divmod(S("2"), S("3.5")) == Tuple(S("0"), S("2")) assert divmod(S("3.5"), S("2")) == Tuple(S("1"), S("1.5")) assert divmod(S("2"), S("1/3")) == Tuple(S("6"), S("0")) assert divmod(S("1/3"), S("2")) == Tuple(S("0"), S("1/3")) assert divmod(S("2"), S("1/10")) == Tuple(S("20"), S("0")) assert divmod(S("2"), S(".1"))[0] == 19 assert divmod(S("0.1"), S("2")) == Tuple(S("0"), S("0.1")) assert divmod(S("2"), 2) == Tuple(S("1"), S("0")) assert divmod(2, S("2")) == Tuple(S("1"), S("0")) assert divmod(S("2"), 1.5) == Tuple(S("1"), S("0.5")) assert divmod(1.5, S("2")) == Tuple(S("0"), S("1.5")) assert divmod(0.3, S("2")) == Tuple(S("0"), S("0.3")) assert divmod(S("3/2"), S("3.5")) == Tuple(S("0"), S("3/2")) assert divmod(S("3.5"), S("3/2")) == Tuple(S("2"), S("0.5")) assert divmod(S("3/2"), S("1/3")) == Tuple(S("4"), S("1/6")) assert divmod(S("1/3"), S("3/2")) == Tuple(S("0"), S("1/3")) assert divmod(S("3/2"), S("0.1"))[0] == 14 assert divmod(S("0.1"), S("3/2")) == Tuple(S("0"), S("0.1")) assert divmod(S("3/2"), 2) == Tuple(S("0"), S("3/2")) assert divmod(2, S("3/2")) == Tuple(S("1"), S("1/2")) assert divmod(S("3/2"), 1.5) == Tuple(S("1"), S("0")) assert divmod(1.5, S("3/2")) == Tuple(S("1"), S("0")) assert divmod(S("3/2"), 0.3) == Tuple(S("5"), S("0")) assert divmod(0.3, S("3/2")) == Tuple(S("0"), S("0.3")) assert divmod(S("1/3"), S("3.5")) == Tuple(S("0"), S("1/3")) assert divmod(S("3.5"), S("0.1")) == Tuple(S("35"), S("0")) assert divmod(S("0.1"), S("3.5")) == Tuple(S("0"), S("0.1")) assert divmod(S("3.5"), 2) == Tuple(S("1"), S("1.5")) assert divmod(2, S("3.5")) == Tuple(S("0"), S("2")) assert divmod(S("3.5"), 1.5) == Tuple(S("2"), S("0.5")) assert divmod(1.5, S("3.5")) == Tuple(S("0"), S("1.5")) assert divmod(0.3, S("3.5")) == Tuple(S("0"), S("0.3")) assert divmod(S("0.1"), S("1/3")) == Tuple(S("0"), S("0.1")) assert divmod(S("1/3"), 2) == Tuple(S("0"), S("1/3")) assert divmod(2, S("1/3")) == Tuple(S("6"), S("0")) assert divmod(S("1/3"), 1.5) == Tuple(S("0"), S("1/3")) assert divmod(0.3, S("1/3")) == Tuple(S("0"), S("0.3")) assert divmod(S("0.1"), 2) == Tuple(S("0"), S("0.1")) assert divmod(2, S("0.1"))[0] == 19 assert divmod(S("0.1"), 1.5) == Tuple(S("0"), S("0.1")) assert divmod(1.5, S("0.1")) == Tuple(S("15"), S("0")) assert divmod(S("0.1"), 0.3) == Tuple(S("0"), S("0.1")) assert str(divmod(S("2"), 0.3)) == '(6, 0.2)' assert str(divmod(S("3.5"), S("1/3"))) == '(10, 0.166666666666667)' assert str(divmod(S("3.5"), 0.3)) == '(11, 0.2)' assert str(divmod(S("1/3"), S("0.1"))) == '(3, 0.0333333333333333)' assert str(divmod(1.5, S("1/3"))) == '(4, 0.166666666666667)' assert str(divmod(S("1/3"), 0.3)) == '(1, 0.0333333333333333)' assert str(divmod(0.3, S("0.1"))) == '(2, 0.1)' assert divmod(-3, S(2)) == (-2, 1) assert divmod(S(-3), S(2)) == (-2, 1) assert divmod(S(-3), 2) == (-2, 1) assert divmod(S(4), S(-3.1)) == Tuple(-2, -2.2) assert divmod(S(4), S(-2.1)) == divmod(4, -2.1) assert divmod(S(-8), S(-2.5) ) == Tuple(3, -0.5) assert divmod(oo, 1) == (S.NaN, S.NaN) assert divmod(S.NaN, 1) == (S.NaN, S.NaN) assert divmod(1, S.NaN) == (S.NaN, S.NaN) ans = [(-1, oo), (-1, oo), (0, 0), (0, 1), (0, 2)] OO = float('inf') ANS = [tuple(map(float, i)) for i in ans] assert [divmod(i, oo) for i in range(-2, 3)] == ans ans = [(0, -2), (0, -1), (0, 0), (-1, -oo), (-1, -oo)] ANS = [tuple(map(float, i)) for i in ans] assert [divmod(i, -oo) for i in range(-2, 3)] == ans assert [divmod(i, -OO) for i in range(-2, 3)] == ANS assert divmod(S(3.5), S(-2)) == divmod(3.5, -2) assert divmod(-S(3.5), S(-2)) == divmod(-3.5, -2) assert divmod(S(0.0), S(9)) == divmod(0.0, 9) assert divmod(S(0), S(9.0)) == divmod(0, 9.0) def test_igcd(): assert igcd(0, 0) == 0 assert igcd(0, 1) == 1 assert igcd(1, 0) == 1 assert igcd(0, 7) == 7 assert igcd(7, 0) == 7 assert igcd(7, 1) == 1 assert igcd(1, 7) == 1 assert igcd(-1, 0) == 1 assert igcd(0, -1) == 1 assert igcd(-1, -1) == 1 assert igcd(-1, 7) == 1 assert igcd(7, -1) == 1 assert igcd(8, 2) == 2 assert igcd(4, 8) == 4 assert igcd(8, 16) == 8 assert igcd(7, -3) == 1 assert igcd(-7, 3) == 1 assert igcd(-7, -3) == 1 assert igcd(*[10, 20, 30]) == 10 raises(TypeError, lambda: igcd()) raises(TypeError, lambda: igcd(2)) raises(ValueError, lambda: igcd(0, None)) raises(ValueError, lambda: igcd(1, 2.2)) for args in permutations((45.1, 1, 30)): raises(ValueError, lambda: igcd(*args)) for args in permutations((1, 2, None)): raises(ValueError, lambda: igcd(*args)) def test_igcd_lehmer(): a, b = fibonacci(10001), fibonacci(10000) # len(str(a)) == 2090 # small divisors, long Euclidean sequence assert igcd_lehmer(a, b) == 1 c = fibonacci(100) assert igcd_lehmer(a*c, b*c) == c # big divisor assert igcd_lehmer(a, 10**1000) == 1 # swapping argmument assert igcd_lehmer(1, 2) == igcd_lehmer(2, 1) def test_igcd2(): # short loop assert igcd2(2**100 - 1, 2**99 - 1) == 1 # Lehmer's algorithm a, b = int(fibonacci(10001)), int(fibonacci(10000)) assert igcd2(a, b) == 1 def test_ilcm(): assert ilcm(0, 0) == 0 assert ilcm(1, 0) == 0 assert ilcm(0, 1) == 0 assert ilcm(1, 1) == 1 assert ilcm(2, 1) == 2 assert ilcm(8, 2) == 8 assert ilcm(8, 6) == 24 assert ilcm(8, 7) == 56 assert ilcm(*[10, 20, 30]) == 60 raises(ValueError, lambda: ilcm(8.1, 7)) raises(ValueError, lambda: ilcm(8, 7.1)) raises(TypeError, lambda: ilcm(8)) def test_igcdex(): assert igcdex(2, 3) == (-1, 1, 1) assert igcdex(10, 12) == (-1, 1, 2) assert igcdex(100, 2004) == (-20, 1, 4) assert igcdex(0, 0) == (0, 1, 0) assert igcdex(1, 0) == (1, 0, 1) def _strictly_equal(a, b): return (a.p, a.q, type(a.p), type(a.q)) == \ (b.p, b.q, type(b.p), type(b.q)) def _test_rational_new(cls): """ Tests that are common between Integer and Rational. """ assert cls(0) is S.Zero assert cls(1) is S.One assert cls(-1) is S.NegativeOne # These look odd, but are similar to int(): assert cls('1') is S.One assert cls('-1') is S.NegativeOne i = Integer(10) assert _strictly_equal(i, cls('10')) assert _strictly_equal(i, cls('10')) assert _strictly_equal(i, cls(int(10))) assert _strictly_equal(i, cls(i)) raises(TypeError, lambda: cls(Symbol('x'))) def test_Integer_new(): """ Test for Integer constructor """ _test_rational_new(Integer) assert _strictly_equal(Integer(0.9), S.Zero) assert _strictly_equal(Integer(10.5), Integer(10)) raises(ValueError, lambda: Integer("10.5")) assert Integer(Rational('1.' + '9'*20)) == 1 def test_Rational_new(): """" Test for Rational constructor """ _test_rational_new(Rational) n1 = S.Half assert n1 == Rational(Integer(1), 2) assert n1 == Rational(Integer(1), Integer(2)) assert n1 == Rational(1, Integer(2)) assert n1 == Rational(S.Half) assert 1 == Rational(n1, n1) assert Rational(3, 2) == Rational(S.Half, Rational(1, 3)) assert Rational(3, 1) == Rational(1, Rational(1, 3)) n3_4 = Rational(3, 4) assert Rational('3/4') == n3_4 assert -Rational('-3/4') == n3_4 assert Rational('.76').limit_denominator(4) == n3_4 assert Rational(19, 25).limit_denominator(4) == n3_4 assert Rational('19/25').limit_denominator(4) == n3_4 assert Rational(1.0, 3) == Rational(1, 3) assert Rational(1, 3.0) == Rational(1, 3) assert Rational(Float(0.5)) == S.Half assert Rational('1e2/1e-2') == Rational(10000) assert Rational('1 234') == Rational(1234) assert Rational('1/1 234') == Rational(1, 1234) assert Rational(-1, 0) is S.ComplexInfinity assert Rational(1, 0) is S.ComplexInfinity # Make sure Rational doesn't lose precision on Floats assert Rational(pi.evalf(100)).evalf(100) == pi.evalf(100) raises(TypeError, lambda: Rational('3**3')) raises(TypeError, lambda: Rational('1/2 + 2/3')) # handle fractions.Fraction instances try: import fractions assert Rational(fractions.Fraction(1, 2)) == S.Half except ImportError: pass assert Rational(mpq(2, 6)) == Rational(1, 3) assert Rational(PythonRational(2, 6)) == Rational(1, 3) assert Rational(2, 4, gcd=1).q == 4 n = Rational(2, -4, gcd=1) assert n.q == 4 assert n.p == -2 def test_Number_new(): """" Test for Number constructor """ # Expected behavior on numbers and strings assert Number(1) is S.One assert Number(2).__class__ is Integer assert Number(-622).__class__ is Integer assert Number(5, 3).__class__ is Rational assert Number(5.3).__class__ is Float assert Number('1') is S.One assert Number('2').__class__ is Integer assert Number('-622').__class__ is Integer assert Number('5/3').__class__ is Rational assert Number('5.3').__class__ is Float raises(ValueError, lambda: Number('cos')) raises(TypeError, lambda: Number(cos)) a = Rational(3, 5) assert Number(a) is a # Check idempotence on Numbers u = ['inf', '-inf', 'nan', 'iNF', '+inf'] v = [oo, -oo, nan, oo, oo] for i, a in zip(u, v): assert Number(i) is a, (i, Number(i), a) def test_Number_cmp(): n1 = Number(1) n2 = Number(2) n3 = Number(-3) assert n1 < n2 assert n1 <= n2 assert n3 < n1 assert n2 > n3 assert n2 >= n3 raises(TypeError, lambda: n1 < S.NaN) raises(TypeError, lambda: n1 <= S.NaN) raises(TypeError, lambda: n1 > S.NaN) raises(TypeError, lambda: n1 >= S.NaN) def test_Rational_cmp(): n1 = Rational(1, 4) n2 = Rational(1, 3) n3 = Rational(2, 4) n4 = Rational(2, -4) n5 = Rational(0) n6 = Rational(1) n7 = Rational(3) n8 = Rational(-3) assert n8 < n5 assert n5 < n6 assert n6 < n7 assert n8 < n7 assert n7 > n8 assert (n1 + 1)**n2 < 2 assert ((n1 + n6)/n7) < 1 assert n4 < n3 assert n2 < n3 assert n1 < n2 assert n3 > n1 assert not n3 < n1 assert not (Rational(-1) > 0) assert Rational(-1) < 0 raises(TypeError, lambda: n1 < S.NaN) raises(TypeError, lambda: n1 <= S.NaN) raises(TypeError, lambda: n1 > S.NaN) raises(TypeError, lambda: n1 >= S.NaN) def test_Float(): def eq(a, b): t = Float("1.0E-15") return (-t < a - b < t) zeros = (0, S.Zero, 0., Float(0)) for i, j in permutations(zeros, 2): assert i == j for z in zeros: assert z in zeros assert S.Zero.is_zero a = Float(2) ** Float(3) assert eq(a.evalf(), Float(8)) assert eq((pi ** -1).evalf(), Float("0.31830988618379067")) a = Float(2) ** Float(4) assert eq(a.evalf(), Float(16)) assert (S(.3) == S(.5)) is False mpf = (0, 5404319552844595, -52, 53) x_str = Float((0, '13333333333333', -52, 53)) x_0xstr = Float((0, '0x13333333333333', -52, 53)) x2_str = Float((0, '26666666666666', -53, 54)) x_hex = Float((0, int(0x13333333333333), -52, 53)) x_dec = Float(mpf) assert x_str == x_0xstr == x_hex == x_dec == Float(1.2) # x2_str was entered slightly malformed in that the mantissa # was even -- it should be odd and the even part should be # included with the exponent, but this is resolved by normalization # ONLY IF REQUIREMENTS of mpf_norm are met: the bitcount must # be exact: double the mantissa ==> increase bc by 1 assert Float(1.2)._mpf_ == mpf assert x2_str._mpf_ == mpf assert Float((0, int(0), -123, -1)) is S.NaN assert Float((0, int(0), -456, -2)) is S.Infinity assert Float((1, int(0), -789, -3)) is S.NegativeInfinity # if you don't give the full signature, it's not special assert Float((0, int(0), -123)) == Float(0) assert Float((0, int(0), -456)) == Float(0) assert Float((1, int(0), -789)) == Float(0) raises(ValueError, lambda: Float((0, 7, 1, 3), '')) assert Float('0.0').is_finite is True assert Float('0.0').is_negative is False assert Float('0.0').is_positive is False assert Float('0.0').is_infinite is False assert Float('0.0').is_zero is True # rationality properties # if the integer test fails then the use of intlike # should be removed from gamma_functions.py assert Float(1).is_integer is False assert Float(1).is_rational is None assert Float(1).is_irrational is None assert sqrt(2).n(15).is_rational is None assert sqrt(2).n(15).is_irrational is None # do not automatically evalf def teq(a): assert (a.evalf() == a) is False assert (a.evalf() != a) is True assert (a == a.evalf()) is False assert (a != a.evalf()) is True teq(pi) teq(2*pi) teq(cos(0.1, evaluate=False)) # long integer i = 12345678901234567890 assert same_and_same_prec(Float(12, ''), Float('12', '')) assert same_and_same_prec(Float(Integer(i), ''), Float(i, '')) assert same_and_same_prec(Float(i, ''), Float(str(i), 20)) assert same_and_same_prec(Float(str(i)), Float(i, '')) assert same_and_same_prec(Float(i), Float(i, '')) # inexact floats (repeating binary = denom not multiple of 2) # cannot have precision greater than 15 assert Float(.125, 22) == .125 assert Float(2.0, 22) == 2 assert float(Float('.12500000000000001', '')) == .125 raises(ValueError, lambda: Float(.12500000000000001, '')) # allow spaces assert Float('123 456.123 456') == Float('123456.123456') assert Integer('123 456') == Integer('123456') assert Rational('123 456.123 456') == Rational('123456.123456') assert Float(' .3e2') == Float('0.3e2') # allow underscore assert Float('1_23.4_56') == Float('123.456') assert Float('1_') == Float('1.0') assert Float('1_.') == Float('1.0') assert Float('1._') == Float('1.0') assert Float('1__2') == Float('12.0') # assert Float('1_23.4_5_6', 12) == Float('123.456', 12) # ...but not in all cases (per Py 3.6) raises(ValueError, lambda: Float('_1')) raises(ValueError, lambda: Float('_inf')) # allow auto precision detection assert Float('.1', '') == Float(.1, 1) assert Float('.125', '') == Float(.125, 3) assert Float('.100', '') == Float(.1, 3) assert Float('2.0', '') == Float('2', 2) raises(ValueError, lambda: Float("12.3d-4", "")) raises(ValueError, lambda: Float(12.3, "")) raises(ValueError, lambda: Float('.')) raises(ValueError, lambda: Float('-.')) zero = Float('0.0') assert Float('-0') == zero assert Float('.0') == zero assert Float('-.0') == zero assert Float('-0.0') == zero assert Float(0.0) == zero assert Float(0) == zero assert Float(0, '') == Float('0', '') assert Float(1) == Float(1.0) assert Float(S.Zero) == zero assert Float(S.One) == Float(1.0) assert Float(decimal.Decimal('0.1'), 3) == Float('.1', 3) assert Float(decimal.Decimal('nan')) is S.NaN assert Float(decimal.Decimal('Infinity')) is S.Infinity assert Float(decimal.Decimal('-Infinity')) is S.NegativeInfinity assert '{:.3f}'.format(Float(4.236622)) == '4.237' assert '{:.35f}'.format(Float(pi.n(40), 40)) == \ '3.14159265358979323846264338327950288' # unicode assert Float('0.73908513321516064100000000') == \ Float('0.73908513321516064100000000') assert Float('0.73908513321516064100000000', 28) == \ Float('0.73908513321516064100000000', 28) # binary precision # Decimal value 0.1 cannot be expressed precisely as a base 2 fraction a = Float(S.One/10, dps=15) b = Float(S.One/10, dps=16) p = Float(S.One/10, precision=53) q = Float(S.One/10, precision=54) assert a._mpf_ == p._mpf_ assert not a._mpf_ == q._mpf_ assert not b._mpf_ == q._mpf_ # Precision specifying errors raises(ValueError, lambda: Float("1.23", dps=3, precision=10)) raises(ValueError, lambda: Float("1.23", dps="", precision=10)) raises(ValueError, lambda: Float("1.23", dps=3, precision="")) raises(ValueError, lambda: Float("1.23", dps="", precision="")) # from NumberSymbol assert same_and_same_prec(Float(pi, 32), pi.evalf(32)) assert same_and_same_prec(Float(Catalan), Catalan.evalf()) # oo and nan u = ['inf', '-inf', 'nan', 'iNF', '+inf'] v = [oo, -oo, nan, oo, oo] for i, a in zip(u, v): assert Float(i) is a def test_zero_not_false(): # https://github.com/sympy/sympy/issues/20796 assert (S(0.0) == S.false) is False assert (S.false == S(0.0)) is False assert (S(0) == S.false) is False assert (S.false == S(0)) is False @conserve_mpmath_dps def test_float_mpf(): import mpmath mpmath.mp.dps = 100 mp_pi = mpmath.pi() assert Float(mp_pi, 100) == Float(mp_pi._mpf_, 100) == pi.evalf(100) mpmath.mp.dps = 15 assert Float(mp_pi, 100) == Float(mp_pi._mpf_, 100) == pi.evalf(100) def test_Float_RealElement(): repi = RealField(dps=100)(pi.evalf(100)) # We still have to pass the precision because Float doesn't know what # RealElement is, but make sure it keeps full precision from the result. assert Float(repi, 100) == pi.evalf(100) def test_Float_default_to_highprec_from_str(): s = str(pi.evalf(128)) assert same_and_same_prec(Float(s), Float(s, '')) def test_Float_eval(): a = Float(3.2) assert (a**2).is_Float def test_Float_issue_2107(): a = Float(0.1, 10) b = Float("0.1", 10) assert a - a == 0 assert a + (-a) == 0 assert S.Zero + a - a == 0 assert S.Zero + a + (-a) == 0 assert b - b == 0 assert b + (-b) == 0 assert S.Zero + b - b == 0 assert S.Zero + b + (-b) == 0 def test_issue_14289(): from sympy.polys.numberfields import to_number_field a = 1 - sqrt(2) b = to_number_field(a) assert b.as_expr() == a assert b.minpoly(a).expand() == 0 def test_Float_from_tuple(): a = Float((0, '1L', 0, 1)) b = Float((0, '1', 0, 1)) assert a == b def test_Infinity(): assert oo != 1 assert 1*oo is oo assert 1 != oo assert oo != -oo assert oo != Symbol("x")**3 assert oo + 1 is oo assert 2 + oo is oo assert 3*oo + 2 is oo assert S.Half**oo == 0 assert S.Half**(-oo) is oo assert -oo*3 is -oo assert oo + oo is oo assert -oo + oo*(-5) is -oo assert 1/oo == 0 assert 1/(-oo) == 0 assert 8/oo == 0 assert oo % 2 is nan assert 2 % oo is nan assert oo/oo is nan assert oo/-oo is nan assert -oo/oo is nan assert -oo/-oo is nan assert oo - oo is nan assert oo - -oo is oo assert -oo - oo is -oo assert -oo - -oo is nan assert oo + -oo is nan assert -oo + oo is nan assert oo + oo is oo assert -oo + oo is nan assert oo + -oo is nan assert -oo + -oo is -oo assert oo*oo is oo assert -oo*oo is -oo assert oo*-oo is -oo assert -oo*-oo is oo assert oo/0 is oo assert -oo/0 is -oo assert 0/oo == 0 assert 0/-oo == 0 assert oo*0 is nan assert -oo*0 is nan assert 0*oo is nan assert 0*-oo is nan assert oo + 0 is oo assert -oo + 0 is -oo assert 0 + oo is oo assert 0 + -oo is -oo assert oo - 0 is oo assert -oo - 0 is -oo assert 0 - oo is -oo assert 0 - -oo is oo assert oo/2 is oo assert -oo/2 is -oo assert oo/-2 is -oo assert -oo/-2 is oo assert oo*2 is oo assert -oo*2 is -oo assert oo*-2 is -oo assert 2/oo == 0 assert 2/-oo == 0 assert -2/oo == 0 assert -2/-oo == 0 assert 2*oo is oo assert 2*-oo is -oo assert -2*oo is -oo assert -2*-oo is oo assert 2 + oo is oo assert 2 - oo is -oo assert -2 + oo is oo assert -2 - oo is -oo assert 2 + -oo is -oo assert 2 - -oo is oo assert -2 + -oo is -oo assert -2 - -oo is oo assert S(2) + oo is oo assert S(2) - oo is -oo assert oo/I == -oo*I assert -oo/I == oo*I assert oo*float(1) == _inf and (oo*float(1)) is oo assert -oo*float(1) == _ninf and (-oo*float(1)) is -oo assert oo/float(1) == _inf and (oo/float(1)) is oo assert -oo/float(1) == _ninf and (-oo/float(1)) is -oo assert oo*float(-1) == _ninf and (oo*float(-1)) is -oo assert -oo*float(-1) == _inf and (-oo*float(-1)) is oo assert oo/float(-1) == _ninf and (oo/float(-1)) is -oo assert -oo/float(-1) == _inf and (-oo/float(-1)) is oo assert oo + float(1) == _inf and (oo + float(1)) is oo assert -oo + float(1) == _ninf and (-oo + float(1)) is -oo assert oo - float(1) == _inf and (oo - float(1)) is oo assert -oo - float(1) == _ninf and (-oo - float(1)) is -oo assert float(1)*oo == _inf and (float(1)*oo) is oo assert float(1)*-oo == _ninf and (float(1)*-oo) is -oo assert float(1)/oo == 0 assert float(1)/-oo == 0 assert float(-1)*oo == _ninf and (float(-1)*oo) is -oo assert float(-1)*-oo == _inf and (float(-1)*-oo) is oo assert float(-1)/oo == 0 assert float(-1)/-oo == 0 assert float(1) + oo is oo assert float(1) + -oo is -oo assert float(1) - oo is -oo assert float(1) - -oo is oo assert oo == float(oo) assert (oo != float(oo)) is False assert type(float(oo)) is float assert -oo == float(-oo) assert (-oo != float(-oo)) is False assert type(float(-oo)) is float assert Float('nan') is nan assert nan*1.0 is nan assert -1.0*nan is nan assert nan*oo is nan assert nan*-oo is nan assert nan/oo is nan assert nan/-oo is nan assert nan + oo is nan assert nan + -oo is nan assert nan - oo is nan assert nan - -oo is nan assert -oo * S.Zero is nan assert oo*nan is nan assert -oo*nan is nan assert oo/nan is nan assert -oo/nan is nan assert oo + nan is nan assert -oo + nan is nan assert oo - nan is nan assert -oo - nan is nan assert S.Zero * oo is nan assert oo.is_Rational is False assert isinstance(oo, Rational) is False assert S.One/oo == 0 assert -S.One/oo == 0 assert S.One/-oo == 0 assert -S.One/-oo == 0 assert S.One*oo is oo assert -S.One*oo is -oo assert S.One*-oo is -oo assert -S.One*-oo is oo assert S.One/nan is nan assert S.One - -oo is oo assert S.One + nan is nan assert S.One - nan is nan assert nan - S.One is nan assert nan/S.One is nan assert -oo - S.One is -oo def test_Infinity_2(): x = Symbol('x') assert oo*x != oo assert oo*(pi - 1) is oo assert oo*(1 - pi) is -oo assert (-oo)*x != -oo assert (-oo)*(pi - 1) is -oo assert (-oo)*(1 - pi) is oo assert (-1)**S.NaN is S.NaN assert oo - _inf is S.NaN assert oo + _ninf is S.NaN assert oo*0 is S.NaN assert oo/_inf is S.NaN assert oo/_ninf is S.NaN assert oo**S.NaN is S.NaN assert -oo + _inf is S.NaN assert -oo - _ninf is S.NaN assert -oo*S.NaN is S.NaN assert -oo*0 is S.NaN assert -oo/_inf is S.NaN assert -oo/_ninf is S.NaN assert -oo/S.NaN is S.NaN assert abs(-oo) is oo assert all((-oo)**i is S.NaN for i in (oo, -oo, S.NaN)) assert (-oo)**3 is -oo assert (-oo)**2 is oo assert abs(S.ComplexInfinity) is oo def test_Mul_Infinity_Zero(): assert Float(0)*_inf is nan assert Float(0)*_ninf is nan assert Float(0)*_inf is nan assert Float(0)*_ninf is nan assert _inf*Float(0) is nan assert _ninf*Float(0) is nan assert _inf*Float(0) is nan assert _ninf*Float(0) is nan def test_Div_By_Zero(): assert 1/S.Zero is zoo assert 1/Float(0) is zoo assert 0/S.Zero is nan assert 0/Float(0) is nan assert S.Zero/0 is nan assert Float(0)/0 is nan assert -1/S.Zero is zoo assert -1/Float(0) is zoo @_both_exp_pow def test_Infinity_inequations(): assert oo > pi assert not (oo < pi) assert exp(-3) < oo assert _inf > pi assert not (_inf < pi) assert exp(-3) < _inf raises(TypeError, lambda: oo < I) raises(TypeError, lambda: oo <= I) raises(TypeError, lambda: oo > I) raises(TypeError, lambda: oo >= I) raises(TypeError, lambda: -oo < I) raises(TypeError, lambda: -oo <= I) raises(TypeError, lambda: -oo > I) raises(TypeError, lambda: -oo >= I) raises(TypeError, lambda: I < oo) raises(TypeError, lambda: I <= oo) raises(TypeError, lambda: I > oo) raises(TypeError, lambda: I >= oo) raises(TypeError, lambda: I < -oo) raises(TypeError, lambda: I <= -oo) raises(TypeError, lambda: I > -oo) raises(TypeError, lambda: I >= -oo) assert oo > -oo and oo >= -oo assert (oo < -oo) == False and (oo <= -oo) == False assert -oo < oo and -oo <= oo assert (-oo > oo) == False and (-oo >= oo) == False assert (oo < oo) == False # issue 7775 assert (oo > oo) == False assert (-oo > -oo) == False and (-oo < -oo) == False assert oo >= oo and oo <= oo and -oo >= -oo and -oo <= -oo assert (-oo < -_inf) == False assert (oo > _inf) == False assert -oo >= -_inf assert oo <= _inf x = Symbol('x') b = Symbol('b', finite=True, real=True) assert (x < oo) == Lt(x, oo) # issue 7775 assert b < oo and b > -oo and b <= oo and b >= -oo assert oo > b and oo >= b and (oo < b) == False and (oo <= b) == False assert (-oo > b) == False and (-oo >= b) == False and -oo < b and -oo <= b assert (oo < x) == Lt(oo, x) and (oo > x) == Gt(oo, x) assert (oo <= x) == Le(oo, x) and (oo >= x) == Ge(oo, x) assert (-oo < x) == Lt(-oo, x) and (-oo > x) == Gt(-oo, x) assert (-oo <= x) == Le(-oo, x) and (-oo >= x) == Ge(-oo, x) def test_NaN(): assert nan is nan assert nan != 1 assert 1*nan is nan assert 1 != nan assert -nan is nan assert oo != Symbol("x")**3 assert 2 + nan is nan assert 3*nan + 2 is nan assert -nan*3 is nan assert nan + nan is nan assert -nan + nan*(-5) is nan assert 8/nan is nan raises(TypeError, lambda: nan > 0) raises(TypeError, lambda: nan < 0) raises(TypeError, lambda: nan >= 0) raises(TypeError, lambda: nan <= 0) raises(TypeError, lambda: 0 < nan) raises(TypeError, lambda: 0 > nan) raises(TypeError, lambda: 0 <= nan) raises(TypeError, lambda: 0 >= nan) assert nan**0 == 1 # as per IEEE 754 assert 1**nan is nan # IEEE 754 is not the best choice for symbolic work # test Pow._eval_power's handling of NaN assert Pow(nan, 0, evaluate=False)**2 == 1 for n in (1, 1., S.One, S.NegativeOne, Float(1)): assert n + nan is nan assert n - nan is nan assert nan + n is nan assert nan - n is nan assert n/nan is nan assert nan/n is nan def test_special_numbers(): assert isinstance(S.NaN, Number) is True assert isinstance(S.Infinity, Number) is True assert isinstance(S.NegativeInfinity, Number) is True assert S.NaN.is_number is True assert S.Infinity.is_number is True assert S.NegativeInfinity.is_number is True assert S.ComplexInfinity.is_number is True assert isinstance(S.NaN, Rational) is False assert isinstance(S.Infinity, Rational) is False assert isinstance(S.NegativeInfinity, Rational) is False assert S.NaN.is_rational is not True assert S.Infinity.is_rational is not True assert S.NegativeInfinity.is_rational is not True def test_powers(): assert integer_nthroot(1, 2) == (1, True) assert integer_nthroot(1, 5) == (1, True) assert integer_nthroot(2, 1) == (2, True) assert integer_nthroot(2, 2) == (1, False) assert integer_nthroot(2, 5) == (1, False) assert integer_nthroot(4, 2) == (2, True) assert integer_nthroot(123**25, 25) == (123, True) assert integer_nthroot(123**25 + 1, 25) == (123, False) assert integer_nthroot(123**25 - 1, 25) == (122, False) assert integer_nthroot(1, 1) == (1, True) assert integer_nthroot(0, 1) == (0, True) assert integer_nthroot(0, 3) == (0, True) assert integer_nthroot(10000, 1) == (10000, True) assert integer_nthroot(4, 2) == (2, True) assert integer_nthroot(16, 2) == (4, True) assert integer_nthroot(26, 2) == (5, False) assert integer_nthroot(1234567**7, 7) == (1234567, True) assert integer_nthroot(1234567**7 + 1, 7) == (1234567, False) assert integer_nthroot(1234567**7 - 1, 7) == (1234566, False) b = 25**1000 assert integer_nthroot(b, 1000) == (25, True) assert integer_nthroot(b + 1, 1000) == (25, False) assert integer_nthroot(b - 1, 1000) == (24, False) c = 10**400 c2 = c**2 assert integer_nthroot(c2, 2) == (c, True) assert integer_nthroot(c2 + 1, 2) == (c, False) assert integer_nthroot(c2 - 1, 2) == (c - 1, False) assert integer_nthroot(2, 10**10) == (1, False) p, r = integer_nthroot(int(factorial(10000)), 100) assert p % (10**10) == 5322420655 assert not r # Test that this is fast assert integer_nthroot(2, 10**10) == (1, False) # output should be int if possible assert type(integer_nthroot(2**61, 2)[0]) is int def test_integer_nthroot_overflow(): assert integer_nthroot(10**(50*50), 50) == (10**50, True) assert integer_nthroot(10**100000, 10000) == (10**10, True) def test_integer_log(): raises(ValueError, lambda: integer_log(2, 1)) raises(ValueError, lambda: integer_log(0, 2)) raises(ValueError, lambda: integer_log(1.1, 2)) raises(ValueError, lambda: integer_log(1, 2.2)) assert integer_log(1, 2) == (0, True) assert integer_log(1, 3) == (0, True) assert integer_log(2, 3) == (0, False) assert integer_log(3, 3) == (1, True) assert integer_log(3*2, 3) == (1, False) assert integer_log(3**2, 3) == (2, True) assert integer_log(3*4, 3) == (2, False) assert integer_log(3**3, 3) == (3, True) assert integer_log(27, 5) == (2, False) assert integer_log(2, 3) == (0, False) assert integer_log(-4, -2) == (2, False) assert integer_log(27, -3) == (3, False) assert integer_log(-49, 7) == (0, False) assert integer_log(-49, -7) == (2, False) def test_isqrt(): from math import sqrt as _sqrt limit = 4503599761588223 assert int(_sqrt(limit)) == integer_nthroot(limit, 2)[0] assert int(_sqrt(limit + 1)) != integer_nthroot(limit + 1, 2)[0] assert isqrt(limit + 1) == integer_nthroot(limit + 1, 2)[0] assert isqrt(limit + S.Half) == integer_nthroot(limit, 2)[0] assert isqrt(limit + 1 + S.Half) == integer_nthroot(limit + 1, 2)[0] assert isqrt(limit + 2 + S.Half) == integer_nthroot(limit + 2, 2)[0] # Regression tests for https://github.com/sympy/sympy/issues/17034 assert isqrt(4503599761588224) == 67108864 assert isqrt(9999999999999999) == 99999999 # Other corner cases, especially involving non-integers. raises(ValueError, lambda: isqrt(-1)) raises(ValueError, lambda: isqrt(-10**1000)) raises(ValueError, lambda: isqrt(Rational(-1, 2))) tiny = Rational(1, 10**1000) raises(ValueError, lambda: isqrt(-tiny)) assert isqrt(1-tiny) == 0 assert isqrt(4503599761588224-tiny) == 67108864 assert isqrt(10**100 - tiny) == 10**50 - 1 # Check that using an inaccurate math.sqrt doesn't affect the results. from sympy.core import power old_sqrt = power._sqrt power._sqrt = lambda x: 2.999999999 try: assert isqrt(9) == 3 assert isqrt(10000) == 100 finally: power._sqrt = old_sqrt def test_powers_Integer(): """Test Integer._eval_power""" # check infinity assert S.One ** S.Infinity is S.NaN assert S.NegativeOne** S.Infinity is S.NaN assert S(2) ** S.Infinity is S.Infinity assert S(-2)** S.Infinity == zoo assert S(0) ** S.Infinity is S.Zero # check Nan assert S.One ** S.NaN is S.NaN assert S.NegativeOne ** S.NaN is S.NaN # check for exact roots assert S.NegativeOne ** Rational(6, 5) == - (-1)**(S.One/5) assert sqrt(S(4)) == 2 assert sqrt(S(-4)) == I * 2 assert S(16) ** Rational(1, 4) == 2 assert S(-16) ** Rational(1, 4) == 2 * (-1)**Rational(1, 4) assert S(9) ** Rational(3, 2) == 27 assert S(-9) ** Rational(3, 2) == -27*I assert S(27) ** Rational(2, 3) == 9 assert S(-27) ** Rational(2, 3) == 9 * (S.NegativeOne ** Rational(2, 3)) assert (-2) ** Rational(-2, 1) == Rational(1, 4) # not exact roots assert sqrt(-3) == I*sqrt(3) assert (3) ** (Rational(3, 2)) == 3 * sqrt(3) assert (-3) ** (Rational(3, 2)) == - 3 * sqrt(-3) assert (-3) ** (Rational(5, 2)) == 9 * I * sqrt(3) assert (-3) ** (Rational(7, 2)) == - I * 27 * sqrt(3) assert (2) ** (Rational(3, 2)) == 2 * sqrt(2) assert (2) ** (Rational(-3, 2)) == sqrt(2) / 4 assert (81) ** (Rational(2, 3)) == 9 * (S(3) ** (Rational(2, 3))) assert (-81) ** (Rational(2, 3)) == 9 * (S(-3) ** (Rational(2, 3))) assert (-3) ** Rational(-7, 3) == \ -(-1)**Rational(2, 3)*3**Rational(2, 3)/27 assert (-3) ** Rational(-2, 3) == \ -(-1)**Rational(1, 3)*3**Rational(1, 3)/3 # join roots assert sqrt(6) + sqrt(24) == 3*sqrt(6) assert sqrt(2) * sqrt(3) == sqrt(6) # separate symbols & constansts x = Symbol("x") assert sqrt(49 * x) == 7 * sqrt(x) assert sqrt((3 - sqrt(pi)) ** 2) == 3 - sqrt(pi) # check that it is fast for big numbers assert (2**64 + 1) ** Rational(4, 3) assert (2**64 + 1) ** Rational(17, 25) # negative rational power and negative base assert (-3) ** Rational(-7, 3) == \ -(-1)**Rational(2, 3)*3**Rational(2, 3)/27 assert (-3) ** Rational(-2, 3) == \ -(-1)**Rational(1, 3)*3**Rational(1, 3)/3 assert (-2) ** Rational(-10, 3) == \ (-1)**Rational(2, 3)*2**Rational(2, 3)/16 assert abs(Pow(-2, Rational(-10, 3)).n() - Pow(-2, Rational(-10, 3), evaluate=False).n()) < 1e-16 # negative base and rational power with some simplification assert (-8) ** Rational(2, 5) == \ 2*(-1)**Rational(2, 5)*2**Rational(1, 5) assert (-4) ** Rational(9, 5) == \ -8*(-1)**Rational(4, 5)*2**Rational(3, 5) assert S(1234).factors() == {617: 1, 2: 1} assert Rational(2*3, 3*5*7).factors() == {2: 1, 5: -1, 7: -1} # test that eval_power factors numbers bigger than # the current limit in factor_trial_division (2**15) from sympy.ntheory.generate import nextprime n = nextprime(2**15) assert sqrt(n**2) == n assert sqrt(n**3) == n*sqrt(n) assert sqrt(4*n) == 2*sqrt(n) # check that factors of base with powers sharing gcd with power are removed assert (2**4*3)**Rational(1, 6) == 2**Rational(2, 3)*3**Rational(1, 6) assert (2**4*3)**Rational(5, 6) == 8*2**Rational(1, 3)*3**Rational(5, 6) # check that bases sharing a gcd are exptracted assert 2**Rational(1, 3)*3**Rational(1, 4)*6**Rational(1, 5) == \ 2**Rational(8, 15)*3**Rational(9, 20) assert sqrt(8)*24**Rational(1, 3)*6**Rational(1, 5) == \ 4*2**Rational(7, 10)*3**Rational(8, 15) assert sqrt(8)*(-24)**Rational(1, 3)*(-6)**Rational(1, 5) == \ 4*(-3)**Rational(8, 15)*2**Rational(7, 10) assert 2**Rational(1, 3)*2**Rational(8, 9) == 2*2**Rational(2, 9) assert 2**Rational(2, 3)*6**Rational(1, 3) == 2*3**Rational(1, 3) assert 2**Rational(2, 3)*6**Rational(8, 9) == \ 2*2**Rational(5, 9)*3**Rational(8, 9) assert (-2)**Rational(2, S(3))*(-4)**Rational(1, S(3)) == -2*2**Rational(1, 3) assert 3*Pow(3, 2, evaluate=False) == 3**3 assert 3*Pow(3, Rational(-1, 3), evaluate=False) == 3**Rational(2, 3) assert (-2)**Rational(1, 3)*(-3)**Rational(1, 4)*(-5)**Rational(5, 6) == \ -(-1)**Rational(5, 12)*2**Rational(1, 3)*3**Rational(1, 4) * \ 5**Rational(5, 6) assert Integer(-2)**Symbol('', even=True) == \ Integer(2)**Symbol('', even=True) assert (-1)**Float(.5) == 1.0*I def test_powers_Rational(): """Test Rational._eval_power""" # check infinity assert S.Half ** S.Infinity == 0 assert Rational(3, 2) ** S.Infinity is S.Infinity assert Rational(-1, 2) ** S.Infinity == 0 assert Rational(-3, 2) ** S.Infinity == zoo # check Nan assert Rational(3, 4) ** S.NaN is S.NaN assert Rational(-2, 3) ** S.NaN is S.NaN # exact roots on numerator assert sqrt(Rational(4, 3)) == 2 * sqrt(3) / 3 assert Rational(4, 3) ** Rational(3, 2) == 8 * sqrt(3) / 9 assert sqrt(Rational(-4, 3)) == I * 2 * sqrt(3) / 3 assert Rational(-4, 3) ** Rational(3, 2) == - I * 8 * sqrt(3) / 9 assert Rational(27, 2) ** Rational(1, 3) == 3 * (2 ** Rational(2, 3)) / 2 assert Rational(5**3, 8**3) ** Rational(4, 3) == Rational(5**4, 8**4) # exact root on denominator assert sqrt(Rational(1, 4)) == S.Half assert sqrt(Rational(1, -4)) == I * S.Half assert sqrt(Rational(3, 4)) == sqrt(3) / 2 assert sqrt(Rational(3, -4)) == I * sqrt(3) / 2 assert Rational(5, 27) ** Rational(1, 3) == (5 ** Rational(1, 3)) / 3 # not exact roots assert sqrt(S.Half) == sqrt(2) / 2 assert sqrt(Rational(-4, 7)) == I * sqrt(Rational(4, 7)) assert Rational(-3, 2)**Rational(-7, 3) == \ -4*(-1)**Rational(2, 3)*2**Rational(1, 3)*3**Rational(2, 3)/27 assert Rational(-3, 2)**Rational(-2, 3) == \ -(-1)**Rational(1, 3)*2**Rational(2, 3)*3**Rational(1, 3)/3 assert Rational(-3, 2)**Rational(-10, 3) == \ 8*(-1)**Rational(2, 3)*2**Rational(1, 3)*3**Rational(2, 3)/81 assert abs(Pow(Rational(-2, 3), Rational(-7, 4)).n() - Pow(Rational(-2, 3), Rational(-7, 4), evaluate=False).n()) < 1e-16 # negative integer power and negative rational base assert Rational(-2, 3) ** Rational(-2, 1) == Rational(9, 4) a = Rational(1, 10) assert a**Float(a, 2) == Float(a, 2)**Float(a, 2) assert Rational(-2, 3)**Symbol('', even=True) == \ Rational(2, 3)**Symbol('', even=True) def test_powers_Float(): assert str((S('-1/10')**S('3/10')).n()) == str(Float(-.1)**(.3)) def test_lshift_Integer(): assert Integer(0) << Integer(2) == Integer(0) assert Integer(0) << 2 == Integer(0) assert 0 << Integer(2) == Integer(0) assert Integer(0b11) << Integer(0) == Integer(0b11) assert Integer(0b11) << 0 == Integer(0b11) assert 0b11 << Integer(0) == Integer(0b11) assert Integer(0b11) << Integer(2) == Integer(0b11 << 2) assert Integer(0b11) << 2 == Integer(0b11 << 2) assert 0b11 << Integer(2) == Integer(0b11 << 2) assert Integer(-0b11) << Integer(2) == Integer(-0b11 << 2) assert Integer(-0b11) << 2 == Integer(-0b11 << 2) assert -0b11 << Integer(2) == Integer(-0b11 << 2) raises(TypeError, lambda: Integer(2) << 0.0) raises(TypeError, lambda: 0.0 << Integer(2)) raises(ValueError, lambda: Integer(1) << Integer(-1)) def test_rshift_Integer(): assert Integer(0) >> Integer(2) == Integer(0) assert Integer(0) >> 2 == Integer(0) assert 0 >> Integer(2) == Integer(0) assert Integer(0b11) >> Integer(0) == Integer(0b11) assert Integer(0b11) >> 0 == Integer(0b11) assert 0b11 >> Integer(0) == Integer(0b11) assert Integer(0b11) >> Integer(2) == Integer(0) assert Integer(0b11) >> 2 == Integer(0) assert 0b11 >> Integer(2) == Integer(0) assert Integer(-0b11) >> Integer(2) == Integer(-1) assert Integer(-0b11) >> 2 == Integer(-1) assert -0b11 >> Integer(2) == Integer(-1) assert Integer(0b1100) >> Integer(2) == Integer(0b1100 >> 2) assert Integer(0b1100) >> 2 == Integer(0b1100 >> 2) assert 0b1100 >> Integer(2) == Integer(0b1100 >> 2) assert Integer(-0b1100) >> Integer(2) == Integer(-0b1100 >> 2) assert Integer(-0b1100) >> 2 == Integer(-0b1100 >> 2) assert -0b1100 >> Integer(2) == Integer(-0b1100 >> 2) raises(TypeError, lambda: Integer(0b10) >> 0.0) raises(TypeError, lambda: 0.0 >> Integer(2)) raises(ValueError, lambda: Integer(1) >> Integer(-1)) def test_and_Integer(): assert Integer(0b01010101) & Integer(0b10101010) == Integer(0) assert Integer(0b01010101) & 0b10101010 == Integer(0) assert 0b01010101 & Integer(0b10101010) == Integer(0) assert Integer(0b01010101) & Integer(0b11011011) == Integer(0b01010001) assert Integer(0b01010101) & 0b11011011 == Integer(0b01010001) assert 0b01010101 & Integer(0b11011011) == Integer(0b01010001) assert -Integer(0b01010101) & Integer(0b11011011) == Integer(-0b01010101 & 0b11011011) assert Integer(-0b01010101) & 0b11011011 == Integer(-0b01010101 & 0b11011011) assert -0b01010101 & Integer(0b11011011) == Integer(-0b01010101 & 0b11011011) assert Integer(0b01010101) & -Integer(0b11011011) == Integer(0b01010101 & -0b11011011) assert Integer(0b01010101) & -0b11011011 == Integer(0b01010101 & -0b11011011) assert 0b01010101 & Integer(-0b11011011) == Integer(0b01010101 & -0b11011011) raises(TypeError, lambda: Integer(2) & 0.0) raises(TypeError, lambda: 0.0 & Integer(2)) def test_xor_Integer(): assert Integer(0b01010101) ^ Integer(0b11111111) == Integer(0b10101010) assert Integer(0b01010101) ^ 0b11111111 == Integer(0b10101010) assert 0b01010101 ^ Integer(0b11111111) == Integer(0b10101010) assert Integer(0b01010101) ^ Integer(0b11011011) == Integer(0b10001110) assert Integer(0b01010101) ^ 0b11011011 == Integer(0b10001110) assert 0b01010101 ^ Integer(0b11011011) == Integer(0b10001110) assert -Integer(0b01010101) ^ Integer(0b11011011) == Integer(-0b01010101 ^ 0b11011011) assert Integer(-0b01010101) ^ 0b11011011 == Integer(-0b01010101 ^ 0b11011011) assert -0b01010101 ^ Integer(0b11011011) == Integer(-0b01010101 ^ 0b11011011) assert Integer(0b01010101) ^ -Integer(0b11011011) == Integer(0b01010101 ^ -0b11011011) assert Integer(0b01010101) ^ -0b11011011 == Integer(0b01010101 ^ -0b11011011) assert 0b01010101 ^ Integer(-0b11011011) == Integer(0b01010101 ^ -0b11011011) raises(TypeError, lambda: Integer(2) ^ 0.0) raises(TypeError, lambda: 0.0 ^ Integer(2)) def test_or_Integer(): assert Integer(0b01010101) | Integer(0b10101010) == Integer(0b11111111) assert Integer(0b01010101) | 0b10101010 == Integer(0b11111111) assert 0b01010101 | Integer(0b10101010) == Integer(0b11111111) assert Integer(0b01010101) | Integer(0b11011011) == Integer(0b11011111) assert Integer(0b01010101) | 0b11011011 == Integer(0b11011111) assert 0b01010101 | Integer(0b11011011) == Integer(0b11011111) assert -Integer(0b01010101) | Integer(0b11011011) == Integer(-0b01010101 | 0b11011011) assert Integer(-0b01010101) | 0b11011011 == Integer(-0b01010101 | 0b11011011) assert -0b01010101 | Integer(0b11011011) == Integer(-0b01010101 | 0b11011011) assert Integer(0b01010101) | -Integer(0b11011011) == Integer(0b01010101 | -0b11011011) assert Integer(0b01010101) | -0b11011011 == Integer(0b01010101 | -0b11011011) assert 0b01010101 | Integer(-0b11011011) == Integer(0b01010101 | -0b11011011) raises(TypeError, lambda: Integer(2) | 0.0) raises(TypeError, lambda: 0.0 | Integer(2)) def test_invert_Integer(): assert ~Integer(0b01010101) == Integer(-0b01010110) assert ~Integer(0b01010101) == Integer(~0b01010101) assert ~(~Integer(0b01010101)) == Integer(0b01010101) def test_abs1(): assert Rational(1, 6) != Rational(-1, 6) assert abs(Rational(1, 6)) == abs(Rational(-1, 6)) def test_accept_int(): assert Float(4) == 4 def test_dont_accept_str(): assert Float("0.2") != "0.2" assert not (Float("0.2") == "0.2") def test_int(): a = Rational(5) assert int(a) == 5 a = Rational(9, 10) assert int(a) == int(-a) == 0 assert 1/(-1)**Rational(2, 3) == -(-1)**Rational(1, 3) # issue 10368 a = Rational(32442016954, 78058255275) assert type(int(a)) is type(int(-a)) is int def test_int_NumberSymbols(): assert int(Catalan) == 0 assert int(EulerGamma) == 0 assert int(pi) == 3 assert int(E) == 2 assert int(GoldenRatio) == 1 assert int(TribonacciConstant) == 1 for i in [Catalan, E, EulerGamma, GoldenRatio, TribonacciConstant, pi]: a, b = i.approximation_interval(Integer) ia = int(i) assert ia == a assert isinstance(ia, int) assert b == a + 1 assert a.is_Integer and b.is_Integer def test_real_bug(): x = Symbol("x") assert str(2.0*x*x) in ["(2.0*x)*x", "2.0*x**2", "2.00000000000000*x**2"] assert str(2.1*x*x) != "(2.0*x)*x" def test_bug_sqrt(): assert ((sqrt(Rational(2)) + 1)*(sqrt(Rational(2)) - 1)).expand() == 1 def test_pi_Pi(): "Test that pi (instance) is imported, but Pi (class) is not" from sympy import pi # noqa with raises(ImportError): from sympy import Pi # noqa def test_no_len(): # there should be no len for numbers raises(TypeError, lambda: len(Rational(2))) raises(TypeError, lambda: len(Rational(2, 3))) raises(TypeError, lambda: len(Integer(2))) def test_issue_3321(): assert sqrt(Rational(1, 5)) == Rational(1, 5)**S.Half assert 5 * sqrt(Rational(1, 5)) == sqrt(5) def test_issue_3692(): assert ((-1)**Rational(1, 6)).expand(complex=True) == I/2 + sqrt(3)/2 assert ((-5)**Rational(1, 6)).expand(complex=True) == \ 5**Rational(1, 6)*I/2 + 5**Rational(1, 6)*sqrt(3)/2 assert ((-64)**Rational(1, 6)).expand(complex=True) == I + sqrt(3) def test_issue_3423(): x = Symbol("x") assert sqrt(x - 1).as_base_exp() == (x - 1, S.Half) assert sqrt(x - 1) != I*sqrt(1 - x) def test_issue_3449(): x = Symbol("x") assert sqrt(x - 1).subs(x, 5) == 2 def test_issue_13890(): x = Symbol("x") e = (-x/4 - S.One/12)**x - 1 f = simplify(e) a = Rational(9, 5) assert abs(e.subs(x,a).evalf() - f.subs(x,a).evalf()) < 1e-15 def test_Integer_factors(): def F(i): return Integer(i).factors() assert F(1) == {} assert F(2) == {2: 1} assert F(3) == {3: 1} assert F(4) == {2: 2} assert F(5) == {5: 1} assert F(6) == {2: 1, 3: 1} assert F(7) == {7: 1} assert F(8) == {2: 3} assert F(9) == {3: 2} assert F(10) == {2: 1, 5: 1} assert F(11) == {11: 1} assert F(12) == {2: 2, 3: 1} assert F(13) == {13: 1} assert F(14) == {2: 1, 7: 1} assert F(15) == {3: 1, 5: 1} assert F(16) == {2: 4} assert F(17) == {17: 1} assert F(18) == {2: 1, 3: 2} assert F(19) == {19: 1} assert F(20) == {2: 2, 5: 1} assert F(21) == {3: 1, 7: 1} assert F(22) == {2: 1, 11: 1} assert F(23) == {23: 1} assert F(24) == {2: 3, 3: 1} assert F(25) == {5: 2} assert F(26) == {2: 1, 13: 1} assert F(27) == {3: 3} assert F(28) == {2: 2, 7: 1} assert F(29) == {29: 1} assert F(30) == {2: 1, 3: 1, 5: 1} assert F(31) == {31: 1} assert F(32) == {2: 5} assert F(33) == {3: 1, 11: 1} assert F(34) == {2: 1, 17: 1} assert F(35) == {5: 1, 7: 1} assert F(36) == {2: 2, 3: 2} assert F(37) == {37: 1} assert F(38) == {2: 1, 19: 1} assert F(39) == {3: 1, 13: 1} assert F(40) == {2: 3, 5: 1} assert F(41) == {41: 1} assert F(42) == {2: 1, 3: 1, 7: 1} assert F(43) == {43: 1} assert F(44) == {2: 2, 11: 1} assert F(45) == {3: 2, 5: 1} assert F(46) == {2: 1, 23: 1} assert F(47) == {47: 1} assert F(48) == {2: 4, 3: 1} assert F(49) == {7: 2} assert F(50) == {2: 1, 5: 2} assert F(51) == {3: 1, 17: 1} def test_Rational_factors(): def F(p, q, visual=None): return Rational(p, q).factors(visual=visual) assert F(2, 3) == {2: 1, 3: -1} assert F(2, 9) == {2: 1, 3: -2} assert F(2, 15) == {2: 1, 3: -1, 5: -1} assert F(6, 10) == {3: 1, 5: -1} def test_issue_4107(): assert pi*(E + 10) + pi*(-E - 10) != 0 assert pi*(E + 10**10) + pi*(-E - 10**10) != 0 assert pi*(E + 10**20) + pi*(-E - 10**20) != 0 assert pi*(E + 10**80) + pi*(-E - 10**80) != 0 assert (pi*(E + 10) + pi*(-E - 10)).expand() == 0 assert (pi*(E + 10**10) + pi*(-E - 10**10)).expand() == 0 assert (pi*(E + 10**20) + pi*(-E - 10**20)).expand() == 0 assert (pi*(E + 10**80) + pi*(-E - 10**80)).expand() == 0 def test_IntegerInteger(): a = Integer(4) b = Integer(a) assert a == b def test_Rational_gcd_lcm_cofactors(): assert Integer(4).gcd(2) == Integer(2) assert Integer(4).lcm(2) == Integer(4) assert Integer(4).gcd(Integer(2)) == Integer(2) assert Integer(4).lcm(Integer(2)) == Integer(4) a, b = 720**99911, 480**12342 assert Integer(a).lcm(b) == a*b/Integer(a).gcd(b) assert Integer(4).gcd(3) == Integer(1) assert Integer(4).lcm(3) == Integer(12) assert Integer(4).gcd(Integer(3)) == Integer(1) assert Integer(4).lcm(Integer(3)) == Integer(12) assert Rational(4, 3).gcd(2) == Rational(2, 3) assert Rational(4, 3).lcm(2) == Integer(4) assert Rational(4, 3).gcd(Integer(2)) == Rational(2, 3) assert Rational(4, 3).lcm(Integer(2)) == Integer(4) assert Integer(4).gcd(Rational(2, 9)) == Rational(2, 9) assert Integer(4).lcm(Rational(2, 9)) == Integer(4) assert Rational(4, 3).gcd(Rational(2, 9)) == Rational(2, 9) assert Rational(4, 3).lcm(Rational(2, 9)) == Rational(4, 3) assert Rational(4, 5).gcd(Rational(2, 9)) == Rational(2, 45) assert Rational(4, 5).lcm(Rational(2, 9)) == Integer(4) assert Rational(5, 9).lcm(Rational(3, 7)) == Rational(Integer(5).lcm(3),Integer(9).gcd(7)) assert Integer(4).cofactors(2) == (Integer(2), Integer(2), Integer(1)) assert Integer(4).cofactors(Integer(2)) == \ (Integer(2), Integer(2), Integer(1)) assert Integer(4).gcd(Float(2.0)) == S.One assert Integer(4).lcm(Float(2.0)) == Float(8.0) assert Integer(4).cofactors(Float(2.0)) == (S.One, Integer(4), Float(2.0)) assert S.Half.gcd(Float(2.0)) == S.One assert S.Half.lcm(Float(2.0)) == Float(1.0) assert S.Half.cofactors(Float(2.0)) == \ (S.One, S.Half, Float(2.0)) def test_Float_gcd_lcm_cofactors(): assert Float(2.0).gcd(Integer(4)) == S.One assert Float(2.0).lcm(Integer(4)) == Float(8.0) assert Float(2.0).cofactors(Integer(4)) == (S.One, Float(2.0), Integer(4)) assert Float(2.0).gcd(S.Half) == S.One assert Float(2.0).lcm(S.Half) == Float(1.0) assert Float(2.0).cofactors(S.Half) == \ (S.One, Float(2.0), S.Half) def test_issue_4611(): assert abs(pi._evalf(50) - 3.14159265358979) < 1e-10 assert abs(E._evalf(50) - 2.71828182845905) < 1e-10 assert abs(Catalan._evalf(50) - 0.915965594177219) < 1e-10 assert abs(EulerGamma._evalf(50) - 0.577215664901533) < 1e-10 assert abs(GoldenRatio._evalf(50) - 1.61803398874989) < 1e-10 assert abs(TribonacciConstant._evalf(50) - 1.83928675521416) < 1e-10 x = Symbol("x") assert (pi + x).evalf() == pi.evalf() + x assert (E + x).evalf() == E.evalf() + x assert (Catalan + x).evalf() == Catalan.evalf() + x assert (EulerGamma + x).evalf() == EulerGamma.evalf() + x assert (GoldenRatio + x).evalf() == GoldenRatio.evalf() + x assert (TribonacciConstant + x).evalf() == TribonacciConstant.evalf() + x @conserve_mpmath_dps def test_conversion_to_mpmath(): assert mpmath.mpmathify(Integer(1)) == mpmath.mpf(1) assert mpmath.mpmathify(S.Half) == mpmath.mpf(0.5) assert mpmath.mpmathify(Float('1.23', 15)) == mpmath.mpf('1.23') assert mpmath.mpmathify(I) == mpmath.mpc(1j) assert mpmath.mpmathify(1 + 2*I) == mpmath.mpc(1 + 2j) assert mpmath.mpmathify(1.0 + 2*I) == mpmath.mpc(1 + 2j) assert mpmath.mpmathify(1 + 2.0*I) == mpmath.mpc(1 + 2j) assert mpmath.mpmathify(1.0 + 2.0*I) == mpmath.mpc(1 + 2j) assert mpmath.mpmathify(S.Half + S.Half*I) == mpmath.mpc(0.5 + 0.5j) assert mpmath.mpmathify(2*I) == mpmath.mpc(2j) assert mpmath.mpmathify(2.0*I) == mpmath.mpc(2j) assert mpmath.mpmathify(S.Half*I) == mpmath.mpc(0.5j) mpmath.mp.dps = 100 assert mpmath.mpmathify(pi.evalf(100) + pi.evalf(100)*I) == mpmath.pi + mpmath.pi*mpmath.j assert mpmath.mpmathify(pi.evalf(100)*I) == mpmath.pi*mpmath.j def test_relational(): # real x = S(.1) assert (x != cos) is True assert (x == cos) is False # rational x = Rational(1, 3) assert (x != cos) is True assert (x == cos) is False # integer defers to rational so these tests are omitted # number symbol x = pi assert (x != cos) is True assert (x == cos) is False def test_Integer_as_index(): assert 'hello'[Integer(2):] == 'llo' def test_Rational_int(): assert int( Rational(7, 5)) == 1 assert int( S.Half) == 0 assert int(Rational(-1, 2)) == 0 assert int(-Rational(7, 5)) == -1 def test_zoo(): b = Symbol('b', finite=True) nz = Symbol('nz', nonzero=True) p = Symbol('p', positive=True) n = Symbol('n', negative=True) im = Symbol('i', imaginary=True) c = Symbol('c', complex=True) pb = Symbol('pb', positive=True) nb = Symbol('nb', negative=True) imb = Symbol('ib', imaginary=True, finite=True) for i in [I, S.Infinity, S.NegativeInfinity, S.Zero, S.One, S.Pi, S.Half, S(3), log(3), b, nz, p, n, im, pb, nb, imb, c]: if i.is_finite and (i.is_real or i.is_imaginary): assert i + zoo is zoo assert i - zoo is zoo assert zoo + i is zoo assert zoo - i is zoo elif i.is_finite is not False: assert (i + zoo).is_Add assert (i - zoo).is_Add assert (zoo + i).is_Add assert (zoo - i).is_Add else: assert (i + zoo) is S.NaN assert (i - zoo) is S.NaN assert (zoo + i) is S.NaN assert (zoo - i) is S.NaN if fuzzy_not(i.is_zero) and (i.is_extended_real or i.is_imaginary): assert i*zoo is zoo assert zoo*i is zoo elif i.is_zero: assert i*zoo is S.NaN assert zoo*i is S.NaN else: assert (i*zoo).is_Mul assert (zoo*i).is_Mul if fuzzy_not((1/i).is_zero) and (i.is_real or i.is_imaginary): assert zoo/i is zoo elif (1/i).is_zero: assert zoo/i is S.NaN elif i.is_zero: assert zoo/i is zoo else: assert (zoo/i).is_Mul assert (I*oo).is_Mul # allow directed infinity assert zoo + zoo is S.NaN assert zoo * zoo is zoo assert zoo - zoo is S.NaN assert zoo/zoo is S.NaN assert zoo**zoo is S.NaN assert zoo**0 is S.One assert zoo**2 is zoo assert 1/zoo is S.Zero assert Mul.flatten([S.NegativeOne, oo, S(0)]) == ([S.NaN], [], None) def test_issue_4122(): x = Symbol('x', nonpositive=True) assert oo + x is oo x = Symbol('x', extended_nonpositive=True) assert (oo + x).is_Add x = Symbol('x', finite=True) assert (oo + x).is_Add # x could be imaginary x = Symbol('x', nonnegative=True) assert oo + x is oo x = Symbol('x', extended_nonnegative=True) assert oo + x is oo x = Symbol('x', finite=True, real=True) assert oo + x is oo # similarly for negative infinity x = Symbol('x', nonnegative=True) assert -oo + x is -oo x = Symbol('x', extended_nonnegative=True) assert (-oo + x).is_Add x = Symbol('x', finite=True) assert (-oo + x).is_Add x = Symbol('x', nonpositive=True) assert -oo + x is -oo x = Symbol('x', extended_nonpositive=True) assert -oo + x is -oo x = Symbol('x', finite=True, real=True) assert -oo + x is -oo def test_GoldenRatio_expand(): assert GoldenRatio.expand(func=True) == S.Half + sqrt(5)/2 def test_TribonacciConstant_expand(): assert TribonacciConstant.expand(func=True) == \ (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3 def test_as_content_primitive(): assert S.Zero.as_content_primitive() == (1, 0) assert S.Half.as_content_primitive() == (S.Half, 1) assert (Rational(-1, 2)).as_content_primitive() == (S.Half, -1) assert S(3).as_content_primitive() == (3, 1) assert S(3.1).as_content_primitive() == (1, 3.1) def test_hashing_sympy_integers(): # Test for issue 5072 assert {Integer(3)} == {int(3)} assert hash(Integer(4)) == hash(int(4)) def test_rounding_issue_4172(): assert int((E**100).round()) == \ 26881171418161354484126255515800135873611119 assert int((pi**100).round()) == \ 51878483143196131920862615246303013562686760680406 assert int((Rational(1)/EulerGamma**100).round()) == \ 734833795660954410469466 @XFAIL def test_mpmath_issues(): from mpmath.libmp.libmpf import _normalize import mpmath.libmp as mlib rnd = mlib.round_nearest mpf = (0, int(0), -123, -1, 53, rnd) # nan assert _normalize(mpf, 53) != (0, int(0), 0, 0) mpf = (0, int(0), -456, -2, 53, rnd) # +inf assert _normalize(mpf, 53) != (0, int(0), 0, 0) mpf = (1, int(0), -789, -3, 53, rnd) # -inf assert _normalize(mpf, 53) != (0, int(0), 0, 0) from mpmath.libmp.libmpf import fnan assert mlib.mpf_eq(fnan, fnan) def test_Catalan_EulerGamma_prec(): n = GoldenRatio f = Float(n.n(), 5) assert f._mpf_ == (0, int(212079), -17, 18) assert f._prec == 20 assert n._as_mpf_val(20) == f._mpf_ n = EulerGamma f = Float(n.n(), 5) assert f._mpf_ == (0, int(302627), -19, 19) assert f._prec == 20 assert n._as_mpf_val(20) == f._mpf_ def test_Catalan_rewrite(): k = Dummy('k', integer=True, nonnegative=True) assert Catalan.rewrite(Sum).dummy_eq( Sum((-1)**k/(2*k + 1)**2, (k, 0, oo))) assert Catalan.rewrite() == Catalan def test_bool_eq(): assert 0 == False assert S(0) == False assert S(0) != S.false assert 1 == True assert S.One == True assert S.One != S.true def test_Float_eq(): # all .5 values are the same assert Float(.5, 10) == Float(.5, 11) == Float(.5, 1) # but floats that aren't exact in base-2 still # don't compare the same because they have different # underlying mpf values assert Float(.12, 3) != Float(.12, 4) assert Float(.12, 3) != .12 assert 0.12 != Float(.12, 3) assert Float('.12', 22) != .12 # issue 11707 # but Float/Rational -- except for 0 -- # are exact so Rational(x) = Float(y) only if # Rational(x) == Rational(Float(y)) assert Float('1.1') != Rational(11, 10) assert Rational(11, 10) != Float('1.1') # coverage assert not Float(3) == 2 assert not Float(2**2) == S.Half assert Float(2**2) == 4 assert not Float(2**-2) == 1 assert Float(2**-1) == S.Half assert not Float(2*3) == 3 assert not Float(2*3) == S.Half assert Float(2*3) == 6 assert not Float(2*3) == 8 assert Float(.75) == Rational(3, 4) assert Float(5/18) == 5/18 # 4473 assert Float(2.) != 3 assert Float((0,1,-3)) == S.One/8 assert Float((0,1,-3)) != S.One/9 # 16196 assert 2 == Float(2) # as per Python # but in a computation... assert t**2 != t**2.0 def test_issue_6640(): from mpmath.libmp.libmpf import finf, fninf # fnan is not included because Float no longer returns fnan, # but otherwise, the same sort of test could apply assert Float(finf).is_zero is False assert Float(fninf).is_zero is False assert bool(Float(0)) is False def test_issue_6349(): assert Float('23.e3', '')._prec == 10 assert Float('23e3', '')._prec == 20 assert Float('23000', '')._prec == 20 assert Float('-23000', '')._prec == 20 def test_mpf_norm(): assert mpf_norm((1, 0, 1, 0), 10) == mpf('0')._mpf_ assert Float._new((1, 0, 1, 0), 10)._mpf_ == mpf('0')._mpf_ def test_latex(): assert latex(pi) == r"\pi" assert latex(E) == r"e" assert latex(GoldenRatio) == r"\phi" assert latex(TribonacciConstant) == r"\text{TribonacciConstant}" assert latex(EulerGamma) == r"\gamma" assert latex(oo) == r"\infty" assert latex(-oo) == r"-\infty" assert latex(zoo) == r"\tilde{\infty}" assert latex(nan) == r"\text{NaN}" assert latex(I) == r"i" def test_issue_7742(): assert -oo % 1 is nan def test_simplify_AlgebraicNumber(): A = AlgebraicNumber e = 3**(S.One/6)*(3 + (135 + 78*sqrt(3))**Rational(2, 3))/(45 + 26*sqrt(3))**(S.One/3) assert simplify(A(e)) == A(12) # wester test_C20 e = (41 + 29*sqrt(2))**(S.One/5) assert simplify(A(e)) == A(1 + sqrt(2)) # wester test_C21 e = (3 + 4*I)**Rational(3, 2) assert simplify(A(e)) == A(2 + 11*I) # issue 4401 def test_Float_idempotence(): x = Float('1.23', '') y = Float(x) z = Float(x, 15) assert same_and_same_prec(y, x) assert not same_and_same_prec(z, x) x = Float(10**20) y = Float(x) z = Float(x, 15) assert same_and_same_prec(y, x) assert not same_and_same_prec(z, x) def test_comp1(): # sqrt(2) = 1.414213 5623730950... a = sqrt(2).n(7) assert comp(a, 1.4142129) is False assert comp(a, 1.4142130) # ... assert comp(a, 1.4142141) assert comp(a, 1.4142142) is False assert comp(sqrt(2).n(2), '1.4') assert comp(sqrt(2).n(2), Float(1.4, 2), '') assert comp(sqrt(2).n(2), 1.4, '') assert comp(sqrt(2).n(2), Float(1.4, 3), '') is False assert comp(sqrt(2) + sqrt(3)*I, 1.4 + 1.7*I, .1) assert not comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*0.89, .1) assert comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*0.90, .1) assert comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*1.07, .1) assert not comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*1.08, .1) assert [(i, j) for i in range(130, 150) for j in range(170, 180) if comp((sqrt(2)+ I*sqrt(3)).n(3), i/100. + I*j/100.)] == [ (141, 173), (142, 173)] raises(ValueError, lambda: comp(t, '1')) raises(ValueError, lambda: comp(t, 1)) assert comp(0, 0.0) assert comp(.5, S.Half) assert comp(2 + sqrt(2), 2.0 + sqrt(2)) assert not comp(0, 1) assert not comp(2, sqrt(2)) assert not comp(2 + I, 2.0 + sqrt(2)) assert not comp(2.0 + sqrt(2), 2 + I) assert not comp(2.0 + sqrt(2), sqrt(3)) assert comp(1/pi.n(4), 0.3183, 1e-5) assert not comp(1/pi.n(4), 0.3183, 8e-6) def test_issue_9491(): assert oo**zoo is nan def test_issue_10063(): assert 2**Float(3) == Float(8) def test_issue_10020(): assert oo**I is S.NaN assert oo**(1 + I) is S.ComplexInfinity assert oo**(-1 + I) is S.Zero assert (-oo)**I is S.NaN assert (-oo)**(-1 + I) is S.Zero assert oo**t == Pow(oo, t, evaluate=False) assert (-oo)**t == Pow(-oo, t, evaluate=False) def test_invert_numbers(): assert S(2).invert(5) == 3 assert S(2).invert(Rational(5, 2)) == S.Half assert S(2).invert(5.) == 0.5 assert S(2).invert(S(5)) == 3 assert S(2.).invert(5) == 0.5 assert S(sqrt(2)).invert(5) == 1/sqrt(2) assert S(sqrt(2)).invert(sqrt(3)) == 1/sqrt(2) def test_mod_inverse(): assert mod_inverse(3, 11) == 4 assert mod_inverse(5, 11) == 9 assert mod_inverse(21124921, 521512) == 7713 assert mod_inverse(124215421, 5125) == 2981 assert mod_inverse(214, 12515) == 1579 assert mod_inverse(5823991, 3299) == 1442 assert mod_inverse(123, 44) == 39 assert mod_inverse(2, 5) == 3 assert mod_inverse(-2, 5) == 2 assert mod_inverse(2, -5) == -2 assert mod_inverse(-2, -5) == -3 assert mod_inverse(-3, -7) == -5 x = Symbol('x') assert S(2).invert(x) == S.Half raises(TypeError, lambda: mod_inverse(2, x)) raises(ValueError, lambda: mod_inverse(2, S.Half)) raises(ValueError, lambda: mod_inverse(2, cos(1)**2 + sin(1)**2)) def test_golden_ratio_rewrite_as_sqrt(): assert GoldenRatio.rewrite(sqrt) == S.Half + sqrt(5)*S.Half def test_tribonacci_constant_rewrite_as_sqrt(): assert TribonacciConstant.rewrite(sqrt) == \ (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3 def test_comparisons_with_unknown_type(): class Foo: """ Class that is unaware of Basic, and relies on both classes returning the NotImplemented singleton for equivalence to evaluate to False. """ ni, nf, nr = Integer(3), Float(1.0), Rational(1, 3) foo = Foo() for n in ni, nf, nr, oo, -oo, zoo, nan: assert n != foo assert foo != n assert not n == foo assert not foo == n raises(TypeError, lambda: n < foo) raises(TypeError, lambda: foo > n) raises(TypeError, lambda: n > foo) raises(TypeError, lambda: foo < n) raises(TypeError, lambda: n <= foo) raises(TypeError, lambda: foo >= n) raises(TypeError, lambda: n >= foo) raises(TypeError, lambda: foo <= n) class Bar: """ Class that considers itself equal to any instance of Number except infinities and nans, and relies on SymPy types returning the NotImplemented singleton for symmetric equality relations. """ def __eq__(self, other): if other in (oo, -oo, zoo, nan): return False if isinstance(other, Number): return True return NotImplemented def __ne__(self, other): return not self == other bar = Bar() for n in ni, nf, nr: assert n == bar assert bar == n assert not n != bar assert not bar != n for n in oo, -oo, zoo, nan: assert n != bar assert bar != n assert not n == bar assert not bar == n for n in ni, nf, nr, oo, -oo, zoo, nan: raises(TypeError, lambda: n < bar) raises(TypeError, lambda: bar > n) raises(TypeError, lambda: n > bar) raises(TypeError, lambda: bar < n) raises(TypeError, lambda: n <= bar) raises(TypeError, lambda: bar >= n) raises(TypeError, lambda: n >= bar) raises(TypeError, lambda: bar <= n) def test_NumberSymbol_comparison(): from sympy.core.tests.test_relational import rel_check rpi = Rational('905502432259640373/288230376151711744') fpi = Float(float(pi)) assert rel_check(rpi, fpi) def test_Integer_precision(): # Make sure Integer inputs for keyword args work assert Float('1.0', dps=Integer(15))._prec == 53 assert Float('1.0', precision=Integer(15))._prec == 15 assert type(Float('1.0', precision=Integer(15))._prec) == int assert sympify(srepr(Float('1.0', precision=15))) == Float('1.0', precision=15) def test_numpy_to_float(): from sympy.testing.pytest import skip from sympy.external import import_module np = import_module('numpy') if not np: skip('numpy not installed. Abort numpy tests.') def check_prec_and_relerr(npval, ratval): prec = np.finfo(npval).nmant + 1 x = Float(npval) assert x._prec == prec y = Float(ratval, precision=prec) assert abs((x - y)/y) < 2**(-(prec + 1)) check_prec_and_relerr(np.float16(2.0/3), Rational(2, 3)) check_prec_and_relerr(np.float32(2.0/3), Rational(2, 3)) check_prec_and_relerr(np.float64(2.0/3), Rational(2, 3)) # extended precision, on some arch/compilers: x = np.longdouble(2)/3 check_prec_and_relerr(x, Rational(2, 3)) y = Float(x, precision=10) assert same_and_same_prec(y, Float(Rational(2, 3), precision=10)) raises(TypeError, lambda: Float(np.complex64(1+2j))) raises(TypeError, lambda: Float(np.complex128(1+2j))) def test_Integer_ceiling_floor(): a = Integer(4) assert a.floor() == a assert a.ceiling() == a def test_ComplexInfinity(): assert zoo.floor() is zoo assert zoo.ceiling() is zoo assert zoo**zoo is S.NaN def test_Infinity_floor_ceiling_power(): assert oo.floor() is oo assert oo.ceiling() is oo assert oo**S.NaN is S.NaN assert oo**zoo is S.NaN def test_One_power(): assert S.One**12 is S.One assert S.NegativeOne**S.NaN is S.NaN def test_NegativeInfinity(): assert (-oo).floor() is -oo assert (-oo).ceiling() is -oo assert (-oo)**11 is -oo assert (-oo)**12 is oo def test_issue_6133(): raises(TypeError, lambda: (-oo < None)) raises(TypeError, lambda: (S(-2) < None)) raises(TypeError, lambda: (oo < None)) raises(TypeError, lambda: (oo > None)) raises(TypeError, lambda: (S(2) < None)) def test_abc(): x = numbers.Float(5) assert(isinstance(x, nums.Number)) assert(isinstance(x, numbers.Number)) assert(isinstance(x, nums.Real)) y = numbers.Rational(1, 3) assert(isinstance(y, nums.Number)) assert(y.numerator == 1) assert(y.denominator == 3) assert(isinstance(y, nums.Rational)) z = numbers.Integer(3) assert(isinstance(z, nums.Number)) assert(isinstance(z, numbers.Number)) assert(isinstance(z, nums.Rational)) assert(isinstance(z, numbers.Rational)) assert(isinstance(z, nums.Integral)) def test_floordiv(): assert S(2)//S.Half == 4 def test_negation(): assert -S.Zero is S.Zero assert -Float(0) is not S.Zero and -Float(0) == 0
9d51544c228e7c35ea860888c1e277a5b94db4c6669b91227cd54484867c90c2
from sympy.concrete.summations import Sum from sympy.core.basic import Basic, _aresame from sympy.core.cache import clear_cache from sympy.core.containers import Dict, Tuple from sympy.core.expr import Expr, unchanged from sympy.core.function import (Subs, Function, diff, Lambda, expand, nfloat, Derivative) from sympy.core.numbers import E, Float, zoo, Rational, pi, I, oo, nan from sympy.core.power import Pow from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import symbols, Dummy, Symbol from sympy.functions.elementary.complexes import im, re from sympy.functions.elementary.exponential import log, exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import sin, cos, acos from sympy.functions.special.error_functions import expint from sympy.functions.special.gamma_functions import loggamma, polygamma from sympy.matrices.dense import Matrix from sympy.printing.str import sstr from sympy.series.order import O from sympy.tensor.indexed import Indexed from sympy.core.function import (PoleError, _mexpand, arity, BadSignatureError, BadArgumentsError) from sympy.core.parameters import _exp_is_pow from sympy.core.sympify import sympify from sympy.matrices import MutableMatrix, ImmutableMatrix from sympy.sets.sets import FiniteSet from sympy.solvers.solveset import solveset from sympy.tensor.array import NDimArray from sympy.utilities.iterables import subsets, variations from sympy.testing.pytest import XFAIL, raises, warns_deprecated_sympy, _both_exp_pow from sympy.abc import t, w, x, y, z f, g, h = symbols('f g h', cls=Function) _xi_1, _xi_2, _xi_3 = [Dummy() for i in range(3)] def test_f_expand_complex(): x = Symbol('x', real=True) assert f(x).expand(complex=True) == I*im(f(x)) + re(f(x)) assert exp(x).expand(complex=True) == exp(x) assert exp(I*x).expand(complex=True) == cos(x) + I*sin(x) assert exp(z).expand(complex=True) == cos(im(z))*exp(re(z)) + \ I*sin(im(z))*exp(re(z)) def test_bug1(): e = sqrt(-log(w)) assert e.subs(log(w), -x) == sqrt(x) e = sqrt(-5*log(w)) assert e.subs(log(w), -x) == sqrt(5*x) def test_general_function(): nu = Function('nu') e = nu(x) edx = e.diff(x) edy = e.diff(y) edxdx = e.diff(x).diff(x) edxdy = e.diff(x).diff(y) assert e == nu(x) assert edx != nu(x) assert edx == diff(nu(x), x) assert edy == 0 assert edxdx == diff(diff(nu(x), x), x) assert edxdy == 0 def test_general_function_nullary(): nu = Function('nu') e = nu() edx = e.diff(x) edxdx = e.diff(x).diff(x) assert e == nu() assert edx != nu() assert edx == 0 assert edxdx == 0 def test_derivative_subs_bug(): e = diff(g(x), x) assert e.subs(g(x), f(x)) != e assert e.subs(g(x), f(x)) == Derivative(f(x), x) assert e.subs(g(x), -f(x)) == Derivative(-f(x), x) assert e.subs(x, y) == Derivative(g(y), y) def test_derivative_subs_self_bug(): d = diff(f(x), x) assert d.subs(d, y) == y def test_derivative_linearity(): assert diff(-f(x), x) == -diff(f(x), x) assert diff(8*f(x), x) == 8*diff(f(x), x) assert diff(8*f(x), x) != 7*diff(f(x), x) assert diff(8*f(x)*x, x) == 8*f(x) + 8*x*diff(f(x), x) assert diff(8*f(x)*y*x, x).expand() == 8*y*f(x) + 8*y*x*diff(f(x), x) def test_derivative_evaluate(): assert Derivative(sin(x), x) != diff(sin(x), x) assert Derivative(sin(x), x).doit() == diff(sin(x), x) assert Derivative(Derivative(f(x), x), x) == diff(f(x), x, x) assert Derivative(sin(x), x, 0) == sin(x) assert Derivative(sin(x), (x, y), (x, -y)) == sin(x) def test_diff_symbols(): assert diff(f(x, y, z), x, y, z) == Derivative(f(x, y, z), x, y, z) assert diff(f(x, y, z), x, x, x) == Derivative(f(x, y, z), x, x, x) == Derivative(f(x, y, z), (x, 3)) assert diff(f(x, y, z), x, 3) == Derivative(f(x, y, z), x, 3) # issue 5028 assert [diff(-z + x/y, sym) for sym in (z, x, y)] == [-1, 1/y, -x/y**2] assert diff(f(x, y, z), x, y, z, 2) == Derivative(f(x, y, z), x, y, z, z) assert diff(f(x, y, z), x, y, z, 2, evaluate=False) == \ Derivative(f(x, y, z), x, y, z, z) assert Derivative(f(x, y, z), x, y, z)._eval_derivative(z) == \ Derivative(f(x, y, z), x, y, z, z) assert Derivative(Derivative(f(x, y, z), x), y)._eval_derivative(z) == \ Derivative(f(x, y, z), x, y, z) raises(TypeError, lambda: cos(x).diff((x, y)).variables) assert cos(x).diff((x, y))._wrt_variables == [x] def test_Function(): class myfunc(Function): @classmethod def eval(cls): # zero args return assert myfunc.nargs == FiniteSet(0) assert myfunc().nargs == FiniteSet(0) raises(TypeError, lambda: myfunc(x).nargs) class myfunc(Function): @classmethod def eval(cls, x): # one arg return assert myfunc.nargs == FiniteSet(1) assert myfunc(x).nargs == FiniteSet(1) raises(TypeError, lambda: myfunc(x, y).nargs) class myfunc(Function): @classmethod def eval(cls, *x): # star args return assert myfunc.nargs == S.Naturals0 assert myfunc(x).nargs == S.Naturals0 def test_nargs(): f = Function('f') assert f.nargs == S.Naturals0 assert f(1).nargs == S.Naturals0 assert Function('f', nargs=2)(1, 2).nargs == FiniteSet(2) assert sin.nargs == FiniteSet(1) assert sin(2).nargs == FiniteSet(1) assert log.nargs == FiniteSet(1, 2) assert log(2).nargs == FiniteSet(1, 2) assert Function('f', nargs=2).nargs == FiniteSet(2) assert Function('f', nargs=0).nargs == FiniteSet(0) assert Function('f', nargs=(0, 1)).nargs == FiniteSet(0, 1) assert Function('f', nargs=None).nargs == S.Naturals0 raises(ValueError, lambda: Function('f', nargs=())) def test_nargs_inheritance(): class f1(Function): nargs = 2 class f2(f1): pass class f3(f2): pass class f4(f3): nargs = 1,2 class f5(f4): pass class f6(f5): pass class f7(f6): nargs=None class f8(f7): pass class f9(f8): pass class f10(f9): nargs = 1 class f11(f10): pass assert f1.nargs == FiniteSet(2) assert f2.nargs == FiniteSet(2) assert f3.nargs == FiniteSet(2) assert f4.nargs == FiniteSet(1, 2) assert f5.nargs == FiniteSet(1, 2) assert f6.nargs == FiniteSet(1, 2) assert f7.nargs == S.Naturals0 assert f8.nargs == S.Naturals0 assert f9.nargs == S.Naturals0 assert f10.nargs == FiniteSet(1) assert f11.nargs == FiniteSet(1) def test_arity(): f = lambda x, y: 1 assert arity(f) == 2 def f(x, y, z=None): pass assert arity(f) == (2, 3) assert arity(lambda *x: x) is None assert arity(log) == (1, 2) def test_Lambda(): e = Lambda(x, x**2) assert e(4) == 16 assert e(x) == x**2 assert e(y) == y**2 assert Lambda((), 42)() == 42 assert unchanged(Lambda, (), 42) assert Lambda((), 42) != Lambda((), 43) assert Lambda((), f(x))() == f(x) assert Lambda((), 42).nargs == FiniteSet(0) assert unchanged(Lambda, (x,), x**2) assert Lambda(x, x**2) == Lambda((x,), x**2) assert Lambda(x, x**2) != Lambda(x, x**2 + 1) assert Lambda((x, y), x**y) != Lambda((y, x), y**x) assert Lambda((x, y), x**y) != Lambda((x, y), y**x) assert Lambda((x, y), x**y)(x, y) == x**y assert Lambda((x, y), x**y)(3, 3) == 3**3 assert Lambda((x, y), x**y)(x, 3) == x**3 assert Lambda((x, y), x**y)(3, y) == 3**y assert Lambda(x, f(x))(x) == f(x) assert Lambda(x, x**2)(e(x)) == x**4 assert e(e(x)) == x**4 x1, x2 = (Indexed('x', i) for i in (1, 2)) assert Lambda((x1, x2), x1 + x2)(x, y) == x + y assert Lambda((x, y), x + y).nargs == FiniteSet(2) p = x, y, z, t assert Lambda(p, t*(x + y + z))(*p) == t * (x + y + z) eq = Lambda(x, 2*x) + Lambda(y, 2*y) assert eq != 2*Lambda(x, 2*x) assert eq.as_dummy() == 2*Lambda(x, 2*x).as_dummy() assert Lambda(x, 2*x) not in [ Lambda(x, x) ] raises(BadSignatureError, lambda: Lambda(1, x)) assert Lambda(x, 1)(1) is S.One raises(BadSignatureError, lambda: Lambda((x, x), x + 2)) raises(BadSignatureError, lambda: Lambda(((x, x), y), x)) raises(BadSignatureError, lambda: Lambda(((y, x), x), x)) raises(BadSignatureError, lambda: Lambda(((y, 1), 2), x)) with warns_deprecated_sympy(): assert Lambda([x, y], x+y) == Lambda((x, y), x+y) flam = Lambda(((x, y),), x + y) assert flam((2, 3)) == 5 flam = Lambda(((x, y), z), x + y + z) assert flam((2, 3), 1) == 6 flam = Lambda((((x, y), z),), x + y + z) assert flam(((2, 3), 1)) == 6 raises(BadArgumentsError, lambda: flam(1, 2, 3)) flam = Lambda( (x,), (x, x)) assert flam(1,) == (1, 1) assert flam((1,)) == ((1,), (1,)) flam = Lambda( ((x,),), (x, x)) raises(BadArgumentsError, lambda: flam(1)) assert flam((1,)) == (1, 1) # Previously TypeError was raised so this is potentially needed for # backwards compatibility. assert issubclass(BadSignatureError, TypeError) assert issubclass(BadArgumentsError, TypeError) # These are tested to see they don't raise: hash(Lambda(x, 2*x)) hash(Lambda(x, x)) # IdentityFunction subclass def test_IdentityFunction(): assert Lambda(x, x) is Lambda(y, y) is S.IdentityFunction assert Lambda(x, 2*x) is not S.IdentityFunction assert Lambda((x, y), x) is not S.IdentityFunction def test_Lambda_symbols(): assert Lambda(x, 2*x).free_symbols == set() assert Lambda(x, x*y).free_symbols == {y} assert Lambda((), 42).free_symbols == set() assert Lambda((), x*y).free_symbols == {x,y} def test_functionclas_symbols(): assert f.free_symbols == set() def test_Lambda_arguments(): raises(TypeError, lambda: Lambda(x, 2*x)(x, y)) raises(TypeError, lambda: Lambda((x, y), x + y)(x)) raises(TypeError, lambda: Lambda((), 42)(x)) def test_Lambda_equality(): assert Lambda((x, y), 2*x) == Lambda((x, y), 2*x) # these, of course, should never be equal assert Lambda(x, 2*x) != Lambda((x, y), 2*x) assert Lambda(x, 2*x) != 2*x # But it is tempting to want expressions that differ only # in bound symbols to compare the same. But this is not what # Python's `==` is intended to do; two objects that compare # as equal means that they are indistibguishable and cache to the # same value. We wouldn't want to expression that are # mathematically the same but written in different variables to be # interchanged else what is the point of allowing for different # variable names? assert Lambda(x, 2*x) != Lambda(y, 2*y) def test_Subs(): assert Subs(1, (), ()) is S.One # check null subs influence on hashing assert Subs(x, y, z) != Subs(x, y, 1) # neutral subs works assert Subs(x, x, 1).subs(x, y).has(y) # self mapping var/point assert Subs(Derivative(f(x), (x, 2)), x, x).doit() == f(x).diff(x, x) assert Subs(x, x, 0).has(x) # it's a structural answer assert not Subs(x, x, 0).free_symbols assert Subs(Subs(x + y, x, 2), y, 1) == Subs(x + y, (x, y), (2, 1)) assert Subs(x, (x,), (0,)) == Subs(x, x, 0) assert Subs(x, x, 0) == Subs(y, y, 0) assert Subs(x, x, 0).subs(x, 1) == Subs(x, x, 0) assert Subs(y, x, 0).subs(y, 1) == Subs(1, x, 0) assert Subs(f(x), x, 0).doit() == f(0) assert Subs(f(x**2), x**2, 0).doit() == f(0) assert Subs(f(x, y, z), (x, y, z), (0, 1, 1)) != \ Subs(f(x, y, z), (x, y, z), (0, 0, 1)) assert Subs(x, y, 2).subs(x, y).doit() == 2 assert Subs(f(x, y), (x, y, z), (0, 1, 1)) != \ Subs(f(x, y) + z, (x, y, z), (0, 1, 0)) assert Subs(f(x, y), (x, y), (0, 1)).doit() == f(0, 1) assert Subs(Subs(f(x, y), x, 0), y, 1).doit() == f(0, 1) raises(ValueError, lambda: Subs(f(x, y), (x, y), (0, 0, 1))) raises(ValueError, lambda: Subs(f(x, y), (x, x, y), (0, 0, 1))) assert len(Subs(f(x, y), (x, y), (0, 1)).variables) == 2 assert Subs(f(x, y), (x, y), (0, 1)).point == Tuple(0, 1) assert Subs(f(x), x, 0) == Subs(f(y), y, 0) assert Subs(f(x, y), (x, y), (0, 1)) == Subs(f(x, y), (y, x), (1, 0)) assert Subs(f(x)*y, (x, y), (0, 1)) == Subs(f(y)*x, (y, x), (0, 1)) assert Subs(f(x)*y, (x, y), (1, 1)) == Subs(f(y)*x, (x, y), (1, 1)) assert Subs(f(x), x, 0).subs(x, 1).doit() == f(0) assert Subs(f(x), x, y).subs(y, 0) == Subs(f(x), x, 0) assert Subs(y*f(x), x, y).subs(y, 2) == Subs(2*f(x), x, 2) assert (2 * Subs(f(x), x, 0)).subs(Subs(f(x), x, 0), y) == 2*y assert Subs(f(x), x, 0).free_symbols == set() assert Subs(f(x, y), x, z).free_symbols == {y, z} assert Subs(f(x).diff(x), x, 0).doit(), Subs(f(x).diff(x), x, 0) assert Subs(1 + f(x).diff(x), x, 0).doit(), 1 + Subs(f(x).diff(x), x, 0) assert Subs(y*f(x, y).diff(x), (x, y), (0, 2)).doit() == \ 2*Subs(Derivative(f(x, 2), x), x, 0) assert Subs(y**2*f(x), x, 0).diff(y) == 2*y*f(0) e = Subs(y**2*f(x), x, y) assert e.diff(y) == e.doit().diff(y) == y**2*Derivative(f(y), y) + 2*y*f(y) assert Subs(f(x), x, 0) + Subs(f(x), x, 0) == 2*Subs(f(x), x, 0) e1 = Subs(z*f(x), x, 1) e2 = Subs(z*f(y), y, 1) assert e1 + e2 == 2*e1 assert e1.__hash__() == e2.__hash__() assert Subs(z*f(x + 1), x, 1) not in [ e1, e2 ] assert Derivative(f(x), x).subs(x, g(x)) == Derivative(f(g(x)), g(x)) assert Derivative(f(x), x).subs(x, x + y) == Subs(Derivative(f(x), x), x, x + y) assert Subs(f(x)*cos(y) + z, (x, y), (0, pi/3)).n(2) == \ Subs(f(x)*cos(y) + z, (x, y), (0, pi/3)).evalf(2) == \ z + Rational('1/2').n(2)*f(0) assert f(x).diff(x).subs(x, 0).subs(x, y) == f(x).diff(x).subs(x, 0) assert (x*f(x).diff(x).subs(x, 0)).subs(x, y) == y*f(x).diff(x).subs(x, 0) assert Subs(Derivative(g(x)**2, g(x), x), g(x), exp(x) ).doit() == 2*exp(x) assert Subs(Derivative(g(x)**2, g(x), x), g(x), exp(x) ).doit(deep=False) == 2*Derivative(exp(x), x) assert Derivative(f(x, g(x)), x).doit() == Derivative( f(x, g(x)), g(x))*Derivative(g(x), x) + Subs(Derivative( f(y, g(x)), y), y, x) def test_doitdoit(): done = Derivative(f(x, g(x)), x, g(x)).doit() assert done == done.doit() @XFAIL def test_Subs2(): # this reflects a limitation of subs(), probably won't fix assert Subs(f(x), x**2, x).doit() == f(sqrt(x)) def test_expand_function(): assert expand(x + y) == x + y assert expand(x + y, complex=True) == I*im(x) + I*im(y) + re(x) + re(y) assert expand((x + y)**11, modulus=11) == x**11 + y**11 def test_function_comparable(): assert sin(x).is_comparable is False assert cos(x).is_comparable is False assert sin(Float('0.1')).is_comparable is True assert cos(Float('0.1')).is_comparable is True assert sin(E).is_comparable is True assert cos(E).is_comparable is True assert sin(Rational(1, 3)).is_comparable is True assert cos(Rational(1, 3)).is_comparable is True def test_function_comparable_infinities(): assert sin(oo).is_comparable is False assert sin(-oo).is_comparable is False assert sin(zoo).is_comparable is False assert sin(nan).is_comparable is False def test_deriv1(): # These all require derivatives evaluated at a point (issue 4719) to work. # See issue 4624 assert f(2*x).diff(x) == 2*Subs(Derivative(f(x), x), x, 2*x) assert (f(x)**3).diff(x) == 3*f(x)**2*f(x).diff(x) assert (f(2*x)**3).diff(x) == 6*f(2*x)**2*Subs( Derivative(f(x), x), x, 2*x) assert f(2 + x).diff(x) == Subs(Derivative(f(x), x), x, x + 2) assert f(2 + 3*x).diff(x) == 3*Subs( Derivative(f(x), x), x, 3*x + 2) assert f(3*sin(x)).diff(x) == 3*cos(x)*Subs( Derivative(f(x), x), x, 3*sin(x)) # See issue 8510 assert f(x, x + z).diff(x) == ( Subs(Derivative(f(y, x + z), y), y, x) + Subs(Derivative(f(x, y), y), y, x + z)) assert f(x, x**2).diff(x) == ( 2*x*Subs(Derivative(f(x, y), y), y, x**2) + Subs(Derivative(f(y, x**2), y), y, x)) # but Subs is not always necessary assert f(x, g(y)).diff(g(y)) == Derivative(f(x, g(y)), g(y)) def test_deriv2(): assert (x**3).diff(x) == 3*x**2 assert (x**3).diff(x, evaluate=False) != 3*x**2 assert (x**3).diff(x, evaluate=False) == Derivative(x**3, x) assert diff(x**3, x) == 3*x**2 assert diff(x**3, x, evaluate=False) != 3*x**2 assert diff(x**3, x, evaluate=False) == Derivative(x**3, x) def test_func_deriv(): assert f(x).diff(x) == Derivative(f(x), x) # issue 4534 assert f(x, y).diff(x, y) - f(x, y).diff(y, x) == 0 assert Derivative(f(x, y), x, y).args[1:] == ((x, 1), (y, 1)) assert Derivative(f(x, y), y, x).args[1:] == ((y, 1), (x, 1)) assert (Derivative(f(x, y), x, y) - Derivative(f(x, y), y, x)).doit() == 0 def test_suppressed_evaluation(): a = sin(0, evaluate=False) assert a != 0 assert a.func is sin assert a.args == (0,) def test_function_evalf(): def eq(a, b, eps): return abs(a - b) < eps assert eq(sin(1).evalf(15), Float("0.841470984807897"), 1e-13) assert eq( sin(2).evalf(25), Float("0.9092974268256816953960199", 25), 1e-23) assert eq(sin(1 + I).evalf( 15), Float("1.29845758141598") + Float("0.634963914784736")*I, 1e-13) assert eq(exp(1 + I).evalf(15), Float( "1.46869393991588") + Float("2.28735528717884239")*I, 1e-13) assert eq(exp(-0.5 + 1.5*I).evalf(15), Float( "0.0429042815937374") + Float("0.605011292285002")*I, 1e-13) assert eq(log(pi + sqrt(2)*I).evalf( 15), Float("1.23699044022052") + Float("0.422985442737893")*I, 1e-13) assert eq(cos(100).evalf(15), Float("0.86231887228768"), 1e-13) def test_extensibility_eval(): class MyFunc(Function): @classmethod def eval(cls, *args): return (0, 0, 0) assert MyFunc(0) == (0, 0, 0) @_both_exp_pow def test_function_non_commutative(): x = Symbol('x', commutative=False) assert f(x).is_commutative is False assert sin(x).is_commutative is False assert exp(x).is_commutative is False assert log(x).is_commutative is False assert f(x).is_complex is False assert sin(x).is_complex is False assert exp(x).is_complex is False assert log(x).is_complex is False def test_function_complex(): x = Symbol('x', complex=True) xzf = Symbol('x', complex=True, zero=False) assert f(x).is_commutative is True assert sin(x).is_commutative is True assert exp(x).is_commutative is True assert log(x).is_commutative is True assert f(x).is_complex is None assert sin(x).is_complex is True assert exp(x).is_complex is True assert log(x).is_complex is None assert log(xzf).is_complex is True def test_function__eval_nseries(): n = Symbol('n') assert sin(x)._eval_nseries(x, 2, None) == x + O(x**2) assert sin(x + 1)._eval_nseries(x, 2, None) == x*cos(1) + sin(1) + O(x**2) assert sin(pi*(1 - x))._eval_nseries(x, 2, None) == pi*x + O(x**2) assert acos(1 - x**2)._eval_nseries(x, 2, None) == sqrt(2)*sqrt(x**2) + O(x**2) assert polygamma(n, x + 1)._eval_nseries(x, 2, None) == \ polygamma(n, 1) + polygamma(n + 1, 1)*x + O(x**2) raises(PoleError, lambda: sin(1/x)._eval_nseries(x, 2, None)) assert acos(1 - x)._eval_nseries(x, 2, None) == sqrt(2)*sqrt(x) + sqrt(2)*x**(S(3)/2)/12 + O(x**2) assert acos(1 + x)._eval_nseries(x, 2, None) == sqrt(2)*sqrt(-x) + sqrt(2)*(-x)**(S(3)/2)/12 + O(x**2) assert loggamma(1/x)._eval_nseries(x, 0, None) == \ log(x)/2 - log(x)/x - 1/x + O(1, x) assert loggamma(log(1/x)).nseries(x, n=1, logx=y) == loggamma(-y) # issue 6725: assert expint(Rational(3, 2), -x)._eval_nseries(x, 5, None) == \ 2 - 2*sqrt(pi)*sqrt(-x) - 2*x + x**2 + x**3/3 + x**4/12 + 4*I*x**(S(3)/2)*sqrt(-x)/3 + \ 2*I*x**(S(5)/2)*sqrt(-x)/5 + 2*I*x**(S(7)/2)*sqrt(-x)/21 + O(x**5) assert sin(sqrt(x))._eval_nseries(x, 3, None) == \ sqrt(x) - x**Rational(3, 2)/6 + x**Rational(5, 2)/120 + O(x**3) # issue 19065: s1 = f(x,y).series(y, n=2) assert {i.name for i in s1.atoms(Symbol)} == {'x', 'xi', 'y'} xi = Symbol('xi') s2 = f(xi, y).series(y, n=2) assert {i.name for i in s2.atoms(Symbol)} == {'xi', 'xi0', 'y'} def test_doit(): n = Symbol('n', integer=True) f = Sum(2 * n * x, (n, 1, 3)) d = Derivative(f, x) assert d.doit() == 12 assert d.doit(deep=False) == Sum(2*n, (n, 1, 3)) def test_evalf_default(): from sympy.functions.special.gamma_functions import polygamma assert type(sin(4.0)) == Float assert type(re(sin(I + 1.0))) == Float assert type(im(sin(I + 1.0))) == Float assert type(sin(4)) == sin assert type(polygamma(2.0, 4.0)) == Float assert type(sin(Rational(1, 4))) == sin def test_issue_5399(): args = [x, y, S(2), S.Half] def ok(a): """Return True if the input args for diff are ok""" if not a: return False if a[0].is_Symbol is False: return False s_at = [i for i in range(len(a)) if a[i].is_Symbol] n_at = [i for i in range(len(a)) if not a[i].is_Symbol] # every symbol is followed by symbol or int # every number is followed by a symbol return (all(a[i + 1].is_Symbol or a[i + 1].is_Integer for i in s_at if i + 1 < len(a)) and all(a[i + 1].is_Symbol for i in n_at if i + 1 < len(a))) eq = x**10*y**8 for a in subsets(args): for v in variations(a, len(a)): if ok(v): eq.diff(*v) # does not raise else: raises(ValueError, lambda: eq.diff(*v)) def test_derivative_numerically(): z0 = x._random() assert abs(Derivative(sin(x), x).doit_numerically(z0) - cos(z0)) < 1e-15 def test_fdiff_argument_index_error(): from sympy.core.function import ArgumentIndexError class myfunc(Function): nargs = 1 # define since there is no eval routine def fdiff(self, idx): raise ArgumentIndexError mf = myfunc(x) assert mf.diff(x) == Derivative(mf, x) raises(TypeError, lambda: myfunc(x, x)) def test_deriv_wrt_function(): x = f(t) xd = diff(x, t) xdd = diff(xd, t) y = g(t) yd = diff(y, t) assert diff(x, t) == xd assert diff(2 * x + 4, t) == 2 * xd assert diff(2 * x + 4 + y, t) == 2 * xd + yd assert diff(2 * x + 4 + y * x, t) == 2 * xd + x * yd + xd * y assert diff(2 * x + 4 + y * x, x) == 2 + y assert (diff(4 * x**2 + 3 * x + x * y, t) == 3 * xd + x * yd + xd * y + 8 * x * xd) assert (diff(4 * x**2 + 3 * xd + x * y, t) == 3 * xdd + x * yd + xd * y + 8 * x * xd) assert diff(4 * x**2 + 3 * xd + x * y, xd) == 3 assert diff(4 * x**2 + 3 * xd + x * y, xdd) == 0 assert diff(sin(x), t) == xd * cos(x) assert diff(exp(x), t) == xd * exp(x) assert diff(sqrt(x), t) == xd / (2 * sqrt(x)) def test_diff_wrt_value(): assert Expr()._diff_wrt is False assert x._diff_wrt is True assert f(x)._diff_wrt is True assert Derivative(f(x), x)._diff_wrt is True assert Derivative(x**2, x)._diff_wrt is False def test_diff_wrt(): fx = f(x) dfx = diff(f(x), x) ddfx = diff(f(x), x, x) assert diff(sin(fx) + fx**2, fx) == cos(fx) + 2*fx assert diff(sin(dfx) + dfx**2, dfx) == cos(dfx) + 2*dfx assert diff(sin(ddfx) + ddfx**2, ddfx) == cos(ddfx) + 2*ddfx assert diff(fx**2, dfx) == 0 assert diff(fx**2, ddfx) == 0 assert diff(dfx**2, fx) == 0 assert diff(dfx**2, ddfx) == 0 assert diff(ddfx**2, dfx) == 0 assert diff(fx*dfx*ddfx, fx) == dfx*ddfx assert diff(fx*dfx*ddfx, dfx) == fx*ddfx assert diff(fx*dfx*ddfx, ddfx) == fx*dfx assert diff(f(x), x).diff(f(x)) == 0 assert (sin(f(x)) - cos(diff(f(x), x))).diff(f(x)) == cos(f(x)) assert diff(sin(fx), fx, x) == diff(sin(fx), x, fx) # Chain rule cases assert f(g(x)).diff(x) == \ Derivative(g(x), x)*Derivative(f(g(x)), g(x)) assert diff(f(g(x), h(y)), x) == \ Derivative(g(x), x)*Derivative(f(g(x), h(y)), g(x)) assert diff(f(g(x), h(x)), x) == ( Derivative(f(g(x), h(x)), g(x))*Derivative(g(x), x) + Derivative(f(g(x), h(x)), h(x))*Derivative(h(x), x)) assert f( sin(x)).diff(x) == cos(x)*Subs(Derivative(f(x), x), x, sin(x)) assert diff(f(g(x)), g(x)) == Derivative(f(g(x)), g(x)) def test_diff_wrt_func_subs(): assert f(g(x)).diff(x).subs(g, Lambda(x, 2*x)).doit() == f(2*x).diff(x) def test_subs_in_derivative(): expr = sin(x*exp(y)) u = Function('u') v = Function('v') assert Derivative(expr, y).subs(expr, y) == Derivative(y, y) assert Derivative(expr, y).subs(y, x).doit() == \ Derivative(expr, y).doit().subs(y, x) assert Derivative(f(x, y), y).subs(y, x) == Subs(Derivative(f(x, y), y), y, x) assert Derivative(f(x, y), y).subs(x, y) == Subs(Derivative(f(x, y), y), x, y) assert Derivative(f(x, y), y).subs(y, g(x, y)) == Subs(Derivative(f(x, y), y), y, g(x, y)).doit() assert Derivative(f(x, y), y).subs(x, g(x, y)) == Subs(Derivative(f(x, y), y), x, g(x, y)) assert Derivative(f(x, y), g(y)).subs(x, g(x, y)) == Derivative(f(g(x, y), y), g(y)) assert Derivative(f(u(x), h(y)), h(y)).subs(h(y), g(x, y)) == \ Subs(Derivative(f(u(x), h(y)), h(y)), h(y), g(x, y)).doit() assert Derivative(f(x, y), y).subs(y, z) == Derivative(f(x, z), z) assert Derivative(f(x, y), y).subs(y, g(y)) == Derivative(f(x, g(y)), g(y)) assert Derivative(f(g(x), h(y)), h(y)).subs(h(y), u(y)) == \ Derivative(f(g(x), u(y)), u(y)) assert Derivative(f(x, f(x, x)), f(x, x)).subs( f, Lambda((x, y), x + y)) == Subs( Derivative(z + x, z), z, 2*x) assert Subs(Derivative(f(f(x)), x), f, cos).doit() == sin(x)*sin(cos(x)) assert Subs(Derivative(f(f(x)), f(x)), f, cos).doit() == -sin(cos(x)) # Issue 13791. No comparison (it's a long formula) but this used to raise an exception. assert isinstance(v(x, y, u(x, y)).diff(y).diff(x).diff(y), Expr) # This is also related to issues 13791 and 13795; issue 15190 F = Lambda((x, y), exp(2*x + 3*y)) abstract = f(x, f(x, x)).diff(x, 2) concrete = F(x, F(x, x)).diff(x, 2) assert (abstract.subs(f, F).doit() - concrete).simplify() == 0 # don't introduce a new symbol if not necessary assert x in f(x).diff(x).subs(x, 0).atoms() # case (4) assert Derivative(f(x,f(x,y)), x, y).subs(x, g(y) ) == Subs(Derivative(f(x, f(x, y)), x, y), x, g(y)) assert Derivative(f(x, x), x).subs(x, 0 ) == Subs(Derivative(f(x, x), x), x, 0) # issue 15194 assert Derivative(f(y, g(x)), (x, z)).subs(z, x ) == Derivative(f(y, g(x)), (x, x)) df = f(x).diff(x) assert df.subs(df, 1) is S.One assert df.diff(df) is S.One dxy = Derivative(f(x, y), x, y) dyx = Derivative(f(x, y), y, x) assert dxy.subs(Derivative(f(x, y), y, x), 1) is S.One assert dxy.diff(dyx) is S.One assert Derivative(f(x, y), x, 2, y, 3).subs( dyx, g(x, y)) == Derivative(g(x, y), x, 1, y, 2) assert Derivative(f(x, x - y), y).subs(x, x + y) == Subs( Derivative(f(x, x - y), y), x, x + y) def test_diff_wrt_not_allowed(): # issue 7027 included for wrt in ( cos(x), re(x), x**2, x*y, 1 + x, Derivative(cos(x), x), Derivative(f(f(x)), x)): raises(ValueError, lambda: diff(f(x), wrt)) # if we don't differentiate wrt then don't raise error assert diff(exp(x*y), x*y, 0) == exp(x*y) def test_klein_gordon_lagrangian(): m = Symbol('m') phi = f(x, t) L = -(diff(phi, t)**2 - diff(phi, x)**2 - m**2*phi**2)/2 eqna = Eq( diff(L, phi) - diff(L, diff(phi, x), x) - diff(L, diff(phi, t), t), 0) eqnb = Eq(diff(phi, t, t) - diff(phi, x, x) + m**2*phi, 0) assert eqna == eqnb def test_sho_lagrangian(): m = Symbol('m') k = Symbol('k') x = f(t) L = m*diff(x, t)**2/2 - k*x**2/2 eqna = Eq(diff(L, x), diff(L, diff(x, t), t)) eqnb = Eq(-k*x, m*diff(x, t, t)) assert eqna == eqnb assert diff(L, x, t) == diff(L, t, x) assert diff(L, diff(x, t), t) == m*diff(x, t, 2) assert diff(L, t, diff(x, t)) == -k*x + m*diff(x, t, 2) def test_straight_line(): F = f(x) Fd = F.diff(x) L = sqrt(1 + Fd**2) assert diff(L, F) == 0 assert diff(L, Fd) == Fd/sqrt(1 + Fd**2) def test_sort_variable(): vsort = Derivative._sort_variable_count def vsort0(*v, reverse=False): return [i[0] for i in vsort([(i, 0) for i in ( reversed(v) if reverse else v)])] for R in range(2): assert vsort0(y, x, reverse=R) == [x, y] assert vsort0(f(x), x, reverse=R) == [x, f(x)] assert vsort0(f(y), f(x), reverse=R) == [f(x), f(y)] assert vsort0(g(x), f(y), reverse=R) == [f(y), g(x)] assert vsort0(f(x, y), f(x), reverse=R) == [f(x), f(x, y)] fx = f(x).diff(x) assert vsort0(fx, y, reverse=R) == [y, fx] fy = f(y).diff(y) assert vsort0(fy, fx, reverse=R) == [fx, fy] fxx = fx.diff(x) assert vsort0(fxx, fx, reverse=R) == [fx, fxx] assert vsort0(Basic(x), f(x), reverse=R) == [f(x), Basic(x)] assert vsort0(Basic(y), Basic(x), reverse=R) == [Basic(x), Basic(y)] assert vsort0(Basic(y, z), Basic(x), reverse=R) == [ Basic(x), Basic(y, z)] assert vsort0(fx, x, reverse=R) == [ x, fx] if R else [fx, x] assert vsort0(Basic(x), x, reverse=R) == [ x, Basic(x)] if R else [Basic(x), x] assert vsort0(Basic(f(x)), f(x), reverse=R) == [ f(x), Basic(f(x))] if R else [Basic(f(x)), f(x)] assert vsort0(Basic(x, z), Basic(x), reverse=R) == [ Basic(x), Basic(x, z)] if R else [Basic(x, z), Basic(x)] assert vsort([]) == [] assert _aresame(vsort([(x, 1)]), [Tuple(x, 1)]) assert vsort([(x, y), (x, z)]) == [(x, y + z)] assert vsort([(y, 1), (x, 1 + y)]) == [(x, 1 + y), (y, 1)] # coverage complete; legacy tests below assert vsort([(x, 3), (y, 2), (z, 1)]) == [(x, 3), (y, 2), (z, 1)] assert vsort([(h(x), 1), (g(x), 1), (f(x), 1)]) == [ (f(x), 1), (g(x), 1), (h(x), 1)] assert vsort([(z, 1), (y, 2), (x, 3), (h(x), 1), (g(x), 1), (f(x), 1)]) == [(x, 3), (y, 2), (z, 1), (f(x), 1), (g(x), 1), (h(x), 1)] assert vsort([(x, 1), (f(x), 1), (y, 1), (f(y), 1)]) == [(x, 1), (y, 1), (f(x), 1), (f(y), 1)] assert vsort([(y, 1), (x, 2), (g(x), 1), (f(x), 1), (z, 1), (h(x), 1), (y, 2), (x, 1)]) == [(x, 3), (y, 3), (z, 1), (f(x), 1), (g(x), 1), (h(x), 1)] assert vsort([(z, 1), (y, 1), (f(x), 1), (x, 1), (f(x), 1), (g(x), 1)]) == [(x, 1), (y, 1), (z, 1), (f(x), 2), (g(x), 1)] assert vsort([(z, 1), (y, 2), (f(x), 1), (x, 2), (f(x), 2), (g(x), 1), (z, 2), (z, 1), (y, 1), (x, 1)]) == [(x, 3), (y, 3), (z, 4), (f(x), 3), (g(x), 1)] assert vsort(((y, 2), (x, 1), (y, 1), (x, 1))) == [(x, 2), (y, 3)] assert isinstance(vsort([(x, 3), (y, 2), (z, 1)])[0], Tuple) assert vsort([(x, 1), (f(x), 1), (x, 1)]) == [(x, 2), (f(x), 1)] assert vsort([(y, 2), (x, 3), (z, 1)]) == [(x, 3), (y, 2), (z, 1)] assert vsort([(h(y), 1), (g(x), 1), (f(x), 1)]) == [ (f(x), 1), (g(x), 1), (h(y), 1)] assert vsort([(x, 1), (y, 1), (x, 1)]) == [(x, 2), (y, 1)] assert vsort([(f(x), 1), (f(y), 1), (f(x), 1)]) == [ (f(x), 2), (f(y), 1)] dfx = f(x).diff(x) self = [(dfx, 1), (x, 1)] assert vsort(self) == self assert vsort([ (dfx, 1), (y, 1), (f(x), 1), (x, 1), (f(y), 1), (x, 1)]) == [ (y, 1), (f(x), 1), (f(y), 1), (dfx, 1), (x, 2)] dfy = f(y).diff(y) assert vsort([(dfy, 1), (dfx, 1)]) == [(dfx, 1), (dfy, 1)] d2fx = dfx.diff(x) assert vsort([(d2fx, 1), (dfx, 1)]) == [(dfx, 1), (d2fx, 1)] def test_multiple_derivative(): # Issue #15007 assert f(x, y).diff(y, y, x, y, x ) == Derivative(f(x, y), (x, 2), (y, 3)) def test_unhandled(): class MyExpr(Expr): def _eval_derivative(self, s): if not s.name.startswith('xi'): return self else: return None eq = MyExpr(f(x), y, z) assert diff(eq, x, y, f(x), z) == Derivative(eq, f(x)) assert diff(eq, f(x), x) == Derivative(eq, f(x)) assert f(x, y).diff(x,(y, z)) == Derivative(f(x, y), x, (y, z)) assert f(x, y).diff(x,(y, 0)) == Derivative(f(x, y), x) def test_nfloat(): from sympy.core.basic import _aresame from sympy.polys.rootoftools import rootof x = Symbol("x") eq = x**Rational(4, 3) + 4*x**(S.One/3)/3 assert _aresame(nfloat(eq), x**Rational(4, 3) + (4.0/3)*x**(S.One/3)) assert _aresame(nfloat(eq, exponent=True), x**(4.0/3) + (4.0/3)*x**(1.0/3)) eq = x**Rational(4, 3) + 4*x**(x/3)/3 assert _aresame(nfloat(eq), x**Rational(4, 3) + (4.0/3)*x**(x/3)) big = 12345678901234567890 # specify precision to match value used in nfloat Float_big = Float(big, 15) assert _aresame(nfloat(big), Float_big) assert _aresame(nfloat(big*x), Float_big*x) assert _aresame(nfloat(x**big, exponent=True), x**Float_big) assert nfloat(cos(x + sqrt(2))) == cos(x + nfloat(sqrt(2))) # issue 6342 f = S('x*lamda + lamda**3*(x/2 + 1/2) + lamda**2 + 1/4') assert not any(a.free_symbols for a in solveset(f.subs(x, -0.139))) # issue 6632 assert nfloat(-100000*sqrt(2500000001) + 5000000001) == \ 9.99999999800000e-11 # issue 7122 eq = cos(3*x**4 + y)*rootof(x**5 + 3*x**3 + 1, 0) assert str(nfloat(eq, exponent=False, n=1)) == '-0.7*cos(3.0*x**4 + y)' # issue 10933 for ti in (dict, Dict): d = ti({S.Half: S.Half}) n = nfloat(d) assert isinstance(n, ti) assert _aresame(list(n.items()).pop(), (S.Half, Float(.5))) for ti in (dict, Dict): d = ti({S.Half: S.Half}) n = nfloat(d, dkeys=True) assert isinstance(n, ti) assert _aresame(list(n.items()).pop(), (Float(.5), Float(.5))) d = [S.Half] n = nfloat(d) assert type(n) is list assert _aresame(n[0], Float(.5)) assert _aresame(nfloat(Eq(x, S.Half)).rhs, Float(.5)) assert _aresame(nfloat(S(True)), S(True)) assert _aresame(nfloat(Tuple(S.Half))[0], Float(.5)) assert nfloat(Eq((3 - I)**2/2 + I, 0)) == S.false # pass along kwargs assert nfloat([{S.Half: x}], dkeys=True) == [{Float(0.5): x}] # Issue 17706 A = MutableMatrix([[1, 2], [3, 4]]) B = MutableMatrix( [[Float('1.0', precision=53), Float('2.0', precision=53)], [Float('3.0', precision=53), Float('4.0', precision=53)]]) assert _aresame(nfloat(A), B) A = ImmutableMatrix([[1, 2], [3, 4]]) B = ImmutableMatrix( [[Float('1.0', precision=53), Float('2.0', precision=53)], [Float('3.0', precision=53), Float('4.0', precision=53)]]) assert _aresame(nfloat(A), B) # issue 22524 f = Function('f') assert not nfloat(f(2)).atoms(Float) def test_issue_7068(): from sympy.abc import a, b f = Function('f') y1 = Dummy('y') y2 = Dummy('y') func1 = f(a + y1 * b) func2 = f(a + y2 * b) func1_y = func1.diff(y1) func2_y = func2.diff(y2) assert func1_y != func2_y z1 = Subs(f(a), a, y1) z2 = Subs(f(a), a, y2) assert z1 != z2 def test_issue_7231(): from sympy.abc import a ans1 = f(x).series(x, a) res = (f(a) + (-a + x)*Subs(Derivative(f(y), y), y, a) + (-a + x)**2*Subs(Derivative(f(y), y, y), y, a)/2 + (-a + x)**3*Subs(Derivative(f(y), y, y, y), y, a)/6 + (-a + x)**4*Subs(Derivative(f(y), y, y, y, y), y, a)/24 + (-a + x)**5*Subs(Derivative(f(y), y, y, y, y, y), y, a)/120 + O((-a + x)**6, (x, a))) assert res == ans1 ans2 = f(x).series(x, a) assert res == ans2 def test_issue_7687(): from sympy.core.function import Function from sympy.abc import x f = Function('f')(x) ff = Function('f')(x) match_with_cache = ff.matches(f) assert isinstance(f, type(ff)) clear_cache() ff = Function('f')(x) assert isinstance(f, type(ff)) assert match_with_cache == ff.matches(f) def test_issue_7688(): from sympy.core.function import Function, UndefinedFunction f = Function('f') # actually an UndefinedFunction clear_cache() class A(UndefinedFunction): pass a = A('f') assert isinstance(a, type(f)) def test_mexpand(): from sympy.abc import x assert _mexpand(None) is None assert _mexpand(1) is S.One assert _mexpand(x*(x + 1)**2) == (x*(x + 1)**2).expand() def test_issue_8469(): # This should not take forever to run N = 40 def g(w, theta): return 1/(1+exp(w-theta)) ws = symbols(['w%i'%i for i in range(N)]) import functools expr = functools.reduce(g, ws) assert isinstance(expr, Pow) def test_issue_12996(): # foo=True imitates the sort of arguments that Derivative can get # from Integral when it passes doit to the expression assert Derivative(im(x), x).doit(foo=True) == Derivative(im(x), x) def test_should_evalf(): # This should not take forever to run (see #8506) assert isinstance(sin((1.0 + 1.0*I)**10000 + 1), sin) def test_Derivative_as_finite_difference(): # Central 1st derivative at gridpoint x, h = symbols('x h', real=True) dfdx = f(x).diff(x) assert (dfdx.as_finite_difference([x-2, x-1, x, x+1, x+2]) - (S.One/12*(f(x-2)-f(x+2)) + Rational(2, 3)*(f(x+1)-f(x-1)))).simplify() == 0 # Central 1st derivative "half-way" assert (dfdx.as_finite_difference() - (f(x + S.Half)-f(x - S.Half))).simplify() == 0 assert (dfdx.as_finite_difference(h) - (f(x + h/S(2))-f(x - h/S(2)))/h).simplify() == 0 assert (dfdx.as_finite_difference([x - 3*h, x-h, x+h, x + 3*h]) - (S(9)/(8*2*h)*(f(x+h) - f(x-h)) + S.One/(24*2*h)*(f(x - 3*h) - f(x + 3*h)))).simplify() == 0 # One sided 1st derivative at gridpoint assert (dfdx.as_finite_difference([0, 1, 2], 0) - (Rational(-3, 2)*f(0) + 2*f(1) - f(2)/2)).simplify() == 0 assert (dfdx.as_finite_difference([x, x+h], x) - (f(x+h) - f(x))/h).simplify() == 0 assert (dfdx.as_finite_difference([x-h, x, x+h], x-h) - (-S(3)/(2*h)*f(x-h) + 2/h*f(x) - S.One/(2*h)*f(x+h))).simplify() == 0 # One sided 1st derivative "half-way" assert (dfdx.as_finite_difference([x-h, x+h, x + 3*h, x + 5*h, x + 7*h]) - 1/(2*h)*(-S(11)/(12)*f(x-h) + S(17)/(24)*f(x+h) + Rational(3, 8)*f(x + 3*h) - Rational(5, 24)*f(x + 5*h) + S.One/24*f(x + 7*h))).simplify() == 0 d2fdx2 = f(x).diff(x, 2) # Central 2nd derivative at gridpoint assert (d2fdx2.as_finite_difference([x-h, x, x+h]) - h**-2 * (f(x-h) + f(x+h) - 2*f(x))).simplify() == 0 assert (d2fdx2.as_finite_difference([x - 2*h, x-h, x, x+h, x + 2*h]) - h**-2 * (Rational(-1, 12)*(f(x - 2*h) + f(x + 2*h)) + Rational(4, 3)*(f(x+h) + f(x-h)) - Rational(5, 2)*f(x))).simplify() == 0 # Central 2nd derivative "half-way" assert (d2fdx2.as_finite_difference([x - 3*h, x-h, x+h, x + 3*h]) - (2*h)**-2 * (S.Half*(f(x - 3*h) + f(x + 3*h)) - S.Half*(f(x+h) + f(x-h)))).simplify() == 0 # One sided 2nd derivative at gridpoint assert (d2fdx2.as_finite_difference([x, x+h, x + 2*h, x + 3*h]) - h**-2 * (2*f(x) - 5*f(x+h) + 4*f(x+2*h) - f(x+3*h))).simplify() == 0 # One sided 2nd derivative at "half-way" assert (d2fdx2.as_finite_difference([x-h, x+h, x + 3*h, x + 5*h]) - (2*h)**-2 * (Rational(3, 2)*f(x-h) - Rational(7, 2)*f(x+h) + Rational(5, 2)*f(x + 3*h) - S.Half*f(x + 5*h))).simplify() == 0 d3fdx3 = f(x).diff(x, 3) # Central 3rd derivative at gridpoint assert (d3fdx3.as_finite_difference() - (-f(x - Rational(3, 2)) + 3*f(x - S.Half) - 3*f(x + S.Half) + f(x + Rational(3, 2)))).simplify() == 0 assert (d3fdx3.as_finite_difference( [x - 3*h, x - 2*h, x-h, x, x+h, x + 2*h, x + 3*h]) - h**-3 * (S.One/8*(f(x - 3*h) - f(x + 3*h)) - f(x - 2*h) + f(x + 2*h) + Rational(13, 8)*(f(x-h) - f(x+h)))).simplify() == 0 # Central 3rd derivative at "half-way" assert (d3fdx3.as_finite_difference([x - 3*h, x-h, x+h, x + 3*h]) - (2*h)**-3 * (f(x + 3*h)-f(x - 3*h) + 3*(f(x-h)-f(x+h)))).simplify() == 0 # One sided 3rd derivative at gridpoint assert (d3fdx3.as_finite_difference([x, x+h, x + 2*h, x + 3*h]) - h**-3 * (f(x + 3*h)-f(x) + 3*(f(x+h)-f(x + 2*h)))).simplify() == 0 # One sided 3rd derivative at "half-way" assert (d3fdx3.as_finite_difference([x-h, x+h, x + 3*h, x + 5*h]) - (2*h)**-3 * (f(x + 5*h)-f(x-h) + 3*(f(x+h)-f(x + 3*h)))).simplify() == 0 # issue 11007 y = Symbol('y', real=True) d2fdxdy = f(x, y).diff(x, y) ref0 = Derivative(f(x + S.Half, y), y) - Derivative(f(x - S.Half, y), y) assert (d2fdxdy.as_finite_difference(wrt=x) - ref0).simplify() == 0 half = S.Half xm, xp, ym, yp = x-half, x+half, y-half, y+half ref2 = f(xm, ym) + f(xp, yp) - f(xp, ym) - f(xm, yp) assert (d2fdxdy.as_finite_difference() - ref2).simplify() == 0 def test_issue_11159(): # Tests Application._eval_subs with _exp_is_pow(False): expr1 = E expr0 = expr1 * expr1 expr1 = expr0.subs(expr1,expr0) assert expr0 == expr1 with _exp_is_pow(True): expr1 = E expr0 = expr1 * expr1 expr2 = expr0.subs(expr1, expr0) assert expr2 == E ** 4 def test_issue_12005(): e1 = Subs(Derivative(f(x), x), x, x) assert e1.diff(x) == Derivative(f(x), x, x) e2 = Subs(Derivative(f(x), x), x, x**2 + 1) assert e2.diff(x) == 2*x*Subs(Derivative(f(x), x, x), x, x**2 + 1) e3 = Subs(Derivative(f(x) + y**2 - y, y), y, y**2) assert e3.diff(y) == 4*y e4 = Subs(Derivative(f(x + y), y), y, (x**2)) assert e4.diff(y) is S.Zero e5 = Subs(Derivative(f(x), x), (y, z), (y, z)) assert e5.diff(x) == Derivative(f(x), x, x) assert f(g(x)).diff(g(x), g(x)) == Derivative(f(g(x)), g(x), g(x)) def test_issue_13843(): x = symbols('x') f = Function('f') m, n = symbols('m n', integer=True) assert Derivative(Derivative(f(x), (x, m)), (x, n)) == Derivative(f(x), (x, m + n)) assert Derivative(Derivative(f(x), (x, m+5)), (x, n+3)) == Derivative(f(x), (x, m + n + 8)) assert Derivative(f(x), (x, n)).doit() == Derivative(f(x), (x, n)) def test_order_could_be_zero(): x, y = symbols('x, y') n = symbols('n', integer=True, nonnegative=True) m = symbols('m', integer=True, positive=True) assert diff(y, (x, n)) == Piecewise((y, Eq(n, 0)), (0, True)) assert diff(y, (x, n + 1)) is S.Zero assert diff(y, (x, m)) is S.Zero def test_undefined_function_eq(): f = Function('f') f2 = Function('f') g = Function('g') f_real = Function('f', is_real=True) # This test may only be meaningful if the cache is turned off assert f == f2 assert hash(f) == hash(f2) assert f == f assert f != g assert f != f_real def test_function_assumptions(): x = Symbol('x') f = Function('f') f_real = Function('f', real=True) f_real1 = Function('f', real=1) f_real_inherit = Function(Symbol('f', real=True)) assert f_real == f_real1 # assumptions are sanitized assert f != f_real assert f(x) != f_real(x) assert f(x).is_real is None assert f_real(x).is_real is True assert f_real_inherit(x).is_real is True and f_real_inherit.name == 'f' # Can also do it this way, but it won't be equal to f_real because of the # way UndefinedFunction.__new__ works. Any non-recognized assumptions # are just added literally as something which is used in the hash f_real2 = Function('f', is_real=True) assert f_real2(x).is_real is True def test_undef_fcn_float_issue_6938(): f = Function('ceil') assert not f(0.3).is_number f = Function('sin') assert not f(0.3).is_number assert not f(pi).evalf().is_number x = Symbol('x') assert not f(x).evalf(subs={x:1.2}).is_number def test_undefined_function_eval(): # Issue 15170. Make sure UndefinedFunction with eval defined works # properly. The issue there was that the hash was determined before _nargs # was set, which is included in the hash, hence changing the hash. The # class is added to sympy.core.core.all_classes before the hash is # changed, meaning "temp in all_classes" would fail, causing sympify(temp(t)) # to give a new class. We will eventually remove all_classes, but make # sure this continues to work. fdiff = lambda self, argindex=1: cos(self.args[argindex - 1]) eval = classmethod(lambda cls, t: None) _imp_ = classmethod(lambda cls, t: sin(t)) temp = Function('temp', fdiff=fdiff, eval=eval, _imp_=_imp_) expr = temp(t) assert sympify(expr) == expr assert type(sympify(expr)).fdiff.__name__ == "<lambda>" assert expr.diff(t) == cos(t) def test_issue_15241(): F = f(x) Fx = F.diff(x) assert (F + x*Fx).diff(x, Fx) == 2 assert (F + x*Fx).diff(Fx, x) == 1 assert (x*F + x*Fx*F).diff(F, x) == x*Fx.diff(x) + Fx + 1 assert (x*F + x*Fx*F).diff(x, F) == x*Fx.diff(x) + Fx + 1 y = f(x) G = f(y) Gy = G.diff(y) assert (G + y*Gy).diff(y, Gy) == 2 assert (G + y*Gy).diff(Gy, y) == 1 assert (y*G + y*Gy*G).diff(G, y) == y*Gy.diff(y) + Gy + 1 assert (y*G + y*Gy*G).diff(y, G) == y*Gy.diff(y) + Gy + 1 def test_issue_15226(): assert Subs(Derivative(f(y), x, y), y, g(x)).doit() != 0 def test_issue_7027(): for wrt in (cos(x), re(x), Derivative(cos(x), x)): raises(ValueError, lambda: diff(f(x), wrt)) def test_derivative_quick_exit(): assert f(x).diff(y) == 0 assert f(x).diff(y, f(x)) == 0 assert f(x).diff(x, f(y)) == 0 assert f(f(x)).diff(x, f(x), f(y)) == 0 assert f(f(x)).diff(x, f(x), y) == 0 assert f(x).diff(g(x)) == 0 assert f(x).diff(x, f(x).diff(x)) == 1 df = f(x).diff(x) assert f(x).diff(df) == 0 dg = g(x).diff(x) assert dg.diff(df).doit() == 0 def test_issue_15084_13166(): eq = f(x, g(x)) assert eq.diff((g(x), y)) == Derivative(f(x, g(x)), (g(x), y)) # issue 13166 assert eq.diff(x, 2).doit() == ( (Derivative(f(x, g(x)), (g(x), 2))*Derivative(g(x), x) + Subs(Derivative(f(x, _xi_2), _xi_2, x), _xi_2, g(x)))*Derivative(g(x), x) + Derivative(f(x, g(x)), g(x))*Derivative(g(x), (x, 2)) + Derivative(g(x), x)*Subs(Derivative(f(_xi_1, g(x)), _xi_1, g(x)), _xi_1, x) + Subs(Derivative(f(_xi_1, g(x)), (_xi_1, 2)), _xi_1, x)) # issue 6681 assert diff(f(x, t, g(x, t)), x).doit() == ( Derivative(f(x, t, g(x, t)), g(x, t))*Derivative(g(x, t), x) + Subs(Derivative(f(_xi_1, t, g(x, t)), _xi_1), _xi_1, x)) # make sure the order doesn't matter when using diff assert eq.diff(x, g(x)) == eq.diff(g(x), x) def test_negative_counts(): # issue 13873 raises(ValueError, lambda: sin(x).diff(x, -1)) def test_Derivative__new__(): raises(TypeError, lambda: f(x).diff((x, 2), 0)) assert f(x, y).diff([(x, y), 0]) == f(x, y) assert f(x, y).diff([(x, y), 1]) == NDimArray([ Derivative(f(x, y), x), Derivative(f(x, y), y)]) assert f(x,y).diff(y, (x, z), y, x) == Derivative( f(x, y), (x, z + 1), (y, 2)) assert Matrix([x]).diff(x, 2) == Matrix([0]) # is_zero exit def test_issue_14719_10150(): class V(Expr): _diff_wrt = True is_scalar = False assert V().diff(V()) == Derivative(V(), V()) assert (2*V()).diff(V()) == 2*Derivative(V(), V()) class X(Expr): _diff_wrt = True assert X().diff(X()) == 1 assert (2*X()).diff(X()) == 2 def test_noncommutative_issue_15131(): x = Symbol('x', commutative=False) t = Symbol('t', commutative=False) fx = Function('Fx', commutative=False)(x) ft = Function('Ft', commutative=False)(t) A = Symbol('A', commutative=False) eq = fx * A * ft eqdt = eq.diff(t) assert eqdt.args[-1] == ft.diff(t) def test_Subs_Derivative(): a = Derivative(f(g(x), h(x)), g(x), h(x),x) b = Derivative(Derivative(f(g(x), h(x)), g(x), h(x)),x) c = f(g(x), h(x)).diff(g(x), h(x), x) d = f(g(x), h(x)).diff(g(x), h(x)).diff(x) e = Derivative(f(g(x), h(x)), x) eqs = (a, b, c, d, e) subs = lambda arg: arg.subs(f, Lambda((x, y), exp(x + y)) ).subs(g(x), 1/x).subs(h(x), x**3) ans = 3*x**2*exp(1/x)*exp(x**3) - exp(1/x)*exp(x**3)/x**2 assert all(subs(i).doit().expand() == ans for i in eqs) assert all(subs(i.doit()).doit().expand() == ans for i in eqs) def test_issue_15360(): f = Function('f') assert f.name == 'f' def test_issue_15947(): assert f._diff_wrt is False raises(TypeError, lambda: f(f)) raises(TypeError, lambda: f(x).diff(f)) def test_Derivative_free_symbols(): f = Function('f') n = Symbol('n', integer=True, positive=True) assert diff(f(x), (x, n)).free_symbols == {n, x} def test_issue_20683(): x = Symbol('x') y = Symbol('y') z = Symbol('z') y = Derivative(z, x).subs(x,0) assert y.doit() == 0 y = Derivative(8, x).subs(x,0) assert y.doit() == 0 def test_issue_10503(): f = exp(x**3)*cos(x**6) assert f.series(x, 0, 14) == 1 + x**3 + x**6/2 + x**9/6 - 11*x**12/24 + O(x**14) def test_issue_17382(): # copied from sympy/core/tests/test_evalf.py def NS(e, n=15, **options): return sstr(sympify(e).evalf(n, **options), full_prec=True) x = Symbol('x') expr = solveset(2 * cos(x) * cos(2 * x) - 1, x, S.Reals) expected = "Union(" \ "ImageSet(Lambda(_n, 6.28318530717959*_n + 5.79812359592087), Integers), " \ "ImageSet(Lambda(_n, 6.28318530717959*_n + 0.485061711258717), Integers))" assert NS(expr) == expected
83431f314c334e0e96799de30ee147e4315094a5e3c2e5774137db53e0ed5956
"""This tests sympy/core/basic.py with (ideally) no reference to subclasses of Basic or Atom.""" import collections from sympy.assumptions.ask import Q from sympy.core.basic import (Basic, Atom, as_Basic, _atomic, _aresame) from sympy.core.containers import Tuple from sympy.core.function import Function, Lambda from sympy.core.numbers import I, pi from sympy.core.singleton import S from sympy.core.symbol import symbols, Symbol, Dummy from sympy.concrete.summations import Sum from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.gamma_functions import gamma from sympy.integrals.integrals import Integral from sympy.functions.elementary.exponential import exp from sympy.testing.pytest import raises b1 = Basic() b2 = Basic(b1) b3 = Basic(b2) b21 = Basic(b2, b1) def test__aresame(): assert not _aresame(Basic(Tuple()), Basic()) assert not _aresame(Basic(S(2)), Basic(S(2.))) def test_structure(): assert b21.args == (b2, b1) assert b21.func(*b21.args) == b21 assert bool(b1) def test_immutable(): assert not hasattr(b1, '__dict__') with raises(AttributeError): b1.x = 1 def test_equality(): instances = [b1, b2, b3, b21, Basic(b1, b1, b1), Basic] for i, b_i in enumerate(instances): for j, b_j in enumerate(instances): assert (b_i == b_j) == (i == j) assert (b_i != b_j) == (i != j) assert Basic() != [] assert not(Basic() == []) assert Basic() != 0 assert not(Basic() == 0) class Foo: """ Class that is unaware of Basic, and relies on both classes returning the NotImplemented singleton for equivalence to evaluate to False. """ b = Basic() foo = Foo() assert b != foo assert foo != b assert not b == foo assert not foo == b class Bar: """ Class that considers itself equal to any instance of Basic, and relies on Basic returning the NotImplemented singleton in order to achieve a symmetric equivalence relation. """ def __eq__(self, other): if isinstance(other, Basic): return True return NotImplemented def __ne__(self, other): return not self == other bar = Bar() assert b == bar assert bar == b assert not b != bar assert not bar != b def test_matches_basic(): instances = [Basic(b1, b1, b2), Basic(b1, b2, b1), Basic(b2, b1, b1), Basic(b1, b2), Basic(b2, b1), b2, b1] for i, b_i in enumerate(instances): for j, b_j in enumerate(instances): if i == j: assert b_i.matches(b_j) == {} else: assert b_i.matches(b_j) is None assert b1.match(b1) == {} def test_has(): assert b21.has(b1) assert b21.has(b3, b1) assert b21.has(Basic) assert not b1.has(b21, b3) assert not b21.has() assert not b21.has(str) assert not Symbol("x").has("x") def test_subs(): assert b21.subs(b2, b1) == Basic(b1, b1) assert b21.subs(b2, b21) == Basic(b21, b1) assert b3.subs(b2, b1) == b2 assert b21.subs([(b2, b1), (b1, b2)]) == Basic(b2, b2) assert b21.subs({b1: b2, b2: b1}) == Basic(b2, b2) assert b21.subs(collections.ChainMap({b1: b2}, {b2: b1})) == Basic(b2, b2) assert b21.subs(collections.OrderedDict([(b2, b1), (b1, b2)])) == Basic(b2, b2) raises(ValueError, lambda: b21.subs('bad arg')) raises(ValueError, lambda: b21.subs(b1, b2, b3)) # dict(b1=foo) creates a string 'b1' but leaves foo unchanged; subs # will convert the first to a symbol but will raise an error if foo # cannot be sympified; sympification is strict if foo is not string raises(ValueError, lambda: b21.subs(b1='bad arg')) assert Symbol("text").subs({"text": b1}) == b1 assert Symbol("s").subs({"s": 1}) == 1 def test_subs_with_unicode_symbols(): expr = Symbol('var1') replaced = expr.subs('var1', 'x') assert replaced.name == 'x' replaced = expr.subs('var1', 'x') assert replaced.name == 'x' def test_atoms(): assert b21.atoms() == {Basic()} def test_free_symbols_empty(): assert b21.free_symbols == set() def test_doit(): assert b21.doit() == b21 assert b21.doit(deep=False) == b21 def test_S(): assert repr(S) == 'S' def test_xreplace(): assert b21.xreplace({b2: b1}) == Basic(b1, b1) assert b21.xreplace({b2: b21}) == Basic(b21, b1) assert b3.xreplace({b2: b1}) == b2 assert Basic(b1, b2).xreplace({b1: b2, b2: b1}) == Basic(b2, b1) assert Atom(b1).xreplace({b1: b2}) == Atom(b1) assert Atom(b1).xreplace({Atom(b1): b2}) == b2 raises(TypeError, lambda: b1.xreplace()) raises(TypeError, lambda: b1.xreplace([b1, b2])) for f in (exp, Function('f')): assert f.xreplace({}) == f assert f.xreplace({}, hack2=True) == f assert f.xreplace({f: b1}) == b1 assert f.xreplace({f: b1}, hack2=True) == b1 def test_sorted_args(): x = symbols('x') assert b21._sorted_args == b21.args raises(AttributeError, lambda: x._sorted_args) def test_call(): x, y = symbols('x y') # See the long history of this in issues 5026 and 5105. raises(TypeError, lambda: sin(x)({ x : 1, sin(x) : 2})) raises(TypeError, lambda: sin(x)(1)) # No effect as there are no callables assert sin(x).rcall(1) == sin(x) assert (1 + sin(x)).rcall(1) == 1 + sin(x) # Effect in the pressence of callables l = Lambda(x, 2*x) assert (l + x).rcall(y) == 2*y + x assert (x**l).rcall(2) == x**4 # TODO UndefinedFunction does not subclass Expr #f = Function('f') #assert (2*f)(x) == 2*f(x) assert (Q.real & Q.positive).rcall(x) == Q.real(x) & Q.positive(x) def test_rewrite(): x, y, z = symbols('x y z') a, b = symbols('a b') f1 = sin(x) + cos(x) assert f1.rewrite(cos,exp) == exp(I*x)/2 + sin(x) + exp(-I*x)/2 assert f1.rewrite([cos],sin) == sin(x) + sin(x + pi/2, evaluate=False) f2 = sin(x) + cos(y)/gamma(z) assert f2.rewrite(sin,exp) == -I*(exp(I*x) - exp(-I*x))/2 + cos(y)/gamma(z) assert f1.rewrite() == f1 def test_literal_evalf_is_number_is_zero_is_comparable(): x = symbols('x') f = Function('f') # issue 5033 assert f.is_number is False # issue 6646 assert f(1).is_number is False i = Integral(0, (x, x, x)) # expressions that are symbolically 0 can be difficult to prove # so in case there is some easy way to know if something is 0 # it should appear in the is_zero property for that object; # if is_zero is true evalf should always be able to compute that # zero assert i.n() == 0 assert i.is_zero assert i.is_number is False assert i.evalf(2, strict=False) == 0 # issue 10268 n = sin(1)**2 + cos(1)**2 - 1 assert n.is_comparable is False assert n.n(2).is_comparable is False assert n.n(2).n(2).is_comparable def test_as_Basic(): assert as_Basic(1) is S.One assert as_Basic(()) == Tuple() raises(TypeError, lambda: as_Basic([])) def test_atomic(): g, h = map(Function, 'gh') x = symbols('x') assert _atomic(g(x + h(x))) == {g(x + h(x))} assert _atomic(g(x + h(x)), recursive=True) == {h(x), x, g(x + h(x))} assert _atomic(1) == set() assert _atomic(Basic(S(1), S(2))) == set() def test_as_dummy(): u, v, x, y, z, _0, _1 = symbols('u v x y z _0 _1') assert Lambda(x, x + 1).as_dummy() == Lambda(_0, _0 + 1) assert Lambda(x, x + _0).as_dummy() == Lambda(_1, _0 + _1) eq = (1 + Sum(x, (x, 1, x))) ans = 1 + Sum(_0, (_0, 1, x)) once = eq.as_dummy() assert once == ans twice = once.as_dummy() assert twice == ans assert Integral(x + _0, (x, x + 1), (_0, 1, 2) ).as_dummy() == Integral(_0 + _1, (_0, x + 1), (_1, 1, 2)) for T in (Symbol, Dummy): d = T('x', real=True) D = d.as_dummy() assert D != d and D.func == Dummy and D.is_real is None assert Dummy().as_dummy().is_commutative assert Dummy(commutative=False).as_dummy().is_commutative is False def test_canonical_variables(): x, i0, i1 = symbols('x _:2') assert Integral(x, (x, x + 1)).canonical_variables == {x: i0} assert Integral(x, (x, x + 1), (i0, 1, 2)).canonical_variables == { x: i0, i0: i1} assert Integral(x, (x, x + i0)).canonical_variables == {x: i1} def test_replace_exceptions(): from sympy.core.symbol import Wild x, y = symbols('x y') e = (x**2 + x*y) raises(TypeError, lambda: e.replace(sin, 2)) b = Wild('b') c = Wild('c') raises(TypeError, lambda: e.replace(b*c, c.is_real)) raises(TypeError, lambda: e.replace(b.is_real, 1)) raises(TypeError, lambda: e.replace(lambda d: d.is_Number, 1))
81a26d2c795b12264ab51299e01a43a7b0392d1a55a86d724b65a5a493684b13
from sympy.core.mul import Mul from sympy.core.numbers import (I, Rational as R, pi) from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.series.order import O from sympy.simplify.radsimp import expand_numer from sympy.core.function import expand, expand_multinomial, expand_power_base from sympy.testing.pytest import raises from sympy.core.random import verify_numerically from sympy.abc import x, y, z def test_expand_no_log(): assert ( (1 + log(x**4))**2).expand(log=False) == 1 + 2*log(x**4) + log(x**4)**2 assert ((1 + log(x**4))*(1 + log(x**3))).expand( log=False) == 1 + log(x**4) + log(x**3) + log(x**4)*log(x**3) def test_expand_no_multinomial(): assert ((1 + x)*(1 + (1 + x)**4)).expand(multinomial=False) == \ 1 + x + (1 + x)**4 + x*(1 + x)**4 def test_expand_negative_integer_powers(): expr = (x + y)**(-2) assert expr.expand() == 1 / (2*x*y + x**2 + y**2) assert expr.expand(multinomial=False) == (x + y)**(-2) expr = (x + y)**(-3) assert expr.expand() == 1 / (3*x*x*y + 3*x*y*y + x**3 + y**3) assert expr.expand(multinomial=False) == (x + y)**(-3) expr = (x + y)**(2) * (x + y)**(-4) assert expr.expand() == 1 / (2*x*y + x**2 + y**2) assert expr.expand(multinomial=False) == (x + y)**(-2) def test_expand_non_commutative(): A = Symbol('A', commutative=False) B = Symbol('B', commutative=False) C = Symbol('C', commutative=False) a = Symbol('a') b = Symbol('b') i = Symbol('i', integer=True) n = Symbol('n', negative=True) m = Symbol('m', negative=True) p = Symbol('p', polar=True) np = Symbol('p', polar=False) assert (C*(A + B)).expand() == C*A + C*B assert (C*(A + B)).expand() != A*C + B*C assert ((A + B)**2).expand() == A**2 + A*B + B*A + B**2 assert ((A + B)**3).expand() == (A**2*B + B**2*A + A*B**2 + B*A**2 + A**3 + B**3 + A*B*A + B*A*B) # issue 6219 assert ((a*A*B*A**-1)**2).expand() == a**2*A*B**2/A # Note that (a*A*B*A**-1)**2 is automatically converted to a**2*(A*B*A**-1)**2 assert ((a*A*B*A**-1)**2).expand(deep=False) == a**2*(A*B*A**-1)**2 assert ((a*A*B*A**-1)**2).expand() == a**2*(A*B**2*A**-1) assert ((a*A*B*A**-1)**2).expand(force=True) == a**2*A*B**2*A**(-1) assert ((a*A*B)**2).expand() == a**2*A*B*A*B assert ((a*A)**2).expand() == a**2*A**2 assert ((a*A*B)**i).expand() == a**i*(A*B)**i assert ((a*A*(B*(A*B/A)**2))**i).expand() == a**i*(A*B*A*B**2/A)**i # issue 6558 assert (A*B*(A*B)**-1).expand() == 1 assert ((a*A)**i).expand() == a**i*A**i assert ((a*A*B*A**-1)**3).expand() == a**3*A*B**3/A assert ((a*A*B*A*B/A)**3).expand() == \ a**3*A*B*(A*B**2)*(A*B**2)*A*B*A**(-1) assert ((a*A*B*A*B/A)**-2).expand() == \ A*B**-1*A**-1*B**-2*A**-1*B**-1*A**-1/a**2 assert ((a*b*A*B*A**-1)**i).expand() == a**i*b**i*(A*B/A)**i assert ((a*(a*b)**i)**i).expand() == a**i*a**(i**2)*b**(i**2) e = Pow(Mul(a, 1/a, A, B, evaluate=False), S(2), evaluate=False) assert e.expand() == A*B*A*B assert sqrt(a*(A*b)**i).expand() == sqrt(a*b**i*A**i) assert (sqrt(-a)**a).expand() == sqrt(-a)**a assert expand((-2*n)**(i/3)) == 2**(i/3)*(-n)**(i/3) assert expand((-2*n*m)**(i/a)) == (-2)**(i/a)*(-n)**(i/a)*(-m)**(i/a) assert expand((-2*a*p)**b) == 2**b*p**b*(-a)**b assert expand((-2*a*np)**b) == 2**b*(-a*np)**b assert expand(sqrt(A*B)) == sqrt(A*B) assert expand(sqrt(-2*a*b)) == sqrt(2)*sqrt(-a*b) def test_expand_radicals(): a = (x + y)**R(1, 2) assert (a**1).expand() == a assert (a**3).expand() == x*a + y*a assert (a**5).expand() == x**2*a + 2*x*y*a + y**2*a assert (1/a**1).expand() == 1/a assert (1/a**3).expand() == 1/(x*a + y*a) assert (1/a**5).expand() == 1/(x**2*a + 2*x*y*a + y**2*a) a = (x + y)**R(1, 3) assert (a**1).expand() == a assert (a**2).expand() == a**2 assert (a**4).expand() == x*a + y*a assert (a**5).expand() == x*a**2 + y*a**2 assert (a**7).expand() == x**2*a + 2*x*y*a + y**2*a def test_expand_modulus(): assert ((x + y)**11).expand(modulus=11) == x**11 + y**11 assert ((x + sqrt(2)*y)**11).expand(modulus=11) == x**11 + 10*sqrt(2)*y**11 assert (x + y/2).expand(modulus=1) == y/2 raises(ValueError, lambda: ((x + y)**11).expand(modulus=0)) raises(ValueError, lambda: ((x + y)**11).expand(modulus=x)) def test_issue_5743(): assert (x*sqrt( x + y)*(1 + sqrt(x + y))).expand() == x**2 + x*y + x*sqrt(x + y) assert (x*sqrt( x + y)*(1 + x*sqrt(x + y))).expand() == x**3 + x**2*y + x*sqrt(x + y) def test_expand_frac(): assert expand((x + y)*y/x/(x + 1), frac=True) == \ (x*y + y**2)/(x**2 + x) assert expand((x + y)*y/x/(x + 1), numer=True) == \ (x*y + y**2)/(x*(x + 1)) assert expand((x + y)*y/x/(x + 1), denom=True) == \ y*(x + y)/(x**2 + x) eq = (x + 1)**2/y assert expand_numer(eq, multinomial=False) == eq def test_issue_6121(): eq = -I*exp(-3*I*pi/4)/(4*pi**(S(3)/2)*sqrt(x)) assert eq.expand(complex=True) # does not give oo recursion eq = -I*exp(-3*I*pi/4)/(4*pi**(R(3, 2))*sqrt(x)) assert eq.expand(complex=True) # does not give oo recursion def test_expand_power_base(): assert expand_power_base((x*y*z)**4) == x**4*y**4*z**4 assert expand_power_base((x*y*z)**x).is_Pow assert expand_power_base((x*y*z)**x, force=True) == x**x*y**x*z**x assert expand_power_base((x*(y*z)**2)**3) == x**3*y**6*z**6 assert expand_power_base((sin((x*y)**2)*y)**z).is_Pow assert expand_power_base( (sin((x*y)**2)*y)**z, force=True) == sin((x*y)**2)**z*y**z assert expand_power_base( (sin((x*y)**2)*y)**z, deep=True) == (sin(x**2*y**2)*y)**z assert expand_power_base(exp(x)**2) == exp(2*x) assert expand_power_base((exp(x)*exp(y))**2) == exp(2*x)*exp(2*y) assert expand_power_base( (exp((x*y)**z)*exp(y))**2) == exp(2*(x*y)**z)*exp(2*y) assert expand_power_base((exp((x*y)**z)*exp( y))**2, deep=True, force=True) == exp(2*x**z*y**z)*exp(2*y) assert expand_power_base((exp(x)*exp(y))**z).is_Pow assert expand_power_base( (exp(x)*exp(y))**z, force=True) == exp(x)**z*exp(y)**z def test_expand_arit(): a = Symbol("a") b = Symbol("b", positive=True) c = Symbol("c") p = R(5) e = (a + b)*c assert e == c*(a + b) assert (e.expand() - a*c - b*c) == R(0) e = (a + b)*(a + b) assert e == (a + b)**2 assert e.expand() == 2*a*b + a**2 + b**2 e = (a + b)*(a + b)**R(2) assert e == (a + b)**3 assert e.expand() == 3*b*a**2 + 3*a*b**2 + a**3 + b**3 assert e.expand() == 3*b*a**2 + 3*a*b**2 + a**3 + b**3 e = (a + b)*(a + c)*(b + c) assert e == (a + c)*(a + b)*(b + c) assert e.expand() == 2*a*b*c + b*a**2 + c*a**2 + b*c**2 + a*c**2 + c*b**2 + a*b**2 e = (a + R(1))**p assert e == (1 + a)**5 assert e.expand() == 1 + 5*a + 10*a**2 + 10*a**3 + 5*a**4 + a**5 e = (a + b + c)*(a + c + p) assert e == (5 + a + c)*(a + b + c) assert e.expand() == 5*a + 5*b + 5*c + 2*a*c + b*c + a*b + a**2 + c**2 x = Symbol("x") s = exp(x*x) - 1 e = s.nseries(x, 0, 6)/x**2 assert e.expand() == 1 + x**2/2 + O(x**4) e = (x*(y + z))**(x*(y + z))*(x + y) assert e.expand(power_exp=False, power_base=False) == x*(x*y + x* z)**(x*y + x*z) + y*(x*y + x*z)**(x*y + x*z) assert e.expand(power_exp=False, power_base=False, deep=False) == x* \ (x*(y + z))**(x*(y + z)) + y*(x*(y + z))**(x*(y + z)) e = x * (x + (y + 1)**2) assert e.expand(deep=False) == x**2 + x*(y + 1)**2 e = (x*(y + z))**z assert e.expand(power_base=True, mul=True, deep=True) in [x**z*(y + z)**z, (x*y + x*z)**z] assert ((2*y)**z).expand() == 2**z*y**z p = Symbol('p', positive=True) assert sqrt(-x).expand().is_Pow assert sqrt(-x).expand(force=True) == I*sqrt(x) assert ((2*y*p)**z).expand() == 2**z*p**z*y**z assert ((2*y*p*x)**z).expand() == 2**z*p**z*(x*y)**z assert ((2*y*p*x)**z).expand(force=True) == 2**z*p**z*x**z*y**z assert ((2*y*p*-pi)**z).expand() == 2**z*pi**z*p**z*(-y)**z assert ((2*y*p*-pi*x)**z).expand() == 2**z*pi**z*p**z*(-x*y)**z n = Symbol('n', negative=True) m = Symbol('m', negative=True) assert ((-2*x*y*n)**z).expand() == 2**z*(-n)**z*(x*y)**z assert ((-2*x*y*n*m)**z).expand() == 2**z*(-m)**z*(-n)**z*(-x*y)**z # issue 5482 assert sqrt(-2*x*n) == sqrt(2)*sqrt(-n)*sqrt(x) # issue 5605 (2) assert (cos(x + y)**2).expand(trig=True) in [ (-sin(x)*sin(y) + cos(x)*cos(y))**2, sin(x)**2*sin(y)**2 - 2*sin(x)*sin(y)*cos(x)*cos(y) + cos(x)**2*cos(y)**2 ] # Check that this isn't too slow x = Symbol('x') W = 1 for i in range(1, 21): W = W * (x - i) W = W.expand() assert W.has(-1672280820*x**15) def test_expand_mul(): # part of issue 20597 e = Mul(2, 3, evaluate=False) assert e.expand() == 6 e = Mul(2, 3, 1/x, evaluate = False) assert e.expand() == 6/x e = Mul(2, R(1, 3), evaluate=False) assert e.expand() == R(2, 3) def test_power_expand(): """Test for Pow.expand()""" a = Symbol('a') b = Symbol('b') p = (a + b)**2 assert p.expand() == a**2 + b**2 + 2*a*b p = (1 + 2*(1 + a))**2 assert p.expand() == 9 + 4*(a**2) + 12*a p = 2**(a + b) assert p.expand() == 2**a*2**b A = Symbol('A', commutative=False) B = Symbol('B', commutative=False) assert (2**(A + B)).expand() == 2**(A + B) assert (A**(a + b)).expand() != A**(a + b) def test_issues_5919_6830(): # issue 5919 n = -1 + 1/x z = n/x/(-n)**2 - 1/n/x assert expand(z) == 1/(x**2 - 2*x + 1) - 1/(x - 2 + 1/x) - 1/(-x + 1) # issue 6830 p = (1 + x)**2 assert expand_multinomial((1 + x*p)**2) == ( x**2*(x**4 + 4*x**3 + 6*x**2 + 4*x + 1) + 2*x*(x**2 + 2*x + 1) + 1) assert expand_multinomial((1 + (y + x)*p)**2) == ( 2*((x + y)*(x**2 + 2*x + 1)) + (x**2 + 2*x*y + y**2)* (x**4 + 4*x**3 + 6*x**2 + 4*x + 1) + 1) A = Symbol('A', commutative=False) p = (1 + A)**2 assert expand_multinomial((1 + x*p)**2) == ( x**2*(1 + 4*A + 6*A**2 + 4*A**3 + A**4) + 2*x*(1 + 2*A + A**2) + 1) assert expand_multinomial((1 + (y + x)*p)**2) == ( (x + y)*(1 + 2*A + A**2)*2 + (x**2 + 2*x*y + y**2)* (1 + 4*A + 6*A**2 + 4*A**3 + A**4) + 1) assert expand_multinomial((1 + (y + x)*p)**3) == ( (x + y)*(1 + 2*A + A**2)*3 + (x**2 + 2*x*y + y**2)*(1 + 4*A + 6*A**2 + 4*A**3 + A**4)*3 + (x**3 + 3*x**2*y + 3*x*y**2 + y**3)*(1 + 6*A + 15*A**2 + 20*A**3 + 15*A**4 + 6*A**5 + A**6) + 1) # unevaluate powers eq = (Pow((x + 1)*((A + 1)**2), 2, evaluate=False)) # - in this case the base is not an Add so no further # expansion is done assert expand_multinomial(eq) == \ (x**2 + 2*x + 1)*(1 + 4*A + 6*A**2 + 4*A**3 + A**4) # - but here, the expanded base *is* an Add so it gets expanded eq = (Pow(((A + 1)**2), 2, evaluate=False)) assert expand_multinomial(eq) == 1 + 4*A + 6*A**2 + 4*A**3 + A**4 # coverage def ok(a, b, n): e = (a + I*b)**n return verify_numerically(e, expand_multinomial(e)) for a in [2, S.Half]: for b in [3, R(1, 3)]: for n in range(2, 6): assert ok(a, b, n) assert expand_multinomial((x + 1 + O(z))**2) == \ 1 + 2*x + x**2 + O(z) assert expand_multinomial((x + 1 + O(z))**3) == \ 1 + 3*x + 3*x**2 + x**3 + O(z) assert expand_multinomial(3**(x + y + 3)) == 27*3**(x + y) def test_expand_log(): t = Symbol('t', positive=True) # after first expansion, -2*log(2) + log(4); then 0 after second assert expand(log(t**2) - log(t**2/4) - 2*log(2)) == 0
a141a3df0c93963f68670efa8be028de79b28fc1017dd1fe22877e70df368752
import random from sympy.core.symbol import Symbol, symbols from sympy.functions.elementary.trigonometric import sin, acos from sympy.abc import x def test_random(): random.seed(42) a = random.random() random.seed(42) Symbol('z').is_finite b = random.random() assert a == b got = set() for i in range(2): random.seed(28) m0, m1 = symbols('m_0 m_1', real=True) _ = acos(-m0/m1) got.add(random.uniform(0,1)) assert len(got) == 1 random.seed(10) y = 0 for i in range(4): y += sin(random.uniform(-10,10) * x) random.seed(10) z = 0 for i in range(4): z += sin(random.uniform(-10,10) * x) assert y == z
4c8d7ada63205b1f24a788a5567c52161eed196fc9c4f28c13c9a01a51109243
"""Tests for tools for manipulating of large commutative expressions. """ from sympy.concrete.summations import Sum from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.containers import (Dict, Tuple) from sympy.core.function import Function from sympy.core.mul import Mul from sympy.core.numbers import (I, Rational, oo) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, symbols) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import (root, sqrt) from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.integrals.integrals import Integral from sympy.series.order import O from sympy.sets.sets import Interval from sympy.simplify.radsimp import collect from sympy.simplify.simplify import simplify from sympy.core.exprtools import (decompose_power, Factors, Term, _gcd_terms, gcd_terms, factor_terms, factor_nc, _mask_nc, _monotonic_sign) from sympy.core.mul import _keep_coeff as _keep_coeff from sympy.simplify.cse_opts import sub_pre from sympy.testing.pytest import raises from sympy.abc import a, b, t, x, y, z def test_decompose_power(): assert decompose_power(x) == (x, 1) assert decompose_power(x**2) == (x, 2) assert decompose_power(x**(2*y)) == (x**y, 2) assert decompose_power(x**(2*y/3)) == (x**(y/3), 2) assert decompose_power(x**(y*Rational(2, 3))) == (x**(y/3), 2) def test_Factors(): assert Factors() == Factors({}) == Factors(S.One) assert Factors().as_expr() is S.One assert Factors({x: 2, y: 3, sin(x): 4}).as_expr() == x**2*y**3*sin(x)**4 assert Factors(S.Infinity) == Factors({oo: 1}) assert Factors(S.NegativeInfinity) == Factors({oo: 1, -1: 1}) # issue #18059: assert Factors((x**2)**S.Half).as_expr() == (x**2)**S.Half a = Factors({x: 5, y: 3, z: 7}) b = Factors({ y: 4, z: 3, t: 10}) assert a.mul(b) == a*b == Factors({x: 5, y: 7, z: 10, t: 10}) assert a.div(b) == divmod(a, b) == \ (Factors({x: 5, z: 4}), Factors({y: 1, t: 10})) assert a.quo(b) == a/b == Factors({x: 5, z: 4}) assert a.rem(b) == a % b == Factors({y: 1, t: 10}) assert a.pow(3) == a**3 == Factors({x: 15, y: 9, z: 21}) assert b.pow(3) == b**3 == Factors({y: 12, z: 9, t: 30}) assert a.gcd(b) == Factors({y: 3, z: 3}) assert a.lcm(b) == Factors({x: 5, y: 4, z: 7, t: 10}) a = Factors({x: 4, y: 7, t: 7}) b = Factors({z: 1, t: 3}) assert a.normal(b) == (Factors({x: 4, y: 7, t: 4}), Factors({z: 1})) assert Factors(sqrt(2)*x).as_expr() == sqrt(2)*x assert Factors(-I)*I == Factors() assert Factors({S.NegativeOne: S(3)})*Factors({S.NegativeOne: S.One, I: S(5)}) == \ Factors(I) assert Factors(sqrt(I)*I) == Factors(I**(S(3)/2)) == Factors({I: S(3)/2}) assert Factors({I: S(3)/2}).as_expr() == I**(S(3)/2) assert Factors(S(2)**x).div(S(3)**x) == \ (Factors({S(2): x}), Factors({S(3): x})) assert Factors(2**(2*x + 2)).div(S(8)) == \ (Factors({S(2): 2*x + 2}), Factors({S(8): S.One})) # coverage # /!\ things break if this is not True assert Factors({S.NegativeOne: Rational(3, 2)}) == Factors({I: S.One, S.NegativeOne: S.One}) assert Factors({I: S.One, S.NegativeOne: Rational(1, 3)}).as_expr() == I*(-1)**Rational(1, 3) assert Factors(-1.) == Factors({S.NegativeOne: S.One, S(1.): 1}) assert Factors(-2.) == Factors({S.NegativeOne: S.One, S(2.): 1}) assert Factors((-2.)**x) == Factors({S(-2.): x}) assert Factors(S(-2)) == Factors({S.NegativeOne: S.One, S(2): 1}) assert Factors(S.Half) == Factors({S(2): -S.One}) assert Factors(Rational(3, 2)) == Factors({S(3): S.One, S(2): S.NegativeOne}) assert Factors({I: S.One}) == Factors(I) assert Factors({-1.0: 2, I: 1}) == Factors({S(1.0): 1, I: 1}) assert Factors({S.NegativeOne: Rational(-3, 2)}).as_expr() == I A = symbols('A', commutative=False) assert Factors(2*A**2) == Factors({S(2): 1, A**2: 1}) assert Factors(I) == Factors({I: S.One}) assert Factors(x).normal(S(2)) == (Factors(x), Factors(S(2))) assert Factors(x).normal(S.Zero) == (Factors(), Factors(S.Zero)) raises(ZeroDivisionError, lambda: Factors(x).div(S.Zero)) assert Factors(x).mul(S(2)) == Factors(2*x) assert Factors(x).mul(S.Zero).is_zero assert Factors(x).mul(1/x).is_one assert Factors(x**sqrt(2)**3).as_expr() == x**(2*sqrt(2)) assert Factors(x)**Factors(S(2)) == Factors(x**2) assert Factors(x).gcd(S.Zero) == Factors(x) assert Factors(x).lcm(S.Zero).is_zero assert Factors(S.Zero).div(x) == (Factors(S.Zero), Factors()) assert Factors(x).div(x) == (Factors(), Factors()) assert Factors({x: .2})/Factors({x: .2}) == Factors() assert Factors(x) != Factors() assert Factors(S.Zero).normal(x) == (Factors(S.Zero), Factors()) n, d = x**(2 + y), x**2 f = Factors(n) assert f.div(d) == f.normal(d) == (Factors(x**y), Factors()) assert f.gcd(d) == Factors() d = x**y assert f.div(d) == f.normal(d) == (Factors(x**2), Factors()) assert f.gcd(d) == Factors(d) n = d = 2**x f = Factors(n) assert f.div(d) == f.normal(d) == (Factors(), Factors()) assert f.gcd(d) == Factors(d) n, d = 2**x, 2**y f = Factors(n) assert f.div(d) == f.normal(d) == (Factors({S(2): x}), Factors({S(2): y})) assert f.gcd(d) == Factors() # extraction of constant only n = x**(x + 3) assert Factors(n).normal(x**-3) == (Factors({x: x + 6}), Factors({})) assert Factors(n).normal(x**3) == (Factors({x: x}), Factors({})) assert Factors(n).normal(x**4) == (Factors({x: x}), Factors({x: 1})) assert Factors(n).normal(x**(y - 3)) == \ (Factors({x: x + 6}), Factors({x: y})) assert Factors(n).normal(x**(y + 3)) == (Factors({x: x}), Factors({x: y})) assert Factors(n).normal(x**(y + 4)) == \ (Factors({x: x}), Factors({x: y + 1})) assert Factors(n).div(x**-3) == (Factors({x: x + 6}), Factors({})) assert Factors(n).div(x**3) == (Factors({x: x}), Factors({})) assert Factors(n).div(x**4) == (Factors({x: x}), Factors({x: 1})) assert Factors(n).div(x**(y - 3)) == \ (Factors({x: x + 6}), Factors({x: y})) assert Factors(n).div(x**(y + 3)) == (Factors({x: x}), Factors({x: y})) assert Factors(n).div(x**(y + 4)) == \ (Factors({x: x}), Factors({x: y + 1})) assert Factors(3 * x / 2) == Factors({3: 1, 2: -1, x: 1}) assert Factors(x * x / y) == Factors({x: 2, y: -1}) assert Factors(27 * x / y**9) == Factors({27: 1, x: 1, y: -9}) def test_Term(): a = Term(4*x*y**2/z/t**3) b = Term(2*x**3*y**5/t**3) assert a == Term(4, Factors({x: 1, y: 2}), Factors({z: 1, t: 3})) assert b == Term(2, Factors({x: 3, y: 5}), Factors({t: 3})) assert a.as_expr() == 4*x*y**2/z/t**3 assert b.as_expr() == 2*x**3*y**5/t**3 assert a.inv() == \ Term(S.One/4, Factors({z: 1, t: 3}), Factors({x: 1, y: 2})) assert b.inv() == Term(S.Half, Factors({t: 3}), Factors({x: 3, y: 5})) assert a.mul(b) == a*b == \ Term(8, Factors({x: 4, y: 7}), Factors({z: 1, t: 6})) assert a.quo(b) == a/b == Term(2, Factors({}), Factors({x: 2, y: 3, z: 1})) assert a.pow(3) == a**3 == \ Term(64, Factors({x: 3, y: 6}), Factors({z: 3, t: 9})) assert b.pow(3) == b**3 == Term(8, Factors({x: 9, y: 15}), Factors({t: 9})) assert a.pow(-3) == a**(-3) == \ Term(S.One/64, Factors({z: 3, t: 9}), Factors({x: 3, y: 6})) assert b.pow(-3) == b**(-3) == \ Term(S.One/8, Factors({t: 9}), Factors({x: 9, y: 15})) assert a.gcd(b) == Term(2, Factors({x: 1, y: 2}), Factors({t: 3})) assert a.lcm(b) == Term(4, Factors({x: 3, y: 5}), Factors({z: 1, t: 3})) a = Term(4*x*y**2/z/t**3) b = Term(2*x**3*y**5*t**7) assert a.mul(b) == Term(8, Factors({x: 4, y: 7, t: 4}), Factors({z: 1})) assert Term((2*x + 2)**3) == Term(8, Factors({x + 1: 3}), Factors({})) assert Term((2*x + 2)*(3*x + 6)**2) == \ Term(18, Factors({x + 1: 1, x + 2: 2}), Factors({})) def test_gcd_terms(): f = 2*(x + 1)*(x + 4)/(5*x**2 + 5) + (2*x + 2)*(x + 5)/(x**2 + 1)/5 + \ (2*x + 2)*(x + 6)/(5*x**2 + 5) assert _gcd_terms(f) == ((Rational(6, 5))*((1 + x)/(1 + x**2)), 5 + x, 1) assert _gcd_terms(Add.make_args(f)) == \ ((Rational(6, 5))*((1 + x)/(1 + x**2)), 5 + x, 1) newf = (Rational(6, 5))*((1 + x)*(5 + x)/(1 + x**2)) assert gcd_terms(f) == newf args = Add.make_args(f) # non-Basic sequences of terms treated as terms of Add assert gcd_terms(list(args)) == newf assert gcd_terms(tuple(args)) == newf assert gcd_terms(set(args)) == newf # but a Basic sequence is treated as a container assert gcd_terms(Tuple(*args)) != newf assert gcd_terms(Basic(Tuple(S(1), 3*y + 3*x*y), Tuple(S(1), S(3)))) == \ Basic(Tuple(S(1), 3*y*(x + 1)), Tuple(S(1), S(3))) # but we shouldn't change keys of a dictionary or some may be lost assert gcd_terms(Dict((x*(1 + y), S(2)), (x + x*y, y + x*y))) == \ Dict({x*(y + 1): S(2), x + x*y: y*(1 + x)}) assert gcd_terms((2*x + 2)**3 + (2*x + 2)**2) == 4*(x + 1)**2*(2*x + 3) assert gcd_terms(0) == 0 assert gcd_terms(1) == 1 assert gcd_terms(x) == x assert gcd_terms(2 + 2*x) == Mul(2, 1 + x, evaluate=False) arg = x*(2*x + 4*y) garg = 2*x*(x + 2*y) assert gcd_terms(arg) == garg assert gcd_terms(sin(arg)) == sin(garg) # issue 6139-like alpha, alpha1, alpha2, alpha3 = symbols('alpha:4') a = alpha**2 - alpha*x**2 + alpha + x**3 - x*(alpha + 1) rep = (alpha, (1 + sqrt(5))/2 + alpha1*x + alpha2*x**2 + alpha3*x**3) s = (a/(x - alpha)).subs(*rep).series(x, 0, 1) assert simplify(collect(s, x)) == -sqrt(5)/2 - Rational(3, 2) + O(x) # issue 5917 assert _gcd_terms([S.Zero, S.Zero]) == (0, 0, 1) assert _gcd_terms([2*x + 4]) == (2, x + 2, 1) eq = x/(x + 1/x) assert gcd_terms(eq, fraction=False) == eq eq = x/2/y + 1/x/y assert gcd_terms(eq, fraction=True, clear=True) == \ (x**2 + 2)/(2*x*y) assert gcd_terms(eq, fraction=True, clear=False) == \ (x**2/2 + 1)/(x*y) assert gcd_terms(eq, fraction=False, clear=True) == \ (x + 2/x)/(2*y) assert gcd_terms(eq, fraction=False, clear=False) == \ (x/2 + 1/x)/y def test_factor_terms(): A = Symbol('A', commutative=False) assert factor_terms(9*(x + x*y + 1) + (3*x + 3)**(2 + 2*x)) == \ 9*x*y + 9*x + _keep_coeff(S(3), x + 1)**_keep_coeff(S(2), x + 1) + 9 assert factor_terms(9*(x + x*y + 1) + (3)**(2 + 2*x)) == \ _keep_coeff(S(9), 3**(2*x) + x*y + x + 1) assert factor_terms(3**(2 + 2*x) + a*3**(2 + 2*x)) == \ 9*3**(2*x)*(a + 1) assert factor_terms(x + x*A) == \ x*(1 + A) assert factor_terms(sin(x + x*A)) == \ sin(x*(1 + A)) assert factor_terms((3*x + 3)**((2 + 2*x)/3)) == \ _keep_coeff(S(3), x + 1)**_keep_coeff(Rational(2, 3), x + 1) assert factor_terms(x + (x*y + x)**(3*x + 3)) == \ x + (x*(y + 1))**_keep_coeff(S(3), x + 1) assert factor_terms(a*(x + x*y) + b*(x*2 + y*x*2)) == \ x*(a + 2*b)*(y + 1) i = Integral(x, (x, 0, oo)) assert factor_terms(i) == i assert factor_terms(x/2 + y) == x/2 + y # fraction doesn't apply to integer denominators assert factor_terms(x/2 + y, fraction=True) == x/2 + y # clear *does* apply to the integer denominators assert factor_terms(x/2 + y, clear=True) == Mul(S.Half, x + 2*y, evaluate=False) # check radical extraction eq = sqrt(2) + sqrt(10) assert factor_terms(eq) == eq assert factor_terms(eq, radical=True) == sqrt(2)*(1 + sqrt(5)) eq = root(-6, 3) + root(6, 3) assert factor_terms(eq, radical=True) == 6**(S.One/3)*(1 + (-1)**(S.One/3)) eq = [x + x*y] ans = [x*(y + 1)] for c in [list, tuple, set]: assert factor_terms(c(eq)) == c(ans) assert factor_terms(Tuple(x + x*y)) == Tuple(x*(y + 1)) assert factor_terms(Interval(0, 1)) == Interval(0, 1) e = 1/sqrt(a/2 + 1) assert factor_terms(e, clear=False) == 1/sqrt(a/2 + 1) assert factor_terms(e, clear=True) == sqrt(2)/sqrt(a + 2) eq = x/(x + 1/x) + 1/(x**2 + 1) assert factor_terms(eq, fraction=False) == eq assert factor_terms(eq, fraction=True) == 1 assert factor_terms((1/(x**3 + x**2) + 2/x**2)*y) == \ y*(2 + 1/(x + 1))/x**2 # if not True, then processesing for this in factor_terms is not necessary assert gcd_terms(-x - y) == -x - y assert factor_terms(-x - y) == Mul(-1, x + y, evaluate=False) # if not True, then "special" processesing in factor_terms is not necessary assert gcd_terms(exp(Mul(-1, x + 1))) == exp(-x - 1) e = exp(-x - 2) + x assert factor_terms(e) == exp(Mul(-1, x + 2, evaluate=False)) + x assert factor_terms(e, sign=False) == e assert factor_terms(exp(-4*x - 2) - x) == -x + exp(Mul(-2, 2*x + 1, evaluate=False)) # sum/integral tests for F in (Sum, Integral): assert factor_terms(F(x, (y, 1, 10))) == x * F(1, (y, 1, 10)) assert factor_terms(F(x, (y, 1, 10)) + x) == x * (1 + F(1, (y, 1, 10))) assert factor_terms(F(x*y + x*y**2, (y, 1, 10))) == x*F(y*(y + 1), (y, 1, 10)) # expressions involving Pow terms with base 0 assert factor_terms(0**(x - 2) - 1) == 0**(x - 2) - 1 assert factor_terms(0**(x + 2) - 1) == 0**(x + 2) - 1 assert factor_terms((0**(x + 2) - 1).subs(x,-2)) == 0 def test_xreplace(): e = Mul(2, 1 + x, evaluate=False) assert e.xreplace({}) == e assert e.xreplace({y: x}) == e def test_factor_nc(): x, y = symbols('x,y') k = symbols('k', integer=True) n, m, o = symbols('n,m,o', commutative=False) # mul and multinomial expansion is needed from sympy.core.function import _mexpand e = x*(1 + y)**2 assert _mexpand(e) == x + x*2*y + x*y**2 def factor_nc_test(e): ex = _mexpand(e) assert ex.is_Add f = factor_nc(ex) assert not f.is_Add and _mexpand(f) == ex factor_nc_test(x*(1 + y)) factor_nc_test(n*(x + 1)) factor_nc_test(n*(x + m)) factor_nc_test((x + m)*n) factor_nc_test(n*m*(x*o + n*o*m)*n) s = Sum(x, (x, 1, 2)) factor_nc_test(x*(1 + s)) factor_nc_test(x*(1 + s)*s) factor_nc_test(x*(1 + sin(s))) factor_nc_test((1 + n)**2) factor_nc_test((x + n)*(x + m)*(x + y)) factor_nc_test(x*(n*m + 1)) factor_nc_test(x*(n*m + x)) factor_nc_test(x*(x*n*m + 1)) factor_nc_test(x*n*(x*m + 1)) factor_nc_test(x*(m*n + x*n*m)) factor_nc_test(n*(1 - m)*n**2) factor_nc_test((n + m)**2) factor_nc_test((n - m)*(n + m)**2) factor_nc_test((n + m)**2*(n - m)) factor_nc_test((m - n)*(n + m)**2*(n - m)) assert factor_nc(n*(n + n*m)) == n**2*(1 + m) assert factor_nc(m*(m*n + n*m*n**2)) == m*(m + n*m*n)*n eq = m*sin(n) - sin(n)*m assert factor_nc(eq) == eq # for coverage: from sympy.physics.secondquant import Commutator from sympy.polys.polytools import factor eq = 1 + x*Commutator(m, n) assert factor_nc(eq) == eq eq = x*Commutator(m, n) + x*Commutator(m, o)*Commutator(m, n) assert factor(eq) == x*(1 + Commutator(m, o))*Commutator(m, n) # issue 6534 assert (2*n + 2*m).factor() == 2*(n + m) # issue 6701 assert factor_nc(n**k + n**(k + 1)) == n**k*(1 + n) assert factor_nc((m*n)**k + (m*n)**(k + 1)) == (1 + m*n)*(m*n)**k # issue 6918 assert factor_nc(-n*(2*x**2 + 2*x)) == -2*n*x*(x + 1) def test_issue_6360(): a, b = symbols("a b") apb = a + b eq = apb + apb**2*(-2*a - 2*b) assert factor_terms(sub_pre(eq)) == a + b - 2*(a + b)**3 def test_issue_7903(): a = symbols(r'a', real=True) t = exp(I*cos(a)) + exp(-I*sin(a)) assert t.simplify() def test_issue_8263(): F, G = symbols('F, G', commutative=False, cls=Function) x, y = symbols('x, y') expr, dummies, _ = _mask_nc(F(x)*G(y) - G(y)*F(x)) for v in dummies.values(): assert not v.is_commutative assert not expr.is_zero def test_monotonic_sign(): F = _monotonic_sign x = symbols('x') assert F(x) is None assert F(-x) is None assert F(Dummy(prime=True)) == 2 assert F(Dummy(prime=True, odd=True)) == 3 assert F(Dummy(composite=True)) == 4 assert F(Dummy(composite=True, odd=True)) == 9 assert F(Dummy(positive=True, integer=True)) == 1 assert F(Dummy(positive=True, even=True)) == 2 assert F(Dummy(positive=True, even=True, prime=False)) == 4 assert F(Dummy(negative=True, integer=True)) == -1 assert F(Dummy(negative=True, even=True)) == -2 assert F(Dummy(zero=True)) == 0 assert F(Dummy(nonnegative=True)) == 0 assert F(Dummy(nonpositive=True)) == 0 assert F(Dummy(positive=True) + 1).is_positive assert F(Dummy(positive=True, integer=True) - 1).is_nonnegative assert F(Dummy(positive=True) - 1) is None assert F(Dummy(negative=True) + 1) is None assert F(Dummy(negative=True, integer=True) - 1).is_nonpositive assert F(Dummy(negative=True) - 1).is_negative assert F(-Dummy(positive=True) + 1) is None assert F(-Dummy(positive=True, integer=True) - 1).is_negative assert F(-Dummy(positive=True) - 1).is_negative assert F(-Dummy(negative=True) + 1).is_positive assert F(-Dummy(negative=True, integer=True) - 1).is_nonnegative assert F(-Dummy(negative=True) - 1) is None x = Dummy(negative=True) assert F(x**3).is_nonpositive assert F(x**3 + log(2)*x - 1).is_negative x = Dummy(positive=True) assert F(-x**3).is_nonpositive p = Dummy(positive=True) assert F(1/p).is_positive assert F(p/(p + 1)).is_positive p = Dummy(nonnegative=True) assert F(p/(p + 1)).is_nonnegative p = Dummy(positive=True) assert F(-1/p).is_negative p = Dummy(nonpositive=True) assert F(p/(-p + 1)).is_nonpositive p = Dummy(positive=True, integer=True) q = Dummy(positive=True, integer=True) assert F(-2/p/q).is_negative assert F(-2/(p - 1)/q) is None assert F((p - 1)*q + 1).is_positive assert F(-(p - 1)*q - 1).is_negative def test_issue_17256(): from sympy.sets.fancysets import Range x = Symbol('x') s1 = Sum(x + 1, (x, 1, 9)) s2 = Sum(x + 1, (x, Range(1, 10))) a = Symbol('a') r1 = s1.xreplace({x:a}) r2 = s2.xreplace({x:a}) assert r1.doit() == r2.doit() s1 = Sum(x + 1, (x, 0, 9)) s2 = Sum(x + 1, (x, Range(10))) a = Symbol('a') r1 = s1.xreplace({x:a}) r2 = s2.xreplace({x:a}) assert r1 == r2 def test_issue_21623(): from sympy.matrices.expressions.matexpr import MatrixSymbol M = MatrixSymbol('X', 2, 2) assert gcd_terms(M[0,0], 1) == M[0,0]
e7e940bbbb2d96aa668f389c054d12e41a311489fa3e467db3028b0f1ef8058c
from sympy.core import ( Basic, Rational, Symbol, S, Float, Integer, Mul, Number, Pow, Expr, I, nan, pi, symbols, oo, zoo, N) from sympy.core.parameters import global_parameters from sympy.core.tests.test_evalf import NS from sympy.core.function import expand_multinomial from sympy.functions.elementary.miscellaneous import sqrt, cbrt from sympy.functions.elementary.exponential import exp, log from sympy.functions.special.error_functions import erf from sympy.functions.elementary.trigonometric import ( sin, cos, tan, sec, csc, sinh, cosh, tanh, atan) from sympy.polys import Poly from sympy.series.order import O from sympy.sets import FiniteSet from sympy.core.power import power from sympy.testing.pytest import warns_deprecated_sympy, _both_exp_pow def test_rational(): a = Rational(1, 5) r = sqrt(5)/5 assert sqrt(a) == r assert 2*sqrt(a) == 2*r r = a*a**S.Half assert a**Rational(3, 2) == r assert 2*a**Rational(3, 2) == 2*r r = a**5*a**Rational(2, 3) assert a**Rational(17, 3) == r assert 2 * a**Rational(17, 3) == 2*r def test_large_rational(): e = (Rational(123712**12 - 1, 7) + Rational(1, 7))**Rational(1, 3) assert e == 234232585392159195136 * (Rational(1, 7)**Rational(1, 3)) def test_negative_real(): def feq(a, b): return abs(a - b) < 1E-10 assert feq(S.One / Float(-0.5), -Integer(2)) def test_expand(): x = Symbol('x') assert (2**(-1 - x)).expand() == S.Half*2**(-x) def test_issue_3449(): #test if powers are simplified correctly #see also issue 3995 x = Symbol('x') assert ((x**Rational(1, 3))**Rational(2)) == x**Rational(2, 3) assert ( (x**Rational(3))**Rational(2, 5)) == (x**Rational(3))**Rational(2, 5) a = Symbol('a', real=True) b = Symbol('b', real=True) assert (a**2)**b == (abs(a)**b)**2 assert sqrt(1/a) != 1/sqrt(a) # e.g. for a = -1 assert (a**3)**Rational(1, 3) != a assert (x**a)**b != x**(a*b) # e.g. x = -1, a=2, b=1/2 assert (x**.5)**b == x**(.5*b) assert (x**.5)**.5 == x**.25 assert (x**2.5)**.5 != x**1.25 # e.g. for x = 5*I k = Symbol('k', integer=True) m = Symbol('m', integer=True) assert (x**k)**m == x**(k*m) assert Number(5)**Rational(2, 3) == Number(25)**Rational(1, 3) assert (x**.5)**2 == x**1.0 assert (x**2)**k == (x**k)**2 == x**(2*k) a = Symbol('a', positive=True) assert (a**3)**Rational(2, 5) == a**Rational(6, 5) assert (a**2)**b == (a**b)**2 assert (a**Rational(2, 3))**x == a**(x*Rational(2, 3)) != (a**x)**Rational(2, 3) def test_issue_3866(): assert --sqrt(sqrt(5) - 1) == sqrt(sqrt(5) - 1) def test_negative_one(): x = Symbol('x', complex=True) y = Symbol('y', complex=True) assert 1/x**y == x**(-y) def test_issue_4362(): neg = Symbol('neg', negative=True) nonneg = Symbol('nonneg', nonnegative=True) any = Symbol('any') num, den = sqrt(1/neg).as_numer_denom() assert num == sqrt(-1) assert den == sqrt(-neg) num, den = sqrt(1/nonneg).as_numer_denom() assert num == 1 assert den == sqrt(nonneg) num, den = sqrt(1/any).as_numer_denom() assert num == sqrt(1/any) assert den == 1 def eqn(num, den, pow): return (num/den)**pow npos = 1 nneg = -1 dpos = 2 - sqrt(3) dneg = 1 - sqrt(3) assert dpos > 0 and dneg < 0 and npos > 0 and nneg < 0 # pos or neg integer eq = eqn(npos, dpos, 2) assert eq.is_Pow and eq.as_numer_denom() == (1, dpos**2) eq = eqn(npos, dneg, 2) assert eq.is_Pow and eq.as_numer_denom() == (1, dneg**2) eq = eqn(nneg, dpos, 2) assert eq.is_Pow and eq.as_numer_denom() == (1, dpos**2) eq = eqn(nneg, dneg, 2) assert eq.is_Pow and eq.as_numer_denom() == (1, dneg**2) eq = eqn(npos, dpos, -2) assert eq.is_Pow and eq.as_numer_denom() == (dpos**2, 1) eq = eqn(npos, dneg, -2) assert eq.is_Pow and eq.as_numer_denom() == (dneg**2, 1) eq = eqn(nneg, dpos, -2) assert eq.is_Pow and eq.as_numer_denom() == (dpos**2, 1) eq = eqn(nneg, dneg, -2) assert eq.is_Pow and eq.as_numer_denom() == (dneg**2, 1) # pos or neg rational pow = S.Half eq = eqn(npos, dpos, pow) assert eq.is_Pow and eq.as_numer_denom() == (npos**pow, dpos**pow) eq = eqn(npos, dneg, pow) assert eq.is_Pow is False and eq.as_numer_denom() == ((-npos)**pow, (-dneg)**pow) eq = eqn(nneg, dpos, pow) assert not eq.is_Pow or eq.as_numer_denom() == (nneg**pow, dpos**pow) eq = eqn(nneg, dneg, pow) assert eq.is_Pow and eq.as_numer_denom() == ((-nneg)**pow, (-dneg)**pow) eq = eqn(npos, dpos, -pow) assert eq.is_Pow and eq.as_numer_denom() == (dpos**pow, npos**pow) eq = eqn(npos, dneg, -pow) assert eq.is_Pow is False and eq.as_numer_denom() == (-(-npos)**pow*(-dneg)**pow, npos) eq = eqn(nneg, dpos, -pow) assert not eq.is_Pow or eq.as_numer_denom() == (dpos**pow, nneg**pow) eq = eqn(nneg, dneg, -pow) assert eq.is_Pow and eq.as_numer_denom() == ((-dneg)**pow, (-nneg)**pow) # unknown exponent pow = 2*any eq = eqn(npos, dpos, pow) assert eq.is_Pow and eq.as_numer_denom() == (npos**pow, dpos**pow) eq = eqn(npos, dneg, pow) assert eq.is_Pow and eq.as_numer_denom() == ((-npos)**pow, (-dneg)**pow) eq = eqn(nneg, dpos, pow) assert eq.is_Pow and eq.as_numer_denom() == (nneg**pow, dpos**pow) eq = eqn(nneg, dneg, pow) assert eq.is_Pow and eq.as_numer_denom() == ((-nneg)**pow, (-dneg)**pow) eq = eqn(npos, dpos, -pow) assert eq.as_numer_denom() == (dpos**pow, npos**pow) eq = eqn(npos, dneg, -pow) assert eq.is_Pow and eq.as_numer_denom() == ((-dneg)**pow, (-npos)**pow) eq = eqn(nneg, dpos, -pow) assert eq.is_Pow and eq.as_numer_denom() == (dpos**pow, nneg**pow) eq = eqn(nneg, dneg, -pow) assert eq.is_Pow and eq.as_numer_denom() == ((-dneg)**pow, (-nneg)**pow) x = Symbol('x') y = Symbol('y') assert ((1/(1 + x/3))**(-S.One)).as_numer_denom() == (3 + x, 3) notp = Symbol('notp', positive=False) # not positive does not imply real b = ((1 + x/notp)**-2) assert (b**(-y)).as_numer_denom() == (1, b**y) assert (b**(-S.One)).as_numer_denom() == ((notp + x)**2, notp**2) nonp = Symbol('nonp', nonpositive=True) assert (((1 + x/nonp)**-2)**(-S.One)).as_numer_denom() == ((-nonp - x)**2, nonp**2) n = Symbol('n', negative=True) assert (x**n).as_numer_denom() == (1, x**-n) assert sqrt(1/n).as_numer_denom() == (S.ImaginaryUnit, sqrt(-n)) n = Symbol('0 or neg', nonpositive=True) # if x and n are split up without negating each term and n is negative # then the answer might be wrong; if n is 0 it won't matter since # 1/oo and 1/zoo are both zero as is sqrt(0)/sqrt(-x) unless x is also # zero (in which case the negative sign doesn't matter): # 1/sqrt(1/-1) = -I but sqrt(-1)/sqrt(1) = I assert (1/sqrt(x/n)).as_numer_denom() == (sqrt(-n), sqrt(-x)) c = Symbol('c', complex=True) e = sqrt(1/c) assert e.as_numer_denom() == (e, 1) i = Symbol('i', integer=True) assert ((1 + x/y)**i).as_numer_denom() == ((x + y)**i, y**i) def test_Pow_Expr_args(): x = Symbol('x') bases = [Basic(), Poly(x, x), FiniteSet(x)] for base in bases: with warns_deprecated_sympy(): Pow(base, S.One) def test_Pow_signs(): """Cf. issues 4595 and 5250""" x = Symbol('x') y = Symbol('y') n = Symbol('n', even=True) assert (3 - y)**2 != (y - 3)**2 assert (3 - y)**n != (y - 3)**n assert (-3 + y - x)**2 != (3 - y + x)**2 assert (y - 3)**3 != -(3 - y)**3 def test_power_with_noncommutative_mul_as_base(): x = Symbol('x', commutative=False) y = Symbol('y', commutative=False) assert not (x*y)**3 == x**3*y**3 assert (2*x*y)**3 == 8*(x*y)**3 @_both_exp_pow def test_power_rewrite_exp(): assert (I**I).rewrite(exp) == exp(-pi/2) expr = (2 + 3*I)**(4 + 5*I) assert expr.rewrite(exp) == exp((4 + 5*I)*(log(sqrt(13)) + I*atan(Rational(3, 2)))) assert expr.rewrite(exp).expand() == \ 169*exp(5*I*log(13)/2)*exp(4*I*atan(Rational(3, 2)))*exp(-5*atan(Rational(3, 2))) assert ((6 + 7*I)**5).rewrite(exp) == 7225*sqrt(85)*exp(5*I*atan(Rational(7, 6))) expr = 5**(6 + 7*I) assert expr.rewrite(exp) == exp((6 + 7*I)*log(5)) assert expr.rewrite(exp).expand() == 15625*exp(7*I*log(5)) assert Pow(123, 789, evaluate=False).rewrite(exp) == 123**789 assert (1**I).rewrite(exp) == 1**I assert (0**I).rewrite(exp) == 0**I expr = (-2)**(2 + 5*I) assert expr.rewrite(exp) == exp((2 + 5*I)*(log(2) + I*pi)) assert expr.rewrite(exp).expand() == 4*exp(-5*pi)*exp(5*I*log(2)) assert ((-2)**S(-5)).rewrite(exp) == (-2)**S(-5) x, y = symbols('x y') assert (x**y).rewrite(exp) == exp(y*log(x)) if global_parameters.exp_is_pow: assert (7**x).rewrite(exp) == Pow(S.Exp1, x*log(7), evaluate=False) else: assert (7**x).rewrite(exp) == exp(x*log(7), evaluate=False) assert ((2 + 3*I)**x).rewrite(exp) == exp(x*(log(sqrt(13)) + I*atan(Rational(3, 2)))) assert (y**(5 + 6*I)).rewrite(exp) == exp(log(y)*(5 + 6*I)) assert all((1/func(x)).rewrite(exp) == 1/(func(x).rewrite(exp)) for func in (sin, cos, tan, sec, csc, sinh, cosh, tanh)) def test_zero(): x = Symbol('x') y = Symbol('y') assert 0**x != 0 assert 0**(2*x) == 0**x assert 0**(1.0*x) == 0**x assert 0**(2.0*x) == 0**x assert (0**(2 - x)).as_base_exp() == (0, 2 - x) assert 0**(x - 2) != S.Infinity**(2 - x) assert 0**(2*x*y) == 0**(x*y) assert 0**(-2*x*y) == S.ComplexInfinity**(x*y) assert Float(0)**2 is not S.Zero assert Float(0)**2 == 0.0 assert Float(0)**-2 is zoo assert Float(0)**oo is S.Zero #Test issue 19572 assert 0 ** -oo is zoo assert power(0, -oo) is zoo assert Float(0)**-oo is zoo def test_pow_as_base_exp(): x = Symbol('x') assert (S.Infinity**(2 - x)).as_base_exp() == (S.Infinity, 2 - x) assert (S.Infinity**(x - 2)).as_base_exp() == (S.Infinity, x - 2) p = S.Half**x assert p.base, p.exp == p.as_base_exp() == (S(2), -x) # issue 8344: assert Pow(1, 2, evaluate=False).as_base_exp() == (S.One, S(2)) def test_nseries(): x = Symbol('x') assert sqrt(I*x - 1)._eval_nseries(x, 4, None, 1) == I + x/2 + I*x**2/8 - x**3/16 + O(x**4) assert sqrt(I*x - 1)._eval_nseries(x, 4, None, -1) == -I - x/2 - I*x**2/8 + x**3/16 + O(x**4) assert cbrt(I*x - 1)._eval_nseries(x, 4, None, 1) == (-1)**(S(1)/3) - (-1)**(S(5)/6)*x/3 + \ (-1)**(S(1)/3)*x**2/9 + 5*(-1)**(S(5)/6)*x**3/81 + O(x**4) assert cbrt(I*x - 1)._eval_nseries(x, 4, None, -1) == (-1)**(S(1)/3)*exp(-2*I*pi/3) - \ (-1)**(S(5)/6)*x*exp(-2*I*pi/3)/3 + (-1)**(S(1)/3)*x**2*exp(-2*I*pi/3)/9 + \ 5*(-1)**(S(5)/6)*x**3*exp(-2*I*pi/3)/81 + O(x**4) assert (1 / (exp(-1/x) + 1/x))._eval_nseries(x, 2, None) == x + O(x**2) def test_issue_6100_12942_4473(): x = Symbol('x') y = Symbol('y') assert x**1.0 != x assert x != x**1.0 assert True != x**1.0 assert x**1.0 is not True assert x is not True assert x*y != (x*y)**1.0 # Pow != Symbol assert (x**1.0)**1.0 != x assert (x**1.0)**2.0 != x**2 b = Expr() assert Pow(b, 1.0, evaluate=False) != b # if the following gets distributed as a Mul (x**1.0*y**1.0 then # __eq__ methods could be added to Symbol and Pow to detect the # power-of-1.0 case. assert ((x*y)**1.0).func is Pow def test_issue_6208(): from sympy.functions.elementary.miscellaneous import root assert sqrt(33**(I*9/10)) == -33**(I*9/20) assert root((6*I)**(2*I), 3).as_base_exp()[1] == Rational(1, 3) # != 2*I/3 assert root((6*I)**(I/3), 3).as_base_exp()[1] == I/9 assert sqrt(exp(3*I)) == exp(3*I/2) assert sqrt(-sqrt(3)*(1 + 2*I)) == sqrt(sqrt(3))*sqrt(-1 - 2*I) assert sqrt(exp(5*I)) == -exp(5*I/2) assert root(exp(5*I), 3).exp == Rational(1, 3) def test_issue_6990(): x = Symbol('x') a = Symbol('a') b = Symbol('b') assert (sqrt(a + b*x + x**2)).series(x, 0, 3).removeO() == \ sqrt(a)*x**2*(1/(2*a) - b**2/(8*a**2)) + sqrt(a) + b*x/(2*sqrt(a)) def test_issue_6068(): x = Symbol('x') assert sqrt(sin(x)).series(x, 0, 7) == \ sqrt(x) - x**Rational(5, 2)/12 + x**Rational(9, 2)/1440 - \ x**Rational(13, 2)/24192 + O(x**7) assert sqrt(sin(x)).series(x, 0, 9) == \ sqrt(x) - x**Rational(5, 2)/12 + x**Rational(9, 2)/1440 - \ x**Rational(13, 2)/24192 - 67*x**Rational(17, 2)/29030400 + O(x**9) assert sqrt(sin(x**3)).series(x, 0, 19) == \ x**Rational(3, 2) - x**Rational(15, 2)/12 + x**Rational(27, 2)/1440 + O(x**19) assert sqrt(sin(x**3)).series(x, 0, 20) == \ x**Rational(3, 2) - x**Rational(15, 2)/12 + x**Rational(27, 2)/1440 - \ x**Rational(39, 2)/24192 + O(x**20) def test_issue_6782(): x = Symbol('x') assert sqrt(sin(x**3)).series(x, 0, 7) == x**Rational(3, 2) + O(x**7) assert sqrt(sin(x**4)).series(x, 0, 3) == x**2 + O(x**3) def test_issue_6653(): x = Symbol('x') assert (1 / sqrt(1 + sin(x**2))).series(x, 0, 3) == 1 - x**2/2 + O(x**3) def test_issue_6429(): x = Symbol('x') c = Symbol('c') f = (c**2 + x)**(0.5) assert f.series(x, x0=0, n=1) == (c**2)**0.5 + O(x) assert f.taylor_term(0, x) == (c**2)**0.5 assert f.taylor_term(1, x) == 0.5*x*(c**2)**(-0.5) assert f.taylor_term(2, x) == -0.125*x**2*(c**2)**(-1.5) def test_issue_7638(): f = pi/log(sqrt(2)) assert ((1 + I)**(I*f/2))**0.3 == (1 + I)**(0.15*I*f) # if 1/3 -> 1.0/3 this should fail since it cannot be shown that the # sign will be +/-1; for the previous "small arg" case, it didn't matter # that this could not be proved assert (1 + I)**(4*I*f) == ((1 + I)**(12*I*f))**Rational(1, 3) assert (((1 + I)**(I*(1 + 7*f)))**Rational(1, 3)).exp == Rational(1, 3) r = symbols('r', real=True) assert sqrt(r**2) == abs(r) assert cbrt(r**3) != r assert sqrt(Pow(2*I, 5*S.Half)) != (2*I)**Rational(5, 4) p = symbols('p', positive=True) assert cbrt(p**2) == p**Rational(2, 3) assert NS(((0.2 + 0.7*I)**(0.7 + 1.0*I))**(0.5 - 0.1*I), 1) == '0.4 + 0.2*I' assert sqrt(1/(1 + I)) == sqrt(1 - I)/sqrt(2) # or 1/sqrt(1 + I) e = 1/(1 - sqrt(2)) assert sqrt(e) == I/sqrt(-1 + sqrt(2)) assert e**Rational(-1, 2) == -I*sqrt(-1 + sqrt(2)) assert sqrt((cos(1)**2 + sin(1)**2 - 1)**(3 + I)).exp in [S.Half, Rational(3, 2) + I/2] assert sqrt(r**Rational(4, 3)) != r**Rational(2, 3) assert sqrt((p + I)**Rational(4, 3)) == (p + I)**Rational(2, 3) assert sqrt((p - p**2*I)**2) == p - p**2*I assert sqrt((p**2*I - p)**2) == p**2*I - p # XXX ok? assert sqrt((p + r*I)**2) != p + r*I e = (1 + I/5) assert sqrt(e**5) == e**(5*S.Half) assert sqrt(e**6) == e**3 assert sqrt((1 + I*r)**6) != (1 + I*r)**3 def test_issue_8582(): assert 1**oo is nan assert 1**(-oo) is nan assert 1**zoo is nan assert 1**(oo + I) is nan assert 1**(1 + I*oo) is nan assert 1**(oo + I*oo) is nan def test_issue_8650(): n = Symbol('n', integer=True, nonnegative=True) assert (n**n).is_positive is True x = 5*n + 5 assert (x**(5*(n + 1))).is_positive is True def test_issue_13914(): b = Symbol('b') assert (-1)**zoo is nan assert 2**zoo is nan assert (S.Half)**(1 + zoo) is nan assert I**(zoo + I) is nan assert b**(I + zoo) is nan def test_better_sqrt(): n = Symbol('n', integer=True, nonnegative=True) assert sqrt(3 + 4*I) == 2 + I assert sqrt(3 - 4*I) == 2 - I assert sqrt(-3 - 4*I) == 1 - 2*I assert sqrt(-3 + 4*I) == 1 + 2*I assert sqrt(32 + 24*I) == 6 + 2*I assert sqrt(32 - 24*I) == 6 - 2*I assert sqrt(-32 - 24*I) == 2 - 6*I assert sqrt(-32 + 24*I) == 2 + 6*I # triple (3, 4, 5): # parity of 3 matches parity of 5 and # den, 4, is a square assert sqrt((3 + 4*I)/4) == 1 + I/2 # triple (8, 15, 17) # parity of 8 doesn't match parity of 17 but # den/2, 8/2, is a square assert sqrt((8 + 15*I)/8) == (5 + 3*I)/4 # handle the denominator assert sqrt((3 - 4*I)/25) == (2 - I)/5 assert sqrt((3 - 4*I)/26) == (2 - I)/sqrt(26) # mul # issue #12739 assert sqrt((3 + 4*I)/(3 - 4*I)) == (3 + 4*I)/5 assert sqrt(2/(3 + 4*I)) == sqrt(2)/5*(2 - I) assert sqrt(n/(3 + 4*I)).subs(n, 2) == sqrt(2)/5*(2 - I) assert sqrt(-2/(3 + 4*I)) == sqrt(2)/5*(1 + 2*I) assert sqrt(-n/(3 + 4*I)).subs(n, 2) == sqrt(2)/5*(1 + 2*I) # power assert sqrt(1/(3 + I*4)) == (2 - I)/5 assert sqrt(1/(3 - I)) == sqrt(10)*sqrt(3 + I)/10 # symbolic i = symbols('i', imaginary=True) assert sqrt(3/i) == Mul(sqrt(3), 1/sqrt(i), evaluate=False) # multiples of 1/2; don't make this too automatic assert sqrt(3 + 4*I)**3 == (2 + I)**3 assert Pow(3 + 4*I, Rational(3, 2)) == 2 + 11*I assert Pow(6 + 8*I, Rational(3, 2)) == 2*sqrt(2)*(2 + 11*I) n, d = (3 + 4*I), (3 - 4*I)**3 a = n/d assert a.args == (1/d, n) eq = sqrt(a) assert eq.args == (a, S.Half) assert expand_multinomial(eq) == sqrt((-117 + 44*I)*(3 + 4*I))/125 assert eq.expand() == (7 - 24*I)/125 # issue 12775 # pos im part assert sqrt(2*I) == (1 + I) assert sqrt(2*9*I) == Mul(3, 1 + I, evaluate=False) assert Pow(2*I, 3*S.Half) == (1 + I)**3 # neg im part assert sqrt(-I/2) == Mul(S.Half, 1 - I, evaluate=False) # fractional im part assert Pow(Rational(-9, 2)*I, Rational(3, 2)) == 27*(1 - I)**3/8 def test_issue_2993(): x = Symbol('x') assert str((2.3*x - 4)**0.3) == '1.5157165665104*(0.575*x - 1)**0.3' assert str((2.3*x + 4)**0.3) == '1.5157165665104*(0.575*x + 1)**0.3' assert str((-2.3*x + 4)**0.3) == '1.5157165665104*(1 - 0.575*x)**0.3' assert str((-2.3*x - 4)**0.3) == '1.5157165665104*(-0.575*x - 1)**0.3' assert str((2.3*x - 2)**0.3) == '1.28386201800527*(x - 0.869565217391304)**0.3' assert str((-2.3*x - 2)**0.3) == '1.28386201800527*(-x - 0.869565217391304)**0.3' assert str((-2.3*x + 2)**0.3) == '1.28386201800527*(0.869565217391304 - x)**0.3' assert str((2.3*x + 2)**0.3) == '1.28386201800527*(x + 0.869565217391304)**0.3' assert str((2.3*x - 4)**Rational(1, 3)) == '2**(2/3)*(0.575*x - 1)**(1/3)' eq = (2.3*x + 4) assert eq**2 == 16*(0.575*x + 1)**2 assert (1/eq).args == (eq, -1) # don't change trivial power # issue 17735 q=.5*exp(x) - .5*exp(-x) + 0.1 assert int((q**2).subs(x, 1)) == 1 # issue 17756 y = Symbol('y') assert len(sqrt(x/(x + y)**2 + Float('0.008', 30)).subs(y, pi.n(25)).atoms(Float)) == 2 # issue 17756 a, b, c, d, e, f, g = symbols('a:g') expr = sqrt(1 + a*(c**4 + g*d - 2*g*e - f*(-g + d))**2/ (c**3*b**2*(d - 3*e + 2*f)**2))/2 r = [ (a, N('0.0170992456333788667034850458615', 30)), (b, N('0.0966594956075474769169134801223', 30)), (c, N('0.390911862903463913632151616184', 30)), (d, N('0.152812084558656566271750185933', 30)), (e, N('0.137562344465103337106561623432', 30)), (f, N('0.174259178881496659302933610355', 30)), (g, N('0.220745448491223779615401870086', 30))] tru = expr.n(30, subs=dict(r)) seq = expr.subs(r) # although `tru` is the right way to evaluate # expr with numerical values, `seq` will have # significant loss of precision if extraction of # the largest coefficient of a power's base's terms # is done improperly assert seq == tru def test_issue_17450(): assert (erf(cosh(1)**7)**I).is_real is None assert (erf(cosh(1)**7)**I).is_imaginary is False assert (Pow(exp(1+sqrt(2)), ((1-sqrt(2))*I*pi), evaluate=False)).is_real is None assert ((-10)**(10*I*pi/3)).is_real is False assert ((-5)**(4*I*pi)).is_real is False def test_issue_18190(): assert sqrt(1 / tan(1 + I)) == 1 / sqrt(tan(1 + I)) def test_issue_14815(): x = Symbol('x', real=True) assert sqrt(x).is_extended_negative is False x = Symbol('x', real=False) assert sqrt(x).is_extended_negative is None x = Symbol('x', complex=True) assert sqrt(x).is_extended_negative is False x = Symbol('x', extended_real=True) assert sqrt(x).is_extended_negative is False assert sqrt(zoo, evaluate=False).is_extended_negative is None assert sqrt(nan, evaluate=False).is_extended_negative is None def test_issue_18509(): x = Symbol('x', prime=True) assert x**oo is oo assert (1/x)**oo is S.Zero assert (-1/x)**oo is S.Zero assert (-x)**oo is zoo assert (-oo)**(-1 + I) is S.Zero assert (-oo)**(1 + I) is zoo assert (oo)**(-1 + I) is S.Zero assert (oo)**(1 + I) is zoo def test_issue_18762(): e, p = symbols('e p') g0 = sqrt(1 + e**2 - 2*e*cos(p)) assert len(g0.series(e, 1, 3).args) == 4 def test_issue_21860(): x = Symbol('x') e = 3*2**Rational(66666666667,200000000000)*3**Rational(16666666667,50000000000)*x**Rational(66666666667, 200000000000) ans = Mul(Rational(3, 2), Pow(Integer(2), Rational(33333333333, 100000000000)), Pow(Integer(3), Rational(26666666667, 40000000000))) assert e.xreplace({x: Rational(3,8)}) == ans def test_issue_21647(): x = Symbol('x') e = log((Integer(567)/500)**(811*(Integer(567)/500)**x/100)) ans = log(Mul(Rational(64701150190720499096094005280169087619821081527, 76293945312500000000000000000000000000000000000), Pow(Integer(2), Rational(396204892125479941, 781250000000000000)), Pow(Integer(3), Rational(385045107874520059, 390625000000000000)), Pow(Integer(5), Rational(407364676376439823, 1562500000000000000)), Pow(Integer(7), Rational(385045107874520059, 1562500000000000000)))) assert e.xreplace({x: 6}) == ans def test_issue_21762(): x = Symbol('x') e = (x**2 + 6)**(Integer(33333333333333333)/50000000000000000) ans = Mul(Rational(5, 4), Pow(Integer(2), Rational(16666666666666667, 25000000000000000)), Pow(Integer(5), Rational(8333333333333333, 25000000000000000))) assert e.xreplace({x: S.Half}) == ans def test_rational_powers_larger_than_one(): assert Rational(2, 3)**Rational(3, 2) == 2*sqrt(6)/9 assert Rational(1, 6)**Rational(9, 4) == 6**Rational(3, 4)/216 assert Rational(3, 7)**Rational(7, 3) == 9*3**Rational(1, 3)*7**Rational(2, 3)/343 def test_power_dispatcher(): class NewBase(Expr): pass class NewPow(NewBase, Pow): pass a, b = Symbol('a'), NewBase() @power.register(Expr, NewBase) @power.register(NewBase, Expr) @power.register(NewBase, NewBase) def _(a, b): return NewPow(a, b) # Pow called as fallback assert power(2, 3) == 8*S.One assert power(a, 2) == Pow(a, 2) assert power(a, a) == Pow(a, a) # NewPow called by dispatch assert power(a, b) == NewPow(a, b) assert power(b, a) == NewPow(b, a) assert power(b, b) == NewPow(b, b) def test_powers_of_I(): assert [sqrt(I)**i for i in range(13)] == [ 1, sqrt(I), I, sqrt(I)**3, -1, -sqrt(I), -I, -sqrt(I)**3, 1, sqrt(I), I, sqrt(I)**3, -1] assert sqrt(I)**(S(9)/2) == -I**(S(1)/4)
9baff8e9714e9d1b85d888e6a424e972859f8922d8132de23412a47f439cbfca
from sympy.core.mod import Mod from sympy.core.numbers import (I, oo, pi) from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (asin, sin) from sympy.simplify.simplify import simplify from sympy.core import Symbol, S, Rational, Integer, Dummy, Wild, Pow from sympy.core.assumptions import (assumptions, check_assumptions, failing_assumptions, common_assumptions) from sympy.core.facts import InconsistentAssumptions from sympy.testing.pytest import raises, XFAIL def test_symbol_unset(): x = Symbol('x', real=True, integer=True) assert x.is_real is True assert x.is_integer is True assert x.is_imaginary is False assert x.is_noninteger is False assert x.is_number is False def test_zero(): z = Integer(0) assert z.is_commutative is True assert z.is_integer is True assert z.is_rational is True assert z.is_algebraic is True assert z.is_transcendental is False assert z.is_real is True assert z.is_complex is True assert z.is_noninteger is False assert z.is_irrational is False assert z.is_imaginary is False assert z.is_positive is False assert z.is_negative is False assert z.is_nonpositive is True assert z.is_nonnegative is True assert z.is_even is True assert z.is_odd is False assert z.is_finite is True assert z.is_infinite is False assert z.is_comparable is True assert z.is_prime is False assert z.is_composite is False assert z.is_number is True def test_one(): z = Integer(1) assert z.is_commutative is True assert z.is_integer is True assert z.is_rational is True assert z.is_algebraic is True assert z.is_transcendental is False assert z.is_real is True assert z.is_complex is True assert z.is_noninteger is False assert z.is_irrational is False assert z.is_imaginary is False assert z.is_positive is True assert z.is_negative is False assert z.is_nonpositive is False assert z.is_nonnegative is True assert z.is_even is False assert z.is_odd is True assert z.is_finite is True assert z.is_infinite is False assert z.is_comparable is True assert z.is_prime is False assert z.is_number is True assert z.is_composite is False # issue 8807 def test_negativeone(): z = Integer(-1) assert z.is_commutative is True assert z.is_integer is True assert z.is_rational is True assert z.is_algebraic is True assert z.is_transcendental is False assert z.is_real is True assert z.is_complex is True assert z.is_noninteger is False assert z.is_irrational is False assert z.is_imaginary is False assert z.is_positive is False assert z.is_negative is True assert z.is_nonpositive is True assert z.is_nonnegative is False assert z.is_even is False assert z.is_odd is True assert z.is_finite is True assert z.is_infinite is False assert z.is_comparable is True assert z.is_prime is False assert z.is_composite is False assert z.is_number is True def test_infinity(): oo = S.Infinity assert oo.is_commutative is True assert oo.is_integer is False assert oo.is_rational is False assert oo.is_algebraic is False assert oo.is_transcendental is False assert oo.is_extended_real is True assert oo.is_real is False assert oo.is_complex is False assert oo.is_noninteger is True assert oo.is_irrational is False assert oo.is_imaginary is False assert oo.is_nonzero is False assert oo.is_positive is False assert oo.is_negative is False assert oo.is_nonpositive is False assert oo.is_nonnegative is False assert oo.is_extended_nonzero is True assert oo.is_extended_positive is True assert oo.is_extended_negative is False assert oo.is_extended_nonpositive is False assert oo.is_extended_nonnegative is True assert oo.is_even is False assert oo.is_odd is False assert oo.is_finite is False assert oo.is_infinite is True assert oo.is_comparable is True assert oo.is_prime is False assert oo.is_composite is False assert oo.is_number is True def test_neg_infinity(): mm = S.NegativeInfinity assert mm.is_commutative is True assert mm.is_integer is False assert mm.is_rational is False assert mm.is_algebraic is False assert mm.is_transcendental is False assert mm.is_extended_real is True assert mm.is_real is False assert mm.is_complex is False assert mm.is_noninteger is True assert mm.is_irrational is False assert mm.is_imaginary is False assert mm.is_nonzero is False assert mm.is_positive is False assert mm.is_negative is False assert mm.is_nonpositive is False assert mm.is_nonnegative is False assert mm.is_extended_nonzero is True assert mm.is_extended_positive is False assert mm.is_extended_negative is True assert mm.is_extended_nonpositive is True assert mm.is_extended_nonnegative is False assert mm.is_even is False assert mm.is_odd is False assert mm.is_finite is False assert mm.is_infinite is True assert mm.is_comparable is True assert mm.is_prime is False assert mm.is_composite is False assert mm.is_number is True def test_zoo(): zoo = S.ComplexInfinity assert zoo.is_complex is False assert zoo.is_real is False assert zoo.is_prime is False def test_nan(): nan = S.NaN assert nan.is_commutative is True assert nan.is_integer is None assert nan.is_rational is None assert nan.is_algebraic is None assert nan.is_transcendental is None assert nan.is_real is None assert nan.is_complex is None assert nan.is_noninteger is None assert nan.is_irrational is None assert nan.is_imaginary is None assert nan.is_positive is None assert nan.is_negative is None assert nan.is_nonpositive is None assert nan.is_nonnegative is None assert nan.is_even is None assert nan.is_odd is None assert nan.is_finite is None assert nan.is_infinite is None assert nan.is_comparable is False assert nan.is_prime is None assert nan.is_composite is None assert nan.is_number is True def test_pos_rational(): r = Rational(3, 4) assert r.is_commutative is True assert r.is_integer is False assert r.is_rational is True assert r.is_algebraic is True assert r.is_transcendental is False assert r.is_real is True assert r.is_complex is True assert r.is_noninteger is True assert r.is_irrational is False assert r.is_imaginary is False assert r.is_positive is True assert r.is_negative is False assert r.is_nonpositive is False assert r.is_nonnegative is True assert r.is_even is False assert r.is_odd is False assert r.is_finite is True assert r.is_infinite is False assert r.is_comparable is True assert r.is_prime is False assert r.is_composite is False r = Rational(1, 4) assert r.is_nonpositive is False assert r.is_positive is True assert r.is_negative is False assert r.is_nonnegative is True r = Rational(5, 4) assert r.is_negative is False assert r.is_positive is True assert r.is_nonpositive is False assert r.is_nonnegative is True r = Rational(5, 3) assert r.is_nonnegative is True assert r.is_positive is True assert r.is_negative is False assert r.is_nonpositive is False def test_neg_rational(): r = Rational(-3, 4) assert r.is_positive is False assert r.is_nonpositive is True assert r.is_negative is True assert r.is_nonnegative is False r = Rational(-1, 4) assert r.is_nonpositive is True assert r.is_positive is False assert r.is_negative is True assert r.is_nonnegative is False r = Rational(-5, 4) assert r.is_negative is True assert r.is_positive is False assert r.is_nonpositive is True assert r.is_nonnegative is False r = Rational(-5, 3) assert r.is_nonnegative is False assert r.is_positive is False assert r.is_negative is True assert r.is_nonpositive is True def test_pi(): z = S.Pi assert z.is_commutative is True assert z.is_integer is False assert z.is_rational is False assert z.is_algebraic is False assert z.is_transcendental is True assert z.is_real is True assert z.is_complex is True assert z.is_noninteger is True assert z.is_irrational is True assert z.is_imaginary is False assert z.is_positive is True assert z.is_negative is False assert z.is_nonpositive is False assert z.is_nonnegative is True assert z.is_even is False assert z.is_odd is False assert z.is_finite is True assert z.is_infinite is False assert z.is_comparable is True assert z.is_prime is False assert z.is_composite is False def test_E(): z = S.Exp1 assert z.is_commutative is True assert z.is_integer is False assert z.is_rational is False assert z.is_algebraic is False assert z.is_transcendental is True assert z.is_real is True assert z.is_complex is True assert z.is_noninteger is True assert z.is_irrational is True assert z.is_imaginary is False assert z.is_positive is True assert z.is_negative is False assert z.is_nonpositive is False assert z.is_nonnegative is True assert z.is_even is False assert z.is_odd is False assert z.is_finite is True assert z.is_infinite is False assert z.is_comparable is True assert z.is_prime is False assert z.is_composite is False def test_I(): z = S.ImaginaryUnit assert z.is_commutative is True assert z.is_integer is False assert z.is_rational is False assert z.is_algebraic is True assert z.is_transcendental is False assert z.is_real is False assert z.is_complex is True assert z.is_noninteger is False assert z.is_irrational is False assert z.is_imaginary is True assert z.is_positive is False assert z.is_negative is False assert z.is_nonpositive is False assert z.is_nonnegative is False assert z.is_even is False assert z.is_odd is False assert z.is_finite is True assert z.is_infinite is False assert z.is_comparable is False assert z.is_prime is False assert z.is_composite is False def test_symbol_real_false(): # issue 3848 a = Symbol('a', real=False) assert a.is_real is False assert a.is_integer is False assert a.is_zero is False assert a.is_negative is False assert a.is_positive is False assert a.is_nonnegative is False assert a.is_nonpositive is False assert a.is_nonzero is False assert a.is_extended_negative is None assert a.is_extended_positive is None assert a.is_extended_nonnegative is None assert a.is_extended_nonpositive is None assert a.is_extended_nonzero is None def test_symbol_extended_real_false(): # issue 3848 a = Symbol('a', extended_real=False) assert a.is_real is False assert a.is_integer is False assert a.is_zero is False assert a.is_negative is False assert a.is_positive is False assert a.is_nonnegative is False assert a.is_nonpositive is False assert a.is_nonzero is False assert a.is_extended_negative is False assert a.is_extended_positive is False assert a.is_extended_nonnegative is False assert a.is_extended_nonpositive is False assert a.is_extended_nonzero is False def test_symbol_imaginary(): a = Symbol('a', imaginary=True) assert a.is_real is False assert a.is_integer is False assert a.is_negative is False assert a.is_positive is False assert a.is_nonnegative is False assert a.is_nonpositive is False assert a.is_zero is False assert a.is_nonzero is False # since nonzero -> real def test_symbol_zero(): x = Symbol('x', zero=True) assert x.is_positive is False assert x.is_nonpositive assert x.is_negative is False assert x.is_nonnegative assert x.is_zero is True # TODO Change to x.is_nonzero is None # See https://github.com/sympy/sympy/pull/9583 assert x.is_nonzero is False assert x.is_finite is True def test_symbol_positive(): x = Symbol('x', positive=True) assert x.is_positive is True assert x.is_nonpositive is False assert x.is_negative is False assert x.is_nonnegative is True assert x.is_zero is False assert x.is_nonzero is True def test_neg_symbol_positive(): x = -Symbol('x', positive=True) assert x.is_positive is False assert x.is_nonpositive is True assert x.is_negative is True assert x.is_nonnegative is False assert x.is_zero is False assert x.is_nonzero is True def test_symbol_nonpositive(): x = Symbol('x', nonpositive=True) assert x.is_positive is False assert x.is_nonpositive is True assert x.is_negative is None assert x.is_nonnegative is None assert x.is_zero is None assert x.is_nonzero is None def test_neg_symbol_nonpositive(): x = -Symbol('x', nonpositive=True) assert x.is_positive is None assert x.is_nonpositive is None assert x.is_negative is False assert x.is_nonnegative is True assert x.is_zero is None assert x.is_nonzero is None def test_symbol_falsepositive(): x = Symbol('x', positive=False) assert x.is_positive is False assert x.is_nonpositive is None assert x.is_negative is None assert x.is_nonnegative is None assert x.is_zero is None assert x.is_nonzero is None def test_symbol_falsepositive_mul(): # To test pull request 9379 # Explicit handling of arg.is_positive=False was added to Mul._eval_is_positive x = 2*Symbol('x', positive=False) assert x.is_positive is False # This was None before assert x.is_nonpositive is None assert x.is_negative is None assert x.is_nonnegative is None assert x.is_zero is None assert x.is_nonzero is None @XFAIL def test_symbol_infinitereal_mul(): ix = Symbol('ix', infinite=True, extended_real=True) assert (-ix).is_extended_positive is None def test_neg_symbol_falsepositive(): x = -Symbol('x', positive=False) assert x.is_positive is None assert x.is_nonpositive is None assert x.is_negative is False assert x.is_nonnegative is None assert x.is_zero is None assert x.is_nonzero is None def test_neg_symbol_falsenegative(): # To test pull request 9379 # Explicit handling of arg.is_negative=False was added to Mul._eval_is_positive x = -Symbol('x', negative=False) assert x.is_positive is False # This was None before assert x.is_nonpositive is None assert x.is_negative is None assert x.is_nonnegative is None assert x.is_zero is None assert x.is_nonzero is None def test_symbol_falsepositive_real(): x = Symbol('x', positive=False, real=True) assert x.is_positive is False assert x.is_nonpositive is True assert x.is_negative is None assert x.is_nonnegative is None assert x.is_zero is None assert x.is_nonzero is None def test_neg_symbol_falsepositive_real(): x = -Symbol('x', positive=False, real=True) assert x.is_positive is None assert x.is_nonpositive is None assert x.is_negative is False assert x.is_nonnegative is True assert x.is_zero is None assert x.is_nonzero is None def test_symbol_falsenonnegative(): x = Symbol('x', nonnegative=False) assert x.is_positive is False assert x.is_nonpositive is None assert x.is_negative is None assert x.is_nonnegative is False assert x.is_zero is False assert x.is_nonzero is None @XFAIL def test_neg_symbol_falsenonnegative(): x = -Symbol('x', nonnegative=False) assert x.is_positive is None assert x.is_nonpositive is False # this currently returns None assert x.is_negative is False # this currently returns None assert x.is_nonnegative is None assert x.is_zero is False # this currently returns None assert x.is_nonzero is True # this currently returns None def test_symbol_falsenonnegative_real(): x = Symbol('x', nonnegative=False, real=True) assert x.is_positive is False assert x.is_nonpositive is True assert x.is_negative is True assert x.is_nonnegative is False assert x.is_zero is False assert x.is_nonzero is True def test_neg_symbol_falsenonnegative_real(): x = -Symbol('x', nonnegative=False, real=True) assert x.is_positive is True assert x.is_nonpositive is False assert x.is_negative is False assert x.is_nonnegative is True assert x.is_zero is False assert x.is_nonzero is True def test_prime(): assert S.NegativeOne.is_prime is False assert S(-2).is_prime is False assert S(-4).is_prime is False assert S.Zero.is_prime is False assert S.One.is_prime is False assert S(2).is_prime is True assert S(17).is_prime is True assert S(4).is_prime is False def test_composite(): assert S.NegativeOne.is_composite is False assert S(-2).is_composite is False assert S(-4).is_composite is False assert S.Zero.is_composite is False assert S(2).is_composite is False assert S(17).is_composite is False assert S(4).is_composite is True x = Dummy(integer=True, positive=True, prime=False) assert x.is_composite is None # x could be 1 assert (x + 1).is_composite is None x = Dummy(positive=True, even=True, prime=False) assert x.is_integer is True assert x.is_composite is True def test_prime_symbol(): x = Symbol('x', prime=True) assert x.is_prime is True assert x.is_integer is True assert x.is_positive is True assert x.is_negative is False assert x.is_nonpositive is False assert x.is_nonnegative is True x = Symbol('x', prime=False) assert x.is_prime is False assert x.is_integer is None assert x.is_positive is None assert x.is_negative is None assert x.is_nonpositive is None assert x.is_nonnegative is None def test_symbol_noncommutative(): x = Symbol('x', commutative=True) assert x.is_complex is None x = Symbol('x', commutative=False) assert x.is_integer is False assert x.is_rational is False assert x.is_algebraic is False assert x.is_irrational is False assert x.is_real is False assert x.is_complex is False def test_other_symbol(): x = Symbol('x', integer=True) assert x.is_integer is True assert x.is_real is True assert x.is_finite is True x = Symbol('x', integer=True, nonnegative=True) assert x.is_integer is True assert x.is_nonnegative is True assert x.is_negative is False assert x.is_positive is None assert x.is_finite is True x = Symbol('x', integer=True, nonpositive=True) assert x.is_integer is True assert x.is_nonpositive is True assert x.is_positive is False assert x.is_negative is None assert x.is_finite is True x = Symbol('x', odd=True) assert x.is_odd is True assert x.is_even is False assert x.is_integer is True assert x.is_finite is True x = Symbol('x', odd=False) assert x.is_odd is False assert x.is_even is None assert x.is_integer is None assert x.is_finite is None x = Symbol('x', even=True) assert x.is_even is True assert x.is_odd is False assert x.is_integer is True assert x.is_finite is True x = Symbol('x', even=False) assert x.is_even is False assert x.is_odd is None assert x.is_integer is None assert x.is_finite is None x = Symbol('x', integer=True, nonnegative=True) assert x.is_integer is True assert x.is_nonnegative is True assert x.is_finite is True x = Symbol('x', integer=True, nonpositive=True) assert x.is_integer is True assert x.is_nonpositive is True assert x.is_finite is True x = Symbol('x', rational=True) assert x.is_real is True assert x.is_finite is True x = Symbol('x', rational=False) assert x.is_real is None assert x.is_finite is None x = Symbol('x', irrational=True) assert x.is_real is True assert x.is_finite is True x = Symbol('x', irrational=False) assert x.is_real is None assert x.is_finite is None with raises(AttributeError): x.is_real = False x = Symbol('x', algebraic=True) assert x.is_transcendental is False x = Symbol('x', transcendental=True) assert x.is_algebraic is False assert x.is_rational is False assert x.is_integer is False def test_issue_3825(): """catch: hash instability""" x = Symbol("x") y = Symbol("y") a1 = x + y a2 = y + x a2.is_comparable h1 = hash(a1) h2 = hash(a2) assert h1 == h2 def test_issue_4822(): z = (-1)**Rational(1, 3)*(1 - I*sqrt(3)) assert z.is_real in [True, None] def test_hash_vs_typeinfo(): """seemingly different typeinfo, but in fact equal""" # the following two are semantically equal x1 = Symbol('x', even=True) x2 = Symbol('x', integer=True, odd=False) assert hash(x1) == hash(x2) assert x1 == x2 def test_hash_vs_typeinfo_2(): """different typeinfo should mean !eq""" # the following two are semantically different x = Symbol('x') x1 = Symbol('x', even=True) assert x != x1 assert hash(x) != hash(x1) # This might fail with very low probability def test_hash_vs_eq(): """catch: different hash for equal objects""" a = 1 + S.Pi # important: do not fold it into a Number instance ha = hash(a) # it should be Add/Mul/... to trigger the bug a.is_positive # this uses .evalf() and deduces it is positive assert a.is_positive is True # be sure that hash stayed the same assert ha == hash(a) # now b should be the same expression b = a.expand(trig=True) hb = hash(b) assert a == b assert ha == hb def test_Add_is_pos_neg(): # these cover lines not covered by the rest of tests in core n = Symbol('n', extended_negative=True, infinite=True) nn = Symbol('n', extended_nonnegative=True, infinite=True) np = Symbol('n', extended_nonpositive=True, infinite=True) p = Symbol('p', extended_positive=True, infinite=True) r = Dummy(extended_real=True, finite=False) x = Symbol('x') xf = Symbol('xf', finite=True) assert (n + p).is_extended_positive is None assert (n + x).is_extended_positive is None assert (p + x).is_extended_positive is None assert (n + p).is_extended_negative is None assert (n + x).is_extended_negative is None assert (p + x).is_extended_negative is None assert (n + xf).is_extended_positive is False assert (p + xf).is_extended_positive is True assert (n + xf).is_extended_negative is True assert (p + xf).is_extended_negative is False assert (x - S.Infinity).is_extended_negative is None # issue 7798 # issue 8046, 16.2 assert (p + nn).is_extended_positive assert (n + np).is_extended_negative assert (p + r).is_extended_positive is None def test_Add_is_imaginary(): nn = Dummy(nonnegative=True) assert (I*nn + I).is_imaginary # issue 8046, 17 def test_Add_is_algebraic(): a = Symbol('a', algebraic=True) b = Symbol('a', algebraic=True) na = Symbol('na', algebraic=False) nb = Symbol('nb', algebraic=False) x = Symbol('x') assert (a + b).is_algebraic assert (na + nb).is_algebraic is None assert (a + na).is_algebraic is False assert (a + x).is_algebraic is None assert (na + x).is_algebraic is None def test_Mul_is_algebraic(): a = Symbol('a', algebraic=True) b = Symbol('b', algebraic=True) na = Symbol('na', algebraic=False) an = Symbol('an', algebraic=True, nonzero=True) nb = Symbol('nb', algebraic=False) x = Symbol('x') assert (a*b).is_algebraic is True assert (na*nb).is_algebraic is None assert (a*na).is_algebraic is None assert (an*na).is_algebraic is False assert (a*x).is_algebraic is None assert (na*x).is_algebraic is None def test_Pow_is_algebraic(): e = Symbol('e', algebraic=True) assert Pow(1, e, evaluate=False).is_algebraic assert Pow(0, e, evaluate=False).is_algebraic a = Symbol('a', algebraic=True) azf = Symbol('azf', algebraic=True, zero=False) na = Symbol('na', algebraic=False) ia = Symbol('ia', algebraic=True, irrational=True) ib = Symbol('ib', algebraic=True, irrational=True) r = Symbol('r', rational=True) x = Symbol('x') assert (a**2).is_algebraic is True assert (a**r).is_algebraic is None assert (azf**r).is_algebraic is True assert (a**x).is_algebraic is None assert (na**r).is_algebraic is None assert (ia**r).is_algebraic is True assert (ia**ib).is_algebraic is False assert (a**e).is_algebraic is None # Gelfond-Schneider constant: assert Pow(2, sqrt(2), evaluate=False).is_algebraic is False assert Pow(S.GoldenRatio, sqrt(3), evaluate=False).is_algebraic is False # issue 8649 t = Symbol('t', real=True, transcendental=True) n = Symbol('n', integer=True) assert (t**n).is_algebraic is None assert (t**n).is_integer is None assert (pi**3).is_algebraic is False r = Symbol('r', zero=True) assert (pi**r).is_algebraic is True def test_Mul_is_prime_composite(): x = Symbol('x', positive=True, integer=True) y = Symbol('y', positive=True, integer=True) assert (x*y).is_prime is None assert ( (x+1)*(y+1) ).is_prime is False assert ( (x+1)*(y+1) ).is_composite is True x = Symbol('x', positive=True) assert ( (x+1)*(y+1) ).is_prime is None assert ( (x+1)*(y+1) ).is_composite is None def test_Pow_is_pos_neg(): z = Symbol('z', real=True) w = Symbol('w', nonpositive=True) assert (S.NegativeOne**S(2)).is_positive is True assert (S.One**z).is_positive is True assert (S.NegativeOne**S(3)).is_positive is False assert (S.Zero**S.Zero).is_positive is True # 0**0 is 1 assert (w**S(3)).is_positive is False assert (w**S(2)).is_positive is None assert (I**2).is_positive is False assert (I**4).is_positive is True # tests emerging from #16332 issue p = Symbol('p', zero=True) q = Symbol('q', zero=False, real=True) j = Symbol('j', zero=False, even=True) x = Symbol('x', zero=True) y = Symbol('y', zero=True) assert (p**q).is_positive is False assert (p**q).is_negative is False assert (p**j).is_positive is False assert (x**y).is_positive is True # 0**0 assert (x**y).is_negative is False def test_Pow_is_prime_composite(): x = Symbol('x', positive=True, integer=True) y = Symbol('y', positive=True, integer=True) assert (x**y).is_prime is None assert ( x**(y+1) ).is_prime is False assert ( x**(y+1) ).is_composite is None assert ( (x+1)**(y+1) ).is_composite is True assert ( (-x-1)**(2*y) ).is_composite is True x = Symbol('x', positive=True) assert (x**y).is_prime is None def test_Mul_is_infinite(): x = Symbol('x') f = Symbol('f', finite=True) i = Symbol('i', infinite=True) z = Dummy(zero=True) nzf = Dummy(finite=True, zero=False) from sympy.core.mul import Mul assert (x*f).is_finite is None assert (x*i).is_finite is None assert (f*i).is_finite is None assert (x*f*i).is_finite is None assert (z*i).is_finite is None assert (nzf*i).is_finite is False assert (z*f).is_finite is True assert Mul(0, f, evaluate=False).is_finite is True assert Mul(0, i, evaluate=False).is_finite is None assert (x*f).is_infinite is None assert (x*i).is_infinite is None assert (f*i).is_infinite is None assert (x*f*i).is_infinite is None assert (z*i).is_infinite is S.NaN.is_infinite assert (nzf*i).is_infinite is True assert (z*f).is_infinite is False assert Mul(0, f, evaluate=False).is_infinite is False assert Mul(0, i, evaluate=False).is_infinite is S.NaN.is_infinite def test_Add_is_infinite(): x = Symbol('x') f = Symbol('f', finite=True) i = Symbol('i', infinite=True) i2 = Symbol('i2', infinite=True) z = Dummy(zero=True) nzf = Dummy(finite=True, zero=False) from sympy.core.add import Add assert (x+f).is_finite is None assert (x+i).is_finite is None assert (f+i).is_finite is False assert (x+f+i).is_finite is None assert (z+i).is_finite is False assert (nzf+i).is_finite is False assert (z+f).is_finite is True assert (i+i2).is_finite is None assert Add(0, f, evaluate=False).is_finite is True assert Add(0, i, evaluate=False).is_finite is False assert (x+f).is_infinite is None assert (x+i).is_infinite is None assert (f+i).is_infinite is True assert (x+f+i).is_infinite is None assert (z+i).is_infinite is True assert (nzf+i).is_infinite is True assert (z+f).is_infinite is False assert (i+i2).is_infinite is None assert Add(0, f, evaluate=False).is_infinite is False assert Add(0, i, evaluate=False).is_infinite is True def test_special_is_rational(): i = Symbol('i', integer=True) i2 = Symbol('i2', integer=True) ni = Symbol('ni', integer=True, nonzero=True) r = Symbol('r', rational=True) rn = Symbol('r', rational=True, nonzero=True) nr = Symbol('nr', irrational=True) x = Symbol('x') assert sqrt(3).is_rational is False assert (3 + sqrt(3)).is_rational is False assert (3*sqrt(3)).is_rational is False assert exp(3).is_rational is False assert exp(ni).is_rational is False assert exp(rn).is_rational is False assert exp(x).is_rational is None assert exp(log(3), evaluate=False).is_rational is True assert log(exp(3), evaluate=False).is_rational is True assert log(3).is_rational is False assert log(ni + 1).is_rational is False assert log(rn + 1).is_rational is False assert log(x).is_rational is None assert (sqrt(3) + sqrt(5)).is_rational is None assert (sqrt(3) + S.Pi).is_rational is False assert (x**i).is_rational is None assert (i**i).is_rational is True assert (i**i2).is_rational is None assert (r**i).is_rational is None assert (r**r).is_rational is None assert (r**x).is_rational is None assert (nr**i).is_rational is None # issue 8598 assert (nr**Symbol('z', zero=True)).is_rational assert sin(1).is_rational is False assert sin(ni).is_rational is False assert sin(rn).is_rational is False assert sin(x).is_rational is None assert asin(r).is_rational is False assert sin(asin(3), evaluate=False).is_rational is True @XFAIL def test_issue_6275(): x = Symbol('x') # both zero or both Muls...but neither "change would be very appreciated. # This is similar to x/x => 1 even though if x = 0, it is really nan. assert isinstance(x*0, type(0*S.Infinity)) if 0*S.Infinity is S.NaN: b = Symbol('b', finite=None) assert (b*0).is_zero is None def test_sanitize_assumptions(): # issue 6666 for cls in (Symbol, Dummy, Wild): x = cls('x', real=1, positive=0) assert x.is_real is True assert x.is_positive is False assert cls('', real=True, positive=None).is_positive is None raises(ValueError, lambda: cls('', commutative=None)) raises(ValueError, lambda: Symbol._sanitize(dict(commutative=None))) def test_special_assumptions(): e = -3 - sqrt(5) + (-sqrt(10)/2 - sqrt(2)/2)**2 assert simplify(e < 0) is S.false assert simplify(e > 0) is S.false assert (e == 0) is False # it's not a literal 0 assert e.equals(0) is True def test_inconsistent(): # cf. issues 5795 and 5545 raises(InconsistentAssumptions, lambda: Symbol('x', real=True, commutative=False)) def test_issue_6631(): assert ((-1)**(I)).is_real is True assert ((-1)**(I*2)).is_real is True assert ((-1)**(I/2)).is_real is True assert ((-1)**(I*S.Pi)).is_real is True assert (I**(I + 2)).is_real is True def test_issue_2730(): assert (1/(1 + I)).is_real is False def test_issue_4149(): assert (3 + I).is_complex assert (3 + I).is_imaginary is False assert (3*I + S.Pi*I).is_imaginary # as Zero.is_imaginary is False, see issue 7649 y = Symbol('y', real=True) assert (3*I + S.Pi*I + y*I).is_imaginary is None p = Symbol('p', positive=True) assert (3*I + S.Pi*I + p*I).is_imaginary n = Symbol('n', negative=True) assert (-3*I - S.Pi*I + n*I).is_imaginary i = Symbol('i', imaginary=True) assert ([(i**a).is_imaginary for a in range(4)] == [False, True, False, True]) # tests from the PR #7887: e = S("-sqrt(3)*I/2 + 0.866025403784439*I") assert e.is_real is False assert e.is_imaginary def test_issue_2920(): n = Symbol('n', negative=True) assert sqrt(n).is_imaginary def test_issue_7899(): x = Symbol('x', real=True) assert (I*x).is_real is None assert ((x - I)*(x - 1)).is_zero is None assert ((x - I)*(x - 1)).is_real is None @XFAIL def test_issue_7993(): x = Dummy(integer=True) y = Dummy(noninteger=True) assert (x - y).is_zero is False def test_issue_8075(): raises(InconsistentAssumptions, lambda: Dummy(zero=True, finite=False)) raises(InconsistentAssumptions, lambda: Dummy(zero=True, infinite=True)) def test_issue_8642(): x = Symbol('x', real=True, integer=False) assert (x*2).is_integer is None, (x*2).is_integer def test_issues_8632_8633_8638_8675_8992(): p = Dummy(integer=True, positive=True) nn = Dummy(integer=True, nonnegative=True) assert (p - S.Half).is_positive assert (p - 1).is_nonnegative assert (nn + 1).is_positive assert (-p + 1).is_nonpositive assert (-nn - 1).is_negative prime = Dummy(prime=True) assert (prime - 2).is_nonnegative assert (prime - 3).is_nonnegative is None even = Dummy(positive=True, even=True) assert (even - 2).is_nonnegative p = Dummy(positive=True) assert (p/(p + 1) - 1).is_negative assert ((p + 2)**3 - S.Half).is_positive n = Dummy(negative=True) assert (n - 3).is_nonpositive def test_issue_9115_9150(): n = Dummy('n', integer=True, nonnegative=True) assert (factorial(n) >= 1) == True assert (factorial(n) < 1) == False assert factorial(n + 1).is_even is None assert factorial(n + 2).is_even is True assert factorial(n + 2) >= 2 def test_issue_9165(): z = Symbol('z', zero=True) f = Symbol('f', finite=False) assert 0/z is S.NaN assert 0*(1/z) is S.NaN assert 0*f is S.NaN def test_issue_10024(): x = Dummy('x') assert Mod(x, 2*pi).is_zero is None def test_issue_10302(): x = Symbol('x') r = Symbol('r', real=True) u = -(3*2**pi)**(1/pi) + 2*3**(1/pi) i = u + u*I assert i.is_real is None # w/o simplification this should fail assert (u + i).is_zero is None assert (1 + i).is_zero is False a = Dummy('a', zero=True) assert (a + I).is_zero is False assert (a + r*I).is_zero is None assert (a + I).is_imaginary assert (a + x + I).is_imaginary is None assert (a + r*I + I).is_imaginary is None def test_complex_reciprocal_imaginary(): assert (1 / (4 + 3*I)).is_imaginary is False def test_issue_16313(): x = Symbol('x', extended_real=False) k = Symbol('k', real=True) l = Symbol('l', real=True, zero=False) assert (-x).is_real is False assert (k*x).is_real is None # k can be zero also assert (l*x).is_real is False assert (l*x*x).is_real is None # since x*x can be a real number assert (-x).is_positive is False def test_issue_16579(): # extended_real -> finite | infinite x = Symbol('x', extended_real=True, infinite=False) y = Symbol('y', extended_real=True, finite=False) assert x.is_finite is True assert y.is_infinite is True # With PR 16978, complex now implies finite c = Symbol('c', complex=True) assert c.is_finite is True raises(InconsistentAssumptions, lambda: Dummy(complex=True, finite=False)) # Now infinite == !finite nf = Symbol('nf', finite=False) assert nf.is_infinite is True def test_issue_17556(): z = I*oo assert z.is_imaginary is False assert z.is_finite is False def test_issue_21651(): k = Symbol('k', positive=True, integer=True) exp = 2*2**(-k) assert exp.is_integer is None def test_assumptions_copy(): assert assumptions(Symbol('x'), dict(commutative=True) ) == {'commutative': True} assert assumptions(Symbol('x'), ['integer']) == {} assert assumptions(Symbol('x'), ['commutative'] ) == {'commutative': True} assert assumptions(Symbol('x')) == {'commutative': True} assert assumptions(1)['positive'] assert assumptions(3 + I) == { 'algebraic': True, 'commutative': True, 'complex': True, 'composite': False, 'even': False, 'extended_negative': False, 'extended_nonnegative': False, 'extended_nonpositive': False, 'extended_nonzero': False, 'extended_positive': False, 'extended_real': False, 'finite': True, 'imaginary': False, 'infinite': False, 'integer': False, 'irrational': False, 'negative': False, 'noninteger': False, 'nonnegative': False, 'nonpositive': False, 'nonzero': False, 'odd': False, 'positive': False, 'prime': False, 'rational': False, 'real': False, 'transcendental': False, 'zero': False} def test_check_assumptions(): assert check_assumptions(1, 0) is False x = Symbol('x', positive=True) assert check_assumptions(1, x) is True assert check_assumptions(1, 1) is True assert check_assumptions(-1, 1) is False i = Symbol('i', integer=True) # don't know if i is positive (or prime, etc...) assert check_assumptions(i, 1) is None assert check_assumptions(Dummy(integer=None), integer=True) is None assert check_assumptions(Dummy(integer=None), integer=False) is None assert check_assumptions(Dummy(integer=False), integer=True) is False assert check_assumptions(Dummy(integer=True), integer=False) is False # no T/F assumptions to check assert check_assumptions(Dummy(integer=False), integer=None) is True raises(ValueError, lambda: check_assumptions(2*x, x, positive=True)) def test_failing_assumptions(): x = Symbol('x', positive=True) y = Symbol('y') assert failing_assumptions(6*x + y, **x.assumptions0) == \ {'real': None, 'imaginary': None, 'complex': None, 'hermitian': None, 'positive': None, 'nonpositive': None, 'nonnegative': None, 'nonzero': None, 'negative': None, 'zero': None, 'extended_real': None, 'finite': None, 'infinite': None, 'extended_negative': None, 'extended_nonnegative': None, 'extended_nonpositive': None, 'extended_nonzero': None, 'extended_positive': None } def test_common_assumptions(): assert common_assumptions([0, 1, 2] ) == {'algebraic': True, 'irrational': False, 'hermitian': True, 'extended_real': True, 'real': True, 'extended_negative': False, 'extended_nonnegative': True, 'integer': True, 'rational': True, 'imaginary': False, 'complex': True, 'commutative': True,'noninteger': False, 'composite': False, 'infinite': False, 'nonnegative': True, 'finite': True, 'transcendental': False,'negative': False} assert common_assumptions([0, 1, 2], 'positive integer'.split() ) == {'integer': True} assert common_assumptions([0, 1, 2], []) == {} assert common_assumptions([], ['integer']) == {} assert common_assumptions([0], ['integer']) == {'integer': True}
4c798408b451ecc7c621fae676a925de34a1f95d71f1a934c25e34c4789979f2
from sympy.core.logic import fuzzy_and from sympy.core.sympify import _sympify from sympy.multipledispatch import dispatch from sympy.testing.pytest import XFAIL, raises, warns_deprecated_sympy from sympy.assumptions.ask import Q from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.expr import Expr from sympy.core.function import Function from sympy.core.mul import Mul from sympy.core.numbers import (Float, I, Rational, nan, oo, pi, zoo) from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.exponential import (exp, exp_polar, log) from sympy.functions.elementary.integers import (ceiling, floor) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.logic.boolalg import (And, Implies, Not, Or, Xor) from sympy.sets import Reals from sympy.simplify.simplify import simplify from sympy.simplify.trigsimp import trigsimp from sympy.core.relational import (Relational, Equality, Unequality, GreaterThan, LessThan, StrictGreaterThan, StrictLessThan, Rel, Eq, Lt, Le, Gt, Ge, Ne, is_le, is_gt, is_ge, is_lt, is_eq, is_neq) from sympy.sets.sets import Interval, FiniteSet from itertools import combinations x, y, z, t = symbols('x,y,z,t') def rel_check(a, b): from sympy.testing.pytest import raises assert a.is_number and b.is_number for do in range(len({type(a), type(b)})): if S.NaN in (a, b): v = [(a == b), (a != b)] assert len(set(v)) == 1 and v[0] == False assert not (a != b) and not (a == b) assert raises(TypeError, lambda: a < b) assert raises(TypeError, lambda: a <= b) assert raises(TypeError, lambda: a > b) assert raises(TypeError, lambda: a >= b) else: E = [(a == b), (a != b)] assert len(set(E)) == 2 v = [ (a < b), (a <= b), (a > b), (a >= b)] i = [ [True, True, False, False], [False, True, False, True], # <-- i == 1 [False, False, True, True]].index(v) if i == 1: assert E[0] or (a.is_Float != b.is_Float) # ugh else: assert E[1] a, b = b, a return True def test_rel_ne(): assert Relational(x, y, '!=') == Ne(x, y) # issue 6116 p = Symbol('p', positive=True) assert Ne(p, 0) is S.true def test_rel_subs(): e = Relational(x, y, '==') e = e.subs(x, z) assert isinstance(e, Equality) assert e.lhs == z assert e.rhs == y e = Relational(x, y, '>=') e = e.subs(x, z) assert isinstance(e, GreaterThan) assert e.lhs == z assert e.rhs == y e = Relational(x, y, '<=') e = e.subs(x, z) assert isinstance(e, LessThan) assert e.lhs == z assert e.rhs == y e = Relational(x, y, '>') e = e.subs(x, z) assert isinstance(e, StrictGreaterThan) assert e.lhs == z assert e.rhs == y e = Relational(x, y, '<') e = e.subs(x, z) assert isinstance(e, StrictLessThan) assert e.lhs == z assert e.rhs == y e = Eq(x, 0) assert e.subs(x, 0) is S.true assert e.subs(x, 1) is S.false def test_wrappers(): e = x + x**2 res = Relational(y, e, '==') assert Rel(y, x + x**2, '==') == res assert Eq(y, x + x**2) == res res = Relational(y, e, '<') assert Lt(y, x + x**2) == res res = Relational(y, e, '<=') assert Le(y, x + x**2) == res res = Relational(y, e, '>') assert Gt(y, x + x**2) == res res = Relational(y, e, '>=') assert Ge(y, x + x**2) == res res = Relational(y, e, '!=') assert Ne(y, x + x**2) == res def test_Eq_Ne(): assert Eq(x, x) # issue 5719 with warns_deprecated_sympy(): assert Eq(x) == Eq(x, 0) # issue 6116 p = Symbol('p', positive=True) assert Eq(p, 0) is S.false # issue 13348; 19048 # SymPy is strict about 0 and 1 not being # interpreted as Booleans assert Eq(True, 1) is S.false assert Eq(False, 0) is S.false assert Eq(~x, 0) is S.false assert Eq(~x, 1) is S.false assert Ne(True, 1) is S.true assert Ne(False, 0) is S.true assert Ne(~x, 0) is S.true assert Ne(~x, 1) is S.true assert Eq((), 1) is S.false assert Ne((), 1) is S.true def test_as_poly(): from sympy.polys.polytools import Poly # Only Eq should have an as_poly method: assert Eq(x, 1).as_poly() == Poly(x - 1, x, domain='ZZ') raises(AttributeError, lambda: Ne(x, 1).as_poly()) raises(AttributeError, lambda: Ge(x, 1).as_poly()) raises(AttributeError, lambda: Gt(x, 1).as_poly()) raises(AttributeError, lambda: Le(x, 1).as_poly()) raises(AttributeError, lambda: Lt(x, 1).as_poly()) def test_rel_Infinity(): # NOTE: All of these are actually handled by sympy.core.Number, and do # not create Relational objects. assert (oo > oo) is S.false assert (oo > -oo) is S.true assert (oo > 1) is S.true assert (oo < oo) is S.false assert (oo < -oo) is S.false assert (oo < 1) is S.false assert (oo >= oo) is S.true assert (oo >= -oo) is S.true assert (oo >= 1) is S.true assert (oo <= oo) is S.true assert (oo <= -oo) is S.false assert (oo <= 1) is S.false assert (-oo > oo) is S.false assert (-oo > -oo) is S.false assert (-oo > 1) is S.false assert (-oo < oo) is S.true assert (-oo < -oo) is S.false assert (-oo < 1) is S.true assert (-oo >= oo) is S.false assert (-oo >= -oo) is S.true assert (-oo >= 1) is S.false assert (-oo <= oo) is S.true assert (-oo <= -oo) is S.true assert (-oo <= 1) is S.true def test_infinite_symbol_inequalities(): x = Symbol('x', extended_positive=True, infinite=True) y = Symbol('y', extended_positive=True, infinite=True) z = Symbol('z', extended_negative=True, infinite=True) w = Symbol('w', extended_negative=True, infinite=True) inf_set = (x, y, oo) ninf_set = (z, w, -oo) for inf1 in inf_set: assert (inf1 < 1) is S.false assert (inf1 > 1) is S.true assert (inf1 <= 1) is S.false assert (inf1 >= 1) is S.true for inf2 in inf_set: assert (inf1 < inf2) is S.false assert (inf1 > inf2) is S.false assert (inf1 <= inf2) is S.true assert (inf1 >= inf2) is S.true for ninf1 in ninf_set: assert (inf1 < ninf1) is S.false assert (inf1 > ninf1) is S.true assert (inf1 <= ninf1) is S.false assert (inf1 >= ninf1) is S.true assert (ninf1 < inf1) is S.true assert (ninf1 > inf1) is S.false assert (ninf1 <= inf1) is S.true assert (ninf1 >= inf1) is S.false for ninf1 in ninf_set: assert (ninf1 < 1) is S.true assert (ninf1 > 1) is S.false assert (ninf1 <= 1) is S.true assert (ninf1 >= 1) is S.false for ninf2 in ninf_set: assert (ninf1 < ninf2) is S.false assert (ninf1 > ninf2) is S.false assert (ninf1 <= ninf2) is S.true assert (ninf1 >= ninf2) is S.true def test_bool(): assert Eq(0, 0) is S.true assert Eq(1, 0) is S.false assert Ne(0, 0) is S.false assert Ne(1, 0) is S.true assert Lt(0, 1) is S.true assert Lt(1, 0) is S.false assert Le(0, 1) is S.true assert Le(1, 0) is S.false assert Le(0, 0) is S.true assert Gt(1, 0) is S.true assert Gt(0, 1) is S.false assert Ge(1, 0) is S.true assert Ge(0, 1) is S.false assert Ge(1, 1) is S.true assert Eq(I, 2) is S.false assert Ne(I, 2) is S.true raises(TypeError, lambda: Gt(I, 2)) raises(TypeError, lambda: Ge(I, 2)) raises(TypeError, lambda: Lt(I, 2)) raises(TypeError, lambda: Le(I, 2)) a = Float('.000000000000000000001', '') b = Float('.0000000000000000000001', '') assert Eq(pi + a, pi + b) is S.false def test_rich_cmp(): assert (x < y) == Lt(x, y) assert (x <= y) == Le(x, y) assert (x > y) == Gt(x, y) assert (x >= y) == Ge(x, y) def test_doit(): from sympy.core.symbol import Symbol p = Symbol('p', positive=True) n = Symbol('n', negative=True) np = Symbol('np', nonpositive=True) nn = Symbol('nn', nonnegative=True) assert Gt(p, 0).doit() is S.true assert Gt(p, 1).doit() == Gt(p, 1) assert Ge(p, 0).doit() is S.true assert Le(p, 0).doit() is S.false assert Lt(n, 0).doit() is S.true assert Le(np, 0).doit() is S.true assert Gt(nn, 0).doit() == Gt(nn, 0) assert Lt(nn, 0).doit() is S.false assert Eq(x, 0).doit() == Eq(x, 0) def test_new_relational(): x = Symbol('x') assert Eq(x, 0) == Relational(x, 0) # None ==> Equality assert Eq(x, 0) == Relational(x, 0, '==') assert Eq(x, 0) == Relational(x, 0, 'eq') assert Eq(x, 0) == Equality(x, 0) assert Eq(x, 0) != Relational(x, 1) # None ==> Equality assert Eq(x, 0) != Relational(x, 1, '==') assert Eq(x, 0) != Relational(x, 1, 'eq') assert Eq(x, 0) != Equality(x, 1) assert Eq(x, -1) == Relational(x, -1) # None ==> Equality assert Eq(x, -1) == Relational(x, -1, '==') assert Eq(x, -1) == Relational(x, -1, 'eq') assert Eq(x, -1) == Equality(x, -1) assert Eq(x, -1) != Relational(x, 1) # None ==> Equality assert Eq(x, -1) != Relational(x, 1, '==') assert Eq(x, -1) != Relational(x, 1, 'eq') assert Eq(x, -1) != Equality(x, 1) assert Ne(x, 0) == Relational(x, 0, '!=') assert Ne(x, 0) == Relational(x, 0, '<>') assert Ne(x, 0) == Relational(x, 0, 'ne') assert Ne(x, 0) == Unequality(x, 0) assert Ne(x, 0) != Relational(x, 1, '!=') assert Ne(x, 0) != Relational(x, 1, '<>') assert Ne(x, 0) != Relational(x, 1, 'ne') assert Ne(x, 0) != Unequality(x, 1) assert Ge(x, 0) == Relational(x, 0, '>=') assert Ge(x, 0) == Relational(x, 0, 'ge') assert Ge(x, 0) == GreaterThan(x, 0) assert Ge(x, 1) != Relational(x, 0, '>=') assert Ge(x, 1) != Relational(x, 0, 'ge') assert Ge(x, 1) != GreaterThan(x, 0) assert (x >= 1) == Relational(x, 1, '>=') assert (x >= 1) == Relational(x, 1, 'ge') assert (x >= 1) == GreaterThan(x, 1) assert (x >= 0) != Relational(x, 1, '>=') assert (x >= 0) != Relational(x, 1, 'ge') assert (x >= 0) != GreaterThan(x, 1) assert Le(x, 0) == Relational(x, 0, '<=') assert Le(x, 0) == Relational(x, 0, 'le') assert Le(x, 0) == LessThan(x, 0) assert Le(x, 1) != Relational(x, 0, '<=') assert Le(x, 1) != Relational(x, 0, 'le') assert Le(x, 1) != LessThan(x, 0) assert (x <= 1) == Relational(x, 1, '<=') assert (x <= 1) == Relational(x, 1, 'le') assert (x <= 1) == LessThan(x, 1) assert (x <= 0) != Relational(x, 1, '<=') assert (x <= 0) != Relational(x, 1, 'le') assert (x <= 0) != LessThan(x, 1) assert Gt(x, 0) == Relational(x, 0, '>') assert Gt(x, 0) == Relational(x, 0, 'gt') assert Gt(x, 0) == StrictGreaterThan(x, 0) assert Gt(x, 1) != Relational(x, 0, '>') assert Gt(x, 1) != Relational(x, 0, 'gt') assert Gt(x, 1) != StrictGreaterThan(x, 0) assert (x > 1) == Relational(x, 1, '>') assert (x > 1) == Relational(x, 1, 'gt') assert (x > 1) == StrictGreaterThan(x, 1) assert (x > 0) != Relational(x, 1, '>') assert (x > 0) != Relational(x, 1, 'gt') assert (x > 0) != StrictGreaterThan(x, 1) assert Lt(x, 0) == Relational(x, 0, '<') assert Lt(x, 0) == Relational(x, 0, 'lt') assert Lt(x, 0) == StrictLessThan(x, 0) assert Lt(x, 1) != Relational(x, 0, '<') assert Lt(x, 1) != Relational(x, 0, 'lt') assert Lt(x, 1) != StrictLessThan(x, 0) assert (x < 1) == Relational(x, 1, '<') assert (x < 1) == Relational(x, 1, 'lt') assert (x < 1) == StrictLessThan(x, 1) assert (x < 0) != Relational(x, 1, '<') assert (x < 0) != Relational(x, 1, 'lt') assert (x < 0) != StrictLessThan(x, 1) # finally, some fuzz testing from sympy.core.random import randint for i in range(100): while 1: strtype, length = (chr, 65535) if randint(0, 1) else (chr, 255) relation_type = strtype(randint(0, length)) if randint(0, 1): relation_type += strtype(randint(0, length)) if relation_type not in ('==', 'eq', '!=', '<>', 'ne', '>=', 'ge', '<=', 'le', '>', 'gt', '<', 'lt', ':=', '+=', '-=', '*=', '/=', '%='): break raises(ValueError, lambda: Relational(x, 1, relation_type)) assert all(Relational(x, 0, op).rel_op == '==' for op in ('eq', '==')) assert all(Relational(x, 0, op).rel_op == '!=' for op in ('ne', '<>', '!=')) assert all(Relational(x, 0, op).rel_op == '>' for op in ('gt', '>')) assert all(Relational(x, 0, op).rel_op == '<' for op in ('lt', '<')) assert all(Relational(x, 0, op).rel_op == '>=' for op in ('ge', '>=')) assert all(Relational(x, 0, op).rel_op == '<=' for op in ('le', '<=')) def test_relational_arithmetic(): for cls in [Eq, Ne, Le, Lt, Ge, Gt]: rel = cls(x, y) raises(TypeError, lambda: 0+rel) raises(TypeError, lambda: 1*rel) raises(TypeError, lambda: 1**rel) raises(TypeError, lambda: rel**1) raises(TypeError, lambda: Add(0, rel)) raises(TypeError, lambda: Mul(1, rel)) raises(TypeError, lambda: Pow(1, rel)) raises(TypeError, lambda: Pow(rel, 1)) def test_relational_bool_output(): # https://github.com/sympy/sympy/issues/5931 raises(TypeError, lambda: bool(x > 3)) raises(TypeError, lambda: bool(x >= 3)) raises(TypeError, lambda: bool(x < 3)) raises(TypeError, lambda: bool(x <= 3)) raises(TypeError, lambda: bool(Eq(x, 3))) raises(TypeError, lambda: bool(Ne(x, 3))) def test_relational_logic_symbols(): # See issue 6204 assert (x < y) & (z < t) == And(x < y, z < t) assert (x < y) | (z < t) == Or(x < y, z < t) assert ~(x < y) == Not(x < y) assert (x < y) >> (z < t) == Implies(x < y, z < t) assert (x < y) << (z < t) == Implies(z < t, x < y) assert (x < y) ^ (z < t) == Xor(x < y, z < t) assert isinstance((x < y) & (z < t), And) assert isinstance((x < y) | (z < t), Or) assert isinstance(~(x < y), GreaterThan) assert isinstance((x < y) >> (z < t), Implies) assert isinstance((x < y) << (z < t), Implies) assert isinstance((x < y) ^ (z < t), (Or, Xor)) def test_univariate_relational_as_set(): assert (x > 0).as_set() == Interval(0, oo, True, True) assert (x >= 0).as_set() == Interval(0, oo) assert (x < 0).as_set() == Interval(-oo, 0, True, True) assert (x <= 0).as_set() == Interval(-oo, 0) assert Eq(x, 0).as_set() == FiniteSet(0) assert Ne(x, 0).as_set() == Interval(-oo, 0, True, True) + \ Interval(0, oo, True, True) assert (x**2 >= 4).as_set() == Interval(-oo, -2) + Interval(2, oo) @XFAIL def test_multivariate_relational_as_set(): assert (x*y >= 0).as_set() == Interval(0, oo)*Interval(0, oo) + \ Interval(-oo, 0)*Interval(-oo, 0) def test_Not(): assert Not(Equality(x, y)) == Unequality(x, y) assert Not(Unequality(x, y)) == Equality(x, y) assert Not(StrictGreaterThan(x, y)) == LessThan(x, y) assert Not(StrictLessThan(x, y)) == GreaterThan(x, y) assert Not(GreaterThan(x, y)) == StrictLessThan(x, y) assert Not(LessThan(x, y)) == StrictGreaterThan(x, y) def test_evaluate(): assert str(Eq(x, x, evaluate=False)) == 'Eq(x, x)' assert Eq(x, x, evaluate=False).doit() == S.true assert str(Ne(x, x, evaluate=False)) == 'Ne(x, x)' assert Ne(x, x, evaluate=False).doit() == S.false assert str(Ge(x, x, evaluate=False)) == 'x >= x' assert str(Le(x, x, evaluate=False)) == 'x <= x' assert str(Gt(x, x, evaluate=False)) == 'x > x' assert str(Lt(x, x, evaluate=False)) == 'x < x' def assert_all_ineq_raise_TypeError(a, b): raises(TypeError, lambda: a > b) raises(TypeError, lambda: a >= b) raises(TypeError, lambda: a < b) raises(TypeError, lambda: a <= b) raises(TypeError, lambda: b > a) raises(TypeError, lambda: b >= a) raises(TypeError, lambda: b < a) raises(TypeError, lambda: b <= a) def assert_all_ineq_give_class_Inequality(a, b): """All inequality operations on `a` and `b` result in class Inequality.""" from sympy.core.relational import _Inequality as Inequality assert isinstance(a > b, Inequality) assert isinstance(a >= b, Inequality) assert isinstance(a < b, Inequality) assert isinstance(a <= b, Inequality) assert isinstance(b > a, Inequality) assert isinstance(b >= a, Inequality) assert isinstance(b < a, Inequality) assert isinstance(b <= a, Inequality) def test_imaginary_compare_raises_TypeError(): # See issue #5724 assert_all_ineq_raise_TypeError(I, x) def test_complex_compare_not_real(): # two cases which are not real y = Symbol('y', imaginary=True) z = Symbol('z', complex=True, extended_real=False) for w in (y, z): assert_all_ineq_raise_TypeError(2, w) # some cases which should remain un-evaluated t = Symbol('t') x = Symbol('x', real=True) z = Symbol('z', complex=True) for w in (x, z, t): assert_all_ineq_give_class_Inequality(2, w) def test_imaginary_and_inf_compare_raises_TypeError(): # See pull request #7835 y = Symbol('y', imaginary=True) assert_all_ineq_raise_TypeError(oo, y) assert_all_ineq_raise_TypeError(-oo, y) def test_complex_pure_imag_not_ordered(): raises(TypeError, lambda: 2*I < 3*I) # more generally x = Symbol('x', real=True, nonzero=True) y = Symbol('y', imaginary=True) z = Symbol('z', complex=True) assert_all_ineq_raise_TypeError(I, y) t = I*x # an imaginary number, should raise errors assert_all_ineq_raise_TypeError(2, t) t = -I*y # a real number, so no errors assert_all_ineq_give_class_Inequality(2, t) t = I*z # unknown, should be unevaluated assert_all_ineq_give_class_Inequality(2, t) def test_x_minus_y_not_same_as_x_lt_y(): """ A consequence of pull request #7792 is that `x - y < 0` and `x < y` are not synonymous. """ x = I + 2 y = I + 3 raises(TypeError, lambda: x < y) assert x - y < 0 ineq = Lt(x, y, evaluate=False) raises(TypeError, lambda: ineq.doit()) assert ineq.lhs - ineq.rhs < 0 t = Symbol('t', imaginary=True) x = 2 + t y = 3 + t ineq = Lt(x, y, evaluate=False) raises(TypeError, lambda: ineq.doit()) assert ineq.lhs - ineq.rhs < 0 # this one should give error either way x = I + 2 y = 2*I + 3 raises(TypeError, lambda: x < y) raises(TypeError, lambda: x - y < 0) def test_nan_equality_exceptions(): # See issue #7774 import random assert Equality(nan, nan) is S.false assert Unequality(nan, nan) is S.true # See issue #7773 A = (x, S.Zero, S.One/3, pi, oo, -oo) assert Equality(nan, random.choice(A)) is S.false assert Equality(random.choice(A), nan) is S.false assert Unequality(nan, random.choice(A)) is S.true assert Unequality(random.choice(A), nan) is S.true def test_nan_inequality_raise_errors(): # See discussion in pull request #7776. We test inequalities with # a set including examples of various classes. for q in (x, S.Zero, S(10), S.One/3, pi, S(1.3), oo, -oo, nan): assert_all_ineq_raise_TypeError(q, nan) def test_nan_complex_inequalities(): # Comparisons of NaN with non-real raise errors, we're not too # fussy whether its the NaN error or complex error. for r in (I, zoo, Symbol('z', imaginary=True)): assert_all_ineq_raise_TypeError(r, nan) def test_complex_infinity_inequalities(): raises(TypeError, lambda: zoo > 0) raises(TypeError, lambda: zoo >= 0) raises(TypeError, lambda: zoo < 0) raises(TypeError, lambda: zoo <= 0) def test_inequalities_symbol_name_same(): """Using the operator and functional forms should give same results.""" # We test all combinations from a set # FIXME: could replace with random selection after test passes A = (x, y, S.Zero, S.One/3, pi, oo, -oo) for a in A: for b in A: assert Gt(a, b) == (a > b) assert Lt(a, b) == (a < b) assert Ge(a, b) == (a >= b) assert Le(a, b) == (a <= b) for b in (y, S.Zero, S.One/3, pi, oo, -oo): assert Gt(x, b, evaluate=False) == (x > b) assert Lt(x, b, evaluate=False) == (x < b) assert Ge(x, b, evaluate=False) == (x >= b) assert Le(x, b, evaluate=False) == (x <= b) for b in (y, S.Zero, S.One/3, pi, oo, -oo): assert Gt(b, x, evaluate=False) == (b > x) assert Lt(b, x, evaluate=False) == (b < x) assert Ge(b, x, evaluate=False) == (b >= x) assert Le(b, x, evaluate=False) == (b <= x) def test_inequalities_symbol_name_same_complex(): """Using the operator and functional forms should give same results. With complex non-real numbers, both should raise errors. """ # FIXME: could replace with random selection after test passes for a in (x, S.Zero, S.One/3, pi, oo, Rational(1, 3)): raises(TypeError, lambda: Gt(a, I)) raises(TypeError, lambda: a > I) raises(TypeError, lambda: Lt(a, I)) raises(TypeError, lambda: a < I) raises(TypeError, lambda: Ge(a, I)) raises(TypeError, lambda: a >= I) raises(TypeError, lambda: Le(a, I)) raises(TypeError, lambda: a <= I) def test_inequalities_cant_sympify_other(): # see issue 7833 from operator import gt, lt, ge, le bar = "foo" for a in (x, S.Zero, S.One/3, pi, I, zoo, oo, -oo, nan, Rational(1, 3)): for op in (lt, gt, le, ge): raises(TypeError, lambda: op(a, bar)) def test_ineq_avoid_wild_symbol_flip(): # see issue #7951, we try to avoid this internally, e.g., by using # __lt__ instead of "<". from sympy.core.symbol import Wild p = symbols('p', cls=Wild) # x > p might flip, but Gt should not: assert Gt(x, p) == Gt(x, p, evaluate=False) # Previously failed as 'p > x': e = Lt(x, y).subs({y: p}) assert e == Lt(x, p, evaluate=False) # Previously failed as 'p <= x': e = Ge(x, p).doit() assert e == Ge(x, p, evaluate=False) def test_issue_8245(): a = S("6506833320952669167898688709329/5070602400912917605986812821504") assert rel_check(a, a.n(10)) assert rel_check(a, a.n(20)) assert rel_check(a, a.n()) # prec of 30 is enough to fully capture a as mpf assert Float(a, 30) == Float(str(a.p), '')/Float(str(a.q), '') for i in range(31): r = Rational(Float(a, i)) f = Float(r) assert (f < a) == (Rational(f) < a) # test sign handling assert (-f < -a) == (Rational(-f) < -a) # test equivalence handling isa = Float(a.p,'')/Float(a.q,'') assert isa <= a assert not isa < a assert isa >= a assert not isa > a assert isa > 0 a = sqrt(2) r = Rational(str(a.n(30))) assert rel_check(a, r) a = sqrt(2) r = Rational(str(a.n(29))) assert rel_check(a, r) assert Eq(log(cos(2)**2 + sin(2)**2), 0) is S.true def test_issue_8449(): p = Symbol('p', nonnegative=True) assert Lt(-oo, p) assert Ge(-oo, p) is S.false assert Gt(oo, -p) assert Le(oo, -p) is S.false def test_simplify_relational(): assert simplify(x*(y + 1) - x*y - x + 1 < x) == (x > 1) assert simplify(x*(y + 1) - x*y - x - 1 < x) == (x > -1) assert simplify(x < x*(y + 1) - x*y - x + 1) == (x < 1) q, r = symbols("q r") assert (((-q + r) - (q - r)) <= 0).simplify() == (q >= r) root2 = sqrt(2) equation = ((root2 * (-q + r) - root2 * (q - r)) <= 0).simplify() assert equation == (q >= r) r = S.One < x # canonical operations are not the same as simplification, # so if there is no simplification, canonicalization will # be done unless the measure forbids it assert simplify(r) == r.canonical assert simplify(r, ratio=0) != r.canonical # this is not a random test; in _eval_simplify # this will simplify to S.false and that is the # reason for the 'if r.is_Relational' in Relational's # _eval_simplify routine assert simplify(-(2**(pi*Rational(3, 2)) + 6**pi)**(1/pi) + 2*(2**(pi/2) + 3**pi)**(1/pi) < 0) is S.false # canonical at least assert Eq(y, x).simplify() == Eq(x, y) assert Eq(x - 1, 0).simplify() == Eq(x, 1) assert Eq(x - 1, x).simplify() == S.false assert Eq(2*x - 1, x).simplify() == Eq(x, 1) assert Eq(2*x, 4).simplify() == Eq(x, 2) z = cos(1)**2 + sin(1)**2 - 1 # z.is_zero is None assert Eq(z*x, 0).simplify() == S.true assert Ne(y, x).simplify() == Ne(x, y) assert Ne(x - 1, 0).simplify() == Ne(x, 1) assert Ne(x - 1, x).simplify() == S.true assert Ne(2*x - 1, x).simplify() == Ne(x, 1) assert Ne(2*x, 4).simplify() == Ne(x, 2) assert Ne(z*x, 0).simplify() == S.false # No real-valued assumptions assert Ge(y, x).simplify() == Le(x, y) assert Ge(x - 1, 0).simplify() == Ge(x, 1) assert Ge(x - 1, x).simplify() == S.false assert Ge(2*x - 1, x).simplify() == Ge(x, 1) assert Ge(2*x, 4).simplify() == Ge(x, 2) assert Ge(z*x, 0).simplify() == S.true assert Ge(x, -2).simplify() == Ge(x, -2) assert Ge(-x, -2).simplify() == Le(x, 2) assert Ge(x, 2).simplify() == Ge(x, 2) assert Ge(-x, 2).simplify() == Le(x, -2) assert Le(y, x).simplify() == Ge(x, y) assert Le(x - 1, 0).simplify() == Le(x, 1) assert Le(x - 1, x).simplify() == S.true assert Le(2*x - 1, x).simplify() == Le(x, 1) assert Le(2*x, 4).simplify() == Le(x, 2) assert Le(z*x, 0).simplify() == S.true assert Le(x, -2).simplify() == Le(x, -2) assert Le(-x, -2).simplify() == Ge(x, 2) assert Le(x, 2).simplify() == Le(x, 2) assert Le(-x, 2).simplify() == Ge(x, -2) assert Gt(y, x).simplify() == Lt(x, y) assert Gt(x - 1, 0).simplify() == Gt(x, 1) assert Gt(x - 1, x).simplify() == S.false assert Gt(2*x - 1, x).simplify() == Gt(x, 1) assert Gt(2*x, 4).simplify() == Gt(x, 2) assert Gt(z*x, 0).simplify() == S.false assert Gt(x, -2).simplify() == Gt(x, -2) assert Gt(-x, -2).simplify() == Lt(x, 2) assert Gt(x, 2).simplify() == Gt(x, 2) assert Gt(-x, 2).simplify() == Lt(x, -2) assert Lt(y, x).simplify() == Gt(x, y) assert Lt(x - 1, 0).simplify() == Lt(x, 1) assert Lt(x - 1, x).simplify() == S.true assert Lt(2*x - 1, x).simplify() == Lt(x, 1) assert Lt(2*x, 4).simplify() == Lt(x, 2) assert Lt(z*x, 0).simplify() == S.false assert Lt(x, -2).simplify() == Lt(x, -2) assert Lt(-x, -2).simplify() == Gt(x, 2) assert Lt(x, 2).simplify() == Lt(x, 2) assert Lt(-x, 2).simplify() == Gt(x, -2) # Test particulat branches of _eval_simplify m = exp(1) - exp_polar(1) assert simplify(m*x > 1) is S.false # These two tests the same branch assert simplify(m*x + 2*m*y > 1) is S.false assert simplify(m*x + y > 1 + y) is S.false def test_equals(): w, x, y, z = symbols('w:z') f = Function('f') assert Eq(x, 1).equals(Eq(x*(y + 1) - x*y - x + 1, x)) assert Eq(x, y).equals(x < y, True) == False assert Eq(x, f(1)).equals(Eq(x, f(2)), True) == f(1) - f(2) assert Eq(f(1), y).equals(Eq(f(2), y), True) == f(1) - f(2) assert Eq(x, f(1)).equals(Eq(f(2), x), True) == f(1) - f(2) assert Eq(f(1), x).equals(Eq(x, f(2)), True) == f(1) - f(2) assert Eq(w, x).equals(Eq(y, z), True) == False assert Eq(f(1), f(2)).equals(Eq(f(3), f(4)), True) == f(1) - f(3) assert (x < y).equals(y > x, True) == True assert (x < y).equals(y >= x, True) == False assert (x < y).equals(z < y, True) == False assert (x < y).equals(x < z, True) == False assert (x < f(1)).equals(x < f(2), True) == f(1) - f(2) assert (f(1) < x).equals(f(2) < x, True) == f(1) - f(2) def test_reversed(): assert (x < y).reversed == (y > x) assert (x <= y).reversed == (y >= x) assert Eq(x, y, evaluate=False).reversed == Eq(y, x, evaluate=False) assert Ne(x, y, evaluate=False).reversed == Ne(y, x, evaluate=False) assert (x >= y).reversed == (y <= x) assert (x > y).reversed == (y < x) def test_canonical(): c = [i.canonical for i in ( x + y < z, x + 2 > 3, x < 2, S(2) > x, x**2 > -x/y, Gt(3, 2, evaluate=False) )] assert [i.canonical for i in c] == c assert [i.reversed.canonical for i in c] == c assert not any(i.lhs.is_Number and not i.rhs.is_Number for i in c) c = [i.reversed.func(i.rhs, i.lhs, evaluate=False).canonical for i in c] assert [i.canonical for i in c] == c assert [i.reversed.canonical for i in c] == c assert not any(i.lhs.is_Number and not i.rhs.is_Number for i in c) assert Eq(y < x, x > y).canonical is S.true @XFAIL def test_issue_8444_nonworkingtests(): x = symbols('x', real=True) assert (x <= oo) == (x >= -oo) == True x = symbols('x') assert x >= floor(x) assert (x < floor(x)) == False assert x <= ceiling(x) assert (x > ceiling(x)) == False def test_issue_8444_workingtests(): x = symbols('x') assert Gt(x, floor(x)) == Gt(x, floor(x), evaluate=False) assert Ge(x, floor(x)) == Ge(x, floor(x), evaluate=False) assert Lt(x, ceiling(x)) == Lt(x, ceiling(x), evaluate=False) assert Le(x, ceiling(x)) == Le(x, ceiling(x), evaluate=False) i = symbols('i', integer=True) assert (i > floor(i)) == False assert (i < ceiling(i)) == False def test_issue_10304(): d = cos(1)**2 + sin(1)**2 - 1 assert d.is_comparable is False # if this fails, find a new d e = 1 + d*I assert simplify(Eq(e, 0)) is S.false def test_issue_18412(): d = (Rational(1, 6) + z / 4 / y) assert Eq(x, pi * y**3 * d).replace(y**3, z) == Eq(x, pi * z * d) def test_issue_10401(): x = symbols('x') fin = symbols('inf', finite=True) inf = symbols('inf', infinite=True) inf2 = symbols('inf2', infinite=True) infx = symbols('infx', infinite=True, extended_real=True) # Used in the commented tests below: #infx2 = symbols('infx2', infinite=True, extended_real=True) infnx = symbols('inf~x', infinite=True, extended_real=False) infnx2 = symbols('inf~x2', infinite=True, extended_real=False) infp = symbols('infp', infinite=True, extended_positive=True) infp1 = symbols('infp1', infinite=True, extended_positive=True) infn = symbols('infn', infinite=True, extended_negative=True) zero = symbols('z', zero=True) nonzero = symbols('nz', zero=False, finite=True) assert Eq(1/(1/x + 1), 1).func is Eq assert Eq(1/(1/x + 1), 1).subs(x, S.ComplexInfinity) is S.true assert Eq(1/(1/fin + 1), 1) is S.false T, F = S.true, S.false assert Eq(fin, inf) is F assert Eq(inf, inf2) not in (T, F) and inf != inf2 assert Eq(1 + inf, 2 + inf2) not in (T, F) and inf != inf2 assert Eq(infp, infp1) is T assert Eq(infp, infn) is F assert Eq(1 + I*oo, I*oo) is F assert Eq(I*oo, 1 + I*oo) is F assert Eq(1 + I*oo, 2 + I*oo) is F assert Eq(1 + I*oo, 2 + I*infx) is F assert Eq(1 + I*oo, 2 + infx) is F # FIXME: The test below fails because (-infx).is_extended_positive is True # (should be None) #assert Eq(1 + I*infx, 1 + I*infx2) not in (T, F) and infx != infx2 # assert Eq(zoo, sqrt(2) + I*oo) is F assert Eq(zoo, oo) is F r = Symbol('r', real=True) i = Symbol('i', imaginary=True) assert Eq(i*I, r) not in (T, F) assert Eq(infx, infnx) is F assert Eq(infnx, infnx2) not in (T, F) and infnx != infnx2 assert Eq(zoo, oo) is F assert Eq(inf/inf2, 0) is F assert Eq(inf/fin, 0) is F assert Eq(fin/inf, 0) is T assert Eq(zero/nonzero, 0) is T and ((zero/nonzero) != 0) # The commented out test below is incorrect because: assert zoo == -zoo assert Eq(zoo, -zoo) is T assert Eq(oo, -oo) is F assert Eq(inf, -inf) not in (T, F) assert Eq(fin/(fin + 1), 1) is S.false o = symbols('o', odd=True) assert Eq(o, 2*o) is S.false p = symbols('p', positive=True) assert Eq(p/(p - 1), 1) is F def test_issue_10633(): assert Eq(True, False) == False assert Eq(False, True) == False assert Eq(True, True) == True assert Eq(False, False) == True def test_issue_10927(): x = symbols('x') assert str(Eq(x, oo)) == 'Eq(x, oo)' assert str(Eq(x, -oo)) == 'Eq(x, -oo)' def test_issues_13081_12583_12534(): # 13081 r = Rational('905502432259640373/288230376151711744') assert (r < pi) is S.false assert (r > pi) is S.true # 12583 v = sqrt(2) u = sqrt(v) + 2/sqrt(10 - 8/sqrt(2 - v) + 4*v*(1/sqrt(2 - v) - 1)) assert (u >= 0) is S.true # 12534; Rational vs NumberSymbol # here are some precisions for which Rational forms # at a lower and higher precision bracket the value of pi # e.g. for p = 20: # Rational(pi.n(p + 1)).n(25) = 3.14159265358979323846 2834 # pi.n(25) = 3.14159265358979323846 2643 # Rational(pi.n(p )).n(25) = 3.14159265358979323846 1987 assert [p for p in range(20, 50) if (Rational(pi.n(p)) < pi) and (pi < Rational(pi.n(p + 1)))] == [20, 24, 27, 33, 37, 43, 48] # pick one such precision and affirm that the reversed operation # gives the opposite result, i.e. if x < y is true then x > y # must be false for i in (20, 21): v = pi.n(i) assert rel_check(Rational(v), pi) assert rel_check(v, pi) assert rel_check(pi.n(20), pi.n(21)) # Float vs Rational # the rational form is less than the floating representation # at the same precision assert [i for i in range(15, 50) if Rational(pi.n(i)) > pi.n(i)] == [] # this should be the same if we reverse the relational assert [i for i in range(15, 50) if pi.n(i) < Rational(pi.n(i))] == [] def test_issue_18188(): from sympy.sets.conditionset import ConditionSet result1 = Eq(x*cos(x) - 3*sin(x), 0) assert result1.as_set() == ConditionSet(x, Eq(x*cos(x) - 3*sin(x), 0), Reals) result2 = Eq(x**2 + sqrt(x*2) + sin(x), 0) assert result2.as_set() == ConditionSet(x, Eq(sqrt(2)*sqrt(x) + x**2 + sin(x), 0), Reals) def test_binary_symbols(): ans = {x} for f in Eq, Ne: for t in S.true, S.false: eq = f(x, S.true) assert eq.binary_symbols == ans assert eq.reversed.binary_symbols == ans assert f(x, 1).binary_symbols == set() def test_rel_args(): # can't have Boolean args; this is automatic for True/False # with Python 3 and we confirm that SymPy does the same # for true/false for op in ['<', '<=', '>', '>=']: for b in (S.true, x < 1, And(x, y)): for v in (0.1, 1, 2**32, t, S.One): raises(TypeError, lambda: Relational(b, v, op)) def test_Equality_rewrite_as_Add(): eq = Eq(x + y, y - x) assert eq.rewrite(Add) == 2*x assert eq.rewrite(Add, evaluate=None).args == (x, x, y, -y) assert eq.rewrite(Add, evaluate=False).args == (x, y, x, -y) def test_issue_15847(): a = Ne(x*(x+y), x**2 + x*y) assert simplify(a) == False def test_negated_property(): eq = Eq(x, y) assert eq.negated == Ne(x, y) eq = Ne(x, y) assert eq.negated == Eq(x, y) eq = Ge(x + y, y - x) assert eq.negated == Lt(x + y, y - x) for f in (Eq, Ne, Ge, Gt, Le, Lt): assert f(x, y).negated.negated == f(x, y) def test_reversedsign_property(): eq = Eq(x, y) assert eq.reversedsign == Eq(-x, -y) eq = Ne(x, y) assert eq.reversedsign == Ne(-x, -y) eq = Ge(x + y, y - x) assert eq.reversedsign == Le(-x - y, x - y) for f in (Eq, Ne, Ge, Gt, Le, Lt): assert f(x, y).reversedsign.reversedsign == f(x, y) for f in (Eq, Ne, Ge, Gt, Le, Lt): assert f(-x, y).reversedsign.reversedsign == f(-x, y) for f in (Eq, Ne, Ge, Gt, Le, Lt): assert f(x, -y).reversedsign.reversedsign == f(x, -y) for f in (Eq, Ne, Ge, Gt, Le, Lt): assert f(-x, -y).reversedsign.reversedsign == f(-x, -y) def test_reversed_reversedsign_property(): for f in (Eq, Ne, Ge, Gt, Le, Lt): assert f(x, y).reversed.reversedsign == f(x, y).reversedsign.reversed for f in (Eq, Ne, Ge, Gt, Le, Lt): assert f(-x, y).reversed.reversedsign == f(-x, y).reversedsign.reversed for f in (Eq, Ne, Ge, Gt, Le, Lt): assert f(x, -y).reversed.reversedsign == f(x, -y).reversedsign.reversed for f in (Eq, Ne, Ge, Gt, Le, Lt): assert f(-x, -y).reversed.reversedsign == \ f(-x, -y).reversedsign.reversed def test_improved_canonical(): def test_different_forms(listofforms): for form1, form2 in combinations(listofforms, 2): assert form1.canonical == form2.canonical def generate_forms(expr): return [expr, expr.reversed, expr.reversedsign, expr.reversed.reversedsign] test_different_forms(generate_forms(x > -y)) test_different_forms(generate_forms(x >= -y)) test_different_forms(generate_forms(Eq(x, -y))) test_different_forms(generate_forms(Ne(x, -y))) test_different_forms(generate_forms(pi < x)) test_different_forms(generate_forms(pi - 5*y < -x + 2*y**2 - 7)) assert (pi >= x).canonical == (x <= pi) def test_set_equality_canonical(): a, b, c = symbols('a b c') A = Eq(FiniteSet(a, b, c), FiniteSet(1, 2, 3)) B = Ne(FiniteSet(a, b, c), FiniteSet(4, 5, 6)) assert A.canonical == A.reversed assert B.canonical == B.reversed def test_trigsimp(): # issue 16736 s, c = sin(2*x), cos(2*x) eq = Eq(s, c) assert trigsimp(eq) == eq # no rearrangement of sides # simplification of sides might result in # an unevaluated Eq changed = trigsimp(Eq(s + c, sqrt(2))) assert isinstance(changed, Eq) assert changed.subs(x, pi/8) is S.true # or an evaluated one assert trigsimp(Eq(cos(x)**2 + sin(x)**2, 1)) is S.true def test_polynomial_relation_simplification(): assert Ge(3*x*(x + 1) + 4, 3*x).simplify() in [Ge(x**2, -Rational(4,3)), Le(-x**2, Rational(4, 3))] assert Le(-(3*x*(x + 1) + 4), -3*x).simplify() in [Ge(x**2, -Rational(4,3)), Le(-x**2, Rational(4, 3))] assert ((x**2+3)*(x**2-1)+3*x >= 2*x**2).simplify() in [(x**4 + 3*x >= 3), (-x**4 - 3*x <= -3)] def test_multivariate_linear_function_simplification(): assert Ge(x + y, x - y).simplify() == Ge(y, 0) assert Le(-x + y, -x - y).simplify() == Le(y, 0) assert Eq(2*x + y, 2*x + y - 3).simplify() == False assert (2*x + y > 2*x + y - 3).simplify() == True assert (2*x + y < 2*x + y - 3).simplify() == False assert (2*x + y < 2*x + y + 3).simplify() == True a, b, c, d, e, f, g = symbols('a b c d e f g') assert Lt(a + b + c + 2*d, 3*d - f + g). simplify() == Lt(a, -b - c + d - f + g) def test_nonpolymonial_relations(): assert Eq(cos(x), 0).simplify() == Eq(cos(x), 0) def test_18778(): raises(TypeError, lambda: is_le(Basic(), Basic())) raises(TypeError, lambda: is_gt(Basic(), Basic())) raises(TypeError, lambda: is_ge(Basic(), Basic())) raises(TypeError, lambda: is_lt(Basic(), Basic())) def test_EvalEq(): """ This test exists to ensure backwards compatibility. The method to use is _eval_is_eq """ from sympy.core.expr import Expr class PowTest(Expr): def __new__(cls, base, exp): return Basic.__new__(PowTest, _sympify(base), _sympify(exp)) def _eval_Eq(lhs, rhs): if type(lhs) == PowTest and type(rhs) == PowTest: return lhs.args[0] == rhs.args[0] and lhs.args[1] == rhs.args[1] assert is_eq(PowTest(3, 4), PowTest(3,4)) assert is_eq(PowTest(3, 4), _sympify(4)) is None assert is_neq(PowTest(3, 4), PowTest(3,7)) def test_is_eq(): # test assumptions assert is_eq(x, y, Q.infinite(x) & Q.finite(y)) is False assert is_eq(x, y, Q.infinite(x) & Q.infinite(y) & Q.extended_real(x) & ~Q.extended_real(y)) is False assert is_eq(x, y, Q.infinite(x) & Q.infinite(y) & Q.extended_positive(x) & Q.extended_negative(y)) is False assert is_eq(x+I, y+I, Q.infinite(x) & Q.finite(y)) is False assert is_eq(1+x*I, 1+y*I, Q.infinite(x) & Q.finite(y)) is False assert is_eq(x, S(0), assumptions=Q.zero(x)) assert is_eq(x, S(0), assumptions=~Q.zero(x)) is False assert is_eq(x, S(0), assumptions=Q.nonzero(x)) is False assert is_neq(x, S(0), assumptions=Q.zero(x)) is False assert is_neq(x, S(0), assumptions=~Q.zero(x)) assert is_neq(x, S(0), assumptions=Q.nonzero(x)) # test registration class PowTest(Expr): def __new__(cls, base, exp): return Basic.__new__(cls, _sympify(base), _sympify(exp)) @dispatch(PowTest, PowTest) def _eval_is_eq(lhs, rhs): if type(lhs) == PowTest and type(rhs) == PowTest: return fuzzy_and([is_eq(lhs.args[0], rhs.args[0]), is_eq(lhs.args[1], rhs.args[1])]) assert is_eq(PowTest(3, 4), PowTest(3,4)) assert is_eq(PowTest(3, 4), _sympify(4)) is None assert is_neq(PowTest(3, 4), PowTest(3,7)) def test_is_ge_le(): # test assumptions assert is_ge(x, S(0), Q.nonnegative(x)) is True assert is_ge(x, S(0), Q.negative(x)) is False # test registration class PowTest(Expr): def __new__(cls, base, exp): return Basic.__new__(cls, _sympify(base), _sympify(exp)) @dispatch(PowTest, PowTest) def _eval_is_ge(lhs, rhs): if type(lhs) == PowTest and type(rhs) == PowTest: return fuzzy_and([is_ge(lhs.args[0], rhs.args[0]), is_ge(lhs.args[1], rhs.args[1])]) assert is_ge(PowTest(3, 9), PowTest(3,2)) assert is_gt(PowTest(3, 9), PowTest(3,2)) assert is_le(PowTest(3, 2), PowTest(3,9)) assert is_lt(PowTest(3, 2), PowTest(3,9)) def test_weak_strict(): for func in (Eq, Ne): eq = func(x, 1) assert eq.strict == eq.weak == eq eq = Gt(x, 1) assert eq.weak == Ge(x, 1) assert eq.strict == eq eq = Lt(x, 1) assert eq.weak == Le(x, 1) assert eq.strict == eq eq = Ge(x, 1) assert eq.strict == Gt(x, 1) assert eq.weak == eq eq = Le(x, 1) assert eq.strict == Lt(x, 1) assert eq.weak == eq
401147eee5d42468660f76e4390b17afc3d1ad076915c766deb735da4d90baaf
from collections import defaultdict from sympy.core.basic import Basic from sympy.core.containers import (Dict, Tuple) from sympy.core.numbers import Integer from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.core.sympify import sympify from sympy.matrices.dense import Matrix from sympy.sets.sets import FiniteSet from sympy.core.containers import tuple_wrapper from sympy.core.expr import unchanged from sympy.core.function import Function, Lambda from sympy.core.relational import Eq from sympy.testing.pytest import raises from sympy.utilities.iterables import is_sequence, iterable from sympy.abc import x, y def test_Tuple(): t = (1, 2, 3, 4) st = Tuple(*t) assert set(sympify(t)) == set(st) assert len(t) == len(st) assert set(sympify(t[:2])) == set(st[:2]) assert isinstance(st[:], Tuple) assert st == Tuple(1, 2, 3, 4) assert st.func(*st.args) == st p, q, r, s = symbols('p q r s') t2 = (p, q, r, s) st2 = Tuple(*t2) assert st2.atoms() == set(t2) assert st == st2.subs({p: 1, q: 2, r: 3, s: 4}) # issue 5505 assert all(isinstance(arg, Basic) for arg in st.args) assert Tuple(p, 1).subs(p, 0) == Tuple(0, 1) assert Tuple(p, Tuple(p, 1)).subs(p, 0) == Tuple(0, Tuple(0, 1)) assert Tuple(t2) == Tuple(Tuple(*t2)) assert Tuple.fromiter(t2) == Tuple(*t2) assert Tuple.fromiter(x for x in range(4)) == Tuple(0, 1, 2, 3) assert st2.fromiter(st2.args) == st2 def test_Tuple_contains(): t1, t2 = Tuple(1), Tuple(2) assert t1 in Tuple(1, 2, 3, t1, Tuple(t2)) assert t2 not in Tuple(1, 2, 3, t1, Tuple(t2)) def test_Tuple_concatenation(): assert Tuple(1, 2) + Tuple(3, 4) == Tuple(1, 2, 3, 4) assert (1, 2) + Tuple(3, 4) == Tuple(1, 2, 3, 4) assert Tuple(1, 2) + (3, 4) == Tuple(1, 2, 3, 4) raises(TypeError, lambda: Tuple(1, 2) + 3) raises(TypeError, lambda: 1 + Tuple(2, 3)) #the Tuple case in __radd__ is only reached when a subclass is involved class Tuple2(Tuple): def __radd__(self, other): return Tuple.__radd__(self, other + other) assert Tuple(1, 2) + Tuple2(3, 4) == Tuple(1, 2, 1, 2, 3, 4) assert Tuple2(1, 2) + Tuple(3, 4) == Tuple(1, 2, 3, 4) def test_Tuple_equality(): assert not isinstance(Tuple(1, 2), tuple) assert (Tuple(1, 2) == (1, 2)) is True assert (Tuple(1, 2) != (1, 2)) is False assert (Tuple(1, 2) == (1, 3)) is False assert (Tuple(1, 2) != (1, 3)) is True assert (Tuple(1, 2) == Tuple(1, 2)) is True assert (Tuple(1, 2) != Tuple(1, 2)) is False assert (Tuple(1, 2) == Tuple(1, 3)) is False assert (Tuple(1, 2) != Tuple(1, 3)) is True def test_Tuple_Eq(): assert Eq(Tuple(), Tuple()) is S.true assert Eq(Tuple(1), 1) is S.false assert Eq(Tuple(1, 2), Tuple(1)) is S.false assert Eq(Tuple(1), Tuple(1)) is S.true assert Eq(Tuple(1, 2), Tuple(1, 3)) is S.false assert Eq(Tuple(1, 2), Tuple(1, 2)) is S.true assert unchanged(Eq, Tuple(1, x), Tuple(1, 2)) assert Eq(Tuple(1, x), Tuple(1, 2)).subs(x, 2) is S.true assert unchanged(Eq, Tuple(1, 2), x) f = Function('f') assert unchanged(Eq, Tuple(1), f(x)) assert Eq(Tuple(1), f(x)).subs(x, 1).subs(f, Lambda(y, (y,))) is S.true def test_Tuple_comparision(): assert (Tuple(1, 3) >= Tuple(-10, 30)) is S.true assert (Tuple(1, 3) <= Tuple(-10, 30)) is S.false assert (Tuple(1, 3) >= Tuple(1, 3)) is S.true assert (Tuple(1, 3) <= Tuple(1, 3)) is S.true def test_Tuple_tuple_count(): assert Tuple(0, 1, 2, 3).tuple_count(4) == 0 assert Tuple(0, 4, 1, 2, 3).tuple_count(4) == 1 assert Tuple(0, 4, 1, 4, 2, 3).tuple_count(4) == 2 assert Tuple(0, 4, 1, 4, 2, 4, 3).tuple_count(4) == 3 def test_Tuple_index(): assert Tuple(4, 0, 1, 2, 3).index(4) == 0 assert Tuple(0, 4, 1, 2, 3).index(4) == 1 assert Tuple(0, 1, 4, 2, 3).index(4) == 2 assert Tuple(0, 1, 2, 4, 3).index(4) == 3 assert Tuple(0, 1, 2, 3, 4).index(4) == 4 raises(ValueError, lambda: Tuple(0, 1, 2, 3).index(4)) raises(ValueError, lambda: Tuple(4, 0, 1, 2, 3).index(4, 1)) raises(ValueError, lambda: Tuple(0, 1, 2, 3, 4).index(4, 1, 4)) def test_Tuple_mul(): assert Tuple(1, 2, 3)*2 == Tuple(1, 2, 3, 1, 2, 3) assert 2*Tuple(1, 2, 3) == Tuple(1, 2, 3, 1, 2, 3) assert Tuple(1, 2, 3)*Integer(2) == Tuple(1, 2, 3, 1, 2, 3) assert Integer(2)*Tuple(1, 2, 3) == Tuple(1, 2, 3, 1, 2, 3) raises(TypeError, lambda: Tuple(1, 2, 3)*S.Half) raises(TypeError, lambda: S.Half*Tuple(1, 2, 3)) def test_tuple_wrapper(): @tuple_wrapper def wrap_tuples_and_return(*t): return t p = symbols('p') assert wrap_tuples_and_return(p, 1) == (p, 1) assert wrap_tuples_and_return((p, 1)) == (Tuple(p, 1),) assert wrap_tuples_and_return(1, (p, 2), 3) == (1, Tuple(p, 2), 3) def test_iterable_is_sequence(): ordered = [list(), tuple(), Tuple(), Matrix([[]])] unordered = [set()] not_sympy_iterable = [{}, '', ''] assert all(is_sequence(i) for i in ordered) assert all(not is_sequence(i) for i in unordered) assert all(iterable(i) for i in ordered + unordered) assert all(not iterable(i) for i in not_sympy_iterable) assert all(iterable(i, exclude=None) for i in not_sympy_iterable) def test_Dict(): x, y, z = symbols('x y z') d = Dict({x: 1, y: 2, z: 3}) assert d[x] == 1 assert d[y] == 2 raises(KeyError, lambda: d[2]) raises(KeyError, lambda: d['2']) assert len(d) == 3 assert set(d.keys()) == {x, y, z} assert set(d.values()) == {S.One, S(2), S(3)} assert d.get(5, 'default') == 'default' assert d.get('5', 'default') == 'default' assert x in d and z in d and 5 not in d and '5' not in d assert d.has(x) and d.has(1) # SymPy Basic .has method # Test input types # input - a Python dict # input - items as args - SymPy style assert (Dict({x: 1, y: 2, z: 3}) == Dict((x, 1), (y, 2), (z, 3))) raises(TypeError, lambda: Dict(((x, 1), (y, 2), (z, 3)))) with raises(NotImplementedError): d[5] = 6 # assert immutability assert set( d.items()) == {Tuple(x, S.One), Tuple(y, S(2)), Tuple(z, S(3))} assert set(d) == {x, y, z} assert str(d) == '{x: 1, y: 2, z: 3}' assert d.__repr__() == '{x: 1, y: 2, z: 3}' # Test creating a Dict from a Dict. d = Dict({x: 1, y: 2, z: 3}) assert d == Dict(d) # Test for supporting defaultdict d = defaultdict(int) assert d[x] == 0 assert d[y] == 0 assert d[z] == 0 assert Dict(d) d = Dict(d) assert len(d) == 3 assert set(d.keys()) == {x, y, z} assert set(d.values()) == {S.Zero, S.Zero, S.Zero} def test_issue_5788(): args = [(1, 2), (2, 1)] for o in [Dict, Tuple, FiniteSet]: # __eq__ and arg handling if o != Tuple: assert o(*args) == o(*reversed(args)) pair = [o(*args), o(*reversed(args))] assert sorted(pair) == sorted(reversed(pair)) assert set(o(*args)) # doesn't fail
d519293b405f5b6f2c78561526ca5a27ef8bb08e5f1c077078dde73bb0badce8
from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.mod import Mod from sympy.core.mul import Mul from sympy.core.numbers import (Float, I, Integer, Rational, comp, nan, oo, pi, zoo) from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, symbols) from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.complexes import (im, re, sign) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.integers import floor from sympy.functions.elementary.miscellaneous import (Max, sqrt) from sympy.functions.elementary.trigonometric import (atan, cos, sin) from sympy.polys.polytools import Poly from sympy.sets.sets import FiniteSet from sympy.core.parameters import distribute from sympy.core.expr import unchanged from sympy.utilities.iterables import permutations from sympy.testing.pytest import XFAIL, raises, warns_deprecated_sympy from sympy.core.random import verify_numerically from sympy.functions.elementary.trigonometric import asin from itertools import product a, c, x, y, z = symbols('a,c,x,y,z') b = Symbol("b", positive=True) def same_and_same_prec(a, b): # stricter matching for Floats return a == b and a._prec == b._prec def test_bug1(): assert re(x) != x x.series(x, 0, 1) assert re(x) != x def test_Symbol(): e = a*b assert e == a*b assert a*b*b == a*b**2 assert a*b*b + c == c + a*b**2 assert a*b*b - c == -c + a*b**2 x = Symbol('x', complex=True, real=False) assert x.is_imaginary is None # could be I or 1 + I x = Symbol('x', complex=True, imaginary=False) assert x.is_real is None # could be 1 or 1 + I x = Symbol('x', real=True) assert x.is_complex x = Symbol('x', imaginary=True) assert x.is_complex x = Symbol('x', real=False, imaginary=False) assert x.is_complex is None # might be a non-number def test_arit0(): p = Rational(5) e = a*b assert e == a*b e = a*b + b*a assert e == 2*a*b e = a*b + b*a + a*b + p*b*a assert e == 8*a*b e = a*b + b*a + a*b + p*b*a + a assert e == a + 8*a*b e = a + a assert e == 2*a e = a + b + a assert e == b + 2*a e = a + b*b + a + b*b assert e == 2*a + 2*b**2 e = a + Rational(2) + b*b + a + b*b + p assert e == 7 + 2*a + 2*b**2 e = (a + b*b + a + b*b)*p assert e == 5*(2*a + 2*b**2) e = (a*b*c + c*b*a + b*a*c)*p assert e == 15*a*b*c e = (a*b*c + c*b*a + b*a*c)*p - Rational(15)*a*b*c assert e == Rational(0) e = Rational(50)*(a - a) assert e == Rational(0) e = b*a - b - a*b + b assert e == Rational(0) e = a*b + c**p assert e == a*b + c**5 e = a/b assert e == a*b**(-1) e = a*2*2 assert e == 4*a e = 2 + a*2/2 assert e == 2 + a e = 2 - a - 2 assert e == -a e = 2*a*2 assert e == 4*a e = 2/a/2 assert e == a**(-1) e = 2**a**2 assert e == 2**(a**2) e = -(1 + a) assert e == -1 - a e = S.Half*(1 + a) assert e == S.Half + a/2 def test_div(): e = a/b assert e == a*b**(-1) e = a/b + c/2 assert e == a*b**(-1) + Rational(1)/2*c e = (1 - b)/(b - 1) assert e == (1 + -b)*((-1) + b)**(-1) def test_pow(): n1 = Rational(1) n2 = Rational(2) n5 = Rational(5) e = a*a assert e == a**2 e = a*a*a assert e == a**3 e = a*a*a*a**Rational(6) assert e == a**9 e = a*a*a*a**Rational(6) - a**Rational(9) assert e == Rational(0) e = a**(b - b) assert e == Rational(1) e = (a + Rational(1) - a)**b assert e == Rational(1) e = (a + b + c)**n2 assert e == (a + b + c)**2 assert e.expand() == 2*b*c + 2*a*c + 2*a*b + a**2 + c**2 + b**2 e = (a + b)**n2 assert e == (a + b)**2 assert e.expand() == 2*a*b + a**2 + b**2 e = (a + b)**(n1/n2) assert e == sqrt(a + b) assert e.expand() == sqrt(a + b) n = n5**(n1/n2) assert n == sqrt(5) e = n*a*b - n*b*a assert e == Rational(0) e = n*a*b + n*b*a assert e == 2*a*b*sqrt(5) assert e.diff(a) == 2*b*sqrt(5) assert e.diff(a) == 2*b*sqrt(5) e = a/b**2 assert e == a*b**(-2) assert sqrt(2*(1 + sqrt(2))) == (2*(1 + 2**S.Half))**S.Half x = Symbol('x') y = Symbol('y') assert ((x*y)**3).expand() == y**3 * x**3 assert ((x*y)**-3).expand() == y**-3 * x**-3 assert (x**5*(3*x)**(3)).expand() == 27 * x**8 assert (x**5*(-3*x)**(3)).expand() == -27 * x**8 assert (x**5*(3*x)**(-3)).expand() == x**2 * Rational(1, 27) assert (x**5*(-3*x)**(-3)).expand() == x**2 * Rational(-1, 27) # expand_power_exp assert (x**(y**(x + exp(x + y)) + z)).expand(deep=False) == \ x**z*x**(y**(x + exp(x + y))) assert (x**(y**(x + exp(x + y)) + z)).expand() == \ x**z*x**(y**x*y**(exp(x)*exp(y))) n = Symbol('n', even=False) k = Symbol('k', even=True) o = Symbol('o', odd=True) assert unchanged(Pow, -1, x) assert unchanged(Pow, -1, n) assert (-2)**k == 2**k assert (-1)**k == 1 assert (-1)**o == -1 def test_pow2(): # x**(2*y) is always (x**y)**2 but is only (x**2)**y if # x.is_positive or y.is_integer # let x = 1 to see why the following are not true. assert (-x)**Rational(2, 3) != x**Rational(2, 3) assert (-x)**Rational(5, 7) != -x**Rational(5, 7) assert ((-x)**2)**Rational(1, 3) != ((-x)**Rational(1, 3))**2 assert sqrt(x**2) != x def test_pow3(): assert sqrt(2)**3 == 2 * sqrt(2) assert sqrt(2)**3 == sqrt(8) def test_mod_pow(): for s, t, u, v in [(4, 13, 497, 445), (4, -3, 497, 365), (3.2, 2.1, 1.9, 0.1031015682350942), (S(3)/2, 5, S(5)/6, S(3)/32)]: assert pow(S(s), t, u) == v assert pow(S(s), S(t), u) == v assert pow(S(s), t, S(u)) == v assert pow(S(s), S(t), S(u)) == v assert pow(S(2), S(10000000000), S(3)) == 1 assert pow(x, y, z) == x**y%z raises(TypeError, lambda: pow(S(4), "13", 497)) raises(TypeError, lambda: pow(S(4), 13, "497")) def test_pow_E(): assert 2**(y/log(2)) == S.Exp1**y assert 2**(y/log(2)/3) == S.Exp1**(y/3) assert 3**(1/log(-3)) != S.Exp1 assert (3 + 2*I)**(1/(log(-3 - 2*I) + I*pi)) == S.Exp1 assert (4 + 2*I)**(1/(log(-4 - 2*I) + I*pi)) == S.Exp1 assert (3 + 2*I)**(1/(log(-3 - 2*I, 3)/2 + I*pi/log(3)/2)) == 9 assert (3 + 2*I)**(1/(log(3 + 2*I, 3)/2)) == 9 # every time tests are run they will affirm with a different random # value that this identity holds while 1: b = x._random() r, i = b.as_real_imag() if i: break assert verify_numerically(b**(1/(log(-b) + sign(i)*I*pi).n()), S.Exp1) def test_pow_issue_3516(): assert 4**Rational(1, 4) == sqrt(2) def test_pow_im(): for m in (-2, -1, 2): for d in (3, 4, 5): b = m*I for i in range(1, 4*d + 1): e = Rational(i, d) assert (b**e - b.n()**e.n()).n(2, chop=1e-10) == 0 e = Rational(7, 3) assert (2*x*I)**e == 4*2**Rational(1, 3)*(I*x)**e # same as Wolfram Alpha im = symbols('im', imaginary=True) assert (2*im*I)**e == 4*2**Rational(1, 3)*(I*im)**e args = [I, I, I, I, 2] e = Rational(1, 3) ans = 2**e assert Mul(*args, evaluate=False)**e == ans assert Mul(*args)**e == ans args = [I, I, I, 2] e = Rational(1, 3) ans = 2**e*(-I)**e assert Mul(*args, evaluate=False)**e == ans assert Mul(*args)**e == ans args.append(-3) ans = (6*I)**e assert Mul(*args, evaluate=False)**e == ans assert Mul(*args)**e == ans args.append(-1) ans = (-6*I)**e assert Mul(*args, evaluate=False)**e == ans assert Mul(*args)**e == ans args = [I, I, 2] e = Rational(1, 3) ans = (-2)**e assert Mul(*args, evaluate=False)**e == ans assert Mul(*args)**e == ans args.append(-3) ans = (6)**e assert Mul(*args, evaluate=False)**e == ans assert Mul(*args)**e == ans args.append(-1) ans = (-6)**e assert Mul(*args, evaluate=False)**e == ans assert Mul(*args)**e == ans assert Mul(Pow(-1, Rational(3, 2), evaluate=False), I, I) == I assert Mul(I*Pow(I, S.Half, evaluate=False)) == sqrt(I)*I def test_real_mul(): assert Float(0) * pi * x == 0 assert set((Float(1) * pi * x).args) == {Float(1), pi, x} def test_ncmul(): A = Symbol("A", commutative=False) B = Symbol("B", commutative=False) C = Symbol("C", commutative=False) assert A*B != B*A assert A*B*C != C*B*A assert A*b*B*3*C == 3*b*A*B*C assert A*b*B*3*C != 3*b*B*A*C assert A*b*B*3*C == 3*A*B*C*b assert A + B == B + A assert (A + B)*C != C*(A + B) assert C*(A + B)*C != C*C*(A + B) assert A*A == A**2 assert (A + B)*(A + B) == (A + B)**2 assert A**-1 * A == 1 assert A/A == 1 assert A/(A**2) == 1/A assert A/(1 + A) == A/(1 + A) assert set((A + B + 2*(A + B)).args) == \ {A, B, 2*(A + B)} def test_mul_add_identity(): m = Mul(1, 2) assert isinstance(m, Rational) and m.p == 2 and m.q == 1 m = Mul(1, 2, evaluate=False) assert isinstance(m, Mul) and m.args == (1, 2) m = Mul(0, 1) assert m is S.Zero m = Mul(0, 1, evaluate=False) assert isinstance(m, Mul) and m.args == (0, 1) m = Add(0, 1) assert m is S.One m = Add(0, 1, evaluate=False) assert isinstance(m, Add) and m.args == (0, 1) def test_ncpow(): x = Symbol('x', commutative=False) y = Symbol('y', commutative=False) z = Symbol('z', commutative=False) a = Symbol('a') b = Symbol('b') c = Symbol('c') assert (x**2)*(y**2) != (y**2)*(x**2) assert (x**-2)*y != y*(x**2) assert 2**x*2**y != 2**(x + y) assert 2**x*2**y*2**z != 2**(x + y + z) assert 2**x*2**(2*x) == 2**(3*x) assert 2**x*2**(2*x)*2**x == 2**(4*x) assert exp(x)*exp(y) != exp(y)*exp(x) assert exp(x)*exp(y)*exp(z) != exp(y)*exp(x)*exp(z) assert exp(x)*exp(y)*exp(z) != exp(x + y + z) assert x**a*x**b != x**(a + b) assert x**a*x**b*x**c != x**(a + b + c) assert x**3*x**4 == x**7 assert x**3*x**4*x**2 == x**9 assert x**a*x**(4*a) == x**(5*a) assert x**a*x**(4*a)*x**a == x**(6*a) def test_powerbug(): x = Symbol("x") assert x**1 != (-x)**1 assert x**2 == (-x)**2 assert x**3 != (-x)**3 assert x**4 == (-x)**4 assert x**5 != (-x)**5 assert x**6 == (-x)**6 assert x**128 == (-x)**128 assert x**129 != (-x)**129 assert (2*x)**2 == (-2*x)**2 def test_Mul_doesnt_expand_exp(): x = Symbol('x') y = Symbol('y') assert unchanged(Mul, exp(x), exp(y)) assert unchanged(Mul, 2**x, 2**y) assert x**2*x**3 == x**5 assert 2**x*3**x == 6**x assert x**(y)*x**(2*y) == x**(3*y) assert sqrt(2)*sqrt(2) == 2 assert 2**x*2**(2*x) == 2**(3*x) assert sqrt(2)*2**Rational(1, 4)*5**Rational(3, 4) == 10**Rational(3, 4) assert (x**(-log(5)/log(3))*x)/(x*x**( - log(5)/log(3))) == sympify(1) def test_Mul_is_integer(): k = Symbol('k', integer=True) n = Symbol('n', integer=True) nr = Symbol('nr', rational=False) nz = Symbol('nz', integer=True, zero=False) e = Symbol('e', even=True) o = Symbol('o', odd=True) i2 = Symbol('2', prime=True, even=True) assert (k/3).is_integer is None assert (nz/3).is_integer is None assert (nr/3).is_integer is False assert (x*k*n).is_integer is None assert (e/2).is_integer is True assert (e**2/2).is_integer is True assert (2/k).is_integer is None assert (2/k**2).is_integer is None assert ((-1)**k*n).is_integer is True assert (3*k*e/2).is_integer is True assert (2*k*e/3).is_integer is None assert (e/o).is_integer is None assert (o/e).is_integer is False assert (o/i2).is_integer is False assert Mul(k, 1/k, evaluate=False).is_integer is None assert Mul(2., S.Half, evaluate=False).is_integer is None assert (2*sqrt(k)).is_integer is None assert (2*k**n).is_integer is None s = 2**2**2**Pow(2, 1000, evaluate=False) m = Mul(s, s, evaluate=False) assert m.is_integer # broken in 1.6 and before, see #20161 xq = Symbol('xq', rational=True) yq = Symbol('yq', rational=True) assert (xq*yq).is_integer is None e_20161 = Mul(-1,Mul(1,Pow(2,-1,evaluate=False),evaluate=False),evaluate=False) assert e_20161.is_integer is not True # expand(e_20161) -> -1/2, but no need to see that in the assumption without evaluation def test_Add_Mul_is_integer(): x = Symbol('x') k = Symbol('k', integer=True) n = Symbol('n', integer=True) nk = Symbol('nk', integer=False) nr = Symbol('nr', rational=False) nz = Symbol('nz', integer=True, zero=False) assert (-nk).is_integer is None assert (-nr).is_integer is False assert (2*k).is_integer is True assert (-k).is_integer is True assert (k + nk).is_integer is False assert (k + n).is_integer is True assert (k + x).is_integer is None assert (k + n*x).is_integer is None assert (k + n/3).is_integer is None assert (k + nz/3).is_integer is None assert (k + nr/3).is_integer is False assert ((1 + sqrt(3))*(-sqrt(3) + 1)).is_integer is not False assert (1 + (1 + sqrt(3))*(-sqrt(3) + 1)).is_integer is not False def test_Add_Mul_is_finite(): x = Symbol('x', extended_real=True, finite=False) assert sin(x).is_finite is True assert (x*sin(x)).is_finite is None assert (x*atan(x)).is_finite is False assert (1024*sin(x)).is_finite is True assert (sin(x)*exp(x)).is_finite is None assert (sin(x)*cos(x)).is_finite is True assert (x*sin(x)*exp(x)).is_finite is None assert (sin(x) - 67).is_finite is True assert (sin(x) + exp(x)).is_finite is not True assert (1 + x).is_finite is False assert (1 + x**2 + (1 + x)*(1 - x)).is_finite is None assert (sqrt(2)*(1 + x)).is_finite is False assert (sqrt(2)*(1 + x)*(1 - x)).is_finite is False def test_Mul_is_even_odd(): x = Symbol('x', integer=True) y = Symbol('y', integer=True) k = Symbol('k', odd=True) n = Symbol('n', odd=True) m = Symbol('m', even=True) assert (2*x).is_even is True assert (2*x).is_odd is False assert (3*x).is_even is None assert (3*x).is_odd is None assert (k/3).is_integer is None assert (k/3).is_even is None assert (k/3).is_odd is None assert (2*n).is_even is True assert (2*n).is_odd is False assert (2*m).is_even is True assert (2*m).is_odd is False assert (-n).is_even is False assert (-n).is_odd is True assert (k*n).is_even is False assert (k*n).is_odd is True assert (k*m).is_even is True assert (k*m).is_odd is False assert (k*n*m).is_even is True assert (k*n*m).is_odd is False assert (k*m*x).is_even is True assert (k*m*x).is_odd is False # issue 6791: assert (x/2).is_integer is None assert (k/2).is_integer is False assert (m/2).is_integer is True assert (x*y).is_even is None assert (x*x).is_even is None assert (x*(x + k)).is_even is True assert (x*(x + m)).is_even is None assert (x*y).is_odd is None assert (x*x).is_odd is None assert (x*(x + k)).is_odd is False assert (x*(x + m)).is_odd is None # issue 8648 assert (m**2/2).is_even assert (m**2/3).is_even is False assert (2/m**2).is_odd is False assert (2/m).is_odd is None @XFAIL def test_evenness_in_ternary_integer_product_with_odd(): # Tests that oddness inference is independent of term ordering. # Term ordering at the point of testing depends on SymPy's symbol order, so # we try to force a different order by modifying symbol names. x = Symbol('x', integer=True) y = Symbol('y', integer=True) k = Symbol('k', odd=True) assert (x*y*(y + k)).is_even is True assert (y*x*(x + k)).is_even is True def test_evenness_in_ternary_integer_product_with_even(): x = Symbol('x', integer=True) y = Symbol('y', integer=True) m = Symbol('m', even=True) assert (x*y*(y + m)).is_even is None @XFAIL def test_oddness_in_ternary_integer_product_with_odd(): # Tests that oddness inference is independent of term ordering. # Term ordering at the point of testing depends on SymPy's symbol order, so # we try to force a different order by modifying symbol names. x = Symbol('x', integer=True) y = Symbol('y', integer=True) k = Symbol('k', odd=True) assert (x*y*(y + k)).is_odd is False assert (y*x*(x + k)).is_odd is False def test_oddness_in_ternary_integer_product_with_even(): x = Symbol('x', integer=True) y = Symbol('y', integer=True) m = Symbol('m', even=True) assert (x*y*(y + m)).is_odd is None def test_Mul_is_rational(): x = Symbol('x') n = Symbol('n', integer=True) m = Symbol('m', integer=True, nonzero=True) assert (n/m).is_rational is True assert (x/pi).is_rational is None assert (x/n).is_rational is None assert (m/pi).is_rational is False r = Symbol('r', rational=True) assert (pi*r).is_rational is None # issue 8008 z = Symbol('z', zero=True) i = Symbol('i', imaginary=True) assert (z*i).is_rational is True bi = Symbol('i', imaginary=True, finite=True) assert (z*bi).is_zero is True def test_Add_is_rational(): x = Symbol('x') n = Symbol('n', rational=True) m = Symbol('m', rational=True) assert (n + m).is_rational is True assert (x + pi).is_rational is None assert (x + n).is_rational is None assert (n + pi).is_rational is False def test_Add_is_even_odd(): x = Symbol('x', integer=True) k = Symbol('k', odd=True) n = Symbol('n', odd=True) m = Symbol('m', even=True) assert (k + 7).is_even is True assert (k + 7).is_odd is False assert (-k + 7).is_even is True assert (-k + 7).is_odd is False assert (k - 12).is_even is False assert (k - 12).is_odd is True assert (-k - 12).is_even is False assert (-k - 12).is_odd is True assert (k + n).is_even is True assert (k + n).is_odd is False assert (k + m).is_even is False assert (k + m).is_odd is True assert (k + n + m).is_even is True assert (k + n + m).is_odd is False assert (k + n + x + m).is_even is None assert (k + n + x + m).is_odd is None def test_Mul_is_negative_positive(): x = Symbol('x', real=True) y = Symbol('y', extended_real=False, complex=True) z = Symbol('z', zero=True) e = 2*z assert e.is_Mul and e.is_positive is False and e.is_negative is False neg = Symbol('neg', negative=True) pos = Symbol('pos', positive=True) nneg = Symbol('nneg', nonnegative=True) npos = Symbol('npos', nonpositive=True) assert neg.is_negative is True assert (-neg).is_negative is False assert (2*neg).is_negative is True assert (2*pos)._eval_is_extended_negative() is False assert (2*pos).is_negative is False assert pos.is_negative is False assert (-pos).is_negative is True assert (2*pos).is_negative is False assert (pos*neg).is_negative is True assert (2*pos*neg).is_negative is True assert (-pos*neg).is_negative is False assert (pos*neg*y).is_negative is False # y.is_real=F; !real -> !neg assert nneg.is_negative is False assert (-nneg).is_negative is None assert (2*nneg).is_negative is False assert npos.is_negative is None assert (-npos).is_negative is False assert (2*npos).is_negative is None assert (nneg*npos).is_negative is None assert (neg*nneg).is_negative is None assert (neg*npos).is_negative is False assert (pos*nneg).is_negative is False assert (pos*npos).is_negative is None assert (npos*neg*nneg).is_negative is False assert (npos*pos*nneg).is_negative is None assert (-npos*neg*nneg).is_negative is None assert (-npos*pos*nneg).is_negative is False assert (17*npos*neg*nneg).is_negative is False assert (17*npos*pos*nneg).is_negative is None assert (neg*npos*pos*nneg).is_negative is False assert (x*neg).is_negative is None assert (nneg*npos*pos*x*neg).is_negative is None assert neg.is_positive is False assert (-neg).is_positive is True assert (2*neg).is_positive is False assert pos.is_positive is True assert (-pos).is_positive is False assert (2*pos).is_positive is True assert (pos*neg).is_positive is False assert (2*pos*neg).is_positive is False assert (-pos*neg).is_positive is True assert (-pos*neg*y).is_positive is False # y.is_real=F; !real -> !neg assert nneg.is_positive is None assert (-nneg).is_positive is False assert (2*nneg).is_positive is None assert npos.is_positive is False assert (-npos).is_positive is None assert (2*npos).is_positive is False assert (nneg*npos).is_positive is False assert (neg*nneg).is_positive is False assert (neg*npos).is_positive is None assert (pos*nneg).is_positive is None assert (pos*npos).is_positive is False assert (npos*neg*nneg).is_positive is None assert (npos*pos*nneg).is_positive is False assert (-npos*neg*nneg).is_positive is False assert (-npos*pos*nneg).is_positive is None assert (17*npos*neg*nneg).is_positive is None assert (17*npos*pos*nneg).is_positive is False assert (neg*npos*pos*nneg).is_positive is None assert (x*neg).is_positive is None assert (nneg*npos*pos*x*neg).is_positive is None def test_Mul_is_negative_positive_2(): a = Symbol('a', nonnegative=True) b = Symbol('b', nonnegative=True) c = Symbol('c', nonpositive=True) d = Symbol('d', nonpositive=True) assert (a*b).is_nonnegative is True assert (a*b).is_negative is False assert (a*b).is_zero is None assert (a*b).is_positive is None assert (c*d).is_nonnegative is True assert (c*d).is_negative is False assert (c*d).is_zero is None assert (c*d).is_positive is None assert (a*c).is_nonpositive is True assert (a*c).is_positive is False assert (a*c).is_zero is None assert (a*c).is_negative is None def test_Mul_is_nonpositive_nonnegative(): x = Symbol('x', real=True) k = Symbol('k', negative=True) n = Symbol('n', positive=True) u = Symbol('u', nonnegative=True) v = Symbol('v', nonpositive=True) assert k.is_nonpositive is True assert (-k).is_nonpositive is False assert (2*k).is_nonpositive is True assert n.is_nonpositive is False assert (-n).is_nonpositive is True assert (2*n).is_nonpositive is False assert (n*k).is_nonpositive is True assert (2*n*k).is_nonpositive is True assert (-n*k).is_nonpositive is False assert u.is_nonpositive is None assert (-u).is_nonpositive is True assert (2*u).is_nonpositive is None assert v.is_nonpositive is True assert (-v).is_nonpositive is None assert (2*v).is_nonpositive is True assert (u*v).is_nonpositive is True assert (k*u).is_nonpositive is True assert (k*v).is_nonpositive is None assert (n*u).is_nonpositive is None assert (n*v).is_nonpositive is True assert (v*k*u).is_nonpositive is None assert (v*n*u).is_nonpositive is True assert (-v*k*u).is_nonpositive is True assert (-v*n*u).is_nonpositive is None assert (17*v*k*u).is_nonpositive is None assert (17*v*n*u).is_nonpositive is True assert (k*v*n*u).is_nonpositive is None assert (x*k).is_nonpositive is None assert (u*v*n*x*k).is_nonpositive is None assert k.is_nonnegative is False assert (-k).is_nonnegative is True assert (2*k).is_nonnegative is False assert n.is_nonnegative is True assert (-n).is_nonnegative is False assert (2*n).is_nonnegative is True assert (n*k).is_nonnegative is False assert (2*n*k).is_nonnegative is False assert (-n*k).is_nonnegative is True assert u.is_nonnegative is True assert (-u).is_nonnegative is None assert (2*u).is_nonnegative is True assert v.is_nonnegative is None assert (-v).is_nonnegative is True assert (2*v).is_nonnegative is None assert (u*v).is_nonnegative is None assert (k*u).is_nonnegative is None assert (k*v).is_nonnegative is True assert (n*u).is_nonnegative is True assert (n*v).is_nonnegative is None assert (v*k*u).is_nonnegative is True assert (v*n*u).is_nonnegative is None assert (-v*k*u).is_nonnegative is None assert (-v*n*u).is_nonnegative is True assert (17*v*k*u).is_nonnegative is True assert (17*v*n*u).is_nonnegative is None assert (k*v*n*u).is_nonnegative is True assert (x*k).is_nonnegative is None assert (u*v*n*x*k).is_nonnegative is None def test_Add_is_negative_positive(): x = Symbol('x', real=True) k = Symbol('k', negative=True) n = Symbol('n', positive=True) u = Symbol('u', nonnegative=True) v = Symbol('v', nonpositive=True) assert (k - 2).is_negative is True assert (k + 17).is_negative is None assert (-k - 5).is_negative is None assert (-k + 123).is_negative is False assert (k - n).is_negative is True assert (k + n).is_negative is None assert (-k - n).is_negative is None assert (-k + n).is_negative is False assert (k - n - 2).is_negative is True assert (k + n + 17).is_negative is None assert (-k - n - 5).is_negative is None assert (-k + n + 123).is_negative is False assert (-2*k + 123*n + 17).is_negative is False assert (k + u).is_negative is None assert (k + v).is_negative is True assert (n + u).is_negative is False assert (n + v).is_negative is None assert (u - v).is_negative is False assert (u + v).is_negative is None assert (-u - v).is_negative is None assert (-u + v).is_negative is None assert (u - v + n + 2).is_negative is False assert (u + v + n + 2).is_negative is None assert (-u - v + n + 2).is_negative is None assert (-u + v + n + 2).is_negative is None assert (k + x).is_negative is None assert (k + x - n).is_negative is None assert (k - 2).is_positive is False assert (k + 17).is_positive is None assert (-k - 5).is_positive is None assert (-k + 123).is_positive is True assert (k - n).is_positive is False assert (k + n).is_positive is None assert (-k - n).is_positive is None assert (-k + n).is_positive is True assert (k - n - 2).is_positive is False assert (k + n + 17).is_positive is None assert (-k - n - 5).is_positive is None assert (-k + n + 123).is_positive is True assert (-2*k + 123*n + 17).is_positive is True assert (k + u).is_positive is None assert (k + v).is_positive is False assert (n + u).is_positive is True assert (n + v).is_positive is None assert (u - v).is_positive is None assert (u + v).is_positive is None assert (-u - v).is_positive is None assert (-u + v).is_positive is False assert (u - v - n - 2).is_positive is None assert (u + v - n - 2).is_positive is None assert (-u - v - n - 2).is_positive is None assert (-u + v - n - 2).is_positive is False assert (n + x).is_positive is None assert (n + x - k).is_positive is None z = (-3 - sqrt(5) + (-sqrt(10)/2 - sqrt(2)/2)**2) assert z.is_zero z = sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3)) - sqrt(10 + 6*sqrt(3)) assert z.is_zero def test_Add_is_nonpositive_nonnegative(): x = Symbol('x', real=True) k = Symbol('k', negative=True) n = Symbol('n', positive=True) u = Symbol('u', nonnegative=True) v = Symbol('v', nonpositive=True) assert (u - 2).is_nonpositive is None assert (u + 17).is_nonpositive is False assert (-u - 5).is_nonpositive is True assert (-u + 123).is_nonpositive is None assert (u - v).is_nonpositive is None assert (u + v).is_nonpositive is None assert (-u - v).is_nonpositive is None assert (-u + v).is_nonpositive is True assert (u - v - 2).is_nonpositive is None assert (u + v + 17).is_nonpositive is None assert (-u - v - 5).is_nonpositive is None assert (-u + v - 123).is_nonpositive is True assert (-2*u + 123*v - 17).is_nonpositive is True assert (k + u).is_nonpositive is None assert (k + v).is_nonpositive is True assert (n + u).is_nonpositive is False assert (n + v).is_nonpositive is None assert (k - n).is_nonpositive is True assert (k + n).is_nonpositive is None assert (-k - n).is_nonpositive is None assert (-k + n).is_nonpositive is False assert (k - n + u + 2).is_nonpositive is None assert (k + n + u + 2).is_nonpositive is None assert (-k - n + u + 2).is_nonpositive is None assert (-k + n + u + 2).is_nonpositive is False assert (u + x).is_nonpositive is None assert (v - x - n).is_nonpositive is None assert (u - 2).is_nonnegative is None assert (u + 17).is_nonnegative is True assert (-u - 5).is_nonnegative is False assert (-u + 123).is_nonnegative is None assert (u - v).is_nonnegative is True assert (u + v).is_nonnegative is None assert (-u - v).is_nonnegative is None assert (-u + v).is_nonnegative is None assert (u - v + 2).is_nonnegative is True assert (u + v + 17).is_nonnegative is None assert (-u - v - 5).is_nonnegative is None assert (-u + v - 123).is_nonnegative is False assert (2*u - 123*v + 17).is_nonnegative is True assert (k + u).is_nonnegative is None assert (k + v).is_nonnegative is False assert (n + u).is_nonnegative is True assert (n + v).is_nonnegative is None assert (k - n).is_nonnegative is False assert (k + n).is_nonnegative is None assert (-k - n).is_nonnegative is None assert (-k + n).is_nonnegative is True assert (k - n - u - 2).is_nonnegative is False assert (k + n - u - 2).is_nonnegative is None assert (-k - n - u - 2).is_nonnegative is None assert (-k + n - u - 2).is_nonnegative is None assert (u - x).is_nonnegative is None assert (v + x + n).is_nonnegative is None def test_Pow_is_integer(): x = Symbol('x') k = Symbol('k', integer=True) n = Symbol('n', integer=True, nonnegative=True) m = Symbol('m', integer=True, positive=True) assert (k**2).is_integer is True assert (k**(-2)).is_integer is None assert ((m + 1)**(-2)).is_integer is False assert (m**(-1)).is_integer is None # issue 8580 assert (2**k).is_integer is None assert (2**(-k)).is_integer is None assert (2**n).is_integer is True assert (2**(-n)).is_integer is None assert (2**m).is_integer is True assert (2**(-m)).is_integer is False assert (x**2).is_integer is None assert (2**x).is_integer is None assert (k**n).is_integer is True assert (k**(-n)).is_integer is None assert (k**x).is_integer is None assert (x**k).is_integer is None assert (k**(n*m)).is_integer is True assert (k**(-n*m)).is_integer is None assert sqrt(3).is_integer is False assert sqrt(.3).is_integer is False assert Pow(3, 2, evaluate=False).is_integer is True assert Pow(3, 0, evaluate=False).is_integer is True assert Pow(3, -2, evaluate=False).is_integer is False assert Pow(S.Half, 3, evaluate=False).is_integer is False # decided by re-evaluating assert Pow(3, S.Half, evaluate=False).is_integer is False assert Pow(3, S.Half, evaluate=False).is_integer is False assert Pow(4, S.Half, evaluate=False).is_integer is True assert Pow(S.Half, -2, evaluate=False).is_integer is True assert ((-1)**k).is_integer # issue 8641 x = Symbol('x', real=True, integer=False) assert (x**2).is_integer is None # issue 10458 x = Symbol('x', positive=True) assert (1/(x + 1)).is_integer is False assert (1/(-x - 1)).is_integer is False assert (-1/(x + 1)).is_integer is False # issue 8648-like k = Symbol('k', even=True) assert (k**3/2).is_integer assert (k**3/8).is_integer assert (k**3/16).is_integer is None assert (2/k).is_integer is None assert (2/k**2).is_integer is False o = Symbol('o', odd=True) assert (k/o).is_integer is None o = Symbol('o', odd=True, prime=True) assert (k/o).is_integer is False def test_Pow_is_real(): x = Symbol('x', real=True) y = Symbol('y', positive=True) assert (x**2).is_real is True assert (x**3).is_real is True assert (x**x).is_real is None assert (y**x).is_real is True assert (x**Rational(1, 3)).is_real is None assert (y**Rational(1, 3)).is_real is True assert sqrt(-1 - sqrt(2)).is_real is False i = Symbol('i', imaginary=True) assert (i**i).is_real is None assert (I**i).is_extended_real is True assert ((-I)**i).is_extended_real is True assert (2**i).is_real is None # (2**(pi/log(2) * I)) is real, 2**I is not assert (2**I).is_real is False assert (2**-I).is_real is False assert (i**2).is_extended_real is True assert (i**3).is_extended_real is False assert (i**x).is_real is None # could be (-I)**(2/3) e = Symbol('e', even=True) o = Symbol('o', odd=True) k = Symbol('k', integer=True) assert (i**e).is_extended_real is True assert (i**o).is_extended_real is False assert (i**k).is_real is None assert (i**(4*k)).is_extended_real is True x = Symbol("x", nonnegative=True) y = Symbol("y", nonnegative=True) assert im(x**y).expand(complex=True) is S.Zero assert (x**y).is_real is True i = Symbol('i', imaginary=True) assert (exp(i)**I).is_extended_real is True assert log(exp(i)).is_imaginary is None # i could be 2*pi*I c = Symbol('c', complex=True) assert log(c).is_real is None # c could be 0 or 2, too assert log(exp(c)).is_real is None # log(0), log(E), ... n = Symbol('n', negative=False) assert log(n).is_real is None n = Symbol('n', nonnegative=True) assert log(n).is_real is None assert sqrt(-I).is_real is False # issue 7843 i = Symbol('i', integer=True) assert (1/(i-1)).is_real is None assert (1/(i-1)).is_extended_real is None # test issue 20715 from sympy.core.parameters import evaluate x = S(-1) with evaluate(False): assert x.is_negative is True f = Pow(x, -1) with evaluate(False): assert f.is_imaginary is False def test_real_Pow(): k = Symbol('k', integer=True, nonzero=True) assert (k**(I*pi/log(k))).is_real def test_Pow_is_finite(): xe = Symbol('xe', extended_real=True) xr = Symbol('xr', real=True) p = Symbol('p', positive=True) n = Symbol('n', negative=True) i = Symbol('i', integer=True) assert (xe**2).is_finite is None # xe could be oo assert (xr**2).is_finite is True assert (xe**xe).is_finite is None assert (xr**xe).is_finite is None assert (xe**xr).is_finite is None # FIXME: The line below should be True rather than None # assert (xr**xr).is_finite is True assert (xr**xr).is_finite is None assert (p**xe).is_finite is None assert (p**xr).is_finite is True assert (n**xe).is_finite is None assert (n**xr).is_finite is True assert (sin(xe)**2).is_finite is True assert (sin(xr)**2).is_finite is True assert (sin(xe)**xe).is_finite is None # xe, xr could be -pi assert (sin(xr)**xr).is_finite is None # FIXME: Should the line below be True rather than None? assert (sin(xe)**exp(xe)).is_finite is None assert (sin(xr)**exp(xr)).is_finite is True assert (1/sin(xe)).is_finite is None # if zero, no, otherwise yes assert (1/sin(xr)).is_finite is None assert (1/exp(xe)).is_finite is None # xe could be -oo assert (1/exp(xr)).is_finite is True assert (1/S.Pi).is_finite is True assert (1/(i-1)).is_finite is None def test_Pow_is_even_odd(): x = Symbol('x') k = Symbol('k', even=True) n = Symbol('n', odd=True) m = Symbol('m', integer=True, nonnegative=True) p = Symbol('p', integer=True, positive=True) assert ((-1)**n).is_odd assert ((-1)**k).is_odd assert ((-1)**(m - p)).is_odd assert (k**2).is_even is True assert (n**2).is_even is False assert (2**k).is_even is None assert (x**2).is_even is None assert (k**m).is_even is None assert (n**m).is_even is False assert (k**p).is_even is True assert (n**p).is_even is False assert (m**k).is_even is None assert (p**k).is_even is None assert (m**n).is_even is None assert (p**n).is_even is None assert (k**x).is_even is None assert (n**x).is_even is None assert (k**2).is_odd is False assert (n**2).is_odd is True assert (3**k).is_odd is None assert (k**m).is_odd is None assert (n**m).is_odd is True assert (k**p).is_odd is False assert (n**p).is_odd is True assert (m**k).is_odd is None assert (p**k).is_odd is None assert (m**n).is_odd is None assert (p**n).is_odd is None assert (k**x).is_odd is None assert (n**x).is_odd is None def test_Pow_is_negative_positive(): r = Symbol('r', real=True) k = Symbol('k', integer=True, positive=True) n = Symbol('n', even=True) m = Symbol('m', odd=True) x = Symbol('x') assert (2**r).is_positive is True assert ((-2)**r).is_positive is None assert ((-2)**n).is_positive is True assert ((-2)**m).is_positive is False assert (k**2).is_positive is True assert (k**(-2)).is_positive is True assert (k**r).is_positive is True assert ((-k)**r).is_positive is None assert ((-k)**n).is_positive is True assert ((-k)**m).is_positive is False assert (2**r).is_negative is False assert ((-2)**r).is_negative is None assert ((-2)**n).is_negative is False assert ((-2)**m).is_negative is True assert (k**2).is_negative is False assert (k**(-2)).is_negative is False assert (k**r).is_negative is False assert ((-k)**r).is_negative is None assert ((-k)**n).is_negative is False assert ((-k)**m).is_negative is True assert (2**x).is_positive is None assert (2**x).is_negative is None def test_Pow_is_zero(): z = Symbol('z', zero=True) e = z**2 assert e.is_zero assert e.is_positive is False assert e.is_negative is False assert Pow(0, 0, evaluate=False).is_zero is False assert Pow(0, 3, evaluate=False).is_zero assert Pow(0, oo, evaluate=False).is_zero assert Pow(0, -3, evaluate=False).is_zero is False assert Pow(0, -oo, evaluate=False).is_zero is False assert Pow(2, 2, evaluate=False).is_zero is False a = Symbol('a', zero=False) assert Pow(a, 3).is_zero is False # issue 7965 assert Pow(2, oo, evaluate=False).is_zero is False assert Pow(2, -oo, evaluate=False).is_zero assert Pow(S.Half, oo, evaluate=False).is_zero assert Pow(S.Half, -oo, evaluate=False).is_zero is False # All combinations of real/complex base/exponent h = S.Half T = True F = False N = None pow_iszero = [ ['**', 0, h, 1, 2, -h, -1,-2,-2*I,-I/2,I/2,1+I,oo,-oo,zoo], [ 0, F, T, T, T, F, F, F, F, F, F, N, T, F, N], [ h, F, F, F, F, F, F, F, F, F, F, F, T, F, N], [ 1, F, F, F, F, F, F, F, F, F, F, F, F, F, N], [ 2, F, F, F, F, F, F, F, F, F, F, F, F, T, N], [ -h, F, F, F, F, F, F, F, F, F, F, F, T, F, N], [ -1, F, F, F, F, F, F, F, F, F, F, F, F, F, N], [ -2, F, F, F, F, F, F, F, F, F, F, F, F, T, N], [-2*I, F, F, F, F, F, F, F, F, F, F, F, F, T, N], [-I/2, F, F, F, F, F, F, F, F, F, F, F, T, F, N], [ I/2, F, F, F, F, F, F, F, F, F, F, F, T, F, N], [ 1+I, F, F, F, F, F, F, F, F, F, F, F, F, T, N], [ oo, F, F, F, F, T, T, T, F, F, F, F, F, T, N], [ -oo, F, F, F, F, T, T, T, F, F, F, F, F, T, N], [ zoo, F, F, F, F, T, T, T, N, N, N, N, F, T, N] ] def test_table(table): n = len(table[0]) for row in range(1, n): base = table[row][0] for col in range(1, n): exp = table[0][col] is_zero = table[row][col] # The actual test here: assert Pow(base, exp, evaluate=False).is_zero is is_zero test_table(pow_iszero) # A zero symbol... zo, zo2 = symbols('zo, zo2', zero=True) # All combinations of finite symbols zf, zf2 = symbols('zf, zf2', finite=True) wf, wf2 = symbols('wf, wf2', nonzero=True) xf, xf2 = symbols('xf, xf2', real=True) yf, yf2 = symbols('yf, yf2', nonzero=True) af, af2 = symbols('af, af2', positive=True) bf, bf2 = symbols('bf, bf2', nonnegative=True) cf, cf2 = symbols('cf, cf2', negative=True) df, df2 = symbols('df, df2', nonpositive=True) # Without finiteness: zi, zi2 = symbols('zi, zi2') wi, wi2 = symbols('wi, wi2', zero=False) xi, xi2 = symbols('xi, xi2', extended_real=True) yi, yi2 = symbols('yi, yi2', zero=False, extended_real=True) ai, ai2 = symbols('ai, ai2', extended_positive=True) bi, bi2 = symbols('bi, bi2', extended_nonnegative=True) ci, ci2 = symbols('ci, ci2', extended_negative=True) di, di2 = symbols('di, di2', extended_nonpositive=True) pow_iszero_sym = [ ['**',zo,wf,yf,af,cf,zf,xf,bf,df,zi,wi,xi,yi,ai,bi,ci,di], [ zo2, F, N, N, T, F, N, N, N, F, N, N, N, N, T, N, F, F], [ wf2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N], [ yf2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N], [ af2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N], [ cf2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N], [ zf2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N], [ xf2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N], [ bf2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N], [ df2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N], [ zi2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N], [ wi2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N], [ xi2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N], [ yi2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N], [ ai2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N], [ bi2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N], [ ci2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N], [ di2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N] ] test_table(pow_iszero_sym) # In some cases (x**x).is_zero is different from (x**y).is_zero even if y # has the same assumptions as x. assert (zo ** zo).is_zero is False assert (wf ** wf).is_zero is False assert (yf ** yf).is_zero is False assert (af ** af).is_zero is False assert (cf ** cf).is_zero is False assert (zf ** zf).is_zero is None assert (xf ** xf).is_zero is None assert (bf ** bf).is_zero is False # None in table assert (df ** df).is_zero is None assert (zi ** zi).is_zero is None assert (wi ** wi).is_zero is None assert (xi ** xi).is_zero is None assert (yi ** yi).is_zero is None assert (ai ** ai).is_zero is False # None in table assert (bi ** bi).is_zero is False # None in table assert (ci ** ci).is_zero is None assert (di ** di).is_zero is None def test_Pow_is_nonpositive_nonnegative(): x = Symbol('x', real=True) k = Symbol('k', integer=True, nonnegative=True) l = Symbol('l', integer=True, positive=True) n = Symbol('n', even=True) m = Symbol('m', odd=True) assert (x**(4*k)).is_nonnegative is True assert (2**x).is_nonnegative is True assert ((-2)**x).is_nonnegative is None assert ((-2)**n).is_nonnegative is True assert ((-2)**m).is_nonnegative is False assert (k**2).is_nonnegative is True assert (k**(-2)).is_nonnegative is None assert (k**k).is_nonnegative is True assert (k**x).is_nonnegative is None # NOTE (0**x).is_real = U assert (l**x).is_nonnegative is True assert (l**x).is_positive is True assert ((-k)**x).is_nonnegative is None assert ((-k)**m).is_nonnegative is None assert (2**x).is_nonpositive is False assert ((-2)**x).is_nonpositive is None assert ((-2)**n).is_nonpositive is False assert ((-2)**m).is_nonpositive is True assert (k**2).is_nonpositive is None assert (k**(-2)).is_nonpositive is None assert (k**x).is_nonpositive is None assert ((-k)**x).is_nonpositive is None assert ((-k)**n).is_nonpositive is None assert (x**2).is_nonnegative is True i = symbols('i', imaginary=True) assert (i**2).is_nonpositive is True assert (i**4).is_nonpositive is False assert (i**3).is_nonpositive is False assert (I**i).is_nonnegative is True assert (exp(I)**i).is_nonnegative is True assert ((-l)**n).is_nonnegative is True assert ((-l)**m).is_nonpositive is True assert ((-k)**n).is_nonnegative is None assert ((-k)**m).is_nonpositive is None def test_Mul_is_imaginary_real(): r = Symbol('r', real=True) p = Symbol('p', positive=True) i1 = Symbol('i1', imaginary=True) i2 = Symbol('i2', imaginary=True) x = Symbol('x') assert I.is_imaginary is True assert I.is_real is False assert (-I).is_imaginary is True assert (-I).is_real is False assert (3*I).is_imaginary is True assert (3*I).is_real is False assert (I*I).is_imaginary is False assert (I*I).is_real is True e = (p + p*I) j = Symbol('j', integer=True, zero=False) assert (e**j).is_real is None assert (e**(2*j)).is_real is None assert (e**j).is_imaginary is None assert (e**(2*j)).is_imaginary is None assert (e**-1).is_imaginary is False assert (e**2).is_imaginary assert (e**3).is_imaginary is False assert (e**4).is_imaginary is False assert (e**5).is_imaginary is False assert (e**-1).is_real is False assert (e**2).is_real is False assert (e**3).is_real is False assert (e**4).is_real is True assert (e**5).is_real is False assert (e**3).is_complex assert (r*i1).is_imaginary is None assert (r*i1).is_real is None assert (x*i1).is_imaginary is None assert (x*i1).is_real is None assert (i1*i2).is_imaginary is False assert (i1*i2).is_real is True assert (r*i1*i2).is_imaginary is False assert (r*i1*i2).is_real is True # Github's issue 5874: nr = Symbol('nr', real=False, complex=True) # e.g. I or 1 + I a = Symbol('a', real=True, nonzero=True) b = Symbol('b', real=True) assert (i1*nr).is_real is None assert (a*nr).is_real is False assert (b*nr).is_real is None ni = Symbol('ni', imaginary=False, complex=True) # e.g. 2 or 1 + I a = Symbol('a', real=True, nonzero=True) b = Symbol('b', real=True) assert (i1*ni).is_real is False assert (a*ni).is_real is None assert (b*ni).is_real is None def test_Mul_hermitian_antihermitian(): a = Symbol('a', hermitian=True, zero=False) b = Symbol('b', hermitian=True) c = Symbol('c', hermitian=False) d = Symbol('d', antihermitian=True) e1 = Mul(a, b, c, evaluate=False) e2 = Mul(b, a, c, evaluate=False) e3 = Mul(a, b, c, d, evaluate=False) e4 = Mul(b, a, c, d, evaluate=False) e5 = Mul(a, c, evaluate=False) e6 = Mul(a, c, d, evaluate=False) assert e1.is_hermitian is None assert e2.is_hermitian is None assert e1.is_antihermitian is None assert e2.is_antihermitian is None assert e3.is_antihermitian is None assert e4.is_antihermitian is None assert e5.is_antihermitian is None assert e6.is_antihermitian is None def test_Add_is_comparable(): assert (x + y).is_comparable is False assert (x + 1).is_comparable is False assert (Rational(1, 3) - sqrt(8)).is_comparable is True def test_Mul_is_comparable(): assert (x*y).is_comparable is False assert (x*2).is_comparable is False assert (sqrt(2)*Rational(1, 3)).is_comparable is True def test_Pow_is_comparable(): assert (x**y).is_comparable is False assert (x**2).is_comparable is False assert (sqrt(Rational(1, 3))).is_comparable is True def test_Add_is_positive_2(): e = Rational(1, 3) - sqrt(8) assert e.is_positive is False assert e.is_negative is True e = pi - 1 assert e.is_positive is True assert e.is_negative is False def test_Add_is_irrational(): i = Symbol('i', irrational=True) assert i.is_irrational is True assert i.is_rational is False assert (i + 1).is_irrational is True assert (i + 1).is_rational is False def test_Mul_is_irrational(): expr = Mul(1, 2, 3, evaluate=False) assert expr.is_irrational is False expr = Mul(1, I, I, evaluate=False) assert expr.is_rational is None # I * I = -1 but *no evaluation allowed* # sqrt(2) * I * I = -sqrt(2) is irrational but # this can't be determined without evaluating the # expression and the eval_is routines shouldn't do that expr = Mul(sqrt(2), I, I, evaluate=False) assert expr.is_irrational is None def test_issue_3531(): # https://github.com/sympy/sympy/issues/3531 # https://github.com/sympy/sympy/pull/18116 class MightyNumeric(tuple): def __rtruediv__(self, other): return "something" assert sympify(1)/MightyNumeric((1, 2)) == "something" def test_issue_3531b(): class Foo: def __init__(self): self.field = 1.0 def __mul__(self, other): self.field = self.field * other def __rmul__(self, other): self.field = other * self.field f = Foo() x = Symbol("x") assert f*x == x*f def test_bug3(): a = Symbol("a") b = Symbol("b", positive=True) e = 2*a + b f = b + 2*a assert e == f def test_suppressed_evaluation(): a = Add(0, 3, 2, evaluate=False) b = Mul(1, 3, 2, evaluate=False) c = Pow(3, 2, evaluate=False) assert a != 6 assert a.func is Add assert a.args == (0, 3, 2) assert b != 6 assert b.func is Mul assert b.args == (1, 3, 2) assert c != 9 assert c.func is Pow assert c.args == (3, 2) def test_AssocOp_doit(): a = Add(x,x, evaluate=False) b = Mul(y,y, evaluate=False) c = Add(b,b, evaluate=False) d = Mul(a,a, evaluate=False) assert c.doit(deep=False).func == Mul assert c.doit(deep=False).args == (2,y,y) assert c.doit().func == Mul assert c.doit().args == (2, Pow(y,2)) assert d.doit(deep=False).func == Pow assert d.doit(deep=False).args == (a, 2*S.One) assert d.doit().func == Mul assert d.doit().args == (4*S.One, Pow(x,2)) def test_Add_Mul_Expr_args(): nonexpr = [Basic(), Poly(x, x), FiniteSet(x)] for typ in [Add, Mul]: for obj in nonexpr: with warns_deprecated_sympy(): typ(obj, 1) def test_Add_as_coeff_mul(): # issue 5524. These should all be (1, self) assert (x + 1).as_coeff_mul() == (1, (x + 1,)) assert (x + 2).as_coeff_mul() == (1, (x + 2,)) assert (x + 3).as_coeff_mul() == (1, (x + 3,)) assert (x - 1).as_coeff_mul() == (1, (x - 1,)) assert (x - 2).as_coeff_mul() == (1, (x - 2,)) assert (x - 3).as_coeff_mul() == (1, (x - 3,)) n = Symbol('n', integer=True) assert (n + 1).as_coeff_mul() == (1, (n + 1,)) assert (n + 2).as_coeff_mul() == (1, (n + 2,)) assert (n + 3).as_coeff_mul() == (1, (n + 3,)) assert (n - 1).as_coeff_mul() == (1, (n - 1,)) assert (n - 2).as_coeff_mul() == (1, (n - 2,)) assert (n - 3).as_coeff_mul() == (1, (n - 3,)) def test_Pow_as_coeff_mul_doesnt_expand(): assert exp(x + y).as_coeff_mul() == (1, (exp(x + y),)) assert exp(x + exp(x + y)) != exp(x + exp(x)*exp(y)) def test_issue_3514_18626(): assert sqrt(S.Half) * sqrt(6) == 2 * sqrt(3)/2 assert S.Half*sqrt(6)*sqrt(2) == sqrt(3) assert sqrt(6)/2*sqrt(2) == sqrt(3) assert sqrt(6)*sqrt(2)/2 == sqrt(3) assert sqrt(8)**Rational(2, 3) == 2 def test_make_args(): assert Add.make_args(x) == (x,) assert Mul.make_args(x) == (x,) assert Add.make_args(x*y*z) == (x*y*z,) assert Mul.make_args(x*y*z) == (x*y*z).args assert Add.make_args(x + y + z) == (x + y + z).args assert Mul.make_args(x + y + z) == (x + y + z,) assert Add.make_args((x + y)**z) == ((x + y)**z,) assert Mul.make_args((x + y)**z) == ((x + y)**z,) def test_issue_5126(): assert (-2)**x*(-3)**x != 6**x i = Symbol('i', integer=1) assert (-2)**i*(-3)**i == 6**i def test_Rational_as_content_primitive(): c, p = S.One, S.Zero assert (c*p).as_content_primitive() == (c, p) c, p = S.Half, S.One assert (c*p).as_content_primitive() == (c, p) def test_Add_as_content_primitive(): assert (x + 2).as_content_primitive() == (1, x + 2) assert (3*x + 2).as_content_primitive() == (1, 3*x + 2) assert (3*x + 3).as_content_primitive() == (3, x + 1) assert (3*x + 6).as_content_primitive() == (3, x + 2) assert (3*x + 2*y).as_content_primitive() == (1, 3*x + 2*y) assert (3*x + 3*y).as_content_primitive() == (3, x + y) assert (3*x + 6*y).as_content_primitive() == (3, x + 2*y) assert (3/x + 2*x*y*z**2).as_content_primitive() == (1, 3/x + 2*x*y*z**2) assert (3/x + 3*x*y*z**2).as_content_primitive() == (3, 1/x + x*y*z**2) assert (3/x + 6*x*y*z**2).as_content_primitive() == (3, 1/x + 2*x*y*z**2) assert (2*x/3 + 4*y/9).as_content_primitive() == \ (Rational(2, 9), 3*x + 2*y) assert (2*x/3 + 2.5*y).as_content_primitive() == \ (Rational(1, 3), 2*x + 7.5*y) # the coefficient may sort to a position other than 0 p = 3 + x + y assert (2*p).expand().as_content_primitive() == (2, p) assert (2.0*p).expand().as_content_primitive() == (1, 2.*p) p *= -1 assert (2*p).expand().as_content_primitive() == (2, p) def test_Mul_as_content_primitive(): assert (2*x).as_content_primitive() == (2, x) assert (x*(2 + 2*x)).as_content_primitive() == (2, x*(1 + x)) assert (x*(2 + 2*y)*(3*x + 3)**2).as_content_primitive() == \ (18, x*(1 + y)*(x + 1)**2) assert ((2 + 2*x)**2*(3 + 6*x) + S.Half).as_content_primitive() == \ (S.Half, 24*(x + 1)**2*(2*x + 1) + 1) def test_Pow_as_content_primitive(): assert (x**y).as_content_primitive() == (1, x**y) assert ((2*x + 2)**y).as_content_primitive() == \ (1, (Mul(2, (x + 1), evaluate=False))**y) assert ((2*x + 2)**3).as_content_primitive() == (8, (x + 1)**3) def test_issue_5460(): u = Mul(2, (1 + x), evaluate=False) assert (2 + u).args == (2, u) def test_product_irrational(): assert (I*pi).is_irrational is False # The following used to be deduced from the above bug: assert (I*pi).is_positive is False def test_issue_5919(): assert (x/(y*(1 + y))).expand() == x/(y**2 + y) def test_Mod(): assert Mod(x, 1).func is Mod assert pi % pi is S.Zero assert Mod(5, 3) == 2 assert Mod(-5, 3) == 1 assert Mod(5, -3) == -1 assert Mod(-5, -3) == -2 assert type(Mod(3.2, 2, evaluate=False)) == Mod assert 5 % x == Mod(5, x) assert x % 5 == Mod(x, 5) assert x % y == Mod(x, y) assert (x % y).subs({x: 5, y: 3}) == 2 assert Mod(nan, 1) is nan assert Mod(1, nan) is nan assert Mod(nan, nan) is nan assert Mod(0, x) == 0 with raises(ZeroDivisionError): Mod(x, 0) k = Symbol('k', integer=True) m = Symbol('m', integer=True, positive=True) assert (x**m % x).func is Mod assert (k**(-m) % k).func is Mod assert k**m % k == 0 assert (-2*k)**m % k == 0 # Float handling point3 = Float(3.3) % 1 assert (x - 3.3) % 1 == Mod(1.*x + 1 - point3, 1) assert Mod(-3.3, 1) == 1 - point3 assert Mod(0.7, 1) == Float(0.7) e = Mod(1.3, 1) assert comp(e, .3) and e.is_Float e = Mod(1.3, .7) assert comp(e, .6) and e.is_Float e = Mod(1.3, Rational(7, 10)) assert comp(e, .6) and e.is_Float e = Mod(Rational(13, 10), 0.7) assert comp(e, .6) and e.is_Float e = Mod(Rational(13, 10), Rational(7, 10)) assert comp(e, .6) and e.is_Rational # check that sign is right r2 = sqrt(2) r3 = sqrt(3) for i in [-r3, -r2, r2, r3]: for j in [-r3, -r2, r2, r3]: assert verify_numerically(i % j, i.n() % j.n()) for _x in range(4): for _y in range(9): reps = [(x, _x), (y, _y)] assert Mod(3*x + y, 9).subs(reps) == (3*_x + _y) % 9 # denesting t = Symbol('t', real=True) assert Mod(Mod(x, t), t) == Mod(x, t) assert Mod(-Mod(x, t), t) == Mod(-x, t) assert Mod(Mod(x, 2*t), t) == Mod(x, t) assert Mod(-Mod(x, 2*t), t) == Mod(-x, t) assert Mod(Mod(x, t), 2*t) == Mod(x, t) assert Mod(-Mod(x, t), -2*t) == -Mod(x, t) for i in [-4, -2, 2, 4]: for j in [-4, -2, 2, 4]: for k in range(4): assert Mod(Mod(x, i), j).subs({x: k}) == (k % i) % j assert Mod(-Mod(x, i), j).subs({x: k}) == -(k % i) % j # known difference assert Mod(5*sqrt(2), sqrt(5)) == 5*sqrt(2) - 3*sqrt(5) p = symbols('p', positive=True) assert Mod(2, p + 3) == 2 assert Mod(-2, p + 3) == p + 1 assert Mod(2, -p - 3) == -p - 1 assert Mod(-2, -p - 3) == -2 assert Mod(p + 5, p + 3) == 2 assert Mod(-p - 5, p + 3) == p + 1 assert Mod(p + 5, -p - 3) == -p - 1 assert Mod(-p - 5, -p - 3) == -2 assert Mod(p + 1, p - 1).func is Mod # handling sums assert (x + 3) % 1 == Mod(x, 1) assert (x + 3.0) % 1 == Mod(1.*x, 1) assert (x - S(33)/10) % 1 == Mod(x + S(7)/10, 1) a = Mod(.6*x + y, .3*y) b = Mod(0.1*y + 0.6*x, 0.3*y) # Test that a, b are equal, with 1e-14 accuracy in coefficients eps = 1e-14 assert abs((a.args[0] - b.args[0]).subs({x: 1, y: 1})) < eps assert abs((a.args[1] - b.args[1]).subs({x: 1, y: 1})) < eps assert (x + 1) % x == 1 % x assert (x + y) % x == y % x assert (x + y + 2) % x == (y + 2) % x assert (a + 3*x + 1) % (2*x) == Mod(a + x + 1, 2*x) assert (12*x + 18*y) % (3*x) == 3*Mod(6*y, x) # gcd extraction assert (-3*x) % (-2*y) == -Mod(3*x, 2*y) assert (.6*pi) % (.3*x*pi) == 0.3*pi*Mod(2, x) assert (.6*pi) % (.31*x*pi) == pi*Mod(0.6, 0.31*x) assert (6*pi) % (.3*x*pi) == 0.3*pi*Mod(20, x) assert (6*pi) % (.31*x*pi) == pi*Mod(6, 0.31*x) assert (6*pi) % (.42*x*pi) == pi*Mod(6, 0.42*x) assert (12*x) % (2*y) == 2*Mod(6*x, y) assert (12*x) % (3*5*y) == 3*Mod(4*x, 5*y) assert (12*x) % (15*x*y) == 3*x*Mod(4, 5*y) assert (-2*pi) % (3*pi) == pi assert (2*x + 2) % (x + 1) == 0 assert (x*(x + 1)) % (x + 1) == (x + 1)*Mod(x, 1) assert Mod(5.0*x, 0.1*y) == 0.1*Mod(50*x, y) i = Symbol('i', integer=True) assert (3*i*x) % (2*i*y) == i*Mod(3*x, 2*y) assert Mod(4*i, 4) == 0 # issue 8677 n = Symbol('n', integer=True, positive=True) assert factorial(n) % n == 0 assert factorial(n + 2) % n == 0 assert (factorial(n + 4) % (n + 5)).func is Mod # Wilson's theorem assert factorial(18042, evaluate=False) % 18043 == 18042 p = Symbol('n', prime=True) assert factorial(p - 1) % p == p - 1 assert factorial(p - 1) % -p == -1 assert (factorial(3, evaluate=False) % 4).doit() == 2 n = Symbol('n', composite=True, odd=True) assert factorial(n - 1) % n == 0 # symbolic with known parity n = Symbol('n', even=True) assert Mod(n, 2) == 0 n = Symbol('n', odd=True) assert Mod(n, 2) == 1 # issue 10963 assert (x**6000%400).args[1] == 400 #issue 13543 assert Mod(Mod(x + 1, 2) + 1, 2) == Mod(x, 2) assert Mod(Mod(x + 2, 4)*(x + 4), 4) == Mod(x*(x + 2), 4) assert Mod(Mod(x + 2, 4)*4, 4) == 0 # issue 15493 i, j = symbols('i j', integer=True, positive=True) assert Mod(3*i, 2) == Mod(i, 2) assert Mod(8*i/j, 4) == 4*Mod(2*i/j, 1) assert Mod(8*i, 4) == 0 # rewrite assert Mod(x, y).rewrite(floor) == x - y*floor(x/y) assert ((x - Mod(x, y))/y).rewrite(floor) == floor(x/y) # issue 21373 from sympy.functions.elementary.trigonometric import sinh from sympy.functions.elementary.piecewise import Piecewise x_r, y_r = symbols('x_r y_r', real=True) assert (Piecewise((x_r, y_r > x_r), (y_r, True)) / z) % 1 expr = exp(sinh(Piecewise((x_r, y_r > x_r), (y_r, True)) / z)) expr.subs({1: 1.0}) sinh(Piecewise((x_r, y_r > x_r), (y_r, True)) * z ** -1.0).is_zero def test_Mod_Pow(): # modular exponentiation assert isinstance(Mod(Pow(2, 2, evaluate=False), 3), Integer) assert Mod(Pow(4, 13, evaluate=False), 497) == Mod(Pow(4, 13), 497) assert Mod(Pow(2, 10000000000, evaluate=False), 3) == 1 assert Mod(Pow(32131231232, 9**10**6, evaluate=False),10**12) == \ pow(32131231232,9**10**6,10**12) assert Mod(Pow(33284959323, 123**999, evaluate=False),11**13) == \ pow(33284959323,123**999,11**13) assert Mod(Pow(78789849597, 333**555, evaluate=False),12**9) == \ pow(78789849597,333**555,12**9) # modular nested exponentiation expr = Pow(2, 2, evaluate=False) expr = Pow(2, expr, evaluate=False) assert Mod(expr, 3**10) == 16 expr = Pow(2, expr, evaluate=False) assert Mod(expr, 3**10) == 6487 expr = Pow(2, expr, evaluate=False) assert Mod(expr, 3**10) == 32191 expr = Pow(2, expr, evaluate=False) assert Mod(expr, 3**10) == 18016 expr = Pow(2, expr, evaluate=False) assert Mod(expr, 3**10) == 5137 expr = Pow(2, 2, evaluate=False) expr = Pow(expr, 2, evaluate=False) assert Mod(expr, 3**10) == 16 expr = Pow(expr, 2, evaluate=False) assert Mod(expr, 3**10) == 256 expr = Pow(expr, 2, evaluate=False) assert Mod(expr, 3**10) == 6487 expr = Pow(expr, 2, evaluate=False) assert Mod(expr, 3**10) == 38281 expr = Pow(expr, 2, evaluate=False) assert Mod(expr, 3**10) == 15928 expr = Pow(2, 2, evaluate=False) expr = Pow(expr, expr, evaluate=False) assert Mod(expr, 3**10) == 256 expr = Pow(expr, expr, evaluate=False) assert Mod(expr, 3**10) == 9229 expr = Pow(expr, expr, evaluate=False) assert Mod(expr, 3**10) == 25708 expr = Pow(expr, expr, evaluate=False) assert Mod(expr, 3**10) == 26608 expr = Pow(expr, expr, evaluate=False) # XXX This used to fail in a nondeterministic way because of overflow # error. assert Mod(expr, 3**10) == 1966 def test_Mod_is_integer(): p = Symbol('p', integer=True) q1 = Symbol('q1', integer=True) q2 = Symbol('q2', integer=True, nonzero=True) assert Mod(x, y).is_integer is None assert Mod(p, q1).is_integer is None assert Mod(x, q2).is_integer is None assert Mod(p, q2).is_integer def test_Mod_is_nonposneg(): n = Symbol('n', integer=True) k = Symbol('k', integer=True, positive=True) assert (n%3).is_nonnegative assert Mod(n, -3).is_nonpositive assert Mod(n, k).is_nonnegative assert Mod(n, -k).is_nonpositive assert Mod(k, n).is_nonnegative is None def test_issue_6001(): A = Symbol("A", commutative=False) eq = A + A**2 # it doesn't matter whether it's True or False; they should # just all be the same assert ( eq.is_commutative == (eq + 1).is_commutative == (A + 1).is_commutative) B = Symbol("B", commutative=False) # Although commutative terms could cancel we return True # meaning "there are non-commutative symbols; aftersubstitution # that definition can change, e.g. (A*B).subs(B,A**-1) -> 1 assert (sqrt(2)*A).is_commutative is False assert (sqrt(2)*A*B).is_commutative is False def test_polar(): from sympy.functions.elementary.complexes import polar_lift p = Symbol('p', polar=True) x = Symbol('x') assert p.is_polar assert x.is_polar is None assert S.One.is_polar is None assert (p**x).is_polar is True assert (x**p).is_polar is None assert ((2*p)**x).is_polar is True assert (2*p).is_polar is True assert (-2*p).is_polar is not True assert (polar_lift(-2)*p).is_polar is True q = Symbol('q', polar=True) assert (p*q)**2 == p**2 * q**2 assert (2*q)**2 == 4 * q**2 assert ((p*q)**x).expand() == p**x * q**x def test_issue_6040(): a, b = Pow(1, 2, evaluate=False), S.One assert a != b assert b != a assert not (a == b) assert not (b == a) def test_issue_6082(): # Comparison is symmetric assert Basic.compare(Max(x, 1), Max(x, 2)) == \ - Basic.compare(Max(x, 2), Max(x, 1)) # Equal expressions compare equal assert Basic.compare(Max(x, 1), Max(x, 1)) == 0 # Basic subtypes (such as Max) compare different than standard types assert Basic.compare(Max(1, x), frozenset((1, x))) != 0 def test_issue_6077(): assert x**2.0/x == x**1.0 assert x/x**2.0 == x**-1.0 assert x*x**2.0 == x**3.0 assert x**1.5*x**2.5 == x**4.0 assert 2**(2.0*x)/2**x == 2**(1.0*x) assert 2**x/2**(2.0*x) == 2**(-1.0*x) assert 2**x*2**(2.0*x) == 2**(3.0*x) assert 2**(1.5*x)*2**(2.5*x) == 2**(4.0*x) def test_mul_flatten_oo(): p = symbols('p', positive=True) n, m = symbols('n,m', negative=True) x_im = symbols('x_im', imaginary=True) assert n*oo is -oo assert n*m*oo is oo assert p*oo is oo assert x_im*oo != I*oo # i could be +/- 3*I -> +/-oo def test_add_flatten(): # see https://github.com/sympy/sympy/issues/2633#issuecomment-29545524 a = oo + I*oo b = oo - I*oo assert a + b is nan assert a - b is nan # FIXME: This evaluates as: # >>> 1/a # 0*(oo + oo*I) # which should not simplify to 0. Should be fixed in Pow.eval #assert (1/a).simplify() == (1/b).simplify() == 0 a = Pow(2, 3, evaluate=False) assert a + a == 16 def test_issue_5160_6087_6089_6090(): # issue 6087 assert ((-2*x*y**y)**3.2).n(2) == (2**3.2*(-x*y**y)**3.2).n(2) # issue 6089 A, B, C = symbols('A,B,C', commutative=False) assert (2.*B*C)**3 == 8.0*(B*C)**3 assert (-2.*B*C)**3 == -8.0*(B*C)**3 assert (-2*B*C)**2 == 4*(B*C)**2 # issue 5160 assert sqrt(-1.0*x) == 1.0*sqrt(-x) assert sqrt(1.0*x) == 1.0*sqrt(x) # issue 6090 assert (-2*x*y*A*B)**2 == 4*x**2*y**2*(A*B)**2 def test_float_int_round(): assert int(float(sqrt(10))) == int(sqrt(10)) assert int(pi**1000) % 10 == 2 assert int(Float('1.123456789012345678901234567890e20', '')) == \ int(112345678901234567890) assert int(Float('1.123456789012345678901234567890e25', '')) == \ int(11234567890123456789012345) # decimal forces float so it's not an exact integer ending in 000000 assert int(Float('1.123456789012345678901234567890e35', '')) == \ 112345678901234567890123456789000192 assert int(Float('123456789012345678901234567890e5', '')) == \ 12345678901234567890123456789000000 assert Integer(Float('1.123456789012345678901234567890e20', '')) == \ 112345678901234567890 assert Integer(Float('1.123456789012345678901234567890e25', '')) == \ 11234567890123456789012345 # decimal forces float so it's not an exact integer ending in 000000 assert Integer(Float('1.123456789012345678901234567890e35', '')) == \ 112345678901234567890123456789000192 assert Integer(Float('123456789012345678901234567890e5', '')) == \ 12345678901234567890123456789000000 assert same_and_same_prec(Float('123000e-2',''), Float('1230.00', '')) assert same_and_same_prec(Float('123000e2',''), Float('12300000', '')) assert int(1 + Rational('.9999999999999999999999999')) == 1 assert int(pi/1e20) == 0 assert int(1 + pi/1e20) == 1 assert int(Add(1.2, -2, evaluate=False)) == int(1.2 - 2) assert int(Add(1.2, +2, evaluate=False)) == int(1.2 + 2) assert int(Add(1 + Float('.99999999999999999', ''), evaluate=False)) == 1 raises(TypeError, lambda: float(x)) raises(TypeError, lambda: float(sqrt(-1))) assert int(12345678901234567890 + cos(1)**2 + sin(1)**2) == \ 12345678901234567891 def test_issue_6611a(): assert Mul.flatten([3**Rational(1, 3), Pow(-Rational(1, 9), Rational(2, 3), evaluate=False)]) == \ ([Rational(1, 3), (-1)**Rational(2, 3)], [], None) def test_denest_add_mul(): # when working with evaluated expressions make sure they denest eq = x + 1 eq = Add(eq, 2, evaluate=False) eq = Add(eq, 2, evaluate=False) assert Add(*eq.args) == x + 5 eq = x*2 eq = Mul(eq, 2, evaluate=False) eq = Mul(eq, 2, evaluate=False) assert Mul(*eq.args) == 8*x # but don't let them denest unecessarily eq = Mul(-2, x - 2, evaluate=False) assert 2*eq == Mul(-4, x - 2, evaluate=False) assert -eq == Mul(2, x - 2, evaluate=False) def test_mul_coeff(): # It is important that all Numbers be removed from the seq; # This can be tricky when powers combine to produce those numbers p = exp(I*pi/3) assert p**2*x*p*y*p*x*p**2 == x**2*y def test_mul_zero_detection(): nz = Dummy(real=True, zero=False) r = Dummy(extended_real=True) c = Dummy(real=False, complex=True) c2 = Dummy(real=False, complex=True) i = Dummy(imaginary=True) e = nz*r*c assert e.is_imaginary is None assert e.is_extended_real is None e = nz*c assert e.is_imaginary is None assert e.is_extended_real is False e = nz*i*c assert e.is_imaginary is False assert e.is_extended_real is None # check for more than one complex; it is important to use # uniquely named Symbols to ensure that two factors appear # e.g. if the symbols have the same name they just become # a single factor, a power. e = nz*i*c*c2 assert e.is_imaginary is None assert e.is_extended_real is None # _eval_is_extended_real and _eval_is_zero both employ trapping of the # zero value so args should be tested in both directions and # TO AVOID GETTING THE CACHED RESULT, Dummy MUST BE USED # real is unknown def test(z, b, e): if z.is_zero and b.is_finite: assert e.is_extended_real and e.is_zero else: assert e.is_extended_real is None if b.is_finite: if z.is_zero: assert e.is_zero else: assert e.is_zero is None elif b.is_finite is False: if z.is_zero is None: assert e.is_zero is None else: assert e.is_zero is False for iz, ib in product(*[[True, False, None]]*2): z = Dummy('z', nonzero=iz) b = Dummy('f', finite=ib) e = Mul(z, b, evaluate=False) test(z, b, e) z = Dummy('nz', nonzero=iz) b = Dummy('f', finite=ib) e = Mul(b, z, evaluate=False) test(z, b, e) # real is True def test(z, b, e): if z.is_zero and not b.is_finite: assert e.is_extended_real is None else: assert e.is_extended_real is True for iz, ib in product(*[[True, False, None]]*2): z = Dummy('z', nonzero=iz, extended_real=True) b = Dummy('b', finite=ib, extended_real=True) e = Mul(z, b, evaluate=False) test(z, b, e) z = Dummy('z', nonzero=iz, extended_real=True) b = Dummy('b', finite=ib, extended_real=True) e = Mul(b, z, evaluate=False) test(z, b, e) def test_Mul_with_zero_infinite(): zer = Dummy(zero=True) inf = Dummy(finite=False) e = Mul(zer, inf, evaluate=False) assert e.is_extended_positive is None assert e.is_hermitian is None e = Mul(inf, zer, evaluate=False) assert e.is_extended_positive is None assert e.is_hermitian is None def test_Mul_does_not_cancel_infinities(): a, b = symbols('a b') assert ((zoo + 3*a)/(3*a + zoo)) is nan assert ((b - oo)/(b - oo)) is nan # issue 13904 expr = (1/(a+b) + 1/(a-b))/(1/(a+b) - 1/(a-b)) assert expr.subs(b, a) is nan def test_Mul_does_not_distribute_infinity(): a, b = symbols('a b') assert ((1 + I)*oo).is_Mul assert ((a + b)*(-oo)).is_Mul assert ((a + 1)*zoo).is_Mul assert ((1 + I)*oo).is_finite is False z = (1 + I)*oo assert ((1 - I)*z).expand() is oo def test_issue_8247_8354(): from sympy.functions.elementary.trigonometric import tan z = sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3)) - sqrt(10 + 6*sqrt(3)) assert z.is_positive is False # it's 0 z = S('''-2**(1/3)*(3*sqrt(93) + 29)**2 - 4*(3*sqrt(93) + 29)**(4/3) + 12*sqrt(93)*(3*sqrt(93) + 29)**(1/3) + 116*(3*sqrt(93) + 29)**(1/3) + 174*2**(1/3)*sqrt(93) + 1678*2**(1/3)''') assert z.is_positive is False # it's 0 z = 2*(-3*tan(19*pi/90) + sqrt(3))*cos(11*pi/90)*cos(19*pi/90) - \ sqrt(3)*(-3 + 4*cos(19*pi/90)**2) assert z.is_positive is not True # it's zero and it shouldn't hang z = S('''9*(3*sqrt(93) + 29)**(2/3)*((3*sqrt(93) + 29)**(1/3)*(-2**(2/3)*(3*sqrt(93) + 29)**(1/3) - 2) - 2*2**(1/3))**3 + 72*(3*sqrt(93) + 29)**(2/3)*(81*sqrt(93) + 783) + (162*sqrt(93) + 1566)*((3*sqrt(93) + 29)**(1/3)*(-2**(2/3)*(3*sqrt(93) + 29)**(1/3) - 2) - 2*2**(1/3))**2''') assert z.is_positive is False # it's 0 (and a single _mexpand isn't enough) def test_Add_is_zero(): x, y = symbols('x y', zero=True) assert (x + y).is_zero # Issue 15873 e = -2*I + (1 + I)**2 assert e.is_zero is None def test_issue_14392(): assert (sin(zoo)**2).as_real_imag() == (nan, nan) def test_divmod(): assert divmod(x, y) == (x//y, x % y) assert divmod(x, 3) == (x//3, x % 3) assert divmod(3, x) == (3//x, 3 % x) def test__neg__(): assert -(x*y) == -x*y assert -(-x*y) == x*y assert -(1.*x) == -1.*x assert -(-1.*x) == 1.*x assert -(2.*x) == -2.*x assert -(-2.*x) == 2.*x with distribute(False): eq = -(x + y) assert eq.is_Mul and eq.args == (-1, x + y) def test_issue_18507(): assert Mul(zoo, zoo, 0) is nan def test_issue_17130(): e = Add(b, -b, I, -I, evaluate=False) assert e.is_zero is None # ideally this would be True def test_issue_21034(): e = -I*log((re(asin(5)) + I*im(asin(5)))/sqrt(re(asin(5))**2 + im(asin(5))**2))/pi assert e.round(2) def test_issue_22021(): from sympy.calculus.accumulationbounds import AccumBounds # these objects are special cases in Mul from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads L = TensorIndexType("L") i = tensor_indices("i", L) A, B = tensor_heads("A B", [L]) e = A(i) + B(i) assert -e == -1*e e = zoo + x assert -e == -1*e a = AccumBounds(1, 2) e = a + x assert -e == -1*e for args in permutations((zoo, a, x)): e = Add(*args, evaluate=False) assert -e == -1*e assert 2*Add(1, x, x, evaluate=False) == 4*x + 2 def test_issue_22244(): assert -(zoo*x) == zoo*x def test_issue_22453(): from sympy.utilities.iterables import cartes e = Symbol('e', extended_positive=True) for a, b in cartes(*[[oo, -oo, 3]]*2): if a == b == 3: continue i = a + I*b assert i**(1 + e) is S.ComplexInfinity assert i**-e is S.Zero assert unchanged(Pow, i, e) assert 1/(oo + I*oo) is S.Zero r, i = [Dummy(infinite=True, extended_real=True) for _ in range(2)] assert 1/(r + I*i) is S.Zero assert 1/(3 + I*i) is S.Zero assert 1/(r + I*3) is S.Zero def test_issue_22613(): assert (0**(x - 2)).as_content_primitive() == (1, 0**(x - 2)) assert (0**(x + 2)).as_content_primitive() == (1, 0**(x + 2))
6f77047324e7df3f33630bfb9f55df0aa91680a001dd2f966c0821302ec3e050
"""Implementation of :class:`AlgebraicField` class. """ from sympy.core.add import Add from sympy.core.mul import Mul from sympy.core.singleton import S from sympy.polys.domains.characteristiczero import CharacteristicZero from sympy.polys.domains.field import Field from sympy.polys.domains.simpledomain import SimpleDomain from sympy.polys.polyclasses import ANP from sympy.polys.polyerrors import CoercionFailed, DomainError, NotAlgebraic, IsomorphismFailed from sympy.utilities import public @public class AlgebraicField(Field, CharacteristicZero, SimpleDomain): r"""Algebraic number field :ref:`QQ(a)` A :ref:`QQ(a)` domain represents an `algebraic number field`_ `\mathbb{Q}(a)` as a :py:class:`~.Domain` in the domain system (see :ref:`polys-domainsintro`). A :py:class:`~.Poly` created from an expression involving `algebraic numbers`_ will treat the algebraic numbers as generators if the generators argument is not specified. >>> from sympy import Poly, Symbol, sqrt >>> x = Symbol('x') >>> Poly(x**2 + sqrt(2)) Poly(x**2 + (sqrt(2)), x, sqrt(2), domain='ZZ') That is a multivariate polynomial with ``sqrt(2)`` treated as one of the generators (variables). If the generators are explicitly specified then ``sqrt(2)`` will be considered to be a coefficient but by default the :ref:`EX` domain is used. To make a :py:class:`~.Poly` with a :ref:`QQ(a)` domain the argument ``extension=True`` can be given. >>> Poly(x**2 + sqrt(2), x) Poly(x**2 + sqrt(2), x, domain='EX') >>> Poly(x**2 + sqrt(2), x, extension=True) Poly(x**2 + sqrt(2), x, domain='QQ<sqrt(2)>') A generator of the algebraic field extension can also be specified explicitly which is particularly useful if the coefficients are all rational but an extension field is needed (e.g. to factor the polynomial). >>> Poly(x**2 + 1) Poly(x**2 + 1, x, domain='ZZ') >>> Poly(x**2 + 1, extension=sqrt(2)) Poly(x**2 + 1, x, domain='QQ<sqrt(2)>') It is possible to factorise a polynomial over a :ref:`QQ(a)` domain using the ``extension`` argument to :py:func:`~.factor` or by specifying the domain explicitly. >>> from sympy import factor, QQ >>> factor(x**2 - 2) x**2 - 2 >>> factor(x**2 - 2, extension=sqrt(2)) (x - sqrt(2))*(x + sqrt(2)) >>> factor(x**2 - 2, domain='QQ<sqrt(2)>') (x - sqrt(2))*(x + sqrt(2)) >>> factor(x**2 - 2, domain=QQ.algebraic_field(sqrt(2))) (x - sqrt(2))*(x + sqrt(2)) The ``extension=True`` argument can be used but will only create an extension that contains the coefficients which is usually not enough to factorise the polynomial. >>> p = x**3 + sqrt(2)*x**2 - 2*x - 2*sqrt(2) >>> factor(p) # treats sqrt(2) as a symbol (x + sqrt(2))*(x**2 - 2) >>> factor(p, extension=True) (x - sqrt(2))*(x + sqrt(2))**2 >>> factor(x**2 - 2, extension=True) # all rational coefficients x**2 - 2 It is also possible to use :ref:`QQ(a)` with the :py:func:`~.cancel` and :py:func:`~.gcd` functions. >>> from sympy import cancel, gcd >>> cancel((x**2 - 2)/(x - sqrt(2))) (x**2 - 2)/(x - sqrt(2)) >>> cancel((x**2 - 2)/(x - sqrt(2)), extension=sqrt(2)) x + sqrt(2) >>> gcd(x**2 - 2, x - sqrt(2)) 1 >>> gcd(x**2 - 2, x - sqrt(2), extension=sqrt(2)) x - sqrt(2) When using the domain directly :ref:`QQ(a)` can be used as a constructor to create instances which then support the operations ``+,-,*,**,/``. The :py:meth:`~.Domain.algebraic_field` method is used to construct a particular :ref:`QQ(a)` domain. The :py:meth:`~.Domain.from_sympy` method can be used to create domain elements from normal SymPy expressions. >>> K = QQ.algebraic_field(sqrt(2)) >>> K QQ<sqrt(2)> >>> xk = K.from_sympy(3 + 4*sqrt(2)) >>> xk # doctest: +SKIP ANP([4, 3], [1, 0, -2], QQ) Elements of :ref:`QQ(a)` are instances of :py:class:`~.ANP` which have limited printing support. The raw display shows the internal representation of the element as the list ``[4, 3]`` representing the coefficients of ``1`` and ``sqrt(2)`` for this element in the form ``a * sqrt(2) + b * 1`` where ``a`` and ``b`` are elements of :ref:`QQ`. The minimal polynomial for the generator ``(x**2 - 2)`` is also shown in the :ref:`dup-representation` as the list ``[1, 0, -2]``. We can use :py:meth:`~.Domain.to_sympy` to get a better printed form for the elements and to see the results of operations. >>> xk = K.from_sympy(3 + 4*sqrt(2)) >>> yk = K.from_sympy(2 + 3*sqrt(2)) >>> xk * yk # doctest: +SKIP ANP([17, 30], [1, 0, -2], QQ) >>> K.to_sympy(xk * yk) 17*sqrt(2) + 30 >>> K.to_sympy(xk + yk) 5 + 7*sqrt(2) >>> K.to_sympy(xk ** 2) 24*sqrt(2) + 41 >>> K.to_sympy(xk / yk) sqrt(2)/14 + 9/7 Any expression representing an algebraic number can be used to generate a :ref:`QQ(a)` domain provided its `minimal polynomial`_ can be computed. The function :py:func:`~.minpoly` function is used for this. >>> from sympy import exp, I, pi, minpoly >>> g = exp(2*I*pi/3) >>> g exp(2*I*pi/3) >>> g.is_algebraic True >>> minpoly(g, x) x**2 + x + 1 >>> factor(x**3 - 1, extension=g) (x - 1)*(x - exp(2*I*pi/3))*(x + 1 + exp(2*I*pi/3)) It is also possible to make an algebraic field from multiple extension elements. >>> K = QQ.algebraic_field(sqrt(2), sqrt(3)) >>> K QQ<sqrt(2) + sqrt(3)> >>> p = x**4 - 5*x**2 + 6 >>> factor(p) (x**2 - 3)*(x**2 - 2) >>> factor(p, domain=K) (x - sqrt(2))*(x + sqrt(2))*(x - sqrt(3))*(x + sqrt(3)) >>> factor(p, extension=[sqrt(2), sqrt(3)]) (x - sqrt(2))*(x + sqrt(2))*(x - sqrt(3))*(x + sqrt(3)) Multiple extension elements are always combined together to make a single `primitive element`_. In the case of ``[sqrt(2), sqrt(3)]`` the primitive element chosen is ``sqrt(2) + sqrt(3)`` which is why the domain displays as ``QQ<sqrt(2) + sqrt(3)>``. The minimal polynomial for the primitive element is computed using the :py:func:`~.primitive_element` function. >>> from sympy import primitive_element >>> primitive_element([sqrt(2), sqrt(3)], x) (x**4 - 10*x**2 + 1, [1, 1]) >>> minpoly(sqrt(2) + sqrt(3), x) x**4 - 10*x**2 + 1 The extension elements that generate the domain can be accessed from the domain using the :py:attr:`~.ext` and :py:attr:`~.orig_ext` attributes as instances of :py:class:`~.AlgebraicNumber`. The minimal polynomial for the primitive element as a :py:class:`~.DMP` instance is available as :py:attr:`~.mod`. >>> K = QQ.algebraic_field(sqrt(2), sqrt(3)) >>> K QQ<sqrt(2) + sqrt(3)> >>> K.ext sqrt(2) + sqrt(3) >>> K.orig_ext (sqrt(2), sqrt(3)) >>> K.mod DMP([1, 0, -10, 0, 1], QQ, None) The `discriminant`_ of the field can be obtained from the :py:meth:`~.discriminant` method, and an `integral basis`_ from the :py:meth:`~.integral_basis` method. The latter returns a list of :py:class:`~.ANP` instances by default, but can be made to return instances of :py:class:`~.Expr` or :py:class:`~.AlgebraicNumber` by passing a ``fmt`` argument. The maximal order, or ring of integers, of the field can also be obtained from the :py:meth:`~.maximal_order` method, as a :py:class:`~sympy.polys.numberfields.modules.Submodule`. >>> zeta5 = exp(2*I*pi/5) >>> K = QQ.algebraic_field(zeta5) >>> K QQ<exp(2*I*pi/5)> >>> K.discriminant() 125 >>> K = QQ.algebraic_field(sqrt(5)) >>> K QQ<sqrt(5)> >>> K.integral_basis(fmt='sympy') [1, 1/2 + sqrt(5)/2] >>> K.maximal_order() Submodule[[2, 0], [1, 1]]/2 The factorization of a rational prime into prime ideals of the field is computed by the :py:meth:`~.primes_above` method, which returns a list of :py:class:`~sympy.polys.numberfields.primes.PrimeIdeal` instances. >>> zeta7 = exp(2*I*pi/7) >>> K = QQ.algebraic_field(zeta7) >>> K QQ<exp(2*I*pi/7)> >>> K.primes_above(11) [[ (11, _x**3 + 5*_x**2 + 4*_x - 1) e=1, f=3 ], [ (11, _x**3 - 4*_x**2 - 5*_x - 1) e=1, f=3 ]] Notes ===== It is not currently possible to generate an algebraic extension over any domain other than :ref:`QQ`. Ideally it would be possible to generate extensions like ``QQ(x)(sqrt(x**2 - 2))``. This is equivalent to the quotient ring ``QQ(x)[y]/(y**2 - x**2 + 2)`` and there are two implementations of this kind of quotient ring/extension in the :py:class:`~.QuotientRing` and :py:class:`~.MonogenicFiniteExtension` classes. Each of those implementations needs some work to make them fully usable though. .. _algebraic number field: https://en.wikipedia.org/wiki/Algebraic_number_field .. _algebraic numbers: https://en.wikipedia.org/wiki/Algebraic_number .. _discriminant: https://en.wikipedia.org/wiki/Discriminant_of_an_algebraic_number_field .. _integral basis: https://en.wikipedia.org/wiki/Algebraic_number_field#Integral_basis .. _minimal polynomial: https://en.wikipedia.org/wiki/Minimal_polynomial_(field_theory) .. _primitive element: https://en.wikipedia.org/wiki/Primitive_element_theorem """ dtype = ANP is_AlgebraicField = is_Algebraic = True is_Numerical = True has_assoc_Ring = False has_assoc_Field = True def __init__(self, dom, *ext): if not dom.is_QQ: raise DomainError("ground domain must be a rational field") from sympy.polys.numberfields import to_number_field if len(ext) == 1 and isinstance(ext[0], tuple): orig_ext = ext[0][1:] else: orig_ext = ext self.orig_ext = orig_ext """ Original elements given to generate the extension. >>> from sympy import QQ, sqrt >>> K = QQ.algebraic_field(sqrt(2), sqrt(3)) >>> K.orig_ext (sqrt(2), sqrt(3)) """ self.ext = to_number_field(ext) """ Primitive element used for the extension. >>> from sympy import QQ, sqrt >>> K = QQ.algebraic_field(sqrt(2), sqrt(3)) >>> K.ext sqrt(2) + sqrt(3) """ self.mod = self.ext.minpoly.rep """ Minimal polynomial for the primitive element of the extension. >>> from sympy import QQ, sqrt >>> K = QQ.algebraic_field(sqrt(2)) >>> K.mod DMP([1, 0, -2], QQ, None) """ self.domain = self.dom = dom self.ngens = 1 self.symbols = self.gens = (self.ext,) self.unit = self([dom(1), dom(0)]) self.zero = self.dtype.zero(self.mod.rep, dom) self.one = self.dtype.one(self.mod.rep, dom) self._maximal_order = None self._discriminant = None self._nilradicals_mod_p = {} def new(self, element): return self.dtype(element, self.mod.rep, self.dom) def __str__(self): return str(self.dom) + '<' + str(self.ext) + '>' def __hash__(self): return hash((self.__class__.__name__, self.dtype, self.dom, self.ext)) def __eq__(self, other): """Returns ``True`` if two domains are equivalent. """ return isinstance(other, AlgebraicField) and \ self.dtype == other.dtype and self.ext == other.ext def algebraic_field(self, *extension): r"""Returns an algebraic field, i.e. `\mathbb{Q}(\alpha, \ldots)`. """ return AlgebraicField(self.dom, *((self.ext,) + extension)) def to_alg_num(self, a): """Convert ``a`` of ``dtype`` to an :py:class:`~.AlgebraicNumber`. """ theta = self.ext # `self.ext.root` may be an `AlgebraicNumber`, in which case we should # use it instead of `self.ext`, in case it has an `alias`. if hasattr(theta.root, "field_element"): theta = theta.root return theta.field_element(a) def to_sympy(self, a): """Convert ``a`` of ``dtype`` to a SymPy object. """ # Precompute a converter to be reused: if not hasattr(self, '_converter'): self._converter = _make_converter(self) return self._converter(a) def from_sympy(self, a): """Convert SymPy's expression to ``dtype``. """ try: return self([self.dom.from_sympy(a)]) except CoercionFailed: pass from sympy.polys.numberfields import to_number_field try: return self(to_number_field(a, self.ext).native_coeffs()) except (NotAlgebraic, IsomorphismFailed): raise CoercionFailed( "%s is not a valid algebraic number in %s" % (a, self)) def from_ZZ(K1, a, K0): """Convert a Python ``int`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_ZZ_python(K1, a, K0): """Convert a Python ``int`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_QQ(K1, a, K0): """Convert a Python ``Fraction`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_QQ_python(K1, a, K0): """Convert a Python ``Fraction`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_ZZ_gmpy(K1, a, K0): """Convert a GMPY ``mpz`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_QQ_gmpy(K1, a, K0): """Convert a GMPY ``mpq`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_RealField(K1, a, K0): """Convert a mpmath ``mpf`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def get_ring(self): """Returns a ring associated with ``self``. """ raise DomainError('there is no ring associated with %s' % self) def is_positive(self, a): """Returns True if ``a`` is positive. """ return self.dom.is_positive(a.LC()) def is_negative(self, a): """Returns True if ``a`` is negative. """ return self.dom.is_negative(a.LC()) def is_nonpositive(self, a): """Returns True if ``a`` is non-positive. """ return self.dom.is_nonpositive(a.LC()) def is_nonnegative(self, a): """Returns True if ``a`` is non-negative. """ return self.dom.is_nonnegative(a.LC()) def numer(self, a): """Returns numerator of ``a``. """ return a def denom(self, a): """Returns denominator of ``a``. """ return self.one def from_AlgebraicField(K1, a, K0): """Convert AlgebraicField element 'a' to another AlgebraicField """ return K1.from_sympy(K0.to_sympy(a)) def from_GaussianIntegerRing(K1, a, K0): """Convert a GaussianInteger element 'a' to ``dtype``. """ return K1.from_sympy(K0.to_sympy(a)) def from_GaussianRationalField(K1, a, K0): """Convert a GaussianRational element 'a' to ``dtype``. """ return K1.from_sympy(K0.to_sympy(a)) def _do_round_two(self): from sympy.polys.numberfields.basis import round_two ZK, dK = round_two(self.ext.minpoly, radicals=self._nilradicals_mod_p) self._maximal_order = ZK self._discriminant = dK def maximal_order(self): """ Compute the maximal order, or ring of integers, of the field. Returns ======= :py:class:`~sympy.polys.numberfields.modules.Submodule`. See Also ======== integral_basis() """ if self._maximal_order is None: self._do_round_two() return self._maximal_order def integral_basis(self, fmt=None): r""" Get an integral basis for the field. Parameters ========== fmt : str, None, optional (default=None) If ``None``, return a list of :py:class:`~.ANP` instances. If ``"sympy"``, convert each element of the list to an :py:class:`~.Expr`, using ``self.to_sympy()``. If ``"alg"``, convert each element of the list to an :py:class:`~.AlgebraicNumber`, using ``self.to_alg_num()``. Examples ======== >>> from sympy import QQ, AlgebraicNumber, sqrt >>> alpha = AlgebraicNumber(sqrt(5), alias='alpha') >>> k = QQ.algebraic_field(alpha) >>> B0 = k.integral_basis() >>> B1 = k.integral_basis(fmt='sympy') >>> B2 = k.integral_basis(fmt='alg') >>> print(B0[1]) # doctest: +SKIP ANP([mpq(1,2), mpq(1,2)], [mpq(1,1), mpq(0,1), mpq(-5,1)], QQ) >>> print(B1[1]) 1/2 + alpha/2 >>> print(B2[1]) alpha/2 + 1/2 In the last two cases we get legible expressions, which print somewhat differently because of the different types involved: >>> print(type(B1[1])) <class 'sympy.core.add.Add'> >>> print(type(B2[1])) <class 'sympy.core.numbers.AlgebraicNumber'> See Also ======== to_sympy() to_alg_num() maximal_order() """ ZK = self.maximal_order() M = ZK.QQ_matrix n = M.shape[1] B = [self.new(list(reversed(M[:, j].flat()))) for j in range(n)] if fmt == 'sympy': return [self.to_sympy(b) for b in B] elif fmt == 'alg': return [self.to_alg_num(b) for b in B] return B def discriminant(self): """Get the discriminant of the field.""" if self._discriminant is None: self._do_round_two() return self._discriminant def primes_above(self, p): """Compute the prime ideals lying above a given rational prime *p*.""" from sympy.polys.numberfields.primes import prime_decomp ZK = self.maximal_order() dK = self.discriminant() rad = self._nilradicals_mod_p.get(p) return prime_decomp(p, ZK=ZK, dK=dK, radical=rad) def _make_converter(K): """Construct the converter to convert back to Expr""" # Precompute the effect of converting to SymPy and expanding expressions # like (sqrt(2) + sqrt(3))**2. Asking Expr to do the expansion on every # conversion from K to Expr is slow. Here we compute the expansions for # each power of the generator and collect together the resulting algebraic # terms and the rational coefficients into a matrix. gen = K.ext.as_expr() todom = K.dom.from_sympy # We'll let Expr compute the expansions. We won't make any presumptions # about what this results in except that it is QQ-linear in some terms # that we will call algebraics. The final result will be expressed in # terms of those. powers = [S.One, gen] for n in range(2, K.mod.degree()): powers.append((gen * powers[-1]).expand()) # Collect the rational coefficients and algebraic Expr that can # map the ANP coefficients into an expanded SymPy expression terms = [dict(t.as_coeff_Mul()[::-1] for t in Add.make_args(p)) for p in powers] algebraics = set().union(*terms) matrix = [[todom(t.get(a, S.Zero)) for t in terms] for a in algebraics] # Create a function to do the conversion efficiently: def converter(a): """Convert a to Expr using converter""" ai = a.rep[::-1] tosympy = K.dom.to_sympy coeffs_dom = [sum(mij*aj for mij, aj in zip(mi, ai)) for mi in matrix] coeffs_sympy = [tosympy(c) for c in coeffs_dom] res = Add(*(Mul(c, a) for c, a in zip(coeffs_sympy, algebraics))) return res return converter
fa77f3b1f55214b9973b06888dc395d4c2c4b1178883824f5558c92ab32a6932
"""Test sparse polynomials. """ from functools import reduce from operator import add, mul from sympy.polys.rings import ring, xring, sring, PolyRing, PolyElement from sympy.polys.fields import field, FracField from sympy.polys.domains import ZZ, QQ, RR, FF, EX from sympy.polys.orderings import lex, grlex from sympy.polys.polyerrors import GeneratorsError, \ ExactQuotientFailed, MultivariatePolynomialError, CoercionFailed from sympy.testing.pytest import raises from sympy.core import Symbol, symbols from sympy.core.numbers import (oo, pi) from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt def test_PolyRing___init__(): x, y, z, t = map(Symbol, "xyzt") assert len(PolyRing("x,y,z", ZZ, lex).gens) == 3 assert len(PolyRing(x, ZZ, lex).gens) == 1 assert len(PolyRing(("x", "y", "z"), ZZ, lex).gens) == 3 assert len(PolyRing((x, y, z), ZZ, lex).gens) == 3 assert len(PolyRing("", ZZ, lex).gens) == 0 assert len(PolyRing([], ZZ, lex).gens) == 0 raises(GeneratorsError, lambda: PolyRing(0, ZZ, lex)) assert PolyRing("x", ZZ[t], lex).domain == ZZ[t] assert PolyRing("x", 'ZZ[t]', lex).domain == ZZ[t] assert PolyRing("x", PolyRing("t", ZZ, lex), lex).domain == ZZ[t] raises(GeneratorsError, lambda: PolyRing("x", PolyRing("x", ZZ, lex), lex)) _lex = Symbol("lex") assert PolyRing("x", ZZ, lex).order == lex assert PolyRing("x", ZZ, _lex).order == lex assert PolyRing("x", ZZ, 'lex').order == lex R1 = PolyRing("x,y", ZZ, lex) R2 = PolyRing("x,y", ZZ, lex) R3 = PolyRing("x,y,z", ZZ, lex) assert R1.x == R1.gens[0] assert R1.y == R1.gens[1] assert R1.x == R2.x assert R1.y == R2.y assert R1.x != R3.x assert R1.y != R3.y def test_PolyRing___hash__(): R, x, y, z = ring("x,y,z", QQ) assert hash(R) def test_PolyRing___eq__(): assert ring("x,y,z", QQ)[0] == ring("x,y,z", QQ)[0] assert ring("x,y,z", QQ)[0] is ring("x,y,z", QQ)[0] assert ring("x,y,z", QQ)[0] != ring("x,y,z", ZZ)[0] assert ring("x,y,z", QQ)[0] is not ring("x,y,z", ZZ)[0] assert ring("x,y,z", ZZ)[0] != ring("x,y,z", QQ)[0] assert ring("x,y,z", ZZ)[0] is not ring("x,y,z", QQ)[0] assert ring("x,y,z", QQ)[0] != ring("x,y", QQ)[0] assert ring("x,y,z", QQ)[0] is not ring("x,y", QQ)[0] assert ring("x,y", QQ)[0] != ring("x,y,z", QQ)[0] assert ring("x,y", QQ)[0] is not ring("x,y,z", QQ)[0] def test_PolyRing_ring_new(): R, x, y, z = ring("x,y,z", QQ) assert R.ring_new(7) == R(7) assert R.ring_new(7*x*y*z) == 7*x*y*z f = x**2 + 2*x*y + 3*x + 4*z**2 + 5*z + 6 assert R.ring_new([[[1]], [[2], [3]], [[4, 5, 6]]]) == f assert R.ring_new({(2, 0, 0): 1, (1, 1, 0): 2, (1, 0, 0): 3, (0, 0, 2): 4, (0, 0, 1): 5, (0, 0, 0): 6}) == f assert R.ring_new([((2, 0, 0), 1), ((1, 1, 0), 2), ((1, 0, 0), 3), ((0, 0, 2), 4), ((0, 0, 1), 5), ((0, 0, 0), 6)]) == f R, = ring("", QQ) assert R.ring_new([((), 7)]) == R(7) def test_PolyRing_drop(): R, x,y,z = ring("x,y,z", ZZ) assert R.drop(x) == PolyRing("y,z", ZZ, lex) assert R.drop(y) == PolyRing("x,z", ZZ, lex) assert R.drop(z) == PolyRing("x,y", ZZ, lex) assert R.drop(0) == PolyRing("y,z", ZZ, lex) assert R.drop(0).drop(0) == PolyRing("z", ZZ, lex) assert R.drop(0).drop(0).drop(0) == ZZ assert R.drop(1) == PolyRing("x,z", ZZ, lex) assert R.drop(2) == PolyRing("x,y", ZZ, lex) assert R.drop(2).drop(1) == PolyRing("x", ZZ, lex) assert R.drop(2).drop(1).drop(0) == ZZ raises(ValueError, lambda: R.drop(3)) raises(ValueError, lambda: R.drop(x).drop(y)) def test_PolyRing___getitem__(): R, x,y,z = ring("x,y,z", ZZ) assert R[0:] == PolyRing("x,y,z", ZZ, lex) assert R[1:] == PolyRing("y,z", ZZ, lex) assert R[2:] == PolyRing("z", ZZ, lex) assert R[3:] == ZZ def test_PolyRing_is_(): R = PolyRing("x", QQ, lex) assert R.is_univariate is True assert R.is_multivariate is False R = PolyRing("x,y,z", QQ, lex) assert R.is_univariate is False assert R.is_multivariate is True R = PolyRing("", QQ, lex) assert R.is_univariate is False assert R.is_multivariate is False def test_PolyRing_add(): R, x = ring("x", ZZ) F = [ x**2 + 2*i + 3 for i in range(4) ] assert R.add(F) == reduce(add, F) == 4*x**2 + 24 R, = ring("", ZZ) assert R.add([2, 5, 7]) == 14 def test_PolyRing_mul(): R, x = ring("x", ZZ) F = [ x**2 + 2*i + 3 for i in range(4) ] assert R.mul(F) == reduce(mul, F) == x**8 + 24*x**6 + 206*x**4 + 744*x**2 + 945 R, = ring("", ZZ) assert R.mul([2, 3, 5]) == 30 def test_sring(): x, y, z, t = symbols("x,y,z,t") R = PolyRing("x,y,z", ZZ, lex) assert sring(x + 2*y + 3*z) == (R, R.x + 2*R.y + 3*R.z) R = PolyRing("x,y,z", QQ, lex) assert sring(x + 2*y + z/3) == (R, R.x + 2*R.y + R.z/3) assert sring([x, 2*y, z/3]) == (R, [R.x, 2*R.y, R.z/3]) Rt = PolyRing("t", ZZ, lex) R = PolyRing("x,y,z", Rt, lex) assert sring(x + 2*t*y + 3*t**2*z, x, y, z) == (R, R.x + 2*Rt.t*R.y + 3*Rt.t**2*R.z) Rt = PolyRing("t", QQ, lex) R = PolyRing("x,y,z", Rt, lex) assert sring(x + t*y/2 + t**2*z/3, x, y, z) == (R, R.x + Rt.t*R.y/2 + Rt.t**2*R.z/3) Rt = FracField("t", ZZ, lex) R = PolyRing("x,y,z", Rt, lex) assert sring(x + 2*y/t + t**2*z/3, x, y, z) == (R, R.x + 2*R.y/Rt.t + Rt.t**2*R.z/3) r = sqrt(2) - sqrt(3) R, a = sring(r, extension=True) assert R.domain == QQ.algebraic_field(sqrt(2) + sqrt(3)) assert R.gens == () assert a == R.domain.from_sympy(r) def test_PolyElement___hash__(): R, x, y, z = ring("x,y,z", QQ) assert hash(x*y*z) def test_PolyElement___eq__(): R, x, y = ring("x,y", ZZ, lex) assert ((x*y + 5*x*y) == 6) == False assert ((x*y + 5*x*y) == 6*x*y) == True assert (6 == (x*y + 5*x*y)) == False assert (6*x*y == (x*y + 5*x*y)) == True assert ((x*y - x*y) == 0) == True assert (0 == (x*y - x*y)) == True assert ((x*y - x*y) == 1) == False assert (1 == (x*y - x*y)) == False assert ((x*y - x*y) == 1) == False assert (1 == (x*y - x*y)) == False assert ((x*y + 5*x*y) != 6) == True assert ((x*y + 5*x*y) != 6*x*y) == False assert (6 != (x*y + 5*x*y)) == True assert (6*x*y != (x*y + 5*x*y)) == False assert ((x*y - x*y) != 0) == False assert (0 != (x*y - x*y)) == False assert ((x*y - x*y) != 1) == True assert (1 != (x*y - x*y)) == True assert R.one == QQ(1, 1) == R.one assert R.one == 1 == R.one Rt, t = ring("t", ZZ) R, x, y = ring("x,y", Rt) assert (t**3*x/x == t**3) == True assert (t**3*x/x == t**4) == False def test_PolyElement__lt_le_gt_ge__(): R, x, y = ring("x,y", ZZ) assert R(1) < x < x**2 < x**3 assert R(1) <= x <= x**2 <= x**3 assert x**3 > x**2 > x > R(1) assert x**3 >= x**2 >= x >= R(1) def test_PolyElement_copy(): R, x, y, z = ring("x,y,z", ZZ) f = x*y + 3*z g = f.copy() assert f == g g[(1, 1, 1)] = 7 assert f != g def test_PolyElement_as_expr(): R, x, y, z = ring("x,y,z", ZZ) f = 3*x**2*y - x*y*z + 7*z**3 + 1 X, Y, Z = R.symbols g = 3*X**2*Y - X*Y*Z + 7*Z**3 + 1 assert f != g assert f.as_expr() == g X, Y, Z = symbols("x,y,z") g = 3*X**2*Y - X*Y*Z + 7*Z**3 + 1 assert f != g assert f.as_expr(X, Y, Z) == g raises(ValueError, lambda: f.as_expr(X)) R, = ring("", ZZ) assert R(3).as_expr() == 3 def test_PolyElement_from_expr(): x, y, z = symbols("x,y,z") R, X, Y, Z = ring((x, y, z), ZZ) f = R.from_expr(1) assert f == 1 and isinstance(f, R.dtype) f = R.from_expr(x) assert f == X and isinstance(f, R.dtype) f = R.from_expr(x*y*z) assert f == X*Y*Z and isinstance(f, R.dtype) f = R.from_expr(x*y*z + x*y + x) assert f == X*Y*Z + X*Y + X and isinstance(f, R.dtype) f = R.from_expr(x**3*y*z + x**2*y**7 + 1) assert f == X**3*Y*Z + X**2*Y**7 + 1 and isinstance(f, R.dtype) r, F = sring([exp(2)]) f = r.from_expr(exp(2)) assert f == F[0] and isinstance(f, r.dtype) raises(ValueError, lambda: R.from_expr(1/x)) raises(ValueError, lambda: R.from_expr(2**x)) raises(ValueError, lambda: R.from_expr(7*x + sqrt(2))) R, = ring("", ZZ) f = R.from_expr(1) assert f == 1 and isinstance(f, R.dtype) def test_PolyElement_degree(): R, x,y,z = ring("x,y,z", ZZ) assert R(0).degree() is -oo assert R(1).degree() == 0 assert (x + 1).degree() == 1 assert (2*y**3 + z).degree() == 0 assert (x*y**3 + z).degree() == 1 assert (x**5*y**3 + z).degree() == 5 assert R(0).degree(x) is -oo assert R(1).degree(x) == 0 assert (x + 1).degree(x) == 1 assert (2*y**3 + z).degree(x) == 0 assert (x*y**3 + z).degree(x) == 1 assert (7*x**5*y**3 + z).degree(x) == 5 assert R(0).degree(y) is -oo assert R(1).degree(y) == 0 assert (x + 1).degree(y) == 0 assert (2*y**3 + z).degree(y) == 3 assert (x*y**3 + z).degree(y) == 3 assert (7*x**5*y**3 + z).degree(y) == 3 assert R(0).degree(z) is -oo assert R(1).degree(z) == 0 assert (x + 1).degree(z) == 0 assert (2*y**3 + z).degree(z) == 1 assert (x*y**3 + z).degree(z) == 1 assert (7*x**5*y**3 + z).degree(z) == 1 R, = ring("", ZZ) assert R(0).degree() is -oo assert R(1).degree() == 0 def test_PolyElement_tail_degree(): R, x,y,z = ring("x,y,z", ZZ) assert R(0).tail_degree() is -oo assert R(1).tail_degree() == 0 assert (x + 1).tail_degree() == 0 assert (2*y**3 + x**3*z).tail_degree() == 0 assert (x*y**3 + x**3*z).tail_degree() == 1 assert (x**5*y**3 + x**3*z).tail_degree() == 3 assert R(0).tail_degree(x) is -oo assert R(1).tail_degree(x) == 0 assert (x + 1).tail_degree(x) == 0 assert (2*y**3 + x**3*z).tail_degree(x) == 0 assert (x*y**3 + x**3*z).tail_degree(x) == 1 assert (7*x**5*y**3 + x**3*z).tail_degree(x) == 3 assert R(0).tail_degree(y) is -oo assert R(1).tail_degree(y) == 0 assert (x + 1).tail_degree(y) == 0 assert (2*y**3 + x**3*z).tail_degree(y) == 0 assert (x*y**3 + x**3*z).tail_degree(y) == 0 assert (7*x**5*y**3 + x**3*z).tail_degree(y) == 0 assert R(0).tail_degree(z) is -oo assert R(1).tail_degree(z) == 0 assert (x + 1).tail_degree(z) == 0 assert (2*y**3 + x**3*z).tail_degree(z) == 0 assert (x*y**3 + x**3*z).tail_degree(z) == 0 assert (7*x**5*y**3 + x**3*z).tail_degree(z) == 0 R, = ring("", ZZ) assert R(0).tail_degree() is -oo assert R(1).tail_degree() == 0 def test_PolyElement_degrees(): R, x,y,z = ring("x,y,z", ZZ) assert R(0).degrees() == (-oo, -oo, -oo) assert R(1).degrees() == (0, 0, 0) assert (x**2*y + x**3*z**2).degrees() == (3, 1, 2) def test_PolyElement_tail_degrees(): R, x,y,z = ring("x,y,z", ZZ) assert R(0).tail_degrees() == (-oo, -oo, -oo) assert R(1).tail_degrees() == (0, 0, 0) assert (x**2*y + x**3*z**2).tail_degrees() == (2, 0, 0) def test_PolyElement_coeff(): R, x, y, z = ring("x,y,z", ZZ, lex) f = 3*x**2*y - x*y*z + 7*z**3 + 23 assert f.coeff(1) == 23 raises(ValueError, lambda: f.coeff(3)) assert f.coeff(x) == 0 assert f.coeff(y) == 0 assert f.coeff(z) == 0 assert f.coeff(x**2*y) == 3 assert f.coeff(x*y*z) == -1 assert f.coeff(z**3) == 7 raises(ValueError, lambda: f.coeff(3*x**2*y)) raises(ValueError, lambda: f.coeff(-x*y*z)) raises(ValueError, lambda: f.coeff(7*z**3)) R, = ring("", ZZ) assert R(3).coeff(1) == 3 def test_PolyElement_LC(): R, x, y = ring("x,y", QQ, lex) assert R(0).LC == QQ(0) assert (QQ(1,2)*x).LC == QQ(1, 2) assert (QQ(1,4)*x*y + QQ(1,2)*x).LC == QQ(1, 4) def test_PolyElement_LM(): R, x, y = ring("x,y", QQ, lex) assert R(0).LM == (0, 0) assert (QQ(1,2)*x).LM == (1, 0) assert (QQ(1,4)*x*y + QQ(1,2)*x).LM == (1, 1) def test_PolyElement_LT(): R, x, y = ring("x,y", QQ, lex) assert R(0).LT == ((0, 0), QQ(0)) assert (QQ(1,2)*x).LT == ((1, 0), QQ(1, 2)) assert (QQ(1,4)*x*y + QQ(1,2)*x).LT == ((1, 1), QQ(1, 4)) R, = ring("", ZZ) assert R(0).LT == ((), 0) assert R(1).LT == ((), 1) def test_PolyElement_leading_monom(): R, x, y = ring("x,y", QQ, lex) assert R(0).leading_monom() == 0 assert (QQ(1,2)*x).leading_monom() == x assert (QQ(1,4)*x*y + QQ(1,2)*x).leading_monom() == x*y def test_PolyElement_leading_term(): R, x, y = ring("x,y", QQ, lex) assert R(0).leading_term() == 0 assert (QQ(1,2)*x).leading_term() == QQ(1,2)*x assert (QQ(1,4)*x*y + QQ(1,2)*x).leading_term() == QQ(1,4)*x*y def test_PolyElement_terms(): R, x,y,z = ring("x,y,z", QQ) terms = (x**2/3 + y**3/4 + z**4/5).terms() assert terms == [((2,0,0), QQ(1,3)), ((0,3,0), QQ(1,4)), ((0,0,4), QQ(1,5))] R, x,y = ring("x,y", ZZ, lex) f = x*y**7 + 2*x**2*y**3 assert f.terms() == f.terms(lex) == f.terms('lex') == [((2, 3), 2), ((1, 7), 1)] assert f.terms(grlex) == f.terms('grlex') == [((1, 7), 1), ((2, 3), 2)] R, x,y = ring("x,y", ZZ, grlex) f = x*y**7 + 2*x**2*y**3 assert f.terms() == f.terms(grlex) == f.terms('grlex') == [((1, 7), 1), ((2, 3), 2)] assert f.terms(lex) == f.terms('lex') == [((2, 3), 2), ((1, 7), 1)] R, = ring("", ZZ) assert R(3).terms() == [((), 3)] def test_PolyElement_monoms(): R, x,y,z = ring("x,y,z", QQ) monoms = (x**2/3 + y**3/4 + z**4/5).monoms() assert monoms == [(2,0,0), (0,3,0), (0,0,4)] R, x,y = ring("x,y", ZZ, lex) f = x*y**7 + 2*x**2*y**3 assert f.monoms() == f.monoms(lex) == f.monoms('lex') == [(2, 3), (1, 7)] assert f.monoms(grlex) == f.monoms('grlex') == [(1, 7), (2, 3)] R, x,y = ring("x,y", ZZ, grlex) f = x*y**7 + 2*x**2*y**3 assert f.monoms() == f.monoms(grlex) == f.monoms('grlex') == [(1, 7), (2, 3)] assert f.monoms(lex) == f.monoms('lex') == [(2, 3), (1, 7)] def test_PolyElement_coeffs(): R, x,y,z = ring("x,y,z", QQ) coeffs = (x**2/3 + y**3/4 + z**4/5).coeffs() assert coeffs == [QQ(1,3), QQ(1,4), QQ(1,5)] R, x,y = ring("x,y", ZZ, lex) f = x*y**7 + 2*x**2*y**3 assert f.coeffs() == f.coeffs(lex) == f.coeffs('lex') == [2, 1] assert f.coeffs(grlex) == f.coeffs('grlex') == [1, 2] R, x,y = ring("x,y", ZZ, grlex) f = x*y**7 + 2*x**2*y**3 assert f.coeffs() == f.coeffs(grlex) == f.coeffs('grlex') == [1, 2] assert f.coeffs(lex) == f.coeffs('lex') == [2, 1] def test_PolyElement___add__(): Rt, t = ring("t", ZZ) Ruv, u,v = ring("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Ruv) assert dict(x + 3*y) == {(1, 0, 0): 1, (0, 1, 0): 3} assert dict(u + x) == dict(x + u) == {(1, 0, 0): 1, (0, 0, 0): u} assert dict(u + x*y) == dict(x*y + u) == {(1, 1, 0): 1, (0, 0, 0): u} assert dict(u + x*y + z) == dict(x*y + z + u) == {(1, 1, 0): 1, (0, 0, 1): 1, (0, 0, 0): u} assert dict(u*x + x) == dict(x + u*x) == {(1, 0, 0): u + 1} assert dict(u*x + x*y) == dict(x*y + u*x) == {(1, 1, 0): 1, (1, 0, 0): u} assert dict(u*x + x*y + z) == dict(x*y + z + u*x) == {(1, 1, 0): 1, (0, 0, 1): 1, (1, 0, 0): u} raises(TypeError, lambda: t + x) raises(TypeError, lambda: x + t) raises(TypeError, lambda: t + u) raises(TypeError, lambda: u + t) Fuv, u,v = field("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Fuv) assert dict(u + x) == dict(x + u) == {(1, 0, 0): 1, (0, 0, 0): u} Rxyz, x,y,z = ring("x,y,z", EX) assert dict(EX(pi) + x*y*z) == dict(x*y*z + EX(pi)) == {(1, 1, 1): EX(1), (0, 0, 0): EX(pi)} def test_PolyElement___sub__(): Rt, t = ring("t", ZZ) Ruv, u,v = ring("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Ruv) assert dict(x - 3*y) == {(1, 0, 0): 1, (0, 1, 0): -3} assert dict(-u + x) == dict(x - u) == {(1, 0, 0): 1, (0, 0, 0): -u} assert dict(-u + x*y) == dict(x*y - u) == {(1, 1, 0): 1, (0, 0, 0): -u} assert dict(-u + x*y + z) == dict(x*y + z - u) == {(1, 1, 0): 1, (0, 0, 1): 1, (0, 0, 0): -u} assert dict(-u*x + x) == dict(x - u*x) == {(1, 0, 0): -u + 1} assert dict(-u*x + x*y) == dict(x*y - u*x) == {(1, 1, 0): 1, (1, 0, 0): -u} assert dict(-u*x + x*y + z) == dict(x*y + z - u*x) == {(1, 1, 0): 1, (0, 0, 1): 1, (1, 0, 0): -u} raises(TypeError, lambda: t - x) raises(TypeError, lambda: x - t) raises(TypeError, lambda: t - u) raises(TypeError, lambda: u - t) Fuv, u,v = field("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Fuv) assert dict(-u + x) == dict(x - u) == {(1, 0, 0): 1, (0, 0, 0): -u} Rxyz, x,y,z = ring("x,y,z", EX) assert dict(-EX(pi) + x*y*z) == dict(x*y*z - EX(pi)) == {(1, 1, 1): EX(1), (0, 0, 0): -EX(pi)} def test_PolyElement___mul__(): Rt, t = ring("t", ZZ) Ruv, u,v = ring("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Ruv) assert dict(u*x) == dict(x*u) == {(1, 0, 0): u} assert dict(2*u*x + z) == dict(x*2*u + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1} assert dict(u*2*x + z) == dict(2*x*u + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1} assert dict(2*u*x + z) == dict(x*2*u + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1} assert dict(u*x*2 + z) == dict(x*u*2 + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1} assert dict(2*u*x*y + z) == dict(x*y*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(u*2*x*y + z) == dict(2*x*y*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(2*u*x*y + z) == dict(x*y*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(u*x*y*2 + z) == dict(x*y*u*2 + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(2*u*y*x + z) == dict(y*x*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(u*2*y*x + z) == dict(2*y*x*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(2*u*y*x + z) == dict(y*x*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(u*y*x*2 + z) == dict(y*x*u*2 + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(3*u*(x + y) + z) == dict((x + y)*3*u + z) == {(1, 0, 0): 3*u, (0, 1, 0): 3*u, (0, 0, 1): 1} raises(TypeError, lambda: t*x + z) raises(TypeError, lambda: x*t + z) raises(TypeError, lambda: t*u + z) raises(TypeError, lambda: u*t + z) Fuv, u,v = field("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Fuv) assert dict(u*x) == dict(x*u) == {(1, 0, 0): u} Rxyz, x,y,z = ring("x,y,z", EX) assert dict(EX(pi)*x*y*z) == dict(x*y*z*EX(pi)) == {(1, 1, 1): EX(pi)} def test_PolyElement___truediv__(): R, x,y,z = ring("x,y,z", ZZ) assert (2*x**2 - 4)/2 == x**2 - 2 assert (2*x**2 - 3)/2 == x**2 assert (x**2 - 1).quo(x) == x assert (x**2 - x).quo(x) == x - 1 assert (x**2 - 1)/x == x - x**(-1) assert (x**2 - x)/x == x - 1 assert (x**2 - 1)/(2*x) == x/2 - x**(-1)/2 assert (x**2 - 1).quo(2*x) == 0 assert (x**2 - x)/(x - 1) == (x**2 - x).quo(x - 1) == x R, x,y,z = ring("x,y,z", ZZ) assert len((x**2/3 + y**3/4 + z**4/5).terms()) == 0 R, x,y,z = ring("x,y,z", QQ) assert len((x**2/3 + y**3/4 + z**4/5).terms()) == 3 Rt, t = ring("t", ZZ) Ruv, u,v = ring("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Ruv) assert dict((u**2*x + u)/u) == {(1, 0, 0): u, (0, 0, 0): 1} raises(TypeError, lambda: u/(u**2*x + u)) raises(TypeError, lambda: t/x) raises(TypeError, lambda: x/t) raises(TypeError, lambda: t/u) raises(TypeError, lambda: u/t) R, x = ring("x", ZZ) f, g = x**2 + 2*x + 3, R(0) raises(ZeroDivisionError, lambda: f.div(g)) raises(ZeroDivisionError, lambda: divmod(f, g)) raises(ZeroDivisionError, lambda: f.rem(g)) raises(ZeroDivisionError, lambda: f % g) raises(ZeroDivisionError, lambda: f.quo(g)) raises(ZeroDivisionError, lambda: f / g) raises(ZeroDivisionError, lambda: f.exquo(g)) R, x, y = ring("x,y", ZZ) f, g = x*y + 2*x + 3, R(0) raises(ZeroDivisionError, lambda: f.div(g)) raises(ZeroDivisionError, lambda: divmod(f, g)) raises(ZeroDivisionError, lambda: f.rem(g)) raises(ZeroDivisionError, lambda: f % g) raises(ZeroDivisionError, lambda: f.quo(g)) raises(ZeroDivisionError, lambda: f / g) raises(ZeroDivisionError, lambda: f.exquo(g)) R, x = ring("x", ZZ) f, g = x**2 + 1, 2*x - 4 q, r = R(0), x**2 + 1 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = 3*x**3 + x**2 + x + 5, 5*x**2 - 3*x + 1 q, r = R(0), f assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = 5*x**4 + 4*x**3 + 3*x**2 + 2*x + 1, x**2 + 2*x + 3 q, r = 5*x**2 - 6*x, 20*x + 1 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = 5*x**5 + 4*x**4 + 3*x**3 + 2*x**2 + x, x**4 + 2*x**3 + 9 q, r = 5*x - 6, 15*x**3 + 2*x**2 - 44*x + 54 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) R, x = ring("x", QQ) f, g = x**2 + 1, 2*x - 4 q, r = x/2 + 1, R(5) assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = 3*x**3 + x**2 + x + 5, 5*x**2 - 3*x + 1 q, r = QQ(3, 5)*x + QQ(14, 25), QQ(52, 25)*x + QQ(111, 25) assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) R, x,y = ring("x,y", ZZ) f, g = x**2 - y**2, x - y q, r = x + y, R(0) assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q assert f.exquo(g) == q f, g = x**2 + y**2, x - y q, r = x + y, 2*y**2 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = x**2 + y**2, -x + y q, r = -x - y, 2*y**2 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = x**2 + y**2, 2*x - 2*y q, r = R(0), f assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) R, x,y = ring("x,y", QQ) f, g = x**2 - y**2, x - y q, r = x + y, R(0) assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q assert f.exquo(g) == q f, g = x**2 + y**2, x - y q, r = x + y, 2*y**2 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = x**2 + y**2, -x + y q, r = -x - y, 2*y**2 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = x**2 + y**2, 2*x - 2*y q, r = x/2 + y/2, 2*y**2 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) def test_PolyElement___pow__(): R, x = ring("x", ZZ, grlex) f = 2*x + 3 assert f**0 == 1 assert f**1 == f raises(ValueError, lambda: f**(-1)) assert x**(-1) == x**(-1) assert f**2 == f._pow_generic(2) == f._pow_multinomial(2) == 4*x**2 + 12*x + 9 assert f**3 == f._pow_generic(3) == f._pow_multinomial(3) == 8*x**3 + 36*x**2 + 54*x + 27 assert f**4 == f._pow_generic(4) == f._pow_multinomial(4) == 16*x**4 + 96*x**3 + 216*x**2 + 216*x + 81 assert f**5 == f._pow_generic(5) == f._pow_multinomial(5) == 32*x**5 + 240*x**4 + 720*x**3 + 1080*x**2 + 810*x + 243 R, x,y,z = ring("x,y,z", ZZ, grlex) f = x**3*y - 2*x*y**2 - 3*z + 1 g = x**6*y**2 - 4*x**4*y**3 - 6*x**3*y*z + 2*x**3*y + 4*x**2*y**4 + 12*x*y**2*z - 4*x*y**2 + 9*z**2 - 6*z + 1 assert f**2 == f._pow_generic(2) == f._pow_multinomial(2) == g R, t = ring("t", ZZ) f = -11200*t**4 - 2604*t**2 + 49 g = 15735193600000000*t**16 + 14633730048000000*t**14 + 4828147466240000*t**12 \ + 598976863027200*t**10 + 3130812416256*t**8 - 2620523775744*t**6 \ + 92413760096*t**4 - 1225431984*t**2 + 5764801 assert f**4 == f._pow_generic(4) == f._pow_multinomial(4) == g def test_PolyElement_div(): R, x = ring("x", ZZ, grlex) f = x**3 - 12*x**2 - 42 g = x - 3 q = x**2 - 9*x - 27 r = -123 assert f.div([g]) == ([q], r) R, x = ring("x", ZZ, grlex) f = x**2 + 2*x + 2 assert f.div([R(1)]) == ([f], 0) R, x = ring("x", QQ, grlex) f = x**2 + 2*x + 2 assert f.div([R(2)]) == ([QQ(1,2)*x**2 + x + 1], 0) R, x,y = ring("x,y", ZZ, grlex) f = 4*x**2*y - 2*x*y + 4*x - 2*y + 8 assert f.div([R(2)]) == ([2*x**2*y - x*y + 2*x - y + 4], 0) assert f.div([2*y]) == ([2*x**2 - x - 1], 4*x + 8) f = x - 1 g = y - 1 assert f.div([g]) == ([0], f) f = x*y**2 + 1 G = [x*y + 1, y + 1] Q = [y, -1] r = 2 assert f.div(G) == (Q, r) f = x**2*y + x*y**2 + y**2 G = [x*y - 1, y**2 - 1] Q = [x + y, 1] r = x + y + 1 assert f.div(G) == (Q, r) G = [y**2 - 1, x*y - 1] Q = [x + 1, x] r = 2*x + 1 assert f.div(G) == (Q, r) R, = ring("", ZZ) assert R(3).div(R(2)) == (0, 3) R, = ring("", QQ) assert R(3).div(R(2)) == (QQ(3, 2), 0) def test_PolyElement_rem(): R, x = ring("x", ZZ, grlex) f = x**3 - 12*x**2 - 42 g = x - 3 r = -123 assert f.rem([g]) == f.div([g])[1] == r R, x,y = ring("x,y", ZZ, grlex) f = 4*x**2*y - 2*x*y + 4*x - 2*y + 8 assert f.rem([R(2)]) == f.div([R(2)])[1] == 0 assert f.rem([2*y]) == f.div([2*y])[1] == 4*x + 8 f = x - 1 g = y - 1 assert f.rem([g]) == f.div([g])[1] == f f = x*y**2 + 1 G = [x*y + 1, y + 1] r = 2 assert f.rem(G) == f.div(G)[1] == r f = x**2*y + x*y**2 + y**2 G = [x*y - 1, y**2 - 1] r = x + y + 1 assert f.rem(G) == f.div(G)[1] == r G = [y**2 - 1, x*y - 1] r = 2*x + 1 assert f.rem(G) == f.div(G)[1] == r def test_PolyElement_deflate(): R, x = ring("x", ZZ) assert (2*x**2).deflate(x**4 + 4*x**2 + 1) == ((2,), [2*x, x**2 + 4*x + 1]) R, x,y = ring("x,y", ZZ) assert R(0).deflate(R(0)) == ((1, 1), [0, 0]) assert R(1).deflate(R(0)) == ((1, 1), [1, 0]) assert R(1).deflate(R(2)) == ((1, 1), [1, 2]) assert R(1).deflate(2*y) == ((1, 1), [1, 2*y]) assert (2*y).deflate(2*y) == ((1, 1), [2*y, 2*y]) assert R(2).deflate(2*y**2) == ((1, 2), [2, 2*y]) assert (2*y**2).deflate(2*y**2) == ((1, 2), [2*y, 2*y]) f = x**4*y**2 + x**2*y + 1 g = x**2*y**3 + x**2*y + 1 assert f.deflate(g) == ((2, 1), [x**2*y**2 + x*y + 1, x*y**3 + x*y + 1]) def test_PolyElement_clear_denoms(): R, x,y = ring("x,y", QQ) assert R(1).clear_denoms() == (ZZ(1), 1) assert R(7).clear_denoms() == (ZZ(1), 7) assert R(QQ(7,3)).clear_denoms() == (3, 7) assert R(QQ(7,3)).clear_denoms() == (3, 7) assert (3*x**2 + x).clear_denoms() == (1, 3*x**2 + x) assert (x**2 + QQ(1,2)*x).clear_denoms() == (2, 2*x**2 + x) rQQ, x,t = ring("x,t", QQ, lex) rZZ, X,T = ring("x,t", ZZ, lex) F = [x - QQ(17824537287975195925064602467992950991718052713078834557692023531499318507213727406844943097,413954288007559433755329699713866804710749652268151059918115348815925474842910720000)*t**7 - QQ(4882321164854282623427463828745855894130208215961904469205260756604820743234704900167747753,12936071500236232304854053116058337647210926633379720622441104650497671088840960000)*t**6 - QQ(36398103304520066098365558157422127347455927422509913596393052633155821154626830576085097433,25872143000472464609708106232116675294421853266759441244882209300995342177681920000)*t**5 - QQ(168108082231614049052707339295479262031324376786405372698857619250210703675982492356828810819,58212321751063045371843239022262519412449169850208742800984970927239519899784320000)*t**4 - QQ(5694176899498574510667890423110567593477487855183144378347226247962949388653159751849449037,1617008937529529038106756639507292205901365829172465077805138081312208886105120000)*t**3 - QQ(154482622347268833757819824809033388503591365487934245386958884099214649755244381307907779,60637835157357338929003373981523457721301218593967440417692678049207833228942000)*t**2 - QQ(2452813096069528207645703151222478123259511586701148682951852876484544822947007791153163,2425513406294293557160134959260938308852048743758697616707707121968313329157680)*t - QQ(34305265428126440542854669008203683099323146152358231964773310260498715579162112959703,202126117191191129763344579938411525737670728646558134725642260164026110763140), t**8 + QQ(693749860237914515552,67859264524169150569)*t**7 + QQ(27761407182086143225024,610733380717522355121)*t**6 + QQ(7785127652157884044288,67859264524169150569)*t**5 + QQ(36567075214771261409792,203577793572507451707)*t**4 + QQ(36336335165196147384320,203577793572507451707)*t**3 + QQ(7452455676042754048000,67859264524169150569)*t**2 + QQ(2593331082514399232000,67859264524169150569)*t + QQ(390399197427343360000,67859264524169150569)] G = [3725588592068034903797967297424801242396746870413359539263038139343329273586196480000*X - 160420835591776763325581422211936558925462474417709511019228211783493866564923546661604487873*T**7 - 1406108495478033395547109582678806497509499966197028487131115097902188374051595011248311352864*T**6 - 5241326875850889518164640374668786338033653548841427557880599579174438246266263602956254030352*T**5 - 10758917262823299139373269714910672770004760114329943852726887632013485035262879510837043892416*T**4 - 13119383576444715672578819534846747735372132018341964647712009275306635391456880068261130581248*T**3 - 9491412317016197146080450036267011389660653495578680036574753839055748080962214787557853941760*T**2 - 3767520915562795326943800040277726397326609797172964377014046018280260848046603967211258368000*T - 632314652371226552085897259159210286886724229880266931574701654721512325555116066073245696000, 610733380717522355121*T**8 + 6243748742141230639968*T**7 + 27761407182086143225024*T**6 + 70066148869420956398592*T**5 + 109701225644313784229376*T**4 + 109009005495588442152960*T**3 + 67072101084384786432000*T**2 + 23339979742629593088000*T + 3513592776846090240000] assert [ f.clear_denoms()[1].set_ring(rZZ) for f in F ] == G def test_PolyElement_cofactors(): R, x, y = ring("x,y", ZZ) f, g = R(0), R(0) assert f.cofactors(g) == (0, 0, 0) f, g = R(2), R(0) assert f.cofactors(g) == (2, 1, 0) f, g = R(-2), R(0) assert f.cofactors(g) == (2, -1, 0) f, g = R(0), R(-2) assert f.cofactors(g) == (2, 0, -1) f, g = R(0), 2*x + 4 assert f.cofactors(g) == (2*x + 4, 0, 1) f, g = 2*x + 4, R(0) assert f.cofactors(g) == (2*x + 4, 1, 0) f, g = R(2), R(2) assert f.cofactors(g) == (2, 1, 1) f, g = R(-2), R(2) assert f.cofactors(g) == (2, -1, 1) f, g = R(2), R(-2) assert f.cofactors(g) == (2, 1, -1) f, g = R(-2), R(-2) assert f.cofactors(g) == (2, -1, -1) f, g = x**2 + 2*x + 1, R(1) assert f.cofactors(g) == (1, x**2 + 2*x + 1, 1) f, g = x**2 + 2*x + 1, R(2) assert f.cofactors(g) == (1, x**2 + 2*x + 1, 2) f, g = 2*x**2 + 4*x + 2, R(2) assert f.cofactors(g) == (2, x**2 + 2*x + 1, 1) f, g = R(2), 2*x**2 + 4*x + 2 assert f.cofactors(g) == (2, 1, x**2 + 2*x + 1) f, g = 2*x**2 + 4*x + 2, x + 1 assert f.cofactors(g) == (x + 1, 2*x + 2, 1) f, g = x + 1, 2*x**2 + 4*x + 2 assert f.cofactors(g) == (x + 1, 1, 2*x + 2) R, x, y, z, t = ring("x,y,z,t", ZZ) f, g = t**2 + 2*t + 1, 2*t + 2 assert f.cofactors(g) == (t + 1, t + 1, 2) f, g = z**2*t**2 + 2*z**2*t + z**2 + z*t + z, t**2 + 2*t + 1 h, cff, cfg = t + 1, z**2*t + z**2 + z, t + 1 assert f.cofactors(g) == (h, cff, cfg) assert g.cofactors(f) == (h, cfg, cff) R, x, y = ring("x,y", QQ) f = QQ(1,2)*x**2 + x + QQ(1,2) g = QQ(1,2)*x + QQ(1,2) h = x + 1 assert f.cofactors(g) == (h, g, QQ(1,2)) assert g.cofactors(f) == (h, QQ(1,2), g) R, x, y = ring("x,y", RR) f = 2.1*x*y**2 - 2.1*x*y + 2.1*x g = 2.1*x**3 h = 1.0*x assert f.cofactors(g) == (h, f/h, g/h) assert g.cofactors(f) == (h, g/h, f/h) def test_PolyElement_gcd(): R, x, y = ring("x,y", QQ) f = QQ(1,2)*x**2 + x + QQ(1,2) g = QQ(1,2)*x + QQ(1,2) assert f.gcd(g) == x + 1 def test_PolyElement_cancel(): R, x, y = ring("x,y", ZZ) f = 2*x**3 + 4*x**2 + 2*x g = 3*x**2 + 3*x F = 2*x + 2 G = 3 assert f.cancel(g) == (F, G) assert (-f).cancel(g) == (-F, G) assert f.cancel(-g) == (-F, G) R, x, y = ring("x,y", QQ) f = QQ(1,2)*x**3 + x**2 + QQ(1,2)*x g = QQ(1,3)*x**2 + QQ(1,3)*x F = 3*x + 3 G = 2 assert f.cancel(g) == (F, G) assert (-f).cancel(g) == (-F, G) assert f.cancel(-g) == (-F, G) Fx, x = field("x", ZZ) Rt, t = ring("t", Fx) f = (-x**2 - 4)/4*t g = t**2 + (x**2 + 2)/2 assert f.cancel(g) == ((-x**2 - 4)*t, 4*t**2 + 2*x**2 + 4) def test_PolyElement_max_norm(): R, x, y = ring("x,y", ZZ) assert R(0).max_norm() == 0 assert R(1).max_norm() == 1 assert (x**3 + 4*x**2 + 2*x + 3).max_norm() == 4 def test_PolyElement_l1_norm(): R, x, y = ring("x,y", ZZ) assert R(0).l1_norm() == 0 assert R(1).l1_norm() == 1 assert (x**3 + 4*x**2 + 2*x + 3).l1_norm() == 10 def test_PolyElement_diff(): R, X = xring("x:11", QQ) f = QQ(288,5)*X[0]**8*X[1]**6*X[4]**3*X[10]**2 + 8*X[0]**2*X[2]**3*X[4]**3 +2*X[0]**2 - 2*X[1]**2 assert f.diff(X[0]) == QQ(2304,5)*X[0]**7*X[1]**6*X[4]**3*X[10]**2 + 16*X[0]*X[2]**3*X[4]**3 + 4*X[0] assert f.diff(X[4]) == QQ(864,5)*X[0]**8*X[1]**6*X[4]**2*X[10]**2 + 24*X[0]**2*X[2]**3*X[4]**2 assert f.diff(X[10]) == QQ(576,5)*X[0]**8*X[1]**6*X[4]**3*X[10] def test_PolyElement___call__(): R, x = ring("x", ZZ) f = 3*x + 1 assert f(0) == 1 assert f(1) == 4 raises(ValueError, lambda: f()) raises(ValueError, lambda: f(0, 1)) raises(CoercionFailed, lambda: f(QQ(1,7))) R, x,y = ring("x,y", ZZ) f = 3*x + y**2 + 1 assert f(0, 0) == 1 assert f(1, 7) == 53 Ry = R.drop(x) assert f(0) == Ry.y**2 + 1 assert f(1) == Ry.y**2 + 4 raises(ValueError, lambda: f()) raises(ValueError, lambda: f(0, 1, 2)) raises(CoercionFailed, lambda: f(1, QQ(1,7))) raises(CoercionFailed, lambda: f(QQ(1,7), 1)) raises(CoercionFailed, lambda: f(QQ(1,7), QQ(1,7))) def test_PolyElement_evaluate(): R, x = ring("x", ZZ) f = x**3 + 4*x**2 + 2*x + 3 r = f.evaluate(x, 0) assert r == 3 and not isinstance(r, PolyElement) raises(CoercionFailed, lambda: f.evaluate(x, QQ(1,7))) R, x, y, z = ring("x,y,z", ZZ) f = (x*y)**3 + 4*(x*y)**2 + 2*x*y + 3 r = f.evaluate(x, 0) assert r == 3 and isinstance(r, R.drop(x).dtype) r = f.evaluate([(x, 0), (y, 0)]) assert r == 3 and isinstance(r, R.drop(x, y).dtype) r = f.evaluate(y, 0) assert r == 3 and isinstance(r, R.drop(y).dtype) r = f.evaluate([(y, 0), (x, 0)]) assert r == 3 and isinstance(r, R.drop(y, x).dtype) r = f.evaluate([(x, 0), (y, 0), (z, 0)]) assert r == 3 and not isinstance(r, PolyElement) raises(CoercionFailed, lambda: f.evaluate([(x, 1), (y, QQ(1,7))])) raises(CoercionFailed, lambda: f.evaluate([(x, QQ(1,7)), (y, 1)])) raises(CoercionFailed, lambda: f.evaluate([(x, QQ(1,7)), (y, QQ(1,7))])) def test_PolyElement_subs(): R, x = ring("x", ZZ) f = x**3 + 4*x**2 + 2*x + 3 r = f.subs(x, 0) assert r == 3 and isinstance(r, R.dtype) raises(CoercionFailed, lambda: f.subs(x, QQ(1,7))) R, x, y, z = ring("x,y,z", ZZ) f = x**3 + 4*x**2 + 2*x + 3 r = f.subs(x, 0) assert r == 3 and isinstance(r, R.dtype) r = f.subs([(x, 0), (y, 0)]) assert r == 3 and isinstance(r, R.dtype) raises(CoercionFailed, lambda: f.subs([(x, 1), (y, QQ(1,7))])) raises(CoercionFailed, lambda: f.subs([(x, QQ(1,7)), (y, 1)])) raises(CoercionFailed, lambda: f.subs([(x, QQ(1,7)), (y, QQ(1,7))])) def test_PolyElement_compose(): R, x = ring("x", ZZ) f = x**3 + 4*x**2 + 2*x + 3 r = f.compose(x, 0) assert r == 3 and isinstance(r, R.dtype) assert f.compose(x, x) == f assert f.compose(x, x**2) == x**6 + 4*x**4 + 2*x**2 + 3 raises(CoercionFailed, lambda: f.compose(x, QQ(1,7))) R, x, y, z = ring("x,y,z", ZZ) f = x**3 + 4*x**2 + 2*x + 3 r = f.compose(x, 0) assert r == 3 and isinstance(r, R.dtype) r = f.compose([(x, 0), (y, 0)]) assert r == 3 and isinstance(r, R.dtype) r = (x**3 + 4*x**2 + 2*x*y*z + 3).compose(x, y*z**2 - 1) q = (y*z**2 - 1)**3 + 4*(y*z**2 - 1)**2 + 2*(y*z**2 - 1)*y*z + 3 assert r == q and isinstance(r, R.dtype) def test_PolyElement_is_(): R, x,y,z = ring("x,y,z", QQ) assert (x - x).is_generator == False assert (x - x).is_ground == True assert (x - x).is_monomial == True assert (x - x).is_term == True assert (x - x + 1).is_generator == False assert (x - x + 1).is_ground == True assert (x - x + 1).is_monomial == True assert (x - x + 1).is_term == True assert x.is_generator == True assert x.is_ground == False assert x.is_monomial == True assert x.is_term == True assert (x*y).is_generator == False assert (x*y).is_ground == False assert (x*y).is_monomial == True assert (x*y).is_term == True assert (3*x).is_generator == False assert (3*x).is_ground == False assert (3*x).is_monomial == False assert (3*x).is_term == True assert (3*x + 1).is_generator == False assert (3*x + 1).is_ground == False assert (3*x + 1).is_monomial == False assert (3*x + 1).is_term == False assert R(0).is_zero is True assert R(1).is_zero is False assert R(0).is_one is False assert R(1).is_one is True assert (x - 1).is_monic is True assert (2*x - 1).is_monic is False assert (3*x + 2).is_primitive is True assert (4*x + 2).is_primitive is False assert (x + y + z + 1).is_linear is True assert (x*y*z + 1).is_linear is False assert (x*y + z + 1).is_quadratic is True assert (x*y*z + 1).is_quadratic is False assert (x - 1).is_squarefree is True assert ((x - 1)**2).is_squarefree is False assert (x**2 + x + 1).is_irreducible is True assert (x**2 + 2*x + 1).is_irreducible is False _, t = ring("t", FF(11)) assert (7*t + 3).is_irreducible is True assert (7*t**2 + 3*t + 1).is_irreducible is False _, u = ring("u", ZZ) f = u**16 + u**14 - u**10 - u**8 - u**6 + u**2 assert f.is_cyclotomic is False assert (f + 1).is_cyclotomic is True raises(MultivariatePolynomialError, lambda: x.is_cyclotomic) R, = ring("", ZZ) assert R(4).is_squarefree is True assert R(6).is_irreducible is True def test_PolyElement_drop(): R, x,y,z = ring("x,y,z", ZZ) assert R(1).drop(0).ring == PolyRing("y,z", ZZ, lex) assert R(1).drop(0).drop(0).ring == PolyRing("z", ZZ, lex) assert isinstance(R(1).drop(0).drop(0).drop(0), R.dtype) is False raises(ValueError, lambda: z.drop(0).drop(0).drop(0)) raises(ValueError, lambda: x.drop(0)) def test_PolyElement_pdiv(): _, x, y = ring("x,y", ZZ) f, g = x**2 - y**2, x - y q, r = x + y, 0 assert f.pdiv(g) == (q, r) assert f.prem(g) == r assert f.pquo(g) == q assert f.pexquo(g) == q def test_PolyElement_gcdex(): _, x = ring("x", QQ) f, g = 2*x, x**2 - 16 s, t, h = x/32, -QQ(1, 16), 1 assert f.half_gcdex(g) == (s, h) assert f.gcdex(g) == (s, t, h) def test_PolyElement_subresultants(): _, x = ring("x", ZZ) f, g, h = x**2 - 2*x + 1, x**2 - 1, 2*x - 2 assert f.subresultants(g) == [f, g, h] def test_PolyElement_resultant(): _, x = ring("x", ZZ) f, g, h = x**2 - 2*x + 1, x**2 - 1, 0 assert f.resultant(g) == h def test_PolyElement_discriminant(): _, x = ring("x", ZZ) f, g = x**3 + 3*x**2 + 9*x - 13, -11664 assert f.discriminant() == g F, a, b, c = ring("a,b,c", ZZ) _, x = ring("x", F) f, g = a*x**2 + b*x + c, b**2 - 4*a*c assert f.discriminant() == g def test_PolyElement_decompose(): _, x = ring("x", ZZ) f = x**12 + 20*x**10 + 150*x**8 + 500*x**6 + 625*x**4 - 2*x**3 - 10*x + 9 g = x**4 - 2*x + 9 h = x**3 + 5*x assert g.compose(x, h) == f assert f.decompose() == [g, h] def test_PolyElement_shift(): _, x = ring("x", ZZ) assert (x**2 - 2*x + 1).shift(2) == x**2 + 2*x + 1 def test_PolyElement_sturm(): F, t = field("t", ZZ) _, x = ring("x", F) f = 1024/(15625*t**8)*x**5 - 4096/(625*t**8)*x**4 + 32/(15625*t**4)*x**3 - 128/(625*t**4)*x**2 + F(1)/62500*x - F(1)/625 assert f.sturm() == [ x**3 - 100*x**2 + t**4/64*x - 25*t**4/16, 3*x**2 - 200*x + t**4/64, (-t**4/96 + F(20000)/9)*x + 25*t**4/18, (-9*t**12 - 11520000*t**8 - 3686400000000*t**4)/(576*t**8 - 245760000*t**4 + 26214400000000), ] def test_PolyElement_gff_list(): _, x = ring("x", ZZ) f = x**5 + 2*x**4 - x**3 - 2*x**2 assert f.gff_list() == [(x, 1), (x + 2, 4)] f = x*(x - 1)**3*(x - 2)**2*(x - 4)**2*(x - 5) assert f.gff_list() == [(x**2 - 5*x + 4, 1), (x**2 - 5*x + 4, 2), (x, 3)] def test_PolyElement_sqf_norm(): R, x = ring("x", QQ.algebraic_field(sqrt(3))) X = R.to_ground().x assert (x**2 - 2).sqf_norm() == (1, x**2 - 2*sqrt(3)*x + 1, X**4 - 10*X**2 + 1) R, x = ring("x", QQ.algebraic_field(sqrt(2))) X = R.to_ground().x assert (x**2 - 3).sqf_norm() == (1, x**2 - 2*sqrt(2)*x - 1, X**4 - 10*X**2 + 1) def test_PolyElement_sqf_list(): _, x = ring("x", ZZ) f = x**5 - x**3 - x**2 + 1 g = x**3 + 2*x**2 + 2*x + 1 h = x - 1 p = x**4 + x**3 - x - 1 assert f.sqf_part() == p assert f.sqf_list() == (1, [(g, 1), (h, 2)]) def test_PolyElement_factor_list(): _, x = ring("x", ZZ) f = x**5 - x**3 - x**2 + 1 u = x + 1 v = x - 1 w = x**2 + x + 1 assert f.factor_list() == (1, [(u, 1), (v, 2), (w, 1)]) def test_issue_21410(): R, x = ring('x', FF(2)) p = x**6 + x**5 + x**4 + x**3 + 1 assert p._pow_multinomial(4) == x**24 + x**20 + x**16 + x**12 + 1
38789876f49e0231fe62d8271d15fa102aea95f21d07dceef41498a2f6959114
"""Tests for the implementation of RootOf class and related tools. """ from sympy.polys.polytools import Poly from sympy.polys.rootoftools import (rootof, RootOf, CRootOf, RootSum, _pure_key_dict as D) from sympy.polys.polyerrors import ( MultivariatePolynomialError, GeneratorsNeeded, PolynomialError, ) from sympy.core.function import (Function, Lambda) from sympy.core.numbers import (Float, I, Rational) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import tan from sympy.integrals.integrals import Integral from sympy.polys.orthopolys import legendre_poly from sympy.solvers.solvers import solve from sympy.testing.pytest import raises, slow from sympy.core.expr import unchanged from sympy.abc import a, b, x, y, z, r def test_CRootOf___new__(): assert rootof(x, 0) == 0 assert rootof(x, -1) == 0 assert rootof(x, S.Zero) == 0 assert rootof(x - 1, 0) == 1 assert rootof(x - 1, -1) == 1 assert rootof(x + 1, 0) == -1 assert rootof(x + 1, -1) == -1 assert rootof(x**2 + 2*x + 3, 0) == -1 - I*sqrt(2) assert rootof(x**2 + 2*x + 3, 1) == -1 + I*sqrt(2) assert rootof(x**2 + 2*x + 3, -1) == -1 + I*sqrt(2) assert rootof(x**2 + 2*x + 3, -2) == -1 - I*sqrt(2) r = rootof(x**2 + 2*x + 3, 0, radicals=False) assert isinstance(r, RootOf) is True r = rootof(x**2 + 2*x + 3, 1, radicals=False) assert isinstance(r, RootOf) is True r = rootof(x**2 + 2*x + 3, -1, radicals=False) assert isinstance(r, RootOf) is True r = rootof(x**2 + 2*x + 3, -2, radicals=False) assert isinstance(r, RootOf) is True assert rootof((x - 1)*(x + 1), 0, radicals=False) == -1 assert rootof((x - 1)*(x + 1), 1, radicals=False) == 1 assert rootof((x - 1)*(x + 1), -1, radicals=False) == 1 assert rootof((x - 1)*(x + 1), -2, radicals=False) == -1 assert rootof((x - 1)*(x + 1), 0, radicals=True) == -1 assert rootof((x - 1)*(x + 1), 1, radicals=True) == 1 assert rootof((x - 1)*(x + 1), -1, radicals=True) == 1 assert rootof((x - 1)*(x + 1), -2, radicals=True) == -1 assert rootof((x - 1)*(x**3 + x + 3), 0) == rootof(x**3 + x + 3, 0) assert rootof((x - 1)*(x**3 + x + 3), 1) == 1 assert rootof((x - 1)*(x**3 + x + 3), 2) == rootof(x**3 + x + 3, 1) assert rootof((x - 1)*(x**3 + x + 3), 3) == rootof(x**3 + x + 3, 2) assert rootof((x - 1)*(x**3 + x + 3), -1) == rootof(x**3 + x + 3, 2) assert rootof((x - 1)*(x**3 + x + 3), -2) == rootof(x**3 + x + 3, 1) assert rootof((x - 1)*(x**3 + x + 3), -3) == 1 assert rootof((x - 1)*(x**3 + x + 3), -4) == rootof(x**3 + x + 3, 0) assert rootof(x**4 + 3*x**3, 0) == -3 assert rootof(x**4 + 3*x**3, 1) == 0 assert rootof(x**4 + 3*x**3, 2) == 0 assert rootof(x**4 + 3*x**3, 3) == 0 raises(GeneratorsNeeded, lambda: rootof(0, 0)) raises(GeneratorsNeeded, lambda: rootof(1, 0)) raises(PolynomialError, lambda: rootof(Poly(0, x), 0)) raises(PolynomialError, lambda: rootof(Poly(1, x), 0)) raises(PolynomialError, lambda: rootof(x - y, 0)) # issue 8617 raises(PolynomialError, lambda: rootof(exp(x), 0)) raises(NotImplementedError, lambda: rootof(x**3 - x + sqrt(2), 0)) raises(NotImplementedError, lambda: rootof(x**3 - x + I, 0)) raises(IndexError, lambda: rootof(x**2 - 1, -4)) raises(IndexError, lambda: rootof(x**2 - 1, -3)) raises(IndexError, lambda: rootof(x**2 - 1, 2)) raises(IndexError, lambda: rootof(x**2 - 1, 3)) raises(ValueError, lambda: rootof(x**2 - 1, x)) assert rootof(Poly(x - y, x), 0) == y assert rootof(Poly(x**2 - y, x), 0) == -sqrt(y) assert rootof(Poly(x**2 - y, x), 1) == sqrt(y) assert rootof(Poly(x**3 - y, x), 0) == y**Rational(1, 3) assert rootof(y*x**3 + y*x + 2*y, x, 0) == -1 raises(NotImplementedError, lambda: rootof(x**3 + x + 2*y, x, 0)) assert rootof(x**3 + x + 1, 0).is_commutative is True def test_CRootOf_attributes(): r = rootof(x**3 + x + 3, 0) assert r.is_number assert r.free_symbols == set() # if the following assertion fails then multivariate polynomials # are apparently supported and the RootOf.free_symbols routine # should be changed to return whatever symbols would not be # the PurePoly dummy symbol raises(NotImplementedError, lambda: rootof(Poly(x**3 + y*x + 1, x), 0)) def test_CRootOf___eq__(): assert (rootof(x**3 + x + 3, 0) == rootof(x**3 + x + 3, 0)) is True assert (rootof(x**3 + x + 3, 0) == rootof(x**3 + x + 3, 1)) is False assert (rootof(x**3 + x + 3, 1) == rootof(x**3 + x + 3, 1)) is True assert (rootof(x**3 + x + 3, 1) == rootof(x**3 + x + 3, 2)) is False assert (rootof(x**3 + x + 3, 2) == rootof(x**3 + x + 3, 2)) is True assert (rootof(x**3 + x + 3, 0) == rootof(y**3 + y + 3, 0)) is True assert (rootof(x**3 + x + 3, 0) == rootof(y**3 + y + 3, 1)) is False assert (rootof(x**3 + x + 3, 1) == rootof(y**3 + y + 3, 1)) is True assert (rootof(x**3 + x + 3, 1) == rootof(y**3 + y + 3, 2)) is False assert (rootof(x**3 + x + 3, 2) == rootof(y**3 + y + 3, 2)) is True def test_CRootOf___eval_Eq__(): f = Function('f') eq = x**3 + x + 3 r = rootof(eq, 2) r1 = rootof(eq, 1) assert Eq(r, r1) is S.false assert Eq(r, r) is S.true assert unchanged(Eq, r, x) assert Eq(r, 0) is S.false assert Eq(r, S.Infinity) is S.false assert Eq(r, I) is S.false assert unchanged(Eq, r, f(0)) sol = solve(eq) for s in sol: if s.is_real: assert Eq(r, s) is S.false r = rootof(eq, 0) for s in sol: if s.is_real: assert Eq(r, s) is S.true eq = x**3 + x + 1 sol = solve(eq) assert [Eq(rootof(eq, i), j) for i in range(3) for j in sol ].count(True) == 3 assert Eq(rootof(eq, 0), 1 + S.ImaginaryUnit) == False def test_CRootOf_is_real(): assert rootof(x**3 + x + 3, 0).is_real is True assert rootof(x**3 + x + 3, 1).is_real is False assert rootof(x**3 + x + 3, 2).is_real is False def test_CRootOf_is_complex(): assert rootof(x**3 + x + 3, 0).is_complex is True def test_CRootOf_subs(): assert rootof(x**3 + x + 1, 0).subs(x, y) == rootof(y**3 + y + 1, 0) def test_CRootOf_diff(): assert rootof(x**3 + x + 1, 0).diff(x) == 0 assert rootof(x**3 + x + 1, 0).diff(y) == 0 @slow def test_CRootOf_evalf(): real = rootof(x**3 + x + 3, 0).evalf(n=20) assert real.epsilon_eq(Float("-1.2134116627622296341")) re, im = rootof(x**3 + x + 3, 1).evalf(n=20).as_real_imag() assert re.epsilon_eq( Float("0.60670583138111481707")) assert im.epsilon_eq(-Float("1.45061224918844152650")) re, im = rootof(x**3 + x + 3, 2).evalf(n=20).as_real_imag() assert re.epsilon_eq(Float("0.60670583138111481707")) assert im.epsilon_eq(Float("1.45061224918844152650")) p = legendre_poly(4, x, polys=True) roots = [str(r.n(17)) for r in p.real_roots()] # magnitudes are given by # sqrt(3/S(7) - 2*sqrt(6/S(5))/7) # and # sqrt(3/S(7) + 2*sqrt(6/S(5))/7) assert roots == [ "-0.86113631159405258", "-0.33998104358485626", "0.33998104358485626", "0.86113631159405258", ] re = rootof(x**5 - 5*x + 12, 0).evalf(n=20) assert re.epsilon_eq(Float("-1.84208596619025438271")) re, im = rootof(x**5 - 5*x + 12, 1).evalf(n=20).as_real_imag() assert re.epsilon_eq(Float("-0.351854240827371999559")) assert im.epsilon_eq(Float("-1.709561043370328882010")) re, im = rootof(x**5 - 5*x + 12, 2).evalf(n=20).as_real_imag() assert re.epsilon_eq(Float("-0.351854240827371999559")) assert im.epsilon_eq(Float("+1.709561043370328882010")) re, im = rootof(x**5 - 5*x + 12, 3).evalf(n=20).as_real_imag() assert re.epsilon_eq(Float("+1.272897223922499190910")) assert im.epsilon_eq(Float("-0.719798681483861386681")) re, im = rootof(x**5 - 5*x + 12, 4).evalf(n=20).as_real_imag() assert re.epsilon_eq(Float("+1.272897223922499190910")) assert im.epsilon_eq(Float("+0.719798681483861386681")) # issue 6393 assert str(rootof(x**5 + 2*x**4 + x**3 - 68719476736, 0).n(3)) == '147.' eq = (531441*x**11 + 3857868*x**10 + 13730229*x**9 + 32597882*x**8 + 55077472*x**7 + 60452000*x**6 + 32172064*x**5 - 4383808*x**4 - 11942912*x**3 - 1506304*x**2 + 1453312*x + 512) a, b = rootof(eq, 1).n(2).as_real_imag() c, d = rootof(eq, 2).n(2).as_real_imag() assert a == c assert b < d assert b == -d # issue 6451 r = rootof(legendre_poly(64, x), 7) assert r.n(2) == r.n(100).n(2) # issue 9019 r0 = rootof(x**2 + 1, 0, radicals=False) r1 = rootof(x**2 + 1, 1, radicals=False) assert r0.n(4) == -1.0*I assert r1.n(4) == 1.0*I # make sure verification is used in case a max/min traps the "root" assert str(rootof(4*x**5 + 16*x**3 + 12*x**2 + 7, 0).n(3)) == '-0.976' # watch out for UnboundLocalError c = CRootOf(90720*x**6 - 4032*x**4 + 84*x**2 - 1, 0) assert c._eval_evalf(2) # doesn't fail # watch out for imaginary parts that don't want to evaluate assert str(RootOf(x**16 + 32*x**14 + 508*x**12 + 5440*x**10 + 39510*x**8 + 204320*x**6 + 755548*x**4 + 1434496*x**2 + 877969, 10).n(2)) == '-3.4*I' assert abs(RootOf(x**4 + 10*x**2 + 1, 0).n(2)) < 0.4 # check reset and args r = [RootOf(x**3 + x + 3, i) for i in range(3)] r[0]._reset() for ri in r: i = ri._get_interval() ri.n(2) assert i != ri._get_interval() ri._reset() assert i == ri._get_interval() assert i == i.func(*i.args) def test_CRootOf_evalf_caching_bug(): r = rootof(x**5 - 5*x + 12, 1) r.n() a = r._get_interval() r = rootof(x**5 - 5*x + 12, 1) r.n() b = r._get_interval() assert a == b def test_CRootOf_real_roots(): assert Poly(x**5 + x + 1).real_roots() == [rootof(x**3 - x**2 + 1, 0)] assert Poly(x**5 + x + 1).real_roots(radicals=False) == [rootof( x**3 - x**2 + 1, 0)] # https://github.com/sympy/sympy/issues/20902 p = Poly(-3*x**4 - 10*x**3 - 12*x**2 - 6*x - 1, x, domain='ZZ') assert CRootOf.real_roots(p) == [S(-1), S(-1), S(-1), S(-1)/3] def test_CRootOf_all_roots(): assert Poly(x**5 + x + 1).all_roots() == [ rootof(x**3 - x**2 + 1, 0), Rational(-1, 2) - sqrt(3)*I/2, Rational(-1, 2) + sqrt(3)*I/2, rootof(x**3 - x**2 + 1, 1), rootof(x**3 - x**2 + 1, 2), ] assert Poly(x**5 + x + 1).all_roots(radicals=False) == [ rootof(x**3 - x**2 + 1, 0), rootof(x**2 + x + 1, 0, radicals=False), rootof(x**2 + x + 1, 1, radicals=False), rootof(x**3 - x**2 + 1, 1), rootof(x**3 - x**2 + 1, 2), ] def test_CRootOf_eval_rational(): p = legendre_poly(4, x, polys=True) roots = [r.eval_rational(n=18) for r in p.real_roots()] for root in roots: assert isinstance(root, Rational) roots = [str(root.n(17)) for root in roots] assert roots == [ "-0.86113631159405258", "-0.33998104358485626", "0.33998104358485626", "0.86113631159405258", ] def test_RootSum___new__(): f = x**3 + x + 3 g = Lambda(r, log(r*x)) s = RootSum(f, g) assert isinstance(s, RootSum) is True assert RootSum(f**2, g) == 2*RootSum(f, g) assert RootSum((x - 7)*f**3, g) == log(7*x) + 3*RootSum(f, g) # issue 5571 assert hash(RootSum((x - 7)*f**3, g)) == hash(log(7*x) + 3*RootSum(f, g)) raises(MultivariatePolynomialError, lambda: RootSum(x**3 + x + y)) raises(ValueError, lambda: RootSum(x**2 + 3, lambda x: x)) assert RootSum(f, exp) == RootSum(f, Lambda(x, exp(x))) assert RootSum(f, log) == RootSum(f, Lambda(x, log(x))) assert isinstance(RootSum(f, auto=False), RootSum) is True assert RootSum(f) == 0 assert RootSum(f, Lambda(x, x)) == 0 assert RootSum(f, Lambda(x, x**2)) == -2 assert RootSum(f, Lambda(x, 1)) == 3 assert RootSum(f, Lambda(x, 2)) == 6 assert RootSum(f, auto=False).is_commutative is True assert RootSum(f, Lambda(x, 1/(x + x**2))) == Rational(11, 3) assert RootSum(f, Lambda(x, y/(x + x**2))) == Rational(11, 3)*y assert RootSum(x**2 - 1, Lambda(x, 3*x**2), x) == 6 assert RootSum(x**2 - y, Lambda(x, 3*x**2), x) == 6*y assert RootSum(x**2 - 1, Lambda(x, z*x**2), x) == 2*z assert RootSum(x**2 - y, Lambda(x, z*x**2), x) == 2*z*y assert RootSum( x**2 - 1, Lambda(x, exp(x)), quadratic=True) == exp(-1) + exp(1) assert RootSum(x**3 + a*x + a**3, tan, x) == \ RootSum(x**3 + x + 1, Lambda(x, tan(a*x))) assert RootSum(a**3*x**3 + a*x + 1, tan, x) == \ RootSum(x**3 + x + 1, Lambda(x, tan(x/a))) def test_RootSum_free_symbols(): assert RootSum(x**3 + x + 3, Lambda(r, exp(r))).free_symbols == set() assert RootSum(x**3 + x + 3, Lambda(r, exp(a*r))).free_symbols == {a} assert RootSum( x**3 + x + y, Lambda(r, exp(a*r)), x).free_symbols == {a, y} def test_RootSum___eq__(): f = Lambda(x, exp(x)) assert (RootSum(x**3 + x + 1, f) == RootSum(x**3 + x + 1, f)) is True assert (RootSum(x**3 + x + 1, f) == RootSum(y**3 + y + 1, f)) is True assert (RootSum(x**3 + x + 1, f) == RootSum(x**3 + x + 2, f)) is False assert (RootSum(x**3 + x + 1, f) == RootSum(y**3 + y + 2, f)) is False def test_RootSum_doit(): rs = RootSum(x**2 + 1, exp) assert isinstance(rs, RootSum) is True assert rs.doit() == exp(-I) + exp(I) rs = RootSum(x**2 + a, exp, x) assert isinstance(rs, RootSum) is True assert rs.doit() == exp(-sqrt(-a)) + exp(sqrt(-a)) def test_RootSum_evalf(): rs = RootSum(x**2 + 1, exp) assert rs.evalf(n=20, chop=True).epsilon_eq(Float("1.0806046117362794348")) assert rs.evalf(n=15, chop=True).epsilon_eq(Float("1.08060461173628")) rs = RootSum(x**2 + a, exp, x) assert rs.evalf() == rs def test_RootSum_diff(): f = x**3 + x + 3 g = Lambda(r, exp(r*x)) h = Lambda(r, r*exp(r*x)) assert RootSum(f, g).diff(x) == RootSum(f, h) def test_RootSum_subs(): f = x**3 + x + 3 g = Lambda(r, exp(r*x)) F = y**3 + y + 3 G = Lambda(r, exp(r*y)) assert RootSum(f, g).subs(y, 1) == RootSum(f, g) assert RootSum(f, g).subs(x, y) == RootSum(F, G) def test_RootSum_rational(): assert RootSum( z**5 - z + 1, Lambda(z, z/(x - z))) == (4*x - 5)/(x**5 - x + 1) f = 161*z**3 + 115*z**2 + 19*z + 1 g = Lambda(z, z*log( -3381*z**4/4 - 3381*z**3/4 - 625*z**2/2 - z*Rational(125, 2) - 5 + exp(x))) assert RootSum(f, g).diff(x) == -( (5*exp(2*x) - 6*exp(x) + 4)*exp(x)/(exp(3*x) - exp(2*x) + 1))/7 def test_RootSum_independent(): f = (x**3 - a)**2*(x**4 - b)**3 g = Lambda(x, 5*tan(x) + 7) h = Lambda(x, tan(x)) r0 = RootSum(x**3 - a, h, x) r1 = RootSum(x**4 - b, h, x) assert RootSum(f, g, x).as_ordered_terms() == [10*r0, 15*r1, 126] def test_issue_7876(): l1 = Poly(x**6 - x + 1, x).all_roots() l2 = [rootof(x**6 - x + 1, i) for i in range(6)] assert frozenset(l1) == frozenset(l2) def test_issue_8316(): f = Poly(7*x**8 - 9) assert len(f.all_roots()) == 8 f = Poly(7*x**8 - 10) assert len(f.all_roots()) == 8 def test__imag_count(): from sympy.polys.rootoftools import _imag_count_of_factor def imag_count(p): return sum([_imag_count_of_factor(f)*m for f, m in p.factor_list()[1]]) assert imag_count(Poly(x**6 + 10*x**2 + 1)) == 2 assert imag_count(Poly(x**2)) == 0 assert imag_count(Poly([1]*3 + [-1], x)) == 0 assert imag_count(Poly(x**3 + 1)) == 0 assert imag_count(Poly(x**2 + 1)) == 2 assert imag_count(Poly(x**2 - 1)) == 0 assert imag_count(Poly(x**4 - 1)) == 2 assert imag_count(Poly(x**4 + 1)) == 0 assert imag_count(Poly([1, 2, 3], x)) == 0 assert imag_count(Poly(x**3 + x + 1)) == 0 assert imag_count(Poly(x**4 + x + 1)) == 0 def q(r1, r2, p): return Poly(((x - r1)*(x - r2)).subs(x, x**p), x) assert imag_count(q(-1, -2, 2)) == 4 assert imag_count(q(-1, 2, 2)) == 2 assert imag_count(q(1, 2, 2)) == 0 assert imag_count(q(1, 2, 4)) == 4 assert imag_count(q(-1, 2, 4)) == 2 assert imag_count(q(-1, -2, 4)) == 0 def test_RootOf_is_imaginary(): r = RootOf(x**4 + 4*x**2 + 1, 1) i = r._get_interval() assert r.is_imaginary and i.ax*i.bx <= 0 def test_is_disjoint(): eq = x**3 + 5*x + 1 ir = rootof(eq, 0)._get_interval() ii = rootof(eq, 1)._get_interval() assert ir.is_disjoint(ii) assert ii.is_disjoint(ir) def test_pure_key_dict(): p = D() assert (x in p) is False assert (1 in p) is False p[x] = 1 assert x in p assert y in p assert p[y] == 1 raises(KeyError, lambda: p[1]) def dont(k): p[k] = 2 raises(ValueError, lambda: dont(1)) @slow def test_eval_approx_relative(): CRootOf.clear_cache() t = [CRootOf(x**3 + 10*x + 1, i) for i in range(3)] assert [i.eval_rational(1e-1) for i in t] == [ Rational(-21, 220), Rational(15, 256) - I*805/256, Rational(15, 256) + I*805/256] t[0]._reset() assert [i.eval_rational(1e-1, 1e-4) for i in t] == [ Rational(-21, 220), Rational(3275, 65536) - I*414645/131072, Rational(3275, 65536) + I*414645/131072] assert S(t[0]._get_interval().dx) < 1e-1 assert S(t[1]._get_interval().dx) < 1e-1 assert S(t[1]._get_interval().dy) < 1e-4 assert S(t[2]._get_interval().dx) < 1e-1 assert S(t[2]._get_interval().dy) < 1e-4 t[0]._reset() assert [i.eval_rational(1e-4, 1e-4) for i in t] == [ Rational(-2001, 20020), Rational(6545, 131072) - I*414645/131072, Rational(6545, 131072) + I*414645/131072] assert S(t[0]._get_interval().dx) < 1e-4 assert S(t[1]._get_interval().dx) < 1e-4 assert S(t[1]._get_interval().dy) < 1e-4 assert S(t[2]._get_interval().dx) < 1e-4 assert S(t[2]._get_interval().dy) < 1e-4 # in the following, the actual relative precision is # less than tested, but it should never be greater t[0]._reset() assert [i.eval_rational(n=2) for i in t] == [ Rational(-202201, 2024022), Rational(104755, 2097152) - I*6634255/2097152, Rational(104755, 2097152) + I*6634255/2097152] assert abs(S(t[0]._get_interval().dx)/t[0]) < 1e-2 assert abs(S(t[1]._get_interval().dx)/t[1]).n() < 1e-2 assert abs(S(t[1]._get_interval().dy)/t[1]).n() < 1e-2 assert abs(S(t[2]._get_interval().dx)/t[2]).n() < 1e-2 assert abs(S(t[2]._get_interval().dy)/t[2]).n() < 1e-2 t[0]._reset() assert [i.eval_rational(n=3) for i in t] == [ Rational(-202201, 2024022), Rational(1676045, 33554432) - I*106148135/33554432, Rational(1676045, 33554432) + I*106148135/33554432] assert abs(S(t[0]._get_interval().dx)/t[0]) < 1e-3 assert abs(S(t[1]._get_interval().dx)/t[1]).n() < 1e-3 assert abs(S(t[1]._get_interval().dy)/t[1]).n() < 1e-3 assert abs(S(t[2]._get_interval().dx)/t[2]).n() < 1e-3 assert abs(S(t[2]._get_interval().dy)/t[2]).n() < 1e-3 t[0]._reset() a = [i.eval_approx(2) for i in t] assert [str(i) for i in a] == [ '-0.10', '0.05 - 3.2*I', '0.05 + 3.2*I'] assert all(abs(((a[i] - t[i])/t[i]).n()) < 1e-2 for i in range(len(a))) def test_issue_15920(): r = rootof(x**5 - x + 1, 0) p = Integral(x, (x, 1, y)) assert unchanged(Eq, r, p) def test_issue_19113(): eq = y**3 - y + 1 # generator is a canonical x in RootOf assert str(Poly(eq).real_roots()) == '[CRootOf(x**3 - x + 1, 0)]' assert str(Poly(eq.subs(y, tan(y))).real_roots() ) == '[CRootOf(x**3 - x + 1, 0)]' assert str(Poly(eq.subs(y, tan(x))).real_roots() ) == '[CRootOf(x**3 - x + 1, 0)]'
0dacfdccb0e19c6c8cb68fb415f1725ecdadab88484755a8e793726c160fe27f
"""Tests for user-friendly public interface to polynomial functions. """ import pickle from sympy.polys.polytools import ( Poly, PurePoly, poly, parallel_poly_from_expr, degree, degree_list, total_degree, LC, LM, LT, pdiv, prem, pquo, pexquo, div, rem, quo, exquo, half_gcdex, gcdex, invert, subresultants, resultant, discriminant, terms_gcd, cofactors, gcd, gcd_list, lcm, lcm_list, trunc, monic, content, primitive, compose, decompose, sturm, gff_list, gff, sqf_norm, sqf_part, sqf_list, sqf, factor_list, factor, intervals, refine_root, count_roots, real_roots, nroots, ground_roots, nth_power_roots_poly, cancel, reduced, groebner, GroebnerBasis, is_zero_dimensional, _torational_factor_list, to_rational_coeffs) from sympy.polys.polyerrors import ( MultivariatePolynomialError, ExactQuotientFailed, PolificationFailed, ComputationFailed, UnificationFailed, RefinementFailed, GeneratorsNeeded, GeneratorsError, PolynomialError, CoercionFailed, DomainError, OptionError, FlagError) from sympy.polys.polyclasses import DMP from sympy.polys.fields import field from sympy.polys.domains import FF, ZZ, QQ, ZZ_I, QQ_I, RR, EX from sympy.polys.domains.realfield import RealField from sympy.polys.domains.complexfield import ComplexField from sympy.polys.orderings import lex, grlex, grevlex from sympy.core.add import Add from sympy.core.basic import _aresame from sympy.core.containers import Tuple from sympy.core.expr import Expr from sympy.core.function import (Derivative, diff, expand) from sympy.core.mul import _keep_coeff, Mul from sympy.core.numbers import (Float, I, Integer, Rational, oo, pi) from sympy.core.power import Pow from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.functions.elementary.complexes import (im, re) from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.hyperbolic import tanh from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import sin from sympy.matrices.dense import Matrix from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.polys.rootoftools import rootof from sympy.simplify.simplify import signsimp from sympy.utilities.iterables import iterable from sympy.testing.pytest import raises, warns_deprecated_sympy from sympy.abc import a, b, c, d, p, q, t, w, x, y, z def _epsilon_eq(a, b): for u, v in zip(a, b): if abs(u - v) > 1e-10: return False return True def _strict_eq(a, b): if type(a) == type(b): if iterable(a): if len(a) == len(b): return all(_strict_eq(c, d) for c, d in zip(a, b)) else: return False else: return isinstance(a, Poly) and a.eq(b, strict=True) else: return False def test_Poly_mixed_operations(): p = Poly(x, x) with warns_deprecated_sympy(): p * exp(x) with warns_deprecated_sympy(): p + exp(x) with warns_deprecated_sympy(): p - exp(x) def test_Poly_from_dict(): K = FF(3) assert Poly.from_dict( {0: 1, 1: 2}, gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_dict( {0: 1, 1: 5}, gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_dict( {(0,): 1, (1,): 2}, gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_dict( {(0,): 1, (1,): 5}, gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_dict({(0, 0): 1, (1, 1): 2}, gens=( x, y), domain=K).rep == DMP([[K(2), K(0)], [K(1)]], K) assert Poly.from_dict({0: 1, 1: 2}, gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_dict( {0: 1, 1: 2}, gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_dict( {0: 1, 1: 2}, gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_dict( {0: 1, 1: 2}, gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_dict( {(0,): 1, (1,): 2}, gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_dict( {(0,): 1, (1,): 2}, gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_dict( {(0,): 1, (1,): 2}, gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_dict( {(0,): 1, (1,): 2}, gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_dict({(1,): sin(y)}, gens=x, composite=False) == \ Poly(sin(y)*x, x, domain='EX') assert Poly.from_dict({(1,): y}, gens=x, composite=False) == \ Poly(y*x, x, domain='EX') assert Poly.from_dict({(1, 1): 1}, gens=(x, y), composite=False) == \ Poly(x*y, x, y, domain='ZZ') assert Poly.from_dict({(1, 0): y}, gens=(x, z), composite=False) == \ Poly(y*x, x, z, domain='EX') def test_Poly_from_list(): K = FF(3) assert Poly.from_list([2, 1], gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_list([5, 1], gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_list([2, 1], gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_list([2, 1], gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_list([2, 1], gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_list([2, 1], gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_list([0, 1.0], gens=x).rep == DMP([RR(1.0)], RR) assert Poly.from_list([1.0, 0], gens=x).rep == DMP([RR(1.0), RR(0.0)], RR) raises(MultivariatePolynomialError, lambda: Poly.from_list([[]], gens=(x, y))) def test_Poly_from_poly(): f = Poly(x + 7, x, domain=ZZ) g = Poly(x + 2, x, modulus=3) h = Poly(x + y, x, y, domain=ZZ) K = FF(3) assert Poly.from_poly(f) == f assert Poly.from_poly(f, domain=K).rep == DMP([K(1), K(1)], K) assert Poly.from_poly(f, domain=ZZ).rep == DMP([1, 7], ZZ) assert Poly.from_poly(f, domain=QQ).rep == DMP([1, 7], QQ) assert Poly.from_poly(f, gens=x) == f assert Poly.from_poly(f, gens=x, domain=K).rep == DMP([K(1), K(1)], K) assert Poly.from_poly(f, gens=x, domain=ZZ).rep == DMP([1, 7], ZZ) assert Poly.from_poly(f, gens=x, domain=QQ).rep == DMP([1, 7], QQ) assert Poly.from_poly(f, gens=y) == Poly(x + 7, y, domain='ZZ[x]') raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=K)) raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=ZZ)) raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=QQ)) assert Poly.from_poly(f, gens=(x, y)) == Poly(x + 7, x, y, domain='ZZ') assert Poly.from_poly( f, gens=(x, y), domain=ZZ) == Poly(x + 7, x, y, domain='ZZ') assert Poly.from_poly( f, gens=(x, y), domain=QQ) == Poly(x + 7, x, y, domain='QQ') assert Poly.from_poly( f, gens=(x, y), modulus=3) == Poly(x + 7, x, y, domain='FF(3)') K = FF(2) assert Poly.from_poly(g) == g assert Poly.from_poly(g, domain=ZZ).rep == DMP([1, -1], ZZ) raises(CoercionFailed, lambda: Poly.from_poly(g, domain=QQ)) assert Poly.from_poly(g, domain=K).rep == DMP([K(1), K(0)], K) assert Poly.from_poly(g, gens=x) == g assert Poly.from_poly(g, gens=x, domain=ZZ).rep == DMP([1, -1], ZZ) raises(CoercionFailed, lambda: Poly.from_poly(g, gens=x, domain=QQ)) assert Poly.from_poly(g, gens=x, domain=K).rep == DMP([K(1), K(0)], K) K = FF(3) assert Poly.from_poly(h) == h assert Poly.from_poly( h, domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ) assert Poly.from_poly( h, domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ) assert Poly.from_poly(h, domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K) assert Poly.from_poly(h, gens=x) == Poly(x + y, x, domain=ZZ[y]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, domain=ZZ)) assert Poly.from_poly( h, gens=x, domain=ZZ[y]) == Poly(x + y, x, domain=ZZ[y]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, domain=QQ)) assert Poly.from_poly( h, gens=x, domain=QQ[y]) == Poly(x + y, x, domain=QQ[y]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, modulus=3)) assert Poly.from_poly(h, gens=y) == Poly(x + y, y, domain=ZZ[x]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, domain=ZZ)) assert Poly.from_poly( h, gens=y, domain=ZZ[x]) == Poly(x + y, y, domain=ZZ[x]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, domain=QQ)) assert Poly.from_poly( h, gens=y, domain=QQ[x]) == Poly(x + y, y, domain=QQ[x]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, modulus=3)) assert Poly.from_poly(h, gens=(x, y)) == h assert Poly.from_poly( h, gens=(x, y), domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ) assert Poly.from_poly( h, gens=(x, y), domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ) assert Poly.from_poly( h, gens=(x, y), domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K) assert Poly.from_poly( h, gens=(y, x)).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ) assert Poly.from_poly( h, gens=(y, x), domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ) assert Poly.from_poly( h, gens=(y, x), domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ) assert Poly.from_poly( h, gens=(y, x), domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K) assert Poly.from_poly( h, gens=(x, y), field=True).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ) assert Poly.from_poly( h, gens=(x, y), field=True).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ) def test_Poly_from_expr(): raises(GeneratorsNeeded, lambda: Poly.from_expr(S.Zero)) raises(GeneratorsNeeded, lambda: Poly.from_expr(S(7))) F3 = FF(3) assert Poly.from_expr(x + 5, domain=F3).rep == DMP([F3(1), F3(2)], F3) assert Poly.from_expr(y + 5, domain=F3).rep == DMP([F3(1), F3(2)], F3) assert Poly.from_expr(x + 5, x, domain=F3).rep == DMP([F3(1), F3(2)], F3) assert Poly.from_expr(y + 5, y, domain=F3).rep == DMP([F3(1), F3(2)], F3) assert Poly.from_expr(x + y, domain=F3).rep == DMP([[F3(1)], [F3(1), F3(0)]], F3) assert Poly.from_expr(x + y, x, y, domain=F3).rep == DMP([[F3(1)], [F3(1), F3(0)]], F3) assert Poly.from_expr(x + 5).rep == DMP([1, 5], ZZ) assert Poly.from_expr(y + 5).rep == DMP([1, 5], ZZ) assert Poly.from_expr(x + 5, x).rep == DMP([1, 5], ZZ) assert Poly.from_expr(y + 5, y).rep == DMP([1, 5], ZZ) assert Poly.from_expr(x + 5, domain=ZZ).rep == DMP([1, 5], ZZ) assert Poly.from_expr(y + 5, domain=ZZ).rep == DMP([1, 5], ZZ) assert Poly.from_expr(x + 5, x, domain=ZZ).rep == DMP([1, 5], ZZ) assert Poly.from_expr(y + 5, y, domain=ZZ).rep == DMP([1, 5], ZZ) assert Poly.from_expr(x + 5, x, y, domain=ZZ).rep == DMP([[1], [5]], ZZ) assert Poly.from_expr(y + 5, x, y, domain=ZZ).rep == DMP([[1, 5]], ZZ) def test_poly_from_domain_element(): dom = ZZ[x] assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom) dom = dom.get_field() assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom) dom = QQ[x] assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom) dom = dom.get_field() assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom) dom = ZZ.old_poly_ring(x) assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom) dom = dom.get_field() assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom) dom = QQ.old_poly_ring(x) assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom) dom = dom.get_field() assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom) dom = QQ.algebraic_field(I) assert Poly(dom([1, 1]), x, domain=dom).rep == DMP([dom([1, 1])], dom) def test_Poly__new__(): raises(GeneratorsError, lambda: Poly(x + 1, x, x)) raises(GeneratorsError, lambda: Poly(x + y, x, y, domain=ZZ[x])) raises(GeneratorsError, lambda: Poly(x + y, x, y, domain=ZZ[y])) raises(OptionError, lambda: Poly(x, x, symmetric=True)) raises(OptionError, lambda: Poly(x + 2, x, modulus=3, domain=QQ)) raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, gaussian=True)) raises(OptionError, lambda: Poly(x + 2, x, modulus=3, gaussian=True)) raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, extension=[sqrt(3)])) raises(OptionError, lambda: Poly(x + 2, x, modulus=3, extension=[sqrt(3)])) raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, extension=True)) raises(OptionError, lambda: Poly(x + 2, x, modulus=3, extension=True)) raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, greedy=True)) raises(OptionError, lambda: Poly(x + 2, x, domain=QQ, field=True)) raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, greedy=False)) raises(OptionError, lambda: Poly(x + 2, x, domain=QQ, field=False)) raises(NotImplementedError, lambda: Poly(x + 1, x, modulus=3, order='grlex')) raises(NotImplementedError, lambda: Poly(x + 1, x, order='grlex')) raises(GeneratorsNeeded, lambda: Poly({1: 2, 0: 1})) raises(GeneratorsNeeded, lambda: Poly([2, 1])) raises(GeneratorsNeeded, lambda: Poly((2, 1))) raises(GeneratorsNeeded, lambda: Poly(1)) f = a*x**2 + b*x + c assert Poly({2: a, 1: b, 0: c}, x) == f assert Poly(iter([a, b, c]), x) == f assert Poly([a, b, c], x) == f assert Poly((a, b, c), x) == f f = Poly({}, x, y, z) assert f.gens == (x, y, z) and f.as_expr() == 0 assert Poly(Poly(a*x + b*y, x, y), x) == Poly(a*x + b*y, x) assert Poly(3*x**2 + 2*x + 1, domain='ZZ').all_coeffs() == [3, 2, 1] assert Poly(3*x**2 + 2*x + 1, domain='QQ').all_coeffs() == [3, 2, 1] assert Poly(3*x**2 + 2*x + 1, domain='RR').all_coeffs() == [3.0, 2.0, 1.0] raises(CoercionFailed, lambda: Poly(3*x**2/5 + x*Rational(2, 5) + 1, domain='ZZ')) assert Poly( 3*x**2/5 + x*Rational(2, 5) + 1, domain='QQ').all_coeffs() == [Rational(3, 5), Rational(2, 5), 1] assert _epsilon_eq( Poly(3*x**2/5 + x*Rational(2, 5) + 1, domain='RR').all_coeffs(), [0.6, 0.4, 1.0]) assert Poly(3.0*x**2 + 2.0*x + 1, domain='ZZ').all_coeffs() == [3, 2, 1] assert Poly(3.0*x**2 + 2.0*x + 1, domain='QQ').all_coeffs() == [3, 2, 1] assert Poly( 3.0*x**2 + 2.0*x + 1, domain='RR').all_coeffs() == [3.0, 2.0, 1.0] raises(CoercionFailed, lambda: Poly(3.1*x**2 + 2.1*x + 1, domain='ZZ')) assert Poly(3.1*x**2 + 2.1*x + 1, domain='QQ').all_coeffs() == [Rational(31, 10), Rational(21, 10), 1] assert Poly(3.1*x**2 + 2.1*x + 1, domain='RR').all_coeffs() == [3.1, 2.1, 1.0] assert Poly({(2, 1): 1, (1, 2): 2, (1, 1): 3}, x, y) == \ Poly(x**2*y + 2*x*y**2 + 3*x*y, x, y) assert Poly(x**2 + 1, extension=I).get_domain() == QQ.algebraic_field(I) f = 3*x**5 - x**4 + x**3 - x** 2 + 65538 assert Poly(f, x, modulus=65537, symmetric=True) == \ Poly(3*x**5 - x**4 + x**3 - x** 2 + 1, x, modulus=65537, symmetric=True) assert Poly(f, x, modulus=65537, symmetric=False) == \ Poly(3*x**5 + 65536*x**4 + x**3 + 65536*x** 2 + 1, x, modulus=65537, symmetric=False) assert isinstance(Poly(x**2 + x + 1.0).get_domain(), RealField) assert isinstance(Poly(x**2 + x + I + 1.0).get_domain(), ComplexField) def test_Poly__args(): assert Poly(x**2 + 1).args == (x**2 + 1, x) def test_Poly__gens(): assert Poly((x - p)*(x - q), x).gens == (x,) assert Poly((x - p)*(x - q), p).gens == (p,) assert Poly((x - p)*(x - q), q).gens == (q,) assert Poly((x - p)*(x - q), x, p).gens == (x, p) assert Poly((x - p)*(x - q), x, q).gens == (x, q) assert Poly((x - p)*(x - q), x, p, q).gens == (x, p, q) assert Poly((x - p)*(x - q), p, x, q).gens == (p, x, q) assert Poly((x - p)*(x - q), p, q, x).gens == (p, q, x) assert Poly((x - p)*(x - q)).gens == (x, p, q) assert Poly((x - p)*(x - q), sort='x > p > q').gens == (x, p, q) assert Poly((x - p)*(x - q), sort='p > x > q').gens == (p, x, q) assert Poly((x - p)*(x - q), sort='p > q > x').gens == (p, q, x) assert Poly((x - p)*(x - q), x, p, q, sort='p > q > x').gens == (x, p, q) assert Poly((x - p)*(x - q), wrt='x').gens == (x, p, q) assert Poly((x - p)*(x - q), wrt='p').gens == (p, x, q) assert Poly((x - p)*(x - q), wrt='q').gens == (q, x, p) assert Poly((x - p)*(x - q), wrt=x).gens == (x, p, q) assert Poly((x - p)*(x - q), wrt=p).gens == (p, x, q) assert Poly((x - p)*(x - q), wrt=q).gens == (q, x, p) assert Poly((x - p)*(x - q), x, p, q, wrt='p').gens == (x, p, q) assert Poly((x - p)*(x - q), wrt='p', sort='q > x').gens == (p, q, x) assert Poly((x - p)*(x - q), wrt='q', sort='p > x').gens == (q, p, x) def test_Poly_zero(): assert Poly(x).zero == Poly(0, x, domain=ZZ) assert Poly(x/2).zero == Poly(0, x, domain=QQ) def test_Poly_one(): assert Poly(x).one == Poly(1, x, domain=ZZ) assert Poly(x/2).one == Poly(1, x, domain=QQ) def test_Poly__unify(): raises(UnificationFailed, lambda: Poly(x)._unify(y)) F3 = FF(3) F5 = FF(5) assert Poly(x, x, modulus=3)._unify(Poly(y, y, modulus=3))[2:] == ( DMP([[F3(1)], []], F3), DMP([[F3(1), F3(0)]], F3)) assert Poly(x, x, modulus=3)._unify(Poly(y, y, modulus=5))[2:] == ( DMP([[F5(1)], []], F5), DMP([[F5(1), F5(0)]], F5)) assert Poly(y, x, y)._unify(Poly(x, x, modulus=3))[2:] == (DMP([[F3(1), F3(0)]], F3), DMP([[F3(1)], []], F3)) assert Poly(x, x, modulus=3)._unify(Poly(y, x, y))[2:] == (DMP([[F3(1)], []], F3), DMP([[F3(1), F3(0)]], F3)) assert Poly(x + 1, x)._unify(Poly(x + 2, x))[2:] == (DMP([1, 1], ZZ), DMP([1, 2], ZZ)) assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([1, 1], QQ), DMP([1, 2], QQ)) assert Poly(x + 1, x)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([1, 1], QQ), DMP([1, 2], QQ)) assert Poly(x + 1, x)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ)) assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, x))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ)) assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ)) assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x)._unify(Poly(x + 2, y, x))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ)) assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, y, x))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x + 1, x)._unify(Poly(x + 2, y, x, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x + 1, y, x)._unify(Poly(x + 2, x))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ)) assert Poly(x + 1, y, x, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, y, x))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ)) assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, y, x))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, y, x, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ)) assert Poly(x + 1, y, x, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x**2 + I, x, domain=ZZ_I).unify(Poly(x**2 + sqrt(2), x, extension=True)) == \ (Poly(x**2 + I, x, domain='QQ<sqrt(2) + I>'), Poly(x**2 + sqrt(2), x, domain='QQ<sqrt(2) + I>')) F, A, B = field("a,b", ZZ) assert Poly(a*x, x, domain='ZZ[a]')._unify(Poly(a*b*x, x, domain='ZZ(a,b)'))[2:] == \ (DMP([A, F(0)], F.to_domain()), DMP([A*B, F(0)], F.to_domain())) assert Poly(a*x, x, domain='ZZ(a)')._unify(Poly(a*b*x, x, domain='ZZ(a,b)'))[2:] == \ (DMP([A, F(0)], F.to_domain()), DMP([A*B, F(0)], F.to_domain())) raises(CoercionFailed, lambda: Poly(Poly(x**2 + x**2*z, y, field=True), domain='ZZ(x)')) f = Poly(t**2 + t/3 + x, t, domain='QQ(x)') g = Poly(t**2 + t/3 + x, t, domain='QQ[x]') assert f._unify(g)[2:] == (f.rep, f.rep) def test_Poly_free_symbols(): assert Poly(x**2 + 1).free_symbols == {x} assert Poly(x**2 + y*z).free_symbols == {x, y, z} assert Poly(x**2 + y*z, x).free_symbols == {x, y, z} assert Poly(x**2 + sin(y*z)).free_symbols == {x, y, z} assert Poly(x**2 + sin(y*z), x).free_symbols == {x, y, z} assert Poly(x**2 + sin(y*z), x, domain=EX).free_symbols == {x, y, z} assert Poly(1 + x + x**2, x, y, z).free_symbols == {x} assert Poly(x + sin(y), z).free_symbols == {x, y} def test_PurePoly_free_symbols(): assert PurePoly(x**2 + 1).free_symbols == set() assert PurePoly(x**2 + y*z).free_symbols == set() assert PurePoly(x**2 + y*z, x).free_symbols == {y, z} assert PurePoly(x**2 + sin(y*z)).free_symbols == set() assert PurePoly(x**2 + sin(y*z), x).free_symbols == {y, z} assert PurePoly(x**2 + sin(y*z), x, domain=EX).free_symbols == {y, z} def test_Poly__eq__(): assert (Poly(x, x) == Poly(x, x)) is True assert (Poly(x, x, domain=QQ) == Poly(x, x)) is False assert (Poly(x, x) == Poly(x, x, domain=QQ)) is False assert (Poly(x, x, domain=ZZ[a]) == Poly(x, x)) is False assert (Poly(x, x) == Poly(x, x, domain=ZZ[a])) is False assert (Poly(x*y, x, y) == Poly(x, x)) is False assert (Poly(x, x, y) == Poly(x, x)) is False assert (Poly(x, x) == Poly(x, x, y)) is False assert (Poly(x**2 + 1, x) == Poly(y**2 + 1, y)) is False assert (Poly(y**2 + 1, y) == Poly(x**2 + 1, x)) is False f = Poly(x, x, domain=ZZ) g = Poly(x, x, domain=QQ) assert f.eq(g) is False assert f.ne(g) is True assert f.eq(g, strict=True) is False assert f.ne(g, strict=True) is True t0 = Symbol('t0') f = Poly((t0/2 + x**2)*t**2 - x**2*t, t, domain='QQ[x,t0]') g = Poly((t0/2 + x**2)*t**2 - x**2*t, t, domain='ZZ(x,t0)') assert (f == g) is False def test_PurePoly__eq__(): assert (PurePoly(x, x) == PurePoly(x, x)) is True assert (PurePoly(x, x, domain=QQ) == PurePoly(x, x)) is True assert (PurePoly(x, x) == PurePoly(x, x, domain=QQ)) is True assert (PurePoly(x, x, domain=ZZ[a]) == PurePoly(x, x)) is True assert (PurePoly(x, x) == PurePoly(x, x, domain=ZZ[a])) is True assert (PurePoly(x*y, x, y) == PurePoly(x, x)) is False assert (PurePoly(x, x, y) == PurePoly(x, x)) is False assert (PurePoly(x, x) == PurePoly(x, x, y)) is False assert (PurePoly(x**2 + 1, x) == PurePoly(y**2 + 1, y)) is True assert (PurePoly(y**2 + 1, y) == PurePoly(x**2 + 1, x)) is True f = PurePoly(x, x, domain=ZZ) g = PurePoly(x, x, domain=QQ) assert f.eq(g) is True assert f.ne(g) is False assert f.eq(g, strict=True) is False assert f.ne(g, strict=True) is True f = PurePoly(x, x, domain=ZZ) g = PurePoly(y, y, domain=QQ) assert f.eq(g) is True assert f.ne(g) is False assert f.eq(g, strict=True) is False assert f.ne(g, strict=True) is True def test_PurePoly_Poly(): assert isinstance(PurePoly(Poly(x**2 + 1)), PurePoly) is True assert isinstance(Poly(PurePoly(x**2 + 1)), Poly) is True def test_Poly_get_domain(): assert Poly(2*x).get_domain() == ZZ assert Poly(2*x, domain='ZZ').get_domain() == ZZ assert Poly(2*x, domain='QQ').get_domain() == QQ assert Poly(x/2).get_domain() == QQ raises(CoercionFailed, lambda: Poly(x/2, domain='ZZ')) assert Poly(x/2, domain='QQ').get_domain() == QQ assert isinstance(Poly(0.2*x).get_domain(), RealField) def test_Poly_set_domain(): assert Poly(2*x + 1).set_domain(ZZ) == Poly(2*x + 1) assert Poly(2*x + 1).set_domain('ZZ') == Poly(2*x + 1) assert Poly(2*x + 1).set_domain(QQ) == Poly(2*x + 1, domain='QQ') assert Poly(2*x + 1).set_domain('QQ') == Poly(2*x + 1, domain='QQ') assert Poly(Rational(2, 10)*x + Rational(1, 10)).set_domain('RR') == Poly(0.2*x + 0.1) assert Poly(0.2*x + 0.1).set_domain('QQ') == Poly(Rational(2, 10)*x + Rational(1, 10)) raises(CoercionFailed, lambda: Poly(x/2 + 1).set_domain(ZZ)) raises(CoercionFailed, lambda: Poly(x + 1, modulus=2).set_domain(QQ)) raises(GeneratorsError, lambda: Poly(x*y, x, y).set_domain(ZZ[y])) def test_Poly_get_modulus(): assert Poly(x**2 + 1, modulus=2).get_modulus() == 2 raises(PolynomialError, lambda: Poly(x**2 + 1).get_modulus()) def test_Poly_set_modulus(): assert Poly( x**2 + 1, modulus=2).set_modulus(7) == Poly(x**2 + 1, modulus=7) assert Poly( x**2 + 5, modulus=7).set_modulus(2) == Poly(x**2 + 1, modulus=2) assert Poly(x**2 + 1).set_modulus(2) == Poly(x**2 + 1, modulus=2) raises(CoercionFailed, lambda: Poly(x/2 + 1).set_modulus(2)) def test_Poly_add_ground(): assert Poly(x + 1).add_ground(2) == Poly(x + 3) def test_Poly_sub_ground(): assert Poly(x + 1).sub_ground(2) == Poly(x - 1) def test_Poly_mul_ground(): assert Poly(x + 1).mul_ground(2) == Poly(2*x + 2) def test_Poly_quo_ground(): assert Poly(2*x + 4).quo_ground(2) == Poly(x + 2) assert Poly(2*x + 3).quo_ground(2) == Poly(x + 1) def test_Poly_exquo_ground(): assert Poly(2*x + 4).exquo_ground(2) == Poly(x + 2) raises(ExactQuotientFailed, lambda: Poly(2*x + 3).exquo_ground(2)) def test_Poly_abs(): assert Poly(-x + 1, x).abs() == abs(Poly(-x + 1, x)) == Poly(x + 1, x) def test_Poly_neg(): assert Poly(-x + 1, x).neg() == -Poly(-x + 1, x) == Poly(x - 1, x) def test_Poly_add(): assert Poly(0, x).add(Poly(0, x)) == Poly(0, x) assert Poly(0, x) + Poly(0, x) == Poly(0, x) assert Poly(1, x).add(Poly(0, x)) == Poly(1, x) assert Poly(1, x, y) + Poly(0, x) == Poly(1, x, y) assert Poly(0, x).add(Poly(1, x, y)) == Poly(1, x, y) assert Poly(0, x, y) + Poly(1, x, y) == Poly(1, x, y) assert Poly(1, x) + x == Poly(x + 1, x) with warns_deprecated_sympy(): Poly(1, x) + sin(x) assert Poly(x, x) + 1 == Poly(x + 1, x) assert 1 + Poly(x, x) == Poly(x + 1, x) def test_Poly_sub(): assert Poly(0, x).sub(Poly(0, x)) == Poly(0, x) assert Poly(0, x) - Poly(0, x) == Poly(0, x) assert Poly(1, x).sub(Poly(0, x)) == Poly(1, x) assert Poly(1, x, y) - Poly(0, x) == Poly(1, x, y) assert Poly(0, x).sub(Poly(1, x, y)) == Poly(-1, x, y) assert Poly(0, x, y) - Poly(1, x, y) == Poly(-1, x, y) assert Poly(1, x) - x == Poly(1 - x, x) with warns_deprecated_sympy(): Poly(1, x) - sin(x) assert Poly(x, x) - 1 == Poly(x - 1, x) assert 1 - Poly(x, x) == Poly(1 - x, x) def test_Poly_mul(): assert Poly(0, x).mul(Poly(0, x)) == Poly(0, x) assert Poly(0, x) * Poly(0, x) == Poly(0, x) assert Poly(2, x).mul(Poly(4, x)) == Poly(8, x) assert Poly(2, x, y) * Poly(4, x) == Poly(8, x, y) assert Poly(4, x).mul(Poly(2, x, y)) == Poly(8, x, y) assert Poly(4, x, y) * Poly(2, x, y) == Poly(8, x, y) assert Poly(1, x) * x == Poly(x, x) with warns_deprecated_sympy(): Poly(1, x) * sin(x) assert Poly(x, x) * 2 == Poly(2*x, x) assert 2 * Poly(x, x) == Poly(2*x, x) def test_issue_13079(): assert Poly(x)*x == Poly(x**2, x, domain='ZZ') assert x*Poly(x) == Poly(x**2, x, domain='ZZ') assert -2*Poly(x) == Poly(-2*x, x, domain='ZZ') assert S(-2)*Poly(x) == Poly(-2*x, x, domain='ZZ') assert Poly(x)*S(-2) == Poly(-2*x, x, domain='ZZ') def test_Poly_sqr(): assert Poly(x*y, x, y).sqr() == Poly(x**2*y**2, x, y) def test_Poly_pow(): assert Poly(x, x).pow(10) == Poly(x**10, x) assert Poly(x, x).pow(Integer(10)) == Poly(x**10, x) assert Poly(2*y, x, y).pow(4) == Poly(16*y**4, x, y) assert Poly(2*y, x, y).pow(Integer(4)) == Poly(16*y**4, x, y) assert Poly(7*x*y, x, y)**3 == Poly(343*x**3*y**3, x, y) raises(TypeError, lambda: Poly(x*y + 1, x, y)**(-1)) raises(TypeError, lambda: Poly(x*y + 1, x, y)**x) def test_Poly_divmod(): f, g = Poly(x**2), Poly(x) q, r = g, Poly(0, x) assert divmod(f, g) == (q, r) assert f // g == q assert f % g == r assert divmod(f, x) == (q, r) assert f // x == q assert f % x == r q, r = Poly(0, x), Poly(2, x) assert divmod(2, g) == (q, r) assert 2 // g == q assert 2 % g == r assert Poly(x)/Poly(x) == 1 assert Poly(x**2)/Poly(x) == x assert Poly(x)/Poly(x**2) == 1/x def test_Poly_eq_ne(): assert (Poly(x + y, x, y) == Poly(x + y, x, y)) is True assert (Poly(x + y, x) == Poly(x + y, x, y)) is False assert (Poly(x + y, x, y) == Poly(x + y, x)) is False assert (Poly(x + y, x) == Poly(x + y, x)) is True assert (Poly(x + y, y) == Poly(x + y, y)) is True assert (Poly(x + y, x, y) == x + y) is True assert (Poly(x + y, x) == x + y) is True assert (Poly(x + y, x, y) == x + y) is True assert (Poly(x + y, x) == x + y) is True assert (Poly(x + y, y) == x + y) is True assert (Poly(x + y, x, y) != Poly(x + y, x, y)) is False assert (Poly(x + y, x) != Poly(x + y, x, y)) is True assert (Poly(x + y, x, y) != Poly(x + y, x)) is True assert (Poly(x + y, x) != Poly(x + y, x)) is False assert (Poly(x + y, y) != Poly(x + y, y)) is False assert (Poly(x + y, x, y) != x + y) is False assert (Poly(x + y, x) != x + y) is False assert (Poly(x + y, x, y) != x + y) is False assert (Poly(x + y, x) != x + y) is False assert (Poly(x + y, y) != x + y) is False assert (Poly(x, x) == sin(x)) is False assert (Poly(x, x) != sin(x)) is True def test_Poly_nonzero(): assert not bool(Poly(0, x)) is True assert not bool(Poly(1, x)) is False def test_Poly_properties(): assert Poly(0, x).is_zero is True assert Poly(1, x).is_zero is False assert Poly(1, x).is_one is True assert Poly(2, x).is_one is False assert Poly(x - 1, x).is_sqf is True assert Poly((x - 1)**2, x).is_sqf is False assert Poly(x - 1, x).is_monic is True assert Poly(2*x - 1, x).is_monic is False assert Poly(3*x + 2, x).is_primitive is True assert Poly(4*x + 2, x).is_primitive is False assert Poly(1, x).is_ground is True assert Poly(x, x).is_ground is False assert Poly(x + y + z + 1).is_linear is True assert Poly(x*y*z + 1).is_linear is False assert Poly(x*y + z + 1).is_quadratic is True assert Poly(x*y*z + 1).is_quadratic is False assert Poly(x*y).is_monomial is True assert Poly(x*y + 1).is_monomial is False assert Poly(x**2 + x*y).is_homogeneous is True assert Poly(x**3 + x*y).is_homogeneous is False assert Poly(x).is_univariate is True assert Poly(x*y).is_univariate is False assert Poly(x*y).is_multivariate is True assert Poly(x).is_multivariate is False assert Poly( x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1).is_cyclotomic is False assert Poly( x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1).is_cyclotomic is True def test_Poly_is_irreducible(): assert Poly(x**2 + x + 1).is_irreducible is True assert Poly(x**2 + 2*x + 1).is_irreducible is False assert Poly(7*x + 3, modulus=11).is_irreducible is True assert Poly(7*x**2 + 3*x + 1, modulus=11).is_irreducible is False def test_Poly_subs(): assert Poly(x + 1).subs(x, 0) == 1 assert Poly(x + 1).subs(x, x) == Poly(x + 1) assert Poly(x + 1).subs(x, y) == Poly(y + 1) assert Poly(x*y, x).subs(y, x) == x**2 assert Poly(x*y, x).subs(x, y) == y**2 def test_Poly_replace(): assert Poly(x + 1).replace(x) == Poly(x + 1) assert Poly(x + 1).replace(y) == Poly(y + 1) raises(PolynomialError, lambda: Poly(x + y).replace(z)) assert Poly(x + 1).replace(x, x) == Poly(x + 1) assert Poly(x + 1).replace(x, y) == Poly(y + 1) assert Poly(x + y).replace(x, x) == Poly(x + y) assert Poly(x + y).replace(x, z) == Poly(z + y, z, y) assert Poly(x + y).replace(y, y) == Poly(x + y) assert Poly(x + y).replace(y, z) == Poly(x + z, x, z) assert Poly(x + y).replace(z, t) == Poly(x + y) raises(PolynomialError, lambda: Poly(x + y).replace(x, y)) assert Poly(x + y, x).replace(x, z) == Poly(z + y, z) assert Poly(x + y, y).replace(y, z) == Poly(x + z, z) raises(PolynomialError, lambda: Poly(x + y, x).replace(x, y)) raises(PolynomialError, lambda: Poly(x + y, y).replace(y, x)) def test_Poly_reorder(): raises(PolynomialError, lambda: Poly(x + y).reorder(x, z)) assert Poly(x + y, x, y).reorder(x, y) == Poly(x + y, x, y) assert Poly(x + y, x, y).reorder(y, x) == Poly(x + y, y, x) assert Poly(x + y, y, x).reorder(x, y) == Poly(x + y, x, y) assert Poly(x + y, y, x).reorder(y, x) == Poly(x + y, y, x) assert Poly(x + y, x, y).reorder(wrt=x) == Poly(x + y, x, y) assert Poly(x + y, x, y).reorder(wrt=y) == Poly(x + y, y, x) def test_Poly_ltrim(): f = Poly(y**2 + y*z**2, x, y, z).ltrim(y) assert f.as_expr() == y**2 + y*z**2 and f.gens == (y, z) assert Poly(x*y - x, z, x, y).ltrim(1) == Poly(x*y - x, x, y) raises(PolynomialError, lambda: Poly(x*y**2 + y**2, x, y).ltrim(y)) raises(PolynomialError, lambda: Poly(x*y - x, x, y).ltrim(-1)) def test_Poly_has_only_gens(): assert Poly(x*y + 1, x, y, z).has_only_gens(x, y) is True assert Poly(x*y + z, x, y, z).has_only_gens(x, y) is False raises(GeneratorsError, lambda: Poly(x*y**2 + y**2, x, y).has_only_gens(t)) def test_Poly_to_ring(): assert Poly(2*x + 1, domain='ZZ').to_ring() == Poly(2*x + 1, domain='ZZ') assert Poly(2*x + 1, domain='QQ').to_ring() == Poly(2*x + 1, domain='ZZ') raises(CoercionFailed, lambda: Poly(x/2 + 1).to_ring()) raises(DomainError, lambda: Poly(2*x + 1, modulus=3).to_ring()) def test_Poly_to_field(): assert Poly(2*x + 1, domain='ZZ').to_field() == Poly(2*x + 1, domain='QQ') assert Poly(2*x + 1, domain='QQ').to_field() == Poly(2*x + 1, domain='QQ') assert Poly(x/2 + 1, domain='QQ').to_field() == Poly(x/2 + 1, domain='QQ') assert Poly(2*x + 1, modulus=3).to_field() == Poly(2*x + 1, modulus=3) assert Poly(2.0*x + 1.0).to_field() == Poly(2.0*x + 1.0) def test_Poly_to_exact(): assert Poly(2*x).to_exact() == Poly(2*x) assert Poly(x/2).to_exact() == Poly(x/2) assert Poly(0.1*x).to_exact() == Poly(x/10) def test_Poly_retract(): f = Poly(x**2 + 1, x, domain=QQ[y]) assert f.retract() == Poly(x**2 + 1, x, domain='ZZ') assert f.retract(field=True) == Poly(x**2 + 1, x, domain='QQ') assert Poly(0, x, y).retract() == Poly(0, x, y) def test_Poly_slice(): f = Poly(x**3 + 2*x**2 + 3*x + 4) assert f.slice(0, 0) == Poly(0, x) assert f.slice(0, 1) == Poly(4, x) assert f.slice(0, 2) == Poly(3*x + 4, x) assert f.slice(0, 3) == Poly(2*x**2 + 3*x + 4, x) assert f.slice(0, 4) == Poly(x**3 + 2*x**2 + 3*x + 4, x) assert f.slice(x, 0, 0) == Poly(0, x) assert f.slice(x, 0, 1) == Poly(4, x) assert f.slice(x, 0, 2) == Poly(3*x + 4, x) assert f.slice(x, 0, 3) == Poly(2*x**2 + 3*x + 4, x) assert f.slice(x, 0, 4) == Poly(x**3 + 2*x**2 + 3*x + 4, x) def test_Poly_coeffs(): assert Poly(0, x).coeffs() == [0] assert Poly(1, x).coeffs() == [1] assert Poly(2*x + 1, x).coeffs() == [2, 1] assert Poly(7*x**2 + 2*x + 1, x).coeffs() == [7, 2, 1] assert Poly(7*x**4 + 2*x + 1, x).coeffs() == [7, 2, 1] assert Poly(x*y**7 + 2*x**2*y**3).coeffs('lex') == [2, 1] assert Poly(x*y**7 + 2*x**2*y**3).coeffs('grlex') == [1, 2] def test_Poly_monoms(): assert Poly(0, x).monoms() == [(0,)] assert Poly(1, x).monoms() == [(0,)] assert Poly(2*x + 1, x).monoms() == [(1,), (0,)] assert Poly(7*x**2 + 2*x + 1, x).monoms() == [(2,), (1,), (0,)] assert Poly(7*x**4 + 2*x + 1, x).monoms() == [(4,), (1,), (0,)] assert Poly(x*y**7 + 2*x**2*y**3).monoms('lex') == [(2, 3), (1, 7)] assert Poly(x*y**7 + 2*x**2*y**3).monoms('grlex') == [(1, 7), (2, 3)] def test_Poly_terms(): assert Poly(0, x).terms() == [((0,), 0)] assert Poly(1, x).terms() == [((0,), 1)] assert Poly(2*x + 1, x).terms() == [((1,), 2), ((0,), 1)] assert Poly(7*x**2 + 2*x + 1, x).terms() == [((2,), 7), ((1,), 2), ((0,), 1)] assert Poly(7*x**4 + 2*x + 1, x).terms() == [((4,), 7), ((1,), 2), ((0,), 1)] assert Poly( x*y**7 + 2*x**2*y**3).terms('lex') == [((2, 3), 2), ((1, 7), 1)] assert Poly( x*y**7 + 2*x**2*y**3).terms('grlex') == [((1, 7), 1), ((2, 3), 2)] def test_Poly_all_coeffs(): assert Poly(0, x).all_coeffs() == [0] assert Poly(1, x).all_coeffs() == [1] assert Poly(2*x + 1, x).all_coeffs() == [2, 1] assert Poly(7*x**2 + 2*x + 1, x).all_coeffs() == [7, 2, 1] assert Poly(7*x**4 + 2*x + 1, x).all_coeffs() == [7, 0, 0, 2, 1] def test_Poly_all_monoms(): assert Poly(0, x).all_monoms() == [(0,)] assert Poly(1, x).all_monoms() == [(0,)] assert Poly(2*x + 1, x).all_monoms() == [(1,), (0,)] assert Poly(7*x**2 + 2*x + 1, x).all_monoms() == [(2,), (1,), (0,)] assert Poly(7*x**4 + 2*x + 1, x).all_monoms() == [(4,), (3,), (2,), (1,), (0,)] def test_Poly_all_terms(): assert Poly(0, x).all_terms() == [((0,), 0)] assert Poly(1, x).all_terms() == [((0,), 1)] assert Poly(2*x + 1, x).all_terms() == [((1,), 2), ((0,), 1)] assert Poly(7*x**2 + 2*x + 1, x).all_terms() == \ [((2,), 7), ((1,), 2), ((0,), 1)] assert Poly(7*x**4 + 2*x + 1, x).all_terms() == \ [((4,), 7), ((3,), 0), ((2,), 0), ((1,), 2), ((0,), 1)] def test_Poly_termwise(): f = Poly(x**2 + 20*x + 400) g = Poly(x**2 + 2*x + 4) def func(monom, coeff): (k,) = monom return coeff//10**(2 - k) assert f.termwise(func) == g def func(monom, coeff): (k,) = monom return (k,), coeff//10**(2 - k) assert f.termwise(func) == g def test_Poly_length(): assert Poly(0, x).length() == 0 assert Poly(1, x).length() == 1 assert Poly(x, x).length() == 1 assert Poly(x + 1, x).length() == 2 assert Poly(x**2 + 1, x).length() == 2 assert Poly(x**2 + x + 1, x).length() == 3 def test_Poly_as_dict(): assert Poly(0, x).as_dict() == {} assert Poly(0, x, y, z).as_dict() == {} assert Poly(1, x).as_dict() == {(0,): 1} assert Poly(1, x, y, z).as_dict() == {(0, 0, 0): 1} assert Poly(x**2 + 3, x).as_dict() == {(2,): 1, (0,): 3} assert Poly(x**2 + 3, x, y, z).as_dict() == {(2, 0, 0): 1, (0, 0, 0): 3} assert Poly(3*x**2*y*z**3 + 4*x*y + 5*x*z).as_dict() == {(2, 1, 3): 3, (1, 1, 0): 4, (1, 0, 1): 5} def test_Poly_as_expr(): assert Poly(0, x).as_expr() == 0 assert Poly(0, x, y, z).as_expr() == 0 assert Poly(1, x).as_expr() == 1 assert Poly(1, x, y, z).as_expr() == 1 assert Poly(x**2 + 3, x).as_expr() == x**2 + 3 assert Poly(x**2 + 3, x, y, z).as_expr() == x**2 + 3 assert Poly( 3*x**2*y*z**3 + 4*x*y + 5*x*z).as_expr() == 3*x**2*y*z**3 + 4*x*y + 5*x*z f = Poly(x**2 + 2*x*y**2 - y, x, y) assert f.as_expr() == -y + x**2 + 2*x*y**2 assert f.as_expr({x: 5}) == 25 - y + 10*y**2 assert f.as_expr({y: 6}) == -6 + 72*x + x**2 assert f.as_expr({x: 5, y: 6}) == 379 assert f.as_expr(5, 6) == 379 raises(GeneratorsError, lambda: f.as_expr({z: 7})) def test_Poly_lift(): assert Poly(x**4 - I*x + 17*I, x, gaussian=True).lift() == \ Poly(x**16 + 2*x**10 + 578*x**8 + x**4 - 578*x**2 + 83521, x, domain='QQ') def test_Poly_deflate(): assert Poly(0, x).deflate() == ((1,), Poly(0, x)) assert Poly(1, x).deflate() == ((1,), Poly(1, x)) assert Poly(x, x).deflate() == ((1,), Poly(x, x)) assert Poly(x**2, x).deflate() == ((2,), Poly(x, x)) assert Poly(x**17, x).deflate() == ((17,), Poly(x, x)) assert Poly( x**2*y*z**11 + x**4*z**11).deflate() == ((2, 1, 11), Poly(x*y*z + x**2*z)) def test_Poly_inject(): f = Poly(x**2*y + x*y**3 + x*y + 1, x) assert f.inject() == Poly(x**2*y + x*y**3 + x*y + 1, x, y) assert f.inject(front=True) == Poly(y**3*x + y*x**2 + y*x + 1, y, x) def test_Poly_eject(): f = Poly(x**2*y + x*y**3 + x*y + 1, x, y) assert f.eject(x) == Poly(x*y**3 + (x**2 + x)*y + 1, y, domain='ZZ[x]') assert f.eject(y) == Poly(y*x**2 + (y**3 + y)*x + 1, x, domain='ZZ[y]') ex = x + y + z + t + w g = Poly(ex, x, y, z, t, w) assert g.eject(x) == Poly(ex, y, z, t, w, domain='ZZ[x]') assert g.eject(x, y) == Poly(ex, z, t, w, domain='ZZ[x, y]') assert g.eject(x, y, z) == Poly(ex, t, w, domain='ZZ[x, y, z]') assert g.eject(w) == Poly(ex, x, y, z, t, domain='ZZ[w]') assert g.eject(t, w) == Poly(ex, x, y, z, domain='ZZ[t, w]') assert g.eject(z, t, w) == Poly(ex, x, y, domain='ZZ[z, t, w]') raises(DomainError, lambda: Poly(x*y, x, y, domain=ZZ[z]).eject(y)) raises(NotImplementedError, lambda: Poly(x*y, x, y, z).eject(y)) def test_Poly_exclude(): assert Poly(x, x, y).exclude() == Poly(x, x) assert Poly(x*y, x, y).exclude() == Poly(x*y, x, y) assert Poly(1, x, y).exclude() == Poly(1, x, y) def test_Poly__gen_to_level(): assert Poly(1, x, y)._gen_to_level(-2) == 0 assert Poly(1, x, y)._gen_to_level(-1) == 1 assert Poly(1, x, y)._gen_to_level( 0) == 0 assert Poly(1, x, y)._gen_to_level( 1) == 1 raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level(-3)) raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level( 2)) assert Poly(1, x, y)._gen_to_level(x) == 0 assert Poly(1, x, y)._gen_to_level(y) == 1 assert Poly(1, x, y)._gen_to_level('x') == 0 assert Poly(1, x, y)._gen_to_level('y') == 1 raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level(z)) raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level('z')) def test_Poly_degree(): assert Poly(0, x).degree() is -oo assert Poly(1, x).degree() == 0 assert Poly(x, x).degree() == 1 assert Poly(0, x).degree(gen=0) is -oo assert Poly(1, x).degree(gen=0) == 0 assert Poly(x, x).degree(gen=0) == 1 assert Poly(0, x).degree(gen=x) is -oo assert Poly(1, x).degree(gen=x) == 0 assert Poly(x, x).degree(gen=x) == 1 assert Poly(0, x).degree(gen='x') is -oo assert Poly(1, x).degree(gen='x') == 0 assert Poly(x, x).degree(gen='x') == 1 raises(PolynomialError, lambda: Poly(1, x).degree(gen=1)) raises(PolynomialError, lambda: Poly(1, x).degree(gen=y)) raises(PolynomialError, lambda: Poly(1, x).degree(gen='y')) assert Poly(1, x, y).degree() == 0 assert Poly(2*y, x, y).degree() == 0 assert Poly(x*y, x, y).degree() == 1 assert Poly(1, x, y).degree(gen=x) == 0 assert Poly(2*y, x, y).degree(gen=x) == 0 assert Poly(x*y, x, y).degree(gen=x) == 1 assert Poly(1, x, y).degree(gen=y) == 0 assert Poly(2*y, x, y).degree(gen=y) == 1 assert Poly(x*y, x, y).degree(gen=y) == 1 assert degree(0, x) is -oo assert degree(1, x) == 0 assert degree(x, x) == 1 assert degree(x*y**2, x) == 1 assert degree(x*y**2, y) == 2 assert degree(x*y**2, z) == 0 assert degree(pi) == 1 raises(TypeError, lambda: degree(y**2 + x**3)) raises(TypeError, lambda: degree(y**2 + x**3, 1)) raises(PolynomialError, lambda: degree(x, 1.1)) raises(PolynomialError, lambda: degree(x**2/(x**3 + 1), x)) assert degree(Poly(0,x),z) is -oo assert degree(Poly(1,x),z) == 0 assert degree(Poly(x**2+y**3,y)) == 3 assert degree(Poly(y**2 + x**3, y, x), 1) == 3 assert degree(Poly(y**2 + x**3, x), z) == 0 assert degree(Poly(y**2 + x**3 + z**4, x), z) == 4 def test_Poly_degree_list(): assert Poly(0, x).degree_list() == (-oo,) assert Poly(0, x, y).degree_list() == (-oo, -oo) assert Poly(0, x, y, z).degree_list() == (-oo, -oo, -oo) assert Poly(1, x).degree_list() == (0,) assert Poly(1, x, y).degree_list() == (0, 0) assert Poly(1, x, y, z).degree_list() == (0, 0, 0) assert Poly(x**2*y + x**3*z**2 + 1).degree_list() == (3, 1, 2) assert degree_list(1, x) == (0,) assert degree_list(x, x) == (1,) assert degree_list(x*y**2) == (1, 2) raises(ComputationFailed, lambda: degree_list(1)) def test_Poly_total_degree(): assert Poly(x**2*y + x**3*z**2 + 1).total_degree() == 5 assert Poly(x**2 + z**3).total_degree() == 3 assert Poly(x*y*z + z**4).total_degree() == 4 assert Poly(x**3 + x + 1).total_degree() == 3 assert total_degree(x*y + z**3) == 3 assert total_degree(x*y + z**3, x, y) == 2 assert total_degree(1) == 0 assert total_degree(Poly(y**2 + x**3 + z**4)) == 4 assert total_degree(Poly(y**2 + x**3 + z**4, x)) == 3 assert total_degree(Poly(y**2 + x**3 + z**4, x), z) == 4 assert total_degree(Poly(x**9 + x*z*y + x**3*z**2 + z**7,x), z) == 7 def test_Poly_homogenize(): assert Poly(x**2+y).homogenize(z) == Poly(x**2+y*z) assert Poly(x+y).homogenize(z) == Poly(x+y, x, y, z) assert Poly(x+y**2).homogenize(y) == Poly(x*y+y**2) def test_Poly_homogeneous_order(): assert Poly(0, x, y).homogeneous_order() is -oo assert Poly(1, x, y).homogeneous_order() == 0 assert Poly(x, x, y).homogeneous_order() == 1 assert Poly(x*y, x, y).homogeneous_order() == 2 assert Poly(x + 1, x, y).homogeneous_order() is None assert Poly(x*y + x, x, y).homogeneous_order() is None assert Poly(x**5 + 2*x**3*y**2 + 9*x*y**4).homogeneous_order() == 5 assert Poly(x**5 + 2*x**3*y**3 + 9*x*y**4).homogeneous_order() is None def test_Poly_LC(): assert Poly(0, x).LC() == 0 assert Poly(1, x).LC() == 1 assert Poly(2*x**2 + x, x).LC() == 2 assert Poly(x*y**7 + 2*x**2*y**3).LC('lex') == 2 assert Poly(x*y**7 + 2*x**2*y**3).LC('grlex') == 1 assert LC(x*y**7 + 2*x**2*y**3, order='lex') == 2 assert LC(x*y**7 + 2*x**2*y**3, order='grlex') == 1 def test_Poly_TC(): assert Poly(0, x).TC() == 0 assert Poly(1, x).TC() == 1 assert Poly(2*x**2 + x, x).TC() == 0 def test_Poly_EC(): assert Poly(0, x).EC() == 0 assert Poly(1, x).EC() == 1 assert Poly(2*x**2 + x, x).EC() == 1 assert Poly(x*y**7 + 2*x**2*y**3).EC('lex') == 1 assert Poly(x*y**7 + 2*x**2*y**3).EC('grlex') == 2 def test_Poly_coeff(): assert Poly(0, x).coeff_monomial(1) == 0 assert Poly(0, x).coeff_monomial(x) == 0 assert Poly(1, x).coeff_monomial(1) == 1 assert Poly(1, x).coeff_monomial(x) == 0 assert Poly(x**8, x).coeff_monomial(1) == 0 assert Poly(x**8, x).coeff_monomial(x**7) == 0 assert Poly(x**8, x).coeff_monomial(x**8) == 1 assert Poly(x**8, x).coeff_monomial(x**9) == 0 assert Poly(3*x*y**2 + 1, x, y).coeff_monomial(1) == 1 assert Poly(3*x*y**2 + 1, x, y).coeff_monomial(x*y**2) == 3 p = Poly(24*x*y*exp(8) + 23*x, x, y) assert p.coeff_monomial(x) == 23 assert p.coeff_monomial(y) == 0 assert p.coeff_monomial(x*y) == 24*exp(8) assert p.as_expr().coeff(x) == 24*y*exp(8) + 23 raises(NotImplementedError, lambda: p.coeff(x)) raises(ValueError, lambda: Poly(x + 1).coeff_monomial(0)) raises(ValueError, lambda: Poly(x + 1).coeff_monomial(3*x)) raises(ValueError, lambda: Poly(x + 1).coeff_monomial(3*x*y)) def test_Poly_nth(): assert Poly(0, x).nth(0) == 0 assert Poly(0, x).nth(1) == 0 assert Poly(1, x).nth(0) == 1 assert Poly(1, x).nth(1) == 0 assert Poly(x**8, x).nth(0) == 0 assert Poly(x**8, x).nth(7) == 0 assert Poly(x**8, x).nth(8) == 1 assert Poly(x**8, x).nth(9) == 0 assert Poly(3*x*y**2 + 1, x, y).nth(0, 0) == 1 assert Poly(3*x*y**2 + 1, x, y).nth(1, 2) == 3 raises(ValueError, lambda: Poly(x*y + 1, x, y).nth(1)) def test_Poly_LM(): assert Poly(0, x).LM() == (0,) assert Poly(1, x).LM() == (0,) assert Poly(2*x**2 + x, x).LM() == (2,) assert Poly(x*y**7 + 2*x**2*y**3).LM('lex') == (2, 3) assert Poly(x*y**7 + 2*x**2*y**3).LM('grlex') == (1, 7) assert LM(x*y**7 + 2*x**2*y**3, order='lex') == x**2*y**3 assert LM(x*y**7 + 2*x**2*y**3, order='grlex') == x*y**7 def test_Poly_LM_custom_order(): f = Poly(x**2*y**3*z + x**2*y*z**3 + x*y*z + 1) rev_lex = lambda monom: tuple(reversed(monom)) assert f.LM(order='lex') == (2, 3, 1) assert f.LM(order=rev_lex) == (2, 1, 3) def test_Poly_EM(): assert Poly(0, x).EM() == (0,) assert Poly(1, x).EM() == (0,) assert Poly(2*x**2 + x, x).EM() == (1,) assert Poly(x*y**7 + 2*x**2*y**3).EM('lex') == (1, 7) assert Poly(x*y**7 + 2*x**2*y**3).EM('grlex') == (2, 3) def test_Poly_LT(): assert Poly(0, x).LT() == ((0,), 0) assert Poly(1, x).LT() == ((0,), 1) assert Poly(2*x**2 + x, x).LT() == ((2,), 2) assert Poly(x*y**7 + 2*x**2*y**3).LT('lex') == ((2, 3), 2) assert Poly(x*y**7 + 2*x**2*y**3).LT('grlex') == ((1, 7), 1) assert LT(x*y**7 + 2*x**2*y**3, order='lex') == 2*x**2*y**3 assert LT(x*y**7 + 2*x**2*y**3, order='grlex') == x*y**7 def test_Poly_ET(): assert Poly(0, x).ET() == ((0,), 0) assert Poly(1, x).ET() == ((0,), 1) assert Poly(2*x**2 + x, x).ET() == ((1,), 1) assert Poly(x*y**7 + 2*x**2*y**3).ET('lex') == ((1, 7), 1) assert Poly(x*y**7 + 2*x**2*y**3).ET('grlex') == ((2, 3), 2) def test_Poly_max_norm(): assert Poly(-1, x).max_norm() == 1 assert Poly( 0, x).max_norm() == 0 assert Poly( 1, x).max_norm() == 1 def test_Poly_l1_norm(): assert Poly(-1, x).l1_norm() == 1 assert Poly( 0, x).l1_norm() == 0 assert Poly( 1, x).l1_norm() == 1 def test_Poly_clear_denoms(): coeff, poly = Poly(x + 2, x).clear_denoms() assert coeff == 1 and poly == Poly( x + 2, x, domain='ZZ') and poly.get_domain() == ZZ coeff, poly = Poly(x/2 + 1, x).clear_denoms() assert coeff == 2 and poly == Poly( x + 2, x, domain='QQ') and poly.get_domain() == QQ coeff, poly = Poly(x/2 + 1, x).clear_denoms(convert=True) assert coeff == 2 and poly == Poly( x + 2, x, domain='ZZ') and poly.get_domain() == ZZ coeff, poly = Poly(x/y + 1, x).clear_denoms(convert=True) assert coeff == y and poly == Poly( x + y, x, domain='ZZ[y]') and poly.get_domain() == ZZ[y] coeff, poly = Poly(x/3 + sqrt(2), x, domain='EX').clear_denoms() assert coeff == 3 and poly == Poly( x + 3*sqrt(2), x, domain='EX') and poly.get_domain() == EX coeff, poly = Poly( x/3 + sqrt(2), x, domain='EX').clear_denoms(convert=True) assert coeff == 3 and poly == Poly( x + 3*sqrt(2), x, domain='EX') and poly.get_domain() == EX def test_Poly_rat_clear_denoms(): f = Poly(x**2/y + 1, x) g = Poly(x**3 + y, x) assert f.rat_clear_denoms(g) == \ (Poly(x**2 + y, x), Poly(y*x**3 + y**2, x)) f = f.set_domain(EX) g = g.set_domain(EX) assert f.rat_clear_denoms(g) == (f, g) def test_issue_20427(): f = Poly(-117968192370600*18**(S(1)/3)/(217603955769048*(24201 + 253*sqrt(9165))**(S(1)/3) + 2273005839412*sqrt(9165)*(24201 + 253*sqrt(9165))**(S(1)/3)) - 15720318185*2**(S(2)/3)*3**(S(1)/3)*(24201 + 253*sqrt(9165))**(S(2)/3)/(217603955769048*(24201 + 253*sqrt(9165))** (S(1)/3) + 2273005839412*sqrt(9165)*(24201 + 253*sqrt(9165))**(S(1)/3)) + 15720318185*12**(S(1)/3)*(24201 + 253*sqrt(9165))**(S(2)/3)/( 217603955769048*(24201 + 253*sqrt(9165))**(S(1)/3) + 2273005839412* sqrt(9165)*(24201 + 253*sqrt(9165))**(S(1)/3)) + 117968192370600*2**( S(1)/3)*3**(S(2)/3)/(217603955769048*(24201 + 253*sqrt(9165))**(S(1)/3) + 2273005839412*sqrt(9165)*(24201 + 253*sqrt(9165))**(S(1)/3)), x) assert f == Poly(0, x, domain='EX') def test_Poly_integrate(): assert Poly(x + 1).integrate() == Poly(x**2/2 + x) assert Poly(x + 1).integrate(x) == Poly(x**2/2 + x) assert Poly(x + 1).integrate((x, 1)) == Poly(x**2/2 + x) assert Poly(x*y + 1).integrate(x) == Poly(x**2*y/2 + x) assert Poly(x*y + 1).integrate(y) == Poly(x*y**2/2 + y) assert Poly(x*y + 1).integrate(x, x) == Poly(x**3*y/6 + x**2/2) assert Poly(x*y + 1).integrate(y, y) == Poly(x*y**3/6 + y**2/2) assert Poly(x*y + 1).integrate((x, 2)) == Poly(x**3*y/6 + x**2/2) assert Poly(x*y + 1).integrate((y, 2)) == Poly(x*y**3/6 + y**2/2) assert Poly(x*y + 1).integrate(x, y) == Poly(x**2*y**2/4 + x*y) assert Poly(x*y + 1).integrate(y, x) == Poly(x**2*y**2/4 + x*y) def test_Poly_diff(): assert Poly(x**2 + x).diff() == Poly(2*x + 1) assert Poly(x**2 + x).diff(x) == Poly(2*x + 1) assert Poly(x**2 + x).diff((x, 1)) == Poly(2*x + 1) assert Poly(x**2*y**2 + x*y).diff(x) == Poly(2*x*y**2 + y) assert Poly(x**2*y**2 + x*y).diff(y) == Poly(2*x**2*y + x) assert Poly(x**2*y**2 + x*y).diff(x, x) == Poly(2*y**2, x, y) assert Poly(x**2*y**2 + x*y).diff(y, y) == Poly(2*x**2, x, y) assert Poly(x**2*y**2 + x*y).diff((x, 2)) == Poly(2*y**2, x, y) assert Poly(x**2*y**2 + x*y).diff((y, 2)) == Poly(2*x**2, x, y) assert Poly(x**2*y**2 + x*y).diff(x, y) == Poly(4*x*y + 1) assert Poly(x**2*y**2 + x*y).diff(y, x) == Poly(4*x*y + 1) def test_issue_9585(): assert diff(Poly(x**2 + x)) == Poly(2*x + 1) assert diff(Poly(x**2 + x), x, evaluate=False) == \ Derivative(Poly(x**2 + x), x) assert Derivative(Poly(x**2 + x), x).doit() == Poly(2*x + 1) def test_Poly_eval(): assert Poly(0, x).eval(7) == 0 assert Poly(1, x).eval(7) == 1 assert Poly(x, x).eval(7) == 7 assert Poly(0, x).eval(0, 7) == 0 assert Poly(1, x).eval(0, 7) == 1 assert Poly(x, x).eval(0, 7) == 7 assert Poly(0, x).eval(x, 7) == 0 assert Poly(1, x).eval(x, 7) == 1 assert Poly(x, x).eval(x, 7) == 7 assert Poly(0, x).eval('x', 7) == 0 assert Poly(1, x).eval('x', 7) == 1 assert Poly(x, x).eval('x', 7) == 7 raises(PolynomialError, lambda: Poly(1, x).eval(1, 7)) raises(PolynomialError, lambda: Poly(1, x).eval(y, 7)) raises(PolynomialError, lambda: Poly(1, x).eval('y', 7)) assert Poly(123, x, y).eval(7) == Poly(123, y) assert Poly(2*y, x, y).eval(7) == Poly(2*y, y) assert Poly(x*y, x, y).eval(7) == Poly(7*y, y) assert Poly(123, x, y).eval(x, 7) == Poly(123, y) assert Poly(2*y, x, y).eval(x, 7) == Poly(2*y, y) assert Poly(x*y, x, y).eval(x, 7) == Poly(7*y, y) assert Poly(123, x, y).eval(y, 7) == Poly(123, x) assert Poly(2*y, x, y).eval(y, 7) == Poly(14, x) assert Poly(x*y, x, y).eval(y, 7) == Poly(7*x, x) assert Poly(x*y + y, x, y).eval({x: 7}) == Poly(8*y, y) assert Poly(x*y + y, x, y).eval({y: 7}) == Poly(7*x + 7, x) assert Poly(x*y + y, x, y).eval({x: 6, y: 7}) == 49 assert Poly(x*y + y, x, y).eval({x: 7, y: 6}) == 48 assert Poly(x*y + y, x, y).eval((6, 7)) == 49 assert Poly(x*y + y, x, y).eval([6, 7]) == 49 assert Poly(x + 1, domain='ZZ').eval(S.Half) == Rational(3, 2) assert Poly(x + 1, domain='ZZ').eval(sqrt(2)) == sqrt(2) + 1 raises(ValueError, lambda: Poly(x*y + y, x, y).eval((6, 7, 8))) raises(DomainError, lambda: Poly(x + 1, domain='ZZ').eval(S.Half, auto=False)) # issue 6344 alpha = Symbol('alpha') result = (2*alpha*z - 2*alpha + z**2 + 3)/(z**2 - 2*z + 1) f = Poly(x**2 + (alpha - 1)*x - alpha + 1, x, domain='ZZ[alpha]') assert f.eval((z + 1)/(z - 1)) == result g = Poly(x**2 + (alpha - 1)*x - alpha + 1, x, y, domain='ZZ[alpha]') assert g.eval((z + 1)/(z - 1)) == Poly(result, y, domain='ZZ(alpha,z)') def test_Poly___call__(): f = Poly(2*x*y + 3*x + y + 2*z) assert f(2) == Poly(5*y + 2*z + 6) assert f(2, 5) == Poly(2*z + 31) assert f(2, 5, 7) == 45 def test_parallel_poly_from_expr(): assert parallel_poly_from_expr( [x - 1, x**2 - 1], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [Poly(x - 1, x), x**2 - 1], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [x - 1, Poly(x**2 - 1, x)], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr([Poly( x - 1, x), Poly(x**2 - 1, x)], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [x - 1, x**2 - 1], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)] assert parallel_poly_from_expr([Poly( x - 1, x), x**2 - 1], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)] assert parallel_poly_from_expr([x - 1, Poly( x**2 - 1, x)], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)] assert parallel_poly_from_expr([Poly(x - 1, x), Poly( x**2 - 1, x)], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)] assert parallel_poly_from_expr( [x - 1, x**2 - 1])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [Poly(x - 1, x), x**2 - 1])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [x - 1, Poly(x**2 - 1, x)])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [Poly(x - 1, x), Poly(x**2 - 1, x)])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [1, x**2 - 1])[0] == [Poly(1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [1, x**2 - 1])[0] == [Poly(1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [1, Poly(x**2 - 1, x)])[0] == [Poly(1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [1, Poly(x**2 - 1, x)])[0] == [Poly(1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [x**2 - 1, 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)] assert parallel_poly_from_expr( [x**2 - 1, 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)] assert parallel_poly_from_expr( [Poly(x**2 - 1, x), 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)] assert parallel_poly_from_expr( [Poly(x**2 - 1, x), 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)] assert parallel_poly_from_expr([Poly(x, x, y), Poly(y, x, y)], x, y, order='lex')[0] == \ [Poly(x, x, y, domain='ZZ'), Poly(y, x, y, domain='ZZ')] raises(PolificationFailed, lambda: parallel_poly_from_expr([0, 1])) def test_pdiv(): f, g = x**2 - y**2, x - y q, r = x + y, 0 F, G, Q, R = [ Poly(h, x, y) for h in (f, g, q, r) ] assert F.pdiv(G) == (Q, R) assert F.prem(G) == R assert F.pquo(G) == Q assert F.pexquo(G) == Q assert pdiv(f, g) == (q, r) assert prem(f, g) == r assert pquo(f, g) == q assert pexquo(f, g) == q assert pdiv(f, g, x, y) == (q, r) assert prem(f, g, x, y) == r assert pquo(f, g, x, y) == q assert pexquo(f, g, x, y) == q assert pdiv(f, g, (x, y)) == (q, r) assert prem(f, g, (x, y)) == r assert pquo(f, g, (x, y)) == q assert pexquo(f, g, (x, y)) == q assert pdiv(F, G) == (Q, R) assert prem(F, G) == R assert pquo(F, G) == Q assert pexquo(F, G) == Q assert pdiv(f, g, polys=True) == (Q, R) assert prem(f, g, polys=True) == R assert pquo(f, g, polys=True) == Q assert pexquo(f, g, polys=True) == Q assert pdiv(F, G, polys=False) == (q, r) assert prem(F, G, polys=False) == r assert pquo(F, G, polys=False) == q assert pexquo(F, G, polys=False) == q raises(ComputationFailed, lambda: pdiv(4, 2)) raises(ComputationFailed, lambda: prem(4, 2)) raises(ComputationFailed, lambda: pquo(4, 2)) raises(ComputationFailed, lambda: pexquo(4, 2)) def test_div(): f, g = x**2 - y**2, x - y q, r = x + y, 0 F, G, Q, R = [ Poly(h, x, y) for h in (f, g, q, r) ] assert F.div(G) == (Q, R) assert F.rem(G) == R assert F.quo(G) == Q assert F.exquo(G) == Q assert div(f, g) == (q, r) assert rem(f, g) == r assert quo(f, g) == q assert exquo(f, g) == q assert div(f, g, x, y) == (q, r) assert rem(f, g, x, y) == r assert quo(f, g, x, y) == q assert exquo(f, g, x, y) == q assert div(f, g, (x, y)) == (q, r) assert rem(f, g, (x, y)) == r assert quo(f, g, (x, y)) == q assert exquo(f, g, (x, y)) == q assert div(F, G) == (Q, R) assert rem(F, G) == R assert quo(F, G) == Q assert exquo(F, G) == Q assert div(f, g, polys=True) == (Q, R) assert rem(f, g, polys=True) == R assert quo(f, g, polys=True) == Q assert exquo(f, g, polys=True) == Q assert div(F, G, polys=False) == (q, r) assert rem(F, G, polys=False) == r assert quo(F, G, polys=False) == q assert exquo(F, G, polys=False) == q raises(ComputationFailed, lambda: div(4, 2)) raises(ComputationFailed, lambda: rem(4, 2)) raises(ComputationFailed, lambda: quo(4, 2)) raises(ComputationFailed, lambda: exquo(4, 2)) f, g = x**2 + 1, 2*x - 4 qz, rz = 0, x**2 + 1 qq, rq = x/2 + 1, 5 assert div(f, g) == (qq, rq) assert div(f, g, auto=True) == (qq, rq) assert div(f, g, auto=False) == (qz, rz) assert div(f, g, domain=ZZ) == (qz, rz) assert div(f, g, domain=QQ) == (qq, rq) assert div(f, g, domain=ZZ, auto=True) == (qq, rq) assert div(f, g, domain=ZZ, auto=False) == (qz, rz) assert div(f, g, domain=QQ, auto=True) == (qq, rq) assert div(f, g, domain=QQ, auto=False) == (qq, rq) assert rem(f, g) == rq assert rem(f, g, auto=True) == rq assert rem(f, g, auto=False) == rz assert rem(f, g, domain=ZZ) == rz assert rem(f, g, domain=QQ) == rq assert rem(f, g, domain=ZZ, auto=True) == rq assert rem(f, g, domain=ZZ, auto=False) == rz assert rem(f, g, domain=QQ, auto=True) == rq assert rem(f, g, domain=QQ, auto=False) == rq assert quo(f, g) == qq assert quo(f, g, auto=True) == qq assert quo(f, g, auto=False) == qz assert quo(f, g, domain=ZZ) == qz assert quo(f, g, domain=QQ) == qq assert quo(f, g, domain=ZZ, auto=True) == qq assert quo(f, g, domain=ZZ, auto=False) == qz assert quo(f, g, domain=QQ, auto=True) == qq assert quo(f, g, domain=QQ, auto=False) == qq f, g, q = x**2, 2*x, x/2 assert exquo(f, g) == q assert exquo(f, g, auto=True) == q raises(ExactQuotientFailed, lambda: exquo(f, g, auto=False)) raises(ExactQuotientFailed, lambda: exquo(f, g, domain=ZZ)) assert exquo(f, g, domain=QQ) == q assert exquo(f, g, domain=ZZ, auto=True) == q raises(ExactQuotientFailed, lambda: exquo(f, g, domain=ZZ, auto=False)) assert exquo(f, g, domain=QQ, auto=True) == q assert exquo(f, g, domain=QQ, auto=False) == q f, g = Poly(x**2), Poly(x) q, r = f.div(g) assert q.get_domain().is_ZZ and r.get_domain().is_ZZ r = f.rem(g) assert r.get_domain().is_ZZ q = f.quo(g) assert q.get_domain().is_ZZ q = f.exquo(g) assert q.get_domain().is_ZZ f, g = Poly(x+y, x), Poly(2*x+y, x) q, r = f.div(g) assert q.get_domain().is_Frac and r.get_domain().is_Frac # https://github.com/sympy/sympy/issues/19579 p = Poly(2+3*I, x, domain=ZZ_I) q = Poly(1-I, x, domain=ZZ_I) assert p.div(q, auto=False) == \ (Poly(0, x, domain='ZZ_I'), Poly(2 + 3*I, x, domain='ZZ_I')) assert p.div(q, auto=True) == \ (Poly(-S(1)/2 + 5*I/2, x, domain='QQ_I'), Poly(0, x, domain='QQ_I')) def test_issue_7864(): q, r = div(a, .408248290463863*a) assert abs(q - 2.44948974278318) < 1e-14 assert r == 0 def test_gcdex(): f, g = 2*x, x**2 - 16 s, t, h = x/32, Rational(-1, 16), 1 F, G, S, T, H = [ Poly(u, x, domain='QQ') for u in (f, g, s, t, h) ] assert F.half_gcdex(G) == (S, H) assert F.gcdex(G) == (S, T, H) assert F.invert(G) == S assert half_gcdex(f, g) == (s, h) assert gcdex(f, g) == (s, t, h) assert invert(f, g) == s assert half_gcdex(f, g, x) == (s, h) assert gcdex(f, g, x) == (s, t, h) assert invert(f, g, x) == s assert half_gcdex(f, g, (x,)) == (s, h) assert gcdex(f, g, (x,)) == (s, t, h) assert invert(f, g, (x,)) == s assert half_gcdex(F, G) == (S, H) assert gcdex(F, G) == (S, T, H) assert invert(F, G) == S assert half_gcdex(f, g, polys=True) == (S, H) assert gcdex(f, g, polys=True) == (S, T, H) assert invert(f, g, polys=True) == S assert half_gcdex(F, G, polys=False) == (s, h) assert gcdex(F, G, polys=False) == (s, t, h) assert invert(F, G, polys=False) == s assert half_gcdex(100, 2004) == (-20, 4) assert gcdex(100, 2004) == (-20, 1, 4) assert invert(3, 7) == 5 raises(DomainError, lambda: half_gcdex(x + 1, 2*x + 1, auto=False)) raises(DomainError, lambda: gcdex(x + 1, 2*x + 1, auto=False)) raises(DomainError, lambda: invert(x + 1, 2*x + 1, auto=False)) def test_revert(): f = Poly(1 - x**2/2 + x**4/24 - x**6/720) g = Poly(61*x**6/720 + 5*x**4/24 + x**2/2 + 1) assert f.revert(8) == g def test_subresultants(): f, g, h = x**2 - 2*x + 1, x**2 - 1, 2*x - 2 F, G, H = Poly(f), Poly(g), Poly(h) assert F.subresultants(G) == [F, G, H] assert subresultants(f, g) == [f, g, h] assert subresultants(f, g, x) == [f, g, h] assert subresultants(f, g, (x,)) == [f, g, h] assert subresultants(F, G) == [F, G, H] assert subresultants(f, g, polys=True) == [F, G, H] assert subresultants(F, G, polys=False) == [f, g, h] raises(ComputationFailed, lambda: subresultants(4, 2)) def test_resultant(): f, g, h = x**2 - 2*x + 1, x**2 - 1, 0 F, G = Poly(f), Poly(g) assert F.resultant(G) == h assert resultant(f, g) == h assert resultant(f, g, x) == h assert resultant(f, g, (x,)) == h assert resultant(F, G) == h assert resultant(f, g, polys=True) == h assert resultant(F, G, polys=False) == h assert resultant(f, g, includePRS=True) == (h, [f, g, 2*x - 2]) f, g, h = x - a, x - b, a - b F, G, H = Poly(f), Poly(g), Poly(h) assert F.resultant(G) == H assert resultant(f, g) == h assert resultant(f, g, x) == h assert resultant(f, g, (x,)) == h assert resultant(F, G) == H assert resultant(f, g, polys=True) == H assert resultant(F, G, polys=False) == h raises(ComputationFailed, lambda: resultant(4, 2)) def test_discriminant(): f, g = x**3 + 3*x**2 + 9*x - 13, -11664 F = Poly(f) assert F.discriminant() == g assert discriminant(f) == g assert discriminant(f, x) == g assert discriminant(f, (x,)) == g assert discriminant(F) == g assert discriminant(f, polys=True) == g assert discriminant(F, polys=False) == g f, g = a*x**2 + b*x + c, b**2 - 4*a*c F, G = Poly(f), Poly(g) assert F.discriminant() == G assert discriminant(f) == g assert discriminant(f, x, a, b, c) == g assert discriminant(f, (x, a, b, c)) == g assert discriminant(F) == G assert discriminant(f, polys=True) == G assert discriminant(F, polys=False) == g raises(ComputationFailed, lambda: discriminant(4)) def test_dispersion(): # We test only the API here. For more mathematical # tests see the dedicated test file. fp = poly((x + 1)*(x + 2), x) assert sorted(fp.dispersionset()) == [0, 1] assert fp.dispersion() == 1 fp = poly(x**4 - 3*x**2 + 1, x) gp = fp.shift(-3) assert sorted(fp.dispersionset(gp)) == [2, 3, 4] assert fp.dispersion(gp) == 4 def test_gcd_list(): F = [x**3 - 1, x**2 - 1, x**2 - 3*x + 2] assert gcd_list(F) == x - 1 assert gcd_list(F, polys=True) == Poly(x - 1) assert gcd_list([]) == 0 assert gcd_list([1, 2]) == 1 assert gcd_list([4, 6, 8]) == 2 assert gcd_list([x*(y + 42) - x*y - x*42]) == 0 gcd = gcd_list([], x) assert gcd.is_Number and gcd is S.Zero gcd = gcd_list([], x, polys=True) assert gcd.is_Poly and gcd.is_zero a = sqrt(2) assert gcd_list([a, -a]) == gcd_list([-a, a]) == a raises(ComputationFailed, lambda: gcd_list([], polys=True)) def test_lcm_list(): F = [x**3 - 1, x**2 - 1, x**2 - 3*x + 2] assert lcm_list(F) == x**5 - x**4 - 2*x**3 - x**2 + x + 2 assert lcm_list(F, polys=True) == Poly(x**5 - x**4 - 2*x**3 - x**2 + x + 2) assert lcm_list([]) == 1 assert lcm_list([1, 2]) == 2 assert lcm_list([4, 6, 8]) == 24 assert lcm_list([x*(y + 42) - x*y - x*42]) == 0 lcm = lcm_list([], x) assert lcm.is_Number and lcm is S.One lcm = lcm_list([], x, polys=True) assert lcm.is_Poly and lcm.is_one raises(ComputationFailed, lambda: lcm_list([], polys=True)) def test_gcd(): f, g = x**3 - 1, x**2 - 1 s, t = x**2 + x + 1, x + 1 h, r = x - 1, x**4 + x**3 - x - 1 F, G, S, T, H, R = [ Poly(u) for u in (f, g, s, t, h, r) ] assert F.cofactors(G) == (H, S, T) assert F.gcd(G) == H assert F.lcm(G) == R assert cofactors(f, g) == (h, s, t) assert gcd(f, g) == h assert lcm(f, g) == r assert cofactors(f, g, x) == (h, s, t) assert gcd(f, g, x) == h assert lcm(f, g, x) == r assert cofactors(f, g, (x,)) == (h, s, t) assert gcd(f, g, (x,)) == h assert lcm(f, g, (x,)) == r assert cofactors(F, G) == (H, S, T) assert gcd(F, G) == H assert lcm(F, G) == R assert cofactors(f, g, polys=True) == (H, S, T) assert gcd(f, g, polys=True) == H assert lcm(f, g, polys=True) == R assert cofactors(F, G, polys=False) == (h, s, t) assert gcd(F, G, polys=False) == h assert lcm(F, G, polys=False) == r f, g = 1.0*x**2 - 1.0, 1.0*x - 1.0 h, s, t = g, 1.0*x + 1.0, 1.0 assert cofactors(f, g) == (h, s, t) assert gcd(f, g) == h assert lcm(f, g) == f f, g = 1.0*x**2 - 1.0, 1.0*x - 1.0 h, s, t = g, 1.0*x + 1.0, 1.0 assert cofactors(f, g) == (h, s, t) assert gcd(f, g) == h assert lcm(f, g) == f assert cofactors(8, 6) == (2, 4, 3) assert gcd(8, 6) == 2 assert lcm(8, 6) == 24 f, g = x**2 - 3*x - 4, x**3 - 4*x**2 + x - 4 l = x**4 - 3*x**3 - 3*x**2 - 3*x - 4 h, s, t = x - 4, x + 1, x**2 + 1 assert cofactors(f, g, modulus=11) == (h, s, t) assert gcd(f, g, modulus=11) == h assert lcm(f, g, modulus=11) == l f, g = x**2 + 8*x + 7, x**3 + 7*x**2 + x + 7 l = x**4 + 8*x**3 + 8*x**2 + 8*x + 7 h, s, t = x + 7, x + 1, x**2 + 1 assert cofactors(f, g, modulus=11, symmetric=False) == (h, s, t) assert gcd(f, g, modulus=11, symmetric=False) == h assert lcm(f, g, modulus=11, symmetric=False) == l a, b = sqrt(2), -sqrt(2) assert gcd(a, b) == gcd(b, a) == sqrt(2) a, b = sqrt(-2), -sqrt(-2) assert gcd(a, b) == gcd(b, a) == sqrt(2) assert gcd(Poly(x - 2, x), Poly(I*x, x)) == Poly(1, x, domain=ZZ_I) raises(TypeError, lambda: gcd(x)) raises(TypeError, lambda: lcm(x)) def test_gcd_numbers_vs_polys(): assert isinstance(gcd(3, 9), Integer) assert isinstance(gcd(3*x, 9), Integer) assert gcd(3, 9) == 3 assert gcd(3*x, 9) == 3 assert isinstance(gcd(Rational(3, 2), Rational(9, 4)), Rational) assert isinstance(gcd(Rational(3, 2)*x, Rational(9, 4)), Rational) assert gcd(Rational(3, 2), Rational(9, 4)) == Rational(3, 4) assert gcd(Rational(3, 2)*x, Rational(9, 4)) == 1 assert isinstance(gcd(3.0, 9.0), Float) assert isinstance(gcd(3.0*x, 9.0), Float) assert gcd(3.0, 9.0) == 1.0 assert gcd(3.0*x, 9.0) == 1.0 # partial fix of 20597 assert gcd(Mul(2, 3, evaluate=False), 2) == 2 def test_terms_gcd(): assert terms_gcd(1) == 1 assert terms_gcd(1, x) == 1 assert terms_gcd(x - 1) == x - 1 assert terms_gcd(-x - 1) == -x - 1 assert terms_gcd(2*x + 3) == 2*x + 3 assert terms_gcd(6*x + 4) == Mul(2, 3*x + 2, evaluate=False) assert terms_gcd(x**3*y + x*y**3) == x*y*(x**2 + y**2) assert terms_gcd(2*x**3*y + 2*x*y**3) == 2*x*y*(x**2 + y**2) assert terms_gcd(x**3*y/2 + x*y**3/2) == x*y/2*(x**2 + y**2) assert terms_gcd(x**3*y + 2*x*y**3) == x*y*(x**2 + 2*y**2) assert terms_gcd(2*x**3*y + 4*x*y**3) == 2*x*y*(x**2 + 2*y**2) assert terms_gcd(2*x**3*y/3 + 4*x*y**3/5) == x*y*Rational(2, 15)*(5*x**2 + 6*y**2) assert terms_gcd(2.0*x**3*y + 4.1*x*y**3) == x*y*(2.0*x**2 + 4.1*y**2) assert _aresame(terms_gcd(2.0*x + 3), 2.0*x + 3) assert terms_gcd((3 + 3*x)*(x + x*y), expand=False) == \ (3*x + 3)*(x*y + x) assert terms_gcd((3 + 3*x)*(x + x*sin(3 + 3*y)), expand=False, deep=True) == \ 3*x*(x + 1)*(sin(Mul(3, y + 1, evaluate=False)) + 1) assert terms_gcd(sin(x + x*y), deep=True) == \ sin(x*(y + 1)) eq = Eq(2*x, 2*y + 2*z*y) assert terms_gcd(eq) == Eq(2*x, 2*y*(z + 1)) assert terms_gcd(eq, deep=True) == Eq(2*x, 2*y*(z + 1)) raises(TypeError, lambda: terms_gcd(x < 2)) def test_trunc(): f, g = x**5 + 2*x**4 + 3*x**3 + 4*x**2 + 5*x + 6, x**5 - x**4 + x**2 - x F, G = Poly(f), Poly(g) assert F.trunc(3) == G assert trunc(f, 3) == g assert trunc(f, 3, x) == g assert trunc(f, 3, (x,)) == g assert trunc(F, 3) == G assert trunc(f, 3, polys=True) == G assert trunc(F, 3, polys=False) == g f, g = 6*x**5 + 5*x**4 + 4*x**3 + 3*x**2 + 2*x + 1, -x**4 + x**3 - x + 1 F, G = Poly(f), Poly(g) assert F.trunc(3) == G assert trunc(f, 3) == g assert trunc(f, 3, x) == g assert trunc(f, 3, (x,)) == g assert trunc(F, 3) == G assert trunc(f, 3, polys=True) == G assert trunc(F, 3, polys=False) == g f = Poly(x**2 + 2*x + 3, modulus=5) assert f.trunc(2) == Poly(x**2 + 1, modulus=5) def test_monic(): f, g = 2*x - 1, x - S.Half F, G = Poly(f, domain='QQ'), Poly(g) assert F.monic() == G assert monic(f) == g assert monic(f, x) == g assert monic(f, (x,)) == g assert monic(F) == G assert monic(f, polys=True) == G assert monic(F, polys=False) == g raises(ComputationFailed, lambda: monic(4)) assert monic(2*x**2 + 6*x + 4, auto=False) == x**2 + 3*x + 2 raises(ExactQuotientFailed, lambda: monic(2*x + 6*x + 1, auto=False)) assert monic(2.0*x**2 + 6.0*x + 4.0) == 1.0*x**2 + 3.0*x + 2.0 assert monic(2*x**2 + 3*x + 4, modulus=5) == x**2 - x + 2 def test_content(): f, F = 4*x + 2, Poly(4*x + 2) assert F.content() == 2 assert content(f) == 2 raises(ComputationFailed, lambda: content(4)) f = Poly(2*x, modulus=3) assert f.content() == 1 def test_primitive(): f, g = 4*x + 2, 2*x + 1 F, G = Poly(f), Poly(g) assert F.primitive() == (2, G) assert primitive(f) == (2, g) assert primitive(f, x) == (2, g) assert primitive(f, (x,)) == (2, g) assert primitive(F) == (2, G) assert primitive(f, polys=True) == (2, G) assert primitive(F, polys=False) == (2, g) raises(ComputationFailed, lambda: primitive(4)) f = Poly(2*x, modulus=3) g = Poly(2.0*x, domain=RR) assert f.primitive() == (1, f) assert g.primitive() == (1.0, g) assert primitive(S('-3*x/4 + y + 11/8')) == \ S('(1/8, -6*x + 8*y + 11)') def test_compose(): f = x**12 + 20*x**10 + 150*x**8 + 500*x**6 + 625*x**4 - 2*x**3 - 10*x + 9 g = x**4 - 2*x + 9 h = x**3 + 5*x F, G, H = map(Poly, (f, g, h)) assert G.compose(H) == F assert compose(g, h) == f assert compose(g, h, x) == f assert compose(g, h, (x,)) == f assert compose(G, H) == F assert compose(g, h, polys=True) == F assert compose(G, H, polys=False) == f assert F.decompose() == [G, H] assert decompose(f) == [g, h] assert decompose(f, x) == [g, h] assert decompose(f, (x,)) == [g, h] assert decompose(F) == [G, H] assert decompose(f, polys=True) == [G, H] assert decompose(F, polys=False) == [g, h] raises(ComputationFailed, lambda: compose(4, 2)) raises(ComputationFailed, lambda: decompose(4)) assert compose(x**2 - y**2, x - y, x, y) == x**2 - 2*x*y assert compose(x**2 - y**2, x - y, y, x) == -y**2 + 2*x*y def test_shift(): assert Poly(x**2 - 2*x + 1, x).shift(2) == Poly(x**2 + 2*x + 1, x) def test_transform(): # Also test that 3-way unification is done correctly assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1), Poly(x - 1)) == \ Poly(4, x) == \ cancel((x - 1)**2*(x**2 - 2*x + 1).subs(x, (x + 1)/(x - 1))) assert Poly(x**2 - x/2 + 1, x).transform(Poly(x + 1), Poly(x - 1)) == \ Poly(3*x**2/2 + Rational(5, 2), x) == \ cancel((x - 1)**2*(x**2 - x/2 + 1).subs(x, (x + 1)/(x - 1))) assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + S.Half), Poly(x - 1)) == \ Poly(Rational(9, 4), x) == \ cancel((x - 1)**2*(x**2 - 2*x + 1).subs(x, (x + S.Half)/(x - 1))) assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1), Poly(x - S.Half)) == \ Poly(Rational(9, 4), x) == \ cancel((x - S.Half)**2*(x**2 - 2*x + 1).subs(x, (x + 1)/(x - S.Half))) # Unify ZZ, QQ, and RR assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1.0), Poly(x - S.Half)) == \ Poly(Rational(9, 4), x, domain='RR') == \ cancel((x - S.Half)**2*(x**2 - 2*x + 1).subs(x, (x + 1.0)/(x - S.Half))) raises(ValueError, lambda: Poly(x*y).transform(Poly(x + 1), Poly(x - 1))) raises(ValueError, lambda: Poly(x).transform(Poly(y + 1), Poly(x - 1))) raises(ValueError, lambda: Poly(x).transform(Poly(x + 1), Poly(y - 1))) raises(ValueError, lambda: Poly(x).transform(Poly(x*y + 1), Poly(x - 1))) raises(ValueError, lambda: Poly(x).transform(Poly(x + 1), Poly(x*y - 1))) def test_sturm(): f, F = x, Poly(x, domain='QQ') g, G = 1, Poly(1, x, domain='QQ') assert F.sturm() == [F, G] assert sturm(f) == [f, g] assert sturm(f, x) == [f, g] assert sturm(f, (x,)) == [f, g] assert sturm(F) == [F, G] assert sturm(f, polys=True) == [F, G] assert sturm(F, polys=False) == [f, g] raises(ComputationFailed, lambda: sturm(4)) raises(DomainError, lambda: sturm(f, auto=False)) f = Poly(S(1024)/(15625*pi**8)*x**5 - S(4096)/(625*pi**8)*x**4 + S(32)/(15625*pi**4)*x**3 - S(128)/(625*pi**4)*x**2 + Rational(1, 62500)*x - Rational(1, 625), x, domain='ZZ(pi)') assert sturm(f) == \ [Poly(x**3 - 100*x**2 + pi**4/64*x - 25*pi**4/16, x, domain='ZZ(pi)'), Poly(3*x**2 - 200*x + pi**4/64, x, domain='ZZ(pi)'), Poly((Rational(20000, 9) - pi**4/96)*x + 25*pi**4/18, x, domain='ZZ(pi)'), Poly((-3686400000000*pi**4 - 11520000*pi**8 - 9*pi**12)/(26214400000000 - 245760000*pi**4 + 576*pi**8), x, domain='ZZ(pi)')] def test_gff(): f = x**5 + 2*x**4 - x**3 - 2*x**2 assert Poly(f).gff_list() == [(Poly(x), 1), (Poly(x + 2), 4)] assert gff_list(f) == [(x, 1), (x + 2, 4)] raises(NotImplementedError, lambda: gff(f)) f = x*(x - 1)**3*(x - 2)**2*(x - 4)**2*(x - 5) assert Poly(f).gff_list() == [( Poly(x**2 - 5*x + 4), 1), (Poly(x**2 - 5*x + 4), 2), (Poly(x), 3)] assert gff_list(f) == [(x**2 - 5*x + 4, 1), (x**2 - 5*x + 4, 2), (x, 3)] raises(NotImplementedError, lambda: gff(f)) def test_norm(): a, b = sqrt(2), sqrt(3) f = Poly(a*x + b*y, x, y, extension=(a, b)) assert f.norm() == Poly(4*x**4 - 12*x**2*y**2 + 9*y**4, x, y, domain='QQ') def test_sqf_norm(): assert sqf_norm(x**2 - 2, extension=sqrt(3)) == \ (1, x**2 - 2*sqrt(3)*x + 1, x**4 - 10*x**2 + 1) assert sqf_norm(x**2 - 3, extension=sqrt(2)) == \ (1, x**2 - 2*sqrt(2)*x - 1, x**4 - 10*x**2 + 1) assert Poly(x**2 - 2, extension=sqrt(3)).sqf_norm() == \ (1, Poly(x**2 - 2*sqrt(3)*x + 1, x, extension=sqrt(3)), Poly(x**4 - 10*x**2 + 1, x, domain='QQ')) assert Poly(x**2 - 3, extension=sqrt(2)).sqf_norm() == \ (1, Poly(x**2 - 2*sqrt(2)*x - 1, x, extension=sqrt(2)), Poly(x**4 - 10*x**2 + 1, x, domain='QQ')) def test_sqf(): f = x**5 - x**3 - x**2 + 1 g = x**3 + 2*x**2 + 2*x + 1 h = x - 1 p = x**4 + x**3 - x - 1 F, G, H, P = map(Poly, (f, g, h, p)) assert F.sqf_part() == P assert sqf_part(f) == p assert sqf_part(f, x) == p assert sqf_part(f, (x,)) == p assert sqf_part(F) == P assert sqf_part(f, polys=True) == P assert sqf_part(F, polys=False) == p assert F.sqf_list() == (1, [(G, 1), (H, 2)]) assert sqf_list(f) == (1, [(g, 1), (h, 2)]) assert sqf_list(f, x) == (1, [(g, 1), (h, 2)]) assert sqf_list(f, (x,)) == (1, [(g, 1), (h, 2)]) assert sqf_list(F) == (1, [(G, 1), (H, 2)]) assert sqf_list(f, polys=True) == (1, [(G, 1), (H, 2)]) assert sqf_list(F, polys=False) == (1, [(g, 1), (h, 2)]) assert F.sqf_list_include() == [(G, 1), (H, 2)] raises(ComputationFailed, lambda: sqf_part(4)) assert sqf(1) == 1 assert sqf_list(1) == (1, []) assert sqf((2*x**2 + 2)**7) == 128*(x**2 + 1)**7 assert sqf(f) == g*h**2 assert sqf(f, x) == g*h**2 assert sqf(f, (x,)) == g*h**2 d = x**2 + y**2 assert sqf(f/d) == (g*h**2)/d assert sqf(f/d, x) == (g*h**2)/d assert sqf(f/d, (x,)) == (g*h**2)/d assert sqf(x - 1) == x - 1 assert sqf(-x - 1) == -x - 1 assert sqf(x - 1) == x - 1 assert sqf(6*x - 10) == Mul(2, 3*x - 5, evaluate=False) assert sqf((6*x - 10)/(3*x - 6)) == Rational(2, 3)*((3*x - 5)/(x - 2)) assert sqf(Poly(x**2 - 2*x + 1)) == (x - 1)**2 f = 3 + x - x*(1 + x) + x**2 assert sqf(f) == 3 f = (x**2 + 2*x + 1)**20000000000 assert sqf(f) == (x + 1)**40000000000 assert sqf_list(f) == (1, [(x + 1, 40000000000)]) def test_factor(): f = x**5 - x**3 - x**2 + 1 u = x + 1 v = x - 1 w = x**2 + x + 1 F, U, V, W = map(Poly, (f, u, v, w)) assert F.factor_list() == (1, [(U, 1), (V, 2), (W, 1)]) assert factor_list(f) == (1, [(u, 1), (v, 2), (w, 1)]) assert factor_list(f, x) == (1, [(u, 1), (v, 2), (w, 1)]) assert factor_list(f, (x,)) == (1, [(u, 1), (v, 2), (w, 1)]) assert factor_list(F) == (1, [(U, 1), (V, 2), (W, 1)]) assert factor_list(f, polys=True) == (1, [(U, 1), (V, 2), (W, 1)]) assert factor_list(F, polys=False) == (1, [(u, 1), (v, 2), (w, 1)]) assert F.factor_list_include() == [(U, 1), (V, 2), (W, 1)] assert factor_list(1) == (1, []) assert factor_list(6) == (6, []) assert factor_list(sqrt(3), x) == (sqrt(3), []) assert factor_list((-1)**x, x) == (1, [(-1, x)]) assert factor_list((2*x)**y, x) == (1, [(2, y), (x, y)]) assert factor_list(sqrt(x*y), x) == (1, [(x*y, S.Half)]) assert factor(6) == 6 and factor(6).is_Integer assert factor_list(3*x) == (3, [(x, 1)]) assert factor_list(3*x**2) == (3, [(x, 2)]) assert factor(3*x) == 3*x assert factor(3*x**2) == 3*x**2 assert factor((2*x**2 + 2)**7) == 128*(x**2 + 1)**7 assert factor(f) == u*v**2*w assert factor(f, x) == u*v**2*w assert factor(f, (x,)) == u*v**2*w g, p, q, r = x**2 - y**2, x - y, x + y, x**2 + 1 assert factor(f/g) == (u*v**2*w)/(p*q) assert factor(f/g, x) == (u*v**2*w)/(p*q) assert factor(f/g, (x,)) == (u*v**2*w)/(p*q) p = Symbol('p', positive=True) i = Symbol('i', integer=True) r = Symbol('r', real=True) assert factor(sqrt(x*y)).is_Pow is True assert factor(sqrt(3*x**2 - 3)) == sqrt(3)*sqrt((x - 1)*(x + 1)) assert factor(sqrt(3*x**2 + 3)) == sqrt(3)*sqrt(x**2 + 1) assert factor((y*x**2 - y)**i) == y**i*(x - 1)**i*(x + 1)**i assert factor((y*x**2 + y)**i) == y**i*(x**2 + 1)**i assert factor((y*x**2 - y)**t) == (y*(x - 1)*(x + 1))**t assert factor((y*x**2 + y)**t) == (y*(x**2 + 1))**t f = sqrt(expand((r**2 + 1)*(p + 1)*(p - 1)*(p - 2)**3)) g = sqrt((p - 2)**3*(p - 1))*sqrt(p + 1)*sqrt(r**2 + 1) assert factor(f) == g assert factor(g) == g g = (x - 1)**5*(r**2 + 1) f = sqrt(expand(g)) assert factor(f) == sqrt(g) f = Poly(sin(1)*x + 1, x, domain=EX) assert f.factor_list() == (1, [(f, 1)]) f = x**4 + 1 assert factor(f) == f assert factor(f, extension=I) == (x**2 - I)*(x**2 + I) assert factor(f, gaussian=True) == (x**2 - I)*(x**2 + I) assert factor( f, extension=sqrt(2)) == (x**2 + sqrt(2)*x + 1)*(x**2 - sqrt(2)*x + 1) assert factor(x**2 + 4*I*x - 4) == (x + 2*I)**2 f = x**2 + 2*I*x - 4 assert factor(f) == f f = 8192*x**2 + x*(22656 + 175232*I) - 921416 + 242313*I f_zzi = I*(x*(64 - 64*I) + 773 + 596*I)**2 f_qqi = 8192*(x + S(177)/128 + 1369*I/128)**2 assert factor(f) == f_zzi assert factor(f, domain=ZZ_I) == f_zzi assert factor(f, domain=QQ_I) == f_qqi f = x**2 + 2*sqrt(2)*x + 2 assert factor(f, extension=sqrt(2)) == (x + sqrt(2))**2 assert factor(f**3, extension=sqrt(2)) == (x + sqrt(2))**6 assert factor(x**2 - 2*y**2, extension=sqrt(2)) == \ (x + sqrt(2)*y)*(x - sqrt(2)*y) assert factor(2*x**2 - 4*y**2, extension=sqrt(2)) == \ 2*((x + sqrt(2)*y)*(x - sqrt(2)*y)) assert factor(x - 1) == x - 1 assert factor(-x - 1) == -x - 1 assert factor(x - 1) == x - 1 assert factor(6*x - 10) == Mul(2, 3*x - 5, evaluate=False) assert factor(x**11 + x + 1, modulus=65537, symmetric=True) == \ (x**2 + x + 1)*(x**9 - x**8 + x**6 - x**5 + x**3 - x** 2 + 1) assert factor(x**11 + x + 1, modulus=65537, symmetric=False) == \ (x**2 + x + 1)*(x**9 + 65536*x**8 + x**6 + 65536*x**5 + x**3 + 65536*x** 2 + 1) f = x/pi + x*sin(x)/pi g = y/(pi**2 + 2*pi + 1) + y*sin(x)/(pi**2 + 2*pi + 1) assert factor(f) == x*(sin(x) + 1)/pi assert factor(g) == y*(sin(x) + 1)/(pi + 1)**2 assert factor(Eq( x**2 + 2*x + 1, x**3 + 1)) == Eq((x + 1)**2, (x + 1)*(x**2 - x + 1)) f = (x**2 - 1)/(x**2 + 4*x + 4) assert factor(f) == (x + 1)*(x - 1)/(x + 2)**2 assert factor(f, x) == (x + 1)*(x - 1)/(x + 2)**2 f = 3 + x - x*(1 + x) + x**2 assert factor(f) == 3 assert factor(f, x) == 3 assert factor(1/(x**2 + 2*x + 1/x) - 1) == -((1 - x + 2*x**2 + x**3)/(1 + 2*x**2 + x**3)) assert factor(f, expand=False) == f raises(PolynomialError, lambda: factor(f, x, expand=False)) raises(FlagError, lambda: factor(x**2 - 1, polys=True)) assert factor([x, Eq(x**2 - y**2, Tuple(x**2 - z**2, 1/x + 1/y))]) == \ [x, Eq((x - y)*(x + y), Tuple((x - z)*(x + z), (x + y)/x/y))] assert not isinstance( Poly(x**3 + x + 1).factor_list()[1][0][0], PurePoly) is True assert isinstance( PurePoly(x**3 + x + 1).factor_list()[1][0][0], PurePoly) is True assert factor(sqrt(-x)) == sqrt(-x) # issue 5917 e = (-2*x*(-x + 1)*(x - 1)*(-x*(-x + 1)*(x - 1) - x*(x - 1)**2)*(x**2*(x - 1) - x*(x - 1) - x) - (-2*x**2*(x - 1)**2 - x*(-x + 1)*(-x*(-x + 1) + x*(x - 1)))*(x**2*(x - 1)**4 - x*(-x*(-x + 1)*(x - 1) - x*(x - 1)**2))) assert factor(e) == 0 # deep option assert factor(sin(x**2 + x) + x, deep=True) == sin(x*(x + 1)) + x assert factor(sin(x**2 + x)*x, deep=True) == sin(x*(x + 1))*x assert factor(sqrt(x**2)) == sqrt(x**2) # issue 13149 assert factor(expand((0.5*x+1)*(0.5*y+1))) == Mul(1.0, 0.5*x + 1.0, 0.5*y + 1.0, evaluate = False) assert factor(expand((0.5*x+0.5)**2)) == 0.25*(1.0*x + 1.0)**2 eq = x**2*y**2 + 11*x**2*y + 30*x**2 + 7*x*y**2 + 77*x*y + 210*x + 12*y**2 + 132*y + 360 assert factor(eq, x) == (x + 3)*(x + 4)*(y**2 + 11*y + 30) assert factor(eq, x, deep=True) == (x + 3)*(x + 4)*(y**2 + 11*y + 30) assert factor(eq, y, deep=True) == (y + 5)*(y + 6)*(x**2 + 7*x + 12) # fraction option f = 5*x + 3*exp(2 - 7*x) assert factor(f, deep=True) == factor(f, deep=True, fraction=True) assert factor(f, deep=True, fraction=False) == 5*x + 3*exp(2)*exp(-7*x) assert factor_list(x**3 - x*y**2, t, w, x) == ( 1, [(x, 1), (x - y, 1), (x + y, 1)]) def test_factor_large(): f = (x**2 + 4*x + 4)**10000000*(x**2 + 1)*(x**2 + 2*x + 1)**1234567 g = ((x**2 + 2*x + 1)**3000*y**2 + (x**2 + 2*x + 1)**3000*2*y + ( x**2 + 2*x + 1)**3000) assert factor(f) == (x + 2)**20000000*(x**2 + 1)*(x + 1)**2469134 assert factor(g) == (x + 1)**6000*(y + 1)**2 assert factor_list( f) == (1, [(x + 1, 2469134), (x + 2, 20000000), (x**2 + 1, 1)]) assert factor_list(g) == (1, [(y + 1, 2), (x + 1, 6000)]) f = (x**2 - y**2)**200000*(x**7 + 1) g = (x**2 + y**2)**200000*(x**7 + 1) assert factor(f) == \ (x + 1)*(x - y)**200000*(x + y)**200000*(x**6 - x**5 + x**4 - x**3 + x**2 - x + 1) assert factor(g, gaussian=True) == \ (x + 1)*(x - I*y)**200000*(x + I*y)**200000*(x**6 - x**5 + x**4 - x**3 + x**2 - x + 1) assert factor_list(f) == \ (1, [(x + 1, 1), (x - y, 200000), (x + y, 200000), (x**6 - x**5 + x**4 - x**3 + x**2 - x + 1, 1)]) assert factor_list(g, gaussian=True) == \ (1, [(x + 1, 1), (x - I*y, 200000), (x + I*y, 200000), ( x**6 - x**5 + x**4 - x**3 + x**2 - x + 1, 1)]) def test_factor_noeval(): assert factor(6*x - 10) == Mul(2, 3*x - 5, evaluate=False) assert factor((6*x - 10)/(3*x - 6)) == Mul(Rational(2, 3), 3*x - 5, 1/(x - 2)) def test_intervals(): assert intervals(0) == [] assert intervals(1) == [] assert intervals(x, sqf=True) == [(0, 0)] assert intervals(x) == [((0, 0), 1)] assert intervals(x**128) == [((0, 0), 128)] assert intervals([x**2, x**4]) == [((0, 0), {0: 2, 1: 4})] f = Poly((x*Rational(2, 5) - Rational(17, 3))*(4*x + Rational(1, 257))) assert f.intervals(sqf=True) == [(-1, 0), (14, 15)] assert f.intervals() == [((-1, 0), 1), ((14, 15), 1)] assert f.intervals(fast=True, sqf=True) == [(-1, 0), (14, 15)] assert f.intervals(fast=True) == [((-1, 0), 1), ((14, 15), 1)] assert f.intervals(eps=Rational(1, 10)) == f.intervals(eps=0.1) == \ [((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert f.intervals(eps=Rational(1, 100)) == f.intervals(eps=0.01) == \ [((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert f.intervals(eps=Rational(1, 1000)) == f.intervals(eps=0.001) == \ [((Rational(-1, 1002), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert f.intervals(eps=Rational(1, 10000)) == f.intervals(eps=0.0001) == \ [((Rational(-1, 1028), Rational(-1, 1028)), 1), ((Rational(85, 6), Rational(85, 6)), 1)] f = (x*Rational(2, 5) - Rational(17, 3))*(4*x + Rational(1, 257)) assert intervals(f, sqf=True) == [(-1, 0), (14, 15)] assert intervals(f) == [((-1, 0), 1), ((14, 15), 1)] assert intervals(f, eps=Rational(1, 10)) == intervals(f, eps=0.1) == \ [((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert intervals(f, eps=Rational(1, 100)) == intervals(f, eps=0.01) == \ [((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert intervals(f, eps=Rational(1, 1000)) == intervals(f, eps=0.001) == \ [((Rational(-1, 1002), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert intervals(f, eps=Rational(1, 10000)) == intervals(f, eps=0.0001) == \ [((Rational(-1, 1028), Rational(-1, 1028)), 1), ((Rational(85, 6), Rational(85, 6)), 1)] f = Poly((x**2 - 2)*(x**2 - 3)**7*(x + 1)*(7*x + 3)**3) assert f.intervals() == \ [((-2, Rational(-3, 2)), 7), ((Rational(-3, 2), -1), 1), ((-1, -1), 1), ((-1, 0), 3), ((1, Rational(3, 2)), 1), ((Rational(3, 2), 2), 7)] assert intervals([x**5 - 200, x**5 - 201]) == \ [((Rational(75, 26), Rational(101, 35)), {0: 1}), ((Rational(309, 107), Rational(26, 9)), {1: 1})] assert intervals([x**5 - 200, x**5 - 201], fast=True) == \ [((Rational(75, 26), Rational(101, 35)), {0: 1}), ((Rational(309, 107), Rational(26, 9)), {1: 1})] assert intervals([x**2 - 200, x**2 - 201]) == \ [((Rational(-71, 5), Rational(-85, 6)), {1: 1}), ((Rational(-85, 6), -14), {0: 1}), ((14, Rational(85, 6)), {0: 1}), ((Rational(85, 6), Rational(71, 5)), {1: 1})] assert intervals([x + 1, x + 2, x - 1, x + 1, 1, x - 1, x - 1, (x - 2)**2]) == \ [((-2, -2), {1: 1}), ((-1, -1), {0: 1, 3: 1}), ((1, 1), {2: 1, 5: 1, 6: 1}), ((2, 2), {7: 2})] f, g, h = x**2 - 2, x**4 - 4*x**2 + 4, x - 1 assert intervals(f, inf=Rational(7, 4), sqf=True) == [] assert intervals(f, inf=Rational(7, 5), sqf=True) == [(Rational(7, 5), Rational(3, 2))] assert intervals(f, sup=Rational(7, 4), sqf=True) == [(-2, -1), (1, Rational(3, 2))] assert intervals(f, sup=Rational(7, 5), sqf=True) == [(-2, -1)] assert intervals(g, inf=Rational(7, 4)) == [] assert intervals(g, inf=Rational(7, 5)) == [((Rational(7, 5), Rational(3, 2)), 2)] assert intervals(g, sup=Rational(7, 4)) == [((-2, -1), 2), ((1, Rational(3, 2)), 2)] assert intervals(g, sup=Rational(7, 5)) == [((-2, -1), 2)] assert intervals([g, h], inf=Rational(7, 4)) == [] assert intervals([g, h], inf=Rational(7, 5)) == [((Rational(7, 5), Rational(3, 2)), {0: 2})] assert intervals([g, h], sup=S( 7)/4) == [((-2, -1), {0: 2}), ((1, 1), {1: 1}), ((1, Rational(3, 2)), {0: 2})] assert intervals( [g, h], sup=Rational(7, 5)) == [((-2, -1), {0: 2}), ((1, 1), {1: 1})] assert intervals([x + 2, x**2 - 2]) == \ [((-2, -2), {0: 1}), ((-2, -1), {1: 1}), ((1, 2), {1: 1})] assert intervals([x + 2, x**2 - 2], strict=True) == \ [((-2, -2), {0: 1}), ((Rational(-3, 2), -1), {1: 1}), ((1, 2), {1: 1})] f = 7*z**4 - 19*z**3 + 20*z**2 + 17*z + 20 assert intervals(f) == [] real_part, complex_part = intervals(f, all=True, sqf=True) assert real_part == [] assert all(re(a) < re(r) < re(b) and im( a) < im(r) < im(b) for (a, b), r in zip(complex_part, nroots(f))) assert complex_part == [(Rational(-40, 7) - I*40/7, 0), (Rational(-40, 7), I*40/7), (I*Rational(-40, 7), Rational(40, 7)), (0, Rational(40, 7) + I*40/7)] real_part, complex_part = intervals(f, all=True, sqf=True, eps=Rational(1, 10)) assert real_part == [] assert all(re(a) < re(r) < re(b) and im( a) < im(r) < im(b) for (a, b), r in zip(complex_part, nroots(f))) raises(ValueError, lambda: intervals(x**2 - 2, eps=10**-100000)) raises(ValueError, lambda: Poly(x**2 - 2).intervals(eps=10**-100000)) raises( ValueError, lambda: intervals([x**2 - 2, x**2 - 3], eps=10**-100000)) def test_refine_root(): f = Poly(x**2 - 2) assert f.refine_root(1, 2, steps=0) == (1, 2) assert f.refine_root(-2, -1, steps=0) == (-2, -1) assert f.refine_root(1, 2, steps=None) == (1, Rational(3, 2)) assert f.refine_root(-2, -1, steps=None) == (Rational(-3, 2), -1) assert f.refine_root(1, 2, steps=1) == (1, Rational(3, 2)) assert f.refine_root(-2, -1, steps=1) == (Rational(-3, 2), -1) assert f.refine_root(1, 2, steps=1, fast=True) == (1, Rational(3, 2)) assert f.refine_root(-2, -1, steps=1, fast=True) == (Rational(-3, 2), -1) assert f.refine_root(1, 2, eps=Rational(1, 100)) == (Rational(24, 17), Rational(17, 12)) assert f.refine_root(1, 2, eps=1e-2) == (Rational(24, 17), Rational(17, 12)) raises(PolynomialError, lambda: (f**2).refine_root(1, 2, check_sqf=True)) raises(RefinementFailed, lambda: (f**2).refine_root(1, 2)) raises(RefinementFailed, lambda: (f**2).refine_root(2, 3)) f = x**2 - 2 assert refine_root(f, 1, 2, steps=1) == (1, Rational(3, 2)) assert refine_root(f, -2, -1, steps=1) == (Rational(-3, 2), -1) assert refine_root(f, 1, 2, steps=1, fast=True) == (1, Rational(3, 2)) assert refine_root(f, -2, -1, steps=1, fast=True) == (Rational(-3, 2), -1) assert refine_root(f, 1, 2, eps=Rational(1, 100)) == (Rational(24, 17), Rational(17, 12)) assert refine_root(f, 1, 2, eps=1e-2) == (Rational(24, 17), Rational(17, 12)) raises(PolynomialError, lambda: refine_root(1, 7, 8, eps=Rational(1, 100))) raises(ValueError, lambda: Poly(f).refine_root(1, 2, eps=10**-100000)) raises(ValueError, lambda: refine_root(f, 1, 2, eps=10**-100000)) def test_count_roots(): assert count_roots(x**2 - 2) == 2 assert count_roots(x**2 - 2, inf=-oo) == 2 assert count_roots(x**2 - 2, sup=+oo) == 2 assert count_roots(x**2 - 2, inf=-oo, sup=+oo) == 2 assert count_roots(x**2 - 2, inf=-2) == 2 assert count_roots(x**2 - 2, inf=-1) == 1 assert count_roots(x**2 - 2, sup=1) == 1 assert count_roots(x**2 - 2, sup=2) == 2 assert count_roots(x**2 - 2, inf=-1, sup=1) == 0 assert count_roots(x**2 - 2, inf=-2, sup=2) == 2 assert count_roots(x**2 - 2, inf=-1, sup=1) == 0 assert count_roots(x**2 - 2, inf=-2, sup=2) == 2 assert count_roots(x**2 + 2) == 0 assert count_roots(x**2 + 2, inf=-2*I) == 2 assert count_roots(x**2 + 2, sup=+2*I) == 2 assert count_roots(x**2 + 2, inf=-2*I, sup=+2*I) == 2 assert count_roots(x**2 + 2, inf=0) == 0 assert count_roots(x**2 + 2, sup=0) == 0 assert count_roots(x**2 + 2, inf=-I) == 1 assert count_roots(x**2 + 2, sup=+I) == 1 assert count_roots(x**2 + 2, inf=+I/2, sup=+I) == 0 assert count_roots(x**2 + 2, inf=-I, sup=-I/2) == 0 raises(PolynomialError, lambda: count_roots(1)) def test_Poly_root(): f = Poly(2*x**3 - 7*x**2 + 4*x + 4) assert f.root(0) == Rational(-1, 2) assert f.root(1) == 2 assert f.root(2) == 2 raises(IndexError, lambda: f.root(3)) assert Poly(x**5 + x + 1).root(0) == rootof(x**3 - x**2 + 1, 0) def test_real_roots(): assert real_roots(x) == [0] assert real_roots(x, multiple=False) == [(0, 1)] assert real_roots(x**3) == [0, 0, 0] assert real_roots(x**3, multiple=False) == [(0, 3)] assert real_roots(x*(x**3 + x + 3)) == [rootof(x**3 + x + 3, 0), 0] assert real_roots(x*(x**3 + x + 3), multiple=False) == [(rootof( x**3 + x + 3, 0), 1), (0, 1)] assert real_roots( x**3*(x**3 + x + 3)) == [rootof(x**3 + x + 3, 0), 0, 0, 0] assert real_roots(x**3*(x**3 + x + 3), multiple=False) == [(rootof( x**3 + x + 3, 0), 1), (0, 3)] f = 2*x**3 - 7*x**2 + 4*x + 4 g = x**3 + x + 1 assert Poly(f).real_roots() == [Rational(-1, 2), 2, 2] assert Poly(g).real_roots() == [rootof(g, 0)] def test_all_roots(): f = 2*x**3 - 7*x**2 + 4*x + 4 g = x**3 + x + 1 assert Poly(f).all_roots() == [Rational(-1, 2), 2, 2] assert Poly(g).all_roots() == [rootof(g, 0), rootof(g, 1), rootof(g, 2)] def test_nroots(): assert Poly(0, x).nroots() == [] assert Poly(1, x).nroots() == [] assert Poly(x**2 - 1, x).nroots() == [-1.0, 1.0] assert Poly(x**2 + 1, x).nroots() == [-1.0*I, 1.0*I] roots = Poly(x**2 - 1, x).nroots() assert roots == [-1.0, 1.0] roots = Poly(x**2 + 1, x).nroots() assert roots == [-1.0*I, 1.0*I] roots = Poly(x**2/3 - Rational(1, 3), x).nroots() assert roots == [-1.0, 1.0] roots = Poly(x**2/3 + Rational(1, 3), x).nroots() assert roots == [-1.0*I, 1.0*I] assert Poly(x**2 + 2*I, x).nroots() == [-1.0 + 1.0*I, 1.0 - 1.0*I] assert Poly( x**2 + 2*I, x, extension=I).nroots() == [-1.0 + 1.0*I, 1.0 - 1.0*I] assert Poly(0.2*x + 0.1).nroots() == [-0.5] roots = nroots(x**5 + x + 1, n=5) eps = Float("1e-5") assert re(roots[0]).epsilon_eq(-0.75487, eps) is S.true assert im(roots[0]) == 0.0 assert re(roots[1]) == -0.5 assert im(roots[1]).epsilon_eq(-0.86602, eps) is S.true assert re(roots[2]) == -0.5 assert im(roots[2]).epsilon_eq(+0.86602, eps) is S.true assert re(roots[3]).epsilon_eq(+0.87743, eps) is S.true assert im(roots[3]).epsilon_eq(-0.74486, eps) is S.true assert re(roots[4]).epsilon_eq(+0.87743, eps) is S.true assert im(roots[4]).epsilon_eq(+0.74486, eps) is S.true eps = Float("1e-6") assert re(roots[0]).epsilon_eq(-0.75487, eps) is S.false assert im(roots[0]) == 0.0 assert re(roots[1]) == -0.5 assert im(roots[1]).epsilon_eq(-0.86602, eps) is S.false assert re(roots[2]) == -0.5 assert im(roots[2]).epsilon_eq(+0.86602, eps) is S.false assert re(roots[3]).epsilon_eq(+0.87743, eps) is S.false assert im(roots[3]).epsilon_eq(-0.74486, eps) is S.false assert re(roots[4]).epsilon_eq(+0.87743, eps) is S.false assert im(roots[4]).epsilon_eq(+0.74486, eps) is S.false raises(DomainError, lambda: Poly(x + y, x).nroots()) raises(MultivariatePolynomialError, lambda: Poly(x + y).nroots()) assert nroots(x**2 - 1) == [-1.0, 1.0] roots = nroots(x**2 - 1) assert roots == [-1.0, 1.0] assert nroots(x + I) == [-1.0*I] assert nroots(x + 2*I) == [-2.0*I] raises(PolynomialError, lambda: nroots(0)) # issue 8296 f = Poly(x**4 - 1) assert f.nroots(2) == [w.n(2) for w in f.all_roots()] assert str(Poly(x**16 + 32*x**14 + 508*x**12 + 5440*x**10 + 39510*x**8 + 204320*x**6 + 755548*x**4 + 1434496*x**2 + 877969).nroots(2)) == ('[-1.7 - 1.9*I, -1.7 + 1.9*I, -1.7 ' '- 2.5*I, -1.7 + 2.5*I, -1.0*I, 1.0*I, -1.7*I, 1.7*I, -2.8*I, ' '2.8*I, -3.4*I, 3.4*I, 1.7 - 1.9*I, 1.7 + 1.9*I, 1.7 - 2.5*I, ' '1.7 + 2.5*I]') assert str(Poly(1e-15*x**2 -1).nroots()) == ('[-31622776.6016838, 31622776.6016838]') def test_ground_roots(): f = x**6 - 4*x**4 + 4*x**3 - x**2 assert Poly(f).ground_roots() == {S.One: 2, S.Zero: 2} assert ground_roots(f) == {S.One: 2, S.Zero: 2} def test_nth_power_roots_poly(): f = x**4 - x**2 + 1 f_2 = (x**2 - x + 1)**2 f_3 = (x**2 + 1)**2 f_4 = (x**2 + x + 1)**2 f_12 = (x - 1)**4 assert nth_power_roots_poly(f, 1) == f raises(ValueError, lambda: nth_power_roots_poly(f, 0)) raises(ValueError, lambda: nth_power_roots_poly(f, x)) assert factor(nth_power_roots_poly(f, 2)) == f_2 assert factor(nth_power_roots_poly(f, 3)) == f_3 assert factor(nth_power_roots_poly(f, 4)) == f_4 assert factor(nth_power_roots_poly(f, 12)) == f_12 raises(MultivariatePolynomialError, lambda: nth_power_roots_poly( x + y, 2, x, y)) def test_torational_factor_list(): p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + sqrt(2))})) assert _torational_factor_list(p, x) == (-2, [ (-x*(1 + sqrt(2))/2 + 1, 1), (-x*(1 + sqrt(2)) - 1, 1), (-x*(1 + sqrt(2)) + 1, 1)]) p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + 2**Rational(1, 4))})) assert _torational_factor_list(p, x) is None def test_cancel(): assert cancel(0) == 0 assert cancel(7) == 7 assert cancel(x) == x assert cancel(oo) is oo assert cancel((2, 3)) == (1, 2, 3) assert cancel((1, 0), x) == (1, 1, 0) assert cancel((0, 1), x) == (1, 0, 1) f, g, p, q = 4*x**2 - 4, 2*x - 2, 2*x + 2, 1 F, G, P, Q = [ Poly(u, x) for u in (f, g, p, q) ] assert F.cancel(G) == (1, P, Q) assert cancel((f, g)) == (1, p, q) assert cancel((f, g), x) == (1, p, q) assert cancel((f, g), (x,)) == (1, p, q) assert cancel((F, G)) == (1, P, Q) assert cancel((f, g), polys=True) == (1, P, Q) assert cancel((F, G), polys=False) == (1, p, q) f = (x**2 - 2)/(x + sqrt(2)) assert cancel(f) == f assert cancel(f, greedy=False) == x - sqrt(2) f = (x**2 - 2)/(x - sqrt(2)) assert cancel(f) == f assert cancel(f, greedy=False) == x + sqrt(2) assert cancel((x**2/4 - 1, x/2 - 1)) == (1, x + 2, 2) # assert cancel((x**2/4 - 1, x/2 - 1)) == (S.Half, x + 2, 1) assert cancel((x**2 - y)/(x - y)) == 1/(x - y)*(x**2 - y) assert cancel((x**2 - y**2)/(x - y), x) == x + y assert cancel((x**2 - y**2)/(x - y), y) == x + y assert cancel((x**2 - y**2)/(x - y)) == x + y assert cancel((x**3 - 1)/(x**2 - 1)) == (x**2 + x + 1)/(x + 1) assert cancel((x**3/2 - S.Half)/(x**2 - 1)) == (x**2 + x + 1)/(2*x + 2) assert cancel((exp(2*x) + 2*exp(x) + 1)/(exp(x) + 1)) == exp(x) + 1 f = Poly(x**2 - a**2, x) g = Poly(x - a, x) F = Poly(x + a, x, domain='ZZ[a]') G = Poly(1, x, domain='ZZ[a]') assert cancel((f, g)) == (1, F, G) f = x**3 + (sqrt(2) - 2)*x**2 - (2*sqrt(2) + 3)*x - 3*sqrt(2) g = x**2 - 2 assert cancel((f, g), extension=True) == (1, x**2 - 2*x - 3, x - sqrt(2)) f = Poly(-2*x + 3, x) g = Poly(-x**9 + x**8 + x**6 - x**5 + 2*x**2 - 3*x + 1, x) assert cancel((f, g)) == (1, -f, -g) f = Poly(y, y, domain='ZZ(x)') g = Poly(1, y, domain='ZZ[x]') assert f.cancel( g) == (1, Poly(y, y, domain='ZZ(x)'), Poly(1, y, domain='ZZ(x)')) assert f.cancel(g, include=True) == ( Poly(y, y, domain='ZZ(x)'), Poly(1, y, domain='ZZ(x)')) f = Poly(5*x*y + x, y, domain='ZZ(x)') g = Poly(2*x**2*y, y, domain='ZZ(x)') assert f.cancel(g, include=True) == ( Poly(5*y + 1, y, domain='ZZ(x)'), Poly(2*x*y, y, domain='ZZ(x)')) f = -(-2*x - 4*y + 0.005*(z - y)**2)/((z - y)*(-z + y + 2)) assert cancel(f).is_Mul == True P = tanh(x - 3.0) Q = tanh(x + 3.0) f = ((-2*P**2 + 2)*(-P**2 + 1)*Q**2/2 + (-2*P**2 + 2)*(-2*Q**2 + 2)*P*Q - (-2*P**2 + 2)*P**2*Q**2 + (-2*Q**2 + 2)*(-Q**2 + 1)*P**2/2 - (-2*Q**2 + 2)*P**2*Q**2)/(2*sqrt(P**2*Q**2 + 0.0001)) \ + (-(-2*P**2 + 2)*P*Q**2/2 - (-2*Q**2 + 2)*P**2*Q/2)*((-2*P**2 + 2)*P*Q**2/2 + (-2*Q**2 + 2)*P**2*Q/2)/(2*(P**2*Q**2 + 0.0001)**Rational(3, 2)) assert cancel(f).is_Mul == True # issue 7022 A = Symbol('A', commutative=False) p1 = Piecewise((A*(x**2 - 1)/(x + 1), x > 1), ((x + 2)/(x**2 + 2*x), True)) p2 = Piecewise((A*(x - 1), x > 1), (1/x, True)) assert cancel(p1) == p2 assert cancel(2*p1) == 2*p2 assert cancel(1 + p1) == 1 + p2 assert cancel((x**2 - 1)/(x + 1)*p1) == (x - 1)*p2 assert cancel((x**2 - 1)/(x + 1) + p1) == (x - 1) + p2 p3 = Piecewise(((x**2 - 1)/(x + 1), x > 1), ((x + 2)/(x**2 + 2*x), True)) p4 = Piecewise(((x - 1), x > 1), (1/x, True)) assert cancel(p3) == p4 assert cancel(2*p3) == 2*p4 assert cancel(1 + p3) == 1 + p4 assert cancel((x**2 - 1)/(x + 1)*p3) == (x - 1)*p4 assert cancel((x**2 - 1)/(x + 1) + p3) == (x - 1) + p4 # issue 4077 q = S('''(2*1*(x - 1/x)/(x*(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x)) - 2*1*((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))*((-x + 1/x)*((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x) + 1)*((x - 1/x)/((x - 1/x)**2) - ((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))**2/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x) - 1/(x - 1/x))*(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x)/x - 1/x)*(((-x + 1/x)/((x*(x - 1/x)**2)) + 1/(x*(x - 1/x)))*((-(x - 1/x)/(x*(x - 1/x)) - 1/x)*((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x) - 1 + (x - 1/x)/(x - 1/x))/((x*((x - 1/x)/((x - 1/x)**2) - ((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))**2/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x) - 1/(x - 1/x))*(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x))) + ((x - 1/x)/((x*(x - 1/x))) + 1/x)/((x*(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x))) + 1/x)/(2*x + 2*((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))*((-(x - 1/x)/(x*(x - 1/x)) - 1/x)*((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x) - 1 + (x - 1/x)/(x - 1/x))/((x*((x - 1/x)/((x - 1/x)**2) - ((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))**2/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x) - 1/(x - 1/x))*(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x))) - 2*((x - 1/x)/((x*(x - 1/x))) + 1/x)/(x*(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x)) - 2/x) - ((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))*((-x + 1/x)*((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x) + 1)/(x*((x - 1/x)/((x - 1/x)**2) - ((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))**2/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x) - 1/(x - 1/x))*(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x)) + (x - 1/x)/((x*(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x))) - 1/x''', evaluate=False) assert cancel(q, _signsimp=False) is S.NaN assert q.subs(x, 2) is S.NaN assert signsimp(q) is S.NaN # issue 9363 M = MatrixSymbol('M', 5, 5) assert cancel(M[0,0] + 7) == M[0,0] + 7 expr = sin(M[1, 4] + M[2, 1] * 5 * M[4, 0]) - 5 * M[1, 2] / z assert cancel(expr) == (z*sin(M[1, 4] + M[2, 1] * 5 * M[4, 0]) - 5 * M[1, 2]) / z assert cancel((x**2 + 1)/(x - I)) == x + I def test_reduced(): f = 2*x**4 + y**2 - x**2 + y**3 G = [x**3 - x, y**3 - y] Q = [2*x, 1] r = x**2 + y**2 + y assert reduced(f, G) == (Q, r) assert reduced(f, G, x, y) == (Q, r) H = groebner(G) assert H.reduce(f) == (Q, r) Q = [Poly(2*x, x, y), Poly(1, x, y)] r = Poly(x**2 + y**2 + y, x, y) assert _strict_eq(reduced(f, G, polys=True), (Q, r)) assert _strict_eq(reduced(f, G, x, y, polys=True), (Q, r)) H = groebner(G, polys=True) assert _strict_eq(H.reduce(f), (Q, r)) f = 2*x**3 + y**3 + 3*y G = groebner([x**2 + y**2 - 1, x*y - 2]) Q = [x**2 - x*y**3/2 + x*y/2 + y**6/4 - y**4/2 + y**2/4, -y**5/4 + y**3/2 + y*Rational(3, 4)] r = 0 assert reduced(f, G) == (Q, r) assert G.reduce(f) == (Q, r) assert reduced(f, G, auto=False)[1] != 0 assert G.reduce(f, auto=False)[1] != 0 assert G.contains(f) is True assert G.contains(f + 1) is False assert reduced(1, [1], x) == ([1], 0) raises(ComputationFailed, lambda: reduced(1, [1])) def test_groebner(): assert groebner([], x, y, z) == [] assert groebner([x**2 + 1, y**4*x + x**3], x, y, order='lex') == [1 + x**2, -1 + y**4] assert groebner([x**2 + 1, y**4*x + x**3, x*y*z**3], x, y, z, order='grevlex') == [-1 + y**4, z**3, 1 + x**2] assert groebner([x**2 + 1, y**4*x + x**3], x, y, order='lex', polys=True) == \ [Poly(1 + x**2, x, y), Poly(-1 + y**4, x, y)] assert groebner([x**2 + 1, y**4*x + x**3, x*y*z**3], x, y, z, order='grevlex', polys=True) == \ [Poly(-1 + y**4, x, y, z), Poly(z**3, x, y, z), Poly(1 + x**2, x, y, z)] assert groebner([x**3 - 1, x**2 - 1]) == [x - 1] assert groebner([Eq(x**3, 1), Eq(x**2, 1)]) == [x - 1] F = [3*x**2 + y*z - 5*x - 1, 2*x + 3*x*y + y**2, x - 3*y + x*z - 2*z**2] f = z**9 - x**2*y**3 - 3*x*y**2*z + 11*y*z**2 + x**2*z**2 - 5 G = groebner(F, x, y, z, modulus=7, symmetric=False) assert G == [1 + x + y + 3*z + 2*z**2 + 2*z**3 + 6*z**4 + z**5, 1 + 3*y + y**2 + 6*z**2 + 3*z**3 + 3*z**4 + 3*z**5 + 4*z**6, 1 + 4*y + 4*z + y*z + 4*z**3 + z**4 + z**6, 6 + 6*z + z**2 + 4*z**3 + 3*z**4 + 6*z**5 + 3*z**6 + z**7] Q, r = reduced(f, G, x, y, z, modulus=7, symmetric=False, polys=True) assert sum([ q*g for q, g in zip(Q, G.polys)], r) == Poly(f, modulus=7) F = [x*y - 2*y, 2*y**2 - x**2] assert groebner(F, x, y, order='grevlex') == \ [y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y] assert groebner(F, y, x, order='grevlex') == \ [x**3 - 2*x**2, -x**2 + 2*y**2, x*y - 2*y] assert groebner(F, order='grevlex', field=True) == \ [y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y] assert groebner([1], x) == [1] assert groebner([x**2 + 2.0*y], x, y) == [1.0*x**2 + 2.0*y] raises(ComputationFailed, lambda: groebner([1])) assert groebner([x**2 - 1, x**3 + 1], method='buchberger') == [x + 1] assert groebner([x**2 - 1, x**3 + 1], method='f5b') == [x + 1] raises(ValueError, lambda: groebner([x, y], method='unknown')) def test_fglm(): F = [a + b + c + d, a*b + a*d + b*c + b*d, a*b*c + a*b*d + a*c*d + b*c*d, a*b*c*d - 1] G = groebner(F, a, b, c, d, order=grlex) B = [ 4*a + 3*d**9 - 4*d**5 - 3*d, 4*b + 4*c - 3*d**9 + 4*d**5 + 7*d, 4*c**2 + 3*d**10 - 4*d**6 - 3*d**2, 4*c*d**4 + 4*c - d**9 + 4*d**5 + 5*d, d**12 - d**8 - d**4 + 1, ] assert groebner(F, a, b, c, d, order=lex) == B assert G.fglm(lex) == B F = [9*x**8 + 36*x**7 - 32*x**6 - 252*x**5 - 78*x**4 + 468*x**3 + 288*x**2 - 108*x + 9, -72*t*x**7 - 252*t*x**6 + 192*t*x**5 + 1260*t*x**4 + 312*t*x**3 - 404*t*x**2 - 576*t*x + \ 108*t - 72*x**7 - 256*x**6 + 192*x**5 + 1280*x**4 + 312*x**3 - 576*x + 96] G = groebner(F, t, x, order=grlex) B = [ 203577793572507451707*t + 627982239411707112*x**7 - 666924143779443762*x**6 - \ 10874593056632447619*x**5 + 5119998792707079562*x**4 + 72917161949456066376*x**3 + \ 20362663855832380362*x**2 - 142079311455258371571*x + 183756699868981873194, 9*x**8 + 36*x**7 - 32*x**6 - 252*x**5 - 78*x**4 + 468*x**3 + 288*x**2 - 108*x + 9, ] assert groebner(F, t, x, order=lex) == B assert G.fglm(lex) == B F = [x**2 - x - 3*y + 1, -2*x + y**2 + y - 1] G = groebner(F, x, y, order=lex) B = [ x**2 - x - 3*y + 1, y**2 - 2*x + y - 1, ] assert groebner(F, x, y, order=grlex) == B assert G.fglm(grlex) == B def test_is_zero_dimensional(): assert is_zero_dimensional([x, y], x, y) is True assert is_zero_dimensional([x**3 + y**2], x, y) is False assert is_zero_dimensional([x, y, z], x, y, z) is True assert is_zero_dimensional([x, y, z], x, y, z, t) is False F = [x*y - z, y*z - x, x*y - y] assert is_zero_dimensional(F, x, y, z) is True F = [x**2 - 2*x*z + 5, x*y**2 + y*z**3, 3*y**2 - 8*z**2] assert is_zero_dimensional(F, x, y, z) is True def test_GroebnerBasis(): F = [x*y - 2*y, 2*y**2 - x**2] G = groebner(F, x, y, order='grevlex') H = [y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y] P = [ Poly(h, x, y) for h in H ] assert groebner(F + [0], x, y, order='grevlex') == G assert isinstance(G, GroebnerBasis) is True assert len(G) == 3 assert G[0] == H[0] and not G[0].is_Poly assert G[1] == H[1] and not G[1].is_Poly assert G[2] == H[2] and not G[2].is_Poly assert G[1:] == H[1:] and not any(g.is_Poly for g in G[1:]) assert G[:2] == H[:2] and not any(g.is_Poly for g in G[1:]) assert G.exprs == H assert G.polys == P assert G.gens == (x, y) assert G.domain == ZZ assert G.order == grevlex assert G == H assert G == tuple(H) assert G == P assert G == tuple(P) assert G != [] G = groebner(F, x, y, order='grevlex', polys=True) assert G[0] == P[0] and G[0].is_Poly assert G[1] == P[1] and G[1].is_Poly assert G[2] == P[2] and G[2].is_Poly assert G[1:] == P[1:] and all(g.is_Poly for g in G[1:]) assert G[:2] == P[:2] and all(g.is_Poly for g in G[1:]) def test_poly(): assert poly(x) == Poly(x, x) assert poly(y) == Poly(y, y) assert poly(x + y) == Poly(x + y, x, y) assert poly(x + sin(x)) == Poly(x + sin(x), x, sin(x)) assert poly(x + y, wrt=y) == Poly(x + y, y, x) assert poly(x + sin(x), wrt=sin(x)) == Poly(x + sin(x), sin(x), x) assert poly(x*y + 2*x*z**2 + 17) == Poly(x*y + 2*x*z**2 + 17, x, y, z) assert poly(2*(y + z)**2 - 1) == Poly(2*y**2 + 4*y*z + 2*z**2 - 1, y, z) assert poly( x*(y + z)**2 - 1) == Poly(x*y**2 + 2*x*y*z + x*z**2 - 1, x, y, z) assert poly(2*x*( y + z)**2 - 1) == Poly(2*x*y**2 + 4*x*y*z + 2*x*z**2 - 1, x, y, z) assert poly(2*( y + z)**2 - x - 1) == Poly(2*y**2 + 4*y*z + 2*z**2 - x - 1, x, y, z) assert poly(x*( y + z)**2 - x - 1) == Poly(x*y**2 + 2*x*y*z + x*z**2 - x - 1, x, y, z) assert poly(2*x*(y + z)**2 - x - 1) == Poly(2*x*y**2 + 4*x*y*z + 2* x*z**2 - x - 1, x, y, z) assert poly(x*y + (x + y)**2 + (x + z)**2) == \ Poly(2*x*z + 3*x*y + y**2 + z**2 + 2*x**2, x, y, z) assert poly(x*y*(x + y)*(x + z)**2) == \ Poly(x**3*y**2 + x*y**2*z**2 + y*x**2*z**2 + 2*z*x**2* y**2 + 2*y*z*x**3 + y*x**4, x, y, z) assert poly(Poly(x + y + z, y, x, z)) == Poly(x + y + z, y, x, z) assert poly((x + y)**2, x) == Poly(x**2 + 2*x*y + y**2, x, domain=ZZ[y]) assert poly((x + y)**2, y) == Poly(x**2 + 2*x*y + y**2, y, domain=ZZ[x]) assert poly(1, x) == Poly(1, x) raises(GeneratorsNeeded, lambda: poly(1)) # issue 6184 assert poly(x + y, x, y) == Poly(x + y, x, y) assert poly(x + y, y, x) == Poly(x + y, y, x) def test_keep_coeff(): u = Mul(2, x + 1, evaluate=False) assert _keep_coeff(S.One, x) == x assert _keep_coeff(S.NegativeOne, x) == -x assert _keep_coeff(S(1.0), x) == 1.0*x assert _keep_coeff(S(-1.0), x) == -1.0*x assert _keep_coeff(S.One, 2*x) == 2*x assert _keep_coeff(S(2), x/2) == x assert _keep_coeff(S(2), sin(x)) == 2*sin(x) assert _keep_coeff(S(2), x + 1) == u assert _keep_coeff(x, 1/x) == 1 assert _keep_coeff(x + 1, S(2)) == u assert _keep_coeff(S.Half, S.One) == S.Half p = Pow(2, 3, evaluate=False) assert _keep_coeff(S(-1), p) == Mul(-1, p, evaluate=False) a = Add(2, p, evaluate=False) assert _keep_coeff(S.Half, a, clear=True ) == Mul(S.Half, a, evaluate=False) assert _keep_coeff(S.Half, a, clear=False ) == Add(1, Mul(S.Half, p, evaluate=False), evaluate=False) def test_poly_matching_consistency(): # Test for this issue: # https://github.com/sympy/sympy/issues/5514 assert I * Poly(x, x) == Poly(I*x, x) assert Poly(x, x) * I == Poly(I*x, x) def test_issue_5786(): assert expand(factor(expand( (x - I*y)*(z - I*t)), extension=[I])) == -I*t*x - t*y + x*z - I*y*z def test_noncommutative(): class foo(Expr): is_commutative=False e = x/(x + x*y) c = 1/( 1 + y) assert cancel(foo(e)) == foo(c) assert cancel(e + foo(e)) == c + foo(c) assert cancel(e*foo(c)) == c*foo(c) def test_to_rational_coeffs(): assert to_rational_coeffs( Poly(x**3 + y*x**2 + sqrt(y), x, domain='EX')) is None # issue 21268 assert to_rational_coeffs( Poly(y**3 + sqrt(2)*y**2*sin(x) + 1, y)) is None assert to_rational_coeffs(Poly(x, y)) is None assert to_rational_coeffs(Poly(sqrt(2)*y)) is None def test_factor_terms(): # issue 7067 assert factor_list(x*(x + y)) == (1, [(x, 1), (x + y, 1)]) assert sqf_list(x*(x + y)) == (1, [(x**2 + x*y, 1)]) def test_as_list(): # issue 14496 assert Poly(x**3 + 2, x, domain='ZZ').as_list() == [1, 0, 0, 2] assert Poly(x**2 + y + 1, x, y, domain='ZZ').as_list() == [[1], [], [1, 1]] assert Poly(x**2 + y + 1, x, y, z, domain='ZZ').as_list() == \ [[[1]], [[]], [[1], [1]]] def test_issue_11198(): assert factor_list(sqrt(2)*x) == (sqrt(2), [(x, 1)]) assert factor_list(sqrt(2)*sin(x), sin(x)) == (sqrt(2), [(sin(x), 1)]) def test_Poly_precision(): # Make sure Poly doesn't lose precision p = Poly(pi.evalf(100)*x) assert p.as_expr() == pi.evalf(100)*x def test_issue_12400(): # Correction of check for negative exponents assert poly(1/(1+sqrt(2)), x) == \ Poly(1/(1+sqrt(2)), x, domain='EX') def test_issue_14364(): assert gcd(S(6)*(1 + sqrt(3))/5, S(3)*(1 + sqrt(3))/10) == Rational(3, 10) * (1 + sqrt(3)) assert gcd(sqrt(5)*Rational(4, 7), sqrt(5)*Rational(2, 3)) == sqrt(5)*Rational(2, 21) assert lcm(Rational(2, 3)*sqrt(3), Rational(5, 6)*sqrt(3)) == S(10)*sqrt(3)/3 assert lcm(3*sqrt(3), 4/sqrt(3)) == 12*sqrt(3) assert lcm(S(5)*(1 + 2**Rational(1, 3))/6, S(3)*(1 + 2**Rational(1, 3))/8) == Rational(15, 2) * (1 + 2**Rational(1, 3)) assert gcd(Rational(2, 3)*sqrt(3), Rational(5, 6)/sqrt(3)) == sqrt(3)/18 assert gcd(S(4)*sqrt(13)/7, S(3)*sqrt(13)/14) == sqrt(13)/14 # gcd_list and lcm_list assert gcd([S(2)*sqrt(47)/7, S(6)*sqrt(47)/5, S(8)*sqrt(47)/5]) == sqrt(47)*Rational(2, 35) assert gcd([S(6)*(1 + sqrt(7))/5, S(2)*(1 + sqrt(7))/7, S(4)*(1 + sqrt(7))/13]) == (1 + sqrt(7))*Rational(2, 455) assert lcm((Rational(7, 2)/sqrt(15), Rational(5, 6)/sqrt(15), Rational(5, 8)/sqrt(15))) == Rational(35, 2)/sqrt(15) assert lcm([S(5)*(2 + 2**Rational(5, 7))/6, S(7)*(2 + 2**Rational(5, 7))/2, S(13)*(2 + 2**Rational(5, 7))/4]) == Rational(455, 2) * (2 + 2**Rational(5, 7)) def test_issue_15669(): x = Symbol("x", positive=True) expr = (16*x**3/(-x**2 + sqrt(8*x**2 + (x**2 - 2)**2) + 2)**2 - 2*2**Rational(4, 5)*x*(-x**2 + sqrt(8*x**2 + (x**2 - 2)**2) + 2)**Rational(3, 5) + 10*x) assert factor(expr, deep=True) == x*(x**2 + 2) def test_issue_17988(): x = Symbol('x') p = poly(x - 1) with warns_deprecated_sympy(): M = Matrix([[poly(x + 1), poly(x + 1)]]) with warns_deprecated_sympy(): assert p * M == M * p == Matrix([[poly(x**2 - 1), poly(x**2 - 1)]]) def test_issue_18205(): assert cancel((2 + I)*(3 - I)) == 7 + I assert cancel((2 + I)*(2 - I)) == 5 def test_issue_8695(): p = (x**2 + 1) * (x - 1)**2 * (x - 2)**3 * (x - 3)**3 result = (1, [(x**2 + 1, 1), (x - 1, 2), (x**2 - 5*x + 6, 3)]) assert sqf_list(p) == result def test_issue_19113(): eq = sin(x)**3 - sin(x) + 1 raises(PolynomialError, lambda: refine_root(eq, 1, 2, 1e-2)) raises(PolynomialError, lambda: count_roots(eq, -1, 1)) raises(PolynomialError, lambda: real_roots(eq)) raises(PolynomialError, lambda: nroots(eq)) raises(PolynomialError, lambda: ground_roots(eq)) raises(PolynomialError, lambda: nth_power_roots_poly(eq, 2)) def test_issue_19360(): f = 2*x**2 - 2*sqrt(2)*x*y + y**2 assert factor(f, extension=sqrt(2)) == 2*(x - (sqrt(2)*y/2))**2 f = -I*t*x - t*y + x*z - I*y*z assert factor(f, extension=I) == (x - I*y)*(-I*t + z) def test_poly_copy_equals_original(): poly = Poly(x + y, x, y, z) copy = poly.copy() assert poly == copy, ( "Copied polynomial not equal to original.") assert poly.gens == copy.gens, ( "Copied polynomial has different generators than original.") def test_deserialized_poly_equals_original(): poly = Poly(x + y, x, y, z) deserialized = pickle.loads(pickle.dumps(poly)) assert poly == deserialized, ( "Deserialized polynomial not equal to original.") assert poly.gens == deserialized.gens, ( "Deserialized polynomial has different generators than original.") def test_issue_20389(): result = degree(x * (x + 1) - x ** 2 - x, x) assert result == -oo def test_issue_20985(): from sympy.core.symbol import symbols w, R = symbols('w R') poly = Poly(1.0 + I*w/R, w, 1/R) assert poly.degree() == S(1)