hash
stringlengths
64
64
content
stringlengths
0
1.51M
d4f9288be4cdc6f074a13d49e7f617af269bca21a03de5e2812fefa3fe31feff
from sympy.ntheory.generate import Sieve, sieve from sympy.ntheory.primetest import (mr, is_lucas_prp, is_square, is_strong_lucas_prp, is_extra_strong_lucas_prp, isprime, is_euler_pseudoprime, is_gaussian_prime) from sympy.testing.pytest import slow from sympy.core.numbers import I def test_euler_pseudoprimes(): assert is_euler_pseudoprime(9, 1) == True assert is_euler_pseudoprime(341, 2) == False assert is_euler_pseudoprime(121, 3) == True assert is_euler_pseudoprime(341, 4) == True assert is_euler_pseudoprime(217, 5) == False assert is_euler_pseudoprime(185, 6) == False assert is_euler_pseudoprime(55, 111) == True assert is_euler_pseudoprime(115, 114) == True assert is_euler_pseudoprime(49, 117) == True assert is_euler_pseudoprime(85, 84) == True assert is_euler_pseudoprime(87, 88) == True assert is_euler_pseudoprime(49, 128) == True assert is_euler_pseudoprime(39, 77) == True assert is_euler_pseudoprime(9881, 30) == True assert is_euler_pseudoprime(8841, 29) == False assert is_euler_pseudoprime(8421, 29) == False assert is_euler_pseudoprime(9997, 19) == True def test_is_extra_strong_lucas_prp(): assert is_extra_strong_lucas_prp(4) == False assert is_extra_strong_lucas_prp(989) == True assert is_extra_strong_lucas_prp(10877) == True assert is_extra_strong_lucas_prp(9) == False assert is_extra_strong_lucas_prp(16) == False assert is_extra_strong_lucas_prp(169) == False @slow def test_prps(): oddcomposites = [n for n in range(1, 10**5) if n % 2 and not isprime(n)] # A checksum would be better. assert sum(oddcomposites) == 2045603465 assert [n for n in oddcomposites if mr(n, [2])] == [ 2047, 3277, 4033, 4681, 8321, 15841, 29341, 42799, 49141, 52633, 65281, 74665, 80581, 85489, 88357, 90751] assert [n for n in oddcomposites if mr(n, [3])] == [ 121, 703, 1891, 3281, 8401, 8911, 10585, 12403, 16531, 18721, 19345, 23521, 31621, 44287, 47197, 55969, 63139, 74593, 79003, 82513, 87913, 88573, 97567] assert [n for n in oddcomposites if mr(n, [325])] == [ 9, 25, 27, 49, 65, 81, 325, 341, 343, 697, 1141, 2059, 2149, 3097, 3537, 4033, 4681, 4941, 5833, 6517, 7987, 8911, 12403, 12913, 15043, 16021, 20017, 22261, 23221, 24649, 24929, 31841, 35371, 38503, 43213, 44173, 47197, 50041, 55909, 56033, 58969, 59089, 61337, 65441, 68823, 72641, 76793, 78409, 85879] assert not any(mr(n, [9345883071009581737]) for n in oddcomposites) assert [n for n in oddcomposites if is_lucas_prp(n)] == [ 323, 377, 1159, 1829, 3827, 5459, 5777, 9071, 9179, 10877, 11419, 11663, 13919, 14839, 16109, 16211, 18407, 18971, 19043, 22499, 23407, 24569, 25199, 25877, 26069, 27323, 32759, 34943, 35207, 39059, 39203, 39689, 40309, 44099, 46979, 47879, 50183, 51983, 53663, 56279, 58519, 60377, 63881, 69509, 72389, 73919, 75077, 77219, 79547, 79799, 82983, 84419, 86063, 90287, 94667, 97019, 97439] assert [n for n in oddcomposites if is_strong_lucas_prp(n)] == [ 5459, 5777, 10877, 16109, 18971, 22499, 24569, 25199, 40309, 58519, 75077, 97439] assert [n for n in oddcomposites if is_extra_strong_lucas_prp(n) ] == [ 989, 3239, 5777, 10877, 27971, 29681, 30739, 31631, 39059, 72389, 73919, 75077] def test_isprime(): s = Sieve() s.extend(100000) ps = set(s.primerange(2, 100001)) for n in range(100001): # if (n in ps) != isprime(n): print n assert (n in ps) == isprime(n) assert isprime(179424673) assert isprime(20678048681) assert isprime(1968188556461) assert isprime(2614941710599) assert isprime(65635624165761929287) assert isprime(1162566711635022452267983) assert isprime(77123077103005189615466924501) assert isprime(3991617775553178702574451996736229) assert isprime(273952953553395851092382714516720001799) assert isprime(int(''' 531137992816767098689588206552468627329593117727031923199444138200403\ 559860852242739162502265229285668889329486246501015346579337652707239\ 409519978766587351943831270835393219031728127''')) # Some Mersenne primes assert isprime(2**61 - 1) assert isprime(2**89 - 1) assert isprime(2**607 - 1) # (but not all Mersenne's are primes assert not isprime(2**601 - 1) # pseudoprimes #------------- # to some small bases assert not isprime(2152302898747) assert not isprime(3474749660383) assert not isprime(341550071728321) assert not isprime(3825123056546413051) # passes the base set [2, 3, 7, 61, 24251] assert not isprime(9188353522314541) # large examples assert not isprime(877777777777777777777777) # conjectured psi_12 given at http://mathworld.wolfram.com/StrongPseudoprime.html assert not isprime(318665857834031151167461) # conjectured psi_17 given at http://mathworld.wolfram.com/StrongPseudoprime.html assert not isprime(564132928021909221014087501701) # Arnault's 1993 number; a factor of it is # 400958216639499605418306452084546853005188166041132508774506\ # 204738003217070119624271622319159721973358216316508535816696\ # 9145233813917169287527980445796800452592031836601 assert not isprime(int(''' 803837457453639491257079614341942108138837688287558145837488917522297\ 427376533365218650233616396004545791504202360320876656996676098728404\ 396540823292873879185086916685732826776177102938969773947016708230428\ 687109997439976544144845341155872450633409279022275296229414984230688\ 1685404326457534018329786111298960644845216191652872597534901''')) # Arnault's 1995 number; can be factored as # p1*(313*(p1 - 1) + 1)*(353*(p1 - 1) + 1) where p1 is # 296744956686855105501541746429053327307719917998530433509950\ # 755312768387531717701995942385964281211880336647542183455624\ # 93168782883 assert not isprime(int(''' 288714823805077121267142959713039399197760945927972270092651602419743\ 230379915273311632898314463922594197780311092934965557841894944174093\ 380561511397999942154241693397290542371100275104208013496673175515285\ 922696291677532547504444585610194940420003990443211677661994962953925\ 045269871932907037356403227370127845389912612030924484149472897688540\ 6024976768122077071687938121709811322297802059565867''')) sieve.extend(3000) assert isprime(2819) assert not isprime(2931) assert not isprime(2.0) def test_is_square(): assert [i for i in range(25) if is_square(i)] == [0, 1, 4, 9, 16] # issue #17044 assert not is_square(60 ** 3) assert not is_square(60 ** 5) assert not is_square(84 ** 7) assert not is_square(105 ** 9) assert not is_square(120 ** 3) def test_is_gaussianprime(): assert is_gaussian_prime(7*I) assert is_gaussian_prime(7) assert is_gaussian_prime(2 + 3*I) assert not is_gaussian_prime(2 + 2*I)
e9cc79adb50a57bbb613254b071baa5fde066cb5e6518029059807ec2eb41056
from sympy.concrete.summations import summation from sympy.core.containers import Dict from sympy.core.mul import Mul from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.functions.combinatorial.factorials import factorial as fac from sympy.core.evalf import bitcount from sympy.core.numbers import Integer, Rational from sympy.ntheory import (totient, factorint, primefactors, divisors, nextprime, primerange, pollard_rho, perfect_power, multiplicity, multiplicity_in_factorial, trailing, divisor_count, primorial, pollard_pm1, divisor_sigma, factorrat, reduced_totient) from sympy.ntheory.factor_ import (smoothness, smoothness_p, proper_divisors, antidivisors, antidivisor_count, core, udivisors, udivisor_sigma, udivisor_count, proper_divisor_count, primenu, primeomega, small_trailing, mersenne_prime_exponent, is_perfect, is_mersenne_prime, is_abundant, is_deficient, is_amicable, dra, drm) from sympy.testing.pytest import raises, slow from sympy.utilities.iterables import capture def fac_multiplicity(n, p): """Return the power of the prime number p in the factorization of n!""" if p > n: return 0 if p > n//2: return 1 q, m = n, 0 while q >= p: q //= p m += q return m def multiproduct(seq=(), start=1): """ Return the product of a sequence of factors with multiplicities, times the value of the parameter ``start``. The input may be a sequence of (factor, exponent) pairs or a dict of such pairs. >>> multiproduct({3:7, 2:5}, 4) # = 3**7 * 2**5 * 4 279936 """ if not seq: return start if isinstance(seq, dict): seq = iter(seq.items()) units = start multi = [] for base, exp in seq: if not exp: continue elif exp == 1: units *= base else: if exp % 2: units *= base multi.append((base, exp//2)) return units * multiproduct(multi)**2 def test_trailing_bitcount(): assert trailing(0) == 0 assert trailing(1) == 0 assert trailing(-1) == 0 assert trailing(2) == 1 assert trailing(7) == 0 assert trailing(-7) == 0 for i in range(100): assert trailing(1 << i) == i assert trailing((1 << i) * 31337) == i assert trailing(1 << 1000001) == 1000001 assert trailing((1 << 273956)*7**37) == 273956 # issue 12709 big = small_trailing[-1]*2 assert trailing(-big) == trailing(big) assert bitcount(-big) == bitcount(big) def test_multiplicity(): for b in range(2, 20): for i in range(100): assert multiplicity(b, b**i) == i assert multiplicity(b, (b**i) * 23) == i assert multiplicity(b, (b**i) * 1000249) == i # Should be fast assert multiplicity(10, 10**10023) == 10023 # Should exit quickly assert multiplicity(10**10, 10**10) == 1 # Should raise errors for bad input raises(ValueError, lambda: multiplicity(1, 1)) raises(ValueError, lambda: multiplicity(1, 2)) raises(ValueError, lambda: multiplicity(1.3, 2)) raises(ValueError, lambda: multiplicity(2, 0)) raises(ValueError, lambda: multiplicity(1.3, 0)) # handles Rationals assert multiplicity(10, Rational(30, 7)) == 1 assert multiplicity(Rational(2, 7), Rational(4, 7)) == 1 assert multiplicity(Rational(1, 7), Rational(3, 49)) == 2 assert multiplicity(Rational(2, 7), Rational(7, 2)) == -1 assert multiplicity(3, Rational(1, 9)) == -2 def test_multiplicity_in_factorial(): n = fac(1000) for i in (2, 4, 6, 12, 30, 36, 48, 60, 72, 96): assert multiplicity(i, n) == multiplicity_in_factorial(i, 1000) def test_perfect_power(): raises(ValueError, lambda: perfect_power(0)) raises(ValueError, lambda: perfect_power(Rational(25, 4))) assert perfect_power(1) is False assert perfect_power(2) is False assert perfect_power(3) is False assert perfect_power(4) == (2, 2) assert perfect_power(14) is False assert perfect_power(25) == (5, 2) assert perfect_power(22) is False assert perfect_power(22, [2]) is False assert perfect_power(137**(3*5*13)) == (137, 3*5*13) assert perfect_power(137**(3*5*13) + 1) is False assert perfect_power(137**(3*5*13) - 1) is False assert perfect_power(103005006004**7) == (103005006004, 7) assert perfect_power(103005006004**7 + 1) is False assert perfect_power(103005006004**7 - 1) is False assert perfect_power(103005006004**12) == (103005006004, 12) assert perfect_power(103005006004**12 + 1) is False assert perfect_power(103005006004**12 - 1) is False assert perfect_power(2**10007) == (2, 10007) assert perfect_power(2**10007 + 1) is False assert perfect_power(2**10007 - 1) is False assert perfect_power((9**99 + 1)**60) == (9**99 + 1, 60) assert perfect_power((9**99 + 1)**60 + 1) is False assert perfect_power((9**99 + 1)**60 - 1) is False assert perfect_power((10**40000)**2, big=False) == (10**40000, 2) assert perfect_power(10**100000) == (10, 100000) assert perfect_power(10**100001) == (10, 100001) assert perfect_power(13**4, [3, 5]) is False assert perfect_power(3**4, [3, 10], factor=0) is False assert perfect_power(3**3*5**3) == (15, 3) assert perfect_power(2**3*5**5) is False assert perfect_power(2*13**4) is False assert perfect_power(2**5*3**3) is False t = 2**24 for d in divisors(24): m = perfect_power(t*3**d) assert m and m[1] == d or d == 1 m = perfect_power(t*3**d, big=False) assert m and m[1] == 2 or d == 1 or d == 3, (d, m) @slow def test_factorint(): assert primefactors(123456) == [2, 3, 643] assert factorint(0) == {0: 1} assert factorint(1) == {} assert factorint(-1) == {-1: 1} assert factorint(-2) == {-1: 1, 2: 1} assert factorint(-16) == {-1: 1, 2: 4} assert factorint(2) == {2: 1} assert factorint(126) == {2: 1, 3: 2, 7: 1} assert factorint(123456) == {2: 6, 3: 1, 643: 1} assert factorint(5951757) == {3: 1, 7: 1, 29: 2, 337: 1} assert factorint(64015937) == {7993: 1, 8009: 1} assert factorint(2**(2**6) + 1) == {274177: 1, 67280421310721: 1} #issue 19683 assert factorint(10**38 - 1) == {3: 2, 11: 1, 909090909090909091: 1, 1111111111111111111: 1} #issue 17676 assert factorint(28300421052393658575) == {3: 1, 5: 2, 11: 2, 43: 1, 2063: 2, 4127: 1, 4129: 1} assert factorint(2063**2 * 4127**1 * 4129**1) == {2063: 2, 4127: 1, 4129: 1} assert factorint(2347**2 * 7039**1 * 7043**1) == {2347: 2, 7039: 1, 7043: 1} assert factorint(0, multiple=True) == [0] assert factorint(1, multiple=True) == [] assert factorint(-1, multiple=True) == [-1] assert factorint(-2, multiple=True) == [-1, 2] assert factorint(-16, multiple=True) == [-1, 2, 2, 2, 2] assert factorint(2, multiple=True) == [2] assert factorint(24, multiple=True) == [2, 2, 2, 3] assert factorint(126, multiple=True) == [2, 3, 3, 7] assert factorint(123456, multiple=True) == [2, 2, 2, 2, 2, 2, 3, 643] assert factorint(5951757, multiple=True) == [3, 7, 29, 29, 337] assert factorint(64015937, multiple=True) == [7993, 8009] assert factorint(2**(2**6) + 1, multiple=True) == [274177, 67280421310721] assert factorint(fac(1, evaluate=False)) == {} assert factorint(fac(7, evaluate=False)) == {2: 4, 3: 2, 5: 1, 7: 1} assert factorint(fac(15, evaluate=False)) == \ {2: 11, 3: 6, 5: 3, 7: 2, 11: 1, 13: 1} assert factorint(fac(20, evaluate=False)) == \ {2: 18, 3: 8, 5: 4, 7: 2, 11: 1, 13: 1, 17: 1, 19: 1} assert factorint(fac(23, evaluate=False)) == \ {2: 19, 3: 9, 5: 4, 7: 3, 11: 2, 13: 1, 17: 1, 19: 1, 23: 1} assert multiproduct(factorint(fac(200))) == fac(200) assert multiproduct(factorint(fac(200, evaluate=False))) == fac(200) for b, e in factorint(fac(150)).items(): assert e == fac_multiplicity(150, b) for b, e in factorint(fac(150, evaluate=False)).items(): assert e == fac_multiplicity(150, b) assert factorint(103005006059**7) == {103005006059: 7} assert factorint(31337**191) == {31337: 191} assert factorint(2**1000 * 3**500 * 257**127 * 383**60) == \ {2: 1000, 3: 500, 257: 127, 383: 60} assert len(factorint(fac(10000))) == 1229 assert len(factorint(fac(10000, evaluate=False))) == 1229 assert factorint(12932983746293756928584532764589230) == \ {2: 1, 5: 1, 73: 1, 727719592270351: 1, 63564265087747: 1, 383: 1} assert factorint(727719592270351) == {727719592270351: 1} assert factorint(2**64 + 1, use_trial=False) == factorint(2**64 + 1) for n in range(60000): assert multiproduct(factorint(n)) == n assert pollard_rho(2**64 + 1, seed=1) == 274177 assert pollard_rho(19, seed=1) is None assert factorint(3, limit=2) == {3: 1} assert factorint(12345) == {3: 1, 5: 1, 823: 1} assert factorint( 12345, limit=3) == {4115: 1, 3: 1} # the 5 is greater than the limit assert factorint(1, limit=1) == {} assert factorint(0, 3) == {0: 1} assert factorint(12, limit=1) == {12: 1} assert factorint(30, limit=2) == {2: 1, 15: 1} assert factorint(16, limit=2) == {2: 4} assert factorint(124, limit=3) == {2: 2, 31: 1} assert factorint(4*31**2, limit=3) == {2: 2, 31: 2} p1 = nextprime(2**32) p2 = nextprime(2**16) p3 = nextprime(p2) assert factorint(p1*p2*p3) == {p1: 1, p2: 1, p3: 1} assert factorint(13*17*19, limit=15) == {13: 1, 17*19: 1} assert factorint(1951*15013*15053, limit=2000) == {225990689: 1, 1951: 1} assert factorint(primorial(17) + 1, use_pm1=0) == \ {int(19026377261): 1, 3467: 1, 277: 1, 105229: 1} # when prime b is closer than approx sqrt(8*p) to prime p then they are # "close" and have a trivial factorization a = nextprime(2**2**8) # 78 digits b = nextprime(a + 2**2**4) assert 'Fermat' in capture(lambda: factorint(a*b, verbose=1)) raises(ValueError, lambda: pollard_rho(4)) raises(ValueError, lambda: pollard_pm1(3)) raises(ValueError, lambda: pollard_pm1(10, B=2)) # verbose coverage n = nextprime(2**16)*nextprime(2**17)*nextprime(1901) assert 'with primes' in capture(lambda: factorint(n, verbose=1)) capture(lambda: factorint(nextprime(2**16)*1012, verbose=1)) n = nextprime(2**17) capture(lambda: factorint(n**3, verbose=1)) # perfect power termination capture(lambda: factorint(2*n, verbose=1)) # factoring complete msg # exceed 1st n = nextprime(2**17) n *= nextprime(n) assert '1000' in capture(lambda: factorint(n, limit=1000, verbose=1)) n *= nextprime(n) assert len(factorint(n)) == 3 assert len(factorint(n, limit=p1)) == 3 n *= nextprime(2*n) # exceed 2nd assert '2001' in capture(lambda: factorint(n, limit=2000, verbose=1)) assert capture( lambda: factorint(n, limit=4000, verbose=1)).count('Pollard') == 2 # non-prime pm1 result n = nextprime(8069) n *= nextprime(2*n)*nextprime(2*n, 2) capture(lambda: factorint(n, verbose=1)) # non-prime pm1 result # factor fermat composite p1 = nextprime(2**17) p2 = nextprime(2*p1) assert factorint((p1*p2**2)**3) == {p1: 3, p2: 6} # Test for non integer input raises(ValueError, lambda: factorint(4.5)) # test dict/Dict input sans = '2**10*3**3' n = {4: 2, 12: 3} assert str(factorint(n)) == sans assert str(factorint(Dict(n))) == sans def test_divisors_and_divisor_count(): assert divisors(-1) == [1] assert divisors(0) == [] assert divisors(1) == [1] assert divisors(2) == [1, 2] assert divisors(3) == [1, 3] assert divisors(17) == [1, 17] assert divisors(10) == [1, 2, 5, 10] assert divisors(100) == [1, 2, 4, 5, 10, 20, 25, 50, 100] assert divisors(101) == [1, 101] assert divisor_count(0) == 0 assert divisor_count(-1) == 1 assert divisor_count(1) == 1 assert divisor_count(6) == 4 assert divisor_count(12) == 6 assert divisor_count(180, 3) == divisor_count(180//3) assert divisor_count(2*3*5, 7) == 0 def test_proper_divisors_and_proper_divisor_count(): assert proper_divisors(-1) == [] assert proper_divisors(0) == [] assert proper_divisors(1) == [] assert proper_divisors(2) == [1] assert proper_divisors(3) == [1] assert proper_divisors(17) == [1] assert proper_divisors(10) == [1, 2, 5] assert proper_divisors(100) == [1, 2, 4, 5, 10, 20, 25, 50] assert proper_divisors(1000000007) == [1] assert proper_divisor_count(0) == 0 assert proper_divisor_count(-1) == 0 assert proper_divisor_count(1) == 0 assert proper_divisor_count(36) == 8 assert proper_divisor_count(2*3*5) == 7 def test_udivisors_and_udivisor_count(): assert udivisors(-1) == [1] assert udivisors(0) == [] assert udivisors(1) == [1] assert udivisors(2) == [1, 2] assert udivisors(3) == [1, 3] assert udivisors(17) == [1, 17] assert udivisors(10) == [1, 2, 5, 10] assert udivisors(100) == [1, 4, 25, 100] assert udivisors(101) == [1, 101] assert udivisors(1000) == [1, 8, 125, 1000] assert udivisor_count(0) == 0 assert udivisor_count(-1) == 1 assert udivisor_count(1) == 1 assert udivisor_count(6) == 4 assert udivisor_count(12) == 4 assert udivisor_count(180) == 8 assert udivisor_count(2*3*5*7) == 16 def test_issue_6981(): S = set(divisors(4)).union(set(divisors(Integer(2)))) assert S == {1,2,4} def test_totient(): assert [totient(k) for k in range(1, 12)] == \ [1, 1, 2, 2, 4, 2, 6, 4, 6, 4, 10] assert totient(5005) == 2880 assert totient(5006) == 2502 assert totient(5009) == 5008 assert totient(2**100) == 2**99 raises(ValueError, lambda: totient(30.1)) raises(ValueError, lambda: totient(20.001)) m = Symbol("m", integer=True) assert totient(m) assert totient(m).subs(m, 3**10) == 3**10 - 3**9 assert summation(totient(m), (m, 1, 11)) == 42 n = Symbol("n", integer=True, positive=True) assert totient(n).is_integer x=Symbol("x", integer=False) raises(ValueError, lambda: totient(x)) y=Symbol("y", positive=False) raises(ValueError, lambda: totient(y)) z=Symbol("z", positive=True, integer=True) raises(ValueError, lambda: totient(2**(-z))) def test_reduced_totient(): assert [reduced_totient(k) for k in range(1, 16)] == \ [1, 1, 2, 2, 4, 2, 6, 2, 6, 4, 10, 2, 12, 6, 4] assert reduced_totient(5005) == 60 assert reduced_totient(5006) == 2502 assert reduced_totient(5009) == 5008 assert reduced_totient(2**100) == 2**98 m = Symbol("m", integer=True) assert reduced_totient(m) assert reduced_totient(m).subs(m, 2**3*3**10) == 3**10 - 3**9 assert summation(reduced_totient(m), (m, 1, 16)) == 68 n = Symbol("n", integer=True, positive=True) assert reduced_totient(n).is_integer def test_divisor_sigma(): assert [divisor_sigma(k) for k in range(1, 12)] == \ [1, 3, 4, 7, 6, 12, 8, 15, 13, 18, 12] assert [divisor_sigma(k, 2) for k in range(1, 12)] == \ [1, 5, 10, 21, 26, 50, 50, 85, 91, 130, 122] assert divisor_sigma(23450) == 50592 assert divisor_sigma(23450, 0) == 24 assert divisor_sigma(23450, 1) == 50592 assert divisor_sigma(23450, 2) == 730747500 assert divisor_sigma(23450, 3) == 14666785333344 a = Symbol("a", prime=True) b = Symbol("b", prime=True) j = Symbol("j", integer=True, positive=True) k = Symbol("k", integer=True, positive=True) assert divisor_sigma(a**j*b**k) == (a**(j + 1) - 1)*(b**(k + 1) - 1)/((a - 1)*(b - 1)) assert divisor_sigma(a**j*b**k, 2) == (a**(2*j + 2) - 1)*(b**(2*k + 2) - 1)/((a**2 - 1)*(b**2 - 1)) assert divisor_sigma(a**j*b**k, 0) == (j + 1)*(k + 1) m = Symbol("m", integer=True) k = Symbol("k", integer=True) assert divisor_sigma(m) assert divisor_sigma(m, k) assert divisor_sigma(m).subs(m, 3**10) == 88573 assert divisor_sigma(m, k).subs([(m, 3**10), (k, 3)]) == 213810021790597 assert summation(divisor_sigma(m), (m, 1, 11)) == 99 def test_udivisor_sigma(): assert [udivisor_sigma(k) for k in range(1, 12)] == \ [1, 3, 4, 5, 6, 12, 8, 9, 10, 18, 12] assert [udivisor_sigma(k, 3) for k in range(1, 12)] == \ [1, 9, 28, 65, 126, 252, 344, 513, 730, 1134, 1332] assert udivisor_sigma(23450) == 42432 assert udivisor_sigma(23450, 0) == 16 assert udivisor_sigma(23450, 1) == 42432 assert udivisor_sigma(23450, 2) == 702685000 assert udivisor_sigma(23450, 4) == 321426961814978248 m = Symbol("m", integer=True) k = Symbol("k", integer=True) assert udivisor_sigma(m) assert udivisor_sigma(m, k) assert udivisor_sigma(m).subs(m, 4**9) == 262145 assert udivisor_sigma(m, k).subs([(m, 4**9), (k, 2)]) == 68719476737 assert summation(udivisor_sigma(m), (m, 2, 15)) == 169 def test_issue_4356(): assert factorint(1030903) == {53: 2, 367: 1} def test_divisors(): assert divisors(28) == [1, 2, 4, 7, 14, 28] assert [x for x in divisors(3*5*7, 1)] == [1, 3, 5, 15, 7, 21, 35, 105] assert divisors(0) == [] def test_divisor_count(): assert divisor_count(0) == 0 assert divisor_count(6) == 4 def test_proper_divisors(): assert proper_divisors(-1) == [] assert proper_divisors(28) == [1, 2, 4, 7, 14] assert [x for x in proper_divisors(3*5*7, True)] == [1, 3, 5, 15, 7, 21, 35] def test_proper_divisor_count(): assert proper_divisor_count(6) == 3 assert proper_divisor_count(108) == 11 def test_antidivisors(): assert antidivisors(-1) == [] assert antidivisors(-3) == [2] assert antidivisors(14) == [3, 4, 9] assert antidivisors(237) == [2, 5, 6, 11, 19, 25, 43, 95, 158] assert antidivisors(12345) == [2, 6, 7, 10, 30, 1646, 3527, 4938, 8230] assert antidivisors(393216) == [262144] assert sorted(x for x in antidivisors(3*5*7, 1)) == \ [2, 6, 10, 11, 14, 19, 30, 42, 70] assert antidivisors(1) == [] def test_antidivisor_count(): assert antidivisor_count(0) == 0 assert antidivisor_count(-1) == 0 assert antidivisor_count(-4) == 1 assert antidivisor_count(20) == 3 assert antidivisor_count(25) == 5 assert antidivisor_count(38) == 7 assert antidivisor_count(180) == 6 assert antidivisor_count(2*3*5) == 3 def test_smoothness_and_smoothness_p(): assert smoothness(1) == (1, 1) assert smoothness(2**4*3**2) == (3, 16) assert smoothness_p(10431, m=1) == \ (1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))]) assert smoothness_p(10431) == \ (-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))]) assert smoothness_p(10431, power=1) == \ (-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))]) assert smoothness_p(21477639576571, visual=1) == \ 'p**i=4410317**1 has p-1 B=1787, B-pow=1787\n' + \ 'p**i=4869863**1 has p-1 B=2434931, B-pow=2434931' def test_visual_factorint(): assert factorint(1, visual=1) == 1 forty2 = factorint(42, visual=True) assert type(forty2) == Mul assert str(forty2) == '2**1*3**1*7**1' assert factorint(1, visual=True) is S.One no = dict(evaluate=False) assert factorint(42**2, visual=True) == Mul(Pow(2, 2, **no), Pow(3, 2, **no), Pow(7, 2, **no), **no) assert -1 in factorint(-42, visual=True).args def test_factorrat(): assert str(factorrat(S(12)/1, visual=True)) == '2**2*3**1' assert str(factorrat(Rational(1, 1), visual=True)) == '1' assert str(factorrat(S(25)/14, visual=True)) == '5**2/(2*7)' assert str(factorrat(Rational(25, 14), visual=True)) == '5**2/(2*7)' assert str(factorrat(S(-25)/14/9, visual=True)) == '-1*5**2/(2*3**2*7)' assert factorrat(S(12)/1, multiple=True) == [2, 2, 3] assert factorrat(Rational(1, 1), multiple=True) == [] assert factorrat(S(25)/14, multiple=True) == [Rational(1, 7), S.Half, 5, 5] assert factorrat(Rational(25, 14), multiple=True) == [Rational(1, 7), S.Half, 5, 5] assert factorrat(Rational(12, 1), multiple=True) == [2, 2, 3] assert factorrat(S(-25)/14/9, multiple=True) == \ [-1, Rational(1, 7), Rational(1, 3), Rational(1, 3), S.Half, 5, 5] def test_visual_io(): sm = smoothness_p fi = factorint # with smoothness_p n = 124 d = fi(n) m = fi(d, visual=True) t = sm(n) s = sm(t) for th in [d, s, t, n, m]: assert sm(th, visual=True) == s assert sm(th, visual=1) == s for th in [d, s, t, n, m]: assert sm(th, visual=False) == t assert [sm(th, visual=None) for th in [d, s, t, n, m]] == [s, d, s, t, t] assert [sm(th, visual=2) for th in [d, s, t, n, m]] == [s, d, s, t, t] # with factorint for th in [d, m, n]: assert fi(th, visual=True) == m assert fi(th, visual=1) == m for th in [d, m, n]: assert fi(th, visual=False) == d assert [fi(th, visual=None) for th in [d, m, n]] == [m, d, d] assert [fi(th, visual=0) for th in [d, m, n]] == [m, d, d] # test reevaluation no = dict(evaluate=False) assert sm({4: 2}, visual=False) == sm(16) assert sm(Mul(*[Pow(k, v, **no) for k, v in {4: 2, 2: 6}.items()], **no), visual=False) == sm(2**10) assert fi({4: 2}, visual=False) == fi(16) assert fi(Mul(*[Pow(k, v, **no) for k, v in {4: 2, 2: 6}.items()], **no), visual=False) == fi(2**10) def test_core(): assert core(35**13, 10) == 42875 assert core(210**2) == 1 assert core(7776, 3) == 36 assert core(10**27, 22) == 10**5 assert core(537824) == 14 assert core(1, 6) == 1 def test_primenu(): assert primenu(2) == 1 assert primenu(2 * 3) == 2 assert primenu(2 * 3 * 5) == 3 assert primenu(3 * 25) == primenu(3) + primenu(25) assert [primenu(p) for p in primerange(1, 10)] == [1, 1, 1, 1] assert primenu(fac(50)) == 15 assert primenu(2 ** 9941 - 1) == 1 n = Symbol('n', integer=True) assert primenu(n) assert primenu(n).subs(n, 2 ** 31 - 1) == 1 assert summation(primenu(n), (n, 2, 30)) == 43 def test_primeomega(): assert primeomega(2) == 1 assert primeomega(2 * 2) == 2 assert primeomega(2 * 2 * 3) == 3 assert primeomega(3 * 25) == primeomega(3) + primeomega(25) assert [primeomega(p) for p in primerange(1, 10)] == [1, 1, 1, 1] assert primeomega(fac(50)) == 108 assert primeomega(2 ** 9941 - 1) == 1 n = Symbol('n', integer=True) assert primeomega(n) assert primeomega(n).subs(n, 2 ** 31 - 1) == 1 assert summation(primeomega(n), (n, 2, 30)) == 59 def test_mersenne_prime_exponent(): assert mersenne_prime_exponent(1) == 2 assert mersenne_prime_exponent(4) == 7 assert mersenne_prime_exponent(10) == 89 assert mersenne_prime_exponent(25) == 21701 raises(ValueError, lambda: mersenne_prime_exponent(52)) raises(ValueError, lambda: mersenne_prime_exponent(0)) def test_is_perfect(): assert is_perfect(6) is True assert is_perfect(15) is False assert is_perfect(28) is True assert is_perfect(400) is False assert is_perfect(496) is True assert is_perfect(8128) is True assert is_perfect(10000) is False def test_is_mersenne_prime(): assert is_mersenne_prime(10) is False assert is_mersenne_prime(127) is True assert is_mersenne_prime(511) is False assert is_mersenne_prime(131071) is True assert is_mersenne_prime(2147483647) is True def test_is_abundant(): assert is_abundant(10) is False assert is_abundant(12) is True assert is_abundant(18) is True assert is_abundant(21) is False assert is_abundant(945) is True def test_is_deficient(): assert is_deficient(10) is True assert is_deficient(22) is True assert is_deficient(56) is False assert is_deficient(20) is False assert is_deficient(36) is False def test_is_amicable(): assert is_amicable(173, 129) is False assert is_amicable(220, 284) is True assert is_amicable(8756, 8756) is False def test_dra(): assert dra(19, 12) == 8 assert dra(2718, 10) == 9 assert dra(0, 22) == 0 assert dra(23456789, 10) == 8 raises(ValueError, lambda: dra(24, -2)) raises(ValueError, lambda: dra(24.2, 5)) def test_drm(): assert drm(19, 12) == 7 assert drm(2718, 10) == 2 assert drm(0, 15) == 0 assert drm(234161, 10) == 6 raises(ValueError, lambda: drm(24, -2)) raises(ValueError, lambda: drm(11.6, 9))
1f2f6961164fb859bbcab19546cda86ffc37618ddb30410d1ff8640e1f78ed41
from sympy.ntheory.ecm import ecm, Point from sympy.testing.pytest import slow @slow def test_ecm(): assert ecm(3146531246531241245132451321) == {3, 100327907731, 10454157497791297} assert ecm(46167045131415113) == {43, 2634823, 407485517} assert ecm(631211032315670776841) == {9312934919, 67777885039} assert ecm(398883434337287) == {99476569, 4009823} assert ecm(64211816600515193) == {281719, 359641, 633767} assert ecm(4269021180054189416198169786894227) == {184039, 241603, 333331, 477973, 618619, 974123} assert ecm(4516511326451341281684513) == {3, 39869, 131743543, 95542348571} assert ecm(4132846513818654136451) == {47, 160343, 2802377, 195692803} assert ecm(168541512131094651323) == {79, 113, 11011069, 1714635721} #This takes ~10secs while factorint is not able to factorize this even in ~10mins assert ecm(7060005655815754299976961394452809, B1=100000, B2=1000000) == {6988699669998001, 1010203040506070809} def test_Point(): from sympy.core.numbers import mod_inverse #The curve is of the form y**2 = x**3 + a*x**2 + x mod = 101 a = 10 a_24 = (a + 2)*mod_inverse(4, mod) p1 = Point(10, 17, a_24, mod) p2 = p1.double() assert p2 == Point(68, 56, a_24, mod) p4 = p2.double() assert p4 == Point(22, 64, a_24, mod) p8 = p4.double() assert p8 == Point(71, 95, a_24, mod) p16 = p8.double() assert p16 == Point(5, 16, a_24, mod) p32 = p16.double() assert p32 == Point(33, 96, a_24, mod) # p3 = p2 + p1 p3 = p2.add(p1, p1) assert p3 == Point(1, 61, a_24, mod) # p5 = p3 + p2 or p4 + p1 p5 = p3.add(p2, p1) assert p5 == Point(49, 90, a_24, mod) assert p5 == p4.add(p1, p3) # p6 = 2*p3 p6 = p3.double() assert p6 == Point(87, 43, a_24, mod) assert p6 == p4.add(p2, p2) # p7 = p5 + p2 p7 = p5.add(p2, p3) assert p7 == Point(69, 23, a_24, mod) assert p7 == p4.add(p3, p1) assert p7 == p6.add(p1, p5) # p9 = p5 + p4 p9 = p5.add(p4, p1) assert p9 == Point(56, 99, a_24, mod) assert p9 == p6.add(p3, p3) assert p9 == p7.add(p2, p5) assert p9 == p8.add(p1, p7) assert p5 == p1.mont_ladder(5) assert p9 == p1.mont_ladder(9) assert p16 == p1.mont_ladder(16) assert p9 == p3.mont_ladder(3)
f2eba3e9795ab4dc8820b3a98c96a9d7708c6660f0ac2c862a7f4b8885222d5d
from sympy.ntheory.multinomial import (binomial_coefficients, binomial_coefficients_list, multinomial_coefficients) from sympy.ntheory.multinomial import multinomial_coefficients_iterator def test_binomial_coefficients_list(): assert binomial_coefficients_list(0) == [1] assert binomial_coefficients_list(1) == [1, 1] assert binomial_coefficients_list(2) == [1, 2, 1] assert binomial_coefficients_list(3) == [1, 3, 3, 1] assert binomial_coefficients_list(4) == [1, 4, 6, 4, 1] assert binomial_coefficients_list(5) == [1, 5, 10, 10, 5, 1] assert binomial_coefficients_list(6) == [1, 6, 15, 20, 15, 6, 1] def test_binomial_coefficients(): for n in range(15): c = binomial_coefficients(n) l = [c[k] for k in sorted(c)] assert l == binomial_coefficients_list(n) def test_multinomial_coefficients(): assert multinomial_coefficients(1, 1) == {(1,): 1} assert multinomial_coefficients(1, 2) == {(2,): 1} assert multinomial_coefficients(1, 3) == {(3,): 1} assert multinomial_coefficients(2, 0) == {(0, 0): 1} assert multinomial_coefficients(2, 1) == {(0, 1): 1, (1, 0): 1} assert multinomial_coefficients(2, 2) == {(2, 0): 1, (0, 2): 1, (1, 1): 2} assert multinomial_coefficients(2, 3) == {(3, 0): 1, (1, 2): 3, (0, 3): 1, (2, 1): 3} assert multinomial_coefficients(3, 1) == {(1, 0, 0): 1, (0, 1, 0): 1, (0, 0, 1): 1} assert multinomial_coefficients(3, 2) == {(0, 1, 1): 2, (0, 0, 2): 1, (1, 1, 0): 2, (0, 2, 0): 1, (1, 0, 1): 2, (2, 0, 0): 1} mc = multinomial_coefficients(3, 3) assert mc == {(2, 1, 0): 3, (0, 3, 0): 1, (1, 0, 2): 3, (0, 2, 1): 3, (0, 1, 2): 3, (3, 0, 0): 1, (2, 0, 1): 3, (1, 2, 0): 3, (1, 1, 1): 6, (0, 0, 3): 1} assert dict(multinomial_coefficients_iterator(2, 0)) == {(0, 0): 1} assert dict( multinomial_coefficients_iterator(2, 1)) == {(0, 1): 1, (1, 0): 1} assert dict(multinomial_coefficients_iterator(2, 2)) == \ {(2, 0): 1, (0, 2): 1, (1, 1): 2} assert dict(multinomial_coefficients_iterator(3, 3)) == mc it = multinomial_coefficients_iterator(7, 2) assert [next(it) for i in range(4)] == \ [((2, 0, 0, 0, 0, 0, 0), 1), ((1, 1, 0, 0, 0, 0, 0), 2), ((0, 2, 0, 0, 0, 0, 0), 1), ((1, 0, 1, 0, 0, 0, 0), 2)]
985def6528c4196ae7726a92469c5dbd10d0b9f3e5738a328b7ab15fcb8b8025
from collections import defaultdict from sympy.core.containers import Tuple from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol) from sympy.ntheory import n_order, is_primitive_root, is_quad_residue, \ legendre_symbol, jacobi_symbol, totient, primerange, sqrt_mod, \ primitive_root, quadratic_residues, is_nthpow_residue, nthroot_mod, \ sqrt_mod_iter, mobius, discrete_log, quadratic_congruence, \ polynomial_congruence from sympy.ntheory.residue_ntheory import _primitive_root_prime_iter, \ _discrete_log_trial_mul, _discrete_log_shanks_steps, \ _discrete_log_pollard_rho, _discrete_log_pohlig_hellman from sympy.polys.domains import ZZ from sympy.testing.pytest import raises def test_residue(): assert n_order(2, 13) == 12 assert [n_order(a, 7) for a in range(1, 7)] == \ [1, 3, 6, 3, 6, 2] assert n_order(5, 17) == 16 assert n_order(17, 11) == n_order(6, 11) assert n_order(101, 119) == 6 assert n_order(11, (10**50 + 151)**2) == 10000000000000000000000000000000000000000000000030100000000000000000000000000000000000000000000022650 raises(ValueError, lambda: n_order(6, 9)) assert is_primitive_root(2, 7) is False assert is_primitive_root(3, 8) is False assert is_primitive_root(11, 14) is False assert is_primitive_root(12, 17) == is_primitive_root(29, 17) raises(ValueError, lambda: is_primitive_root(3, 6)) for p in primerange(3, 100): it = _primitive_root_prime_iter(p) assert len(list(it)) == totient(totient(p)) assert primitive_root(97) == 5 assert primitive_root(97**2) == 5 assert primitive_root(40487) == 5 # note that primitive_root(40487) + 40487 = 40492 is a primitive root # of 40487**2, but it is not the smallest assert primitive_root(40487**2) == 10 assert primitive_root(82) == 7 p = 10**50 + 151 assert primitive_root(p) == 11 assert primitive_root(2*p) == 11 assert primitive_root(p**2) == 11 raises(ValueError, lambda: primitive_root(-3)) assert is_quad_residue(3, 7) is False assert is_quad_residue(10, 13) is True assert is_quad_residue(12364, 139) == is_quad_residue(12364 % 139, 139) assert is_quad_residue(207, 251) is True assert is_quad_residue(0, 1) is True assert is_quad_residue(1, 1) is True assert is_quad_residue(0, 2) == is_quad_residue(1, 2) is True assert is_quad_residue(1, 4) is True assert is_quad_residue(2, 27) is False assert is_quad_residue(13122380800, 13604889600) is True assert [j for j in range(14) if is_quad_residue(j, 14)] == \ [0, 1, 2, 4, 7, 8, 9, 11] raises(ValueError, lambda: is_quad_residue(1.1, 2)) raises(ValueError, lambda: is_quad_residue(2, 0)) assert quadratic_residues(S.One) == [0] assert quadratic_residues(1) == [0] assert quadratic_residues(12) == [0, 1, 4, 9] assert quadratic_residues(12) == [0, 1, 4, 9] assert quadratic_residues(13) == [0, 1, 3, 4, 9, 10, 12] assert [len(quadratic_residues(i)) for i in range(1, 20)] == \ [1, 2, 2, 2, 3, 4, 4, 3, 4, 6, 6, 4, 7, 8, 6, 4, 9, 8, 10] assert list(sqrt_mod_iter(6, 2)) == [0] assert sqrt_mod(3, 13) == 4 assert sqrt_mod(3, -13) == 4 assert sqrt_mod(6, 23) == 11 assert sqrt_mod(345, 690) == 345 assert sqrt_mod(67, 101) == None assert sqrt_mod(1020, 104729) == None for p in range(3, 100): d = defaultdict(list) for i in range(p): d[pow(i, 2, p)].append(i) for i in range(1, p): it = sqrt_mod_iter(i, p) v = sqrt_mod(i, p, True) if v: v = sorted(v) assert d[i] == v else: assert not d[i] assert sqrt_mod(9, 27, True) == [3, 6, 12, 15, 21, 24] assert sqrt_mod(9, 81, True) == [3, 24, 30, 51, 57, 78] assert sqrt_mod(9, 3**5, True) == [3, 78, 84, 159, 165, 240] assert sqrt_mod(81, 3**4, True) == [0, 9, 18, 27, 36, 45, 54, 63, 72] assert sqrt_mod(81, 3**5, True) == [9, 18, 36, 45, 63, 72, 90, 99, 117,\ 126, 144, 153, 171, 180, 198, 207, 225, 234] assert sqrt_mod(81, 3**6, True) == [9, 72, 90, 153, 171, 234, 252, 315,\ 333, 396, 414, 477, 495, 558, 576, 639, 657, 720] assert sqrt_mod(81, 3**7, True) == [9, 234, 252, 477, 495, 720, 738, 963,\ 981, 1206, 1224, 1449, 1467, 1692, 1710, 1935, 1953, 2178] for a, p in [(26214400, 32768000000), (26214400, 16384000000), (262144, 1048576), (87169610025, 163443018796875), (22315420166400, 167365651248000000)]: assert pow(sqrt_mod(a, p), 2, p) == a n = 70 a, p = 5**2*3**n*2**n, 5**6*3**(n+1)*2**(n+2) it = sqrt_mod_iter(a, p) for i in range(10): assert pow(next(it), 2, p) == a a, p = 5**2*3**n*2**n, 5**6*3**(n+1)*2**(n+3) it = sqrt_mod_iter(a, p) for i in range(2): assert pow(next(it), 2, p) == a n = 100 a, p = 5**2*3**n*2**n, 5**6*3**(n+1)*2**(n+1) it = sqrt_mod_iter(a, p) for i in range(2): assert pow(next(it), 2, p) == a assert type(next(sqrt_mod_iter(9, 27))) is int assert type(next(sqrt_mod_iter(9, 27, ZZ))) is type(ZZ(1)) assert type(next(sqrt_mod_iter(1, 7, ZZ))) is type(ZZ(1)) assert is_nthpow_residue(2, 1, 5) #issue 10816 assert is_nthpow_residue(1, 0, 1) is False assert is_nthpow_residue(1, 0, 2) is True assert is_nthpow_residue(3, 0, 2) is True assert is_nthpow_residue(0, 1, 8) is True assert is_nthpow_residue(2, 3, 2) is True assert is_nthpow_residue(2, 3, 9) is False assert is_nthpow_residue(3, 5, 30) is True assert is_nthpow_residue(21, 11, 20) is True assert is_nthpow_residue(7, 10, 20) is False assert is_nthpow_residue(5, 10, 20) is True assert is_nthpow_residue(3, 10, 48) is False assert is_nthpow_residue(1, 10, 40) is True assert is_nthpow_residue(3, 10, 24) is False assert is_nthpow_residue(1, 10, 24) is True assert is_nthpow_residue(3, 10, 24) is False assert is_nthpow_residue(2, 10, 48) is False assert is_nthpow_residue(81, 3, 972) is False assert is_nthpow_residue(243, 5, 5103) is True assert is_nthpow_residue(243, 3, 1240029) is False assert is_nthpow_residue(36010, 8, 87382) is True assert is_nthpow_residue(28552, 6, 2218) is True assert is_nthpow_residue(92712, 9, 50026) is True x = {pow(i, 56, 1024) for i in range(1024)} assert {a for a in range(1024) if is_nthpow_residue(a, 56, 1024)} == x x = { pow(i, 256, 2048) for i in range(2048)} assert {a for a in range(2048) if is_nthpow_residue(a, 256, 2048)} == x x = { pow(i, 11, 324000) for i in range(1000)} assert [ is_nthpow_residue(a, 11, 324000) for a in x] x = { pow(i, 17, 22217575536) for i in range(1000)} assert [ is_nthpow_residue(a, 17, 22217575536) for a in x] assert is_nthpow_residue(676, 3, 5364) assert is_nthpow_residue(9, 12, 36) assert is_nthpow_residue(32, 10, 41) assert is_nthpow_residue(4, 2, 64) assert is_nthpow_residue(31, 4, 41) assert not is_nthpow_residue(2, 2, 5) assert is_nthpow_residue(8547, 12, 10007) assert is_nthpow_residue(Dummy(even=True) + 3, 3, 2) == True assert nthroot_mod(Dummy(odd=True), 3, 2) == 1 assert nthroot_mod(29, 31, 74) == [45] assert nthroot_mod(1801, 11, 2663) == 44 for a, q, p in [(51922, 2, 203017), (43, 3, 109), (1801, 11, 2663), (26118163, 1303, 33333347), (1499, 7, 2663), (595, 6, 2663), (1714, 12, 2663), (28477, 9, 33343)]: r = nthroot_mod(a, q, p) assert pow(r, q, p) == a assert nthroot_mod(11, 3, 109) is None assert nthroot_mod(16, 5, 36, True) == [4, 22] assert nthroot_mod(9, 16, 36, True) == [3, 9, 15, 21, 27, 33] assert nthroot_mod(4, 3, 3249000) == [] assert nthroot_mod(36010, 8, 87382, True) == [40208, 47174] assert nthroot_mod(0, 12, 37, True) == [0] assert nthroot_mod(0, 7, 100, True) == [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] assert nthroot_mod(4, 4, 27, True) == [5, 22] assert nthroot_mod(4, 4, 121, True) == [19, 102] assert nthroot_mod(2, 3, 7, True) == [] for p in range(5, 100): qv = range(3, p, 4) for q in qv: d = defaultdict(list) for i in range(p): d[pow(i, q, p)].append(i) for a in range(1, p - 1): res = nthroot_mod(a, q, p, True) if d[a]: assert d[a] == res else: assert res == [] assert legendre_symbol(5, 11) == 1 assert legendre_symbol(25, 41) == 1 assert legendre_symbol(67, 101) == -1 assert legendre_symbol(0, 13) == 0 assert legendre_symbol(9, 3) == 0 raises(ValueError, lambda: legendre_symbol(2, 4)) assert jacobi_symbol(25, 41) == 1 assert jacobi_symbol(-23, 83) == -1 assert jacobi_symbol(3, 9) == 0 assert jacobi_symbol(42, 97) == -1 assert jacobi_symbol(3, 5) == -1 assert jacobi_symbol(7, 9) == 1 assert jacobi_symbol(0, 3) == 0 assert jacobi_symbol(0, 1) == 1 assert jacobi_symbol(2, 1) == 1 assert jacobi_symbol(1, 3) == 1 raises(ValueError, lambda: jacobi_symbol(3, 8)) assert mobius(13*7) == 1 assert mobius(1) == 1 assert mobius(13*7*5) == -1 assert mobius(13**2) == 0 raises(ValueError, lambda: mobius(-3)) p = Symbol('p', integer=True, positive=True, prime=True) x = Symbol('x', positive=True) i = Symbol('i', integer=True) assert mobius(p) == -1 raises(TypeError, lambda: mobius(x)) raises(ValueError, lambda: mobius(i)) assert _discrete_log_trial_mul(587, 2**7, 2) == 7 assert _discrete_log_trial_mul(941, 7**18, 7) == 18 assert _discrete_log_trial_mul(389, 3**81, 3) == 81 assert _discrete_log_trial_mul(191, 19**123, 19) == 123 assert _discrete_log_shanks_steps(442879, 7**2, 7) == 2 assert _discrete_log_shanks_steps(874323, 5**19, 5) == 19 assert _discrete_log_shanks_steps(6876342, 7**71, 7) == 71 assert _discrete_log_shanks_steps(2456747, 3**321, 3) == 321 assert _discrete_log_pollard_rho(6013199, 2**6, 2, rseed=0) == 6 assert _discrete_log_pollard_rho(6138719, 2**19, 2, rseed=0) == 19 assert _discrete_log_pollard_rho(36721943, 2**40, 2, rseed=0) == 40 assert _discrete_log_pollard_rho(24567899, 3**333, 3, rseed=0) == 333 raises(ValueError, lambda: _discrete_log_pollard_rho(11, 7, 31, rseed=0)) raises(ValueError, lambda: _discrete_log_pollard_rho(227, 3**7, 5, rseed=0)) assert _discrete_log_pohlig_hellman(98376431, 11**9, 11) == 9 assert _discrete_log_pohlig_hellman(78723213, 11**31, 11) == 31 assert _discrete_log_pohlig_hellman(32942478, 11**98, 11) == 98 assert _discrete_log_pohlig_hellman(14789363, 11**444, 11) == 444 assert discrete_log(587, 2**9, 2) == 9 assert discrete_log(2456747, 3**51, 3) == 51 assert discrete_log(32942478, 11**127, 11) == 127 assert discrete_log(432751500361, 7**324, 7) == 324 args = 5779, 3528, 6215 assert discrete_log(*args) == 687 assert discrete_log(*Tuple(*args)) == 687 assert quadratic_congruence(400, 85, 125, 1600) == [295, 615, 935, 1255, 1575] assert quadratic_congruence(3, 6, 5, 25) == [3, 20] assert quadratic_congruence(120, 80, 175, 500) == [] assert quadratic_congruence(15, 14, 7, 2) == [1] assert quadratic_congruence(8, 15, 7, 29) == [10, 28] assert quadratic_congruence(160, 200, 300, 461) == [144, 431] assert quadratic_congruence(100000, 123456, 7415263, 48112959837082048697) == [30417843635344493501, 36001135160550533083] assert quadratic_congruence(65, 121, 72, 277) == [249, 252] assert quadratic_congruence(5, 10, 14, 2) == [0] assert quadratic_congruence(10, 17, 19, 2) == [1] assert quadratic_congruence(10, 14, 20, 2) == [0, 1] assert polynomial_congruence(6*x**5 + 10*x**4 + 5*x**3 + x**2 + x + 1, 972000) == [220999, 242999, 463999, 485999, 706999, 728999, 949999, 971999] assert polynomial_congruence(x**3 - 10*x**2 + 12*x - 82, 33075) == [30287] assert polynomial_congruence(x**2 + x + 47, 2401) == [785, 1615] assert polynomial_congruence(10*x**2 + 14*x + 20, 2) == [0, 1] assert polynomial_congruence(x**3 + 3, 16) == [5] assert polynomial_congruence(65*x**2 + 121*x + 72, 277) == [249, 252] assert polynomial_congruence(x**4 - 4, 27) == [5, 22] assert polynomial_congruence(35*x**3 - 6*x**2 - 567*x + 2308, 148225) == [86957, 111157, 122531, 146731] assert polynomial_congruence(x**16 - 9, 36) == [3, 9, 15, 21, 27, 33] assert polynomial_congruence(x**6 - 2*x**5 - 35, 6125) == [3257] raises(ValueError, lambda: polynomial_congruence(x**x, 6125)) raises(ValueError, lambda: polynomial_congruence(x**i, 6125)) raises(ValueError, lambda: polynomial_congruence(0.1*x**2 + 6, 100))
00b2b32c07023c8313af7242e91247b8e61deb3d1a155685e7e7b8f3589c61ef
from sympy.core.numbers import (I, Rational, nan, zoo) from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.ntheory.generate import (sieve, Sieve) from sympy.series.limits import limit from sympy.ntheory import isprime, totient, mobius, randprime, nextprime, prevprime, \ primerange, primepi, prime, primorial, composite, compositepi, reduced_totient from sympy.ntheory.generate import cycle_length from sympy.ntheory.primetest import mr from sympy.testing.pytest import raises def test_prime(): assert prime(1) == 2 assert prime(2) == 3 assert prime(5) == 11 assert prime(11) == 31 assert prime(57) == 269 assert prime(296) == 1949 assert prime(559) == 4051 assert prime(3000) == 27449 assert prime(4096) == 38873 assert prime(9096) == 94321 assert prime(25023) == 287341 assert prime(10000000) == 179424673 # issue #20951 assert prime(99999999) == 2038074739 raises(ValueError, lambda: prime(0)) sieve.extend(3000) assert prime(401) == 2749 raises(ValueError, lambda: prime(-1)) def test_primepi(): assert primepi(-1) == 0 assert primepi(1) == 0 assert primepi(2) == 1 assert primepi(Rational(7, 2)) == 2 assert primepi(3.5) == 2 assert primepi(5) == 3 assert primepi(11) == 5 assert primepi(57) == 16 assert primepi(296) == 62 assert primepi(559) == 102 assert primepi(3000) == 430 assert primepi(4096) == 564 assert primepi(9096) == 1128 assert primepi(25023) == 2763 assert primepi(10**8) == 5761455 assert primepi(253425253) == 13856396 assert primepi(8769575643) == 401464322 sieve.extend(3000) assert primepi(2000) == 303 n = Symbol('n') assert primepi(n).subs(n, 2) == 1 r = Symbol('r', real=True) assert primepi(r).subs(r, 2) == 1 assert primepi(S.Infinity) is S.Infinity assert primepi(S.NegativeInfinity) == 0 assert limit(primepi(n), n, 100) == 25 raises(ValueError, lambda: primepi(I)) raises(ValueError, lambda: primepi(1 + I)) raises(ValueError, lambda: primepi(zoo)) raises(ValueError, lambda: primepi(nan)) def test_composite(): from sympy.ntheory.generate import sieve sieve._reset() assert composite(1) == 4 assert composite(2) == 6 assert composite(5) == 10 assert composite(11) == 20 assert composite(41) == 58 assert composite(57) == 80 assert composite(296) == 370 assert composite(559) == 684 assert composite(3000) == 3488 assert composite(4096) == 4736 assert composite(9096) == 10368 assert composite(25023) == 28088 sieve.extend(3000) assert composite(1957) == 2300 assert composite(2568) == 2998 raises(ValueError, lambda: composite(0)) def test_compositepi(): assert compositepi(1) == 0 assert compositepi(2) == 0 assert compositepi(5) == 1 assert compositepi(11) == 5 assert compositepi(57) == 40 assert compositepi(296) == 233 assert compositepi(559) == 456 assert compositepi(3000) == 2569 assert compositepi(4096) == 3531 assert compositepi(9096) == 7967 assert compositepi(25023) == 22259 assert compositepi(10**8) == 94238544 assert compositepi(253425253) == 239568856 assert compositepi(8769575643) == 8368111320 sieve.extend(3000) assert compositepi(2321) == 1976 def test_generate(): from sympy.ntheory.generate import sieve sieve._reset() assert nextprime(-4) == 2 assert nextprime(2) == 3 assert nextprime(5) == 7 assert nextprime(12) == 13 assert prevprime(3) == 2 assert prevprime(7) == 5 assert prevprime(13) == 11 assert prevprime(19) == 17 assert prevprime(20) == 19 sieve.extend_to_no(9) assert sieve._list[-1] == 23 assert sieve._list[-1] < 31 assert 31 in sieve assert nextprime(90) == 97 assert nextprime(10**40) == (10**40 + 121) assert prevprime(97) == 89 assert prevprime(10**40) == (10**40 - 17) assert list(sieve.primerange(10, 1)) == [] assert list(sieve.primerange(5, 9)) == [5, 7] sieve._reset(prime=True) assert list(sieve.primerange(2, 13)) == [2, 3, 5, 7, 11] assert list(sieve.primerange(13)) == [2, 3, 5, 7, 11] assert list(sieve.primerange(8)) == [2, 3, 5, 7] assert list(sieve.primerange(-2)) == [] assert list(sieve.primerange(29)) == [2, 3, 5, 7, 11, 13, 17, 19, 23] assert list(sieve.primerange(34)) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] assert list(sieve.totientrange(5, 15)) == [4, 2, 6, 4, 6, 4, 10, 4, 12, 6] sieve._reset(totient=True) assert list(sieve.totientrange(3, 13)) == [2, 2, 4, 2, 6, 4, 6, 4, 10, 4] assert list(sieve.totientrange(900, 1000)) == [totient(x) for x in range(900, 1000)] assert list(sieve.totientrange(0, 1)) == [] assert list(sieve.totientrange(1, 2)) == [1] assert list(sieve.mobiusrange(5, 15)) == [-1, 1, -1, 0, 0, 1, -1, 0, -1, 1] sieve._reset(mobius=True) assert list(sieve.mobiusrange(3, 13)) == [-1, 0, -1, 1, -1, 0, 0, 1, -1, 0] assert list(sieve.mobiusrange(1050, 1100)) == [mobius(x) for x in range(1050, 1100)] assert list(sieve.mobiusrange(0, 1)) == [] assert list(sieve.mobiusrange(1, 2)) == [1] assert list(primerange(10, 1)) == [] assert list(primerange(2, 7)) == [2, 3, 5] assert list(primerange(2, 10)) == [2, 3, 5, 7] assert list(primerange(1050, 1100)) == [1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097] s = Sieve() for i in range(30, 2350, 376): for j in range(2, 5096, 1139): A = list(s.primerange(i, i + j)) B = list(primerange(i, i + j)) assert A == B s = Sieve() assert s[10] == 29 assert nextprime(2, 2) == 5 raises(ValueError, lambda: totient(0)) raises(ValueError, lambda: reduced_totient(0)) raises(ValueError, lambda: primorial(0)) assert mr(1, [2]) is False func = lambda i: (i**2 + 1) % 51 assert next(cycle_length(func, 4)) == (6, 2) assert list(cycle_length(func, 4, values=True)) == \ [17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14] assert next(cycle_length(func, 4, nmax=5)) == (5, None) assert list(cycle_length(func, 4, nmax=5, values=True)) == \ [17, 35, 2, 5, 26] sieve.extend(3000) assert nextprime(2968) == 2969 assert prevprime(2930) == 2927 raises(ValueError, lambda: prevprime(1)) raises(ValueError, lambda: prevprime(-4)) def test_randprime(): assert randprime(10, 1) is None assert randprime(3, -3) is None assert randprime(2, 3) == 2 assert randprime(1, 3) == 2 assert randprime(3, 5) == 3 raises(ValueError, lambda: randprime(-12, -2)) raises(ValueError, lambda: randprime(-10, 0)) raises(ValueError, lambda: randprime(20, 22)) raises(ValueError, lambda: randprime(0, 2)) raises(ValueError, lambda: randprime(1, 2)) for a in [100, 300, 500, 250000]: for b in [100, 300, 500, 250000]: p = randprime(a, a + b) assert a <= p < (a + b) and isprime(p) def test_primorial(): assert primorial(1) == 2 assert primorial(1, nth=0) == 1 assert primorial(2) == 6 assert primorial(2, nth=0) == 2 assert primorial(4, nth=0) == 6 def test_search(): assert 2 in sieve assert 2.1 not in sieve assert 1 not in sieve assert 2**1000 not in sieve raises(ValueError, lambda: sieve.search(1)) def test_sieve_slice(): assert sieve[5] == 11 assert list(sieve[5:10]) == [sieve[x] for x in range(5, 10)] assert list(sieve[5:10:2]) == [sieve[x] for x in range(5, 10, 2)] assert list(sieve[1:5]) == [2, 3, 5, 7] raises(IndexError, lambda: sieve[:5]) raises(IndexError, lambda: sieve[0]) raises(IndexError, lambda: sieve[0:5]) def test_sieve_iter(): values = [] for value in sieve: if value > 7: break values.append(value) assert values == list(sieve[1:5]) def test_sieve_repr(): assert "sieve" in repr(sieve) assert "prime" in repr(sieve)
d98c95a17df1e2c3923f1c5edb2ca856686afbe93c4fee4a90f2eea4f348c44e
from typing import Dict as tDict, Tuple as tTuple from sympy.ntheory import qs from sympy.ntheory.qs import SievePolynomial, \ _generate_factor_base, _initialize_first_polynomial, _initialize_ith_poly, \ _gen_sieve_array, _check_smoothness, _trial_division_stage, _gauss_mod_2, \ _build_matrix, _find_factor assert qs(10009202107, 100, 10000) == {100043, 100049} assert qs(211107295182713951054568361, 1000, 10000) == {13791315212531, 15307263442931} assert qs(980835832582657*990377764891511, 3000, 50000) == {980835832582657, 990377764891511} assert qs(18640889198609*20991129234731, 1000, 50000) == {18640889198609, 20991129234731} n = 10009202107 M = 50 #a = 10, b = 15, modified_coeff = [a**2, 2*a*b, b**2 - N] sieve_poly = SievePolynomial([100, 1600, -10009195707], 10, 80) assert sieve_poly.eval(10) == -10009169707 assert sieve_poly.eval(5) == -10009185207 idx_1000, idx_5000, factor_base = _generate_factor_base(2000, n) assert idx_1000 == 82 assert [factor_base[i].prime for i in range(15)] == [2, 3, 7, 11, 17, 19, 29, 31,\ 43, 59, 61, 67, 71, 73, 79] assert [factor_base[i].tmem_p for i in range(15)] == [1, 1, 3, 5, 3, 6, 6, 14, 1,\ 16, 24, 22, 18, 22, 15] assert [factor_base[i].log_p for i in range(5)] == [710, 1125, 1993, 2455, 2901] g, B = _initialize_first_polynomial(n, M, factor_base, idx_1000, idx_5000, seed=0) assert g.a == 1133107 assert g.b == 682543 assert B == [272889, 409654] assert [factor_base[i].soln1 for i in range(15)] == [0, 0, 3, 7, 13, 0, 8, 19,\ 9, 43, 27, 25, 63, 29, 19] assert [factor_base[i].soln2 for i in range(15)] == [0, 1, 1, 3, 12, 16, 15, 6,\ 15, 1, 56, 55, 61, 58, 16] assert [factor_base[i].a_inv for i in range(15)] == [1, 1, 5, 7, 3, 5, 26, 6,\ 40, 5, 21, 45, 4, 1, 8] assert [factor_base[i].b_ainv for i in range(5)] == [[0, 0], [0, 2], [3, 0],\ [3, 9], [13, 13]] g_1 = _initialize_ith_poly(n, factor_base, 1, g, B) assert g_1.a == 1133107 assert g_1.b == 136765 sieve_array = _gen_sieve_array(M, factor_base) assert sieve_array[0:5] == [8424, 13603, 1835, 5335, 710] assert _check_smoothness(9645, factor_base) == (5, False) assert _check_smoothness(210313, factor_base)[0][0:15] == [0, 0, 0, 0, 0, 0, 0,\ 0, 0, 1, 0, 0, 1, 0, 1] assert _check_smoothness(210313, factor_base)[1] == True partial_relations = {} # type: tDict[int, tTuple[int, int]] smooth_relation, partial_relation = _trial_division_stage(n, M, factor_base,\ sieve_array, sieve_poly,\ partial_relations, ERROR_TERM=25*2**10) assert partial_relations == {8699: (440, -10009008507), 166741: (490, -10008962007), 131449: (530, -10008921207), 6653: (550, -10008899607)} assert [smooth_relation[i][0] for i in range(5)] == [-250, -670615476700,\ -45211565844500, -231723037747200, -1811665537200] assert [smooth_relation[i][1] for i in range(5)] == [-10009139607, 1133094251961,\ 5302606761, 53804049849, 1950723889] assert smooth_relation[0][2][0:15] == [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] assert _gauss_mod_2([[0, 0, 1], [1, 0, 1], [0, 1, 0], [0, 1, 1], [0, 1, 1]]) ==\ ([[[0, 1, 1], 3], [[0, 1, 1], 4]], [True, True, True, False, False], [[0, 0, 1],\ [1, 0, 0], [0, 1, 0], [0, 1, 1], [0, 1, 1]]) N=1817 smooth_relations = [(2455024, 637, [0, 0, 0, 1]), (-27993000, 81536, [0, 1, 0, 1]), (11461840, 12544, [0, 0, 0, 0]), (149, 20384, [0, 1, 0, 1]), (-31138074, 19208, [0, 1, 0, 0])] matrix = _build_matrix(smooth_relations) assert matrix == [[0, 0, 0, 1], [0, 1, 0, 1], [0, 0, 0, 0], [0, 1, 0, 1], [0, 1, 0, 0]] dependent_row, mark, gauss_matrix = _gauss_mod_2(matrix) assert dependent_row == [[[0, 0, 0, 0], 2], [[0, 1, 0, 0], 3]] assert mark == [True, True, False, False, True] assert gauss_matrix == [[0, 0, 0, 1], [0, 1, 0, 0], [0, 0, 0, 0], [0, 1, 0, 0], [0, 1, 0, 1]] factor = _find_factor(dependent_row, mark, gauss_matrix, 0, smooth_relations, N) assert factor == 23
dd25a415029e17ea754163f822ef4d200d684f1005a3504b46bacb7ab045021c
from sympy.core.symbol import symbols from sympy.sets.sets import FiniteSet from sympy.combinatorics.polyhedron import (Polyhedron, tetrahedron, cube as square, octahedron, dodecahedron, icosahedron, cube_faces) from sympy.combinatorics.permutations import Permutation from sympy.combinatorics.perm_groups import PermutationGroup from sympy.testing.pytest import raises rmul = Permutation.rmul def test_polyhedron(): raises(ValueError, lambda: Polyhedron(list('ab'), pgroup=[Permutation([0])])) pgroup = [Permutation([[0, 7, 2, 5], [6, 1, 4, 3]]), Permutation([[0, 7, 1, 6], [5, 2, 4, 3]]), Permutation([[3, 6, 0, 5], [4, 1, 7, 2]]), Permutation([[7, 4, 5], [1, 3, 0], [2], [6]]), Permutation([[1, 3, 2], [7, 6, 5], [4], [0]]), Permutation([[4, 7, 6], [2, 0, 3], [1], [5]]), Permutation([[1, 2, 0], [4, 5, 6], [3], [7]]), Permutation([[4, 2], [0, 6], [3, 7], [1, 5]]), Permutation([[3, 5], [7, 1], [2, 6], [0, 4]]), Permutation([[2, 5], [1, 6], [0, 4], [3, 7]]), Permutation([[4, 3], [7, 0], [5, 1], [6, 2]]), Permutation([[4, 1], [0, 5], [6, 2], [7, 3]]), Permutation([[7, 2], [3, 6], [0, 4], [1, 5]]), Permutation([0, 1, 2, 3, 4, 5, 6, 7])] corners = tuple(symbols('A:H')) faces = cube_faces cube = Polyhedron(corners, faces, pgroup) assert cube.edges == FiniteSet(*( (0, 1), (6, 7), (1, 2), (5, 6), (0, 3), (2, 3), (4, 7), (4, 5), (3, 7), (1, 5), (0, 4), (2, 6))) for i in range(3): # add 180 degree face rotations cube.rotate(cube.pgroup[i]**2) assert cube.corners == corners for i in range(3, 7): # add 240 degree axial corner rotations cube.rotate(cube.pgroup[i]**2) assert cube.corners == corners cube.rotate(1) raises(ValueError, lambda: cube.rotate(Permutation([0, 1]))) assert cube.corners != corners assert cube.array_form == [7, 6, 4, 5, 3, 2, 0, 1] assert cube.cyclic_form == [[0, 7, 1, 6], [2, 4, 3, 5]] cube.reset() assert cube.corners == corners def check(h, size, rpt, target): assert len(h.faces) + len(h.vertices) - len(h.edges) == 2 assert h.size == size got = set() for p in h.pgroup: # make sure it restores original P = h.copy() hit = P.corners for i in range(rpt): P.rotate(p) if P.corners == hit: break else: print('error in permutation', p.array_form) for i in range(rpt): P.rotate(p) got.add(tuple(P.corners)) c = P.corners f = [[c[i] for i in f] for f in P.faces] assert h.faces == Polyhedron(c, f).faces assert len(got) == target assert PermutationGroup([Permutation(g) for g in got]).is_group for h, size, rpt, target in zip( (tetrahedron, square, octahedron, dodecahedron, icosahedron), (4, 8, 6, 20, 12), (3, 4, 4, 5, 5), (12, 24, 24, 60, 60)): check(h, size, rpt, target) def test_pgroups(): from sympy.combinatorics.polyhedron import (cube, tetrahedron_faces, octahedron_faces, dodecahedron_faces, icosahedron_faces) from sympy.combinatorics.polyhedron import _pgroup_calcs (tetrahedron2, cube2, octahedron2, dodecahedron2, icosahedron2, tetrahedron_faces2, cube_faces2, octahedron_faces2, dodecahedron_faces2, icosahedron_faces2) = _pgroup_calcs() assert tetrahedron == tetrahedron2 assert cube == cube2 assert octahedron == octahedron2 assert dodecahedron == dodecahedron2 assert icosahedron == icosahedron2 assert sorted(map(sorted, tetrahedron_faces)) == sorted(map(sorted, tetrahedron_faces2)) assert sorted(cube_faces) == sorted(cube_faces2) assert sorted(octahedron_faces) == sorted(octahedron_faces2) assert sorted(dodecahedron_faces) == sorted(dodecahedron_faces2) assert sorted(icosahedron_faces) == sorted(icosahedron_faces2)
ec04ccc333ef0285a21fb09ec7e0fade79a539adb487bd333b94d61958ac1703
from sympy.core.singleton import S from sympy.combinatorics.fp_groups import (FpGroup, low_index_subgroups, reidemeister_presentation, FpSubgroup, simplify_presentation) from sympy.combinatorics.free_groups import (free_group, FreeGroup) from sympy.testing.pytest import slow """ References ========== [1] Holt, D., Eick, B., O'Brien, E. "Handbook of Computational Group Theory" [2] John J. Cannon; Lucien A. Dimino; George Havas; Jane M. Watson Mathematics of Computation, Vol. 27, No. 123. (Jul., 1973), pp. 463-490. "Implementation and Analysis of the Todd-Coxeter Algorithm" [3] PROC. SECOND INTERNAT. CONF. THEORY OF GROUPS, CANBERRA 1973, pp. 347-356. "A Reidemeister-Schreier program" by George Havas. http://staff.itee.uq.edu.au/havas/1973cdhw.pdf """ def test_low_index_subgroups(): F, x, y = free_group("x, y") # Example 5.10 from [1] Pg. 194 f = FpGroup(F, [x**2, y**3, (x*y)**4]) L = low_index_subgroups(f, 4) t1 = [[[0, 0, 0, 0]], [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 3, 3]], [[0, 0, 1, 2], [2, 2, 2, 0], [1, 1, 0, 1]], [[1, 1, 0, 0], [0, 0, 1, 1]]] for i in range(len(t1)): assert L[i].table == t1[i] f = FpGroup(F, [x**2, y**3, (x*y)**7]) L = low_index_subgroups(f, 15) t2 = [[[0, 0, 0, 0]], [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], [4, 4, 5, 3], [6, 6, 3, 4], [5, 5, 6, 6]], [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], [6, 6, 5, 3], [5, 5, 3, 4], [4, 4, 6, 6]], [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], [6, 6, 5, 3], [7, 7, 3, 4], [4, 4, 8, 9], [5, 5, 10, 11], [11, 11, 9, 6], [9, 9, 6, 8], [12, 12, 11, 7], [8, 8, 7, 10], [10, 10, 13, 14], [14, 14, 14, 12], [13, 13, 12, 13]], [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], [6, 6, 5, 3], [7, 7, 3, 4], [4, 4, 8, 9], [5, 5, 10, 11], [11, 11, 9, 6], [12, 12, 6, 8], [10, 10, 11, 7], [8, 8, 7, 10], [9, 9, 13, 14], [14, 14, 14, 12], [13, 13, 12, 13]], [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], [6, 6, 5, 3], [7, 7, 3, 4], [4, 4, 8, 9], [5, 5, 10, 11], [11, 11, 9, 6], [12, 12, 6, 8], [13, 13, 11, 7], [8, 8, 7, 10], [9, 9, 12, 12], [10, 10, 13, 13]], [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 3, 3], [2, 2, 5, 6] , [7, 7, 6, 4], [8, 8, 4, 5], [5, 5, 8, 9], [6, 6, 9, 7], [10, 10, 7, 8], [9, 9, 11, 12], [11, 11, 12, 10], [13, 13, 10, 11], [12, 12, 13, 13]], [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 3, 3], [2, 2, 5, 6] , [7, 7, 6, 4], [8, 8, 4, 5], [5, 5, 8, 9], [6, 6, 9, 7], [10, 10, 7, 8], [9, 9, 11, 12], [13, 13, 12, 10], [12, 12, 10, 11], [11, 11, 13, 13]], [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 4, 4] , [7, 7, 6, 3], [8, 8, 3, 5], [5, 5, 8, 9], [6, 6, 9, 7], [10, 10, 7, 8], [9, 9, 11, 12], [13, 13, 12, 10], [12, 12, 10, 11], [11, 11, 13, 13]], [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8] , [5, 5, 6, 3], [9, 9, 3, 5], [10, 10, 8, 4], [8, 8, 4, 7], [6, 6, 10, 11], [7, 7, 11, 9], [12, 12, 9, 10], [11, 11, 13, 14], [14, 14, 14, 12], [13, 13, 12, 13]], [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8] , [6, 6, 6, 3], [5, 5, 3, 5], [8, 8, 8, 4], [7, 7, 4, 7]], [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8] , [9, 9, 6, 3], [6, 6, 3, 5], [10, 10, 8, 4], [11, 11, 4, 7], [5, 5, 10, 12], [7, 7, 12, 9], [8, 8, 11, 11], [13, 13, 9, 10], [12, 12, 13, 13]], [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8] , [9, 9, 6, 3], [6, 6, 3, 5], [10, 10, 8, 4], [11, 11, 4, 7], [5, 5, 12, 11], [7, 7, 10, 10], [8, 8, 9, 12], [13, 13, 11, 9], [12, 12, 13, 13]], [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8] , [9, 9, 6, 3], [10, 10, 3, 5], [7, 7, 8, 4], [11, 11, 4, 7], [5, 5, 9, 9], [6, 6, 11, 12], [8, 8, 12, 10], [13, 13, 10, 11], [12, 12, 13, 13]], [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8] , [9, 9, 6, 3], [10, 10, 3, 5], [7, 7, 8, 4], [11, 11, 4, 7], [5, 5, 12, 11], [6, 6, 10, 10], [8, 8, 9, 12], [13, 13, 11, 9], [12, 12, 13, 13]], [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8] , [9, 9, 6, 3], [10, 10, 3, 5], [11, 11, 8, 4], [12, 12, 4, 7], [5, 5, 9, 9], [6, 6, 12, 13], [7, 7, 11, 11], [8, 8, 13, 10], [13, 13, 10, 12]], [[1, 1, 0, 0], [0, 0, 2, 3], [4, 4, 3, 1], [5, 5, 1, 2], [2, 2, 4, 4] , [3, 3, 6, 7], [7, 7, 7, 5], [6, 6, 5, 6]]] for i in range(len(t2)): assert L[i].table == t2[i] f = FpGroup(F, [x**2, y**3, (x*y)**7]) L = low_index_subgroups(f, 10, [x]) t3 = [[[0, 0, 0, 0]], [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], [4, 4, 5, 3], [6, 6, 3, 4], [5, 5, 6, 6]], [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], [6, 6, 5, 3], [5, 5, 3, 4], [4, 4, 6, 6]], [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8], [6, 6, 6, 3], [5, 5, 3, 5], [8, 8, 8, 4], [7, 7, 4, 7]]] for i in range(len(t3)): assert L[i].table == t3[i] def test_subgroup_presentations(): F, x, y = free_group("x, y") f = FpGroup(F, [x**3, y**5, (x*y)**2]) H = [x*y, x**-1*y**-1*x*y*x] p1 = reidemeister_presentation(f, H) assert str(p1) == "((y_1, y_2), (y_1**2, y_2**3, y_2*y_1*y_2*y_1*y_2*y_1))" H = f.subgroup(H) assert (H.generators, H.relators) == p1 f = FpGroup(F, [x**3, y**3, (x*y)**3]) H = [x*y, x*y**-1] p2 = reidemeister_presentation(f, H) assert str(p2) == "((x_0, y_0), (x_0**3, y_0**3, x_0*y_0*x_0*y_0*x_0*y_0))" f = FpGroup(F, [x**2*y**2, y**-1*x*y*x**-3]) H = [x] p3 = reidemeister_presentation(f, H) assert str(p3) == "((x_0,), (x_0**4,))" f = FpGroup(F, [x**3*y**-3, (x*y)**3, (x*y**-1)**2]) H = [x] p4 = reidemeister_presentation(f, H) assert str(p4) == "((x_0,), (x_0**6,))" # this presentation can be improved, the most simplified form # of presentation is <a, b | a^11, b^2, (a*b)^3, (a^4*b*a^-5*b)^2> # See [2] Pg 474 group PSL_2(11) # This is the group PSL_2(11) F, a, b, c = free_group("a, b, c") f = FpGroup(F, [a**11, b**5, c**4, (b*c**2)**2, (a*b*c)**3, (a**4*c**2)**3, b**2*c**-1*b**-1*c, a**4*b**-1*a**-1*b]) H = [a, b, c**2] gens, rels = reidemeister_presentation(f, H) assert str(gens) == "(b_1, c_3)" assert len(rels) == 18 @slow def test_order(): F, x, y = free_group("x, y") f = FpGroup(F, [x**4, y**2, x*y*x**-1*y]) assert f.order() == 8 f = FpGroup(F, [x*y*x**-1*y**-1, y**2]) assert f.order() is S.Infinity F, a, b, c = free_group("a, b, c") f = FpGroup(F, [a**250, b**2, c*b*c**-1*b, c**4, c**-1*a**-1*c*a, a**-1*b**-1*a*b]) assert f.order() == 2000 F, x = free_group("x") f = FpGroup(F, []) assert f.order() is S.Infinity f = FpGroup(free_group('')[0], []) assert f.order() == 1 def test_fp_subgroup(): def _test_subgroup(K, T, S): _gens = T(K.generators) assert all(elem in S for elem in _gens) assert T.is_injective() assert T.image().order() == S.order() F, x, y = free_group("x, y") f = FpGroup(F, [x**4, y**2, x*y*x**-1*y]) S = FpSubgroup(f, [x*y]) assert (x*y)**-3 in S K, T = f.subgroup([x*y], homomorphism=True) assert T(K.generators) == [y*x**-1] _test_subgroup(K, T, S) S = FpSubgroup(f, [x**-1*y*x]) assert x**-1*y**4*x in S assert x**-1*y**4*x**2 not in S K, T = f.subgroup([x**-1*y*x], homomorphism=True) assert T(K.generators[0]**3) == y**3 _test_subgroup(K, T, S) f = FpGroup(F, [x**3, y**5, (x*y)**2]) H = [x*y, x**-1*y**-1*x*y*x] K, T = f.subgroup(H, homomorphism=True) S = FpSubgroup(f, H) _test_subgroup(K, T, S) def test_permutation_methods(): F, x, y = free_group("x, y") # DihedralGroup(8) G = FpGroup(F, [x**2, y**8, x*y*x**-1*y]) T = G._to_perm_group()[1] assert T.is_isomorphism() assert G.center() == [y**4] # DiheadralGroup(4) G = FpGroup(F, [x**2, y**4, x*y*x**-1*y]) S = FpSubgroup(G, G.normal_closure([x])) assert x in S assert y**-1*x*y in S # Z_5xZ_4 G = FpGroup(F, [x*y*x**-1*y**-1, y**5, x**4]) assert G.is_abelian assert G.is_solvable # AlternatingGroup(5) G = FpGroup(F, [x**3, y**2, (x*y)**5]) assert not G.is_solvable # AlternatingGroup(4) G = FpGroup(F, [x**3, y**2, (x*y)**3]) assert len(G.derived_series()) == 3 S = FpSubgroup(G, G.derived_subgroup()) assert S.order() == 4 def test_simplify_presentation(): # ref #16083 G = simplify_presentation(FpGroup(FreeGroup([]), [])) assert not G.generators assert not G.relators def test_cyclic(): F, x, y = free_group("x, y") f = FpGroup(F, [x*y, x**-1*y**-1*x*y*x]) assert f.is_cyclic f = FpGroup(F, [x*y, x*y**-1]) assert f.is_cyclic f = FpGroup(F, [x**4, y**2, x*y*x**-1*y]) assert not f.is_cyclic def test_abelian_invariants(): F, x, y = free_group("x, y") f = FpGroup(F, [x*y, x**-1*y**-1*x*y*x]) assert f.abelian_invariants() == [] f = FpGroup(F, [x*y, x*y**-1]) assert f.abelian_invariants() == [2] f = FpGroup(F, [x**4, y**2, x*y*x**-1*y]) assert f.abelian_invariants() == [2, 4]
a29a6ccca24b2d2a5c1331e07aca48bde4a6102ddf0d9d2a92eb3593b301b781
from sympy.core.sorting import ordered, default_sort_key from sympy.combinatorics.partitions import (Partition, IntegerPartition, RGS_enum, RGS_unrank, RGS_rank, random_integer_partition) from sympy.testing.pytest import raises from sympy.utilities.iterables import partitions from sympy.sets.sets import Set, FiniteSet def test_partition_constructor(): raises(ValueError, lambda: Partition([1, 1, 2])) raises(ValueError, lambda: Partition([1, 2, 3], [2, 3, 4])) raises(ValueError, lambda: Partition(1, 2, 3)) raises(ValueError, lambda: Partition(*list(range(3)))) assert Partition([1, 2, 3], [4, 5]) == Partition([4, 5], [1, 2, 3]) assert Partition({1, 2, 3}, {4, 5}) == Partition([1, 2, 3], [4, 5]) a = FiniteSet(1, 2, 3) b = FiniteSet(4, 5) assert Partition(a, b) == Partition([1, 2, 3], [4, 5]) assert Partition({a, b}) == Partition(FiniteSet(a, b)) assert Partition({a, b}) != Partition(a, b) def test_partition(): from sympy.abc import x a = Partition([1, 2, 3], [4]) b = Partition([1, 2], [3, 4]) c = Partition([x]) l = [a, b, c] l.sort(key=default_sort_key) assert l == [c, a, b] l.sort(key=lambda w: default_sort_key(w, order='rev-lex')) assert l == [c, a, b] assert (a == b) is False assert a <= b assert (a > b) is False assert a != b assert a < b assert (a + 2).partition == [[1, 2], [3, 4]] assert (b - 1).partition == [[1, 2, 4], [3]] assert (a - 1).partition == [[1, 2, 3, 4]] assert (a + 1).partition == [[1, 2, 4], [3]] assert (b + 1).partition == [[1, 2], [3], [4]] assert a.rank == 1 assert b.rank == 3 assert a.RGS == (0, 0, 0, 1) assert b.RGS == (0, 0, 1, 1) def test_integer_partition(): # no zeros in partition raises(ValueError, lambda: IntegerPartition(list(range(3)))) # check fails since 1 + 2 != 100 raises(ValueError, lambda: IntegerPartition(100, list(range(1, 3)))) a = IntegerPartition(8, [1, 3, 4]) b = a.next_lex() c = IntegerPartition([1, 3, 4]) d = IntegerPartition(8, {1: 3, 3: 1, 2: 1}) assert a == c assert a.integer == d.integer assert a.conjugate == [3, 2, 2, 1] assert (a == b) is False assert a <= b assert (a > b) is False assert a != b for i in range(1, 11): next = set() prev = set() a = IntegerPartition([i]) ans = {IntegerPartition(p) for p in partitions(i)} n = len(ans) for j in range(n): next.add(a) a = a.next_lex() IntegerPartition(i, a.partition) # check it by giving i for j in range(n): prev.add(a) a = a.prev_lex() IntegerPartition(i, a.partition) # check it by giving i assert next == ans assert prev == ans assert IntegerPartition([1, 2, 3]).as_ferrers() == '###\n##\n#' assert IntegerPartition([1, 1, 3]).as_ferrers('o') == 'ooo\no\no' assert str(IntegerPartition([1, 1, 3])) == '[3, 1, 1]' assert IntegerPartition([1, 1, 3]).partition == [3, 1, 1] raises(ValueError, lambda: random_integer_partition(-1)) assert random_integer_partition(1) == [1] assert random_integer_partition(10, seed=[1, 3, 2, 1, 5, 1] ) == [5, 2, 1, 1, 1] def test_rgs(): raises(ValueError, lambda: RGS_unrank(-1, 3)) raises(ValueError, lambda: RGS_unrank(3, 0)) raises(ValueError, lambda: RGS_unrank(10, 1)) raises(ValueError, lambda: Partition.from_rgs(list(range(3)), list(range(2)))) raises(ValueError, lambda: Partition.from_rgs(list(range(1, 3)), list(range(2)))) assert RGS_enum(-1) == 0 assert RGS_enum(1) == 1 assert RGS_unrank(7, 5) == [0, 0, 1, 0, 2] assert RGS_unrank(23, 14) == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 2] assert RGS_rank(RGS_unrank(40, 100)) == 40 def test_ordered_partition_9608(): a = Partition([1, 2, 3], [4]) b = Partition([1, 2], [3, 4]) assert list(ordered([a,b], Set._infimum_key))
84c10ac017b15044291783cdc2b76c1014ecacd12b7798aec24607bb872dfb16
from sympy.core import S, Rational from sympy.combinatorics.schur_number import schur_partition, SchurNumber from sympy.testing.randtest import _randint from sympy.testing.pytest import raises from sympy.core.symbol import symbols def _sum_free_test(subset): """ Checks if subset is sum-free(There are no x,y,z in the subset such that x + y = z) """ for i in subset: for j in subset: assert (i + j in subset) is False def test_schur_partition(): raises(ValueError, lambda: schur_partition(S.Infinity)) raises(ValueError, lambda: schur_partition(-1)) raises(ValueError, lambda: schur_partition(0)) assert schur_partition(2) == [[1, 2]] random_number_generator = _randint(1000) for _ in range(5): n = random_number_generator(1, 1000) result = schur_partition(n) t = 0 numbers = [] for item in result: _sum_free_test(item) """ Checks if the occurance of all numbers is exactly one """ t += len(item) for l in item: assert (l in numbers) is False numbers.append(l) assert n == t x = symbols("x") raises(ValueError, lambda: schur_partition(x)) def test_schur_number(): first_known_schur_numbers = {1: 1, 2: 4, 3: 13, 4: 44, 5: 160} for k in first_known_schur_numbers: assert SchurNumber(k) == first_known_schur_numbers[k] assert SchurNumber(S.Infinity) == S.Infinity assert SchurNumber(0) == 0 raises(ValueError, lambda: SchurNumber(0.5)) n = symbols("n") assert SchurNumber(n).lower_bound() == 3**n/2 - Rational(1, 2) assert SchurNumber(8).lower_bound() == 5039
ad3bc6758470d99c3398145e0586befdd4a9906006bc8c83fb9f43e940c10169
from itertools import permutations from sympy.core.expr import unchanged from sympy.core.numbers import Integer from sympy.core.relational import Eq from sympy.core.symbol import Symbol from sympy.core.singleton import S from sympy.combinatorics.permutations import \ Permutation, _af_parity, _af_rmul, _af_rmuln, AppliedPermutation, Cycle from sympy.printing import sstr, srepr, pretty, latex from sympy.testing.pytest import raises, warns_deprecated_sympy rmul = Permutation.rmul a = Symbol('a', integer=True) def test_Permutation(): # don't auto fill 0 raises(ValueError, lambda: Permutation([1])) p = Permutation([0, 1, 2, 3]) # call as bijective assert [p(i) for i in range(p.size)] == list(p) # call as operator assert p(list(range(p.size))) == list(p) # call as function assert list(p(1, 2)) == [0, 2, 1, 3] raises(TypeError, lambda: p(-1)) raises(TypeError, lambda: p(5)) # conversion to list assert list(p) == list(range(4)) assert Permutation(size=4) == Permutation(3) assert Permutation(Permutation(3), size=5) == Permutation(4) # cycle form with size assert Permutation([[1, 2]], size=4) == Permutation([[1, 2], [0], [3]]) # random generation assert Permutation.random(2) in (Permutation([1, 0]), Permutation([0, 1])) p = Permutation([2, 5, 1, 6, 3, 0, 4]) q = Permutation([[1], [0, 3, 5, 6, 2, 4]]) assert len({p, p}) == 1 r = Permutation([1, 3, 2, 0, 4, 6, 5]) ans = Permutation(_af_rmuln(*[w.array_form for w in (p, q, r)])).array_form assert rmul(p, q, r).array_form == ans # make sure no other permutation of p, q, r could have given # that answer for a, b, c in permutations((p, q, r)): if (a, b, c) == (p, q, r): continue assert rmul(a, b, c).array_form != ans assert p.support() == list(range(7)) assert q.support() == [0, 2, 3, 4, 5, 6] assert Permutation(p.cyclic_form).array_form == p.array_form assert p.cardinality == 5040 assert q.cardinality == 5040 assert q.cycles == 2 assert rmul(q, p) == Permutation([4, 6, 1, 2, 5, 3, 0]) assert rmul(p, q) == Permutation([6, 5, 3, 0, 2, 4, 1]) assert _af_rmul(p.array_form, q.array_form) == \ [6, 5, 3, 0, 2, 4, 1] assert rmul(Permutation([[1, 2, 3], [0, 4]]), Permutation([[1, 2, 4], [0], [3]])).cyclic_form == \ [[0, 4, 2], [1, 3]] assert q.array_form == [3, 1, 4, 5, 0, 6, 2] assert q.cyclic_form == [[0, 3, 5, 6, 2, 4]] assert q.full_cyclic_form == [[0, 3, 5, 6, 2, 4], [1]] assert p.cyclic_form == [[0, 2, 1, 5], [3, 6, 4]] t = p.transpositions() assert t == [(0, 5), (0, 1), (0, 2), (3, 4), (3, 6)] assert Permutation.rmul(*[Permutation(Cycle(*ti)) for ti in (t)]) assert Permutation([1, 0]).transpositions() == [(0, 1)] assert p**13 == p assert q**0 == Permutation(list(range(q.size))) assert q**-2 == ~q**2 assert q**2 == Permutation([5, 1, 0, 6, 3, 2, 4]) assert q**3 == q**2*q assert q**4 == q**2*q**2 a = Permutation(1, 3) b = Permutation(2, 0, 3) I = Permutation(3) assert ~a == a**-1 assert a*~a == I assert a*b**-1 == a*~b ans = Permutation(0, 5, 3, 1, 6)(2, 4) assert (p + q.rank()).rank() == ans.rank() assert (p + q.rank())._rank == ans.rank() assert (q + p.rank()).rank() == ans.rank() raises(TypeError, lambda: p + Permutation(list(range(10)))) assert (p - q.rank()).rank() == Permutation(0, 6, 3, 1, 2, 5, 4).rank() assert p.rank() - q.rank() < 0 # for coverage: make sure mod is used assert (q - p.rank()).rank() == Permutation(1, 4, 6, 2)(3, 5).rank() assert p*q == Permutation(_af_rmuln(*[list(w) for w in (q, p)])) assert p*Permutation([]) == p assert Permutation([])*p == p assert p*Permutation([[0, 1]]) == Permutation([2, 5, 0, 6, 3, 1, 4]) assert Permutation([[0, 1]])*p == Permutation([5, 2, 1, 6, 3, 0, 4]) pq = p ^ q assert pq == Permutation([5, 6, 0, 4, 1, 2, 3]) assert pq == rmul(q, p, ~q) qp = q ^ p assert qp == Permutation([4, 3, 6, 2, 1, 5, 0]) assert qp == rmul(p, q, ~p) raises(ValueError, lambda: p ^ Permutation([])) assert p.commutator(q) == Permutation(0, 1, 3, 4, 6, 5, 2) assert q.commutator(p) == Permutation(0, 2, 5, 6, 4, 3, 1) assert p.commutator(q) == ~q.commutator(p) raises(ValueError, lambda: p.commutator(Permutation([]))) assert len(p.atoms()) == 7 assert q.atoms() == {0, 1, 2, 3, 4, 5, 6} assert p.inversion_vector() == [2, 4, 1, 3, 1, 0] assert q.inversion_vector() == [3, 1, 2, 2, 0, 1] assert Permutation.from_inversion_vector(p.inversion_vector()) == p assert Permutation.from_inversion_vector(q.inversion_vector()).array_form\ == q.array_form raises(ValueError, lambda: Permutation.from_inversion_vector([0, 2])) assert Permutation([i for i in range(500, -1, -1)]).inversions() == 125250 s = Permutation([0, 4, 1, 3, 2]) assert s.parity() == 0 _ = s.cyclic_form # needed to create a value for _cyclic_form assert len(s._cyclic_form) != s.size and s.parity() == 0 assert not s.is_odd assert s.is_even assert Permutation([0, 1, 4, 3, 2]).parity() == 1 assert _af_parity([0, 4, 1, 3, 2]) == 0 assert _af_parity([0, 1, 4, 3, 2]) == 1 s = Permutation([0]) assert s.is_Singleton assert Permutation([]).is_Empty r = Permutation([3, 2, 1, 0]) assert (r**2).is_Identity assert rmul(~p, p).is_Identity assert (~p)**13 == Permutation([5, 2, 0, 4, 6, 1, 3]) assert ~(r**2).is_Identity assert p.max() == 6 assert p.min() == 0 q = Permutation([[6], [5], [0, 1, 2, 3, 4]]) assert q.max() == 4 assert q.min() == 0 p = Permutation([1, 5, 2, 0, 3, 6, 4]) q = Permutation([[1, 2, 3, 5, 6], [0, 4]]) assert p.ascents() == [0, 3, 4] assert q.ascents() == [1, 2, 4] assert r.ascents() == [] assert p.descents() == [1, 2, 5] assert q.descents() == [0, 3, 5] assert Permutation(r.descents()).is_Identity assert p.inversions() == 7 # test the merge-sort with a longer permutation big = list(p) + list(range(p.max() + 1, p.max() + 130)) assert Permutation(big).inversions() == 7 assert p.signature() == -1 assert q.inversions() == 11 assert q.signature() == -1 assert rmul(p, ~p).inversions() == 0 assert rmul(p, ~p).signature() == 1 assert p.order() == 6 assert q.order() == 10 assert (p**(p.order())).is_Identity assert p.length() == 6 assert q.length() == 7 assert r.length() == 4 assert p.runs() == [[1, 5], [2], [0, 3, 6], [4]] assert q.runs() == [[4], [2, 3, 5], [0, 6], [1]] assert r.runs() == [[3], [2], [1], [0]] assert p.index() == 8 assert q.index() == 8 assert r.index() == 3 assert p.get_precedence_distance(q) == q.get_precedence_distance(p) assert p.get_adjacency_distance(q) == p.get_adjacency_distance(q) assert p.get_positional_distance(q) == p.get_positional_distance(q) p = Permutation([0, 1, 2, 3]) q = Permutation([3, 2, 1, 0]) assert p.get_precedence_distance(q) == 6 assert p.get_adjacency_distance(q) == 3 assert p.get_positional_distance(q) == 8 p = Permutation([0, 3, 1, 2, 4]) q = Permutation.josephus(4, 5, 2) assert p.get_adjacency_distance(q) == 3 raises(ValueError, lambda: p.get_adjacency_distance(Permutation([]))) raises(ValueError, lambda: p.get_positional_distance(Permutation([]))) raises(ValueError, lambda: p.get_precedence_distance(Permutation([]))) a = [Permutation.unrank_nonlex(4, i) for i in range(5)] iden = Permutation([0, 1, 2, 3]) for i in range(5): for j in range(i + 1, 5): assert a[i].commutes_with(a[j]) == \ (rmul(a[i], a[j]) == rmul(a[j], a[i])) if a[i].commutes_with(a[j]): assert a[i].commutator(a[j]) == iden assert a[j].commutator(a[i]) == iden a = Permutation(3) b = Permutation(0, 6, 3)(1, 2) assert a.cycle_structure == {1: 4} assert b.cycle_structure == {2: 1, 3: 1, 1: 2} # issue 11130 raises(ValueError, lambda: Permutation(3, size=3)) raises(ValueError, lambda: Permutation([1, 2, 0, 3], size=3)) def test_Permutation_subclassing(): # Subclass that adds permutation application on iterables class CustomPermutation(Permutation): def __call__(self, *i): try: return super().__call__(*i) except TypeError: pass try: perm_obj = i[0] return [self._array_form[j] for j in perm_obj] except TypeError: raise TypeError('unrecognized argument') def __eq__(self, other): if isinstance(other, Permutation): return self._hashable_content() == other._hashable_content() else: return super().__eq__(other) def __hash__(self): return super().__hash__() p = CustomPermutation([1, 2, 3, 0]) q = Permutation([1, 2, 3, 0]) assert p == q raises(TypeError, lambda: q([1, 2])) assert [2, 3] == p([1, 2]) assert type(p * q) == CustomPermutation assert type(q * p) == Permutation # True because q.__mul__(p) is called! # Run all tests for the Permutation class also on the subclass def wrapped_test_Permutation(): # Monkeypatch the class definition in the globals globals()['__Perm'] = globals()['Permutation'] globals()['Permutation'] = CustomPermutation test_Permutation() globals()['Permutation'] = globals()['__Perm'] # Restore del globals()['__Perm'] wrapped_test_Permutation() def test_josephus(): assert Permutation.josephus(4, 6, 1) == Permutation([3, 1, 0, 2, 5, 4]) assert Permutation.josephus(1, 5, 1).is_Identity def test_ranking(): assert Permutation.unrank_lex(5, 10).rank() == 10 p = Permutation.unrank_lex(15, 225) assert p.rank() == 225 p1 = p.next_lex() assert p1.rank() == 226 assert Permutation.unrank_lex(15, 225).rank() == 225 assert Permutation.unrank_lex(10, 0).is_Identity p = Permutation.unrank_lex(4, 23) assert p.rank() == 23 assert p.array_form == [3, 2, 1, 0] assert p.next_lex() is None p = Permutation([1, 5, 2, 0, 3, 6, 4]) q = Permutation([[1, 2, 3, 5, 6], [0, 4]]) a = [Permutation.unrank_trotterjohnson(4, i).array_form for i in range(5)] assert a == [[0, 1, 2, 3], [0, 1, 3, 2], [0, 3, 1, 2], [3, 0, 1, 2], [3, 0, 2, 1] ] assert [Permutation(pa).rank_trotterjohnson() for pa in a] == list(range(5)) assert Permutation([0, 1, 2, 3]).next_trotterjohnson() == \ Permutation([0, 1, 3, 2]) assert q.rank_trotterjohnson() == 2283 assert p.rank_trotterjohnson() == 3389 assert Permutation([1, 0]).rank_trotterjohnson() == 1 a = Permutation(list(range(3))) b = a l = [] tj = [] for i in range(6): l.append(a) tj.append(b) a = a.next_lex() b = b.next_trotterjohnson() assert a == b is None assert {tuple(a) for a in l} == {tuple(a) for a in tj} p = Permutation([2, 5, 1, 6, 3, 0, 4]) q = Permutation([[6], [5], [0, 1, 2, 3, 4]]) assert p.rank() == 1964 assert q.rank() == 870 assert Permutation([]).rank_nonlex() == 0 prank = p.rank_nonlex() assert prank == 1600 assert Permutation.unrank_nonlex(7, 1600) == p qrank = q.rank_nonlex() assert qrank == 41 assert Permutation.unrank_nonlex(7, 41) == Permutation(q.array_form) a = [Permutation.unrank_nonlex(4, i).array_form for i in range(24)] assert a == [ [1, 2, 3, 0], [3, 2, 0, 1], [1, 3, 0, 2], [1, 2, 0, 3], [2, 3, 1, 0], [2, 0, 3, 1], [3, 0, 1, 2], [2, 0, 1, 3], [1, 3, 2, 0], [3, 0, 2, 1], [1, 0, 3, 2], [1, 0, 2, 3], [2, 1, 3, 0], [2, 3, 0, 1], [3, 1, 0, 2], [2, 1, 0, 3], [3, 2, 1, 0], [0, 2, 3, 1], [0, 3, 1, 2], [0, 2, 1, 3], [3, 1, 2, 0], [0, 3, 2, 1], [0, 1, 3, 2], [0, 1, 2, 3]] N = 10 p1 = Permutation(a[0]) for i in range(1, N+1): p1 = p1*Permutation(a[i]) p2 = Permutation.rmul_with_af(*[Permutation(h) for h in a[N::-1]]) assert p1 == p2 ok = [] p = Permutation([1, 0]) for i in range(3): ok.append(p.array_form) p = p.next_nonlex() if p is None: ok.append(None) break assert ok == [[1, 0], [0, 1], None] assert Permutation([3, 2, 0, 1]).next_nonlex() == Permutation([1, 3, 0, 2]) assert [Permutation(pa).rank_nonlex() for pa in a] == list(range(24)) def test_mul(): a, b = [0, 2, 1, 3], [0, 1, 3, 2] assert _af_rmul(a, b) == [0, 2, 3, 1] assert _af_rmuln(a, b, list(range(4))) == [0, 2, 3, 1] assert rmul(Permutation(a), Permutation(b)).array_form == [0, 2, 3, 1] a = Permutation([0, 2, 1, 3]) b = (0, 1, 3, 2) c = (3, 1, 2, 0) assert Permutation.rmul(a, b, c) == Permutation([1, 2, 3, 0]) assert Permutation.rmul(a, c) == Permutation([3, 2, 1, 0]) raises(TypeError, lambda: Permutation.rmul(b, c)) n = 6 m = 8 a = [Permutation.unrank_nonlex(n, i).array_form for i in range(m)] h = list(range(n)) for i in range(m): h = _af_rmul(h, a[i]) h2 = _af_rmuln(*a[:i + 1]) assert h == h2 def test_args(): p = Permutation([(0, 3, 1, 2), (4, 5)]) assert p._cyclic_form is None assert Permutation(p) == p assert p.cyclic_form == [[0, 3, 1, 2], [4, 5]] assert p._array_form == [3, 2, 0, 1, 5, 4] p = Permutation((0, 3, 1, 2)) assert p._cyclic_form is None assert p._array_form == [0, 3, 1, 2] assert Permutation([0]) == Permutation((0, )) assert Permutation([[0], [1]]) == Permutation(((0, ), (1, ))) == \ Permutation(((0, ), [1])) assert Permutation([[1, 2]]) == Permutation([0, 2, 1]) assert Permutation([[1], [4, 2]]) == Permutation([0, 1, 4, 3, 2]) assert Permutation([[1], [4, 2]], size=1) == Permutation([0, 1, 4, 3, 2]) assert Permutation( [[1], [4, 2]], size=6) == Permutation([0, 1, 4, 3, 2, 5]) assert Permutation([[0, 1], [0, 2]]) == Permutation(0, 1, 2) assert Permutation([], size=3) == Permutation([0, 1, 2]) assert Permutation(3).list(5) == [0, 1, 2, 3, 4] assert Permutation(3).list(-1) == [] assert Permutation(5)(1, 2).list(-1) == [0, 2, 1] assert Permutation(5)(1, 2).list() == [0, 2, 1, 3, 4, 5] raises(ValueError, lambda: Permutation([1, 2], [0])) # enclosing brackets needed raises(ValueError, lambda: Permutation([[1, 2], 0])) # enclosing brackets needed on 0 raises(ValueError, lambda: Permutation([1, 1, 0])) raises(ValueError, lambda: Permutation([4, 5], size=10)) # where are 0-3? # but this is ok because cycles imply that only those listed moved assert Permutation(4, 5) == Permutation([0, 1, 2, 3, 5, 4]) def test_Cycle(): assert str(Cycle()) == '()' assert Cycle(Cycle(1,2)) == Cycle(1, 2) assert Cycle(1,2).copy() == Cycle(1,2) assert list(Cycle(1, 3, 2)) == [0, 3, 1, 2] assert Cycle(1, 2)(2, 3) == Cycle(1, 3, 2) assert Cycle(1, 2)(2, 3)(4, 5) == Cycle(1, 3, 2)(4, 5) assert Permutation(Cycle(1, 2)(2, 1, 0, 3)).cyclic_form, Cycle(0, 2, 1) raises(ValueError, lambda: Cycle().list()) assert Cycle(1, 2).list() == [0, 2, 1] assert Cycle(1, 2).list(4) == [0, 2, 1, 3] assert Cycle(3).list(2) == [0, 1] assert Cycle(3).list(6) == [0, 1, 2, 3, 4, 5] assert Permutation(Cycle(1, 2), size=4) == \ Permutation([0, 2, 1, 3]) assert str(Cycle(1, 2)(4, 5)) == '(1 2)(4 5)' assert str(Cycle(1, 2)) == '(1 2)' assert Cycle(Permutation(list(range(3)))) == Cycle() assert Cycle(1, 2).list() == [0, 2, 1] assert Cycle(1, 2).list(4) == [0, 2, 1, 3] assert Cycle().size == 0 raises(ValueError, lambda: Cycle((1, 2))) raises(ValueError, lambda: Cycle(1, 2, 1)) raises(TypeError, lambda: Cycle(1, 2)*{}) raises(ValueError, lambda: Cycle(4)[a]) raises(ValueError, lambda: Cycle(2, -4, 3)) # check round-trip p = Permutation([[1, 2], [4, 3]], size=5) assert Permutation(Cycle(p)) == p def test_from_sequence(): assert Permutation.from_sequence('SymPy') == Permutation(4)(0, 1, 3) assert Permutation.from_sequence('SymPy', key=lambda x: x.lower()) == \ Permutation(4)(0, 2)(1, 3) def test_resize(): p = Permutation(0, 1, 2) assert p.resize(5) == Permutation(0, 1, 2, size=5) assert p.resize(4) == Permutation(0, 1, 2, size=4) assert p.resize(3) == p raises(ValueError, lambda: p.resize(2)) p = Permutation(0, 1, 2)(3, 4)(5, 6) assert p.resize(3) == Permutation(0, 1, 2) raises(ValueError, lambda: p.resize(4)) def test_printing_cyclic(): p1 = Permutation([0, 2, 1]) assert repr(p1) == 'Permutation(1, 2)' assert str(p1) == '(1 2)' p2 = Permutation() assert repr(p2) == 'Permutation()' assert str(p2) == '()' p3 = Permutation([1, 2, 0, 3]) assert repr(p3) == 'Permutation(3)(0, 1, 2)' def test_printing_non_cyclic(): p1 = Permutation([0, 1, 2, 3, 4, 5]) assert srepr(p1, perm_cyclic=False) == 'Permutation([], size=6)' assert sstr(p1, perm_cyclic=False) == 'Permutation([], size=6)' p2 = Permutation([0, 1, 2]) assert srepr(p2, perm_cyclic=False) == 'Permutation([0, 1, 2])' assert sstr(p2, perm_cyclic=False) == 'Permutation([0, 1, 2])' p3 = Permutation([0, 2, 1]) assert srepr(p3, perm_cyclic=False) == 'Permutation([0, 2, 1])' assert sstr(p3, perm_cyclic=False) == 'Permutation([0, 2, 1])' p4 = Permutation([0, 1, 3, 2, 4, 5, 6, 7]) assert srepr(p4, perm_cyclic=False) == 'Permutation([0, 1, 3, 2], size=8)' def test_deprecated_print_cyclic(): p = Permutation(0, 1, 2) try: Permutation.print_cyclic = True with warns_deprecated_sympy(): assert sstr(p) == '(0 1 2)' with warns_deprecated_sympy(): assert srepr(p) == 'Permutation(0, 1, 2)' with warns_deprecated_sympy(): assert pretty(p) == '(0 1 2)' with warns_deprecated_sympy(): assert latex(p) == r'\left( 0\; 1\; 2\right)' Permutation.print_cyclic = False with warns_deprecated_sympy(): assert sstr(p) == 'Permutation([1, 2, 0])' with warns_deprecated_sympy(): assert srepr(p) == 'Permutation([1, 2, 0])' with warns_deprecated_sympy(): assert pretty(p, use_unicode=False) == '/0 1 2\\\n\\1 2 0/' with warns_deprecated_sympy(): assert latex(p) == \ r'\begin{pmatrix} 0 & 1 & 2 \\ 1 & 2 & 0 \end{pmatrix}' finally: Permutation.print_cyclic = None def test_permutation_equality(): a = Permutation(0, 1, 2) b = Permutation(0, 1, 2) assert Eq(a, b) is S.true c = Permutation(0, 2, 1) assert Eq(a, c) is S.false d = Permutation(0, 1, 2, size=4) assert unchanged(Eq, a, d) e = Permutation(0, 2, 1, size=4) assert unchanged(Eq, a, e) i = Permutation() assert unchanged(Eq, i, 0) assert unchanged(Eq, 0, i) def test_issue_17661(): c1 = Cycle(1,2) c2 = Cycle(1,2) assert c1 == c2 assert repr(c1) == 'Cycle(1, 2)' assert c1 == c2 def test_permutation_apply(): x = Symbol('x') p = Permutation(0, 1, 2) assert p.apply(0) == 1 assert isinstance(p.apply(0), Integer) assert p.apply(x) == AppliedPermutation(p, x) assert AppliedPermutation(p, x).subs(x, 0) == 1 x = Symbol('x', integer=False) raises(NotImplementedError, lambda: p.apply(x)) x = Symbol('x', negative=True) raises(NotImplementedError, lambda: p.apply(x)) def test_AppliedPermutation(): x = Symbol('x') p = Permutation(0, 1, 2) raises(ValueError, lambda: AppliedPermutation((0, 1, 2), x)) assert AppliedPermutation(p, 1, evaluate=True) == 2 assert AppliedPermutation(p, 1, evaluate=False).__class__ == \ AppliedPermutation
ea9ca12d85791ee5efc7adebfa01951ebf0b4ab1915dca43b9d8459fd7c1a97f
from sympy.combinatorics.subsets import Subset, ksubsets from sympy.testing.pytest import raises def test_subset(): a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) assert a.next_binary() == Subset(['b'], ['a', 'b', 'c', 'd']) assert a.prev_binary() == Subset(['c'], ['a', 'b', 'c', 'd']) assert a.next_lexicographic() == Subset(['d'], ['a', 'b', 'c', 'd']) assert a.prev_lexicographic() == Subset(['c'], ['a', 'b', 'c', 'd']) assert a.next_gray() == Subset(['c'], ['a', 'b', 'c', 'd']) assert a.prev_gray() == Subset(['d'], ['a', 'b', 'c', 'd']) assert a.rank_binary == 3 assert a.rank_lexicographic == 14 assert a.rank_gray == 2 assert a.cardinality == 16 assert a.size == 2 assert Subset.bitlist_from_subset(a, ['a', 'b', 'c', 'd']) == '0011' a = Subset([2, 5, 7], [1, 2, 3, 4, 5, 6, 7]) assert a.next_binary() == Subset([2, 5, 6], [1, 2, 3, 4, 5, 6, 7]) assert a.prev_binary() == Subset([2, 5], [1, 2, 3, 4, 5, 6, 7]) assert a.next_lexicographic() == Subset([2, 6], [1, 2, 3, 4, 5, 6, 7]) assert a.prev_lexicographic() == Subset([2, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7]) assert a.next_gray() == Subset([2, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7]) assert a.prev_gray() == Subset([2, 5], [1, 2, 3, 4, 5, 6, 7]) assert a.rank_binary == 37 assert a.rank_lexicographic == 93 assert a.rank_gray == 57 assert a.cardinality == 128 superset = ['a', 'b', 'c', 'd'] assert Subset.unrank_binary(4, superset).rank_binary == 4 assert Subset.unrank_gray(10, superset).rank_gray == 10 superset = [1, 2, 3, 4, 5, 6, 7, 8, 9] assert Subset.unrank_binary(33, superset).rank_binary == 33 assert Subset.unrank_gray(25, superset).rank_gray == 25 a = Subset([], ['a', 'b', 'c', 'd']) i = 1 while a.subset != Subset(['d'], ['a', 'b', 'c', 'd']).subset: a = a.next_lexicographic() i = i + 1 assert i == 16 i = 1 while a.subset != Subset([], ['a', 'b', 'c', 'd']).subset: a = a.prev_lexicographic() i = i + 1 assert i == 16 raises(ValueError, lambda: Subset(['a', 'b'], ['a'])) raises(ValueError, lambda: Subset(['a'], ['b', 'c'])) raises(ValueError, lambda: Subset.subset_from_bitlist(['a', 'b'], '010')) assert Subset(['a'], ['a', 'b']) != Subset(['b'], ['a', 'b']) assert Subset(['a'], ['a', 'b']) != Subset(['a'], ['a', 'c']) def test_ksubsets(): assert list(ksubsets([1, 2, 3], 2)) == [(1, 2), (1, 3), (2, 3)] assert list(ksubsets([1, 2, 3, 4, 5], 2)) == [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]
877b4fca3300efd33d40c734ace960557537d65674b3fc6863f60856c573d058
from sympy.combinatorics.free_groups import free_group, FreeGroup from sympy.core import Symbol from sympy.testing.pytest import raises from sympy.core.numbers import oo F, x, y, z = free_group("x, y, z") def test_FreeGroup__init__(): x, y, z = map(Symbol, "xyz") assert len(FreeGroup("x, y, z").generators) == 3 assert len(FreeGroup(x).generators) == 1 assert len(FreeGroup(("x", "y", "z"))) == 3 assert len(FreeGroup((x, y, z)).generators) == 3 def test_free_group(): G, a, b, c = free_group("a, b, c") assert F.generators == (x, y, z) assert x*z**2 in F assert x in F assert y*z**-1 in F assert (y*z)**0 in F assert a not in F assert a**0 not in F assert len(F) == 3 assert str(F) == '<free group on the generators (x, y, z)>' assert not F == G assert F.order() is oo assert F.is_abelian == False assert F.center() == {F.identity} (e,) = free_group("") assert e.order() == 1 assert e.generators == () assert e.elements == {e.identity} assert e.is_abelian == True def test_FreeGroup__hash__(): assert hash(F) def test_FreeGroup__eq__(): assert free_group("x, y, z")[0] == free_group("x, y, z")[0] assert free_group("x, y, z")[0] is free_group("x, y, z")[0] assert free_group("x, y, z")[0] != free_group("a, x, y")[0] assert free_group("x, y, z")[0] is not free_group("a, x, y")[0] assert free_group("x, y")[0] != free_group("x, y, z")[0] assert free_group("x, y")[0] is not free_group("x, y, z")[0] assert free_group("x, y, z")[0] != free_group("x, y")[0] assert free_group("x, y, z")[0] is not free_group("x, y")[0] def test_FreeGroup__getitem__(): assert F[0:] == FreeGroup("x, y, z") assert F[1:] == FreeGroup("y, z") assert F[2:] == FreeGroup("z") def test_FreeGroupElm__hash__(): assert hash(x*y*z) def test_FreeGroupElm_copy(): f = x*y*z**3 g = f.copy() h = x*y*z**7 assert f == g assert f != h def test_FreeGroupElm_inverse(): assert x.inverse() == x**-1 assert (x*y).inverse() == y**-1*x**-1 assert (y*x*y**-1).inverse() == y*x**-1*y**-1 assert (y**2*x**-1).inverse() == x*y**-2 def test_FreeGroupElm_type_error(): raises(TypeError, lambda: 2/x) raises(TypeError, lambda: x**2 + y**2) raises(TypeError, lambda: x/2) def test_FreeGroupElm_methods(): assert (x**0).order() == 1 assert (y**2).order() is oo assert (x**-1*y).commutator(x) == y**-1*x**-1*y*x assert len(x**2*y**-1) == 3 assert len(x**-1*y**3*z) == 5 def test_FreeGroupElm_eliminate_word(): w = x**5*y*x**2*y**-4*x assert w.eliminate_word( x, x**2 ) == x**10*y*x**4*y**-4*x**2 w3 = x**2*y**3*x**-1*y assert w3.eliminate_word(x, x**2) == x**4*y**3*x**-2*y assert w3.eliminate_word(x, y) == y**5 assert w3.eliminate_word(x, y**4) == y**8 assert w3.eliminate_word(y, x**-1) == x**-3 assert w3.eliminate_word(x, y*z) == y*z*y*z*y**3*z**-1 assert (y**-3).eliminate_word(y, x**-1*z**-1) == z*x*z*x*z*x #assert w3.eliminate_word(x, y*x) == y*x*y*x**2*y*x*y*x*y*x*z**3 #assert w3.eliminate_word(x, x*y) == x*y*x**2*y*x*y*x*y*x*y*z**3 def test_FreeGroupElm_array_form(): assert (x*z).array_form == ((Symbol('x'), 1), (Symbol('z'), 1)) assert (x**2*z*y*x**-2).array_form == \ ((Symbol('x'), 2), (Symbol('z'), 1), (Symbol('y'), 1), (Symbol('x'), -2)) assert (x**-2*y**-1).array_form == ((Symbol('x'), -2), (Symbol('y'), -1)) def test_FreeGroupElm_letter_form(): assert (x**3).letter_form == (Symbol('x'), Symbol('x'), Symbol('x')) assert (x**2*z**-2*x).letter_form == \ (Symbol('x'), Symbol('x'), -Symbol('z'), -Symbol('z'), Symbol('x')) def test_FreeGroupElm_ext_rep(): assert (x**2*z**-2*x).ext_rep == \ (Symbol('x'), 2, Symbol('z'), -2, Symbol('x'), 1) assert (x**-2*y**-1).ext_rep == (Symbol('x'), -2, Symbol('y'), -1) assert (x*z).ext_rep == (Symbol('x'), 1, Symbol('z'), 1) def test_FreeGroupElm__mul__pow__(): x1 = x.group.dtype(((Symbol('x'), 1),)) assert x**2 == x1*x assert (x**2*y*x**-2)**4 == x**2*y**4*x**-2 assert (x**2)**2 == x**4 assert (x**-1)**-1 == x assert (x**-1)**0 == F.identity assert (y**2)**-2 == y**-4 assert x**2*x**-1 == x assert x**2*y**2*y**-1 == x**2*y assert x*x**-1 == F.identity assert x/x == F.identity assert x/x**2 == x**-1 assert (x**2*y)/(x**2*y**-1) == x**2*y**2*x**-2 assert (x**2*y)/(y**-1*x**2) == x**2*y*x**-2*y assert x*(x**-1*y*z*y**-1) == y*z*y**-1 assert x**2*(x**-2*y**-1*z**2*y) == y**-1*z**2*y def test_FreeGroupElm__len__(): assert len(x**5*y*x**2*y**-4*x) == 13 assert len(x**17) == 17 assert len(y**0) == 0 def test_FreeGroupElm_comparison(): assert not (x*y == y*x) assert x**0 == y**0 assert x**2 < y**3 assert not x**3 < y**2 assert x*y < x**2*y assert x**2*y**2 < y**4 assert not y**4 < y**-4 assert not y**4 < x**-4 assert y**-2 < y**2 assert x**2 <= y**2 assert x**2 <= x**2 assert not y*z > z*y assert x > x**-1 assert not x**2 >= y**2 def test_FreeGroupElm_syllables(): w = x**5*y*x**2*y**-4*x assert w.number_syllables() == 5 assert w.exponent_syllable(2) == 2 assert w.generator_syllable(3) == Symbol('y') assert w.sub_syllables(1, 2) == y assert w.sub_syllables(3, 3) == F.identity def test_FreeGroup_exponents(): w1 = x**2*y**3 assert w1.exponent_sum(x) == 2 assert w1.exponent_sum(x**-1) == -2 assert w1.generator_count(x) == 2 w2 = x**2*y**4*x**-3 assert w2.exponent_sum(x) == -1 assert w2.generator_count(x) == 5 def test_FreeGroup_generators(): assert (x**2*y**4*z**-1).contains_generators() == {x, y, z} assert (x**-1*y**3).contains_generators() == {x, y} def test_FreeGroupElm_words(): w = x**5*y*x**2*y**-4*x assert w.subword(2, 6) == x**3*y assert w.subword(3, 2) == F.identity assert w.subword(6, 10) == x**2*y**-2 assert w.substituted_word(0, 7, y**-1) == y**-1*x*y**-4*x assert w.substituted_word(0, 7, y**2*x) == y**2*x**2*y**-4*x
e6946cc39e44432af7d66529deec1c6b0ffea6eb57709203ce603b912edc5d43
from sympy.concrete.products import (Product, product) from sympy.concrete.summations import Sum from sympy.core.function import (Derivative, Function, diff) from sympy.core.numbers import (Rational, oo, pi) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, symbols) from sympy.functions.combinatorial.factorials import (rf, factorial) 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.tensor_functions import KroneckerDelta from sympy.simplify.combsimp import combsimp from sympy.simplify.simplify import simplify from sympy.testing.pytest import raises a, k, n, m, x = symbols('a,k,n,m,x', integer=True) f = Function('f') def test_karr_convention(): # Test the Karr product 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 for sums on page 309 and # essentially in section 1.4, definition 3. For products # we can find in analogy: # # \prod_{m <= i < n} f(i) 'has the obvious meaning' for m < n # \prod_{m <= i < n} f(i) = 0 for m = n # \prod_{m <= i < n} f(i) = 1 / \prod_{n <= i < m} f(i) for m > n # # It is important to note that he defines all products with # the upper limit being *exclusive*. # In contrast, SymPy and the usual mathematical notation has: # # prod_{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: # # \prod_{m <= i < n} f(i) = \prod_{i = m}^{n-1} f(i) # # where we intentionally used two different ways to typeset the # products and its limits. i = Symbol("i", integer=True) k = Symbol("k", integer=True) j = Symbol("j", integer=True, positive=True) # A simple example with a concrete factors and symbolic limits. # The normal product: m = k and n = k + j and therefore m < n: m = k n = k + j a = m b = n - 1 S1 = Product(i**2, (i, a, b)).doit() # The reversed product: m = k + j and n = k and therefore m > n: m = k + j n = k a = m b = n - 1 S2 = Product(i**2, (i, a, b)).doit() assert S1 * S2 == 1 # Test the empty product: m = k and n = k and therefore m = n: m = k n = k a = m b = n - 1 Sz = Product(i**2, (i, a, b)).doit() assert Sz == 1 # Another example this time with an unspecified factor and # numeric limits. (We can not do both tests in the same example.) f = Function("f") # The normal product with m < n: m = 2 n = 11 a = m b = n - 1 S1 = Product(f(i), (i, a, b)).doit() # The reversed product with m > n: m = 11 n = 2 a = m b = n - 1 S2 = Product(f(i), (i, a, b)).doit() assert simplify(S1 * S2) == 1 # Test the empty product with m = n: m = 5 n = 5 a = m b = n - 1 Sz = Product(f(i), (i, a, b)).doit() assert Sz == 1 def test_karr_proposition_2a(): # Test Karr, page 309, proposition 2, part a i, u, v = symbols('i u v', integer=True) def test_the_product(m, n): # g g = i**3 + 2*i**2 - 3*i # f = Delta g f = simplify(g.subs(i, i+1) / g) # The product a = m b = n - 1 P = Product(f, (i, a, b)).doit() # Test if Product_{m <= i < n} f(i) = g(n) / g(m) assert combsimp(P / (g.subs(i, n) / g.subs(i, m))) == 1 # m < n test_the_product(u, u + v) # m = n test_the_product(u, u) # m > n test_the_product(u + v, u) def test_karr_proposition_2b(): # Test Karr, page 309, proposition 2, part b i, u, v, w = symbols('i u v w', integer=True) def test_the_product(l, n, m): # Productmand s = i**3 # First product a = l b = n - 1 S1 = Product(s, (i, a, b)).doit() # Second product a = l b = m - 1 S2 = Product(s, (i, a, b)).doit() # Third product a = m b = n - 1 S3 = Product(s, (i, a, b)).doit() # Test if S1 = S2 * S3 as required assert combsimp(S1 / (S2 * S3)) == 1 # l < m < n test_the_product(u, u + v, u + v + w) # l < m = n test_the_product(u, u + v, u + v) # l < m > n test_the_product(u, u + v + w, v) # l = m < n test_the_product(u, u, u + v) # l = m = n test_the_product(u, u, u) # l = m > n test_the_product(u + v, u + v, u) # l > m < n test_the_product(u + v, u, u + w) # l > m = n test_the_product(u + v, u, u) # l > m > n test_the_product(u + v + w, u + v, u) def test_simple_products(): assert product(2, (k, a, n)) == 2**(n - a + 1) assert product(k, (k, 1, n)) == factorial(n) assert product(k**3, (k, 1, n)) == factorial(n)**3 assert product(k + 1, (k, 0, n - 1)) == factorial(n) assert product(k + 1, (k, a, n - 1)) == rf(1 + a, n - a) assert product(cos(k), (k, 0, 5)) == cos(1)*cos(2)*cos(3)*cos(4)*cos(5) assert product(cos(k), (k, 3, 5)) == cos(3)*cos(4)*cos(5) assert product(cos(k), (k, 1, Rational(5, 2))) != cos(1)*cos(2) assert isinstance(product(k**k, (k, 1, n)), Product) assert Product(x**k, (k, 1, n)).variables == [k] raises(ValueError, lambda: Product(n)) raises(ValueError, lambda: Product(n, k)) raises(ValueError, lambda: Product(n, k, 1)) raises(ValueError, lambda: Product(n, k, 1, 10)) raises(ValueError, lambda: Product(n, (k, 1))) assert product(1, (n, 1, oo)) == 1 # issue 8301 assert product(2, (n, 1, oo)) is oo assert product(-1, (n, 1, oo)).func is Product def test_multiple_products(): assert product(x, (n, 1, k), (k, 1, m)) == x**(m**2/2 + m/2) assert product(f(n), ( n, 1, m), (m, 1, k)) == Product(f(n), (n, 1, m), (m, 1, k)).doit() assert Product(f(n), (m, 1, k), (n, 1, k)).doit() == \ Product(Product(f(n), (m, 1, k)), (n, 1, k)).doit() == \ product(f(n), (m, 1, k), (n, 1, k)) == \ product(product(f(n), (m, 1, k)), (n, 1, k)) == \ Product(f(n)**k, (n, 1, k)) assert Product( x, (x, 1, k), (k, 1, n)).doit() == Product(factorial(k), (k, 1, n)) assert Product(x**k, (n, 1, k), (k, 1, m)).variables == [n, k] def test_rational_products(): assert product(1 + 1/k, (k, 1, n)) == rf(2, n)/factorial(n) def test_special_products(): # Wallis product assert product((4*k)**2 / (4*k**2 - 1), (k, 1, n)) == \ 4**n*factorial(n)**2/rf(S.Half, n)/rf(Rational(3, 2), n) # Euler's product formula for sin assert product(1 + a/k**2, (k, 1, n)) == \ rf(1 - sqrt(-a), n)*rf(1 + sqrt(-a), n)/factorial(n)**2 def test__eval_product(): from sympy.abc import i, n # issue 4809 a = Function('a') assert product(2*a(i), (i, 1, n)) == 2**n * Product(a(i), (i, 1, n)) # issue 4810 assert product(2**i, (i, 1, n)) == 2**(n/2 + n**2/2) k, m = symbols('k m', integer=True) assert product(2**i, (i, k, m)) == 2**(-k**2/2 + k/2 + m**2/2 + m/2) n = Symbol('n', negative=True, integer=True) p = Symbol('p', positive=True, integer=True) assert product(2**i, (i, n, p)) == 2**(-n**2/2 + n/2 + p**2/2 + p/2) assert product(2**i, (i, p, n)) == 2**(n**2/2 + n/2 - p**2/2 + p/2) def test_product_pow(): # issue 4817 assert product(2**f(k), (k, 1, n)) == 2**Sum(f(k), (k, 1, n)) assert product(2**(2*f(k)), (k, 1, n)) == 2**Sum(2*f(k), (k, 1, n)) def test_infinite_product(): # issue 5737 assert isinstance(Product(2**(1/factorial(n)), (n, 0, oo)), Product) def test_conjugate_transpose(): p = Product(x**k, (k, 1, 3)) assert p.adjoint().doit() == p.doit().adjoint() assert p.conjugate().doit() == p.doit().conjugate() assert p.transpose().doit() == p.doit().transpose() A, B = symbols("A B", commutative=False) p = Product(A*B**k, (k, 1, 3)) assert p.adjoint().doit() == p.doit().adjoint() assert p.conjugate().doit() == p.doit().conjugate() assert p.transpose().doit() == p.doit().transpose() p = Product(B**k*A, (k, 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_simplify_prod(): y, t, b, c = symbols('y, t, b, c', integer = True) _simplify = lambda e: simplify(e, doit=False) assert _simplify(Product(x*y, (x, n, m), (y, a, k)) * \ Product(y, (x, n, m), (y, a, k))) == \ Product(x*y**2, (x, n, m), (y, a, k)) assert _simplify(3 * y* Product(x, (x, n, m)) * Product(x, (x, m + 1, a))) \ == 3 * y * Product(x, (x, n, a)) assert _simplify(Product(x, (x, k + 1, a)) * Product(x, (x, n, k))) == \ Product(x, (x, n, a)) assert _simplify(Product(x, (x, k + 1, a)) * Product(x + 1, (x, n, k))) == \ Product(x, (x, k + 1, a)) * Product(x + 1, (x, n, k)) assert _simplify(Product(x, (t, a, b)) * Product(y, (t, a, b)) * \ Product(x, (t, b+1, c))) == Product(x*y, (t, a, b)) * \ Product(x, (t, b+1, c)) assert _simplify(Product(x, (t, a, b)) * Product(x, (t, b+1, c)) * \ Product(y, (t, a, b))) == Product(x*y, (t, a, b)) * \ Product(x, (t, b+1, c)) def test_change_index(): b, y, c, d, z = symbols('b, y, c, d, z', integer = True) assert Product(x, (x, a, b)).change_index(x, x + 1, y) == \ Product(y - 1, (y, a + 1, b + 1)) assert Product(x**2, (x, a, b)).change_index(x, x - 1) == \ Product((x + 1)**2, (x, a - 1, b - 1)) assert Product(x**2, (x, a, b)).change_index(x, -x, y) == \ Product((-y)**2, (y, -b, -a)) assert Product(x, (x, a, b)).change_index(x, -x - 1) == \ Product(-x - 1, (x, - b - 1, -a - 1)) assert Product(x*y, (x, a, b), (y, c, d)).change_index(x, x - 1, z) == \ Product((z + 1)*y, (z, a - 1, b - 1), (y, c, d)) def test_reorder(): b, y, c, d, z = symbols('b, y, c, d, z', integer = True) assert Product(x*y, (x, a, b), (y, c, d)).reorder((0, 1)) == \ Product(x*y, (y, c, d), (x, a, b)) assert Product(x, (x, a, b), (x, c, d)).reorder((0, 1)) == \ Product(x, (x, c, d), (x, a, b)) assert Product(x*y + z, (x, a, b), (z, m, n), (y, c, d)).reorder(\ (2, 0), (0, 1)) == Product(x*y + z, (z, m, n), (y, c, d), (x, a, b)) assert Product(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\ (0, 1), (1, 2), (0, 2)) == \ Product(x*y*z, (x, a, b), (z, m, n), (y, c, d)) assert Product(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\ (x, y), (y, z), (x, z)) == \ Product(x*y*z, (x, a, b), (z, m, n), (y, c, d)) assert Product(x*y, (x, a, b), (y, c, d)).reorder((x, 1)) == \ Product(x*y, (y, c, d), (x, a, b)) assert Product(x*y, (x, a, b), (y, c, d)).reorder((y, x)) == \ Product(x*y, (y, c, d), (x, a, b)) def test_Product_is_convergent(): assert Product(1/n**2, (n, 1, oo)).is_convergent() is S.false assert Product(exp(1/n**2), (n, 1, oo)).is_convergent() is S.true assert Product(1/n, (n, 1, oo)).is_convergent() is S.false assert Product(1 + 1/n, (n, 1, oo)).is_convergent() is S.false assert Product(1 + 1/n**2, (n, 1, oo)).is_convergent() is S.true def test_reverse_order(): x, y, a, b, c, d= symbols('x, y, a, b, c, d', integer = True) assert Product(x, (x, 0, 3)).reverse_order(0) == Product(1/x, (x, 4, -1)) assert Product(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(0, 1) == \ Product(x*y, (x, 6, 0), (y, 7, -1)) assert Product(x, (x, 1, 2)).reverse_order(0) == Product(1/x, (x, 3, 0)) assert Product(x, (x, 1, 3)).reverse_order(0) == Product(1/x, (x, 4, 0)) assert Product(x, (x, 1, a)).reverse_order(0) == Product(1/x, (x, a + 1, 0)) assert Product(x, (x, a, 5)).reverse_order(0) == Product(1/x, (x, 6, a - 1)) assert Product(x, (x, a + 1, a + 5)).reverse_order(0) == \ Product(1/x, (x, a + 6, a)) assert Product(x, (x, a + 1, a + 2)).reverse_order(0) == \ Product(1/x, (x, a + 3, a)) assert Product(x, (x, a + 1, a + 1)).reverse_order(0) == \ Product(1/x, (x, a + 2, a)) assert Product(x, (x, a, b)).reverse_order(0) == Product(1/x, (x, b + 1, a - 1)) assert Product(x, (x, a, b)).reverse_order(x) == Product(1/x, (x, b + 1, a - 1)) assert Product(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1) == \ Product(x*y, (x, b + 1, a - 1), (y, 6, 1)) assert Product(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x) == \ Product(x*y, (x, b + 1, a - 1), (y, 6, 1)) def test_issue_9983(): n = Symbol('n', integer=True, positive=True) p = Product(1 + 1/n**Rational(2, 3), (n, 1, oo)) assert p.is_convergent() is S.false assert product(1 + 1/n**Rational(2, 3), (n, 1, oo)) == p.doit() def test_issue_13546(): n = Symbol('n') k = Symbol('k') p = Product(n + 1 / 2**k, (k, 0, n-1)).doit() assert p.subs(n, 2).doit() == Rational(15, 2) def test_issue_14036(): a, n = symbols('a n') assert product(1 - a**2 / (n*pi)**2, [n, 1, oo]) != 0 def test_rewrite_Sum(): assert Product(1 - S.Half**2/k**2, (k, 1, oo)).rewrite(Sum) == \ exp(Sum(log(1 - 1/(4*k**2)), (k, 1, oo))) def test_KroneckerDelta_Product(): y = Symbol('y') assert Product(x*KroneckerDelta(x, y), (x, 0, 1)).doit() == 0 def test_issue_20848(): _i = Dummy('i') t, y, z = symbols('t y z') assert diff(Product(x, (y, 1, z)), x).as_dummy() == Sum(Product(x, (y, 1, _i - 1))*Product(x, (y, _i + 1, z)), (_i, 1, z)).as_dummy() assert diff(Product(x, (y, 1, z)), x).doit() == x**z*z/x assert diff(Product(x, (y, x, z)), x) == Derivative(Product(x, (y, x, z)), x) assert diff(Product(t, (x, 1, z)), x) == S(0) assert Product(sin(n*x), (n, -1, 1)).diff(x).doit() == S(0)
fe2dd6180c67bcb7754eebf31ab22f43b624f88e85de65fae3049d136a772c42
from sympy.concrete.guess import ( find_simple_recurrence_vector, find_simple_recurrence, rationalize, guess_generating_function_rational, guess_generating_function, guess ) from sympy.concrete.products import Product from sympy.core.function import Function from sympy.core.numbers import Rational 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 (RisingFactorial, factorial) from sympy.functions.combinatorial.numbers import fibonacci from sympy.functions.elementary.exponential import exp def test_find_simple_recurrence_vector(): assert find_simple_recurrence_vector( [fibonacci(k) for k in range(12)]) == [1, -1, -1] def test_find_simple_recurrence(): a = Function('a') n = Symbol('n') assert find_simple_recurrence([fibonacci(k) for k in range(12)]) == ( -a(n) - a(n + 1) + a(n + 2)) f = Function('a') i = Symbol('n') a = [1, 1, 1] for k in range(15): a.append(5*a[-1]-3*a[-2]+8*a[-3]) assert find_simple_recurrence(a, A=f, N=i) == ( -8*f(i) + 3*f(i + 1) - 5*f(i + 2) + f(i + 3)) assert find_simple_recurrence([0, 2, 15, 74, 12, 3, 0, 1, 2, 85, 4, 5, 63]) == 0 def test_rationalize(): from mpmath import cos, pi, mpf assert rationalize(cos(pi/3)) == S.Half assert rationalize(mpf("0.333333333333333")) == Rational(1, 3) assert rationalize(mpf("-0.333333333333333")) == Rational(-1, 3) assert rationalize(pi, maxcoeff = 250) == Rational(355, 113) def test_guess_generating_function_rational(): x = Symbol('x') assert guess_generating_function_rational([fibonacci(k) for k in range(5, 15)]) == ((3*x + 5)/(-x**2 - x + 1)) def test_guess_generating_function(): x = Symbol('x') assert guess_generating_function([fibonacci(k) for k in range(5, 15)])['ogf'] == ((3*x + 5)/(-x**2 - x + 1)) assert guess_generating_function( [1, 2, 5, 14, 41, 124, 383, 1200, 3799, 12122, 38919])['ogf'] == ( (1/(x**4 + 2*x**2 - 4*x + 1))**S.Half) assert guess_generating_function(sympify( "[3/2, 11/2, 0, -121/2, -363/2, 121, 4719/2, 11495/2, -8712, -178717/2]") )['ogf'] == (x + Rational(3, 2))/(11*x**2 - 3*x + 1) assert guess_generating_function([factorial(k) for k in range(12)], types=['egf'])['egf'] == 1/(-x + 1) assert guess_generating_function([k+1 for k in range(12)], types=['egf']) == {'egf': (x + 1)*exp(x), 'lgdegf': (x + 2)/(x + 1)} def test_guess(): i0, i1 = symbols('i0 i1') assert guess([1, 2, 6, 24, 120], evaluate=False) == [Product(i1 + 1, (i1, 1, i0 - 1))] assert guess([1, 2, 6, 24, 120]) == [RisingFactorial(2, i0 - 1)] assert guess([1, 2, 7, 42, 429, 7436, 218348, 10850216], niter=4) == [ 2**(i0 - 1)*(Rational(27, 16))**(i0**2/2 - 3*i0/2 + 1)*Product(RisingFactorial(Rational(5, 3), i1 - 1)*RisingFactorial(Rational(7, 3), i1 - 1)/(RisingFactorial(Rational(3, 2), i1 - 1)*RisingFactorial(Rational(5, 2), i1 - 1)), (i1, 1, i0 - 1))] assert guess([1, 0, 2]) == [] x, y = symbols('x y') guess([1, 2, 6, 24, 120], variables=[x, y]) == [RisingFactorial(2, x - 1)]
fb1f42cad5cf484f9e75572a871694765d23d7f015be09577955716ca6a95cfd
"""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.exponential import (exp, log) 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() == -exp(m*log(a) + m*log(b))*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
baf4ebb1e85cb12d29b469c90f61f9b60814177ef904846a499822bc2ac8454b
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) 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.) f = Function("f") # 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(): f, g = symbols('f g', cls=Function) # 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) f = Function("f") 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(): f = Function("f") 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(): f = Function('f') 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} 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(Function('f')(x) * y * z, (x, a, b)) / (y * z)) \ == Sum(Function('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(): f = Function('f') 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)))
c825fc9a78cf57404005aae02720d4412f2aeaab2c27753bbe75d2b686fd6cde
import sympy import tempfile import os from sympy.core.mod import Mod from sympy.core.relational import Eq from sympy.core.symbol import symbols from sympy.external import import_module from sympy.tensor import IndexedBase, Idx from sympy.utilities.autowrap import autowrap, ufuncify, CodeWrapError from sympy.testing.pytest import skip numpy = import_module('numpy', min_module_version='1.6.1') Cython = import_module('Cython', min_module_version='0.15.1') f2py = import_module('numpy.f2py', import_kwargs={'fromlist': ['f2py']}) f2pyworks = False if f2py: try: autowrap(symbols('x'), 'f95', 'f2py') except (CodeWrapError, ImportError, OSError): f2pyworks = False else: f2pyworks = True a, b, c = symbols('a b c') n, m, d = symbols('n m d', integer=True) A, B, C = symbols('A B C', cls=IndexedBase) i = Idx('i', m) j = Idx('j', n) k = Idx('k', d) def has_module(module): """ Return True if module exists, otherwise run skip(). module should be a string. """ # To give a string of the module name to skip(), this function takes a # string. So we don't waste time running import_module() more than once, # just map the three modules tested here in this dict. modnames = {'numpy': numpy, 'Cython': Cython, 'f2py': f2py} if modnames[module]: if module == 'f2py' and not f2pyworks: skip("Couldn't run f2py.") return True skip("Couldn't import %s." % module) # # test runners used by several language-backend combinations # def runtest_autowrap_twice(language, backend): f = autowrap((((a + b)/c)**5).expand(), language, backend) g = autowrap((((a + b)/c)**4).expand(), language, backend) # check that autowrap updates the module name. Else, g gives the same as f assert f(1, -2, 1) == -1.0 assert g(1, -2, 1) == 1.0 def runtest_autowrap_trace(language, backend): has_module('numpy') trace = autowrap(A[i, i], language, backend) assert trace(numpy.eye(100)) == 100 def runtest_autowrap_matrix_vector(language, backend): has_module('numpy') x, y = symbols('x y', cls=IndexedBase) expr = Eq(y[i], A[i, j]*x[j]) mv = autowrap(expr, language, backend) # compare with numpy's dot product M = numpy.random.rand(10, 20) x = numpy.random.rand(20) y = numpy.dot(M, x) assert numpy.sum(numpy.abs(y - mv(M, x))) < 1e-13 def runtest_autowrap_matrix_matrix(language, backend): has_module('numpy') expr = Eq(C[i, j], A[i, k]*B[k, j]) matmat = autowrap(expr, language, backend) # compare with numpy's dot product M1 = numpy.random.rand(10, 20) M2 = numpy.random.rand(20, 15) M3 = numpy.dot(M1, M2) assert numpy.sum(numpy.abs(M3 - matmat(M1, M2))) < 1e-13 def runtest_ufuncify(language, backend): has_module('numpy') a, b, c = symbols('a b c') fabc = ufuncify([a, b, c], a*b + c, backend=backend) facb = ufuncify([a, c, b], a*b + c, backend=backend) grid = numpy.linspace(-2, 2, 50) b = numpy.linspace(-5, 4, 50) c = numpy.linspace(-1, 1, 50) expected = grid*b + c numpy.testing.assert_allclose(fabc(grid, b, c), expected) numpy.testing.assert_allclose(facb(grid, c, b), expected) def runtest_issue_10274(language, backend): expr = (a - b + c)**(13) tmp = tempfile.mkdtemp() f = autowrap(expr, language, backend, tempdir=tmp, helpers=('helper', a - b + c, (a, b, c))) assert f(1, 1, 1) == 1 for file in os.listdir(tmp): if file.startswith("wrapped_code_") and file.endswith(".c"): fil = open(tmp + '/' + file) lines = fil.readlines() assert lines[0] == "/******************************************************************************\n" assert "Code generated with SymPy " + sympy.__version__ in lines[1] assert lines[2:] == [ " * *\n", " * See http://www.sympy.org/ for more information. *\n", " * *\n", " * This file is part of 'autowrap' *\n", " ******************************************************************************/\n", "#include " + '"' + file[:-1]+ 'h"' + "\n", "#include <math.h>\n", "\n", "double helper(double a, double b, double c) {\n", "\n", " double helper_result;\n", " helper_result = a - b + c;\n", " return helper_result;\n", "\n", "}\n", "\n", "double autofunc(double a, double b, double c) {\n", "\n", " double autofunc_result;\n", " autofunc_result = pow(helper(a, b, c), 13);\n", " return autofunc_result;\n", "\n", "}\n", ] def runtest_issue_15337(language, backend): has_module('numpy') # NOTE : autowrap was originally designed to only accept an iterable for # the kwarg "helpers", but in issue 10274 the user mistakenly thought that # if there was only a single helper it did not need to be passed via an # iterable that wrapped the helper tuple. There were no tests for this # behavior so when the code was changed to accept a single tuple it broke # the original behavior. These tests below ensure that both now work. a, b, c, d, e = symbols('a, b, c, d, e') expr = (a - b + c - d + e)**13 exp_res = (1. - 2. + 3. - 4. + 5.)**13 f = autowrap(expr, language, backend, args=(a, b, c, d, e), helpers=('f1', a - b + c, (a, b, c))) numpy.testing.assert_allclose(f(1, 2, 3, 4, 5), exp_res) f = autowrap(expr, language, backend, args=(a, b, c, d, e), helpers=(('f1', a - b, (a, b)), ('f2', c - d, (c, d)))) numpy.testing.assert_allclose(f(1, 2, 3, 4, 5), exp_res) def test_issue_15230(): has_module('f2py') x, y = symbols('x, y') expr = Mod(x, 3.0) - Mod(y, -2.0) f = autowrap(expr, args=[x, y], language='F95') exp_res = float(expr.xreplace({x: 3.5, y: 2.7}).evalf()) assert abs(f(3.5, 2.7) - exp_res) < 1e-14 x, y = symbols('x, y', integer=True) expr = Mod(x, 3) - Mod(y, -2) f = autowrap(expr, args=[x, y], language='F95') assert f(3, 2) == expr.xreplace({x: 3, y: 2}) # # tests of language-backend combinations # # f2py def test_wrap_twice_f95_f2py(): has_module('f2py') runtest_autowrap_twice('f95', 'f2py') def test_autowrap_trace_f95_f2py(): has_module('f2py') runtest_autowrap_trace('f95', 'f2py') def test_autowrap_matrix_vector_f95_f2py(): has_module('f2py') runtest_autowrap_matrix_vector('f95', 'f2py') def test_autowrap_matrix_matrix_f95_f2py(): has_module('f2py') runtest_autowrap_matrix_matrix('f95', 'f2py') def test_ufuncify_f95_f2py(): has_module('f2py') runtest_ufuncify('f95', 'f2py') def test_issue_15337_f95_f2py(): has_module('f2py') runtest_issue_15337('f95', 'f2py') # Cython def test_wrap_twice_c_cython(): has_module('Cython') runtest_autowrap_twice('C', 'cython') def test_autowrap_trace_C_Cython(): has_module('Cython') runtest_autowrap_trace('C99', 'cython') def test_autowrap_matrix_vector_C_cython(): has_module('Cython') runtest_autowrap_matrix_vector('C99', 'cython') def test_autowrap_matrix_matrix_C_cython(): has_module('Cython') runtest_autowrap_matrix_matrix('C99', 'cython') def test_ufuncify_C_Cython(): has_module('Cython') runtest_ufuncify('C99', 'cython') def test_issue_10274_C_cython(): has_module('Cython') runtest_issue_10274('C89', 'cython') def test_issue_15337_C_cython(): has_module('Cython') runtest_issue_15337('C89', 'cython') def test_autowrap_custom_printer(): has_module('Cython') from sympy.core.numbers import pi from sympy.utilities.codegen import C99CodeGen from sympy.printing.c import C99CodePrinter class PiPrinter(C99CodePrinter): def _print_Pi(self, expr): return "S_PI" printer = PiPrinter() gen = C99CodeGen(printer=printer) gen.preprocessor_statements.append('#include "shortpi.h"') expr = pi * a expected = ( '#include "%s"\n' '#include <math.h>\n' '#include "shortpi.h"\n' '\n' 'double autofunc(double a) {\n' '\n' ' double autofunc_result;\n' ' autofunc_result = S_PI*a;\n' ' return autofunc_result;\n' '\n' '}\n' ) tmpdir = tempfile.mkdtemp() # write a trivial header file to use in the generated code open(os.path.join(tmpdir, 'shortpi.h'), 'w').write('#define S_PI 3.14') func = autowrap(expr, backend='cython', tempdir=tmpdir, code_gen=gen) assert func(4.2) == 3.14 * 4.2 # check that the generated code is correct for filename in os.listdir(tmpdir): if filename.startswith('wrapped_code') and filename.endswith('.c'): with open(os.path.join(tmpdir, filename)) as f: lines = f.readlines() expected = expected % filename.replace('.c', '.h') assert ''.join(lines[7:]) == expected # Numpy def test_ufuncify_numpy(): # This test doesn't use Cython, but if Cython works, then there is a valid # C compiler, which is needed. has_module('Cython') runtest_ufuncify('C99', 'numpy')
0956b0ec3d3ee83391820efc43a6f7e5234a9f4e4f94ac1626ea973ae53ea9d6
# This testfile tests SymPy <-> SciPy compatibility # Don't test any SymPy features here. Just pure interaction with SciPy. # Always write regular SymPy tests for anything, that can be tested in pure # Python (without scipy). Here we test everything, that a user may need when # using SymPy with SciPy from sympy.external import import_module scipy = import_module('scipy') if not scipy: #bin/test will not execute any tests now disabled = True from sympy.functions.special.bessel import jn_zeros def eq(a, b, tol=1e-6): for x, y in zip(a, b): if not (abs(x - y) < tol): return False return True def test_jn_zeros(): assert eq(jn_zeros(0, 4, method="scipy"), [3.141592, 6.283185, 9.424777, 12.566370]) assert eq(jn_zeros(1, 4, method="scipy"), [4.493409, 7.725251, 10.904121, 14.066193]) assert eq(jn_zeros(2, 4, method="scipy"), [5.763459, 9.095011, 12.322940, 15.514603]) assert eq(jn_zeros(3, 4, method="scipy"), [6.987932, 10.417118, 13.698023, 16.923621]) assert eq(jn_zeros(4, 4, method="scipy"), [8.182561, 11.704907, 15.039664, 18.301255])
528c791e6e956637c34f16ea598e79c0f9f308731730ed20653013df2cc495da
# This tests the compilation and execution of the source code generated with # utilities.codegen. The compilation takes place in a temporary directory that # is removed after the test. By default the test directory is always removed, # but this behavior can be changed by setting the environment variable # SYMPY_TEST_CLEAN_TEMP to: # export SYMPY_TEST_CLEAN_TEMP=always : the default behavior. # export SYMPY_TEST_CLEAN_TEMP=success : only remove the directories of working tests. # export SYMPY_TEST_CLEAN_TEMP=never : never remove the directories with the test code. # When a directory is not removed, the necessary information is printed on # screen to find the files that belong to the (failed) tests. If a test does # not fail, py.test captures all the output and you will not see the directories # corresponding to the successful tests. Use the --nocapture option to see all # the output. # All tests below have a counterpart in utilities/test/test_codegen.py. In the # latter file, the resulting code is compared with predefined strings, without # compilation or execution. # All the generated Fortran code should conform with the Fortran 95 standard, # and all the generated C code should be ANSI C, which facilitates the # incorporation in various projects. The tests below assume that the binary cc # is somewhere in the path and that it can compile ANSI C code. from sympy.abc import x, y, z from sympy.testing.pytest import skip from sympy.utilities.codegen import codegen, make_routine, get_code_generator import sys import os import tempfile import subprocess # templates for the main program that will test the generated code. main_template = {} main_template['F95'] = """ program main include "codegen.h" integer :: result; result = 0 %(statements)s call exit(result) end program """ main_template['C89'] = """ #include "codegen.h" #include <stdio.h> #include <math.h> int main() { int result = 0; %(statements)s return result; } """ main_template['C99'] = main_template['C89'] # templates for the numerical tests numerical_test_template = {} numerical_test_template['C89'] = """ if (fabs(%(call)s)>%(threshold)s) { printf("Numerical validation failed: %(call)s=%%e threshold=%(threshold)s\\n", %(call)s); result = -1; } """ numerical_test_template['C99'] = numerical_test_template['C89'] numerical_test_template['F95'] = """ if (abs(%(call)s)>%(threshold)s) then write(6,"('Numerical validation failed:')") write(6,"('%(call)s=',e15.5,'threshold=',e15.5)") %(call)s, %(threshold)s result = -1; end if """ # command sequences for supported compilers compile_commands = {} compile_commands['cc'] = [ "cc -c codegen.c -o codegen.o", "cc -c main.c -o main.o", "cc main.o codegen.o -lm -o test.exe" ] compile_commands['gfortran'] = [ "gfortran -c codegen.f90 -o codegen.o", "gfortran -ffree-line-length-none -c main.f90 -o main.o", "gfortran main.o codegen.o -o test.exe" ] compile_commands['g95'] = [ "g95 -c codegen.f90 -o codegen.o", "g95 -ffree-line-length-huge -c main.f90 -o main.o", "g95 main.o codegen.o -o test.exe" ] compile_commands['ifort'] = [ "ifort -c codegen.f90 -o codegen.o", "ifort -c main.f90 -o main.o", "ifort main.o codegen.o -o test.exe" ] combinations_lang_compiler = [ ('C89', 'cc'), ('C99', 'cc'), ('F95', 'ifort'), ('F95', 'gfortran'), ('F95', 'g95') ] def try_run(commands): """Run a series of commands and only return True if all ran fine.""" null = open(os.devnull, 'w') for command in commands: retcode = subprocess.call(command, stdout=null, shell=True, stderr=subprocess.STDOUT) if retcode != 0: return False return True def run_test(label, routines, numerical_tests, language, commands, friendly=True): """A driver for the codegen tests. This driver assumes that a compiler ifort is present in the PATH and that ifort is (at least) a Fortran 90 compiler. The generated code is written in a temporary directory, together with a main program that validates the generated code. The test passes when the compilation and the validation run correctly. """ # Check input arguments before touching the file system language = language.upper() assert language in main_template assert language in numerical_test_template # Check that environment variable makes sense clean = os.getenv('SYMPY_TEST_CLEAN_TEMP', 'always').lower() if clean not in ('always', 'success', 'never'): raise ValueError("SYMPY_TEST_CLEAN_TEMP must be one of the following: 'always', 'success' or 'never'.") # Do all the magic to compile, run and validate the test code # 1) prepare the temporary working directory, switch to that dir work = tempfile.mkdtemp("_sympy_%s_test" % language, "%s_" % label) oldwork = os.getcwd() os.chdir(work) # 2) write the generated code if friendly: # interpret the routines as a name_expr list and call the friendly # function codegen codegen(routines, language, "codegen", to_files=True) else: code_gen = get_code_generator(language, "codegen") code_gen.write(routines, "codegen", to_files=True) # 3) write a simple main program that links to the generated code, and that # includes the numerical tests test_strings = [] for fn_name, args, expected, threshold in numerical_tests: call_string = "%s(%s)-(%s)" % ( fn_name, ",".join(str(arg) for arg in args), expected) if language == "F95": call_string = fortranize_double_constants(call_string) threshold = fortranize_double_constants(str(threshold)) test_strings.append(numerical_test_template[language] % { "call": call_string, "threshold": threshold, }) if language == "F95": f_name = "main.f90" elif language.startswith("C"): f_name = "main.c" else: raise NotImplementedError( "FIXME: filename extension unknown for language: %s" % language) with open(f_name, "w") as f: f.write( main_template[language] % {'statements': "".join(test_strings)}) # 4) Compile and link compiled = try_run(commands) # 5) Run if compiled if compiled: executed = try_run(["./test.exe"]) else: executed = False # 6) Clean up stuff if clean == 'always' or (clean == 'success' and compiled and executed): def safe_remove(filename): if os.path.isfile(filename): os.remove(filename) safe_remove("codegen.f90") safe_remove("codegen.c") safe_remove("codegen.h") safe_remove("codegen.o") safe_remove("main.f90") safe_remove("main.c") safe_remove("main.o") safe_remove("test.exe") os.chdir(oldwork) os.rmdir(work) else: print("TEST NOT REMOVED: %s" % work, file=sys.stderr) os.chdir(oldwork) # 7) Do the assertions in the end assert compiled, "failed to compile %s code with:\n%s" % ( language, "\n".join(commands)) assert executed, "failed to execute %s code from:\n%s" % ( language, "\n".join(commands)) def fortranize_double_constants(code_string): """ Replaces every literal float with literal doubles """ import re pattern_exp = re.compile(r'\d+(\.)?\d*[eE]-?\d+') pattern_float = re.compile(r'\d+\.\d*(?!\d*d)') def subs_exp(matchobj): return re.sub('[eE]', 'd', matchobj.group(0)) def subs_float(matchobj): return "%sd0" % matchobj.group(0) code_string = pattern_exp.sub(subs_exp, code_string) code_string = pattern_float.sub(subs_float, code_string) return code_string def is_feasible(language, commands): # This test should always work, otherwise the compiler is not present. routine = make_routine("test", x) numerical_tests = [ ("test", ( 1.0,), 1.0, 1e-15), ("test", (-1.0,), -1.0, 1e-15), ] try: run_test("is_feasible", [routine], numerical_tests, language, commands, friendly=False) return True except AssertionError: return False valid_lang_commands = [] invalid_lang_compilers = [] for lang, compiler in combinations_lang_compiler: commands = compile_commands[compiler] if is_feasible(lang, commands): valid_lang_commands.append((lang, commands)) else: invalid_lang_compilers.append((lang, compiler)) # We test all language-compiler combinations, just to report what is skipped def test_C89_cc(): if ("C89", 'cc') in invalid_lang_compilers: skip("`cc' command didn't work as expected (C89)") def test_C99_cc(): if ("C99", 'cc') in invalid_lang_compilers: skip("`cc' command didn't work as expected (C99)") def test_F95_ifort(): if ("F95", 'ifort') in invalid_lang_compilers: skip("`ifort' command didn't work as expected") def test_F95_gfortran(): if ("F95", 'gfortran') in invalid_lang_compilers: skip("`gfortran' command didn't work as expected") def test_F95_g95(): if ("F95", 'g95') in invalid_lang_compilers: skip("`g95' command didn't work as expected") # Here comes the actual tests def test_basic_codegen(): numerical_tests = [ ("test", (1.0, 6.0, 3.0), 21.0, 1e-15), ("test", (-1.0, 2.0, -2.5), -2.5, 1e-15), ] name_expr = [("test", (x + y)*z)] for lang, commands in valid_lang_commands: run_test("basic_codegen", name_expr, numerical_tests, lang, commands) def test_intrinsic_math1_codegen(): # not included: log10 from sympy.core.evalf import N from sympy.functions import ln from sympy.functions.elementary.exponential import log from sympy.functions.elementary.hyperbolic import (cosh, sinh, tanh) from sympy.functions.elementary.integers import (ceiling, floor) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, tan) name_expr = [ ("test_fabs", abs(x)), ("test_acos", acos(x)), ("test_asin", asin(x)), ("test_atan", atan(x)), ("test_cos", cos(x)), ("test_cosh", cosh(x)), ("test_log", log(x)), ("test_ln", ln(x)), ("test_sin", sin(x)), ("test_sinh", sinh(x)), ("test_sqrt", sqrt(x)), ("test_tan", tan(x)), ("test_tanh", tanh(x)), ] numerical_tests = [] for name, expr in name_expr: for xval in 0.2, 0.5, 0.8: expected = N(expr.subs(x, xval)) numerical_tests.append((name, (xval,), expected, 1e-14)) for lang, commands in valid_lang_commands: if lang.startswith("C"): name_expr_C = [("test_floor", floor(x)), ("test_ceil", ceiling(x))] else: name_expr_C = [] run_test("intrinsic_math1", name_expr + name_expr_C, numerical_tests, lang, commands) def test_instrinsic_math2_codegen(): # not included: frexp, ldexp, modf, fmod from sympy.core.evalf import N from sympy.functions.elementary.trigonometric import atan2 name_expr = [ ("test_atan2", atan2(x, y)), ("test_pow", x**y), ] numerical_tests = [] for name, expr in name_expr: for xval, yval in (0.2, 1.3), (0.5, -0.2), (0.8, 0.8): expected = N(expr.subs(x, xval).subs(y, yval)) numerical_tests.append((name, (xval, yval), expected, 1e-14)) for lang, commands in valid_lang_commands: run_test("intrinsic_math2", name_expr, numerical_tests, lang, commands) def test_complicated_codegen(): from sympy.core.evalf import N from sympy.functions.elementary.trigonometric import (cos, sin, tan) name_expr = [ ("test1", ((sin(x) + cos(y) + tan(z))**7).expand()), ("test2", cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))), ] numerical_tests = [] for name, expr in name_expr: for xval, yval, zval in (0.2, 1.3, -0.3), (0.5, -0.2, 0.0), (0.8, 2.1, 0.8): expected = N(expr.subs(x, xval).subs(y, yval).subs(z, zval)) numerical_tests.append((name, (xval, yval, zval), expected, 1e-12)) for lang, commands in valid_lang_commands: run_test( "complicated_codegen", name_expr, numerical_tests, lang, commands)
65bb8a51523e5fb9aaa98996498d405a10be8810a49076a3898aa8bd853e896a
""" test_pythonmpq.py Test the PythonMPQ class for consistency with gmpy2's mpq type. If gmpy2 is installed run the same tests for both. """ from fractions import Fraction from decimal import Decimal import pickle from typing import Callable, List, Tuple, Type from sympy.testing.pytest import raises from sympy.external.pythonmpq import PythonMPQ # # If gmpy2 is installed then run the tests for both mpq and PythonMPQ. # That should ensure consistency between the implementation here and mpq. # rational_types: List[Tuple[Callable, Type, Callable, Type]] rational_types = [(PythonMPQ, PythonMPQ, int, int)] try: from gmpy2 import mpq, mpz rational_types.append((mpq, type(mpq(1)), mpz, type(mpz(1)))) except ImportError: pass def test_PythonMPQ(): # # Test PythonMPQ and also mpq if gmpy/gmpy2 is installed. # for Q, TQ, Z, TZ in rational_types: def check_Q(q): assert isinstance(q, TQ) assert isinstance(q.numerator, TZ) assert isinstance(q.denominator, TZ) return q.numerator, q.denominator # Check construction from different types assert check_Q(Q(3)) == (3, 1) assert check_Q(Q(3, 5)) == (3, 5) assert check_Q(Q(Q(3, 5))) == (3, 5) assert check_Q(Q(0.5)) == (1, 2) assert check_Q(Q('0.5')) == (1, 2) assert check_Q(Q(Decimal('0.6'))) == (3, 5) assert check_Q(Q(Fraction(3, 5))) == (3, 5) # Invalid types raises(TypeError, lambda: Q([])) raises(TypeError, lambda: Q([], [])) # Check normalisation of signs assert check_Q(Q(2, 3)) == (2, 3) assert check_Q(Q(-2, 3)) == (-2, 3) assert check_Q(Q(2, -3)) == (-2, 3) assert check_Q(Q(-2, -3)) == (2, 3) # Check gcd calculation assert check_Q(Q(12, 8)) == (3, 2) # __int__/__float__ assert int(Q(5, 3)) == 1 assert int(Q(-5, 3)) == -1 assert float(Q(5, 2)) == 2.5 assert float(Q(-5, 2)) == -2.5 # __str__/__repr__ assert str(Q(2, 1)) == "2" assert str(Q(1, 2)) == "1/2" if Q is PythonMPQ: assert repr(Q(2, 1)) == "MPQ(2,1)" assert repr(Q(1, 2)) == "MPQ(1,2)" else: assert repr(Q(2, 1)) == "mpq(2,1)" assert repr(Q(1, 2)) == "mpq(1,2)" # __bool__ assert bool(Q(1, 2)) is True assert bool(Q(0)) is False # __eq__/__ne__ assert (Q(2, 3) == Q(2, 3)) is True assert (Q(2, 3) == Q(2, 5)) is False assert (Q(2, 3) != Q(2, 3)) is False assert (Q(2, 3) != Q(2, 5)) is True # __hash__ assert hash(Q(3, 5)) == hash(Fraction(3, 5)) # __reduce__ q = Q(2, 3) assert pickle.loads(pickle.dumps(q)) == q # __ge__/__gt__/__le__/__lt__ assert (Q(1, 3) < Q(2, 3)) is True assert (Q(2, 3) < Q(2, 3)) is False assert (Q(2, 3) < Q(1, 3)) is False assert (Q(-2, 3) < Q(1, 3)) is True assert (Q(1, 3) < Q(-2, 3)) is False assert (Q(1, 3) <= Q(2, 3)) is True assert (Q(2, 3) <= Q(2, 3)) is True assert (Q(2, 3) <= Q(1, 3)) is False assert (Q(-2, 3) <= Q(1, 3)) is True assert (Q(1, 3) <= Q(-2, 3)) is False assert (Q(1, 3) > Q(2, 3)) is False assert (Q(2, 3) > Q(2, 3)) is False assert (Q(2, 3) > Q(1, 3)) is True assert (Q(-2, 3) > Q(1, 3)) is False assert (Q(1, 3) > Q(-2, 3)) is True assert (Q(1, 3) >= Q(2, 3)) is False assert (Q(2, 3) >= Q(2, 3)) is True assert (Q(2, 3) >= Q(1, 3)) is True assert (Q(-2, 3) >= Q(1, 3)) is False assert (Q(1, 3) >= Q(-2, 3)) is True # __abs__/__pos__/__neg__ assert abs(Q(2, 3)) == abs(Q(-2, 3)) == Q(2, 3) assert +Q(2, 3) == Q(2, 3) assert -Q(2, 3) == Q(-2, 3) # __add__/__radd__ assert Q(2, 3) + Q(5, 7) == Q(29, 21) assert Q(2, 3) + 1 == Q(5, 3) assert 1 + Q(2, 3) == Q(5, 3) raises(TypeError, lambda: [] + Q(1)) raises(TypeError, lambda: Q(1) + []) # __sub__/__rsub__ assert Q(2, 3) - Q(5, 7) == Q(-1, 21) assert Q(2, 3) - 1 == Q(-1, 3) assert 1 - Q(2, 3) == Q(1, 3) raises(TypeError, lambda: [] - Q(1)) raises(TypeError, lambda: Q(1) - []) # __mul__/__rmul__ assert Q(2, 3) * Q(5, 7) == Q(10, 21) assert Q(2, 3) * 1 == Q(2, 3) assert 1 * Q(2, 3) == Q(2, 3) raises(TypeError, lambda: [] * Q(1)) raises(TypeError, lambda: Q(1) * []) # __pow__/__rpow__ assert Q(2, 3) ** 2 == Q(4, 9) assert Q(2, 3) ** 1 == Q(2, 3) assert Q(-2, 3) ** 2 == Q(4, 9) assert Q(-2, 3) ** -1 == Q(-3, 2) if Q is PythonMPQ: raises(TypeError, lambda: 1 ** Q(2, 3)) raises(TypeError, lambda: Q(1, 4) ** Q(1, 2)) raises(TypeError, lambda: [] ** Q(1)) raises(TypeError, lambda: Q(1) ** []) # __div__/__rdiv__ assert Q(2, 3) / Q(5, 7) == Q(14, 15) assert Q(2, 3) / 1 == Q(2, 3) assert 1 / Q(2, 3) == Q(3, 2) raises(TypeError, lambda: [] / Q(1)) raises(TypeError, lambda: Q(1) / []) raises(ZeroDivisionError, lambda: Q(1, 2) / Q(0)) # __divmod__ if Q is PythonMPQ: raises(TypeError, lambda: Q(2, 3) // Q(1, 3)) raises(TypeError, lambda: Q(2, 3) % Q(1, 3)) raises(TypeError, lambda: 1 // Q(1, 3)) raises(TypeError, lambda: 1 % Q(1, 3)) raises(TypeError, lambda: Q(2, 3) // 1) raises(TypeError, lambda: Q(2, 3) % 1)
fcea0e4705c79089afaebff85e48cddb3fc388563603f92f2339848b3fc0a170
# 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()
54534adcde5e857ca107c9c6af8f5b9dc5877ac6559a1738310cb5398872a57e
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)
d8fb5d79e26d0faab212fb7d1c536fc939cc33ca61159463b1c8276f87c79dd5
from sympy.core.numbers import oo from sympy.core.symbol import Symbol from sympy.series.limits import limit x = Symbol('x') def timeit_limit_1x(): limit(1/x, x, oo)
63d3f01935316bc63d9943a56806c6ac11923449f757e65ef58f79e8c79a4e0f
from sympy.core.numbers import E from sympy.core.singleton import S from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.hyperbolic import tanh from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.series.order import Order from sympy.abc import x, y def test_sin(): e = sin(x).lseries(x) assert next(e) == x assert next(e) == -x**3/6 assert next(e) == x**5/120 def test_cos(): e = cos(x).lseries(x) assert next(e) == 1 assert next(e) == -x**2/2 assert next(e) == x**4/24 def test_exp(): e = exp(x).lseries(x) assert next(e) == 1 assert next(e) == x assert next(e) == x**2/2 assert next(e) == x**3/6 def test_exp2(): e = exp(cos(x)).lseries(x) assert next(e) == E assert next(e) == -E*x**2/2 assert next(e) == E*x**4/6 assert next(e) == -31*E*x**6/720 def test_simple(): assert [t for t in x.lseries()] == [x] assert [t for t in S.One.lseries(x)] == [1] assert not next((x/(x + y)).lseries(y)).has(Order) def test_issue_5183(): s = (x + 1/x).lseries() assert [si for si in s] == [1/x, x] assert next((x + x**2).lseries()) == x assert next(((1 + x)**7).lseries(x)) == 1 assert next((sin(x + y)).series(x, n=3).lseries(y)) == x # it would be nice if all terms were grouped, but in the # following case that would mean that all the terms would have # to be known since, for example, every term has a constant in it. s = ((1 + x)**7).series(x, 1, n=None) assert [next(s) for i in range(2)] == [128, -448 + 448*x] def test_issue_6999(): s = tanh(x).lseries(x, 1) assert next(s) == tanh(1) assert next(s) == x - (x - 1)*tanh(1)**2 - 1 assert next(s) == -(x - 1)**2*tanh(1) + (x - 1)**2*tanh(1)**3 assert next(s) == -(x - 1)**3*tanh(1)**4 - (x - 1)**3/3 + \ 4*(x - 1)**3*tanh(1)**2/3
2b66a163ab0ac52e8a41ddf67a71adf38c50ee742bb19dd5b8926369a8bec04d
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.util 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
fce976447a299077a0a840206f6006042277e3292420faa67700297364dee3a8
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(): s = SeqExpr((1, n, y), (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((1, 2, 3), (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
23d0e2a05a5c26716fa7df9712029123f883bf40b652526ad6733daeb7031bb6
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_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).simplify().rewrite(sign) == 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))
9c50a8eeec39f4f7c5ba2b054faedea98fd29193c451d1a25530e3ab60532bd2
from sympy.concrete.summations import Sum from sympy.core.add import Add from sympy.core.function import (Derivative, Function) from sympy.core.mul import Mul from sympy.core.numbers import (I, Rational, oo, pi) from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.hyperbolic import (acosh, asech) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin) from sympy.functions.special.bessel import airyai from sympy.functions.special.error_functions import erf from sympy.functions.special.gamma_functions import gamma from sympy.integrals.integrals import integrate from sympy.series.formal import fps from sympy.series.order import O from sympy.series.formal import (rational_algorithm, FormalPowerSeries, FormalPowerSeriesProduct, FormalPowerSeriesCompose, FormalPowerSeriesInverse, simpleDE, rational_independent, exp_re, hyper_re) from sympy.testing.pytest import raises, XFAIL, slow x, y, z = symbols('x y z') n, m, k = symbols('n m k', integer=True) f, r = Function('f'), Function('r') def test_rational_algorithm(): f = 1 / ((x - 1)**2 * (x - 2)) assert rational_algorithm(f, x, k) == \ (-2**(-k - 1) + 1 - (factorial(k + 1) / factorial(k)), 0, 0) f = (1 + x + x**2 + x**3) / ((x - 1) * (x - 2)) assert rational_algorithm(f, x, k) == \ (-15*2**(-k - 1) + 4, x + 4, 0) f = z / (y*m - m*x - y*x + x**2) assert rational_algorithm(f, x, k) == \ (((-y**(-k - 1)*z) / (y - m)) + ((m**(-k - 1)*z) / (y - m)), 0, 0) f = x / (1 - x - x**2) assert rational_algorithm(f, x, k) is None assert rational_algorithm(f, x, k, full=True) == \ (((Rational(-1, 2) + sqrt(5)/2)**(-k - 1) * (-sqrt(5)/10 + S.Half)) + ((-sqrt(5)/2 - S.Half)**(-k - 1) * (sqrt(5)/10 + S.Half)), 0, 0) f = 1 / (x**2 + 2*x + 2) assert rational_algorithm(f, x, k) is None assert rational_algorithm(f, x, k, full=True) == \ ((I*(-1 + I)**(-k - 1)) / 2 - (I*(-1 - I)**(-k - 1)) / 2, 0, 0) f = log(1 + x) assert rational_algorithm(f, x, k) == \ (-(-1)**(-k) / k, 0, 1) f = atan(x) assert rational_algorithm(f, x, k) is None assert rational_algorithm(f, x, k, full=True) == \ (((I*I**(-k)) / 2 - (I*(-I)**(-k)) / 2) / k, 0, 1) f = x*atan(x) - log(1 + x**2) / 2 assert rational_algorithm(f, x, k) is None assert rational_algorithm(f, x, k, full=True) == \ (((I*I**(-k + 1)) / 2 - (I*(-I)**(-k + 1)) / 2) / (k*(k - 1)), 0, 2) f = log((1 + x) / (1 - x)) / 2 - atan(x) assert rational_algorithm(f, x, k) is None assert rational_algorithm(f, x, k, full=True) == \ ((-(-1)**(-k) / 2 - (I*I**(-k)) / 2 + (I*(-I)**(-k)) / 2 + S.Half) / k, 0, 1) assert rational_algorithm(cos(x), x, k) is None def test_rational_independent(): ri = rational_independent assert ri([], x) == [] assert ri([cos(x), sin(x)], x) == [cos(x), sin(x)] assert ri([x**2, sin(x), x*sin(x), x**3], x) == \ [x**3 + x**2, x*sin(x) + sin(x)] assert ri([S.One, x*log(x), log(x), sin(x)/x, cos(x), sin(x), x], x) == \ [x + 1, x*log(x) + log(x), sin(x)/x + sin(x), cos(x)] def test_simpleDE(): # Tests just the first valid DE for DE in simpleDE(exp(x), x, f): assert DE == (-f(x) + Derivative(f(x), x), 1) break for DE in simpleDE(sin(x), x, f): assert DE == (f(x) + Derivative(f(x), x, x), 2) break for DE in simpleDE(log(1 + x), x, f): assert DE == ((x + 1)*Derivative(f(x), x, 2) + Derivative(f(x), x), 2) break for DE in simpleDE(asin(x), x, f): assert DE == (x*Derivative(f(x), x) + (x**2 - 1)*Derivative(f(x), x, x), 2) break for DE in simpleDE(exp(x)*sin(x), x, f): assert DE == (2*f(x) - 2*Derivative(f(x)) + Derivative(f(x), x, x), 2) break for DE in simpleDE(((1 + x)/(1 - x))**n, x, f): assert DE == (2*n*f(x) + (x**2 - 1)*Derivative(f(x), x), 1) break for DE in simpleDE(airyai(x), x, f): assert DE == (-x*f(x) + Derivative(f(x), x, x), 2) break def test_exp_re(): d = -f(x) + Derivative(f(x), x) assert exp_re(d, r, k) == -r(k) + r(k + 1) d = f(x) + Derivative(f(x), x, x) assert exp_re(d, r, k) == r(k) + r(k + 2) d = f(x) + Derivative(f(x), x) + Derivative(f(x), x, x) assert exp_re(d, r, k) == r(k) + r(k + 1) + r(k + 2) d = Derivative(f(x), x) + Derivative(f(x), x, x) assert exp_re(d, r, k) == r(k) + r(k + 1) d = Derivative(f(x), x, 3) + Derivative(f(x), x, 4) + Derivative(f(x)) assert exp_re(d, r, k) == r(k) + r(k + 2) + r(k + 3) def test_hyper_re(): d = f(x) + Derivative(f(x), x, x) assert hyper_re(d, r, k) == r(k) + (k+1)*(k+2)*r(k + 2) d = -x*f(x) + Derivative(f(x), x, x) assert hyper_re(d, r, k) == (k + 2)*(k + 3)*r(k + 3) - r(k) d = 2*f(x) - 2*Derivative(f(x), x) + Derivative(f(x), x, x) assert hyper_re(d, r, k) == \ (-2*k - 2)*r(k + 1) + (k + 1)*(k + 2)*r(k + 2) + 2*r(k) d = 2*n*f(x) + (x**2 - 1)*Derivative(f(x), x) assert hyper_re(d, r, k) == \ k*r(k) + 2*n*r(k + 1) + (-k - 2)*r(k + 2) d = (x**10 + 4)*Derivative(f(x), x) + x*(x**10 - 1)*Derivative(f(x), x, x) assert hyper_re(d, r, k) == \ (k*(k - 1) + k)*r(k) + (4*k - (k + 9)*(k + 10) + 40)*r(k + 10) d = ((x**2 - 1)*Derivative(f(x), x, 3) + 3*x*Derivative(f(x), x, x) + Derivative(f(x), x)) assert hyper_re(d, r, k) == \ ((k*(k - 2)*(k - 1) + 3*k*(k - 1) + k)*r(k) + (-k*(k + 1)*(k + 2))*r(k + 2)) def test_fps(): assert fps(1) == 1 assert fps(2, x) == 2 assert fps(2, x, dir='+') == 2 assert fps(2, x, dir='-') == 2 assert fps(1/x + 1/x**2) == 1/x + 1/x**2 assert fps(log(1 + x), hyper=False, rational=False) == log(1 + x) f = fps(x**2 + x + 1) assert isinstance(f, FormalPowerSeries) assert f.function == x**2 + x + 1 assert f[0] == 1 assert f[2] == x**2 assert f.truncate(4) == x**2 + x + 1 + O(x**4) assert f.polynomial() == x**2 + x + 1 f = fps(log(1 + x)) assert isinstance(f, FormalPowerSeries) assert f.function == log(1 + x) assert f.subs(x, y) == f assert f[:5] == [0, x, -x**2/2, x**3/3, -x**4/4] assert f.as_leading_term(x) == x assert f.polynomial(6) == x - x**2/2 + x**3/3 - x**4/4 + x**5/5 k = f.ak.variables[0] assert f.infinite == Sum((-(-1)**(-k)*x**k)/k, (k, 1, oo)) ft, s = f.truncate(n=None), f[:5] for i, t in enumerate(ft): if i == 5: break assert s[i] == t f = sin(x).fps(x) assert isinstance(f, FormalPowerSeries) assert f.truncate() == x - x**3/6 + x**5/120 + O(x**6) raises(NotImplementedError, lambda: fps(y*x)) raises(ValueError, lambda: fps(x, dir=0)) @slow def test_fps__rational(): assert fps(1/x) == (1/x) assert fps((x**2 + x + 1) / x**3, dir=-1) == (x**2 + x + 1) / x**3 f = 1 / ((x - 1)**2 * (x - 2)) assert fps(f, x).truncate() == \ (Rational(-1, 2) - x*Rational(5, 4) - 17*x**2/8 - 49*x**3/16 - 129*x**4/32 - 321*x**5/64 + O(x**6)) f = (1 + x + x**2 + x**3) / ((x - 1) * (x - 2)) assert fps(f, x).truncate() == \ (S.Half + x*Rational(5, 4) + 17*x**2/8 + 49*x**3/16 + 113*x**4/32 + 241*x**5/64 + O(x**6)) f = x / (1 - x - x**2) assert fps(f, x, full=True).truncate() == \ x + x**2 + 2*x**3 + 3*x**4 + 5*x**5 + O(x**6) f = 1 / (x**2 + 2*x + 2) assert fps(f, x, full=True).truncate() == \ S.Half - x/2 + x**2/4 - x**4/8 + x**5/8 + O(x**6) f = log(1 + x) assert fps(f, x).truncate() == \ x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6) assert fps(f, x, dir=1).truncate() == fps(f, x, dir=-1).truncate() assert fps(f, x, 2).truncate() == \ (log(3) - Rational(2, 3) - (x - 2)**2/18 + (x - 2)**3/81 - (x - 2)**4/324 + (x - 2)**5/1215 + x/3 + O((x - 2)**6, (x, 2))) assert fps(f, x, 2, dir=-1).truncate() == \ (log(3) - Rational(2, 3) - (-x + 2)**2/18 - (-x + 2)**3/81 - (-x + 2)**4/324 - (-x + 2)**5/1215 + x/3 + O((x - 2)**6, (x, 2))) f = atan(x) assert fps(f, x, full=True).truncate() == x - x**3/3 + x**5/5 + O(x**6) assert fps(f, x, full=True, dir=1).truncate() == \ fps(f, x, full=True, dir=-1).truncate() assert fps(f, x, 2, full=True).truncate() == \ (atan(2) - Rational(2, 5) - 2*(x - 2)**2/25 + 11*(x - 2)**3/375 - 6*(x - 2)**4/625 + 41*(x - 2)**5/15625 + x/5 + O((x - 2)**6, (x, 2))) assert fps(f, x, 2, full=True, dir=-1).truncate() == \ (atan(2) - Rational(2, 5) - 2*(-x + 2)**2/25 - 11*(-x + 2)**3/375 - 6*(-x + 2)**4/625 - 41*(-x + 2)**5/15625 + x/5 + O((x - 2)**6, (x, 2))) f = x*atan(x) - log(1 + x**2) / 2 assert fps(f, x, full=True).truncate() == x**2/2 - x**4/12 + O(x**6) f = log((1 + x) / (1 - x)) / 2 - atan(x) assert fps(f, x, full=True).truncate(n=10) == 2*x**3/3 + 2*x**7/7 + O(x**10) @slow def test_fps__hyper(): f = sin(x) assert fps(f, x).truncate() == x - x**3/6 + x**5/120 + O(x**6) f = cos(x) assert fps(f, x).truncate() == 1 - x**2/2 + x**4/24 + O(x**6) f = exp(x) assert fps(f, x).truncate() == \ 1 + x + x**2/2 + x**3/6 + x**4/24 + x**5/120 + O(x**6) f = atan(x) assert fps(f, x).truncate() == x - x**3/3 + x**5/5 + O(x**6) f = exp(acos(x)) assert fps(f, x).truncate() == \ (exp(pi/2) - x*exp(pi/2) + x**2*exp(pi/2)/2 - x**3*exp(pi/2)/3 + 5*x**4*exp(pi/2)/24 - x**5*exp(pi/2)/6 + O(x**6)) f = exp(acosh(x)) assert fps(f, x).truncate() == I + x - I*x**2/2 - I*x**4/8 + O(x**6) f = atan(1/x) assert fps(f, x).truncate() == pi/2 - x + x**3/3 - x**5/5 + O(x**6) f = x*atan(x) - log(1 + x**2) / 2 assert fps(f, x, rational=False).truncate() == x**2/2 - x**4/12 + O(x**6) f = log(1 + x) assert fps(f, x, rational=False).truncate() == \ x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6) f = airyai(x**2) assert fps(f, x).truncate() == \ (3**Rational(5, 6)*gamma(Rational(1, 3))/(6*pi) - 3**Rational(2, 3)*x**2/(3*gamma(Rational(1, 3))) + O(x**6)) f = exp(x)*sin(x) assert fps(f, x).truncate() == x + x**2 + x**3/3 - x**5/30 + O(x**6) f = exp(x)*sin(x)/x assert fps(f, x).truncate() == 1 + x + x**2/3 - x**4/30 - x**5/90 + O(x**6) f = sin(x) * cos(x) assert fps(f, x).truncate() == x - 2*x**3/3 + 2*x**5/15 + O(x**6) def test_fps_shift(): f = x**-5*sin(x) assert fps(f, x).truncate() == \ 1/x**4 - 1/(6*x**2) + Rational(1, 120) - x**2/5040 + x**4/362880 + O(x**6) f = x**2*atan(x) assert fps(f, x, rational=False).truncate() == \ x**3 - x**5/3 + O(x**6) f = cos(sqrt(x))*x assert fps(f, x).truncate() == \ x - x**2/2 + x**3/24 - x**4/720 + x**5/40320 + O(x**6) f = x**2*cos(sqrt(x)) assert fps(f, x).truncate() == \ x**2 - x**3/2 + x**4/24 - x**5/720 + O(x**6) def test_fps__Add_expr(): f = x*atan(x) - log(1 + x**2) / 2 assert fps(f, x).truncate() == x**2/2 - x**4/12 + O(x**6) f = sin(x) + cos(x) - exp(x) + log(1 + x) assert fps(f, x).truncate() == x - 3*x**2/2 - x**4/4 + x**5/5 + O(x**6) f = 1/x + sin(x) assert fps(f, x).truncate() == 1/x + x - x**3/6 + x**5/120 + O(x**6) f = sin(x) - cos(x) + 1/(x - 1) assert fps(f, x).truncate() == \ -2 - x**2/2 - 7*x**3/6 - 25*x**4/24 - 119*x**5/120 + O(x**6) def test_fps__asymptotic(): f = exp(x) assert fps(f, x, oo) == f assert fps(f, x, -oo).truncate() == O(1/x**6, (x, oo)) f = erf(x) assert fps(f, x, oo).truncate() == 1 + O(1/x**6, (x, oo)) assert fps(f, x, -oo).truncate() == -1 + O(1/x**6, (x, oo)) f = atan(x) assert fps(f, x, oo, full=True).truncate() == \ -1/(5*x**5) + 1/(3*x**3) - 1/x + pi/2 + O(1/x**6, (x, oo)) assert fps(f, x, -oo, full=True).truncate() == \ -1/(5*x**5) + 1/(3*x**3) - 1/x - pi/2 + O(1/x**6, (x, oo)) f = log(1 + x) assert fps(f, x, oo) != \ (-1/(5*x**5) - 1/(4*x**4) + 1/(3*x**3) - 1/(2*x**2) + 1/x - log(1/x) + O(1/x**6, (x, oo))) assert fps(f, x, -oo) != \ (-1/(5*x**5) - 1/(4*x**4) + 1/(3*x**3) - 1/(2*x**2) + 1/x + I*pi - log(-1/x) + O(1/x**6, (x, oo))) def test_fps__fractional(): f = sin(sqrt(x)) / x assert fps(f, x).truncate() == \ (1/sqrt(x) - sqrt(x)/6 + x**Rational(3, 2)/120 - x**Rational(5, 2)/5040 + x**Rational(7, 2)/362880 - x**Rational(9, 2)/39916800 + x**Rational(11, 2)/6227020800 + O(x**6)) f = sin(sqrt(x)) * x assert fps(f, x).truncate() == \ (x**Rational(3, 2) - x**Rational(5, 2)/6 + x**Rational(7, 2)/120 - x**Rational(9, 2)/5040 + x**Rational(11, 2)/362880 + O(x**6)) f = atan(sqrt(x)) / x**2 assert fps(f, x).truncate() == \ (x**Rational(-3, 2) - x**Rational(-1, 2)/3 + x**S.Half/5 - x**Rational(3, 2)/7 + x**Rational(5, 2)/9 - x**Rational(7, 2)/11 + x**Rational(9, 2)/13 - x**Rational(11, 2)/15 + O(x**6)) f = exp(sqrt(x)) assert fps(f, x).truncate().expand() == \ (1 + x/2 + x**2/24 + x**3/720 + x**4/40320 + x**5/3628800 + sqrt(x) + x**Rational(3, 2)/6 + x**Rational(5, 2)/120 + x**Rational(7, 2)/5040 + x**Rational(9, 2)/362880 + x**Rational(11, 2)/39916800 + O(x**6)) f = exp(sqrt(x))*x assert fps(f, x).truncate().expand() == \ (x + x**2/2 + x**3/24 + x**4/720 + x**5/40320 + x**Rational(3, 2) + x**Rational(5, 2)/6 + x**Rational(7, 2)/120 + x**Rational(9, 2)/5040 + x**Rational(11, 2)/362880 + O(x**6)) def test_fps__logarithmic_singularity(): f = log(1 + 1/x) assert fps(f, x) != \ -log(x) + x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6) assert fps(f, x, rational=False) != \ -log(x) + x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6) @XFAIL def test_fps__logarithmic_singularity_fail(): f = asech(x) # Algorithms for computing limits probably needs improvemnts assert fps(f, x) == log(2) - log(x) - x**2/4 - 3*x**4/64 + O(x**6) def test_fps_symbolic(): f = x**n*sin(x**2) assert fps(f, x).truncate(8) == x**(n + 2) - x**(n + 6)/6 + O(x**(n + 8), x) f = x**n*log(1 + x) fp = fps(f, x) k = fp.ak.variables[0] assert fp.infinite == \ Sum((-(-1)**(-k)*x**(k + n))/k, (k, 1, oo)) f = (x - 2)**n*log(1 + x) assert fps(f, x, 2).truncate() == \ ((x - 2)**n*log(3) + (x - 2)**(n + 1)/3 - (x - 2)**(n + 2)/18 + (x - 2)**(n + 3)/81 - (x - 2)**(n + 4)/324 + (x - 2)**(n + 5)/1215 + O((x - 2)**(n + 6), (x, 2))) f = x**(n - 2)*cos(x) assert fps(f, x).truncate() == \ (x**(n - 2) - x**n/2 + x**(n + 2)/24 - x**(n + 4)/720 + O(x**(n + 6), x)) f = x**(n - 2)*sin(x) + x**n*exp(x) assert fps(f, x).truncate() == \ (x**(n - 1) + x**n + 5*x**(n + 1)/6 + x**(n + 2)/2 + 7*x**(n + 3)/40 + x**(n + 4)/24 + 41*x**(n + 5)/5040 + O(x**(n + 6), x)) f = x**n*atan(x) assert fps(f, x, oo).truncate() == \ (-x**(n - 5)/5 + x**(n - 3)/3 + x**n*(pi/2 - 1/x) + O((1/x)**(-n)/x**6, (x, oo))) f = x**(n/2)*cos(x) assert fps(f, x).truncate() == \ x**(n/2) - x**(n/2 + 2)/2 + x**(n/2 + 4)/24 + O(x**(n/2 + 6), x) f = x**(n + m)*sin(x) assert fps(f, x).truncate() == \ x**(m + n + 1) - x**(m + n + 3)/6 + x**(m + n + 5)/120 + O(x**(m + n + 6), x) def test_fps__slow(): f = x*exp(x)*sin(2*x) # TODO: rsolve needs improvement assert fps(f, x).truncate() == 2*x**2 + 2*x**3 - x**4/3 - x**5 + O(x**6) def test_fps__operations(): f1, f2 = fps(sin(x)), fps(cos(x)) fsum = f1 + f2 assert fsum.function == sin(x) + cos(x) assert fsum.truncate() == \ 1 + x - x**2/2 - x**3/6 + x**4/24 + x**5/120 + O(x**6) fsum = f1 + 1 assert fsum.function == sin(x) + 1 assert fsum.truncate() == 1 + x - x**3/6 + x**5/120 + O(x**6) fsum = 1 + f2 assert fsum.function == cos(x) + 1 assert fsum.truncate() == 2 - x**2/2 + x**4/24 + O(x**6) assert (f1 + x) == Add(f1, x) assert -f2.truncate() == -1 + x**2/2 - x**4/24 + O(x**6) assert (f1 - f1) is S.Zero fsub = f1 - f2 assert fsub.function == sin(x) - cos(x) assert fsub.truncate() == \ -1 + x + x**2/2 - x**3/6 - x**4/24 + x**5/120 + O(x**6) fsub = f1 - 1 assert fsub.function == sin(x) - 1 assert fsub.truncate() == -1 + x - x**3/6 + x**5/120 + O(x**6) fsub = 1 - f2 assert fsub.function == -cos(x) + 1 assert fsub.truncate() == x**2/2 - x**4/24 + O(x**6) raises(ValueError, lambda: f1 + fps(exp(x), dir=-1)) raises(ValueError, lambda: f1 + fps(exp(x), x0=1)) fm = f1 * 3 assert fm.function == 3*sin(x) assert fm.truncate() == 3*x - x**3/2 + x**5/40 + O(x**6) fm = 3 * f2 assert fm.function == 3*cos(x) assert fm.truncate() == 3 - 3*x**2/2 + x**4/8 + O(x**6) assert (f1 * f2) == Mul(f1, f2) assert (f1 * x) == Mul(f1, x) fd = f1.diff() assert fd.function == cos(x) assert fd.truncate() == 1 - x**2/2 + x**4/24 + O(x**6) fd = f2.diff() assert fd.function == -sin(x) assert fd.truncate() == -x + x**3/6 - x**5/120 + O(x**6) fd = f2.diff().diff() assert fd.function == -cos(x) assert fd.truncate() == -1 + x**2/2 - x**4/24 + O(x**6) f3 = fps(exp(sqrt(x))) fd = f3.diff() assert fd.truncate().expand() == \ (1/(2*sqrt(x)) + S.Half + x/12 + x**2/240 + x**3/10080 + x**4/725760 + x**5/79833600 + sqrt(x)/4 + x**Rational(3, 2)/48 + x**Rational(5, 2)/1440 + x**Rational(7, 2)/80640 + x**Rational(9, 2)/7257600 + x**Rational(11, 2)/958003200 + O(x**6)) assert f1.integrate((x, 0, 1)) == -cos(1) + 1 assert integrate(f1, (x, 0, 1)) == -cos(1) + 1 fi = integrate(f1, x) assert fi.function == -cos(x) assert fi.truncate() == -1 + x**2/2 - x**4/24 + O(x**6) fi = f2.integrate(x) assert fi.function == sin(x) assert fi.truncate() == x - x**3/6 + x**5/120 + O(x**6) def test_fps__product(): f1, f2, f3 = fps(sin(x)), fps(exp(x)), fps(cos(x)) raises(ValueError, lambda: f1.product(exp(x), x)) raises(ValueError, lambda: f1.product(fps(exp(x), dir=-1), x, 4)) raises(ValueError, lambda: f1.product(fps(exp(x), x0=1), x, 4)) raises(ValueError, lambda: f1.product(fps(exp(y)), x, 4)) fprod = f1.product(f2, x) assert isinstance(fprod, FormalPowerSeriesProduct) assert isinstance(fprod.ffps, FormalPowerSeries) assert isinstance(fprod.gfps, FormalPowerSeries) assert fprod.f == sin(x) assert fprod.g == exp(x) assert fprod.function == sin(x) * exp(x) assert fprod._eval_terms(4) == x + x**2 + x**3/3 assert fprod.truncate(4) == x + x**2 + x**3/3 + O(x**4) assert fprod.polynomial(4) == x + x**2 + x**3/3 raises(NotImplementedError, lambda: fprod._eval_term(5)) raises(NotImplementedError, lambda: fprod.infinite) raises(NotImplementedError, lambda: fprod._eval_derivative(x)) raises(NotImplementedError, lambda: fprod.integrate(x)) assert f1.product(f3, x)._eval_terms(4) == x - 2*x**3/3 assert f1.product(f3, x).truncate(4) == x - 2*x**3/3 + O(x**4) def test_fps__compose(): f1, f2, f3 = fps(exp(x)), fps(sin(x)), fps(cos(x)) raises(ValueError, lambda: f1.compose(sin(x), x)) raises(ValueError, lambda: f1.compose(fps(sin(x), dir=-1), x, 4)) raises(ValueError, lambda: f1.compose(fps(sin(x), x0=1), x, 4)) raises(ValueError, lambda: f1.compose(fps(sin(y)), x, 4)) raises(ValueError, lambda: f1.compose(f3, x)) raises(ValueError, lambda: f2.compose(f3, x)) fcomp = f1.compose(f2, x) assert isinstance(fcomp, FormalPowerSeriesCompose) assert isinstance(fcomp.ffps, FormalPowerSeries) assert isinstance(fcomp.gfps, FormalPowerSeries) assert fcomp.f == exp(x) assert fcomp.g == sin(x) assert fcomp.function == exp(sin(x)) assert fcomp._eval_terms(6) == 1 + x + x**2/2 - x**4/8 - x**5/15 assert fcomp.truncate() == 1 + x + x**2/2 - x**4/8 - x**5/15 + O(x**6) assert fcomp.truncate(5) == 1 + x + x**2/2 - x**4/8 + O(x**5) raises(NotImplementedError, lambda: fcomp._eval_term(5)) raises(NotImplementedError, lambda: fcomp.infinite) raises(NotImplementedError, lambda: fcomp._eval_derivative(x)) raises(NotImplementedError, lambda: fcomp.integrate(x)) assert f1.compose(f2, x).truncate(4) == 1 + x + x**2/2 + O(x**4) assert f1.compose(f2, x).truncate(8) == \ 1 + x + x**2/2 - x**4/8 - x**5/15 - x**6/240 + x**7/90 + O(x**8) assert f1.compose(f2, x).truncate(6) == \ 1 + x + x**2/2 - x**4/8 - x**5/15 + O(x**6) assert f2.compose(f2, x).truncate(4) == x - x**3/3 + O(x**4) assert f2.compose(f2, x).truncate(8) == x - x**3/3 + x**5/10 - 8*x**7/315 + O(x**8) assert f2.compose(f2, x).truncate(6) == x - x**3/3 + x**5/10 + O(x**6) def test_fps__inverse(): f1, f2, f3 = fps(sin(x)), fps(exp(x)), fps(cos(x)) raises(ValueError, lambda: f1.inverse(x)) finv = f2.inverse(x) assert isinstance(finv, FormalPowerSeriesInverse) assert isinstance(finv.ffps, FormalPowerSeries) raises(ValueError, lambda: finv.gfps) assert finv.f == exp(x) assert finv.function == exp(-x) assert finv._eval_terms(5) == 1 - x + x**2/2 - x**3/6 + x**4/24 assert finv.truncate() == 1 - x + x**2/2 - x**3/6 + x**4/24 - x**5/120 + O(x**6) assert finv.truncate(5) == 1 - x + x**2/2 - x**3/6 + x**4/24 + O(x**5) raises(NotImplementedError, lambda: finv._eval_term(5)) raises(ValueError, lambda: finv.g) raises(NotImplementedError, lambda: finv.infinite) raises(NotImplementedError, lambda: finv._eval_derivative(x)) raises(NotImplementedError, lambda: finv.integrate(x)) assert f2.inverse(x).truncate(8) == \ 1 - x + x**2/2 - x**3/6 + x**4/24 - x**5/120 + x**6/720 - x**7/5040 + O(x**8) assert f3.inverse(x).truncate() == 1 + x**2/2 + 5*x**4/24 + O(x**6) assert f3.inverse(x).truncate(8) == 1 + x**2/2 + 5*x**4/24 + 61*x**6/720 + O(x**8)
517ca34f45460c156e2ac993a6a810b3610845c237138e039b48396f0404b91d
from sympy.series import approximants from sympy.core.symbol import symbols from sympy.functions.combinatorial.factorials import binomial from sympy.functions.combinatorial.numbers import (fibonacci, lucas) def test_approximants(): x, t = symbols("x,t") g = [lucas(k) for k in range(16)] assert [e for e in approximants(g)] == ( [2, -4/(x - 2), (5*x - 2)/(3*x - 1), (x - 2)/(x**2 + x - 1)] ) g = [lucas(k)+fibonacci(k+2) for k in range(16)] assert [e for e in approximants(g)] == ( [3, -3/(x - 1), (3*x - 3)/(2*x - 1), -3/(x**2 + x - 1)] ) g = [lucas(k)**2 for k in range(16)] assert [e for e in approximants(g)] == ( [4, -16/(x - 4), (35*x - 4)/(9*x - 1), (37*x - 28)/(13*x**2 + 11*x - 7), (50*x**2 + 63*x - 52)/(37*x**2 + 19*x - 13), (-x**2 - 7*x + 4)/(x**3 - 2*x**2 - 2*x + 1)] ) p = [sum(binomial(k,i)*x**i for i in range(k+1)) for k in range(16)] y = approximants(p, t, simplify=True) assert next(y) == 1 assert next(y) == -1/(t*(x + 1) - 1)
63446fcbbbe961e2d802e582facc789eb1e375eeb264a338f2d48ef89d4271cc
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', real=True, 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() == \ (-6964*sqrt(5) - 15572 + 2440*sqrt(5)*x + 5456*x\ + O((x - 2/(1 + sqrt(5)))**2, (x, 2/(1 + sqrt(5)))))/((1 + sqrt(5))**2\ *(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)
24661a72a24c12a1d2ea84f6018b3d77b8aeb4811bdf63e426cf4426a387c5c4
from sympy.core.numbers import (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 (root, sqrt) from sympy.functions.elementary.trigonometric import (asin, cos, sin, tan) from sympy.polys.rationaltools import together from sympy.series.limits import limit # Numbers listed with the tests refer to problem numbers in the book # "Anti-demidovich, problemas resueltos, Ed. URSS" x = Symbol("x") def test_leadterm(): assert (3 + 2*x**(log(3)/log(2) - 1)).leadterm(x) == (3, 0) def root3(x): return root(x, 3) def root4(x): return root(x, 4) def test_Limits_simple_0(): assert limit((2**(x + 1) + 3**(x + 1))/(2**x + 3**x), x, oo) == 3 # 175 def test_Limits_simple_1(): assert limit((x + 1)*(x + 2)*(x + 3)/x**3, x, oo) == 1 # 172 assert limit(sqrt(x + 1) - sqrt(x), x, oo) == 0 # 179 assert limit((2*x - 3)*(3*x + 5)*(4*x - 6)/(3*x**3 + x - 1), x, oo) == 8 # Primjer 1 assert limit(x/root3(x**3 + 10), x, oo) == 1 # Primjer 2 assert limit((x + 1)**2/(x**2 + 1), x, oo) == 1 # 181 def test_Limits_simple_2(): assert limit(1000*x/(x**2 - 1), x, oo) == 0 # 182 assert limit((x**2 - 5*x + 1)/(3*x + 7), x, oo) is oo # 183 assert limit((2*x**2 - x + 3)/(x**3 - 8*x + 5), x, oo) == 0 # 184 assert limit((2*x**2 - 3*x - 4)/sqrt(x**4 + 1), x, oo) == 2 # 186 assert limit((2*x + 3)/(x + root3(x)), x, oo) == 2 # 187 assert limit(x**2/(10 + x*sqrt(x)), x, oo) is oo # 188 assert limit(root3(x**2 + 1)/(x + 1), x, oo) == 0 # 189 assert limit(sqrt(x)/sqrt(x + sqrt(x + sqrt(x))), x, oo) == 1 # 190 def test_Limits_simple_3a(): a = Symbol('a') #issue 3513 assert together(limit((x**2 - (a + 1)*x + a)/(x**3 - a**3), x, a)) == \ (a - 1)/(3*a**2) # 196 def test_Limits_simple_3b(): h = Symbol("h") assert limit(((x + h)**3 - x**3)/h, h, 0) == 3*x**2 # 197 assert limit((1/(1 - x) - 3/(1 - x**3)), x, 1) == -1 # 198 assert limit((sqrt(1 + x) - 1)/(root3(1 + x) - 1), x, 0) == Rational(3)/2 # Primer 4 assert limit((sqrt(x) - 1)/(x - 1), x, 1) == Rational(1)/2 # 199 assert limit((sqrt(x) - 8)/(root3(x) - 4), x, 64) == 3 # 200 assert limit((root3(x) - 1)/(root4(x) - 1), x, 1) == Rational(4)/3 # 201 assert limit( (root3(x**2) - 2*root3(x) + 1)/(x - 1)**2, x, 1) == Rational(1)/9 # 202 def test_Limits_simple_4a(): a = Symbol('a') assert limit((sqrt(x) - sqrt(a))/(x - a), x, a) == 1/(2*sqrt(a)) # Primer 5 assert limit((sqrt(x) - 1)/(root3(x) - 1), x, 1) == Rational(3, 2) # 205 assert limit((sqrt(1 + x) - sqrt(1 - x))/x, x, 0) == 1 # 207 assert limit(sqrt(x**2 - 5*x + 6) - x, x, oo) == Rational(-5, 2) # 213 def test_limits_simple_4aa(): assert limit(x*(sqrt(x**2 + 1) - x), x, oo) == Rational(1)/2 # 214 def test_Limits_simple_4b(): #issue 3511 assert limit(x - root3(x**3 - 1), x, oo) == 0 # 215 def test_Limits_simple_4c(): assert limit(log(1 + exp(x))/x, x, -oo) == 0 # 267a assert limit(log(1 + exp(x))/x, x, oo) == 1 # 267b def test_bounded(): assert limit(sin(x)/x, x, oo) == 0 # 216b assert limit(x*sin(1/x), x, 0) == 0 # 227a def test_f1a(): #issue 3508: assert limit((sin(2*x)/x)**(1 + x), x, 0) == 2 # Primer 7 def test_f1a2(): #issue 3509: assert limit(((x - 1)/(x + 1))**x, x, oo) == exp(-2) # Primer 9 def test_f1b(): m = Symbol("m") n = Symbol("n") h = Symbol("h") a = Symbol("a") assert limit(sin(x)/x, x, 2) == sin(2)/2 # 216a assert limit(sin(3*x)/x, x, 0) == 3 # 217 assert limit(sin(5*x)/sin(2*x), x, 0) == Rational(5, 2) # 218 assert limit(sin(pi*x)/sin(3*pi*x), x, 0) == Rational(1, 3) # 219 assert limit(x*sin(pi/x), x, oo) == pi # 220 assert limit((1 - cos(x))/x**2, x, 0) == S.Half # 221 assert limit(x*sin(1/x), x, oo) == 1 # 227b assert limit((cos(m*x) - cos(n*x))/x**2, x, 0) == -m**2/2 + n**2/2 # 232 assert limit((tan(x) - sin(x))/x**3, x, 0) == S.Half # 233 assert limit((x - sin(2*x))/(x + sin(3*x)), x, 0) == -Rational(1, 4) # 237 assert limit((1 - sqrt(cos(x)))/x**2, x, 0) == Rational(1, 4) # 239 assert limit((sqrt(1 + sin(x)) - sqrt(1 - sin(x)))/x, x, 0) == 1 # 240 assert limit((1 + h/x)**x, x, oo) == exp(h) # Primer 9 assert limit((sin(x) - sin(a))/(x - a), x, a) == cos(a) # 222, *176 assert limit((cos(x) - cos(a))/(x - a), x, a) == -sin(a) # 223 assert limit((sin(x + h) - sin(x))/h, h, 0) == cos(x) # 225 def test_f2a(): assert limit(((x + 1)/(2*x + 1))**(x**2), x, oo) == 0 # Primer 8 def test_f2(): assert limit((sqrt( cos(x)) - root3(cos(x)))/(sin(x)**2), x, 0) == -Rational(1, 12) # *184 def test_f3(): a = Symbol('a') #issue 3504 assert limit(asin(a*x)/x, x, 0) == a
0e49e4eb845618d3bc9179a9cb645121b4fc6fed028cbff7e50701ba045e5b7f
from sympy.core.add import Add from sympy.core.numbers import (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.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (cos, sin, sinc, tan) from sympy.series.fourier import fourier_series from sympy.series.fourier import FourierSeries from sympy.testing.pytest import raises from functools import lru_cache x, y, z = symbols('x y z') # Don't declare these during import because they are slow @lru_cache() def _get_examples(): fo = fourier_series(x, (x, -pi, pi)) fe = fourier_series(x**2, (-pi, pi)) fp = fourier_series(Piecewise((0, x < 0), (pi, True)), (x, -pi, pi)) return fo, fe, fp def test_FourierSeries(): fo, fe, fp = _get_examples() assert fourier_series(1, (-pi, pi)) == 1 assert (Piecewise((0, x < 0), (pi, True)). fourier_series((x, -pi, pi)).truncate()) == fp.truncate() assert isinstance(fo, FourierSeries) assert fo.function == x assert fo.x == x assert fo.period == (-pi, pi) assert fo.term(3) == 2*sin(3*x) / 3 assert fe.term(3) == -4*cos(3*x) / 9 assert fp.term(3) == 2*sin(3*x) / 3 assert fo.as_leading_term(x) == 2*sin(x) assert fe.as_leading_term(x) == pi**2 / 3 assert fp.as_leading_term(x) == pi / 2 assert fo.truncate() == 2*sin(x) - sin(2*x) + (2*sin(3*x) / 3) assert fe.truncate() == -4*cos(x) + cos(2*x) + pi**2 / 3 assert fp.truncate() == 2*sin(x) + (2*sin(3*x) / 3) + pi / 2 fot = fo.truncate(n=None) s = [0, 2*sin(x), -sin(2*x)] for i, t in enumerate(fot): if i == 3: break assert s[i] == t def _check_iter(f, i): for ind, t in enumerate(f): assert t == f[ind] if ind == i: break _check_iter(fo, 3) _check_iter(fe, 3) _check_iter(fp, 3) assert fo.subs(x, x**2) == fo raises(ValueError, lambda: fourier_series(x, (0, 1, 2))) raises(ValueError, lambda: fourier_series(x, (x, 0, oo))) raises(ValueError, lambda: fourier_series(x*y, (0, oo))) def test_FourierSeries_2(): p = Piecewise((0, x < 0), (x, True)) f = fourier_series(p, (x, -2, 2)) assert f.term(3) == (2*sin(3*pi*x / 2) / (3*pi) - 4*cos(3*pi*x / 2) / (9*pi**2)) assert f.truncate() == (2*sin(pi*x / 2) / pi - sin(pi*x) / pi - 4*cos(pi*x / 2) / pi**2 + S.Half) def test_square_wave(): """Test if fourier_series approximates discontinuous function correctly.""" square_wave = Piecewise((1, x < pi), (-1, True)) s = fourier_series(square_wave, (x, 0, 2*pi)) assert s.truncate(3) == 4 / pi * sin(x) + 4 / (3 * pi) * sin(3 * x) + \ 4 / (5 * pi) * sin(5 * x) assert s.sigma_approximation(4) == 4 / pi * sin(x) * sinc(pi / 4) + \ 4 / (3 * pi) * sin(3 * x) * sinc(3 * pi / 4) def test_sawtooth_wave(): s = fourier_series(x, (x, 0, pi)) assert s.truncate(4) == \ pi/2 - sin(2*x) - sin(4*x)/2 - sin(6*x)/3 s = fourier_series(x, (x, 0, 1)) assert s.truncate(4) == \ S.Half - sin(2*pi*x)/pi - sin(4*pi*x)/(2*pi) - sin(6*pi*x)/(3*pi) def test_FourierSeries__operations(): fo, fe, fp = _get_examples() fes = fe.scale(-1).shift(pi**2) assert fes.truncate() == 4*cos(x) - cos(2*x) + 2*pi**2 / 3 assert fp.shift(-pi/2).truncate() == (2*sin(x) + (2*sin(3*x) / 3) + (2*sin(5*x) / 5)) fos = fo.scale(3) assert fos.truncate() == 6*sin(x) - 3*sin(2*x) + 2*sin(3*x) fx = fe.scalex(2).shiftx(1) assert fx.truncate() == -4*cos(2*x + 2) + cos(4*x + 4) + pi**2 / 3 fl = fe.scalex(3).shift(-pi).scalex(2).shiftx(1).scale(4) assert fl.truncate() == (-16*cos(6*x + 6) + 4*cos(12*x + 12) - 4*pi + 4*pi**2 / 3) raises(ValueError, lambda: fo.shift(x)) raises(ValueError, lambda: fo.shiftx(sin(x))) raises(ValueError, lambda: fo.scale(x*y)) raises(ValueError, lambda: fo.scalex(x**2)) def test_FourierSeries__neg(): fo, fe, fp = _get_examples() assert (-fo).truncate() == -2*sin(x) + sin(2*x) - (2*sin(3*x) / 3) assert (-fe).truncate() == +4*cos(x) - cos(2*x) - pi**2 / 3 def test_FourierSeries__add__sub(): fo, fe, fp = _get_examples() assert fo + fo == fo.scale(2) assert fo - fo == 0 assert -fe - fe == fe.scale(-2) assert (fo + fe).truncate() == 2*sin(x) - sin(2*x) - 4*cos(x) + cos(2*x) \ + pi**2 / 3 assert (fo - fe).truncate() == 2*sin(x) - sin(2*x) + 4*cos(x) - cos(2*x) \ - pi**2 / 3 assert isinstance(fo + 1, Add) raises(ValueError, lambda: fo + fourier_series(x, (x, 0, 2))) def test_FourierSeries_finite(): assert fourier_series(sin(x)).truncate(1) == sin(x) # assert type(fourier_series(sin(x)*log(x))).truncate() == FourierSeries # assert type(fourier_series(sin(x**2+6))).truncate() == FourierSeries assert fourier_series(sin(x)*log(y)*exp(z),(x,pi,-pi)).truncate() == sin(x)*log(y)*exp(z) assert fourier_series(sin(x)**6).truncate(oo) == -15*cos(2*x)/32 + 3*cos(4*x)/16 - cos(6*x)/32 \ + Rational(5, 16) assert fourier_series(sin(x) ** 6).truncate() == -15 * cos(2 * x) / 32 + 3 * cos(4 * x) / 16 \ + Rational(5, 16) assert fourier_series(sin(4*x+3) + cos(3*x+4)).truncate(oo) == -sin(4)*sin(3*x) + sin(4*x)*cos(3) \ + cos(4)*cos(3*x) + sin(3)*cos(4*x) assert fourier_series(sin(x)+cos(x)*tan(x)).truncate(oo) == 2*sin(x) assert fourier_series(cos(pi*x), (x, -1, 1)).truncate(oo) == cos(pi*x) assert fourier_series(cos(3*pi*x + 4) - sin(4*pi*x)*log(pi*y), (x, -1, 1)).truncate(oo) == -log(pi*y)*sin(4*pi*x)\ - sin(4)*sin(3*pi*x) + cos(4)*cos(3*pi*x)
38fa4966f26b516fa3e9848eb0c82470b5100660dd51230459df20ea7616ef4b
from sympy.core.add import Add from sympy.core.function import (Function, expand) from sympy.core.numbers import (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, transpose) 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.integrals.integrals import Integral from sympy.series.order import O, Order from sympy.core.expr import unchanged from sympy.testing.pytest import raises from sympy.abc import w, x, y, z def test_caching_bug(): #needs to be a first test, so that all caches are clean #cache it O(w) #and test that this won't raise an exception O(w**(-1/x/log(3)*log(5)), w) def test_free_symbols(): assert Order(1).free_symbols == set() assert Order(x).free_symbols == {x} assert Order(1, x).free_symbols == {x} assert Order(x*y).free_symbols == {x, y} assert Order(x, x, y).free_symbols == {x, y} def test_simple_1(): o = Rational(0) assert Order(2*x) == Order(x) assert Order(x)*3 == Order(x) assert -28*Order(x) == Order(x) assert Order(Order(x)) == Order(x) assert Order(Order(x), y) == Order(Order(x), x, y) assert Order(-23) == Order(1) assert Order(exp(x)) == Order(1, x) assert Order(exp(1/x)).expr == exp(1/x) assert Order(x*exp(1/x)).expr == x*exp(1/x) assert Order(x**(o/3)).expr == x**(o/3) assert Order(x**(o*Rational(5, 3))).expr == x**(o*Rational(5, 3)) assert Order(x**2 + x + y, x) == O(1, x) assert Order(x**2 + x + y, y) == O(1, y) raises(ValueError, lambda: Order(exp(x), x, x)) raises(TypeError, lambda: Order(x, 2 - x)) def test_simple_2(): assert Order(2*x)*x == Order(x**2) assert Order(2*x)/x == Order(1, x) assert Order(2*x)*x*exp(1/x) == Order(x**2*exp(1/x)) assert (Order(2*x)*x*exp(1/x)/log(x)**3).expr == x**2*exp(1/x)*log(x)**-3 def test_simple_3(): assert Order(x) + x == Order(x) assert Order(x) + 2 == 2 + Order(x) assert Order(x) + x**2 == Order(x) assert Order(x) + 1/x == 1/x + Order(x) assert Order(1/x) + 1/x**2 == 1/x**2 + Order(1/x) assert Order(x) + exp(1/x) == Order(x) + exp(1/x) def test_simple_4(): assert Order(x)**2 == Order(x**2) def test_simple_5(): assert Order(x) + Order(x**2) == Order(x) assert Order(x) + Order(x**-2) == Order(x**-2) assert Order(x) + Order(1/x) == Order(1/x) def test_simple_6(): assert Order(x) - Order(x) == Order(x) assert Order(x) + Order(1) == Order(1) assert Order(x) + Order(x**2) == Order(x) assert Order(1/x) + Order(1) == Order(1/x) assert Order(x) + Order(exp(1/x)) == Order(exp(1/x)) assert Order(x**3) + Order(exp(2/x)) == Order(exp(2/x)) assert Order(x**-3) + Order(exp(2/x)) == Order(exp(2/x)) def test_simple_7(): assert 1 + O(1) == O(1) assert 2 + O(1) == O(1) assert x + O(1) == O(1) assert 1/x + O(1) == 1/x + O(1) def test_simple_8(): assert O(sqrt(-x)) == O(sqrt(x)) assert O(x**2*sqrt(x)) == O(x**Rational(5, 2)) assert O(x**3*sqrt(-(-x)**3)) == O(x**Rational(9, 2)) assert O(x**Rational(3, 2)*sqrt((-x)**3)) == O(x**3) assert O(x*(-2*x)**(I/2)) == O(x*(-x)**(I/2)) def test_as_expr_variables(): assert Order(x).as_expr_variables(None) == (x, ((x, 0),)) assert Order(x).as_expr_variables(((x, 0),)) == (x, ((x, 0),)) assert Order(y).as_expr_variables(((x, 0),)) == (y, ((x, 0), (y, 0))) assert Order(y).as_expr_variables(((x, 0), (y, 0))) == (y, ((x, 0), (y, 0))) def test_contains_0(): assert Order(1, x).contains(Order(1, x)) assert Order(1, x).contains(Order(1)) assert Order(1).contains(Order(1, x)) is False def test_contains_1(): assert Order(x).contains(Order(x)) assert Order(x).contains(Order(x**2)) assert not Order(x**2).contains(Order(x)) assert not Order(x).contains(Order(1/x)) assert not Order(1/x).contains(Order(exp(1/x))) assert not Order(x).contains(Order(exp(1/x))) assert Order(1/x).contains(Order(x)) assert Order(exp(1/x)).contains(Order(x)) assert Order(exp(1/x)).contains(Order(1/x)) assert Order(exp(1/x)).contains(Order(exp(1/x))) assert Order(exp(2/x)).contains(Order(exp(1/x))) assert not Order(exp(1/x)).contains(Order(exp(2/x))) def test_contains_2(): assert Order(x).contains(Order(y)) is None assert Order(x).contains(Order(y*x)) assert Order(y*x).contains(Order(x)) assert Order(y).contains(Order(x*y)) assert Order(x).contains(Order(y**2*x)) def test_contains_3(): assert Order(x*y**2).contains(Order(x**2*y)) is None assert Order(x**2*y).contains(Order(x*y**2)) is None def test_contains_4(): assert Order(sin(1/x**2)).contains(Order(cos(1/x**2))) is True assert Order(cos(1/x**2)).contains(Order(sin(1/x**2))) is True def test_contains(): assert Order(1, x) not in Order(1) assert Order(1) in Order(1, x) raises(TypeError, lambda: Order(x*y**2) in Order(x**2*y)) def test_add_1(): assert Order(x + x) == Order(x) assert Order(3*x - 2*x**2) == Order(x) assert Order(1 + x) == Order(1, x) assert Order(1 + 1/x) == Order(1/x) assert Order(log(x) + 1/log(x)) == Order(log(x)) assert Order(exp(1/x) + x) == Order(exp(1/x)) assert Order(exp(1/x) + 1/x**20) == Order(exp(1/x)) def test_ln_args(): assert O(log(x)) + O(log(2*x)) == O(log(x)) assert O(log(x)) + O(log(x**3)) == O(log(x)) assert O(log(x*y)) + O(log(x) + log(y)) == O(log(x*y)) def test_multivar_0(): assert Order(x*y).expr == x*y assert Order(x*y**2).expr == x*y**2 assert Order(x*y, x).expr == x assert Order(x*y**2, y).expr == y**2 assert Order(x*y*z).expr == x*y*z assert Order(x/y).expr == x/y assert Order(x*exp(1/y)).expr == x*exp(1/y) assert Order(exp(x)*exp(1/y)).expr == exp(x)*exp(1/y) def test_multivar_0a(): assert Order(exp(1/x)*exp(1/y)).expr == exp(1/x)*exp(1/y) def test_multivar_1(): assert Order(x + y).expr == x + y assert Order(x + 2*y).expr == x + y assert (Order(x + y) + x).expr == (x + y) assert (Order(x + y) + x**2) == Order(x + y) assert (Order(x + y) + 1/x) == 1/x + Order(x + y) assert Order(x**2 + y*x).expr == x**2 + y*x def test_multivar_2(): assert Order(x**2*y + y**2*x, x, y).expr == x**2*y + y**2*x def test_multivar_mul_1(): assert Order(x + y)*x == Order(x**2 + y*x, x, y) def test_multivar_3(): assert (Order(x) + Order(y)).args in [ (Order(x), Order(y)), (Order(y), Order(x))] assert Order(x) + Order(y) + Order(x + y) == Order(x + y) assert (Order(x**2*y) + Order(y**2*x)).args in [ (Order(x*y**2), Order(y*x**2)), (Order(y*x**2), Order(x*y**2))] assert (Order(x**2*y) + Order(y*x)) == Order(x*y) def test_issue_3468(): y = Symbol('y', negative=True) z = Symbol('z', complex=True) # check that Order does not modify assumptions about symbols Order(x) Order(y) Order(z) assert x.is_positive is None assert y.is_positive is False assert z.is_positive is None def test_leading_order(): assert (x + 1 + 1/x**5).extract_leading_order(x) == ((1/x**5, O(1/x**5)),) assert (1 + 1/x).extract_leading_order(x) == ((1/x, O(1/x)),) assert (1 + x).extract_leading_order(x) == ((1, O(1, x)),) assert (1 + x**2).extract_leading_order(x) == ((1, O(1, x)),) assert (2 + x**2).extract_leading_order(x) == ((2, O(1, x)),) assert (x + x**2).extract_leading_order(x) == ((x, O(x)),) def test_leading_order2(): assert set((2 + pi + x**2).extract_leading_order(x)) == {(pi, O(1, x)), (S(2), O(1, x))} assert set((2*x + pi*x + x**2).extract_leading_order(x)) == {(2*x, O(x)), (x*pi, O(x))} def test_order_leadterm(): assert O(x**2)._eval_as_leading_term(x) == O(x**2) def test_order_symbols(): e = x*y*sin(x)*Integral(x, (x, 1, 2)) assert O(e) == O(x**2*y, x, y) assert O(e, x) == O(x**2) def test_nan(): assert O(nan) is nan assert not O(x).contains(nan) def test_O1(): assert O(1, x) * x == O(x) assert O(1, y) * x == O(1, y) def test_getn(): # other lines are tested incidentally by the suite assert O(x).getn() == 1 assert O(x/log(x)).getn() == 1 assert O(x**2/log(x)**2).getn() == 2 assert O(x*log(x)).getn() == 1 raises(NotImplementedError, lambda: (O(x) + O(y)).getn()) def test_diff(): assert O(x**2).diff(x) == O(x) def test_getO(): assert (x).getO() is None assert (x).removeO() == x assert (O(x)).getO() == O(x) assert (O(x)).removeO() == 0 assert (z + O(x) + O(y)).getO() == O(x) + O(y) assert (z + O(x) + O(y)).removeO() == z raises(NotImplementedError, lambda: (O(x) + O(y)).getn()) def test_leading_term(): from sympy.functions.special.gamma_functions import digamma assert O(1/digamma(1/x)) == O(1/log(x)) def test_eval(): assert Order(x).subs(Order(x), 1) == 1 assert Order(x).subs(x, y) == Order(y) assert Order(x).subs(y, x) == Order(x) assert Order(x).subs(x, x + y) == Order(x + y, (x, -y)) assert (O(1)**x).is_Pow def test_issue_4279(): a, b = symbols('a b') assert O(a, a, b) + O(1, a, b) == O(1, a, b) assert O(b, a, b) + O(1, a, b) == O(1, a, b) assert O(a + b, a, b) + O(1, a, b) == O(1, a, b) assert O(1, a, b) + O(a, a, b) == O(1, a, b) assert O(1, a, b) + O(b, a, b) == O(1, a, b) assert O(1, a, b) + O(a + b, a, b) == O(1, a, b) def test_issue_4855(): assert 1/O(1) != O(1) assert 1/O(x) != O(1/x) assert 1/O(x, (x, oo)) != O(1/x, (x, oo)) f = Function('f') assert 1/O(f(x)) != O(1/x) def test_order_conjugate_transpose(): x = Symbol('x', real=True) y = Symbol('y', imaginary=True) assert conjugate(Order(x)) == Order(conjugate(x)) assert conjugate(Order(y)) == Order(conjugate(y)) assert conjugate(Order(x**2)) == Order(conjugate(x)**2) assert conjugate(Order(y**2)) == Order(conjugate(y)**2) assert transpose(Order(x)) == Order(transpose(x)) assert transpose(Order(y)) == Order(transpose(y)) assert transpose(Order(x**2)) == Order(transpose(x)**2) assert transpose(Order(y**2)) == Order(transpose(y)**2) def test_order_noncommutative(): A = Symbol('A', commutative=False) assert Order(A + A*x, x) == Order(1, x) assert (A + A*x)*Order(x) == Order(x) assert (A*x)*Order(x) == Order(x**2, x) assert expand((1 + Order(x))*A*A*x) == A*A*x + Order(x**2, x) assert expand((A*A + Order(x))*x) == A*A*x + Order(x**2, x) assert expand((A + Order(x))*A*x) == A*A*x + Order(x**2, x) def test_issue_6753(): assert (1 + x**2)**10000*O(x) == O(x) def test_order_at_infinity(): assert Order(1 + x, (x, oo)) == Order(x, (x, oo)) assert Order(3*x, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo))*3 == Order(x, (x, oo)) assert -28*Order(x, (x, oo)) == Order(x, (x, oo)) assert Order(Order(x, (x, oo)), (x, oo)) == Order(x, (x, oo)) assert Order(Order(x, (x, oo)), (y, oo)) == Order(x, (x, oo), (y, oo)) assert Order(3, (x, oo)) == Order(1, (x, oo)) assert Order(x**2 + x + y, (x, oo)) == O(x**2, (x, oo)) assert Order(x**2 + x + y, (y, oo)) == O(y, (y, oo)) assert Order(2*x, (x, oo))*x == Order(x**2, (x, oo)) assert Order(2*x, (x, oo))/x == Order(1, (x, oo)) assert Order(2*x, (x, oo))*x*exp(1/x) == Order(x**2*exp(1/x), (x, oo)) assert Order(2*x, (x, oo))*x*exp(1/x)/log(x)**3 == Order(x**2*exp(1/x)*log(x)**-3, (x, oo)) assert Order(x, (x, oo)) + 1/x == 1/x + Order(x, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo)) + 1 == 1 + Order(x, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo)) + x == x + Order(x, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo)) + x**2 == x**2 + Order(x, (x, oo)) assert Order(1/x, (x, oo)) + 1/x**2 == 1/x**2 + Order(1/x, (x, oo)) == Order(1/x, (x, oo)) assert Order(x, (x, oo)) + exp(1/x) == exp(1/x) + Order(x, (x, oo)) assert Order(x, (x, oo))**2 == Order(x**2, (x, oo)) assert Order(x, (x, oo)) + Order(x**2, (x, oo)) == Order(x**2, (x, oo)) assert Order(x, (x, oo)) + Order(x**-2, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo)) + Order(1/x, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo)) - Order(x, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo)) + Order(1, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo)) + Order(x**2, (x, oo)) == Order(x**2, (x, oo)) assert Order(1/x, (x, oo)) + Order(1, (x, oo)) == Order(1, (x, oo)) assert Order(x, (x, oo)) + Order(exp(1/x), (x, oo)) == Order(x, (x, oo)) assert Order(x**3, (x, oo)) + Order(exp(2/x), (x, oo)) == Order(x**3, (x, oo)) assert Order(x**-3, (x, oo)) + Order(exp(2/x), (x, oo)) == Order(exp(2/x), (x, oo)) # issue 7207 assert Order(exp(x), (x, oo)).expr == Order(2*exp(x), (x, oo)).expr == exp(x) assert Order(y**x, (x, oo)).expr == Order(2*y**x, (x, oo)).expr == exp(log(y)*x) # issue 19545 assert Order(1/x - 3/(3*x + 2), (x, oo)).expr == x**(-2) def test_mixing_order_at_zero_and_infinity(): assert (Order(x, (x, 0)) + Order(x, (x, oo))).is_Add assert Order(x, (x, 0)) + Order(x, (x, oo)) == Order(x, (x, oo)) + Order(x, (x, 0)) assert Order(Order(x, (x, oo))) == Order(x, (x, oo)) # not supported (yet) raises(NotImplementedError, lambda: Order(x, (x, 0))*Order(x, (x, oo))) raises(NotImplementedError, lambda: Order(x, (x, oo))*Order(x, (x, 0))) raises(NotImplementedError, lambda: Order(Order(x, (x, oo)), y)) raises(NotImplementedError, lambda: Order(Order(x), (x, oo))) def test_order_at_some_point(): assert Order(x, (x, 1)) == Order(1, (x, 1)) assert Order(2*x - 2, (x, 1)) == Order(x - 1, (x, 1)) assert Order(-x + 1, (x, 1)) == Order(x - 1, (x, 1)) assert Order(x - 1, (x, 1))**2 == Order((x - 1)**2, (x, 1)) assert Order(x - 2, (x, 2)) - O(x - 2, (x, 2)) == Order(x - 2, (x, 2)) def test_order_subs_limits(): # issue 3333 assert (1 + Order(x)).subs(x, 1/x) == 1 + Order(1/x, (x, oo)) assert (1 + Order(x)).limit(x, 0) == 1 # issue 5769 assert ((x + Order(x**2))/x).limit(x, 0) == 1 assert Order(x**2).subs(x, y - 1) == Order((y - 1)**2, (y, 1)) assert Order(10*x**2, (x, 2)).subs(x, y - 1) == Order(1, (y, 3)) def test_issue_9351(): assert exp(x).series(x, 10, 1) == exp(10) + Order(x - 10, (x, 10)) def test_issue_9192(): assert O(1)*O(1) == O(1) assert O(1)**O(1) == O(1) def test_issue_9910(): assert O(x*log(x) + sin(x), (x, oo)) == O(x*log(x), (x, oo)) def test_performance_of_adding_order(): l = list(x**i for i in range(1000)) l.append(O(x**1001)) assert Add(*l).subs(x,1) == O(1) def test_issue_14622(): assert (x**(-4) + x**(-3) + x**(-1) + O(x**(-6), (x, oo))).as_numer_denom() == ( x**4 + x**5 + x**7 + O(x**2, (x, oo)), x**8) assert (x**3 + O(x**2, (x, oo))).is_Add assert O(x**2, (x, oo)).contains(x**3) is False assert O(x, (x, oo)).contains(O(x, (x, 0))) is None assert O(x, (x, 0)).contains(O(x, (x, oo))) is None raises(NotImplementedError, lambda: O(x**3).contains(x**w)) def test_issue_15539(): assert O(1/x**2 + 1/x**4, (x, -oo)) == O(1/x**2, (x, -oo)) assert O(1/x**4 + exp(x), (x, -oo)) == O(1/x**4, (x, -oo)) assert O(1/x**4 + exp(-x), (x, -oo)) == O(exp(-x), (x, -oo)) assert O(1/x, (x, oo)).subs(x, -x) == O(-1/x, (x, -oo)) def test_issue_18606(): assert unchanged(Order, 0) def test_issue_22165(): assert O(log(x)).contains(2) def test_issue_9917(): assert O(x*sin(x) + 1, (x, oo)) == O(x, (x, oo))
67ce4585f5ce395922d0734678ae4110164ea64b81e929ca2b716a7cad7e68b4
from sympy.series.kauers import finite_diff from sympy.series.kauers import finite_diff_kauers from sympy.abc import x, y, z, m, n, w from sympy.core.numbers import pi from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.concrete.summations import Sum def test_finite_diff(): assert finite_diff(x**2 + 2*x + 1, x) == 2*x + 3 assert finite_diff(y**3 + 2*y**2 + 3*y + 5, y) == 3*y**2 + 7*y + 6 assert finite_diff(z**2 - 2*z + 3, z) == 2*z - 1 assert finite_diff(w**2 + 3*w - 2, w) == 2*w + 4 assert finite_diff(sin(x), x, pi/6) == -sin(x) + sin(x + pi/6) assert finite_diff(cos(y), y, pi/3) == -cos(y) + cos(y + pi/3) assert finite_diff(x**2 - 2*x + 3, x, 2) == 4*x assert finite_diff(n**2 - 2*n + 3, n, 3) == 6*n + 3 def test_finite_diff_kauers(): assert finite_diff_kauers(Sum(x**2, (x, 1, n))) == (n + 1)**2 assert finite_diff_kauers(Sum(y, (y, 1, m))) == (m + 1) assert finite_diff_kauers(Sum((x*y), (x, 1, m), (y, 1, n))) == (m + 1)*(n + 1) assert finite_diff_kauers(Sum((x*y**2), (x, 1, m), (y, 1, n))) == (n + 1)**2*(m + 1)
f2e6fa8ca37242f21c90a5b2e0f227da934be45bb210b962706f92cc46aaddab
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.util 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)**(1 - pi) assert limit((1 + cos(x))**oo, x, 0) == Limit((cos(x) + 1)**oo, x, 0) 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', real=True, positive=True) 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", real=True, positive=True) h = Symbol("h", real=True, positive=True) m = Symbol("m", real=True, positive=True) w = Symbol("omega", real=True, positive=True) g = Symbol("g", real=True, 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
2db956e210435618a05fd62f35cfc716f326f2724c493013f4f7142b7a7ef475
from sympy.core.function import PoleError from sympy.core.numbers import oo 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.abc import x from sympy.testing.pytest import raises def test_simple(): # Gruntz' theses pp. 91 to 96 # 6.6 e = sin(1/x + exp(-x)) - sin(1/x) assert e.aseries(x) == (1/(24*x**4) - 1/(2*x**2) + 1 + O(x**(-6), (x, oo)))*exp(-x) e = exp(x) * (exp(1/x + exp(-x)) - exp(1/x)) assert e.aseries(x, n=4) == 1/(6*x**3) + 1/(2*x**2) + 1/x + 1 + O(x**(-4), (x, oo)) e = exp(exp(x) / (1 - 1/x)) assert e.aseries(x) == exp(exp(x) / (1 - 1/x)) # The implementation of bound in aseries is incorrect currently. This test # should be commented out when that is fixed. # assert e.aseries(x, bound=3) == exp(exp(x) / x**2)*exp(exp(x) / x)*exp(-exp(x) + exp(x)/(1 - 1/x) - \ # exp(x) / x - exp(x) / x**2) * exp(exp(x)) e = exp(sin(1/x + exp(-exp(x)))) - exp(sin(1/x)) assert e.aseries(x, n=4) == (-1/(2*x**3) + 1/x + 1 + O(x**(-4), (x, oo)))*exp(-exp(x)) e3 = lambda x:exp(exp(exp(x))) e = e3(x)/e3(x - 1/e3(x)) assert e.aseries(x, n=3) == 1 + exp(x + exp(x))*exp(-exp(exp(x)))\ + ((-exp(x)/2 - S.Half)*exp(x + exp(x))\ + exp(2*x + 2*exp(x))/2)*exp(-2*exp(exp(x))) + O(exp(-3*exp(exp(x))), (x, oo)) e = exp(exp(x)) * (exp(sin(1/x + 1/exp(exp(x)))) - exp(sin(1/x))) assert e.aseries(x, n=4) == -1/(2*x**3) + 1/x + 1 + O(x**(-4), (x, oo)) n = Symbol('n', integer=True) e = (sqrt(n)*log(n)**2*exp(sqrt(log(n))*log(log(n))**2*exp(sqrt(log(log(n)))*log(log(log(n)))**3)))/n assert e.aseries(n) == \ exp(exp(sqrt(log(log(n)))*log(log(log(n)))**3)*sqrt(log(n))*log(log(n))**2)*log(n)**2/sqrt(n) def test_hierarchical(): e = sin(1/x + exp(-x)) assert e.aseries(x, n=3, hir=True) == -exp(-2*x)*sin(1/x)/2 + \ exp(-x)*cos(1/x) + sin(1/x) + O(exp(-3*x), (x, oo)) e = sin(x) * cos(exp(-x)) assert e.aseries(x, hir=True) == exp(-4*x)*sin(x)/24 - \ exp(-2*x)*sin(x)/2 + sin(x) + O(exp(-6*x), (x, oo)) raises(PoleError, lambda: e.aseries(x))
f72090e5bcfc17b1b15120af72811f2da1ca9e3cf10b5bb205f85d95e2b0f147
from sympy.core.function import Function from sympy.core.numbers import (I, Rational, pi) from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.functions.combinatorial.factorials import factorial 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 (cot, sin, tan) from sympy.series.residues import residue from sympy.testing.pytest import XFAIL, raises from sympy.abc import x, z, a, s def test_basic1(): assert residue(1/x, x, 0) == 1 assert residue(-2/x, x, 0) == -2 assert residue(81/x, x, 0) == 81 assert residue(1/x**2, x, 0) == 0 assert residue(0, x, 0) == 0 assert residue(5, x, 0) == 0 assert residue(x, x, 0) == 0 assert residue(x**2, x, 0) == 0 def test_basic2(): assert residue(1/x, x, 1) == 0 assert residue(-2/x, x, 1) == 0 assert residue(81/x, x, -1) == 0 assert residue(1/x**2, x, 1) == 0 assert residue(0, x, 1) == 0 assert residue(5, x, 1) == 0 assert residue(x, x, 1) == 0 assert residue(x**2, x, 5) == 0 def test_f(): f = Function("f") assert residue(f(x)/x**5, x, 0) == f(x).diff(x, 4).subs(x, 0)/24 def test_functions(): assert residue(1/sin(x), x, 0) == 1 assert residue(2/sin(x), x, 0) == 2 assert residue(1/sin(x)**2, x, 0) == 0 assert residue(1/sin(x)**5, x, 0) == Rational(3, 8) def test_expressions(): assert residue(1/(x + 1), x, 0) == 0 assert residue(1/(x + 1), x, -1) == 1 assert residue(1/(x**2 + 1), x, -1) == 0 assert residue(1/(x**2 + 1), x, I) == -I/2 assert residue(1/(x**2 + 1), x, -I) == I/2 assert residue(1/(x**4 + 1), x, 0) == 0 assert residue(1/(x**4 + 1), x, exp(I*pi/4)).equals(-(Rational(1, 4) + I/4)/sqrt(2)) assert residue(1/(x**2 + a**2)**2, x, a*I) == -I/4/a**3 @XFAIL def test_expressions_failing(): n = Symbol('n', integer=True, positive=True) assert residue(exp(z)/(z - pi*I/4*a)**n, z, I*pi*a) == \ exp(I*pi*a/4)/factorial(n - 1) def test_NotImplemented(): raises(NotImplementedError, lambda: residue(exp(1/z), z, 0)) def test_bug(): assert residue(2**(z)*(s + z)*(1 - s - z)/z**2, z, 0) == \ 1 + s*log(2) - s**2*log(2) - 2*s def test_issue_5654(): assert residue(1/(x**2 + a**2)**2, x, a*I) == -I/(4*a**3) def test_issue_6499(): assert residue(1/(exp(z) - 1), z, 0) == 1 def test_issue_14037(): assert residue(sin(x**50)/x**51, x, 0) == 1 def test_issue_21176(): f = x**2*cot(pi*x)/(x**4 + 1) assert residue(f, x, -sqrt(2)/2 - sqrt(2)*I/2).cancel().together(deep=True)\ == sqrt(2)*(1 - I)/(8*tan(sqrt(2)*pi*(1 + I)/2)) def test_issue_21177(): r = -sqrt(3)*tanh(sqrt(3)*pi/2)/3 a = residue(cot(pi*x)/((x - 1)*(x - 2) + 1), x, S(3)/2 - sqrt(3)*I/2) b = residue(cot(pi*x)/(x**2 - 3*x + 3), x, S(3)/2 - sqrt(3)*I/2) assert a == r assert (b - a).cancel() == 0
67f69c188398f59b6a0a7e938e29b8bfb059318a457df4afc312935b48e0d599
from sympy.core.function import (Derivative, PoleError) from sympy.core.numbers import (E, I, Integer, Rational, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import sign from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.hyperbolic import (acosh, acoth, asinh, atanh, cosh, coth, sinh, tanh) from sympy.functions.elementary.integers import (ceiling, floor) from sympy.functions.elementary.miscellaneous import (cbrt, sqrt) from sympy.functions.elementary.trigonometric import (asin, cos, cot, sin, tan) from sympy.series.limits import limit from sympy.series.order import O from sympy.abc import x, y, z from sympy.testing.pytest import raises, XFAIL def test_simple_1(): assert x.nseries(x, n=5) == x assert y.nseries(x, n=5) == y assert (1/(x*y)).nseries(y, n=5) == 1/(x*y) assert Rational(3, 4).nseries(x, n=5) == Rational(3, 4) assert x.nseries() == x def test_mul_0(): assert (x*log(x)).nseries(x, n=5) == x*log(x) def test_mul_1(): assert (x*log(2 + x)).nseries(x, n=5) == x*log(2) + x**2/2 - x**3/8 + \ x**4/24 + O(x**5) assert (x*log(1 + x)).nseries( x, n=5) == x**2 - x**3/2 + x**4/3 + O(x**5) def test_pow_0(): assert (x**2).nseries(x, n=5) == x**2 assert (1/x).nseries(x, n=5) == 1/x assert (1/x**2).nseries(x, n=5) == 1/x**2 assert (x**Rational(2, 3)).nseries(x, n=5) == (x**Rational(2, 3)) assert (sqrt(x)**3).nseries(x, n=5) == (sqrt(x)**3) def test_pow_1(): assert ((1 + x)**2).nseries(x, n=5) == x**2 + 2*x + 1 # https://github.com/sympy/sympy/issues/21075 assert ((sqrt(x) + 1)**2).nseries(x) == 2*sqrt(x) + x + 1 assert ((sqrt(x) + cbrt(x))**2).nseries(x) == 2*x**Rational(5, 6)\ + x**Rational(2, 3) + x def test_geometric_1(): assert (1/(1 - x)).nseries(x, n=5) == 1 + x + x**2 + x**3 + x**4 + O(x**5) assert (x/(1 - x)).nseries(x, n=6) == x + x**2 + x**3 + x**4 + x**5 + O(x**6) assert (x**3/(1 - x)).nseries(x, n=8) == x**3 + x**4 + x**5 + x**6 + \ x**7 + O(x**8) def test_sqrt_1(): assert sqrt(1 + x).nseries(x, n=5) == 1 + x/2 - x**2/8 + x**3/16 - 5*x**4/128 + O(x**5) def test_exp_1(): assert exp(x).nseries(x, n=5) == 1 + x + x**2/2 + x**3/6 + x**4/24 + O(x**5) assert exp(x).nseries(x, n=12) == 1 + x + x**2/2 + x**3/6 + x**4/24 + x**5/120 + \ x**6/720 + x**7/5040 + x**8/40320 + x**9/362880 + x**10/3628800 + \ x**11/39916800 + O(x**12) assert exp(1/x).nseries(x, n=5) == exp(1/x) assert exp(1/(1 + x)).nseries(x, n=4) == \ (E*(1 - x - 13*x**3/6 + 3*x**2/2)).expand() + O(x**4) assert exp(2 + x).nseries(x, n=5) == \ (exp(2)*(1 + x + x**2/2 + x**3/6 + x**4/24)).expand() + O(x**5) def test_exp_sqrt_1(): assert exp(1 + sqrt(x)).nseries(x, n=3) == \ (exp(1)*(1 + sqrt(x) + x/2 + sqrt(x)*x/6)).expand() + O(sqrt(x)**3) def test_power_x_x1(): assert (exp(x*log(x))).nseries(x, 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_power_x_x2(): assert (x**x).nseries(x, 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_log_singular1(): assert log(1 + 1/x).nseries(x, n=5) == x - log(x) - x**2/2 + x**3/3 - \ x**4/4 + O(x**5) def test_log_power1(): e = 1 / (1/x + x ** (log(3)/log(2))) assert e.nseries(x, n=5) == -x**(log(3)/log(2) + 2) + x + O(x**5) def test_log_series(): l = Symbol('l') e = 1/(1 - log(x)) assert e.nseries(x, n=5, logx=l) == 1/(1 - l) def test_log2(): e = log(-1/x) assert e.nseries(x, n=5) == -log(x) + log(-1) def test_log3(): l = Symbol('l') e = 1/log(-1/x) assert e.nseries(x, n=4, logx=l) == 1/(-l + log(-1)) def test_series1(): e = sin(x) assert e.nseries(x, 0, 0) != 0 assert e.nseries(x, 0, 0) == O(1, x) assert e.nseries(x, 0, 1) == O(x, x) assert e.nseries(x, 0, 2) == x + O(x**2, x) assert e.nseries(x, 0, 3) == x + O(x**3, x) assert e.nseries(x, 0, 4) == x - x**3/6 + O(x**4, x) e = (exp(x) - 1)/x assert e.nseries(x, 0, 3) == 1 + x/2 + x**2/6 + O(x**3) assert x.nseries(x, 0, 2) == x @XFAIL def test_series1_failing(): assert x.nseries(x, 0, 0) == O(1, x) assert x.nseries(x, 0, 1) == O(x, x) def test_seriesbug1(): assert (1/x).nseries(x, 0, 3) == 1/x assert (x + 1/x).nseries(x, 0, 3) == x + 1/x def test_series2x(): assert ((x + 1)**(-2)).nseries(x, 0, 4) == 1 - 2*x + 3*x**2 - 4*x**3 + O(x**4, x) assert ((x + 1)**(-1)).nseries(x, 0, 4) == 1 - x + x**2 - x**3 + O(x**4, x) assert ((x + 1)**0).nseries(x, 0, 3) == 1 assert ((x + 1)**1).nseries(x, 0, 3) == 1 + x assert ((x + 1)**2).nseries(x, 0, 3) == x**2 + 2*x + 1 assert ((x + 1)**3).nseries(x, 0, 3) == 1 + 3*x + 3*x**2 + O(x**3) assert (1/(1 + x)).nseries(x, 0, 4) == 1 - x + x**2 - x**3 + O(x**4, x) assert (x + 3/(1 + 2*x)).nseries(x, 0, 4) == 3 - 5*x + 12*x**2 - 24*x**3 + O(x**4, x) assert ((1/x + 1)**3).nseries(x, 0, 3) == 1 + 3/x + 3/x**2 + x**(-3) assert (1/(1 + 1/x)).nseries(x, 0, 4) == x - x**2 + x**3 - O(x**4, x) assert (1/(1 + 1/x**2)).nseries(x, 0, 6) == x**2 - x**4 + O(x**6, x) def test_bug2(): # 1/log(0)*log(0) problem w = Symbol("w") e = (w**(-1) + w**( -log(3)*log(2)**(-1)))**(-1)*(3*w**(-log(3)*log(2)**(-1)) + 2*w**(-1)) e = e.expand() assert e.nseries(w, 0, 4).subs(w, 0) == 3 def test_exp(): e = (1 + x)**(1/x) assert e.nseries(x, n=3) == exp(1) - x*exp(1)/2 + 11*exp(1)*x**2/24 + O(x**3) def test_exp2(): w = Symbol("w") e = w**(1 - log(x)/(log(2) + log(x))) logw = Symbol("logw") assert e.nseries( w, 0, 1, logx=logw) == exp(logw*log(2)/(log(x) + log(2))) def test_bug3(): e = (2/x + 3/x**2)/(1/x + 1/x**2) assert e.nseries(x, n=3) == 3 - x + x**2 + O(x**3) def test_generalexponent(): p = 2 e = (2/x + 3/x**p)/(1/x + 1/x**p) assert e.nseries(x, 0, 3) == 3 - x + x**2 + O(x**3) p = S.Half e = (2/x + 3/x**p)/(1/x + 1/x**p) assert e.nseries(x, 0, 2) == 2 - x + sqrt(x) + x**(S(3)/2) + O(x**2) e = 1 + sqrt(x) assert e.nseries(x, 0, 4) == 1 + sqrt(x) # more complicated example def test_genexp_x(): e = 1/(1 + sqrt(x)) assert e.nseries(x, 0, 2) == \ 1 + x - sqrt(x) - sqrt(x)**3 + O(x**2, x) # more complicated example def test_genexp_x2(): p = Rational(3, 2) e = (2/x + 3/x**p)/(1/x + 1/x**p) assert e.nseries(x, 0, 3) == 3 + x + x**2 - sqrt(x) - x**(S(3)/2) - x**(S(5)/2) + O(x**3) def test_seriesbug2(): w = Symbol("w") #simple case (1): e = ((2*w)/w)**(1 + w) assert e.nseries(w, 0, 1) == 2 + O(w, w) assert e.nseries(w, 0, 1).subs(w, 0) == 2 def test_seriesbug2b(): w = Symbol("w") #test sin e = sin(2*w)/w assert e.nseries(w, 0, 3) == 2 - 4*w**2/3 + O(w**3) def test_seriesbug2d(): w = Symbol("w", real=True) e = log(sin(2*w)/w) assert e.series(w, n=5) == log(2) - 2*w**2/3 - 4*w**4/45 + O(w**5) def test_seriesbug2c(): w = Symbol("w", real=True) #more complicated case, but sin(x)~x, so the result is the same as in (1) e = (sin(2*w)/w)**(1 + w) assert e.series(w, 0, 1) == 2 + O(w) assert e.series(w, 0, 3) == 2 + 2*w*log(2) + \ w**2*(Rational(-4, 3) + log(2)**2) + O(w**3) assert e.series(w, 0, 2).subs(w, 0) == 2 def test_expbug4(): x = Symbol("x", real=True) assert (log( sin(2*x)/x)*(1 + x)).series(x, 0, 2) == log(2) + x*log(2) + O(x**2, x) assert exp( log(sin(2*x)/x)*(1 + x)).series(x, 0, 2) == 2 + 2*x*log(2) + O(x**2) assert exp(log(2) + O(x)).nseries(x, 0, 2) == 2 + O(x) assert ((2 + O(x))**(1 + x)).nseries(x, 0, 2) == 2 + O(x) def test_logbug4(): assert log(2 + O(x)).nseries(x, 0, 2) == log(2) + O(x, x) def test_expbug5(): assert exp(log(1 + x)/x).nseries(x, n=3) == exp(1) + -exp(1)*x/2 + 11*exp(1)*x**2/24 + O(x**3) assert exp(O(x)).nseries(x, 0, 2) == 1 + O(x) def test_sinsinbug(): assert sin(sin(x)).nseries(x, 0, 8) == x - x**3/3 + x**5/10 - 8*x**7/315 + O(x**8) def test_issue_3258(): a = x/(exp(x) - 1) assert a.nseries(x, 0, 5) == 1 - x/2 - x**4/720 + x**2/12 + O(x**5) def test_issue_3204(): x = Symbol("x", nonnegative=True) f = sin(x**3)**Rational(1, 3) assert f.nseries(x, 0, 17) == x - x**7/18 - x**13/3240 + O(x**17) def test_issue_3224(): f = sqrt(1 - sqrt(y)) assert f.nseries(y, 0, 2) == 1 - sqrt(y)/2 - y/8 - sqrt(y)**3/16 + O(y**2) def test_issue_3463(): w, i = symbols('w,i') r = log(5)/log(3) p = w**(-1 + r) e = 1/x*(-log(w**(1 + r)) + log(w + w**r)) e_ser = -r*log(w)/x + p/x - p**2/(2*x) + O(w) assert e.nseries(w, n=1) == e_ser def test_sin(): assert sin(8*x).nseries(x, n=4) == 8*x - 256*x**3/3 + O(x**4) assert sin(x + y).nseries(x, n=1) == sin(y) + O(x) assert sin(x + y).nseries(x, n=2) == sin(y) + cos(y)*x + O(x**2) assert sin(x + y).nseries(x, n=5) == sin(y) + cos(y)*x - sin(y)*x**2/2 - \ cos(y)*x**3/6 + sin(y)*x**4/24 + O(x**5) def test_issue_3515(): e = sin(8*x)/x assert e.nseries(x, n=6) == 8 - 256*x**2/3 + 4096*x**4/15 + O(x**6) def test_issue_3505(): e = sin(x)**(-4)*(sqrt(cos(x))*sin(x)**2 - cos(x)**Rational(1, 3)*sin(x)**2) assert e.nseries(x, n=9) == Rational(-1, 12) - 7*x**2/288 - \ 43*x**4/10368 - 1123*x**6/2488320 + 377*x**8/29859840 + O(x**9) def test_issue_3501(): a = Symbol("a") e = x**(-2)*(x*sin(a + x) - x*sin(a)) assert e.nseries(x, n=6) == cos(a) - sin(a)*x/2 - cos(a)*x**2/6 + \ x**3*sin(a)/24 + x**4*cos(a)/120 - x**5*sin(a)/720 + O(x**6) e = x**(-2)*(x*cos(a + x) - x*cos(a)) assert e.nseries(x, n=6) == -sin(a) - cos(a)*x/2 + sin(a)*x**2/6 + \ cos(a)*x**3/24 - x**4*sin(a)/120 - x**5*cos(a)/720 + O(x**6) def test_issue_3502(): e = sin(5*x)/sin(2*x) assert e.nseries(x, n=2) == Rational(5, 2) + O(x**2) assert e.nseries(x, n=6) == \ Rational(5, 2) - 35*x**2/4 + 329*x**4/48 + O(x**6) def test_issue_3503(): e = sin(2 + x)/(2 + x) assert e.nseries(x, n=2) == sin(2)/2 + x*cos(2)/2 - x*sin(2)/4 + O(x**2) def test_issue_3506(): e = (x + sin(3*x))**(-2)*(x*(x + sin(3*x)) - (x + sin(3*x))*sin(2*x)) assert e.nseries(x, n=7) == \ Rational(-1, 4) + 5*x**2/96 + 91*x**4/768 + 11117*x**6/129024 + O(x**7) def test_issue_3508(): x = Symbol("x", real=True) assert log(sin(x)).series(x, n=5) == log(x) - x**2/6 - x**4/180 + O(x**5) e = -log(x) + x*(-log(x) + log(sin(2*x))) + log(sin(2*x)) assert e.series(x, n=5) == \ log(2) + log(2)*x - 2*x**2/3 - 2*x**3/3 - 4*x**4/45 + O(x**5) def test_issue_3507(): e = x**(-4)*(x**2 - x**2*sqrt(cos(x))) assert e.nseries(x, n=9) == \ Rational(1, 4) + x**2/96 + 19*x**4/5760 + 559*x**6/645120 + 29161*x**8/116121600 + O(x**9) def test_issue_3639(): assert sin(cos(x)).nseries(x, n=5) == \ sin(1) - x**2*cos(1)/2 - x**4*sin(1)/8 + x**4*cos(1)/24 + O(x**5) def test_hyperbolic(): assert sinh(x).nseries(x, n=6) == x + x**3/6 + x**5/120 + O(x**6) assert cosh(x).nseries(x, n=5) == 1 + x**2/2 + x**4/24 + O(x**5) assert tanh(x).nseries(x, n=6) == x - x**3/3 + 2*x**5/15 + O(x**6) assert coth(x).nseries(x, n=6) == \ 1/x - x**3/45 + x/3 + 2*x**5/945 + O(x**6) assert asinh(x).nseries(x, n=6) == x - x**3/6 + 3*x**5/40 + O(x**6) assert acosh(x).nseries(x, n=6) == \ pi*I/2 - I*x - 3*I*x**5/40 - I*x**3/6 + O(x**6) assert atanh(x).nseries(x, n=6) == x + x**3/3 + x**5/5 + O(x**6) assert acoth(x).nseries(x, n=6) == x + x**3/3 + x**5/5 + pi*I/2 + O(x**6) def test_series2(): w = Symbol("w", real=True) x = Symbol("x", real=True) e = w**(-2)*(w*exp(1/x - w) - w*exp(1/x)) assert e.nseries(w, n=4) == -exp(1/x) + w*exp(1/x)/2 - w**2*exp(1/x)/6 + w**3*exp(1/x)/24 + O(w**4) def test_series3(): w = Symbol("w", real=True) e = w**(-6)*(w**3*tan(w) - w**3*sin(w)) assert e.nseries(w, n=8) == Integer(1)/2 + w**2/8 + 13*w**4/240 + 529*w**6/24192 + O(w**8) def test_bug4(): w = Symbol("w") e = x/(w**4 + x**2*w**4 + 2*x*w**4)*w**4 assert e.nseries(w, n=2).removeO().expand() in [x/(1 + 2*x + x**2), 1/(1 + x/2 + 1/x/2)/2, 1/x/(1 + 2/x + x**(-2))] def test_bug5(): w = Symbol("w") l = Symbol('l') e = (-log(w) + log(1 + w*log(x)))**(-2)*w**(-2)*((-log(w) + log(1 + x*w))*(-log(w) + log(1 + w*log(x)))*w - x*(-log(w) + log(1 + w*log(x)))*w) assert e.nseries(w, n=0, logx=l) == x/w/l + 1/w + O(1, w) assert e.nseries(w, n=1, logx=l) == x/w/l + 1/w - x/l + 1/l*log(x) \ + x*log(x)/l**2 + O(w) def test_issue_4115(): assert (sin(x)/(1 - cos(x))).nseries(x, n=1) == 2/x + O(x) assert (sin(x)**2/(1 - cos(x))).nseries(x, n=1) == 2 + O(x) def test_pole(): raises(PoleError, lambda: sin(1/x).series(x, 0, 5)) raises(PoleError, lambda: sin(1 + 1/x).series(x, 0, 5)) raises(PoleError, lambda: (x*sin(1/x)).series(x, 0, 5)) def test_expsinbug(): assert exp(sin(x)).series(x, 0, 0) == O(1, x) assert exp(sin(x)).series(x, 0, 1) == 1 + O(x) assert exp(sin(x)).series(x, 0, 2) == 1 + x + O(x**2) assert exp(sin(x)).series(x, 0, 3) == 1 + x + x**2/2 + O(x**3) assert exp(sin(x)).series(x, 0, 4) == 1 + x + x**2/2 + O(x**4) assert exp(sin(x)).series(x, 0, 5) == 1 + x + x**2/2 - x**4/8 + O(x**5) def test_floor(): x = Symbol('x') assert floor(x).series(x) == 0 assert floor(-x).series(x) == -1 assert floor(sin(x)).series(x) == 0 assert floor(sin(-x)).series(x) == -1 assert floor(x**3).series(x) == 0 assert floor(-x**3).series(x) == -1 assert floor(cos(x)).series(x) == 0 assert floor(cos(-x)).series(x) == 0 assert floor(5 + sin(x)).series(x) == 5 assert floor(5 + sin(-x)).series(x) == 4 assert floor(x).series(x, 2) == 2 assert floor(-x).series(x, 2) == -3 x = Symbol('x', negative=True) assert floor(x + 1.5).series(x) == 1 def test_ceiling(): assert ceiling(x).series(x) == 1 assert ceiling(-x).series(x) == 0 assert ceiling(sin(x)).series(x) == 1 assert ceiling(sin(-x)).series(x) == 0 assert ceiling(1 - cos(x)).series(x) == 1 assert ceiling(1 - cos(-x)).series(x) == 1 assert ceiling(x).series(x, 2) == 3 assert ceiling(-x).series(x, 2) == -2 def test_abs(): a = Symbol('a') assert abs(x).nseries(x, n=4) == x assert abs(-x).nseries(x, n=4) == x assert abs(x + 1).nseries(x, n=4) == x + 1 assert abs(sin(x)).nseries(x, n=4) == x - Rational(1, 6)*x**3 + O(x**4) assert abs(sin(-x)).nseries(x, n=4) == x - Rational(1, 6)*x**3 + O(x**4) assert abs(x - a).nseries(x, 1) == -a*sign(1 - a) + (x - 1)*sign(1 - a) + sign(1 - a) def test_dir(): assert abs(x).series(x, 0, dir="+") == x assert abs(x).series(x, 0, dir="-") == -x assert floor(x + 2).series(x, 0, dir='+') == 2 assert floor(x + 2).series(x, 0, dir='-') == 1 assert floor(x + 2.2).series(x, 0, dir='-') == 2 assert ceiling(x + 2.2).series(x, 0, dir='-') == 3 assert sin(x + y).series(x, 0, dir='-') == sin(x + y).series(x, 0, dir='+') def test_issue_3504(): a = Symbol("a") e = asin(a*x)/x assert e.series(x, 4, n=2).removeO() == \ (x - 4)*(a/(4*sqrt(-16*a**2 + 1)) - asin(4*a)/16) + asin(4*a)/4 def test_issue_4441(): a, b = symbols('a,b') f = 1/(1 + a*x) assert f.series(x, 0, 5) == 1 - a*x + a**2*x**2 - a**3*x**3 + \ a**4*x**4 + O(x**5) f = 1/(1 + (a + b)*x) assert f.series(x, 0, 3) == 1 + x*(-a - b)\ + x**2*(a + b)**2 + O(x**3) def test_issue_4329(): assert tan(x).series(x, pi/2, n=3).removeO() == \ -pi/6 + x/3 - 1/(x - pi/2) assert cot(x).series(x, pi, n=3).removeO() == \ -x/3 + pi/3 + 1/(x - pi) assert limit(tan(x)**tan(2*x), x, pi/4) == exp(-1) def test_issue_5183(): assert abs(x + x**2).series(n=1) == O(x) assert abs(x + x**2).series(n=2) == x + O(x**2) assert ((1 + x)**2).series(x, n=6) == x**2 + 2*x + 1 assert (1 + 1/x).series() == 1 + 1/x assert Derivative(exp(x).series(), x).doit() == \ 1 + x + x**2/2 + x**3/6 + x**4/24 + O(x**5) def test_issue_5654(): a = Symbol('a') assert (1/(x**2+a**2)**2).nseries(x, x0=I*a, n=0) == \ -I/(4*a**3*(-I*a + x)) - 1/(4*a**2*(-I*a + x)**2) + O(1, (x, I*a)) assert (1/(x**2+a**2)**2).nseries(x, x0=I*a, n=1) == 3/(16*a**4) \ -I/(4*a**3*(-I*a + x)) - 1/(4*a**2*(-I*a + x)**2) + O(-I*a + x, (x, I*a)) def test_issue_5925(): sx = sqrt(x + z).series(z, 0, 1) sxy = sqrt(x + y + z).series(z, 0, 1) s1, s2 = sx.subs(x, x + y), sxy assert (s1 - s2).expand().removeO().simplify() == 0 sx = sqrt(x + z).series(z, 0, 1) sxy = sqrt(x + y + z).series(z, 0, 1) assert sxy.subs({x:1, y:2}) == sx.subs(x, 3) def test_exp_2(): assert exp(x**3).nseries(x, 0, 14) == 1 + x**3 + x**6/2 + x**9/6 + x**12/24 + O(x**14)
e3346d0d0546a4a4510584809c4179a52334011fdf00cba638dbb639c6f7b6a8
from sympy.core.mul import Mul from sympy.core.numbers import (I, Integer, Rational) from sympy.core.symbol import Symbol from sympy.functions.elementary.miscellaneous import (root, sqrt) from sympy.functions.elementary.trigonometric import cos from sympy.integrals.integrals import Integral from sympy.simplify.sqrtdenest import sqrtdenest from sympy.simplify.sqrtdenest import ( _subsets as subsets, _sqrt_numeric_denest) r2, r3, r5, r6, r7, r10, r15, r29 = [sqrt(x) for x in (2, 3, 5, 6, 7, 10, 15, 29)] def test_sqrtdenest(): d = {sqrt(5 + 2 * r6): r2 + r3, sqrt(5. + 2 * r6): sqrt(5. + 2 * r6), sqrt(5. + 4*sqrt(5 + 2 * r6)): sqrt(5.0 + 4*r2 + 4*r3), sqrt(r2): sqrt(r2), sqrt(5 + r7): sqrt(5 + r7), sqrt(3 + sqrt(5 + 2*r7)): 3*r2*(5 + 2*r7)**Rational(1, 4)/(2*sqrt(6 + 3*r7)) + r2*sqrt(6 + 3*r7)/(2*(5 + 2*r7)**Rational(1, 4)), sqrt(3 + 2*r3): 3**Rational(3, 4)*(r6/2 + 3*r2/2)/3} for i in d: assert sqrtdenest(i) == d[i], i def test_sqrtdenest2(): assert sqrtdenest(sqrt(16 - 2*r29 + 2*sqrt(55 - 10*r29))) == \ r5 + sqrt(11 - 2*r29) e = sqrt(-r5 + sqrt(-2*r29 + 2*sqrt(-10*r29 + 55) + 16)) assert sqrtdenest(e) == root(-2*r29 + 11, 4) r = sqrt(1 + r7) assert sqrtdenest(sqrt(1 + r)) == sqrt(1 + r) e = sqrt(((1 + sqrt(1 + 2*sqrt(3 + r2 + r5)))**2).expand()) assert sqrtdenest(e) == 1 + sqrt(1 + 2*sqrt(r2 + r5 + 3)) assert sqrtdenest(sqrt(5*r3 + 6*r2)) == \ sqrt(2)*root(3, 4) + root(3, 4)**3 assert sqrtdenest(sqrt(((1 + r5 + sqrt(1 + r3))**2).expand())) == \ 1 + r5 + sqrt(1 + r3) assert sqrtdenest(sqrt(((1 + r5 + r7 + sqrt(1 + r3))**2).expand())) == \ 1 + sqrt(1 + r3) + r5 + r7 e = sqrt(((1 + cos(2) + cos(3) + sqrt(1 + r3))**2).expand()) assert sqrtdenest(e) == cos(3) + cos(2) + 1 + sqrt(1 + r3) e = sqrt(-2*r10 + 2*r2*sqrt(-2*r10 + 11) + 14) assert sqrtdenest(e) == sqrt(-2*r10 - 2*r2 + 4*r5 + 14) # check that the result is not more complicated than the input z = sqrt(-2*r29 + cos(2) + 2*sqrt(-10*r29 + 55) + 16) assert sqrtdenest(z) == z assert sqrtdenest(sqrt(r6 + sqrt(15))) == sqrt(r6 + sqrt(15)) z = sqrt(15 - 2*sqrt(31) + 2*sqrt(55 - 10*r29)) assert sqrtdenest(z) == z def test_sqrtdenest_rec(): assert sqrtdenest(sqrt(-4*sqrt(14) - 2*r6 + 4*sqrt(21) + 33)) == \ -r2 + r3 + 2*r7 assert sqrtdenest(sqrt(-28*r7 - 14*r5 + 4*sqrt(35) + 82)) == \ -7 + r5 + 2*r7 assert sqrtdenest(sqrt(6*r2/11 + 2*sqrt(22)/11 + 6*sqrt(11)/11 + 2)) == \ sqrt(11)*(r2 + 3 + sqrt(11))/11 assert sqrtdenest(sqrt(468*r3 + 3024*r2 + 2912*r6 + 19735)) == \ 9*r3 + 26 + 56*r6 z = sqrt(-490*r3 - 98*sqrt(115) - 98*sqrt(345) - 2107) assert sqrtdenest(z) == sqrt(-1)*(7*r5 + 7*r15 + 7*sqrt(23)) z = sqrt(-4*sqrt(14) - 2*r6 + 4*sqrt(21) + 34) assert sqrtdenest(z) == z assert sqrtdenest(sqrt(-8*r2 - 2*r5 + 18)) == -r10 + 1 + r2 + r5 assert sqrtdenest(sqrt(8*r2 + 2*r5 - 18)) == \ sqrt(-1)*(-r10 + 1 + r2 + r5) assert sqrtdenest(sqrt(8*r2/3 + 14*r5/3 + Rational(154, 9))) == \ -r10/3 + r2 + r5 + 3 assert sqrtdenest(sqrt(sqrt(2*r6 + 5) + sqrt(2*r7 + 8))) == \ sqrt(1 + r2 + r3 + r7) assert sqrtdenest(sqrt(4*r15 + 8*r5 + 12*r3 + 24)) == 1 + r3 + r5 + r15 w = 1 + r2 + r3 + r5 + r7 assert sqrtdenest(sqrt((w**2).expand())) == w z = sqrt((w**2).expand() + 1) assert sqrtdenest(z) == z z = sqrt(2*r10 + 6*r2 + 4*r5 + 12 + 10*r15 + 30*r3) assert sqrtdenest(z) == z def test_issue_6241(): z = sqrt( -320 + 32*sqrt(5) + 64*r15) assert sqrtdenest(z) == z def test_sqrtdenest3(): z = sqrt(13 - 2*r10 + 2*r2*sqrt(-2*r10 + 11)) assert sqrtdenest(z) == -1 + r2 + r10 assert sqrtdenest(z, max_iter=1) == -1 + sqrt(2) + sqrt(10) z = sqrt(sqrt(r2 + 2) + 2) assert sqrtdenest(z) == z assert sqrtdenest(sqrt(-2*r10 + 4*r2*sqrt(-2*r10 + 11) + 20)) == \ sqrt(-2*r10 - 4*r2 + 8*r5 + 20) assert sqrtdenest(sqrt((112 + 70*r2) + (46 + 34*r2)*r5)) == \ r10 + 5 + 4*r2 + 3*r5 z = sqrt(5 + sqrt(2*r6 + 5)*sqrt(-2*r29 + 2*sqrt(-10*r29 + 55) + 16)) r = sqrt(-2*r29 + 11) assert sqrtdenest(z) == sqrt(r2*r + r3*r + r10 + r15 + 5) n = sqrt(2*r6/7 + 2*r7/7 + 2*sqrt(42)/7 + 2) d = sqrt(16 - 2*r29 + 2*sqrt(55 - 10*r29)) assert sqrtdenest(n/d) == r7*(1 + r6 + r7)/(Mul(7, (sqrt(-2*r29 + 11) + r5), evaluate=False)) def test_sqrtdenest4(): # see Denest_en.pdf in https://github.com/sympy/sympy/issues/3192 z = sqrt(8 - r2*sqrt(5 - r5) - sqrt(3)*(1 + r5)) z1 = sqrtdenest(z) c = sqrt(-r5 + 5) z1 = ((-r15*c - r3*c + c + r5*c - r6 - r2 + r10 + sqrt(30))/4).expand() assert sqrtdenest(z) == z1 z = sqrt(2*r2*sqrt(r2 + 2) + 5*r2 + 4*sqrt(r2 + 2) + 8) assert sqrtdenest(z) == r2 + sqrt(r2 + 2) + 2 w = 2 + r2 + r3 + (1 + r3)*sqrt(2 + r2 + 5*r3) z = sqrt((w**2).expand()) assert sqrtdenest(z) == w.expand() def test_sqrt_symbolic_denest(): x = Symbol('x') z = sqrt(((1 + sqrt(sqrt(2 + x) + 3))**2).expand()) assert sqrtdenest(z) == sqrt((1 + sqrt(sqrt(2 + x) + 3))**2) z = sqrt(((1 + sqrt(sqrt(2 + cos(1)) + 3))**2).expand()) assert sqrtdenest(z) == 1 + sqrt(sqrt(2 + cos(1)) + 3) z = ((1 + cos(2))**4 + 1).expand() assert sqrtdenest(z) == z z = sqrt(((1 + sqrt(sqrt(2 + cos(3*x)) + 3))**2 + 1).expand()) assert sqrtdenest(z) == z c = cos(3) c2 = c**2 assert sqrtdenest(sqrt(2*sqrt(1 + r3)*c + c2 + 1 + r3*c2)) == \ -1 - sqrt(1 + r3)*c ra = sqrt(1 + r3) z = sqrt(20*ra*sqrt(3 + 3*r3) + 12*r3*ra*sqrt(3 + 3*r3) + 64*r3 + 112) assert sqrtdenest(z) == z def test_issue_5857(): from sympy.abc import x, y z = sqrt(1/(4*r3 + 7) + 1) ans = (r2 + r6)/(r3 + 2) assert sqrtdenest(z) == ans assert sqrtdenest(1 + z) == 1 + ans assert sqrtdenest(Integral(z + 1, (x, 1, 2))) == \ Integral(1 + ans, (x, 1, 2)) assert sqrtdenest(x + sqrt(y)) == x + sqrt(y) ans = (r2 + r6)/(r3 + 2) assert sqrtdenest(z) == ans assert sqrtdenest(1 + z) == 1 + ans assert sqrtdenest(Integral(z + 1, (x, 1, 2))) == \ Integral(1 + ans, (x, 1, 2)) assert sqrtdenest(x + sqrt(y)) == x + sqrt(y) def test_subsets(): assert subsets(1) == [[1]] assert subsets(4) == [ [1, 0, 0, 0], [0, 1, 0, 0], [1, 1, 0, 0], [0, 0, 1, 0], [1, 0, 1, 0], [0, 1, 1, 0], [1, 1, 1, 0], [0, 0, 0, 1], [1, 0, 0, 1], [0, 1, 0, 1], [1, 1, 0, 1], [0, 0, 1, 1], [1, 0, 1, 1], [0, 1, 1, 1], [1, 1, 1, 1]] def test_issue_5653(): assert sqrtdenest( sqrt(2 + sqrt(2 + sqrt(2)))) == sqrt(2 + sqrt(2 + sqrt(2))) def test_issue_12420(): assert sqrtdenest((3 - sqrt(2)*sqrt(4 + 3*I) + 3*I)/2) == I e = 3 - sqrt(2)*sqrt(4 + I) + 3*I assert sqrtdenest(e) == e def test_sqrt_ratcomb(): assert sqrtdenest(sqrt(1 + r3) + sqrt(3 + 3*r3) - sqrt(10 + 6*r3)) == 0 def test_issue_18041(): e = -sqrt(-2 + 2*sqrt(3)*I) assert sqrtdenest(e) == -1 - sqrt(3)*I def test_issue_19914(): a = Integer(-8) b = Integer(-1) r = Integer(63) d2 = a*a - b*b*r assert _sqrt_numeric_denest(a, b, r, d2) == \ sqrt(14)*I/2 + 3*sqrt(2)*I/2 assert sqrtdenest(sqrt(-8-sqrt(63))) == sqrt(14)*I/2 + 3*sqrt(2)*I/2
b42b2cd6cffed5748f1c7a16dd32461ef556662e29889f553fd29d92d895af62
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.testing.randtest 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]) 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)
ece6331148ad3639fbeb59ee6fc4fbb9fe5b39361335a6d5966887b424d77584
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.testing.randtest 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
2093f398517ec111480dd1dad89c3a135308e78658af311dd82e200c698f98f2
from sympy.core.add import Add from sympy.core.function import (Derivative, Function, diff) from sympy.core.mul import Mul from sympy.core.numbers import (I, Rational) from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import (Symbol, Wild, symbols) from sympy.functions.elementary.complexes import Abs 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.polys.polytools import factor from sympy.series.order import O from sympy.simplify.radsimp import (collect, collect_const, fraction, radsimp, rcollect) from sympy.core.expr import unchanged from sympy.core.mul import _unevaluated_Mul as umul from sympy.simplify.radsimp import (_unevaluated_Add, collect_sqrt, fraction_expand, collect_abs) from sympy.testing.pytest import raises from sympy.abc import x, y, z, a, b, c, d def test_radsimp(): r2 = sqrt(2) r3 = sqrt(3) r5 = sqrt(5) r7 = sqrt(7) assert fraction(radsimp(1/r2)) == (sqrt(2), 2) assert radsimp(1/(1 + r2)) == \ -1 + sqrt(2) assert radsimp(1/(r2 + r3)) == \ -sqrt(2) + sqrt(3) assert fraction(radsimp(1/(1 + r2 + r3))) == \ (-sqrt(6) + sqrt(2) + 2, 4) assert fraction(radsimp(1/(r2 + r3 + r5))) == \ (-sqrt(30) + 2*sqrt(3) + 3*sqrt(2), 12) assert fraction(radsimp(1/(1 + r2 + r3 + r5))) == ( (-34*sqrt(10) - 26*sqrt(15) - 55*sqrt(3) - 61*sqrt(2) + 14*sqrt(30) + 93 + 46*sqrt(6) + 53*sqrt(5), 71)) assert fraction(radsimp(1/(r2 + r3 + r5 + r7))) == ( (-50*sqrt(42) - 133*sqrt(5) - 34*sqrt(70) - 145*sqrt(3) + 22*sqrt(105) + 185*sqrt(2) + 62*sqrt(30) + 135*sqrt(7), 215)) z = radsimp(1/(1 + r2/3 + r3/5 + r5 + r7)) assert len((3616791619821680643598*z).args) == 16 assert radsimp(1/z) == 1/z assert radsimp(1/z, max_terms=20).expand() == 1 + r2/3 + r3/5 + r5 + r7 assert radsimp(1/(r2*3)) == \ sqrt(2)/6 assert radsimp(1/(r2*a + r3 + r5 + r7)) == ( (8*sqrt(2)*a**7 - 8*sqrt(7)*a**6 - 8*sqrt(5)*a**6 - 8*sqrt(3)*a**6 - 180*sqrt(2)*a**5 + 8*sqrt(30)*a**5 + 8*sqrt(42)*a**5 + 8*sqrt(70)*a**5 - 24*sqrt(105)*a**4 + 84*sqrt(3)*a**4 + 100*sqrt(5)*a**4 + 116*sqrt(7)*a**4 - 72*sqrt(70)*a**3 - 40*sqrt(42)*a**3 - 8*sqrt(30)*a**3 + 782*sqrt(2)*a**3 - 462*sqrt(3)*a**2 - 302*sqrt(7)*a**2 - 254*sqrt(5)*a**2 + 120*sqrt(105)*a**2 - 795*sqrt(2)*a - 62*sqrt(30)*a + 82*sqrt(42)*a + 98*sqrt(70)*a - 118*sqrt(105) + 59*sqrt(7) + 295*sqrt(5) + 531*sqrt(3))/(16*a**8 - 480*a**6 + 3128*a**4 - 6360*a**2 + 3481)) assert radsimp(1/(r2*a + r2*b + r3 + r7)) == ( (sqrt(2)*a*(a + b)**2 - 5*sqrt(2)*a + sqrt(42)*a + sqrt(2)*b*(a + b)**2 - 5*sqrt(2)*b + sqrt(42)*b - sqrt(7)*(a + b)**2 - sqrt(3)*(a + b)**2 - 2*sqrt(3) + 2*sqrt(7))/(2*a**4 + 8*a**3*b + 12*a**2*b**2 - 20*a**2 + 8*a*b**3 - 40*a*b + 2*b**4 - 20*b**2 + 8)) assert radsimp(1/(r2*a + r2*b + r2*c + r2*d)) == \ sqrt(2)/(2*a + 2*b + 2*c + 2*d) assert radsimp(1/(1 + r2*a + r2*b + r2*c + r2*d)) == ( (sqrt(2)*a + sqrt(2)*b + sqrt(2)*c + sqrt(2)*d - 1)/(2*a**2 + 4*a*b + 4*a*c + 4*a*d + 2*b**2 + 4*b*c + 4*b*d + 2*c**2 + 4*c*d + 2*d**2 - 1)) assert radsimp((y**2 - x)/(y - sqrt(x))) == \ sqrt(x) + y assert radsimp(-(y**2 - x)/(y - sqrt(x))) == \ -(sqrt(x) + y) assert radsimp(1/(1 - I + a*I)) == \ (-I*a + 1 + I)/(a**2 - 2*a + 2) assert radsimp(1/((-x + y)*(x - sqrt(y)))) == \ (-x - sqrt(y))/((x - y)*(x**2 - y)) e = (3 + 3*sqrt(2))*x*(3*x - 3*sqrt(y)) assert radsimp(e) == x*(3 + 3*sqrt(2))*(3*x - 3*sqrt(y)) assert radsimp(1/e) == ( (-9*x + 9*sqrt(2)*x - 9*sqrt(y) + 9*sqrt(2)*sqrt(y))/(9*x*(9*x**2 - 9*y))) assert radsimp(1 + 1/(1 + sqrt(3))) == \ Mul(S.Half, -1 + sqrt(3), evaluate=False) + 1 A = symbols("A", commutative=False) assert radsimp(x**2 + sqrt(2)*x**2 - sqrt(2)*x*A) == \ x**2 + sqrt(2)*x**2 - sqrt(2)*x*A assert radsimp(1/sqrt(5 + 2 * sqrt(6))) == -sqrt(2) + sqrt(3) assert radsimp(1/sqrt(5 + 2 * sqrt(6))**3) == -(-sqrt(3) + sqrt(2))**3 # issue 6532 assert fraction(radsimp(1/sqrt(x))) == (sqrt(x), x) assert fraction(radsimp(1/sqrt(2*x + 3))) == (sqrt(2*x + 3), 2*x + 3) assert fraction(radsimp(1/sqrt(2*(x + 3)))) == (sqrt(2*x + 6), 2*x + 6) # issue 5994 e = S('-(2 + 2*sqrt(2) + 4*2**(1/4))/' '(1 + 2**(3/4) + 3*2**(1/4) + 3*sqrt(2))') assert radsimp(e).expand() == -2*2**Rational(3, 4) - 2*2**Rational(1, 4) + 2 + 2*sqrt(2) # issue 5986 (modifications to radimp didn't initially recognize this so # the test is included here) assert radsimp(1/(-sqrt(5)/2 - S.Half + (-sqrt(5)/2 - S.Half)**2)) == 1 # from issue 5934 eq = ( (-240*sqrt(2)*sqrt(sqrt(5) + 5)*sqrt(8*sqrt(5) + 40) - 360*sqrt(2)*sqrt(-8*sqrt(5) + 40)*sqrt(-sqrt(5) + 5) - 120*sqrt(10)*sqrt(-8*sqrt(5) + 40)*sqrt(-sqrt(5) + 5) + 120*sqrt(2)*sqrt(-sqrt(5) + 5)*sqrt(8*sqrt(5) + 40) + 120*sqrt(2)*sqrt(-8*sqrt(5) + 40)*sqrt(sqrt(5) + 5) + 120*sqrt(10)*sqrt(-sqrt(5) + 5)*sqrt(8*sqrt(5) + 40) + 120*sqrt(10)*sqrt(-8*sqrt(5) + 40)*sqrt(sqrt(5) + 5))/(-36000 - 7200*sqrt(5) + (12*sqrt(10)*sqrt(sqrt(5) + 5) + 24*sqrt(10)*sqrt(-sqrt(5) + 5))**2)) assert radsimp(eq) is S.NaN # it's 0/0 # work with normal form e = 1/sqrt(sqrt(7)/7 + 2*sqrt(2) + 3*sqrt(3) + 5*sqrt(5)) + 3 assert radsimp(e) == ( -sqrt(sqrt(7) + 14*sqrt(2) + 21*sqrt(3) + 35*sqrt(5))*(-11654899*sqrt(35) - 1577436*sqrt(210) - 1278438*sqrt(15) - 1346996*sqrt(10) + 1635060*sqrt(6) + 5709765 + 7539830*sqrt(14) + 8291415*sqrt(21))/1300423175 + 3) # obey power rules base = sqrt(3) - sqrt(2) assert radsimp(1/base**3) == (sqrt(3) + sqrt(2))**3 assert radsimp(1/(-base)**3) == -(sqrt(2) + sqrt(3))**3 assert radsimp(1/(-base)**x) == (-base)**(-x) assert radsimp(1/base**x) == (sqrt(2) + sqrt(3))**x assert radsimp(root(1/(-1 - sqrt(2)), -x)) == (-1)**(-1/x)*(1 + sqrt(2))**(1/x) # recurse e = cos(1/(1 + sqrt(2))) assert radsimp(e) == cos(-sqrt(2) + 1) assert radsimp(e/2) == cos(-sqrt(2) + 1)/2 assert radsimp(1/e) == 1/cos(-sqrt(2) + 1) assert radsimp(2/e) == 2/cos(-sqrt(2) + 1) assert fraction(radsimp(e/sqrt(x))) == (sqrt(x)*cos(-sqrt(2)+1), x) # test that symbolic denominators are not processed r = 1 + sqrt(2) assert radsimp(x/r, symbolic=False) == -x*(-sqrt(2) + 1) assert radsimp(x/(y + r), symbolic=False) == x/(y + 1 + sqrt(2)) assert radsimp(x/(y + r)/r, symbolic=False) == \ -x*(-sqrt(2) + 1)/(y + 1 + sqrt(2)) # issue 7408 eq = sqrt(x)/sqrt(y) assert radsimp(eq) == umul(sqrt(x), sqrt(y), 1/y) assert radsimp(eq, symbolic=False) == eq # issue 7498 assert radsimp(sqrt(x)/sqrt(y)**3) == umul(sqrt(x), sqrt(y**3), 1/y**3) # for coverage eq = sqrt(x)/y**2 assert radsimp(eq) == eq def test_radsimp_issue_3214(): c, p = symbols('c p', positive=True) s = sqrt(c**2 - p**2) b = (c + I*p - s)/(c + I*p + s) assert radsimp(b) == -I*(c + I*p - sqrt(c**2 - p**2))**2/(2*c*p) def test_collect_1(): """Collect with respect to a Symbol""" x, y, z, n = symbols('x,y,z,n') assert collect(1, x) == 1 assert collect( x + y*x, x ) == x * (1 + y) assert collect( x + x**2, x ) == x + x**2 assert collect( x**2 + y*x**2, x ) == (x**2)*(1 + y) assert collect( x**2 + y*x, x ) == x*y + x**2 assert collect( 2*x**2 + y*x**2 + 3*x*y, [x] ) == x**2*(2 + y) + 3*x*y assert collect( 2*x**2 + y*x**2 + 3*x*y, [y] ) == 2*x**2 + y*(x**2 + 3*x) assert collect( ((1 + y + x)**4).expand(), x) == ((1 + y)**4).expand() + \ x*(4*(1 + y)**3).expand() + x**2*(6*(1 + y)**2).expand() + \ x**3*(4*(1 + y)).expand() + x**4 # symbols can be given as any iterable expr = x + y assert collect(expr, expr.free_symbols) == expr def test_collect_2(): """Collect with respect to a sum""" a, b, x = symbols('a,b,x') assert collect(a*(cos(x) + sin(x)) + b*(cos(x) + sin(x)), sin(x) + cos(x)) == (a + b)*(cos(x) + sin(x)) def test_collect_3(): """Collect with respect to a product""" a, b, c = symbols('a,b,c') f = Function('f') x, y, z, n = symbols('x,y,z,n') assert collect(-x/8 + x*y, -x) == x*(y - Rational(1, 8)) assert collect( 1 + x*(y**2), x*y ) == 1 + x*(y**2) assert collect( x*y + a*x*y, x*y) == x*y*(1 + a) assert collect( 1 + x*y + a*x*y, x*y) == 1 + x*y*(1 + a) assert collect(a*x*f(x) + b*(x*f(x)), x*f(x)) == x*(a + b)*f(x) assert collect(a*x*log(x) + b*(x*log(x)), x*log(x)) == x*(a + b)*log(x) assert collect(a*x**2*log(x)**2 + b*(x*log(x))**2, x*log(x)) == \ x**2*log(x)**2*(a + b) # with respect to a product of three symbols assert collect(y*x*z + a*x*y*z, x*y*z) == (1 + a)*x*y*z def test_collect_4(): """Collect with respect to a power""" a, b, c, x = symbols('a,b,c,x') assert collect(a*x**c + b*x**c, x**c) == x**c*(a + b) # issue 6096: 2 stays with c (unless c is integer or x is positive0 assert collect(a*x**(2*c) + b*x**(2*c), x**c) == x**(2*c)*(a + b) def test_collect_5(): """Collect with respect to a tuple""" a, x, y, z, n = symbols('a,x,y,z,n') assert collect(x**2*y**4 + z*(x*y**2)**2 + z + a*z, [x*y**2, z]) in [ z*(1 + a + x**2*y**4) + x**2*y**4, z*(1 + a) + x**2*y**4*(1 + z) ] assert collect((1 + (x + y) + (x + y)**2).expand(), [x, y]) == 1 + y + x*(1 + 2*y) + x**2 + y**2 def test_collect_pr19431(): """Unevaluated collect with respect to a product""" a = symbols('a') assert collect(a**2*(a**2 + 1), a**2, evaluate=False)[a**2] == (a**2 + 1) def test_collect_D(): D = Derivative f = Function('f') x, a, b = symbols('x,a,b') fx = D(f(x), x) fxx = D(f(x), x, x) assert collect(a*fx + b*fx, fx) == (a + b)*fx assert collect(a*D(fx, x) + b*D(fx, x), fx) == (a + b)*D(fx, x) assert collect(a*fxx + b*fxx, fx) == (a + b)*D(fx, x) # issue 4784 assert collect(5*f(x) + 3*fx, fx) == 5*f(x) + 3*fx assert collect(f(x) + f(x)*diff(f(x), x) + x*diff(f(x), x)*f(x), f(x).diff(x)) == \ (x*f(x) + f(x))*D(f(x), x) + f(x) assert collect(f(x) + f(x)*diff(f(x), x) + x*diff(f(x), x)*f(x), f(x).diff(x), exact=True) == \ (x*f(x) + f(x))*D(f(x), x) + f(x) assert collect(1/f(x) + 1/f(x)*diff(f(x), x) + x*diff(f(x), x)/f(x), f(x).diff(x), exact=True) == \ (1/f(x) + x/f(x))*D(f(x), x) + 1/f(x) e = (1 + x*fx + fx)/f(x) assert collect(e.expand(), fx) == fx*(x/f(x) + 1/f(x)) + 1/f(x) def test_collect_func(): f = ((x + a + 1)**3).expand() assert collect(f, x) == a**3 + 3*a**2 + 3*a + x**3 + x**2*(3*a + 3) + \ x*(3*a**2 + 6*a + 3) + 1 assert collect(f, x, factor) == x**3 + 3*x**2*(a + 1) + 3*x*(a + 1)**2 + \ (a + 1)**3 assert collect(f, x, evaluate=False) == { S.One: a**3 + 3*a**2 + 3*a + 1, x: 3*a**2 + 6*a + 3, x**2: 3*a + 3, x**3: 1 } assert collect(f, x, factor, evaluate=False) == { S.One: (a + 1)**3, x: 3*(a + 1)**2, x**2: umul(S(3), a + 1), x**3: 1} def test_collect_order(): a, b, x, t = symbols('a,b,x,t') assert collect(t + t*x + t*x**2 + O(x**3), t) == t*(1 + x + x**2 + O(x**3)) assert collect(t + t*x + x**2 + O(x**3), t) == \ t*(1 + x + O(x**3)) + x**2 + O(x**3) f = a*x + b*x + c*x**2 + d*x**2 + O(x**3) g = x*(a + b) + x**2*(c + d) + O(x**3) assert collect(f, x) == g assert collect(f, x, distribute_order_term=False) == g f = sin(a + b).series(b, 0, 10) assert collect(f, [sin(a), cos(a)]) == \ sin(a)*cos(b).series(b, 0, 10) + cos(a)*sin(b).series(b, 0, 10) assert collect(f, [sin(a), cos(a)], distribute_order_term=False) == \ sin(a)*cos(b).series(b, 0, 10).removeO() + \ cos(a)*sin(b).series(b, 0, 10).removeO() + O(b**10) def test_rcollect(): assert rcollect((x**2*y + x*y + x + y)/(x + y), y) == \ (x + y*(1 + x + x**2))/(x + y) assert rcollect(sqrt(-((x + 1)*(y + 1))), z) == sqrt(-((x + 1)*(y + 1))) def test_collect_D_0(): D = Derivative f = Function('f') x, a, b = symbols('x,a,b') fxx = D(f(x), x, x) assert collect(a*fxx + b*fxx, fxx) == (a + b)*fxx def test_collect_Wild(): """Collect with respect to functions with Wild argument""" a, b, x, y = symbols('a b x y') f = Function('f') w1 = Wild('.1') w2 = Wild('.2') assert collect(f(x) + a*f(x), f(w1)) == (1 + a)*f(x) assert collect(f(x, y) + a*f(x, y), f(w1)) == f(x, y) + a*f(x, y) assert collect(f(x, y) + a*f(x, y), f(w1, w2)) == (1 + a)*f(x, y) assert collect(f(x, y) + a*f(x, y), f(w1, w1)) == f(x, y) + a*f(x, y) assert collect(f(x, x) + a*f(x, x), f(w1, w1)) == (1 + a)*f(x, x) assert collect(a*(x + 1)**y + (x + 1)**y, w1**y) == (1 + a)*(x + 1)**y assert collect(a*(x + 1)**y + (x + 1)**y, w1**b) == \ a*(x + 1)**y + (x + 1)**y assert collect(a*(x + 1)**y + (x + 1)**y, (x + 1)**w2) == \ (1 + a)*(x + 1)**y assert collect(a*(x + 1)**y + (x + 1)**y, w1**w2) == (1 + a)*(x + 1)**y def test_collect_const(): # coverage not provided by above tests assert collect_const(2*sqrt(3) + 4*a*sqrt(5)) == \ 2*(2*sqrt(5)*a + sqrt(3)) # let the primitive reabsorb assert collect_const(2*sqrt(3) + 4*a*sqrt(5), sqrt(3)) == \ 2*sqrt(3) + 4*a*sqrt(5) assert collect_const(sqrt(2)*(1 + sqrt(2)) + sqrt(3) + x*sqrt(2)) == \ sqrt(2)*(x + 1 + sqrt(2)) + sqrt(3) # issue 5290 assert collect_const(2*x + 2*y + 1, 2) == \ collect_const(2*x + 2*y + 1) == \ Add(S.One, Mul(2, x + y, evaluate=False), evaluate=False) assert collect_const(-y - z) == Mul(-1, y + z, evaluate=False) assert collect_const(2*x - 2*y - 2*z, 2) == \ Mul(2, x - y - z, evaluate=False) assert collect_const(2*x - 2*y - 2*z, -2) == \ _unevaluated_Add(2*x, Mul(-2, y + z, evaluate=False)) # this is why the content_primitive is used eq = (sqrt(15 + 5*sqrt(2))*x + sqrt(3 + sqrt(2))*y)*2 assert collect_sqrt(eq + 2) == \ 2*sqrt(sqrt(2) + 3)*(sqrt(5)*x + y) + 2 # issue 16296 assert collect_const(a + b + x/2 + y/2) == a + b + Mul(S.Half, x + y, evaluate=False) def test_issue_13143(): f = Function('f') fx = f(x).diff(x) e = f(x) + fx + f(x)*fx # collect function before derivative assert collect(e, Wild('w')) == f(x)*(fx + 1) + fx e = f(x) + f(x)*fx + x*fx*f(x) assert collect(e, fx) == (x*f(x) + f(x))*fx + f(x) assert collect(e, f(x)) == (x*fx + fx + 1)*f(x) e = f(x) + fx + f(x)*fx assert collect(e, [f(x), fx]) == f(x)*(1 + fx) + fx assert collect(e, [fx, f(x)]) == fx*(1 + f(x)) + f(x) def test_issue_6097(): assert collect(a*y**(2.0*x) + b*y**(2.0*x), y**x) == (a + b)*(y**x)**2.0 assert collect(a*2**(2.0*x) + b*2**(2.0*x), 2**x) == (a + b)*(2**x)**2.0 def test_fraction_expand(): eq = (x + y)*y/x assert eq.expand(frac=True) == fraction_expand(eq) == (x*y + y**2)/x assert eq.expand() == y + y**2/x def test_fraction(): x, y, z = map(Symbol, 'xyz') A = Symbol('A', commutative=False) assert fraction(S.Half) == (1, 2) assert fraction(x) == (x, 1) assert fraction(1/x) == (1, x) assert fraction(x/y) == (x, y) assert fraction(x/2) == (x, 2) assert fraction(x*y/z) == (x*y, z) assert fraction(x/(y*z)) == (x, y*z) assert fraction(1/y**2) == (1, y**2) assert fraction(x/y**2) == (x, y**2) assert fraction((x**2 + 1)/y) == (x**2 + 1, y) assert fraction(x*(y + 1)/y**7) == (x*(y + 1), y**7) assert fraction(exp(-x), exact=True) == (exp(-x), 1) assert fraction((1/(x + y))/2, exact=True) == (1, Mul(2,(x + y), evaluate=False)) assert fraction(x*A/y) == (x*A, y) assert fraction(x*A**-1/y) == (x*A**-1, y) n = symbols('n', negative=True) assert fraction(exp(n)) == (1, exp(-n)) assert fraction(exp(-n)) == (exp(-n), 1) p = symbols('p', positive=True) assert fraction(exp(-p)*log(p), exact=True) == (exp(-p)*log(p), 1) m = Mul(1, 1, S.Half, evaluate=False) assert fraction(m) == (1, 2) assert fraction(m, exact=True) == (Mul(1, 1, evaluate=False), 2) m = Mul(1, 1, S.Half, S.Half, Pow(1, -1, evaluate=False), evaluate=False) assert fraction(m) == (1, 4) assert fraction(m, exact=True) == \ (Mul(1, 1, evaluate=False), Mul(2, 2, 1, evaluate=False)) def test_issue_5615(): aA, Re, a, b, D = symbols('aA Re a b D') e = ((D**3*a + b*aA**3)/Re).expand() assert collect(e, [aA**3/Re, a]) == e def test_issue_5933(): from sympy.geometry.polygon import (Polygon, RegularPolygon) from sympy.simplify.radsimp import denom x = Polygon(*RegularPolygon((0, 0), 1, 5).vertices).centroid.x assert abs(denom(x).n()) > 1e-12 assert abs(denom(radsimp(x))) > 1e-12 # in case simplify didn't handle it def test_issue_14608(): a, b = symbols('a b', commutative=False) x, y = symbols('x y') raises(AttributeError, lambda: collect(a*b + b*a, a)) assert collect(x*y + y*(x+1), a) == x*y + y*(x+1) assert collect(x*y + y*(x+1) + a*b + b*a, y) == y*(2*x + 1) + a*b + b*a def test_collect_abs(): s = abs(x) + abs(y) assert collect_abs(s) == s assert unchanged(Mul, abs(x), abs(y)) ans = Abs(x*y) assert isinstance(ans, Abs) assert collect_abs(abs(x)*abs(y)) == ans assert collect_abs(1 + exp(abs(x)*abs(y))) == 1 + exp(ans) # See https://github.com/sympy/sympy/issues/12910 p = Symbol('p', positive=True) assert collect_abs(p/abs(1-p)).is_commutative is True def test_issue_19149(): eq = exp(3*x/4) assert collect(eq, exp(x)) == eq def test_issue_19719(): a, b = symbols('a, b') expr = a**2 * (b + 1) + (7 + 1/b)/a collected = collect(expr, (a**2, 1/a), evaluate=False) # Would return {_Dummy_20**(-2): b + 1, 1/a: 7 + 1/b} without xreplace assert collected == {a**2: b + 1, 1/a: 7 + 1/b} def test_issue_21355(): assert radsimp(1/(x + sqrt(x**2))) == 1/(x + sqrt(x**2)) assert radsimp(1/(x - sqrt(x**2))) == 1/(x - sqrt(x**2))
2d98f857a6bde46263d68dcd94a4681cc93bb1618f012165c36e27b26e33e379
from sympy.core.numbers import I from sympy.core.symbol import symbols from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.trigonometric import (cos, cot, sin) from sympy.testing.pytest import _both_exp_pow x, y, z, n = symbols('x,y,z,n') @_both_exp_pow def test_has(): assert cot(x).has(x) assert cot(x).has(cot) assert not cot(x).has(sin) assert sin(x).has(x) assert sin(x).has(sin) assert not sin(x).has(cot) assert exp(x).has(exp) @_both_exp_pow def test_sin_exp_rewrite(): assert sin(x).rewrite(sin, exp) == -I/2*(exp(I*x) - exp(-I*x)) assert sin(x).rewrite(sin, exp).rewrite(exp, sin) == sin(x) assert cos(x).rewrite(cos, exp).rewrite(exp, cos) == cos(x) assert (sin(5*y) - sin( 2*x)).rewrite(sin, exp).rewrite(exp, sin) == sin(5*y) - sin(2*x) assert sin(x + y).rewrite(sin, exp).rewrite(exp, sin) == sin(x + y) assert cos(x + y).rewrite(cos, exp).rewrite(exp, cos) == cos(x + y) # This next test currently passes... not clear whether it should or not? assert cos(x).rewrite(cos, exp).rewrite(exp, sin) == cos(x)
f9c08573320822c844e1dd33a21899ea8210a5ec07356af05d8e021721ee4f61
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)
3bde564b10afa367c342cf9495aac07127f4ffc3373ee4d1efa9614440e8340f
from sympy.core.numbers import Rational from sympy.core.symbol import symbols from sympy.functions.combinatorial.factorials import (FallingFactorial, RisingFactorial, binomial, factorial) from sympy.functions.special.gamma_functions import gamma from sympy.simplify.combsimp import combsimp from sympy.abc import x def test_combsimp(): k, m, n = symbols('k m n', integer = True) assert combsimp(factorial(n)) == factorial(n) assert combsimp(binomial(n, k)) == binomial(n, k) assert combsimp(factorial(n)/factorial(n - 3)) == n*(-1 + n)*(-2 + n) assert combsimp(binomial(n + 1, k + 1)/binomial(n, k)) == (1 + n)/(1 + k) assert combsimp(binomial(3*n + 4, n + 1)/binomial(3*n + 1, n)) == \ Rational(3, 2)*((3*n + 2)*(3*n + 4)/((n + 1)*(2*n + 3))) assert combsimp(factorial(n)**2/factorial(n - 3)) == \ factorial(n)*n*(-1 + n)*(-2 + n) assert combsimp(factorial(n)*binomial(n + 1, k + 1)/binomial(n, k)) == \ factorial(n + 1)/(1 + k) assert combsimp(gamma(n + 3)) == factorial(n + 2) assert combsimp(factorial(x)) == gamma(x + 1) # issue 9699 assert combsimp((n + 1)*factorial(n)) == factorial(n + 1) assert combsimp(factorial(n)/n) == factorial(n-1) # issue 6658 assert combsimp(binomial(n, n - k)) == binomial(n, k) # issue 6341, 7135 assert combsimp(factorial(n)/(factorial(k)*factorial(n - k))) == \ binomial(n, k) assert combsimp(factorial(k)*factorial(n - k)/factorial(n)) == \ 1/binomial(n, k) assert combsimp(factorial(2*n)/factorial(n)**2) == binomial(2*n, n) assert combsimp(factorial(2*n)*factorial(k)*factorial(n - k)/ factorial(n)**3) == binomial(2*n, n)/binomial(n, k) assert combsimp(factorial(n*(1 + n) - n**2 - n)) == 1 assert combsimp(6*FallingFactorial(-4, n)/factorial(n)) == \ (-1)**n*(n + 1)*(n + 2)*(n + 3) assert combsimp(6*FallingFactorial(-4, n - 1)/factorial(n - 1)) == \ (-1)**(n - 1)*n*(n + 1)*(n + 2) assert combsimp(6*FallingFactorial(-4, n - 3)/factorial(n - 3)) == \ (-1)**(n - 3)*n*(n - 1)*(n - 2) assert combsimp(6*FallingFactorial(-4, -n - 1)/factorial(-n - 1)) == \ -(-1)**(-n - 1)*n*(n - 1)*(n - 2) assert combsimp(6*RisingFactorial(4, n)/factorial(n)) == \ (n + 1)*(n + 2)*(n + 3) assert combsimp(6*RisingFactorial(4, n - 1)/factorial(n - 1)) == \ n*(n + 1)*(n + 2) assert combsimp(6*RisingFactorial(4, n - 3)/factorial(n - 3)) == \ n*(n - 1)*(n - 2) assert combsimp(6*RisingFactorial(4, -n - 1)/factorial(-n - 1)) == \ -n*(n - 1)*(n - 2) def test_issue_6878(): n = symbols('n', integer=True) assert combsimp(RisingFactorial(-10, n)) == 3628800*(-1)**n/factorial(10 - n) def test_issue_14528(): p = symbols("p", integer=True, positive=True) assert combsimp(binomial(1,p)) == 1/(factorial(p)*factorial(1-p)) assert combsimp(factorial(2-p)) == factorial(2-p)
a249c2efebeb418b40174dd37c09f7a0463b435a5c24f3af6d6c231d2a66e77c
from 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.testing.randtest 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)
cceb8ed74c262f907cf9b7f04b551b83981e66d52fcd1ac12f42e9c1d3dd2bf7
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(5, 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
ba0b1095fb8ae8f3a28b175e8adeb7428bec540946e49c8268f94fa748f7e4b1
"""Tests for tools for manipulation of expressions using paths. """ from sympy.simplify.epathtools import epath, EPath from sympy.testing.pytest import raises from sympy.core.numbers import E from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.abc import x, y, z, t def test_epath_select(): expr = [((x, 1, t), 2), ((3, y, 4), z)] assert epath("/*", expr) == [((x, 1, t), 2), ((3, y, 4), z)] assert epath("/*/*", expr) == [(x, 1, t), 2, (3, y, 4), z] assert epath("/*/*/*", expr) == [x, 1, t, 3, y, 4] assert epath("/*/*/*/*", expr) == [] assert epath("/[:]", expr) == [((x, 1, t), 2), ((3, y, 4), z)] assert epath("/[:]/[:]", expr) == [(x, 1, t), 2, (3, y, 4), z] assert epath("/[:]/[:]/[:]", expr) == [x, 1, t, 3, y, 4] assert epath("/[:]/[:]/[:]/[:]", expr) == [] assert epath("/*/[:]", expr) == [(x, 1, t), 2, (3, y, 4), z] assert epath("/*/[0]", expr) == [(x, 1, t), (3, y, 4)] assert epath("/*/[1]", expr) == [2, z] assert epath("/*/[2]", expr) == [] assert epath("/*/int", expr) == [2] assert epath("/*/Symbol", expr) == [z] assert epath("/*/tuple", expr) == [(x, 1, t), (3, y, 4)] assert epath("/*/__iter__?", expr) == [(x, 1, t), (3, y, 4)] assert epath("/*/int|tuple", expr) == [(x, 1, t), 2, (3, y, 4)] assert epath("/*/Symbol|tuple", expr) == [(x, 1, t), (3, y, 4), z] assert epath("/*/int|Symbol|tuple", expr) == [(x, 1, t), 2, (3, y, 4), z] assert epath("/*/int|__iter__?", expr) == [(x, 1, t), 2, (3, y, 4)] assert epath("/*/Symbol|__iter__?", expr) == [(x, 1, t), (3, y, 4), z] assert epath( "/*/int|Symbol|__iter__?", expr) == [(x, 1, t), 2, (3, y, 4), z] assert epath("/*/[0]/int", expr) == [1, 3, 4] assert epath("/*/[0]/Symbol", expr) == [x, t, y] assert epath("/*/[0]/int[1:]", expr) == [1, 4] assert epath("/*/[0]/Symbol[1:]", expr) == [t, y] assert epath("/Symbol", x + y + z + 1) == [x, y, z] assert epath("/*/*/Symbol", t + sin(x + 1) + cos(x + y + E)) == [x, x, y] def test_epath_apply(): expr = [((x, 1, t), 2), ((3, y, 4), z)] func = lambda expr: expr**2 assert epath("/*", expr, list) == [[(x, 1, t), 2], [(3, y, 4), z]] assert epath("/*/[0]", expr, list) == [([x, 1, t], 2), ([3, y, 4], z)] assert epath("/*/[1]", expr, func) == [((x, 1, t), 4), ((3, y, 4), z**2)] assert epath("/*/[2]", expr, list) == expr assert epath("/*/[0]/int", expr, func) == [((x, 1, t), 2), ((9, y, 16), z)] assert epath("/*/[0]/Symbol", expr, func) == [((x**2, 1, t**2), 2), ((3, y**2, 4), z)] assert epath( "/*/[0]/int[1:]", expr, func) == [((x, 1, t), 2), ((3, y, 16), z)] assert epath("/*/[0]/Symbol[1:]", expr, func) == [((x, 1, t**2), 2), ((3, y**2, 4), z)] assert epath("/Symbol", x + y + z + 1, func) == x**2 + y**2 + z**2 + 1 assert epath("/*/*/Symbol", t + sin(x + 1) + cos(x + y + E), func) == \ t + sin(x**2 + 1) + cos(x**2 + y**2 + E) def test_EPath(): assert EPath("/*/[0]")._path == "/*/[0]" assert EPath(EPath("/*/[0]"))._path == "/*/[0]" assert isinstance(epath("/*/[0]"), EPath) is True assert repr(EPath("/*/[0]")) == "EPath('/*/[0]')" raises(ValueError, lambda: EPath("")) raises(ValueError, lambda: EPath("/")) raises(ValueError, lambda: EPath("/|x")) raises(ValueError, lambda: EPath("/[")) raises(ValueError, lambda: EPath("/[0]%")) raises(NotImplementedError, lambda: EPath("Symbol"))
95d40b21f5d75981d814971877b78a546bafc01c12259e51ffd9dcbaddee19c2
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 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, Tuple): assert _cse(c(it)) == ([], c(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)
511b63277f45f92c9a254fe490cbda47c2399c9457f7c408486dce70830eff88
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)
b91abb00623de7b2de2ce99821732a2a4b2d43294ad3dc4c6094547e54fc6beb
from sympy.core.numbers import (Rational, pi) from sympy.functions.elementary.exponential import log from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.special.error_functions import erf from sympy.polys.domains.finitefield import GF from sympy.simplify.ratsimp import (ratsimp, ratsimpmodprime) from sympy.abc import x, y, z, t, a, b, c, d, e def test_ratsimp(): f, g = 1/x + 1/y, (x + y)/(x*y) assert f != g and ratsimp(f) == g f, g = 1/(1 + 1/x), 1 - 1/(x + 1) assert f != g and ratsimp(f) == g f, g = x/(x + y) + y/(x + y), 1 assert f != g and ratsimp(f) == g f, g = -x - y - y**2/(x + y) + x**2/(x + y), -2*y assert f != g and ratsimp(f) == g f = (a*c*x*y + a*c*z - b*d*x*y - b*d*z - b*t*x*y - b*t*x - b*t*z + e*x)/(x*y + z) G = [a*c - b*d - b*t + (-b*t*x + e*x)/(x*y + z), a*c - b*d - b*t - ( b*t*x - e*x)/(x*y + z)] assert f != g and ratsimp(f) in G A = sqrt(pi) B = log(erf(x) - 1) C = log(erf(x) + 1) D = 8 - 8*erf(x) f = A*B/D - A*C/D + A*C*erf(x)/D - A*B*erf(x)/D + 2*A/D assert ratsimp(f) == A*B/8 - A*C/8 - A/(4*erf(x) - 4) def test_ratsimpmodprime(): a = y**5 + x + y b = x - y F = [x*y**5 - x - y] assert ratsimpmodprime(a/b, F, x, y, order='lex') == \ (-x**2 - x*y - x - y) / (-x**2 + x*y) a = x + y**2 - 2 b = x + y**2 - y - 1 F = [x*y - 1] assert ratsimpmodprime(a/b, F, x, y, order='lex') == \ (1 + y - x)/(y - x) a = 5*x**3 + 21*x**2 + 4*x*y + 23*x + 12*y + 15 b = 7*x**3 - y*x**2 + 31*x**2 + 2*x*y + 15*y + 37*x + 21 F = [x**2 + y**2 - 1] assert ratsimpmodprime(a/b, F, x, y, order='lex') == \ (1 + 5*y - 5*x)/(8*y - 6*x) a = x*y - x - 2*y + 4 b = x + y**2 - 2*y F = [x - 2, y - 3] assert ratsimpmodprime(a/b, F, x, y, order='lex') == \ Rational(2, 5) # Test a bug where denominators would be dropped assert ratsimpmodprime(x, [y - 2*x], order='lex') == \ y/2 a = (x**5 + 2*x**4 + 2*x**3 + 2*x**2 + x + 2/x + x**(-2)) assert ratsimpmodprime(a, [x + 1], domain=GF(2)) == 1 assert ratsimpmodprime(a, [x + 1], domain=GF(3)) == -1
4b00fa42c7d296b11da43d9d6e470deb608f54844fe5269d8c2a652eb300a1af
from sympy.categories import (Object, Morphism, IdentityMorphism, NamedMorphism, CompositeMorphism, Diagram, Category) from sympy.categories.baseclasses import Class from sympy.testing.pytest import raises from sympy.core.containers import (Dict, Tuple) from sympy.sets import EmptySet from sympy.sets.sets import FiniteSet def test_morphisms(): A = Object("A") B = Object("B") C = Object("C") D = Object("D") # Test the base morphism. f = NamedMorphism(A, B, "f") assert f.domain == A assert f.codomain == B assert f == NamedMorphism(A, B, "f") # Test identities. id_A = IdentityMorphism(A) id_B = IdentityMorphism(B) assert id_A.domain == A assert id_A.codomain == A assert id_A == IdentityMorphism(A) assert id_A != id_B # Test named morphisms. g = NamedMorphism(B, C, "g") assert g.name == "g" assert g != f assert g == NamedMorphism(B, C, "g") assert g != NamedMorphism(B, C, "f") # Test composite morphisms. assert f == CompositeMorphism(f) k = g.compose(f) assert k.domain == A assert k.codomain == C assert k.components == Tuple(f, g) assert g * f == k assert CompositeMorphism(f, g) == k assert CompositeMorphism(g * f) == g * f # Test the associativity of composition. h = NamedMorphism(C, D, "h") p = h * g u = h * g * f assert h * k == u assert p * f == u assert CompositeMorphism(f, g, h) == u # Test flattening. u2 = u.flatten("u") assert isinstance(u2, NamedMorphism) assert u2.name == "u" assert u2.domain == A assert u2.codomain == D # Test identities. assert f * id_A == f assert id_B * f == f assert id_A * id_A == id_A assert CompositeMorphism(id_A) == id_A # Test bad compositions. raises(ValueError, lambda: f * g) raises(TypeError, lambda: f.compose(None)) raises(TypeError, lambda: id_A.compose(None)) raises(TypeError, lambda: f * None) raises(TypeError, lambda: id_A * None) raises(TypeError, lambda: CompositeMorphism(f, None, 1)) raises(ValueError, lambda: NamedMorphism(A, B, "")) raises(NotImplementedError, lambda: Morphism(A, B)) def test_diagram(): A = Object("A") B = Object("B") C = Object("C") f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") id_A = IdentityMorphism(A) id_B = IdentityMorphism(B) empty = EmptySet # Test the addition of identities. d1 = Diagram([f]) assert d1.objects == FiniteSet(A, B) assert d1.hom(A, B) == (FiniteSet(f), empty) assert d1.hom(A, A) == (FiniteSet(id_A), empty) assert d1.hom(B, B) == (FiniteSet(id_B), empty) assert d1 == Diagram([id_A, f]) assert d1 == Diagram([f, f]) # Test the addition of composites. d2 = Diagram([f, g]) homAC = d2.hom(A, C)[0] assert d2.objects == FiniteSet(A, B, C) assert g * f in d2.premises.keys() assert homAC == FiniteSet(g * f) # Test equality, inequality and hash. d11 = Diagram([f]) assert d1 == d11 assert d1 != d2 assert hash(d1) == hash(d11) d11 = Diagram({f: "unique"}) assert d1 != d11 # Make sure that (re-)adding composites (with new properties) # works as expected. d = Diagram([f, g], {g * f: "unique"}) assert d.conclusions == Dict({g * f: FiniteSet("unique")}) # Check the hom-sets when there are premises and conclusions. assert d.hom(A, C) == (FiniteSet(g * f), FiniteSet(g * f)) d = Diagram([f, g], [g * f]) assert d.hom(A, C) == (FiniteSet(g * f), FiniteSet(g * f)) # Check how the properties of composite morphisms are computed. d = Diagram({f: ["unique", "isomorphism"], g: "unique"}) assert d.premises[g * f] == FiniteSet("unique") # Check that conclusion morphisms with new objects are not allowed. d = Diagram([f], [g]) assert d.conclusions == Dict({}) # Test an empty diagram. d = Diagram() assert d.premises == Dict({}) assert d.conclusions == Dict({}) assert d.objects == empty # Check a SymPy Dict object. d = Diagram(Dict({f: FiniteSet("unique", "isomorphism"), g: "unique"})) assert d.premises[g * f] == FiniteSet("unique") # Check the addition of components of composite morphisms. d = Diagram([g * f]) assert f in d.premises assert g in d.premises # Check subdiagrams. d = Diagram([f, g], {g * f: "unique"}) d1 = Diagram([f]) assert d.is_subdiagram(d1) assert not d1.is_subdiagram(d) d = Diagram([NamedMorphism(B, A, "f'")]) assert not d.is_subdiagram(d1) assert not d1.is_subdiagram(d) d1 = Diagram([f, g], {g * f: ["unique", "something"]}) assert not d.is_subdiagram(d1) assert not d1.is_subdiagram(d) d = Diagram({f: "blooh"}) d1 = Diagram({f: "bleeh"}) assert not d.is_subdiagram(d1) assert not d1.is_subdiagram(d) d = Diagram([f, g], {f: "unique", g * f: "veryunique"}) d1 = d.subdiagram_from_objects(FiniteSet(A, B)) assert d1 == Diagram([f], {f: "unique"}) raises(ValueError, lambda: d.subdiagram_from_objects(FiniteSet(A, Object("D")))) raises(ValueError, lambda: Diagram({IdentityMorphism(A): "unique"})) def test_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]) objects = d1.objects | d2.objects K = Category("K", objects, commutative_diagrams=[d1, d2]) assert K.name == "K" assert K.objects == Class(objects) assert K.commutative_diagrams == FiniteSet(d1, d2) raises(ValueError, lambda: Category(""))
2042cfa5a7669d0c90db1e5ae6a1c2f22a2ae647d3d549c0978875bcede06ea8
from sympy.categories.diagram_drawing import _GrowableGrid, ArrowStringDescription from sympy.categories import (DiagramGrid, Object, NamedMorphism, Diagram, XypicDiagramDrawer, xypic_draw_diagram) from sympy.sets.sets import FiniteSet def test_GrowableGrid(): grid = _GrowableGrid(1, 2) # Check dimensions. assert grid.width == 1 assert grid.height == 2 # Check initialization of elements. assert grid[0, 0] is None assert grid[1, 0] is None # Check assignment to elements. grid[0, 0] = 1 grid[1, 0] = "two" assert grid[0, 0] == 1 assert grid[1, 0] == "two" # Check appending a row. grid.append_row() assert grid.width == 1 assert grid.height == 3 assert grid[0, 0] == 1 assert grid[1, 0] == "two" assert grid[2, 0] is None # Check appending a column. grid.append_column() assert grid.width == 2 assert grid.height == 3 assert grid[0, 0] == 1 assert grid[1, 0] == "two" assert grid[2, 0] is None assert grid[0, 1] is None assert grid[1, 1] is None assert grid[2, 1] is None grid = _GrowableGrid(1, 2) grid[0, 0] = 1 grid[1, 0] = "two" # Check prepending a row. grid.prepend_row() assert grid.width == 1 assert grid.height == 3 assert grid[0, 0] is None assert grid[1, 0] == 1 assert grid[2, 0] == "two" # Check prepending a column. grid.prepend_column() assert grid.width == 2 assert grid.height == 3 assert grid[0, 0] is None assert grid[1, 0] is None assert grid[2, 0] is None assert grid[0, 1] is None assert grid[1, 1] == 1 assert grid[2, 1] == "two" def test_DiagramGrid(): # Set up some objects and morphisms. A = Object("A") B = Object("B") C = Object("C") D = Object("D") E = Object("E") f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") h = NamedMorphism(D, A, "h") k = NamedMorphism(D, B, "k") # A one-morphism diagram. d = Diagram([f]) grid = DiagramGrid(d) assert grid.width == 2 assert grid.height == 1 assert grid[0, 0] == A assert grid[0, 1] == B assert grid.morphisms == {f: FiniteSet()} # A triangle. d = Diagram([f, g], {g * f: "unique"}) grid = DiagramGrid(d) assert grid.width == 2 assert grid.height == 2 assert grid[0, 0] == A assert grid[0, 1] == B assert grid[1, 0] == C assert grid[1, 1] is None assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), g * f: FiniteSet("unique")} # A triangle with a "loop" morphism. l_A = NamedMorphism(A, A, "l_A") d = Diagram([f, g, l_A]) grid = DiagramGrid(d) assert grid.width == 2 assert grid.height == 2 assert grid[0, 0] == A assert grid[0, 1] == B assert grid[1, 0] is None assert grid[1, 1] == C assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), l_A: FiniteSet()} # A simple diagram. d = Diagram([f, g, h, k]) grid = DiagramGrid(d) assert grid.width == 3 assert grid.height == 2 assert grid[0, 0] == A assert grid[0, 1] == B assert grid[0, 2] == D assert grid[1, 0] is None assert grid[1, 1] == C assert grid[1, 2] is None assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(), k: FiniteSet()} assert str(grid) == '[[Object("A"), Object("B"), Object("D")], ' \ '[None, Object("C"), None]]' # A chain of morphisms. f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") h = NamedMorphism(C, D, "h") k = NamedMorphism(D, E, "k") d = Diagram([f, g, h, k]) grid = DiagramGrid(d) assert grid.width == 3 assert grid.height == 3 assert grid[0, 0] == A assert grid[0, 1] == B assert grid[0, 2] is None assert grid[1, 0] is None assert grid[1, 1] == C assert grid[1, 2] == D assert grid[2, 0] is None assert grid[2, 1] is None assert grid[2, 2] == E assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(), k: FiniteSet()} # A square. f = NamedMorphism(A, B, "f") g = NamedMorphism(B, D, "g") h = NamedMorphism(A, C, "h") k = NamedMorphism(C, D, "k") d = Diagram([f, g, h, k]) grid = DiagramGrid(d) assert grid.width == 2 assert grid.height == 2 assert grid[0, 0] == A assert grid[0, 1] == B assert grid[1, 0] == C assert grid[1, 1] == D assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(), k: FiniteSet()} # A strange diagram which resulted from a typo when creating a # test for five lemma, but which allowed to stop one extra problem # in the algorithm. A = Object("A") B = Object("B") C = Object("C") D = Object("D") E = Object("E") A_ = Object("A'") B_ = Object("B'") C_ = Object("C'") D_ = Object("D'") E_ = Object("E'") f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") h = NamedMorphism(C, D, "h") i = NamedMorphism(D, E, "i") # These 4 morphisms should be between primed objects. j = NamedMorphism(A, B, "j") k = NamedMorphism(B, C, "k") l = NamedMorphism(C, D, "l") m = NamedMorphism(D, E, "m") o = NamedMorphism(A, A_, "o") p = NamedMorphism(B, B_, "p") q = NamedMorphism(C, C_, "q") r = NamedMorphism(D, D_, "r") s = NamedMorphism(E, E_, "s") d = Diagram([f, g, h, i, j, k, l, m, o, p, q, r, s]) grid = DiagramGrid(d) assert grid.width == 3 assert grid.height == 4 assert grid[0, 0] is None assert grid[0, 1] == A assert grid[0, 2] == A_ assert grid[1, 0] == C assert grid[1, 1] == B assert grid[1, 2] == B_ assert grid[2, 0] == C_ assert grid[2, 1] == D assert grid[2, 2] == D_ assert grid[3, 0] is None assert grid[3, 1] == E assert grid[3, 2] == E_ morphisms = {} for m in [f, g, h, i, j, k, l, m, o, p, q, r, s]: morphisms[m] = FiniteSet() assert grid.morphisms == morphisms # A cube. A1 = Object("A1") A2 = Object("A2") A3 = Object("A3") A4 = Object("A4") A5 = Object("A5") A6 = Object("A6") A7 = Object("A7") A8 = Object("A8") # The top face of the cube. f1 = NamedMorphism(A1, A2, "f1") f2 = NamedMorphism(A1, A3, "f2") f3 = NamedMorphism(A2, A4, "f3") f4 = NamedMorphism(A3, A4, "f3") # The bottom face of the cube. f5 = NamedMorphism(A5, A6, "f5") f6 = NamedMorphism(A5, A7, "f6") f7 = NamedMorphism(A6, A8, "f7") f8 = NamedMorphism(A7, A8, "f8") # The remaining morphisms. f9 = NamedMorphism(A1, A5, "f9") f10 = NamedMorphism(A2, A6, "f10") f11 = NamedMorphism(A3, A7, "f11") f12 = NamedMorphism(A4, A8, "f11") d = Diagram([f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12]) grid = DiagramGrid(d) assert grid.width == 4 assert grid.height == 3 assert grid[0, 0] is None assert grid[0, 1] == A5 assert grid[0, 2] == A6 assert grid[0, 3] is None assert grid[1, 0] is None assert grid[1, 1] == A1 assert grid[1, 2] == A2 assert grid[1, 3] is None assert grid[2, 0] == A7 assert grid[2, 1] == A3 assert grid[2, 2] == A4 assert grid[2, 3] == A8 morphisms = {} for m in [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12]: morphisms[m] = FiniteSet() assert grid.morphisms == morphisms # A line diagram. A = Object("A") B = Object("B") C = Object("C") D = Object("D") E = Object("E") f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") h = NamedMorphism(C, D, "h") i = NamedMorphism(D, E, "i") d = Diagram([f, g, h, i]) grid = DiagramGrid(d, layout="sequential") assert grid.width == 5 assert grid.height == 1 assert grid[0, 0] == A assert grid[0, 1] == B assert grid[0, 2] == C assert grid[0, 3] == D assert grid[0, 4] == E assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(), i: FiniteSet()} # Test the transposed version. grid = DiagramGrid(d, layout="sequential", transpose=True) assert grid.width == 1 assert grid.height == 5 assert grid[0, 0] == A assert grid[1, 0] == B assert grid[2, 0] == C assert grid[3, 0] == D assert grid[4, 0] == E assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(), i: FiniteSet()} # A pullback. m1 = NamedMorphism(A, B, "m1") m2 = NamedMorphism(A, C, "m2") s1 = NamedMorphism(B, D, "s1") s2 = NamedMorphism(C, D, "s2") f1 = NamedMorphism(E, B, "f1") f2 = NamedMorphism(E, C, "f2") g = NamedMorphism(E, A, "g") d = Diagram([m1, m2, s1, s2, f1, f2], {g: "unique"}) grid = DiagramGrid(d) assert grid.width == 3 assert grid.height == 2 assert grid[0, 0] == A assert grid[0, 1] == B assert grid[0, 2] == E assert grid[1, 0] == C assert grid[1, 1] == D assert grid[1, 2] is None morphisms = {g: FiniteSet("unique")} for m in [m1, m2, s1, s2, f1, f2]: morphisms[m] = FiniteSet() assert grid.morphisms == morphisms # Test the pullback with sequential layout, just for stress # testing. grid = DiagramGrid(d, layout="sequential") assert grid.width == 5 assert grid.height == 1 assert grid[0, 0] == D assert grid[0, 1] == B assert grid[0, 2] == A assert grid[0, 3] == C assert grid[0, 4] == E assert grid.morphisms == morphisms # Test a pullback with object grouping. grid = DiagramGrid(d, groups=FiniteSet(E, FiniteSet(A, B, C, D))) assert grid.width == 3 assert grid.height == 2 assert grid[0, 0] == E assert grid[0, 1] == A assert grid[0, 2] == B assert grid[1, 0] is None assert grid[1, 1] == C assert grid[1, 2] == D assert grid.morphisms == morphisms # Five lemma, actually. A = Object("A") B = Object("B") C = Object("C") D = Object("D") E = Object("E") A_ = Object("A'") B_ = Object("B'") C_ = Object("C'") D_ = Object("D'") E_ = Object("E'") f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") h = NamedMorphism(C, D, "h") i = NamedMorphism(D, E, "i") j = NamedMorphism(A_, B_, "j") k = NamedMorphism(B_, C_, "k") l = NamedMorphism(C_, D_, "l") m = NamedMorphism(D_, E_, "m") o = NamedMorphism(A, A_, "o") p = NamedMorphism(B, B_, "p") q = NamedMorphism(C, C_, "q") r = NamedMorphism(D, D_, "r") s = NamedMorphism(E, E_, "s") d = Diagram([f, g, h, i, j, k, l, m, o, p, q, r, s]) grid = DiagramGrid(d) assert grid.width == 5 assert grid.height == 3 assert grid[0, 0] is None assert grid[0, 1] == A assert grid[0, 2] == A_ assert grid[0, 3] is None assert grid[0, 4] is None assert grid[1, 0] == C assert grid[1, 1] == B assert grid[1, 2] == B_ assert grid[1, 3] == C_ assert grid[1, 4] is None assert grid[2, 0] == D assert grid[2, 1] == E assert grid[2, 2] is None assert grid[2, 3] == D_ assert grid[2, 4] == E_ morphisms = {} for m in [f, g, h, i, j, k, l, m, o, p, q, r, s]: morphisms[m] = FiniteSet() assert grid.morphisms == morphisms # Test the five lemma with object grouping. grid = DiagramGrid(d, FiniteSet( FiniteSet(A, B, C, D, E), FiniteSet(A_, B_, C_, D_, E_))) assert grid.width == 6 assert grid.height == 3 assert grid[0, 0] == A assert grid[0, 1] == B assert grid[0, 2] is None assert grid[0, 3] == A_ assert grid[0, 4] == B_ assert grid[0, 5] is None assert grid[1, 0] is None assert grid[1, 1] == C assert grid[1, 2] == D assert grid[1, 3] is None assert grid[1, 4] == C_ assert grid[1, 5] == D_ assert grid[2, 0] is None assert grid[2, 1] is None assert grid[2, 2] == E assert grid[2, 3] is None assert grid[2, 4] is None assert grid[2, 5] == E_ assert grid.morphisms == morphisms # Test the five lemma with object grouping, but mixing containers # to represent groups. grid = DiagramGrid(d, [(A, B, C, D, E), {A_, B_, C_, D_, E_}]) assert grid.width == 6 assert grid.height == 3 assert grid[0, 0] == A assert grid[0, 1] == B assert grid[0, 2] is None assert grid[0, 3] == A_ assert grid[0, 4] == B_ assert grid[0, 5] is None assert grid[1, 0] is None assert grid[1, 1] == C assert grid[1, 2] == D assert grid[1, 3] is None assert grid[1, 4] == C_ assert grid[1, 5] == D_ assert grid[2, 0] is None assert grid[2, 1] is None assert grid[2, 2] == E assert grid[2, 3] is None assert grid[2, 4] is None assert grid[2, 5] == E_ assert grid.morphisms == morphisms # Test the five lemma with object grouping and hints. grid = DiagramGrid(d, { FiniteSet(A, B, C, D, E): {"layout": "sequential", "transpose": True}, FiniteSet(A_, B_, C_, D_, E_): {"layout": "sequential", "transpose": True}}, transpose=True) assert grid.width == 5 assert grid.height == 2 assert grid[0, 0] == A assert grid[0, 1] == B assert grid[0, 2] == C assert grid[0, 3] == D assert grid[0, 4] == E assert grid[1, 0] == A_ assert grid[1, 1] == B_ assert grid[1, 2] == C_ assert grid[1, 3] == D_ assert grid[1, 4] == E_ assert grid.morphisms == morphisms # A two-triangle disconnected diagram. f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") f_ = NamedMorphism(A_, B_, "f") g_ = NamedMorphism(B_, C_, "g") d = Diagram([f, g, f_, g_], {g * f: "unique", g_ * f_: "unique"}) grid = DiagramGrid(d) assert grid.width == 4 assert grid.height == 2 assert grid[0, 0] == A assert grid[0, 1] == B assert grid[0, 2] == A_ assert grid[0, 3] == B_ assert grid[1, 0] == C assert grid[1, 1] is None assert grid[1, 2] == C_ assert grid[1, 3] is None assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), f_: FiniteSet(), g_: FiniteSet(), g * f: FiniteSet("unique"), g_ * f_: FiniteSet("unique")} # A two-morphism disconnected diagram. f = NamedMorphism(A, B, "f") g = NamedMorphism(C, D, "g") d = Diagram([f, g]) grid = DiagramGrid(d) assert grid.width == 4 assert grid.height == 1 assert grid[0, 0] == A assert grid[0, 1] == B assert grid[0, 2] == C assert grid[0, 3] == D assert grid.morphisms == {f: FiniteSet(), g: FiniteSet()} # Test a one-object diagram. f = NamedMorphism(A, A, "f") d = Diagram([f]) grid = DiagramGrid(d) assert grid.width == 1 assert grid.height == 1 assert grid[0, 0] == A # Test a two-object disconnected diagram. g = NamedMorphism(B, B, "g") d = Diagram([f, g]) grid = DiagramGrid(d) assert grid.width == 2 assert grid.height == 1 assert grid[0, 0] == A assert grid[0, 1] == B def test_DiagramGrid_pseudopod(): # Test a diagram in which even growing a pseudopod does not # eventually help. A = Object("A") B = Object("B") C = Object("C") D = Object("D") E = Object("E") F = Object("F") A_ = Object("A'") B_ = Object("B'") C_ = Object("C'") D_ = Object("D'") E_ = Object("E'") f1 = NamedMorphism(A, B, "f1") f2 = NamedMorphism(A, C, "f2") f3 = NamedMorphism(A, D, "f3") f4 = NamedMorphism(A, E, "f4") f5 = NamedMorphism(A, A_, "f5") f6 = NamedMorphism(A, B_, "f6") f7 = NamedMorphism(A, C_, "f7") f8 = NamedMorphism(A, D_, "f8") f9 = NamedMorphism(A, E_, "f9") f10 = NamedMorphism(A, F, "f10") d = Diagram([f1, f2, f3, f4, f5, f6, f7, f8, f9, f10]) grid = DiagramGrid(d) assert grid.width == 5 assert grid.height == 3 assert grid[0, 0] == E assert grid[0, 1] == C assert grid[0, 2] == C_ assert grid[0, 3] == E_ assert grid[0, 4] == F assert grid[1, 0] == D assert grid[1, 1] == A assert grid[1, 2] == A_ assert grid[1, 3] is None assert grid[1, 4] is None assert grid[2, 0] == D_ assert grid[2, 1] == B assert grid[2, 2] == B_ assert grid[2, 3] is None assert grid[2, 4] is None morphisms = {} for f in [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10]: morphisms[f] = FiniteSet() assert grid.morphisms == morphisms def test_ArrowStringDescription(): astr = ArrowStringDescription("cm", "", None, "", "", "d", "r", "_", "f") assert str(astr) == "\\ar[dr]_{f}" astr = ArrowStringDescription("cm", "", 12, "", "", "d", "r", "_", "f") assert str(astr) == "\\ar[dr]_{f}" astr = ArrowStringDescription("cm", "^", 12, "", "", "d", "r", "_", "f") assert str(astr) == "\\ar@/^12cm/[dr]_{f}" astr = ArrowStringDescription("cm", "", 12, "r", "", "d", "r", "_", "f") assert str(astr) == "\\ar[dr]_{f}" astr = ArrowStringDescription("cm", "", 12, "r", "u", "d", "r", "_", "f") assert str(astr) == "\\ar@(r,u)[dr]_{f}" astr = ArrowStringDescription("cm", "", 12, "r", "u", "d", "r", "_", "f") assert str(astr) == "\\ar@(r,u)[dr]_{f}" astr = ArrowStringDescription("cm", "", 12, "r", "u", "d", "r", "_", "f") astr.arrow_style = "{-->}" assert str(astr) == "\\ar@(r,u)@{-->}[dr]_{f}" astr = ArrowStringDescription("cm", "_", 12, "", "", "d", "r", "_", "f") astr.arrow_style = "{-->}" assert str(astr) == "\\ar@/_12cm/@{-->}[dr]_{f}" def test_XypicDiagramDrawer_line(): # A linear diagram. A = Object("A") B = Object("B") C = Object("C") D = Object("D") E = Object("E") f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") h = NamedMorphism(C, D, "h") i = NamedMorphism(D, E, "i") d = Diagram([f, g, h, i]) grid = DiagramGrid(d, layout="sequential") drawer = XypicDiagramDrawer() assert drawer.draw(d, grid) == "\\xymatrix{\n" \ "A \\ar[r]^{f} & B \\ar[r]^{g} & C \\ar[r]^{h} & D \\ar[r]^{i} & E \n" \ "}\n" # The same diagram, transposed. grid = DiagramGrid(d, layout="sequential", transpose=True) drawer = XypicDiagramDrawer() assert drawer.draw(d, grid) == "\\xymatrix{\n" \ "A \\ar[d]^{f} \\\\\n" \ "B \\ar[d]^{g} \\\\\n" \ "C \\ar[d]^{h} \\\\\n" \ "D \\ar[d]^{i} \\\\\n" \ "E \n" \ "}\n" def test_XypicDiagramDrawer_triangle(): # A triangle diagram. A = Object("A") B = Object("B") C = Object("C") f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") d = Diagram([f, g], {g * f: "unique"}) grid = DiagramGrid(d) drawer = XypicDiagramDrawer() assert drawer.draw(d, grid) == "\\xymatrix{\n" \ "A \\ar[d]_{g\\circ f} \\ar[r]^{f} & B \\ar[ld]^{g} \\\\\n" \ "C & \n" \ "}\n" # The same diagram, transposed. grid = DiagramGrid(d, transpose=True) drawer = XypicDiagramDrawer() assert drawer.draw(d, grid) == "\\xymatrix{\n" \ "A \\ar[r]^{g\\circ f} \\ar[d]_{f} & C \\\\\n" \ "B \\ar[ru]_{g} & \n" \ "}\n" # The same diagram, with a masked morphism. assert drawer.draw(d, grid, masked=[g]) == "\\xymatrix{\n" \ "A \\ar[r]^{g\\circ f} \\ar[d]_{f} & C \\\\\n" \ "B & \n" \ "}\n" # The same diagram with a formatter for "unique". def formatter(astr): astr.label = "\\exists !" + astr.label astr.arrow_style = "{-->}" drawer.arrow_formatters["unique"] = formatter assert drawer.draw(d, grid) == "\\xymatrix{\n" \ "A \\ar@{-->}[r]^{\\exists !g\\circ f} \\ar[d]_{f} & C \\\\\n" \ "B \\ar[ru]_{g} & \n" \ "}\n" # The same diagram with a default formatter. def default_formatter(astr): astr.label_displacement = "(0.45)" drawer.default_arrow_formatter = default_formatter assert drawer.draw(d, grid) == "\\xymatrix{\n" \ "A \\ar@{-->}[r]^(0.45){\\exists !g\\circ f} \\ar[d]_(0.45){f} & C \\\\\n" \ "B \\ar[ru]_(0.45){g} & \n" \ "}\n" # A triangle diagram with a lot of morphisms between the same # objects. f1 = NamedMorphism(B, A, "f1") f2 = NamedMorphism(A, B, "f2") g1 = NamedMorphism(C, B, "g1") g2 = NamedMorphism(B, C, "g2") d = Diagram([f, f1, f2, g, g1, g2], {f1 * g1: "unique", g2 * f2: "unique"}) grid = DiagramGrid(d, transpose=True) drawer = XypicDiagramDrawer() assert drawer.draw(d, grid, masked=[f1*g1*g2*f2, g2*f2*f1*g1]) == \ "\\xymatrix{\n" \ "A \\ar[r]^{g_{2}\\circ f_{2}} \\ar[d]_{f} \\ar@/^3mm/[d]^{f_{2}} " \ "& C \\ar@/^3mm/[l]^{f_{1}\\circ g_{1}} \\ar@/^3mm/[ld]^{g_{1}} \\\\\n" \ "B \\ar@/^3mm/[u]^{f_{1}} \\ar[ru]_{g} \\ar@/^3mm/[ru]^{g_{2}} & \n" \ "}\n" def test_XypicDiagramDrawer_cube(): # A cube diagram. A1 = Object("A1") A2 = Object("A2") A3 = Object("A3") A4 = Object("A4") A5 = Object("A5") A6 = Object("A6") A7 = Object("A7") A8 = Object("A8") # The top face of the cube. f1 = NamedMorphism(A1, A2, "f1") f2 = NamedMorphism(A1, A3, "f2") f3 = NamedMorphism(A2, A4, "f3") f4 = NamedMorphism(A3, A4, "f3") # The bottom face of the cube. f5 = NamedMorphism(A5, A6, "f5") f6 = NamedMorphism(A5, A7, "f6") f7 = NamedMorphism(A6, A8, "f7") f8 = NamedMorphism(A7, A8, "f8") # The remaining morphisms. f9 = NamedMorphism(A1, A5, "f9") f10 = NamedMorphism(A2, A6, "f10") f11 = NamedMorphism(A3, A7, "f11") f12 = NamedMorphism(A4, A8, "f11") d = Diagram([f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12]) grid = DiagramGrid(d) drawer = XypicDiagramDrawer() assert drawer.draw(d, grid) == "\\xymatrix{\n" \ "& A_{5} \\ar[r]^{f_{5}} \\ar[ldd]_{f_{6}} & A_{6} \\ar[rdd]^{f_{7}} " \ "& \\\\\n" \ "& A_{1} \\ar[r]^{f_{1}} \\ar[d]^{f_{2}} \\ar[u]^{f_{9}} & A_{2} " \ "\\ar[d]^{f_{3}} \\ar[u]_{f_{10}} & \\\\\n" \ "A_{7} \\ar@/_3mm/[rrr]_{f_{8}} & A_{3} \\ar[r]^{f_{3}} \\ar[l]_{f_{11}} " \ "& A_{4} \\ar[r]^{f_{11}} & A_{8} \n" \ "}\n" # The same diagram, transposed. grid = DiagramGrid(d, transpose=True) drawer = XypicDiagramDrawer() assert drawer.draw(d, grid) == "\\xymatrix{\n" \ "& & A_{7} \\ar@/^3mm/[ddd]^{f_{8}} \\\\\n" \ "A_{5} \\ar[d]_{f_{5}} \\ar[rru]^{f_{6}} & A_{1} \\ar[d]^{f_{1}} " \ "\\ar[r]^{f_{2}} \\ar[l]^{f_{9}} & A_{3} \\ar[d]_{f_{3}} " \ "\\ar[u]^{f_{11}} \\\\\n" \ "A_{6} \\ar[rrd]_{f_{7}} & A_{2} \\ar[r]^{f_{3}} \\ar[l]^{f_{10}} " \ "& A_{4} \\ar[d]_{f_{11}} \\\\\n" \ "& & A_{8} \n" \ "}\n" def test_XypicDiagramDrawer_curved_and_loops(): # A simple diagram, with a curved arrow. A = Object("A") B = Object("B") C = Object("C") D = Object("D") f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") h = NamedMorphism(D, A, "h") k = NamedMorphism(D, B, "k") d = Diagram([f, g, h, k]) grid = DiagramGrid(d) drawer = XypicDiagramDrawer() assert drawer.draw(d, grid) == "\\xymatrix{\n" \ "A \\ar[r]_{f} & B \\ar[d]^{g} & D \\ar[l]^{k} \\ar@/_3mm/[ll]_{h} \\\\\n" \ "& C & \n" \ "}\n" # The same diagram, transposed. grid = DiagramGrid(d, transpose=True) drawer = XypicDiagramDrawer() assert drawer.draw(d, grid) == "\\xymatrix{\n" \ "A \\ar[d]^{f} & \\\\\n" \ "B \\ar[r]^{g} & C \\\\\n" \ "D \\ar[u]_{k} \\ar@/^3mm/[uu]^{h} & \n" \ "}\n" # The same diagram, larger and rotated. assert drawer.draw(d, grid, diagram_format="@+1cm@dr") == \ "\\xymatrix@+1cm@dr{\n" \ "A \\ar[d]^{f} & \\\\\n" \ "B \\ar[r]^{g} & C \\\\\n" \ "D \\ar[u]_{k} \\ar@/^3mm/[uu]^{h} & \n" \ "}\n" # A simple diagram with three curved arrows. h1 = NamedMorphism(D, A, "h1") h2 = NamedMorphism(A, D, "h2") k = NamedMorphism(D, B, "k") d = Diagram([f, g, h, k, h1, h2]) grid = DiagramGrid(d) drawer = XypicDiagramDrawer() assert drawer.draw(d, grid) == "\\xymatrix{\n" \ "A \\ar[r]_{f} \\ar@/^3mm/[rr]^{h_{2}} & B \\ar[d]^{g} & D \\ar[l]^{k} " \ "\\ar@/_7mm/[ll]_{h} \\ar@/_11mm/[ll]_{h_{1}} \\\\\n" \ "& C & \n" \ "}\n" # The same diagram, transposed. grid = DiagramGrid(d, transpose=True) drawer = XypicDiagramDrawer() assert drawer.draw(d, grid) == "\\xymatrix{\n" \ "A \\ar[d]^{f} \\ar@/_3mm/[dd]_{h_{2}} & \\\\\n" \ "B \\ar[r]^{g} & C \\\\\n" \ "D \\ar[u]_{k} \\ar@/^7mm/[uu]^{h} \\ar@/^11mm/[uu]^{h_{1}} & \n" \ "}\n" # The same diagram, with "loop" morphisms. l_A = NamedMorphism(A, A, "l_A") l_D = NamedMorphism(D, D, "l_D") l_C = NamedMorphism(C, C, "l_C") d = Diagram([f, g, h, k, h1, h2, l_A, l_D, l_C]) grid = DiagramGrid(d) drawer = XypicDiagramDrawer() assert drawer.draw(d, grid) == "\\xymatrix{\n" \ "A \\ar[r]_{f} \\ar@/^3mm/[rr]^{h_{2}} \\ar@(u,l)[]^{l_{A}} " \ "& B \\ar[d]^{g} & D \\ar[l]^{k} \\ar@/_7mm/[ll]_{h} " \ "\\ar@/_11mm/[ll]_{h_{1}} \\ar@(r,u)[]^{l_{D}} \\\\\n" \ "& C \\ar@(l,d)[]^{l_{C}} & \n" \ "}\n" # The same diagram with "loop" morphisms, transposed. grid = DiagramGrid(d, transpose=True) drawer = XypicDiagramDrawer() assert drawer.draw(d, grid) == "\\xymatrix{\n" \ "A \\ar[d]^{f} \\ar@/_3mm/[dd]_{h_{2}} \\ar@(r,u)[]^{l_{A}} & \\\\\n" \ "B \\ar[r]^{g} & C \\ar@(r,u)[]^{l_{C}} \\\\\n" \ "D \\ar[u]_{k} \\ar@/^7mm/[uu]^{h} \\ar@/^11mm/[uu]^{h_{1}} " \ "\\ar@(l,d)[]^{l_{D}} & \n" \ "}\n" # The same diagram with two "loop" morphisms per object. l_A_ = NamedMorphism(A, A, "n_A") l_D_ = NamedMorphism(D, D, "n_D") l_C_ = NamedMorphism(C, C, "n_C") d = Diagram([f, g, h, k, h1, h2, l_A, l_D, l_C, l_A_, l_D_, l_C_]) grid = DiagramGrid(d) drawer = XypicDiagramDrawer() assert drawer.draw(d, grid) == "\\xymatrix{\n" \ "A \\ar[r]_{f} \\ar@/^3mm/[rr]^{h_{2}} \\ar@(u,l)[]^{l_{A}} " \ "\\ar@/^3mm/@(l,d)[]^{n_{A}} & B \\ar[d]^{g} & D \\ar[l]^{k} " \ "\\ar@/_7mm/[ll]_{h} \\ar@/_11mm/[ll]_{h_{1}} \\ar@(r,u)[]^{l_{D}} " \ "\\ar@/^3mm/@(d,r)[]^{n_{D}} \\\\\n" \ "& C \\ar@(l,d)[]^{l_{C}} \\ar@/^3mm/@(d,r)[]^{n_{C}} & \n" \ "}\n" # The same diagram with two "loop" morphisms per object, transposed. grid = DiagramGrid(d, transpose=True) drawer = XypicDiagramDrawer() assert drawer.draw(d, grid) == "\\xymatrix{\n" \ "A \\ar[d]^{f} \\ar@/_3mm/[dd]_{h_{2}} \\ar@(r,u)[]^{l_{A}} " \ "\\ar@/^3mm/@(u,l)[]^{n_{A}} & \\\\\n" \ "B \\ar[r]^{g} & C \\ar@(r,u)[]^{l_{C}} \\ar@/^3mm/@(d,r)[]^{n_{C}} \\\\\n" \ "D \\ar[u]_{k} \\ar@/^7mm/[uu]^{h} \\ar@/^11mm/[uu]^{h_{1}} " \ "\\ar@(l,d)[]^{l_{D}} \\ar@/^3mm/@(d,r)[]^{n_{D}} & \n" \ "}\n" def test_xypic_draw_diagram(): # A linear diagram. A = Object("A") B = Object("B") C = Object("C") D = Object("D") E = Object("E") f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") h = NamedMorphism(C, D, "h") i = NamedMorphism(D, E, "i") d = Diagram([f, g, h, i]) grid = DiagramGrid(d, layout="sequential") drawer = XypicDiagramDrawer() assert drawer.draw(d, grid) == xypic_draw_diagram(d, layout="sequential")
f23f1286720d9b4c0566f255a0bdd16a324e4bd377c5078c75f19edbd16321d7
from sympy.core.function import diff 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.complexes import (Abs, conjugate, im, re, sign) from sympy.functions.elementary.exponential import log from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acos, asin, cos, sin) from sympy.integrals.integrals import integrate from sympy.matrices.dense import Matrix from sympy.simplify.trigsimp import trigsimp from sympy.algebras.quaternion import Quaternion from sympy.testing.pytest import raises w, x, y, z = symbols('w:z') phi = symbols('phi') def test_quaternion_construction(): q = Quaternion(w, x, y, z) assert q + q == Quaternion(2*w, 2*x, 2*y, 2*z) q2 = Quaternion.from_axis_angle((sqrt(3)/3, sqrt(3)/3, sqrt(3)/3), pi*Rational(2, 3)) assert q2 == Quaternion(S.Half, S.Half, S.Half, S.Half) M = Matrix([[cos(phi), -sin(phi), 0], [sin(phi), cos(phi), 0], [0, 0, 1]]) q3 = trigsimp(Quaternion.from_rotation_matrix(M)) assert q3 == Quaternion(sqrt(2)*sqrt(cos(phi) + 1)/2, 0, 0, sqrt(2 - 2*cos(phi))*sign(sin(phi))/2) nc = Symbol('nc', commutative=False) raises(ValueError, lambda: Quaternion(w, x, nc, z)) def test_quaternion_axis_angle(): test_data = [ # axis, angle, expected_quaternion ((1, 0, 0), 0, (1, 0, 0, 0)), ((1, 0, 0), pi/2, (sqrt(2)/2, sqrt(2)/2, 0, 0)), ((0, 1, 0), pi/2, (sqrt(2)/2, 0, sqrt(2)/2, 0)), ((0, 0, 1), pi/2, (sqrt(2)/2, 0, 0, sqrt(2)/2)), ((1, 0, 0), pi, (0, 1, 0, 0)), ((0, 1, 0), pi, (0, 0, 1, 0)), ((0, 0, 1), pi, (0, 0, 0, 1)), ((1, 1, 1), pi, (0, 1/sqrt(3),1/sqrt(3),1/sqrt(3))), ((sqrt(3)/3, sqrt(3)/3, sqrt(3)/3), pi*2/3, (S.Half, S.Half, S.Half, S.Half)) ] for axis, angle, expected in test_data: assert Quaternion.from_axis_angle(axis, angle) == Quaternion(*expected) def test_quaternion_axis_angle_simplification(): result = Quaternion.from_axis_angle((1, 2, 3), asin(4)) assert result.a == cos(asin(4)/2) assert result.b == sqrt(14)*sin(asin(4)/2)/14 assert result.c == sqrt(14)*sin(asin(4)/2)/7 assert result.d == 3*sqrt(14)*sin(asin(4)/2)/14 def test_quaternion_complex_real_addition(): a = symbols("a", complex=True) b = symbols("b", real=True) # This symbol is not complex: c = symbols("c", commutative=False) q = Quaternion(w, x, y, z) assert a + q == Quaternion(w + re(a), x + im(a), y, z) assert 1 + q == Quaternion(1 + w, x, y, z) assert I + q == Quaternion(w, 1 + x, y, z) assert b + q == Quaternion(w + b, x, y, z) raises(ValueError, lambda: c + q) raises(ValueError, lambda: q * c) raises(ValueError, lambda: c * q) assert -q == Quaternion(-w, -x, -y, -z) q1 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) q2 = Quaternion(1, 4, 7, 8) assert q1 + (2 + 3*I) == Quaternion(5 + 7*I, 2 + 5*I, 0, 7 + 8*I) assert q2 + (2 + 3*I) == Quaternion(3, 7, 7, 8) assert q1 * (2 + 3*I) == \ Quaternion((2 + 3*I)*(3 + 4*I), (2 + 3*I)*(2 + 5*I), 0, (2 + 3*I)*(7 + 8*I)) assert q2 * (2 + 3*I) == Quaternion(-10, 11, 38, -5) q1 = Quaternion(1, 2, 3, 4) q0 = Quaternion(0, 0, 0, 0) assert q1 + q0 == q1 assert q1 - q0 == q1 assert q1 - q1 == q0 def test_quaternion_evalf(): assert Quaternion(sqrt(2), 0, 0, sqrt(3)).evalf() == Quaternion(sqrt(2).evalf(), 0, 0, sqrt(3).evalf()) assert Quaternion(1/sqrt(2), 0, 0, 1/sqrt(2)).evalf() == Quaternion((1/sqrt(2)).evalf(), 0, 0, (1/sqrt(2)).evalf()) def test_quaternion_functions(): q = Quaternion(w, x, y, z) q1 = Quaternion(1, 2, 3, 4) q0 = Quaternion(0, 0, 0, 0) assert conjugate(q) == Quaternion(w, -x, -y, -z) assert q.norm() == sqrt(w**2 + x**2 + y**2 + z**2) assert q.normalize() == Quaternion(w, x, y, z) / sqrt(w**2 + x**2 + y**2 + z**2) assert q.inverse() == Quaternion(w, -x, -y, -z) / (w**2 + x**2 + y**2 + z**2) assert q.inverse() == q.pow(-1) raises(ValueError, lambda: q0.inverse()) assert q.pow(2) == Quaternion(w**2 - x**2 - y**2 - z**2, 2*w*x, 2*w*y, 2*w*z) assert q**(2) == Quaternion(w**2 - x**2 - y**2 - z**2, 2*w*x, 2*w*y, 2*w*z) assert q1.pow(-2) == Quaternion(Rational(-7, 225), Rational(-1, 225), Rational(-1, 150), Rational(-2, 225)) assert q1**(-2) == Quaternion(Rational(-7, 225), Rational(-1, 225), Rational(-1, 150), Rational(-2, 225)) assert q1.pow(-0.5) == NotImplemented raises(TypeError, lambda: q1**(-0.5)) assert q1.exp() == \ Quaternion(E * cos(sqrt(29)), 2 * sqrt(29) * E * sin(sqrt(29)) / 29, 3 * sqrt(29) * E * sin(sqrt(29)) / 29, 4 * sqrt(29) * E * sin(sqrt(29)) / 29) assert q1._ln() == \ Quaternion(log(sqrt(30)), 2 * sqrt(29) * acos(sqrt(30)/30) / 29, 3 * sqrt(29) * acos(sqrt(30)/30) / 29, 4 * sqrt(29) * acos(sqrt(30)/30) / 29) assert q1.pow_cos_sin(2) == \ Quaternion(30 * cos(2 * acos(sqrt(30)/30)), 60 * sqrt(29) * sin(2 * acos(sqrt(30)/30)) / 29, 90 * sqrt(29) * sin(2 * acos(sqrt(30)/30)) / 29, 120 * sqrt(29) * sin(2 * acos(sqrt(30)/30)) / 29) assert diff(Quaternion(x, x, x, x), x) == Quaternion(1, 1, 1, 1) assert integrate(Quaternion(x, x, x, x), x) == \ Quaternion(x**2 / 2, x**2 / 2, x**2 / 2, x**2 / 2) assert Quaternion.rotate_point((1, 1, 1), q1) == (S.One / 5, 1, S(7) / 5) n = Symbol('n') raises(TypeError, lambda: q1**n) n = Symbol('n', integer=True) raises(TypeError, lambda: q1**n) def test_quaternion_conversions(): q1 = Quaternion(1, 2, 3, 4) assert q1.to_axis_angle() == ((2 * sqrt(29)/29, 3 * sqrt(29)/29, 4 * sqrt(29)/29), 2 * acos(sqrt(30)/30)) assert q1.to_rotation_matrix() == Matrix([[Rational(-2, 3), Rational(2, 15), Rational(11, 15)], [Rational(2, 3), Rational(-1, 3), Rational(2, 3)], [Rational(1, 3), Rational(14, 15), Rational(2, 15)]]) assert q1.to_rotation_matrix((1, 1, 1)) == Matrix([[Rational(-2, 3), Rational(2, 15), Rational(11, 15), Rational(4, 5)], [Rational(2, 3), Rational(-1, 3), Rational(2, 3), S.Zero], [Rational(1, 3), Rational(14, 15), Rational(2, 15), Rational(-2, 5)], [S.Zero, S.Zero, S.Zero, S.One]]) theta = symbols("theta", real=True) q2 = Quaternion(cos(theta/2), 0, 0, sin(theta/2)) assert trigsimp(q2.to_rotation_matrix()) == Matrix([ [cos(theta), -sin(theta), 0], [sin(theta), cos(theta), 0], [0, 0, 1]]) assert q2.to_axis_angle() == ((0, 0, sin(theta/2)/Abs(sin(theta/2))), 2*acos(cos(theta/2))) assert trigsimp(q2.to_rotation_matrix((1, 1, 1))) == Matrix([ [cos(theta), -sin(theta), 0, sin(theta) - cos(theta) + 1], [sin(theta), cos(theta), 0, -sin(theta) - cos(theta) + 1], [0, 0, 1, 0], [0, 0, 0, 1]]) def test_quaternion_rotation_iss1593(): """ There was a sign mistake in the definition, of the rotation matrix. This tests that particular sign mistake. See issue 1593 for reference. See wikipedia https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Quaternion-derived_rotation_matrix for the correct definition """ q = Quaternion(cos(phi/2), sin(phi/2), 0, 0) assert(trigsimp(q.to_rotation_matrix()) == Matrix([ [1, 0, 0], [0, cos(phi), -sin(phi)], [0, sin(phi), cos(phi)]])) def test_quaternion_multiplication(): q1 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) q2 = Quaternion(1, 2, 3, 5) q3 = Quaternion(1, 1, 1, y) assert Quaternion._generic_mul(4, 1) == 4 assert Quaternion._generic_mul(4, q1) == Quaternion(12 + 16*I, 8 + 20*I, 0, 28 + 32*I) assert q2.mul(2) == Quaternion(2, 4, 6, 10) assert q2.mul(q3) == Quaternion(-5*y - 4, 3*y - 2, 9 - 2*y, y + 4) assert q2.mul(q3) == q2*q3 z = symbols('z', complex=True) z_quat = Quaternion(re(z), im(z), 0, 0) q = Quaternion(*symbols('q:4', real=True)) assert z * q == z_quat * q assert q * z == q * z_quat def test_issue_16318(): #for rtruediv q0 = Quaternion(0, 0, 0, 0) raises(ValueError, lambda: 1/q0) #for rotate_point q = Quaternion(1, 2, 3, 4) (axis, angle) = q.to_axis_angle() assert Quaternion.rotate_point((1, 1, 1), (axis, angle)) == (S.One / 5, 1, S(7) / 5) #test for to_axis_angle q = Quaternion(-1, 1, 1, 1) axis = (-sqrt(3)/3, -sqrt(3)/3, -sqrt(3)/3) angle = 2*pi/3 assert (axis, angle) == q.to_axis_angle()
2db472c61869f8d9e77c9da04e7d527658020509f6ae1c81ef10293a071dfeb3
from sympy.diffgeom import Manifold, Patch, CoordSystem, Point from sympy.core.function import Function from sympy.core.symbol import symbols from sympy.testing.pytest import warns_deprecated_sympy m = Manifold('m', 2) p = Patch('p', m) a, b = symbols('a b') cs = CoordSystem('cs', p, [a, b]) x, y = symbols('x y') f = Function('f') s1, s2 = cs.coord_functions() v1, v2 = cs.base_vectors() f1, f2 = cs.base_oneforms() def test_point(): point = Point(cs, [x, y]) assert point != Point(cs, [2, y]) #TODO assert point.subs(x, 2) == Point(cs, [2, y]) #TODO assert point.free_symbols == set([x, y]) def test_subs(): assert s1.subs(s1, s2) == s2 assert v1.subs(v1, v2) == v2 assert f1.subs(f1, f2) == f2 assert (x*f(s1) + y).subs(s1, s2) == x*f(s2) + y assert (f(s1)*v1).subs(v1, v2) == f(s1)*v2 assert (y*f(s1)*f1).subs(f1, f2) == y*f(s1)*f2 def test_deprecated(): with warns_deprecated_sympy(): cs_wname = CoordSystem('cs', p, ['a', 'b']) assert cs_wname == cs_wname.func(*cs_wname.args)
8f3797c20ad209fd5d231cbe00debcaf8c0f6057e4ee25483ae6fdb8c9ac0f05
from sympy.core import Lambda, Symbol, symbols from sympy.diffgeom.rn import R2, R2_p, R2_r, R3_r, R3_c, R3_s, R2_origin from sympy.diffgeom import (CoordSystem, Commutator, Differential, TensorProduct, WedgeProduct, BaseCovarDerivativeOp, CovarDerivativeOp, LieDerivative, covariant_order, contravariant_order, twoform_to_matrix, metric_to_Christoffel_1st, metric_to_Christoffel_2nd, metric_to_Riemann_components, metric_to_Ricci_components, intcurve_diffequ, intcurve_series) from sympy.simplify import trigsimp, simplify from sympy.functions import sqrt, atan2, sin from sympy.matrices import Matrix from sympy.testing.pytest import raises, nocache_fail from sympy.testing.pytest import warns_deprecated_sympy TP = TensorProduct def test_coordsys_transform(): # test inverse transforms p, q, r, s = symbols('p q r s') rel = {('first', 'second'): [(p, q), (q, -p)]} R2_pq = CoordSystem('first', R2_origin, [p, q], rel) R2_rs = CoordSystem('second', R2_origin, [r, s], rel) r, s = R2_rs.symbols assert R2_rs.transform(R2_pq) == Matrix([[-s], [r]]) # inverse transform impossible case a, b = symbols('a b', positive=True) rel = {('first', 'second'): [(a,), (-a,)]} R2_a = CoordSystem('first', R2_origin, [a], rel) R2_b = CoordSystem('second', R2_origin, [b], rel) # This transformation is uninvertible because there is no positive a, b satisfying a = -b with raises(NotImplementedError): R2_b.transform(R2_a) # inverse transform ambiguous case c, d = symbols('c d') rel = {('first', 'second'): [(c,), (c**2,)]} R2_c = CoordSystem('first', R2_origin, [c], rel) R2_d = CoordSystem('second', R2_origin, [d], rel) # The transform method should throw if it finds multiple inverses for a coordinate transformation. with raises(ValueError): R2_d.transform(R2_c) # test indirect transformation a, b, c, d, e, f = symbols('a, b, c, d, e, f') rel = {('C1', 'C2'): [(a, b), (2*a, 3*b)], ('C2', 'C3'): [(c, d), (3*c, 2*d)]} C1 = CoordSystem('C1', R2_origin, (a, b), rel) C2 = CoordSystem('C2', R2_origin, (c, d), rel) C3 = CoordSystem('C3', R2_origin, (e, f), rel) a, b = C1.symbols c, d = C2.symbols e, f = C3.symbols assert C2.transform(C1) == Matrix([c/2, d/3]) assert C1.transform(C3) == Matrix([6*a, 6*b]) assert C3.transform(C1) == Matrix([e/6, f/6]) assert C3.transform(C2) == Matrix([e/3, f/2]) a, b, c, d, e, f = symbols('a, b, c, d, e, f') rel = {('C1', 'C2'): [(a, b), (2*a, 3*b + 1)], ('C3', 'C2'): [(e, f), (-e - 2, 2*f)]} C1 = CoordSystem('C1', R2_origin, (a, b), rel) C2 = CoordSystem('C2', R2_origin, (c, d), rel) C3 = CoordSystem('C3', R2_origin, (e, f), rel) a, b = C1.symbols c, d = C2.symbols e, f = C3.symbols assert C2.transform(C1) == Matrix([c/2, (d - 1)/3]) assert C1.transform(C3) == Matrix([-2*a - 2, (3*b + 1)/2]) assert C3.transform(C1) == Matrix([-e/2 - 1, (2*f - 1)/3]) assert C3.transform(C2) == Matrix([-e - 2, 2*f]) # old signature uses Lambda a, b, c, d, e, f = symbols('a, b, c, d, e, f') rel = {('C1', 'C2'): Lambda((a, b), (2*a, 3*b + 1)), ('C3', 'C2'): Lambda((e, f), (-e - 2, 2*f))} C1 = CoordSystem('C1', R2_origin, (a, b), rel) C2 = CoordSystem('C2', R2_origin, (c, d), rel) C3 = CoordSystem('C3', R2_origin, (e, f), rel) a, b = C1.symbols c, d = C2.symbols e, f = C3.symbols assert C2.transform(C1) == Matrix([c/2, (d - 1)/3]) assert C1.transform(C3) == Matrix([-2*a - 2, (3*b + 1)/2]) assert C3.transform(C1) == Matrix([-e/2 - 1, (2*f - 1)/3]) assert C3.transform(C2) == Matrix([-e - 2, 2*f]) def test_R2(): x0, y0, r0, theta0 = symbols('x0, y0, r0, theta0', real=True) point_r = R2_r.point([x0, y0]) point_p = R2_p.point([r0, theta0]) # r**2 = x**2 + y**2 assert (R2.r**2 - R2.x**2 - R2.y**2).rcall(point_r) == 0 assert trigsimp( (R2.r**2 - R2.x**2 - R2.y**2).rcall(point_p) ) == 0 assert trigsimp(R2.e_r(R2.x**2 + R2.y**2).rcall(point_p).doit()) == 2*r0 # polar->rect->polar == Id a, b = symbols('a b', positive=True) m = Matrix([[a], [b]]) #TODO assert m == R2_r.transform(R2_p, R2_p.transform(R2_r, [a, b])).applyfunc(simplify) assert m == R2_p.transform(R2_r, R2_r.transform(R2_p, m)).applyfunc(simplify) # deprecated method with warns_deprecated_sympy(): assert m == R2_p.coord_tuple_transform_to( R2_r, R2_r.coord_tuple_transform_to(R2_p, m)).applyfunc(simplify) def test_R3(): a, b, c = symbols('a b c', positive=True) m = Matrix([[a], [b], [c]]) assert m == R3_c.transform(R3_r, R3_r.transform(R3_c, m)).applyfunc(simplify) #TODO assert m == R3_r.transform(R3_c, R3_c.transform(R3_r, m)).applyfunc(simplify) assert m == R3_s.transform( R3_r, R3_r.transform(R3_s, m)).applyfunc(simplify) #TODO assert m == R3_r.transform(R3_s, R3_s.transform(R3_r, m)).applyfunc(simplify) assert m == R3_s.transform( R3_c, R3_c.transform(R3_s, m)).applyfunc(simplify) #TODO assert m == R3_c.transform(R3_s, R3_s.transform(R3_c, m)).applyfunc(simplify) with warns_deprecated_sympy(): assert m == R3_c.coord_tuple_transform_to( R3_r, R3_r.coord_tuple_transform_to(R3_c, m)).applyfunc(simplify) #TODO assert m == R3_r.coord_tuple_transform_to(R3_c, R3_c.coord_tuple_transform_to(R3_r, m)).applyfunc(simplify) assert m == R3_s.coord_tuple_transform_to( R3_r, R3_r.coord_tuple_transform_to(R3_s, m)).applyfunc(simplify) #TODO assert m == R3_r.coord_tuple_transform_to(R3_s, R3_s.coord_tuple_transform_to(R3_r, m)).applyfunc(simplify) assert m == R3_s.coord_tuple_transform_to( R3_c, R3_c.coord_tuple_transform_to(R3_s, m)).applyfunc(simplify) #TODO assert m == R3_c.coord_tuple_transform_to(R3_s, R3_s.coord_tuple_transform_to(R3_c, m)).applyfunc(simplify) def test_CoordinateSymbol(): x, y = R2_r.symbols r, theta = R2_p.symbols assert y.rewrite(R2_p) == r*sin(theta) def test_point(): x, y = symbols('x, y') p = R2_r.point([x, y]) assert p.free_symbols == {x, y} assert p.coords(R2_r) == p.coords() == Matrix([x, y]) assert p.coords(R2_p) == Matrix([sqrt(x**2 + y**2), atan2(y, x)]) def test_commutator(): assert Commutator(R2.e_x, R2.e_y) == 0 assert Commutator(R2.x*R2.e_x, R2.x*R2.e_x) == 0 assert Commutator(R2.x*R2.e_x, R2.x*R2.e_y) == R2.x*R2.e_y c = Commutator(R2.e_x, R2.e_r) assert c(R2.x) == R2.y*(R2.x**2 + R2.y**2)**(-1)*sin(R2.theta) def test_differential(): xdy = R2.x*R2.dy dxdy = Differential(xdy) assert xdy.rcall(None) == xdy assert dxdy(R2.e_x, R2.e_y) == 1 assert dxdy(R2.e_x, R2.x*R2.e_y) == R2.x assert Differential(dxdy) == 0 def test_products(): assert TensorProduct( R2.dx, R2.dy)(R2.e_x, R2.e_y) == R2.dx(R2.e_x)*R2.dy(R2.e_y) == 1 assert TensorProduct(R2.dx, R2.dy)(None, R2.e_y) == R2.dx assert TensorProduct(R2.dx, R2.dy)(R2.e_x, None) == R2.dy assert TensorProduct(R2.dx, R2.dy)(R2.e_x) == R2.dy assert TensorProduct(R2.x, R2.dx) == R2.x*R2.dx assert TensorProduct( R2.e_x, R2.e_y)(R2.x, R2.y) == R2.e_x(R2.x) * R2.e_y(R2.y) == 1 assert TensorProduct(R2.e_x, R2.e_y)(None, R2.y) == R2.e_x assert TensorProduct(R2.e_x, R2.e_y)(R2.x, None) == R2.e_y assert TensorProduct(R2.e_x, R2.e_y)(R2.x) == R2.e_y assert TensorProduct(R2.x, R2.e_x) == R2.x * R2.e_x assert TensorProduct( R2.dx, R2.e_y)(R2.e_x, R2.y) == R2.dx(R2.e_x) * R2.e_y(R2.y) == 1 assert TensorProduct(R2.dx, R2.e_y)(None, R2.y) == R2.dx assert TensorProduct(R2.dx, R2.e_y)(R2.e_x, None) == R2.e_y assert TensorProduct(R2.dx, R2.e_y)(R2.e_x) == R2.e_y assert TensorProduct(R2.x, R2.e_x) == R2.x * R2.e_x assert TensorProduct( R2.e_x, R2.dy)(R2.x, R2.e_y) == R2.e_x(R2.x) * R2.dy(R2.e_y) == 1 assert TensorProduct(R2.e_x, R2.dy)(None, R2.e_y) == R2.e_x assert TensorProduct(R2.e_x, R2.dy)(R2.x, None) == R2.dy assert TensorProduct(R2.e_x, R2.dy)(R2.x) == R2.dy assert TensorProduct(R2.e_y,R2.e_x)(R2.x**2 + R2.y**2,R2.x**2 + R2.y**2) == 4*R2.x*R2.y assert WedgeProduct(R2.dx, R2.dy)(R2.e_x, R2.e_y) == 1 assert WedgeProduct(R2.e_x, R2.e_y)(R2.x, R2.y) == 1 def test_lie_derivative(): assert LieDerivative(R2.e_x, R2.y) == R2.e_x(R2.y) == 0 assert LieDerivative(R2.e_x, R2.x) == R2.e_x(R2.x) == 1 assert LieDerivative(R2.e_x, R2.e_x) == Commutator(R2.e_x, R2.e_x) == 0 assert LieDerivative(R2.e_x, R2.e_r) == Commutator(R2.e_x, R2.e_r) assert LieDerivative(R2.e_x + R2.e_y, R2.x) == 1 assert LieDerivative( R2.e_x, TensorProduct(R2.dx, R2.dy))(R2.e_x, R2.e_y) == 0 @nocache_fail def test_covar_deriv(): ch = metric_to_Christoffel_2nd(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) cvd = BaseCovarDerivativeOp(R2_r, 0, ch) assert cvd(R2.x) == 1 # This line fails if the cache is disabled: assert cvd(R2.x*R2.e_x) == R2.e_x cvd = CovarDerivativeOp(R2.x*R2.e_x, ch) assert cvd(R2.x) == R2.x assert cvd(R2.x*R2.e_x) == R2.x*R2.e_x def test_intcurve_diffequ(): t = symbols('t') start_point = R2_r.point([1, 0]) vector_field = -R2.y*R2.e_x + R2.x*R2.e_y equations, init_cond = intcurve_diffequ(vector_field, t, start_point) assert str(equations) == '[f_1(t) + Derivative(f_0(t), t), -f_0(t) + Derivative(f_1(t), t)]' assert str(init_cond) == '[f_0(0) - 1, f_1(0)]' equations, init_cond = intcurve_diffequ(vector_field, t, start_point, R2_p) assert str( equations) == '[Derivative(f_0(t), t), Derivative(f_1(t), t) - 1]' assert str(init_cond) == '[f_0(0) - 1, f_1(0)]' def test_helpers_and_coordinate_dependent(): one_form = R2.dr + R2.dx two_form = Differential(R2.x*R2.dr + R2.r*R2.dx) three_form = Differential( R2.y*two_form) + Differential(R2.x*Differential(R2.r*R2.dr)) metric = TensorProduct(R2.dx, R2.dx) + TensorProduct(R2.dy, R2.dy) metric_ambig = TensorProduct(R2.dx, R2.dx) + TensorProduct(R2.dr, R2.dr) misform_a = TensorProduct(R2.dr, R2.dr) + R2.dr misform_b = R2.dr**4 misform_c = R2.dx*R2.dy twoform_not_sym = TensorProduct(R2.dx, R2.dx) + TensorProduct(R2.dx, R2.dy) twoform_not_TP = WedgeProduct(R2.dx, R2.dy) one_vector = R2.e_x + R2.e_y two_vector = TensorProduct(R2.e_x, R2.e_y) three_vector = TensorProduct(R2.e_x, R2.e_y, R2.e_x) two_wp = WedgeProduct(R2.e_x,R2.e_y) assert covariant_order(one_form) == 1 assert covariant_order(two_form) == 2 assert covariant_order(three_form) == 3 assert covariant_order(two_form + metric) == 2 assert covariant_order(two_form + metric_ambig) == 2 assert covariant_order(two_form + twoform_not_sym) == 2 assert covariant_order(two_form + twoform_not_TP) == 2 assert contravariant_order(one_vector) == 1 assert contravariant_order(two_vector) == 2 assert contravariant_order(three_vector) == 3 assert contravariant_order(two_vector + two_wp) == 2 raises(ValueError, lambda: covariant_order(misform_a)) raises(ValueError, lambda: covariant_order(misform_b)) raises(ValueError, lambda: covariant_order(misform_c)) assert twoform_to_matrix(metric) == Matrix([[1, 0], [0, 1]]) assert twoform_to_matrix(twoform_not_sym) == Matrix([[1, 0], [1, 0]]) assert twoform_to_matrix(twoform_not_TP) == Matrix([[0, -1], [1, 0]]) raises(ValueError, lambda: twoform_to_matrix(one_form)) raises(ValueError, lambda: twoform_to_matrix(three_form)) raises(ValueError, lambda: twoform_to_matrix(metric_ambig)) raises(ValueError, lambda: metric_to_Christoffel_1st(twoform_not_sym)) raises(ValueError, lambda: metric_to_Christoffel_2nd(twoform_not_sym)) raises(ValueError, lambda: metric_to_Riemann_components(twoform_not_sym)) raises(ValueError, lambda: metric_to_Ricci_components(twoform_not_sym)) def test_correct_arguments(): raises(ValueError, lambda: R2.e_x(R2.e_x)) raises(ValueError, lambda: R2.e_x(R2.dx)) raises(ValueError, lambda: Commutator(R2.e_x, R2.x)) raises(ValueError, lambda: Commutator(R2.dx, R2.e_x)) raises(ValueError, lambda: Differential(Differential(R2.e_x))) raises(ValueError, lambda: R2.dx(R2.x)) raises(ValueError, lambda: LieDerivative(R2.dx, R2.dx)) raises(ValueError, lambda: LieDerivative(R2.x, R2.dx)) raises(ValueError, lambda: CovarDerivativeOp(R2.dx, [])) raises(ValueError, lambda: CovarDerivativeOp(R2.x, [])) a = Symbol('a') raises(ValueError, lambda: intcurve_series(R2.dx, a, R2_r.point([1, 2]))) raises(ValueError, lambda: intcurve_series(R2.x, a, R2_r.point([1, 2]))) raises(ValueError, lambda: intcurve_diffequ(R2.dx, a, R2_r.point([1, 2]))) raises(ValueError, lambda: intcurve_diffequ(R2.x, a, R2_r.point([1, 2]))) raises(ValueError, lambda: contravariant_order(R2.e_x + R2.dx)) raises(ValueError, lambda: covariant_order(R2.e_x + R2.dx)) raises(ValueError, lambda: contravariant_order(R2.e_x*R2.e_y)) raises(ValueError, lambda: covariant_order(R2.dx*R2.dy)) def test_simplify(): x, y = R2_r.coord_functions() dx, dy = R2_r.base_oneforms() ex, ey = R2_r.base_vectors() assert simplify(x) == x assert simplify(x*y) == x*y assert simplify(dx*dy) == dx*dy assert simplify(ex*ey) == ex*ey assert ((1-x)*dx)/(1-x)**2 == dx/(1-x) def test_issue_17917(): X = R2.x*R2.e_x - R2.y*R2.e_y Y = (R2.x**2 + R2.y**2)*R2.e_x - R2.x*R2.y*R2.e_y assert LieDerivative(X, Y).expand() == ( R2.x**2*R2.e_x - 3*R2.y**2*R2.e_x - R2.x*R2.y*R2.e_y)
738c5027f6c14b8c6b323de97f1d4cb37a02dbf2f0b89b8d617359c6cf9c546f
r''' unit test describing the hyperbolic half-plane with the Poincare metric. This is a basic model of hyperbolic geometry on the (positive) half-space {(x,y) \in R^2 | y > 0} with the Riemannian metric ds^2 = (dx^2 + dy^2)/y^2 It has constant negative scalar curvature = -2 https://en.wikipedia.org/wiki/Poincare_half-plane_model ''' from sympy.matrices.dense import diag from sympy.diffgeom import (twoform_to_matrix, metric_to_Christoffel_1st, metric_to_Christoffel_2nd, metric_to_Riemann_components, metric_to_Ricci_components) import sympy.diffgeom.rn from sympy.tensor.array import ImmutableDenseNDimArray def test_H2(): TP = sympy.diffgeom.TensorProduct R2 = sympy.diffgeom.rn.R2 y = R2.y dy = R2.dy dx = R2.dx g = (TP(dx, dx) + TP(dy, dy))*y**(-2) automat = twoform_to_matrix(g) mat = diag(y**(-2), y**(-2)) assert mat == automat gamma1 = metric_to_Christoffel_1st(g) assert gamma1[0, 0, 0] == 0 assert gamma1[0, 0, 1] == -y**(-3) assert gamma1[0, 1, 0] == -y**(-3) assert gamma1[0, 1, 1] == 0 assert gamma1[1, 1, 1] == -y**(-3) assert gamma1[1, 1, 0] == 0 assert gamma1[1, 0, 1] == 0 assert gamma1[1, 0, 0] == y**(-3) gamma2 = metric_to_Christoffel_2nd(g) assert gamma2[0, 0, 0] == 0 assert gamma2[0, 0, 1] == -y**(-1) assert gamma2[0, 1, 0] == -y**(-1) assert gamma2[0, 1, 1] == 0 assert gamma2[1, 1, 1] == -y**(-1) assert gamma2[1, 1, 0] == 0 assert gamma2[1, 0, 1] == 0 assert gamma2[1, 0, 0] == y**(-1) Rm = metric_to_Riemann_components(g) assert Rm[0, 0, 0, 0] == 0 assert Rm[0, 0, 0, 1] == 0 assert Rm[0, 0, 1, 0] == 0 assert Rm[0, 0, 1, 1] == 0 assert Rm[0, 1, 0, 0] == 0 assert Rm[0, 1, 0, 1] == -y**(-2) assert Rm[0, 1, 1, 0] == y**(-2) assert Rm[0, 1, 1, 1] == 0 assert Rm[1, 0, 0, 0] == 0 assert Rm[1, 0, 0, 1] == y**(-2) assert Rm[1, 0, 1, 0] == -y**(-2) assert Rm[1, 0, 1, 1] == 0 assert Rm[1, 1, 0, 0] == 0 assert Rm[1, 1, 0, 1] == 0 assert Rm[1, 1, 1, 0] == 0 assert Rm[1, 1, 1, 1] == 0 Ric = metric_to_Ricci_components(g) assert Ric[0, 0] == -y**(-2) assert Ric[0, 1] == 0 assert Ric[1, 0] == 0 assert Ric[0, 0] == -y**(-2) assert Ric == ImmutableDenseNDimArray([-y**(-2), 0, 0, -y**(-2)], (2, 2)) ## scalar curvature is -2 #TODO - it would be nice to have index contraction built-in R = (Ric[0, 0] + Ric[1, 1])*y**2 assert R == -2 ## Gauss curvature is -1 assert R/2 == -1
af6d3a9fc60cd03d6f14fd2f76351a011ed04699945b0f159aa48c17187c154f
import os import tempfile from sympy.core.symbol import (Symbol, symbols) from sympy.codegen.ast import ( Assignment, Print, Declaration, FunctionDefinition, Return, real, FunctionCall, Variable, Element, integer ) from sympy.codegen.fnodes import ( allocatable, ArrayConstructor, isign, dsign, cmplx, kind, literal_dp, Program, Module, use, Subroutine, dimension, assumed_extent, ImpliedDoLoop, intent_out, size, Do, SubroutineCall, sum_, array, bind_C ) from sympy.codegen.futils import render_as_module from sympy.core.expr import unchanged from sympy.external import import_module from sympy.printing.codeprinter import fcode from sympy.utilities._compilation import has_fortran, compile_run_strings, compile_link_import_strings from sympy.utilities._compilation.util import may_xfail from sympy.testing.pytest import skip, XFAIL cython = import_module('cython') np = import_module('numpy') def test_size(): x = Symbol('x', real=True) sx = size(x) assert fcode(sx, source_format='free') == 'size(x)' @may_xfail def test_size_assumed_shape(): if not has_fortran(): skip("No fortran compiler found.") a = Symbol('a', real=True) body = [Return((sum_(a**2)/size(a))**.5)] arr = array(a, dim=[':'], intent='in') fd = FunctionDefinition(real, 'rms', [arr], body) render_as_module([fd], 'mod_rms') (stdout, stderr), info = compile_run_strings([ ('rms.f90', render_as_module([fd], 'mod_rms')), ('main.f90', ( 'program myprog\n' 'use mod_rms, only: rms\n' 'real*8, dimension(4), parameter :: x = [4, 2, 2, 2]\n' 'print *, dsqrt(7d0) - rms(x)\n' 'end program\n' )) ], clean=True) assert '0.00000' in stdout assert stderr == '' assert info['exit_status'] == os.EX_OK @XFAIL # https://github.com/sympy/sympy/issues/20265 @may_xfail def test_ImpliedDoLoop(): if not has_fortran(): skip("No fortran compiler found.") a, i = symbols('a i', integer=True) idl = ImpliedDoLoop(i**3, i, -3, 3, 2) ac = ArrayConstructor([-28, idl, 28]) a = array(a, dim=[':'], attrs=[allocatable]) prog = Program('idlprog', [ a.as_Declaration(), Assignment(a, ac), Print([a]) ]) fsrc = fcode(prog, standard=2003, source_format='free') (stdout, stderr), info = compile_run_strings([('main.f90', fsrc)], clean=True) for numstr in '-28 -27 -1 1 27 28'.split(): assert numstr in stdout assert stderr == '' assert info['exit_status'] == os.EX_OK @may_xfail def test_Program(): x = Symbol('x', real=True) vx = Variable.deduced(x, 42) decl = Declaration(vx) prnt = Print([x, x+1]) prog = Program('foo', [decl, prnt]) if not has_fortran(): skip("No fortran compiler found.") (stdout, stderr), info = compile_run_strings([('main.f90', fcode(prog, standard=90))], clean=True) assert '42' in stdout assert '43' in stdout assert stderr == '' assert info['exit_status'] == os.EX_OK @may_xfail def test_Module(): x = Symbol('x', real=True) v_x = Variable.deduced(x) sq = FunctionDefinition(real, 'sqr', [v_x], [Return(x**2)]) mod_sq = Module('mod_sq', [], [sq]) sq_call = FunctionCall('sqr', [42.]) prg_sq = Program('foobar', [ use('mod_sq', only=['sqr']), Print(['"Square of 42 = "', sq_call]) ]) if not has_fortran(): skip("No fortran compiler found.") (stdout, stderr), info = compile_run_strings([ ('mod_sq.f90', fcode(mod_sq, standard=90)), ('main.f90', fcode(prg_sq, standard=90)) ], clean=True) assert '42' in stdout assert str(42**2) in stdout assert stderr == '' @XFAIL # https://github.com/sympy/sympy/issues/20265 @may_xfail def test_Subroutine(): # Code to generate the subroutine in the example from # http://www.fortran90.org/src/best-practices.html#arrays r = Symbol('r', real=True) i = Symbol('i', integer=True) v_r = Variable.deduced(r, attrs=(dimension(assumed_extent), intent_out)) v_i = Variable.deduced(i) v_n = Variable('n', integer) do_loop = Do([ Assignment(Element(r, [i]), literal_dp(1)/i**2) ], i, 1, v_n) sub = Subroutine("f", [v_r], [ Declaration(v_n), Declaration(v_i), Assignment(v_n, size(r)), do_loop ]) x = Symbol('x', real=True) v_x3 = Variable.deduced(x, attrs=[dimension(3)]) mod = Module('mymod', definitions=[sub]) prog = Program('foo', [ use(mod, only=[sub]), Declaration(v_x3), SubroutineCall(sub, [v_x3]), Print([sum_(v_x3), v_x3]) ]) if not has_fortran(): skip("No fortran compiler found.") (stdout, stderr), info = compile_run_strings([ ('a.f90', fcode(mod, standard=90)), ('b.f90', fcode(prog, standard=90)) ], clean=True) ref = [1.0/i**2 for i in range(1, 4)] assert str(sum(ref))[:-3] in stdout for _ in ref: assert str(_)[:-3] in stdout assert stderr == '' def test_isign(): x = Symbol('x', integer=True) assert unchanged(isign, 1, x) assert fcode(isign(1, x), standard=95, source_format='free') == 'isign(1, x)' def test_dsign(): x = Symbol('x') assert unchanged(dsign, 1, x) assert fcode(dsign(literal_dp(1), x), standard=95, source_format='free') == 'dsign(1d0, x)' def test_cmplx(): x = Symbol('x') assert unchanged(cmplx, 1, x) def test_kind(): x = Symbol('x') assert unchanged(kind, x) def test_literal_dp(): assert fcode(literal_dp(0), source_format='free') == '0d0' @may_xfail def test_bind_C(): if not has_fortran(): skip("No fortran compiler found.") if not cython: skip("Cython not found.") if not np: skip("NumPy not found.") a = Symbol('a', real=True) s = Symbol('s', integer=True) body = [Return((sum_(a**2)/s)**.5)] arr = array(a, dim=[s], intent='in') fd = FunctionDefinition(real, 'rms', [arr, s], body, attrs=[bind_C('rms')]) f_mod = render_as_module([fd], 'mod_rms') with tempfile.TemporaryDirectory() as folder: mod, info = compile_link_import_strings([ ('rms.f90', f_mod), ('_rms.pyx', ( "#cython: language_level={}\n".format("3") + "cdef extern double rms(double*, int*)\n" "def py_rms(double[::1] x):\n" " cdef int s = x.size\n" " return rms(&x[0], &s)\n")) ], build_dir=folder) assert abs(mod.py_rms(np.array([2., 4., 2., 2.])) - 7**0.5) < 1e-14
a9fc0f8530396266917d7078a50bfb93e016fa17458071baef90ba5c958573fd
from itertools import product from sympy.core.symbol import symbols from sympy.functions.elementary.trigonometric import cos from sympy.core.numbers import pi from sympy.codegen.scipy_nodes import cosm1 x, y, z = symbols('x y z') def test_cosm1(): cm1_xy = cosm1(x*y) ref_xy = cos(x*y) - 1 for wrt, deriv_order in product([x, y, z], range(0, 3)): assert ( cm1_xy.diff(wrt, deriv_order) - ref_xy.diff(wrt, deriv_order) ).rewrite(cos).simplify() == 0 expr_minus2 = cosm1(pi) assert expr_minus2.rewrite(cos) == -2 assert cosm1(3.14).simplify() == cosm1(3.14) # cannot simplify with 3.14
499a4e5336a16ff6c939c783d032dd99e8b0fa3377ece3e67f94d1a757724603
import math from sympy.core.symbol import symbols from sympy.functions.elementary.exponential import exp from sympy.codegen.rewriting import optimize from sympy.codegen.approximations import SumApprox, SeriesApprox def test_SumApprox_trivial(): x = symbols('x') expr1 = 1 + x sum_approx = SumApprox(bounds={x: (-1e-20, 1e-20)}, reltol=1e-16) apx1 = optimize(expr1, [sum_approx]) assert apx1 - 1 == 0 def test_SumApprox_monotone_terms(): x, y, z = symbols('x y z') expr1 = exp(z)*(x**2 + y**2 + 1) bnds1 = {x: (0, 1e-3), y: (100, 1000)} sum_approx_m2 = SumApprox(bounds=bnds1, reltol=1e-2) sum_approx_m5 = SumApprox(bounds=bnds1, reltol=1e-5) sum_approx_m11 = SumApprox(bounds=bnds1, reltol=1e-11) assert (optimize(expr1, [sum_approx_m2])/exp(z) - (y**2)).simplify() == 0 assert (optimize(expr1, [sum_approx_m5])/exp(z) - (y**2 + 1)).simplify() == 0 assert (optimize(expr1, [sum_approx_m11])/exp(z) - (y**2 + 1 + x**2)).simplify() == 0 def test_SeriesApprox_trivial(): x, z = symbols('x z') for factor in [1, exp(z)]: x = symbols('x') expr1 = exp(x)*factor bnds1 = {x: (-1, 1)} series_approx_50 = SeriesApprox(bounds=bnds1, reltol=0.50) series_approx_10 = SeriesApprox(bounds=bnds1, reltol=0.10) series_approx_05 = SeriesApprox(bounds=bnds1, reltol=0.05) c = (bnds1[x][1] + bnds1[x][0])/2 # 0.0 f0 = math.exp(c) # 1.0 ref_50 = f0 + x + x**2/2 ref_10 = f0 + x + x**2/2 + x**3/6 ref_05 = f0 + x + x**2/2 + x**3/6 + x**4/24 res_50 = optimize(expr1, [series_approx_50]) res_10 = optimize(expr1, [series_approx_10]) res_05 = optimize(expr1, [series_approx_05]) assert (res_50/factor - ref_50).simplify() == 0 assert (res_10/factor - ref_10).simplify() == 0 assert (res_05/factor - ref_05).simplify() == 0 max_ord3 = SeriesApprox(bounds=bnds1, reltol=0.05, max_order=3) assert optimize(expr1, [max_ord3]) == expr1
8dc6e1c964d1c0c3f84661d373ecab9f9c355bd69da585e400fc5182a03589e4
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 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'
bdec849ea7957ed22c80a9531bfc4c98259c58f2c379257f3a90047a485fbe94
import tempfile from sympy.core.numbers import pi from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.trigonometric import (cos, sin, sinc) from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.assumptions import assuming, Q from sympy.external import import_module from sympy.printing.codeprinter import ccode from sympy.codegen.matrix_nodes import MatrixSolve from sympy.codegen.cfunctions import log2, exp2, expm1, log1p from sympy.codegen.numpy_nodes import logaddexp, logaddexp2 from sympy.codegen.scipy_nodes import cosm1 from sympy.codegen.rewriting import ( optimize, cosm1_opt, log2_opt, exp2_opt, expm1_opt, log1p_opt, optims_c99, create_expand_pow_optimization, matinv_opt, logaddexp_opt, logaddexp2_opt, optims_numpy, sinc_opts, FuncMinusOneOptim ) from sympy.testing.pytest import XFAIL, skip from sympy.utilities._compilation import compile_link_import_strings, has_c from sympy.utilities._compilation.util import may_xfail cython = import_module('cython') def test_log2_opt(): x = Symbol('x') expr1 = 7*log(3*x + 5)/(log(2)) opt1 = optimize(expr1, [log2_opt]) assert opt1 == 7*log2(3*x + 5) assert opt1.rewrite(log) == expr1 expr2 = 3*log(5*x + 7)/(13*log(2)) opt2 = optimize(expr2, [log2_opt]) assert opt2 == 3*log2(5*x + 7)/13 assert opt2.rewrite(log) == expr2 expr3 = log(x)/log(2) opt3 = optimize(expr3, [log2_opt]) assert opt3 == log2(x) assert opt3.rewrite(log) == expr3 expr4 = log(x)/log(2) + log(x+1) opt4 = optimize(expr4, [log2_opt]) assert opt4 == log2(x) + log(2)*log2(x+1) assert opt4.rewrite(log) == expr4 expr5 = log(17) opt5 = optimize(expr5, [log2_opt]) assert opt5 == expr5 expr6 = log(x + 3)/log(2) opt6 = optimize(expr6, [log2_opt]) assert str(opt6) == 'log2(x + 3)' assert opt6.rewrite(log) == expr6 def test_exp2_opt(): x = Symbol('x') expr1 = 1 + 2**x opt1 = optimize(expr1, [exp2_opt]) assert opt1 == 1 + exp2(x) assert opt1.rewrite(Pow) == expr1 expr2 = 1 + 3**x assert expr2 == optimize(expr2, [exp2_opt]) def test_expm1_opt(): x = Symbol('x') expr1 = exp(x) - 1 opt1 = optimize(expr1, [expm1_opt]) assert expm1(x) - opt1 == 0 assert opt1.rewrite(exp) == expr1 expr2 = 3*exp(x) - 3 opt2 = optimize(expr2, [expm1_opt]) assert 3*expm1(x) == opt2 assert opt2.rewrite(exp) == expr2 expr3 = 3*exp(x) - 5 opt3 = optimize(expr3, [expm1_opt]) assert 3*expm1(x) - 2 == opt3 assert opt3.rewrite(exp) == expr3 expm1_opt_non_opportunistic = FuncMinusOneOptim(exp, expm1, opportunistic=False) assert expr3 == optimize(expr3, [expm1_opt_non_opportunistic]) assert opt1 == optimize(expr1, [expm1_opt_non_opportunistic]) assert opt2 == optimize(expr2, [expm1_opt_non_opportunistic]) expr4 = 3*exp(x) + log(x) - 3 opt4 = optimize(expr4, [expm1_opt]) assert 3*expm1(x) + log(x) == opt4 assert opt4.rewrite(exp) == expr4 expr5 = 3*exp(2*x) - 3 opt5 = optimize(expr5, [expm1_opt]) assert 3*expm1(2*x) == opt5 assert opt5.rewrite(exp) == expr5 expr6 = (2*exp(x) + 1)/(exp(x) + 1) + 1 opt6 = optimize(expr6, [expm1_opt]) assert opt6.count_ops() <= expr6.count_ops() def ev(e): return e.subs(x, 3).evalf() assert abs(ev(expr6) - ev(opt6)) < 1e-15 y = Symbol('y') expr7 = (2*exp(x) - 1)/(1 - exp(y)) - 1/(1-exp(y)) opt7 = optimize(expr7, [expm1_opt]) assert -2*expm1(x)/expm1(y) == opt7 assert (opt7.rewrite(exp) - expr7).factor() == 0 expr8 = (1+exp(x))**2 - 4 opt8 = optimize(expr8, [expm1_opt]) tgt8a = (exp(x) + 3)*expm1(x) tgt8b = 2*expm1(x) + expm1(2*x) # Both tgt8a & tgt8b seem to give full precision (~16 digits for double) # for x=1e-7 (compare with expr8 which only achieves ~8 significant digits). # If we can show that either tgt8a or tgt8b is preferable, we can # change this test to ensure the preferable version is returned. assert (tgt8a - tgt8b).rewrite(exp).factor() == 0 assert opt8 in (tgt8a, tgt8b) assert (opt8.rewrite(exp) - expr8).factor() == 0 expr9 = sin(expr8) opt9 = optimize(expr9, [expm1_opt]) tgt9a = sin(tgt8a) tgt9b = sin(tgt8b) assert opt9 in (tgt9a, tgt9b) assert (opt9.rewrite(exp) - expr9.rewrite(exp)).factor().is_zero def test_expm1_two_exp_terms(): x, y = map(Symbol, 'x y'.split()) expr1 = exp(x) + exp(y) - 2 opt1 = optimize(expr1, [expm1_opt]) assert opt1 == expm1(x) + expm1(y) def test_cosm1_opt(): x = Symbol('x') expr1 = cos(x) - 1 opt1 = optimize(expr1, [cosm1_opt]) assert cosm1(x) - opt1 == 0 assert opt1.rewrite(cos) == expr1 expr2 = 3*cos(x) - 3 opt2 = optimize(expr2, [cosm1_opt]) assert 3*cosm1(x) == opt2 assert opt2.rewrite(cos) == expr2 expr3 = 3*cos(x) - 5 opt3 = optimize(expr3, [cosm1_opt]) assert 3*cosm1(x) - 2 == opt3 assert opt3.rewrite(cos) == expr3 cosm1_opt_non_opportunistic = FuncMinusOneOptim(cos, cosm1, opportunistic=False) assert expr3 == optimize(expr3, [cosm1_opt_non_opportunistic]) assert opt1 == optimize(expr1, [cosm1_opt_non_opportunistic]) assert opt2 == optimize(expr2, [cosm1_opt_non_opportunistic]) expr4 = 3*cos(x) + log(x) - 3 opt4 = optimize(expr4, [cosm1_opt]) assert 3*cosm1(x) + log(x) == opt4 assert opt4.rewrite(cos) == expr4 expr5 = 3*cos(2*x) - 3 opt5 = optimize(expr5, [cosm1_opt]) assert 3*cosm1(2*x) == opt5 assert opt5.rewrite(cos) == expr5 expr6 = 2 - 2*cos(x) opt6 = optimize(expr6, [cosm1_opt]) assert -2*cosm1(x) == opt6 assert opt6.rewrite(cos) == expr6 def test_cosm1_two_cos_terms(): x, y = map(Symbol, 'x y'.split()) expr1 = cos(x) + cos(y) - 2 opt1 = optimize(expr1, [cosm1_opt]) assert opt1 == cosm1(x) + cosm1(y) def test_expm1_cosm1_mixed(): x = Symbol('x') expr1 = exp(x) + cos(x) - 2 opt1 = optimize(expr1, [expm1_opt, cosm1_opt]) assert opt1 == cosm1(x) + expm1(x) def test_log1p_opt(): x = Symbol('x') expr1 = log(x + 1) opt1 = optimize(expr1, [log1p_opt]) assert log1p(x) - opt1 == 0 assert opt1.rewrite(log) == expr1 expr2 = log(3*x + 3) opt2 = optimize(expr2, [log1p_opt]) assert log1p(x) + log(3) == opt2 assert (opt2.rewrite(log) - expr2).simplify() == 0 expr3 = log(2*x + 1) opt3 = optimize(expr3, [log1p_opt]) assert log1p(2*x) - opt3 == 0 assert opt3.rewrite(log) == expr3 expr4 = log(x+3) opt4 = optimize(expr4, [log1p_opt]) assert str(opt4) == 'log(x + 3)' def test_optims_c99(): x = Symbol('x') expr1 = 2**x + log(x)/log(2) + log(x + 1) + exp(x) - 1 opt1 = optimize(expr1, optims_c99).simplify() assert opt1 == exp2(x) + log2(x) + log1p(x) + expm1(x) assert opt1.rewrite(exp).rewrite(log).rewrite(Pow) == expr1 expr2 = log(x)/log(2) + log(x + 1) opt2 = optimize(expr2, optims_c99) assert opt2 == log2(x) + log1p(x) assert opt2.rewrite(log) == expr2 expr3 = log(x)/log(2) + log(17*x + 17) opt3 = optimize(expr3, optims_c99) delta3 = opt3 - (log2(x) + log(17) + log1p(x)) assert delta3 == 0 assert (opt3.rewrite(log) - expr3).simplify() == 0 expr4 = 2**x + 3*log(5*x + 7)/(13*log(2)) + 11*exp(x) - 11 + log(17*x + 17) opt4 = optimize(expr4, optims_c99).simplify() delta4 = opt4 - (exp2(x) + 3*log2(5*x + 7)/13 + 11*expm1(x) + log(17) + log1p(x)) assert delta4 == 0 assert (opt4.rewrite(exp).rewrite(log).rewrite(Pow) - expr4).simplify() == 0 expr5 = 3*exp(2*x) - 3 opt5 = optimize(expr5, optims_c99) delta5 = opt5 - 3*expm1(2*x) assert delta5 == 0 assert opt5.rewrite(exp) == expr5 expr6 = exp(2*x) - 3 opt6 = optimize(expr6, optims_c99) assert opt6 in (expm1(2*x) - 2, expr6) # expm1(2*x) - 2 is not better or worse expr7 = log(3*x + 3) opt7 = optimize(expr7, optims_c99) delta7 = opt7 - (log(3) + log1p(x)) assert delta7 == 0 assert (opt7.rewrite(log) - expr7).simplify() == 0 expr8 = log(2*x + 3) opt8 = optimize(expr8, optims_c99) assert opt8 == expr8 def test_create_expand_pow_optimization(): cc = lambda x: ccode( optimize(x, [create_expand_pow_optimization(4)])) x = Symbol('x') assert cc(x**4) == 'x*x*x*x' assert cc(x**4 + x**2) == 'x*x + x*x*x*x' assert cc(x**5 + x**4) == 'pow(x, 5) + x*x*x*x' assert cc(sin(x)**4) == 'pow(sin(x), 4)' # gh issue 15335 assert cc(x**(-4)) == '1.0/(x*x*x*x)' assert cc(x**(-5)) == 'pow(x, -5)' assert cc(-x**4) == '-(x*x*x*x)' assert cc(x**4 - x**2) == '-(x*x) + x*x*x*x' i = Symbol('i', integer=True) assert cc(x**i - x**2) == 'pow(x, i) - (x*x)' y = Symbol('y', real=True) assert cc(Abs(exp(y**4))) == "exp(y*y*y*y)" # gh issue 20753 cc2 = lambda x: ccode(optimize(x, [create_expand_pow_optimization( 4, base_req=lambda b: b.is_Function)])) assert cc2(x**3 + sin(x)**3) == "pow(x, 3) + sin(x)*sin(x)*sin(x)" def test_matsolve(): n = Symbol('n', integer=True) A = MatrixSymbol('A', n, n) x = MatrixSymbol('x', n, 1) with assuming(Q.fullrank(A)): assert optimize(A**(-1) * x, [matinv_opt]) == MatrixSolve(A, x) assert optimize(A**(-1) * x + x, [matinv_opt]) == MatrixSolve(A, x) + x def test_logaddexp_opt(): x, y = map(Symbol, 'x y'.split()) expr1 = log(exp(x) + exp(y)) opt1 = optimize(expr1, [logaddexp_opt]) assert logaddexp(x, y) - opt1 == 0 assert logaddexp(y, x) - opt1 == 0 assert opt1.rewrite(log) == expr1 def test_logaddexp2_opt(): x, y = map(Symbol, 'x y'.split()) expr1 = log(2**x + 2**y)/log(2) opt1 = optimize(expr1, [logaddexp2_opt]) assert logaddexp2(x, y) - opt1 == 0 assert logaddexp2(y, x) - opt1 == 0 assert opt1.rewrite(log) == expr1 def test_sinc_opts(): def check(d): for k, v in d.items(): assert optimize(k, sinc_opts) == v x = Symbol('x') check({ sin(x)/x : sinc(x), sin(2*x)/(2*x) : sinc(2*x), sin(3*x)/x : 3*sinc(3*x), x*sin(x) : x*sin(x) }) y = Symbol('y') check({ sin(x*y)/(x*y) : sinc(x*y), y*sin(x/y)/x : sinc(x/y), sin(sin(x))/sin(x) : sinc(sin(x)), sin(3*sin(x))/sin(x) : 3*sinc(3*sin(x)), sin(x)/y : sin(x)/y }) def test_optims_numpy(): def check(d): for k, v in d.items(): assert optimize(k, optims_numpy) == v x = Symbol('x') check({ sin(2*x)/(2*x) + exp(2*x) - 1: sinc(2*x) + expm1(2*x), log(x+3)/log(2) + log(x**2 + 1): log1p(x**2) + log2(x+3) }) @XFAIL # room for improvement, ideally this test case should pass. def test_optims_numpy_TODO(): def check(d): for k, v in d.items(): assert optimize(k, optims_numpy) == v x, y = map(Symbol, 'x y'.split()) check({ log(x*y)*sin(x*y)*log(x*y+1)/(log(2)*x*y): log2(x*y)*sinc(x*y)*log1p(x*y), exp(x*sin(y)/y) - 1: expm1(x*sinc(y)) }) @may_xfail def test_compiled_ccode_with_rewriting(): if not cython: skip("cython not installed.") if not has_c(): skip("No C compiler found.") x = Symbol('x') about_two = 2**(58/S(117))*3**(97/S(117))*5**(4/S(39))*7**(92/S(117))/S(30)*pi # about_two: 1.999999999999581826 unchanged = 2*exp(x) - about_two xval = S(10)**-11 ref = unchanged.subs(x, xval).n(19) # 2.0418173913673213e-11 rewritten = optimize(2*exp(x) - about_two, [expm1_opt]) # Unfortunately, we need to call ``.n()`` on our expressions before we hand them # to ``ccode``, and we need to request a large number of significant digits. # In this test, results converged for double precision when the following number # of significant digits were chosen: NUMBER_OF_DIGITS = 25 # TODO: this should ideally be automatically handled. func_c = ''' #include <math.h> double func_unchanged(double x) { return %(unchanged)s; } double func_rewritten(double x) { return %(rewritten)s; } ''' % dict(unchanged=ccode(unchanged.n(NUMBER_OF_DIGITS)), rewritten=ccode(rewritten.n(NUMBER_OF_DIGITS))) func_pyx = ''' #cython: language_level=3 cdef extern double func_unchanged(double) cdef extern double func_rewritten(double) def py_unchanged(x): return func_unchanged(x) def py_rewritten(x): return func_rewritten(x) ''' with tempfile.TemporaryDirectory() as folder: mod, info = compile_link_import_strings( [('func.c', func_c), ('_func.pyx', func_pyx)], build_dir=folder, compile_kwargs=dict(std='c99') ) err_rewritten = abs(mod.py_rewritten(1e-11) - ref) err_unchanged = abs(mod.py_unchanged(1e-11) - ref) assert 1e-27 < err_rewritten < 1e-25 # highly accurate. assert 1e-19 < err_unchanged < 1e-16 # quite poor. # Tolerances used above were determined as follows: # >>> no_opt = unchanged.subs(x, xval.evalf()).evalf() # >>> with_opt = rewritten.n(25).subs(x, 1e-11).evalf() # >>> with_opt - ref, no_opt - ref # (1.1536301877952077e-26, 1.6547074214222335e-18)
7dabbccc0accecf084240348d5d91954d48ce298c23174bb61f94d20c3643297
from itertools import product from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.functions.elementary.exponential import (exp, log) from sympy.printing.repr import srepr from sympy.codegen.numpy_nodes import logaddexp, logaddexp2 x, y, z = symbols('x y z') def test_logaddexp(): lae_xy = logaddexp(x, y) ref_xy = log(exp(x) + exp(y)) for wrt, deriv_order in product([x, y, z], range(0, 3)): assert ( lae_xy.diff(wrt, deriv_order) - ref_xy.diff(wrt, deriv_order) ).rewrite(log).simplify() == 0 one_third_e = 1*exp(1)/3 two_thirds_e = 2*exp(1)/3 logThirdE = log(one_third_e) logTwoThirdsE = log(two_thirds_e) lae_sum_to_e = logaddexp(logThirdE, logTwoThirdsE) assert lae_sum_to_e.rewrite(log) == 1 assert lae_sum_to_e.simplify() == 1 was = logaddexp(2, 3) assert srepr(was) == srepr(was.simplify()) # cannot simplify with 2, 3 def test_logaddexp2(): lae2_xy = logaddexp2(x, y) ref2_xy = log(2**x + 2**y)/log(2) for wrt, deriv_order in product([x, y, z], range(0, 3)): assert ( lae2_xy.diff(wrt, deriv_order) - ref2_xy.diff(wrt, deriv_order) ).rewrite(log).cancel() == 0 def lb(x): return log(x)/log(2) two_thirds = S.One*2/3 four_thirds = 2*two_thirds lbTwoThirds = lb(two_thirds) lbFourThirds = lb(four_thirds) lae2_sum_to_2 = logaddexp2(lbTwoThirds, lbFourThirds) assert lae2_sum_to_2.rewrite(log) == 1 assert lae2_sum_to_2.simplify() == 1 was = logaddexp2(x, y) assert srepr(was) == srepr(was.simplify()) # cannot simplify with x, y
eb60609cd8852e8b4265715046600ce0b4cf9cb5c2bd12535c7078b48be64f01
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, finite=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, finite=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, finite=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, finite=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
1aca35f0a2b34b003ed401c2e794a01cf01f1f51ab19408668de9047b8ae10ed
from sympy.core.symbol import symbols from sympy.codegen.pynodes import List def test_List(): l = List(2, 3, 4) assert l == List(2, 3, 4) assert str(l) == "[2, 3, 4]" x, y, z = symbols('x y z') l = List(x**2,y**3,z**4) # contrary to python's built-in list, we can call e.g. "replace" on List. m = l.replace(lambda arg: arg.is_Pow and arg.exp>2, lambda p: p.base-p.exp) assert m == [x**2, y-3, z-4]
80d2d21aabf4882bed727e327178bfb34fc405d044e5d8f9ef6e5225118c4ed9
""" 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[a.func](*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
922efc1d21cdbc3e90f4b2ec37c98d84a759949c8983792b91c45e219f865028
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[arg.func] return pred(*arg.args) return super().__call__(arg)
f2dc4228fe79a651a40ab3bdc613b534c032c34e6e160f5b9cfb382a90ef72ac
from sympy.assumptions import Predicate from sympy.multipledispatch import Dispatcher class SquarePredicate(Predicate): """ Square matrix predicate. Explanation =========== ``Q.square(x)`` is true iff ``x`` is a square matrix. A square matrix is a matrix with the same number of rows and columns. Examples ======== >>> from sympy import Q, ask, MatrixSymbol, ZeroMatrix, Identity >>> X = MatrixSymbol('X', 2, 2) >>> Y = MatrixSymbol('X', 2, 3) >>> ask(Q.square(X)) True >>> ask(Q.square(Y)) False >>> ask(Q.square(ZeroMatrix(3, 3))) True >>> ask(Q.square(Identity(3))) True References ========== .. [1] https://en.wikipedia.org/wiki/Square_matrix """ name = 'square' handler = Dispatcher("SquareHandler", doc="Handler for Q.square.") class SymmetricPredicate(Predicate): """ Symmetric matrix predicate. Explanation =========== ``Q.symmetric(x)`` is true iff ``x`` is a square matrix and is equal to its transpose. Every square diagonal matrix is a symmetric matrix. Examples ======== >>> from sympy import Q, ask, MatrixSymbol >>> X = MatrixSymbol('X', 2, 2) >>> Y = MatrixSymbol('Y', 2, 3) >>> Z = MatrixSymbol('Z', 2, 2) >>> ask(Q.symmetric(X*Z), Q.symmetric(X) & Q.symmetric(Z)) True >>> ask(Q.symmetric(X + Z), Q.symmetric(X) & Q.symmetric(Z)) True >>> ask(Q.symmetric(Y)) False References ========== .. [1] https://en.wikipedia.org/wiki/Symmetric_matrix """ # TODO: Add handlers to make these keys work with # actual matrices and add more examples in the docstring. name = 'symmetric' handler = Dispatcher("SymmetricHandler", doc="Handler for Q.symmetric.") class InvertiblePredicate(Predicate): """ Invertible matrix predicate. Explanation =========== ``Q.invertible(x)`` is true iff ``x`` is an invertible matrix. A square matrix is called invertible only if its determinant is 0. Examples ======== >>> from sympy import Q, ask, MatrixSymbol >>> X = MatrixSymbol('X', 2, 2) >>> Y = MatrixSymbol('Y', 2, 3) >>> Z = MatrixSymbol('Z', 2, 2) >>> ask(Q.invertible(X*Y), Q.invertible(X)) False >>> ask(Q.invertible(X*Z), Q.invertible(X) & Q.invertible(Z)) True >>> ask(Q.invertible(X), Q.fullrank(X) & Q.square(X)) True References ========== .. [1] https://en.wikipedia.org/wiki/Invertible_matrix """ name = 'invertible' handler = Dispatcher("InvertibleHandler", doc="Handler for Q.invertible.") class OrthogonalPredicate(Predicate): """ Orthogonal matrix predicate. Explanation =========== ``Q.orthogonal(x)`` is true iff ``x`` is an orthogonal matrix. A square matrix ``M`` is an orthogonal matrix if it satisfies ``M^TM = MM^T = I`` where ``M^T`` is the transpose matrix of ``M`` and ``I`` is an identity matrix. Note that an orthogonal matrix is necessarily invertible. Examples ======== >>> from sympy import Q, ask, MatrixSymbol, Identity >>> X = MatrixSymbol('X', 2, 2) >>> Y = MatrixSymbol('Y', 2, 3) >>> Z = MatrixSymbol('Z', 2, 2) >>> ask(Q.orthogonal(Y)) False >>> ask(Q.orthogonal(X*Z*X), Q.orthogonal(X) & Q.orthogonal(Z)) True >>> ask(Q.orthogonal(Identity(3))) True >>> ask(Q.invertible(X), Q.orthogonal(X)) True References ========== .. [1] https://en.wikipedia.org/wiki/Orthogonal_matrix """ name = 'orthogonal' handler = Dispatcher("OrthogonalHandler", doc="Handler for key 'orthogonal'.") class UnitaryPredicate(Predicate): """ Unitary matrix predicate. Explanation =========== ``Q.unitary(x)`` is true iff ``x`` is a unitary matrix. Unitary matrix is an analogue to orthogonal matrix. A square matrix ``M`` with complex elements is unitary if :math:``M^TM = MM^T= I`` where :math:``M^T`` is the conjugate transpose matrix of ``M``. Examples ======== >>> from sympy import Q, ask, MatrixSymbol, Identity >>> X = MatrixSymbol('X', 2, 2) >>> Y = MatrixSymbol('Y', 2, 3) >>> Z = MatrixSymbol('Z', 2, 2) >>> ask(Q.unitary(Y)) False >>> ask(Q.unitary(X*Z*X), Q.unitary(X) & Q.unitary(Z)) True >>> ask(Q.unitary(Identity(3))) True References ========== .. [1] https://en.wikipedia.org/wiki/Unitary_matrix """ name = 'unitary' handler = Dispatcher("UnitaryHandler", doc="Handler for key 'unitary'.") class FullRankPredicate(Predicate): """ Fullrank matrix predicate. Explanation =========== ``Q.fullrank(x)`` is true iff ``x`` is a full rank matrix. A matrix is full rank if all rows and columns of the matrix are linearly independent. A square matrix is full rank iff its determinant is nonzero. Examples ======== >>> from sympy import Q, ask, MatrixSymbol, ZeroMatrix, Identity >>> X = MatrixSymbol('X', 2, 2) >>> ask(Q.fullrank(X.T), Q.fullrank(X)) True >>> ask(Q.fullrank(ZeroMatrix(3, 3))) False >>> ask(Q.fullrank(Identity(3))) True """ name = 'fullrank' handler = Dispatcher("FullRankHandler", doc="Handler for key 'fullrank'.") class PositiveDefinitePredicate(Predicate): r""" Positive definite matrix predicate. Explanation =========== If $M$ is a :math:`n \times n` symmetric real matrix, it is said to be positive definite if :math:`Z^TMZ` is positive for every non-zero column vector $Z$ of $n$ real numbers. Examples ======== >>> from sympy import Q, ask, MatrixSymbol, Identity >>> X = MatrixSymbol('X', 2, 2) >>> Y = MatrixSymbol('Y', 2, 3) >>> Z = MatrixSymbol('Z', 2, 2) >>> ask(Q.positive_definite(Y)) False >>> ask(Q.positive_definite(Identity(3))) True >>> ask(Q.positive_definite(X + Z), Q.positive_definite(X) & ... Q.positive_definite(Z)) True References ========== .. [1] https://en.wikipedia.org/wiki/Positive-definite_matrix """ name = "positive_definite" handler = Dispatcher("PositiveDefiniteHandler", doc="Handler for key 'positive_definite'.") class UpperTriangularPredicate(Predicate): """ Upper triangular matrix predicate. Explanation =========== A matrix $M$ is called upper triangular matrix if :math:`M_{ij}=0` for :math:`i<j`. Examples ======== >>> from sympy import Q, ask, ZeroMatrix, Identity >>> ask(Q.upper_triangular(Identity(3))) True >>> ask(Q.upper_triangular(ZeroMatrix(3, 3))) True References ========== .. [1] http://mathworld.wolfram.com/UpperTriangularMatrix.html """ name = "upper_triangular" handler = Dispatcher("UpperTriangularHandler", doc="Handler for key 'upper_triangular'.") class LowerTriangularPredicate(Predicate): """ Lower triangular matrix predicate. Explanation =========== A matrix $M$ is called lower triangular matrix if :math:`M_{ij}=0` for :math:`i>j`. Examples ======== >>> from sympy import Q, ask, ZeroMatrix, Identity >>> ask(Q.lower_triangular(Identity(3))) True >>> ask(Q.lower_triangular(ZeroMatrix(3, 3))) True References ========== .. [1] http://mathworld.wolfram.com/LowerTriangularMatrix.html """ name = "lower_triangular" handler = Dispatcher("LowerTriangularHandler", doc="Handler for key 'lower_triangular'.") class DiagonalPredicate(Predicate): """ Diagonal matrix predicate. Explanation =========== ``Q.diagonal(x)`` is true iff ``x`` is a diagonal matrix. A diagonal matrix is a matrix in which the entries outside the main diagonal are all zero. Examples ======== >>> from sympy import Q, ask, MatrixSymbol, ZeroMatrix >>> X = MatrixSymbol('X', 2, 2) >>> ask(Q.diagonal(ZeroMatrix(3, 3))) True >>> ask(Q.diagonal(X), Q.lower_triangular(X) & ... Q.upper_triangular(X)) True References ========== .. [1] https://en.wikipedia.org/wiki/Diagonal_matrix """ name = "diagonal" handler = Dispatcher("DiagonalHandler", doc="Handler for key 'diagonal'.") class IntegerElementsPredicate(Predicate): """ Integer elements matrix predicate. Explanation =========== ``Q.integer_elements(x)`` is true iff all the elements of ``x`` are integers. Examples ======== >>> from sympy import Q, ask, MatrixSymbol >>> X = MatrixSymbol('X', 4, 4) >>> ask(Q.integer(X[1, 2]), Q.integer_elements(X)) True """ name = "integer_elements" handler = Dispatcher("IntegerElementsHandler", doc="Handler for key 'integer_elements'.") class RealElementsPredicate(Predicate): """ Real elements matrix predicate. Explanation =========== ``Q.real_elements(x)`` is true iff all the elements of ``x`` are real numbers. Examples ======== >>> from sympy import Q, ask, MatrixSymbol >>> X = MatrixSymbol('X', 4, 4) >>> ask(Q.real(X[1, 2]), Q.real_elements(X)) True """ name = "real_elements" handler = Dispatcher("RealElementsHandler", doc="Handler for key 'real_elements'.") class ComplexElementsPredicate(Predicate): """ Complex elements matrix predicate. Explanation =========== ``Q.complex_elements(x)`` is true iff all the elements of ``x`` are complex numbers. Examples ======== >>> from sympy import Q, ask, MatrixSymbol >>> X = MatrixSymbol('X', 4, 4) >>> ask(Q.complex(X[1, 2]), Q.complex_elements(X)) True >>> ask(Q.complex_elements(X), Q.integer_elements(X)) True """ name = "complex_elements" handler = Dispatcher("ComplexElementsHandler", doc="Handler for key 'complex_elements'.") class SingularPredicate(Predicate): """ Singular matrix predicate. A matrix is singular iff the value of its determinant is 0. Examples ======== >>> from sympy import Q, ask, MatrixSymbol >>> X = MatrixSymbol('X', 4, 4) >>> ask(Q.singular(X), Q.invertible(X)) False >>> ask(Q.singular(X), ~Q.invertible(X)) True References ========== .. [1] http://mathworld.wolfram.com/SingularMatrix.html """ name = "singular" handler = Dispatcher("SingularHandler", doc="Predicate fore key 'singular'.") class NormalPredicate(Predicate): """ Normal matrix predicate. A matrix is normal if it commutes with its conjugate transpose. Examples ======== >>> from sympy import Q, ask, MatrixSymbol >>> X = MatrixSymbol('X', 4, 4) >>> ask(Q.normal(X), Q.unitary(X)) True References ========== .. [1] https://en.wikipedia.org/wiki/Normal_matrix """ name = "normal" handler = Dispatcher("NormalHandler", doc="Predicate fore key 'normal'.") class TriangularPredicate(Predicate): """ Triangular matrix predicate. Explanation =========== ``Q.triangular(X)`` is true if ``X`` is one that is either lower triangular or upper triangular. Examples ======== >>> from sympy import Q, ask, MatrixSymbol >>> X = MatrixSymbol('X', 4, 4) >>> ask(Q.triangular(X), Q.upper_triangular(X)) True >>> ask(Q.triangular(X), Q.lower_triangular(X)) True References ========== .. [1] https://en.wikipedia.org/wiki/Triangular_matrix """ name = "triangular" handler = Dispatcher("TriangularHandler", doc="Predicate fore key 'triangular'.") class UnitTriangularPredicate(Predicate): """ Unit triangular matrix predicate. Explanation =========== A unit triangular matrix is a triangular matrix with 1s on the diagonal. Examples ======== >>> from sympy import Q, ask, MatrixSymbol >>> X = MatrixSymbol('X', 4, 4) >>> ask(Q.triangular(X), Q.unit_triangular(X)) True """ name = "unit_triangular" handler = Dispatcher("UnitTriangularHandler", doc="Predicate fore key 'unit_triangular'.")
d1c4ee0fdd0213f5d249fe797ff63ed344e7c675dce94c4c54d227c528294f88
from sympy.assumptions import Predicate from sympy.multipledispatch import Dispatcher class IntegerPredicate(Predicate): """ Integer predicate. Explanation =========== ``Q.integer(x)`` is true iff ``x`` belongs to the set of integer numbers. Examples ======== >>> from sympy import Q, ask, S >>> ask(Q.integer(5)) True >>> ask(Q.integer(S(1)/2)) False References ========== .. [1] https://en.wikipedia.org/wiki/Integer """ name = 'integer' handler = Dispatcher( "IntegerHandler", doc=("Handler for Q.integer.\n\n" "Test that an expression belongs to the field of integer numbers.") ) class RationalPredicate(Predicate): """ Rational number predicate. Explanation =========== ``Q.rational(x)`` is true iff ``x`` belongs to the set of rational numbers. Examples ======== >>> from sympy import ask, Q, pi, S >>> ask(Q.rational(0)) True >>> ask(Q.rational(S(1)/2)) True >>> ask(Q.rational(pi)) False References ========== .. [1] https://en.wikipedia.org/wiki/Rational_number """ name = 'rational' handler = Dispatcher( "RationalHandler", doc=("Handler for Q.rational.\n\n" "Test that an expression belongs to the field of rational numbers.") ) class IrrationalPredicate(Predicate): """ Irrational number predicate. Explanation =========== ``Q.irrational(x)`` is true iff ``x`` is any real number that cannot be expressed as a ratio of integers. Examples ======== >>> from sympy import ask, Q, pi, S, I >>> ask(Q.irrational(0)) False >>> ask(Q.irrational(S(1)/2)) False >>> ask(Q.irrational(pi)) True >>> ask(Q.irrational(I)) False References ========== .. [1] https://en.wikipedia.org/wiki/Irrational_number """ name = 'irrational' handler = Dispatcher( "IrrationalHandler", doc=("Handler for Q.irrational.\n\n" "Test that an expression is irrational numbers.") ) class RealPredicate(Predicate): r""" Real number predicate. Explanation =========== ``Q.real(x)`` is true iff ``x`` is a real number, i.e., it is in the interval `(-\infty, \infty)`. Note that, in particular the infinities are not real. Use ``Q.extended_real`` if you want to consider those as well. A few important facts about reals: - Every real number is positive, negative, or zero. Furthermore, because these sets are pairwise disjoint, each real number is exactly one of those three. - Every real number is also complex. - Every real number is finite. - Every real number is either rational or irrational. - Every real number is either algebraic or transcendental. - The facts ``Q.negative``, ``Q.zero``, ``Q.positive``, ``Q.nonnegative``, ``Q.nonpositive``, ``Q.nonzero``, ``Q.integer``, ``Q.rational``, and ``Q.irrational`` all imply ``Q.real``, as do all facts that imply those facts. - The facts ``Q.algebraic``, and ``Q.transcendental`` do not imply ``Q.real``; they imply ``Q.complex``. An algebraic or transcendental number may or may not be real. - The "non" facts (i.e., ``Q.nonnegative``, ``Q.nonzero``, ``Q.nonpositive`` and ``Q.noninteger``) are not equivalent to not the fact, but rather, not the fact *and* ``Q.real``. For example, ``Q.nonnegative`` means ``~Q.negative & Q.real``. So for example, ``I`` is not nonnegative, nonzero, or nonpositive. Examples ======== >>> from sympy import Q, ask, symbols >>> x = symbols('x') >>> ask(Q.real(x), Q.positive(x)) True >>> ask(Q.real(0)) True References ========== .. [1] https://en.wikipedia.org/wiki/Real_number """ name = 'real' handler = Dispatcher( "RealHandler", doc=("Handler for Q.real.\n\n" "Test that an expression belongs to the field of real numbers.") ) class ExtendedRealPredicate(Predicate): r""" Extended real predicate. Explanation =========== ``Q.extended_real(x)`` is true iff ``x`` is a real number or `\{-\infty, \infty\}`. See documentation of ``Q.real`` for more information about related facts. Examples ======== >>> from sympy import ask, Q, oo, I >>> ask(Q.extended_real(1)) True >>> ask(Q.extended_real(I)) False >>> ask(Q.extended_real(oo)) True """ name = 'extended_real' handler = Dispatcher( "ExtendedRealHandler", doc=("Handler for Q.extended_real.\n\n" "Test that an expression belongs to the field of extended real\n" "numbers, that is real numbers union {Infinity, -Infinity}.") ) class HermitianPredicate(Predicate): """ Hermitian predicate. Explanation =========== ``ask(Q.hermitian(x))`` is true iff ``x`` belongs to the set of Hermitian operators. References ========== .. [1] http://mathworld.wolfram.com/HermitianOperator.html """ # TODO: Add examples name = 'hermitian' handler = Dispatcher( "HermitianHandler", doc=("Handler for Q.hermitian.\n\n" "Test that an expression belongs to the field of Hermitian operators.") ) class ComplexPredicate(Predicate): """ Complex number predicate. Explanation =========== ``Q.complex(x)`` is true iff ``x`` belongs to the set of complex numbers. Note that every complex number is finite. Examples ======== >>> from sympy import Q, Symbol, ask, I, oo >>> x = Symbol('x') >>> ask(Q.complex(0)) True >>> ask(Q.complex(2 + 3*I)) True >>> ask(Q.complex(oo)) False References ========== .. [1] https://en.wikipedia.org/wiki/Complex_number """ name = 'complex' handler = Dispatcher( "ComplexHandler", doc=("Handler for Q.complex.\n\n" "Test that an expression belongs to the field of complex numbers.") ) class ImaginaryPredicate(Predicate): """ Imaginary number predicate. Explanation =========== ``Q.imaginary(x)`` is true iff ``x`` can be written as a real number multiplied by the imaginary unit ``I``. Please note that ``0`` is not considered to be an imaginary number. Examples ======== >>> from sympy import Q, ask, I >>> ask(Q.imaginary(3*I)) True >>> ask(Q.imaginary(2 + 3*I)) False >>> ask(Q.imaginary(0)) False References ========== .. [1] https://en.wikipedia.org/wiki/Imaginary_number """ name = 'imaginary' handler = Dispatcher( "ImaginaryHandler", doc=("Handler for Q.imaginary.\n\n" "Test that an expression belongs to the field of imaginary numbers,\n" "that is, numbers in the form x*I, where x is real.") ) class AntihermitianPredicate(Predicate): """ Antihermitian predicate. Explanation =========== ``Q.antihermitian(x)`` is true iff ``x`` belongs to the field of antihermitian operators, i.e., operators in the form ``x*I``, where ``x`` is Hermitian. References ========== .. [1] http://mathworld.wolfram.com/HermitianOperator.html """ # TODO: Add examples name = 'antihermitian' handler = Dispatcher( "AntiHermitianHandler", doc=("Handler for Q.antihermitian.\n\n" "Test that an expression belongs to the field of anti-Hermitian\n" "operators, that is, operators in the form x*I, where x is Hermitian.") ) class AlgebraicPredicate(Predicate): r""" Algebraic number predicate. Explanation =========== ``Q.algebraic(x)`` is true iff ``x`` belongs to the set of algebraic numbers. ``x`` is algebraic if there is some polynomial in ``p(x)\in \mathbb\{Q\}[x]`` such that ``p(x) = 0``. Examples ======== >>> from sympy import ask, Q, sqrt, I, pi >>> ask(Q.algebraic(sqrt(2))) True >>> ask(Q.algebraic(I)) True >>> ask(Q.algebraic(pi)) False References ========== .. [1] https://en.wikipedia.org/wiki/Algebraic_number """ name = 'algebraic' AlgebraicHandler = Dispatcher( "AlgebraicHandler", doc="""Handler for Q.algebraic key.""" ) class TranscendentalPredicate(Predicate): """ Transcedental number predicate. Explanation =========== ``Q.transcendental(x)`` is true iff ``x`` belongs to the set of transcendental numbers. A transcendental number is a real or complex number that is not algebraic. """ # TODO: Add examples name = 'transcendental' handler = Dispatcher( "Transcendental", doc="""Handler for Q.transcendental key.""" )
627bb641a5c1274e08eae9a3fa1a6ffcebbc50648c6a0ee279d7b925dd3ab0f7
""" Handlers for keys related to number theory: prime, even, odd, etc. """ from sympy.assumptions import Q, ask from sympy.core import Add, Basic, Expr, Float, Mul, Pow, S from sympy.core.numbers import (ImaginaryUnit, Infinity, Integer, NaN, NegativeInfinity, NumberSymbol, Rational) from sympy.functions import Abs, im, re from sympy.ntheory import isprime from sympy.multipledispatch import MDNotImplementedError from ..predicates.ntheory import (PrimePredicate, CompositePredicate, EvenPredicate, OddPredicate) # PrimePredicate def _PrimePredicate_number(expr, assumptions): # helper method exact = not expr.atoms(Float) try: i = int(expr.round()) if (expr - i).equals(0) is False: raise TypeError except TypeError: return False if exact: return isprime(i) # when not exact, we won't give a True or False # since the number represents an approximate value @PrimePredicate.register(Expr) # type: ignore def _(expr, assumptions): ret = expr.is_prime if ret is None: raise MDNotImplementedError return ret @PrimePredicate.register(Basic) # type: ignore def _(expr, assumptions): if expr.is_number: return _PrimePredicate_number(expr, assumptions) @PrimePredicate.register(Mul) # type: ignore def _(expr, assumptions): if expr.is_number: return _PrimePredicate_number(expr, assumptions) for arg in expr.args: if not ask(Q.integer(arg), assumptions): return None for arg in expr.args: if arg.is_number and arg.is_composite: return False @PrimePredicate.register(Pow) # type: ignore def _(expr, assumptions): """ Integer**Integer -> !Prime """ if expr.is_number: return _PrimePredicate_number(expr, assumptions) if ask(Q.integer(expr.exp), assumptions) and \ ask(Q.integer(expr.base), assumptions): return False @PrimePredicate.register(Integer) # type: ignore def _(expr, assumptions): return isprime(expr) @PrimePredicate.register_many(Rational, Infinity, NegativeInfinity, ImaginaryUnit) # type: ignore def _(expr, assumptions): return False @PrimePredicate.register(Float) # type: ignore def _(expr, assumptions): return _PrimePredicate_number(expr, assumptions) @PrimePredicate.register(NumberSymbol) # type: ignore def _(expr, assumptions): return _PrimePredicate_number(expr, assumptions) @PrimePredicate.register(NaN) # type: ignore def _(expr, assumptions): return None # CompositePredicate @CompositePredicate.register(Expr) # type: ignore def _(expr, assumptions): ret = expr.is_composite if ret is None: raise MDNotImplementedError return ret @CompositePredicate.register(Basic) # type: ignore def _(expr, assumptions): _positive = ask(Q.positive(expr), assumptions) if _positive: _integer = ask(Q.integer(expr), assumptions) if _integer: _prime = ask(Q.prime(expr), assumptions) if _prime is None: return # Positive integer which is not prime is not # necessarily composite if expr.equals(1): return False return not _prime else: return _integer else: return _positive # EvenPredicate def _EvenPredicate_number(expr, assumptions): # helper method try: i = int(expr.round()) if not (expr - i).equals(0): raise TypeError except TypeError: return False if isinstance(expr, (float, Float)): return False return i % 2 == 0 @EvenPredicate.register(Expr) # type: ignore def _(expr, assumptions): ret = expr.is_even if ret is None: raise MDNotImplementedError return ret @EvenPredicate.register(Basic) # type: ignore def _(expr, assumptions): if expr.is_number: return _EvenPredicate_number(expr, assumptions) @EvenPredicate.register(Mul) # type: ignore def _(expr, assumptions): """ Even * Integer -> Even Even * Odd -> Even Integer * Odd -> ? Odd * Odd -> Odd Even * Even -> Even Integer * Integer -> Even if Integer + Integer = Odd otherwise -> ? """ if expr.is_number: return _EvenPredicate_number(expr, assumptions) even, odd, irrational, acc = False, 0, False, 1 for arg in expr.args: # check for all integers and at least one even if ask(Q.integer(arg), assumptions): if ask(Q.even(arg), assumptions): even = True elif ask(Q.odd(arg), assumptions): odd += 1 elif not even and acc != 1: if ask(Q.odd(acc + arg), assumptions): even = True elif ask(Q.irrational(arg), assumptions): # one irrational makes the result False # two makes it undefined if irrational: break irrational = True else: break acc = arg else: if irrational: return False if even: return True if odd == len(expr.args): return False @EvenPredicate.register(Add) # type: ignore def _(expr, assumptions): """ Even + Odd -> Odd Even + Even -> Even Odd + Odd -> Even """ if expr.is_number: return _EvenPredicate_number(expr, assumptions) _result = True for arg in expr.args: if ask(Q.even(arg), assumptions): pass elif ask(Q.odd(arg), assumptions): _result = not _result else: break else: return _result @EvenPredicate.register(Pow) # type: ignore def _(expr, assumptions): if expr.is_number: return _EvenPredicate_number(expr, assumptions) if ask(Q.integer(expr.exp), assumptions): if ask(Q.positive(expr.exp), assumptions): return ask(Q.even(expr.base), assumptions) elif ask(~Q.negative(expr.exp) & Q.odd(expr.base), assumptions): return False elif expr.base is S.NegativeOne: return False @EvenPredicate.register(Integer) # type: ignore def _(expr, assumptions): return not bool(expr.p & 1) @EvenPredicate.register_many(Rational, Infinity, NegativeInfinity, ImaginaryUnit) # type: ignore def _(expr, assumptions): return False @EvenPredicate.register(NumberSymbol) # type: ignore def _(expr, assumptions): return _EvenPredicate_number(expr, assumptions) @EvenPredicate.register(Abs) # type: ignore def _(expr, assumptions): if ask(Q.real(expr.args[0]), assumptions): return ask(Q.even(expr.args[0]), assumptions) @EvenPredicate.register(re) # type: ignore def _(expr, assumptions): if ask(Q.real(expr.args[0]), assumptions): return ask(Q.even(expr.args[0]), assumptions) @EvenPredicate.register(im) # type: ignore def _(expr, assumptions): if ask(Q.real(expr.args[0]), assumptions): return True @EvenPredicate.register(NaN) # type: ignore def _(expr, assumptions): return None # OddPredicate @OddPredicate.register(Expr) # type: ignore def _(expr, assumptions): ret = expr.is_odd if ret is None: raise MDNotImplementedError return ret @OddPredicate.register(Basic) # type: ignore def _(expr, assumptions): _integer = ask(Q.integer(expr), assumptions) if _integer: _even = ask(Q.even(expr), assumptions) if _even is None: return None return not _even return _integer
a6f3dc57fbac742f9ec458cd6941e6056ac467e7b0379e34d12c371bd6cee58a
""" This module contains query handlers responsible for calculus queries: infinitesimal, finite, etc. """ from sympy.assumptions import Q, ask from sympy.core import Add, Mul, Pow, Symbol from sympy.core.numbers import (NegativeInfinity, GoldenRatio, Infinity, Exp1, ComplexInfinity, ImaginaryUnit, NaN, Number, Pi, E, TribonacciConstant) from sympy.functions import cos, exp, log, sign, sin from sympy.logic.boolalg import conjuncts from ..predicates.calculus import (FinitePredicate, InfinitePredicate, PositiveInfinitePredicate, NegativeInfinitePredicate) # FinitePredicate @FinitePredicate.register(Symbol) # type: ignore def _(expr, assumptions): """ Handles Symbol. """ if expr.is_finite is not None: return expr.is_finite if Q.finite(expr) in conjuncts(assumptions): return True return None @FinitePredicate.register(Add) # type: ignore def _(expr, assumptions): """ Return True if expr is bounded, False if not and None if unknown. Truth Table: +-------+-----+-----------+-----------+ | | | | | | | B | U | ? | | | | | | +-------+-----+---+---+---+---+---+---+ | | | | | | | | | | | |'+'|'-'|'x'|'+'|'-'|'x'| | | | | | | | | | +-------+-----+---+---+---+---+---+---+ | | | | | | B | B | U | ? | | | | | | +---+---+-----+---+---+---+---+---+---+ | | | | | | | | | | | |'+'| | U | ? | ? | U | ? | ? | | | | | | | | | | | | +---+-----+---+---+---+---+---+---+ | | | | | | | | | | | U |'-'| | ? | U | ? | ? | U | ? | | | | | | | | | | | | +---+-----+---+---+---+---+---+---+ | | | | | | | |'x'| | ? | ? | | | | | | | +---+---+-----+---+---+---+---+---+---+ | | | | | | ? | | | ? | | | | | | +-------+-----+-----------+---+---+---+ * 'B' = Bounded * 'U' = Unbounded * '?' = unknown boundedness * '+' = positive sign * '-' = negative sign * 'x' = sign unknown * All Bounded -> True * 1 Unbounded and the rest Bounded -> False * >1 Unbounded, all with same known sign -> False * Any Unknown and unknown sign -> None * Else -> None When the signs are not the same you can have an undefined result as in oo - oo, hence 'bounded' is also undefined. """ sign = -1 # sign of unknown or infinite result = True for arg in expr.args: _bounded = ask(Q.finite(arg), assumptions) if _bounded: continue s = ask(Q.extended_positive(arg), assumptions) # if there has been more than one sign or if the sign of this arg # is None and Bounded is None or there was already # an unknown sign, return None if sign != -1 and s != sign or \ s is None and None in (_bounded, sign): return None else: sign = s # once False, do not change if result is not False: result = _bounded return result @FinitePredicate.register(Mul) # type: ignore def _(expr, assumptions): """ Return True if expr is bounded, False if not and None if unknown. Truth Table: +---+---+---+--------+ | | | | | | | B | U | ? | | | | | | +---+---+---+---+----+ | | | | | | | | | | s | /s | | | | | | | +---+---+---+---+----+ | | | | | | B | B | U | ? | | | | | | +---+---+---+---+----+ | | | | | | | U | | U | U | ? | | | | | | | +---+---+---+---+----+ | | | | | | ? | | | ? | | | | | | +---+---+---+---+----+ * B = Bounded * U = Unbounded * ? = unknown boundedness * s = signed (hence nonzero) * /s = not signed """ result = True for arg in expr.args: _bounded = ask(Q.finite(arg), assumptions) if _bounded: continue elif _bounded is None: if result is None: return None if ask(Q.extended_nonzero(arg), assumptions) is None: return None if result is not False: result = None else: result = False return result @FinitePredicate.register(Pow) # type: ignore def _(expr, assumptions): """ * Unbounded ** NonZero -> Unbounded * Bounded ** Bounded -> Bounded * Abs()<=1 ** Positive -> Bounded * Abs()>=1 ** Negative -> Bounded * Otherwise unknown """ if expr.base == E: return ask(Q.finite(expr.exp), assumptions) base_bounded = ask(Q.finite(expr.base), assumptions) exp_bounded = ask(Q.finite(expr.exp), assumptions) if base_bounded is None and exp_bounded is None: # Common Case return None if base_bounded is False and ask(Q.extended_nonzero(expr.exp), assumptions): return False if base_bounded and exp_bounded: return True if (abs(expr.base) <= 1) == True and ask(Q.extended_positive(expr.exp), assumptions): return True if (abs(expr.base) >= 1) == True and ask(Q.extended_negative(expr.exp), assumptions): return True if (abs(expr.base) >= 1) == True and exp_bounded is False: return False return None @FinitePredicate.register(exp) # type: ignore def _(expr, assumptions): return ask(Q.finite(expr.exp), assumptions) @FinitePredicate.register(log) # type: ignore def _(expr, assumptions): # After complex -> finite fact is registered to new assumption system, # querying Q.infinite may be removed. if ask(Q.infinite(expr.args[0]), assumptions): return False return ask(~Q.zero(expr.args[0]), assumptions) @FinitePredicate.register_many(cos, sin, Number, Pi, Exp1, GoldenRatio, # type: ignore TribonacciConstant, ImaginaryUnit, sign) def _(expr, assumptions): return True @FinitePredicate.register_many(ComplexInfinity, Infinity, NegativeInfinity) # type: ignore def _(expr, assumptions): return False @FinitePredicate.register(NaN) # type: ignore def _(expr, assumptions): return None # InfinitePredicate @InfinitePredicate.register_many(ComplexInfinity, Infinity, NegativeInfinity) # type: ignore def _(expr, assumptions): return True # PositiveInfinitePredicate @PositiveInfinitePredicate.register(Infinity) # type: ignore def _(expr, assumptions): return True @PositiveInfinitePredicate.register_many(NegativeInfinity, ComplexInfinity) # type: ignore def _(expr, assumptions): return False # NegativeInfinitePredicate @NegativeInfinitePredicate.register(NegativeInfinity) # type: ignore def _(expr, assumptions): return True @NegativeInfinitePredicate.register_many(Infinity, ComplexInfinity) # type: ignore def _(expr, assumptions): return False
f85d6fcb23e7779dbf12b9c78c73b3caa85983582eeeb7f431d3ec9e504ae762
""" This module defines base class for handlers and some core handlers: ``Q.commutative`` and ``Q.is_true``. """ from sympy.assumptions import Q, ask, AppliedPredicate from sympy.core import Basic, Symbol from sympy.core.logic import _fuzzy_group from sympy.core.numbers import NaN, Number from sympy.logic.boolalg import (And, BooleanTrue, BooleanFalse, conjuncts, Equivalent, Implies, Not, Or) from sympy.utilities.exceptions import SymPyDeprecationWarning from ..predicates.common import CommutativePredicate, IsTruePredicate class AskHandler: """Base class that all Ask Handlers must inherit.""" def __new__(cls, *args, **kwargs): SymPyDeprecationWarning( feature="AskHandler() class", useinstead="multipledispatch handler", issue=20873, deprecated_since_version="1.8" ).warn() return super().__new__(cls, *args, **kwargs) class CommonHandler(AskHandler): # Deprecated """Defines some useful methods common to most Handlers. """ @staticmethod def AlwaysTrue(expr, assumptions): return True @staticmethod def AlwaysFalse(expr, assumptions): return False @staticmethod def AlwaysNone(expr, assumptions): return None NaN = AlwaysFalse # CommutativePredicate @CommutativePredicate.register(Symbol) # type: ignore def _(expr, assumptions): """Objects are expected to be commutative unless otherwise stated""" assumps = conjuncts(assumptions) if expr.is_commutative is not None: return expr.is_commutative and not ~Q.commutative(expr) in assumps if Q.commutative(expr) in assumps: return True elif ~Q.commutative(expr) in assumps: return False return True @CommutativePredicate.register(Basic) # type: ignore def _(expr, assumptions): for arg in expr.args: if not ask(Q.commutative(arg), assumptions): return False return True @CommutativePredicate.register(Number) # type: ignore def _(expr, assumptions): return True @CommutativePredicate.register(NaN) # type: ignore def _(expr, assumptions): return True # IsTruePredicate @IsTruePredicate.register(bool) # type: ignore def _(expr, assumptions): return expr @IsTruePredicate.register(BooleanTrue) # type: ignore def _(expr, assumptions): return True @IsTruePredicate.register(BooleanFalse) # type: ignore def _(expr, assumptions): return False @IsTruePredicate.register(AppliedPredicate) # type: ignore def _(expr, assumptions): return ask(expr, assumptions) @IsTruePredicate.register(Not) # type: ignore def _(expr, assumptions): arg = expr.args[0] if arg.is_Symbol: # symbol used as abstract boolean object return None value = ask(arg, assumptions=assumptions) if value in (True, False): return not value else: return None @IsTruePredicate.register(Or) # type: ignore def _(expr, assumptions): result = False for arg in expr.args: p = ask(arg, assumptions=assumptions) if p is True: return True if p is None: result = None return result @IsTruePredicate.register(And) # type: ignore def _(expr, assumptions): result = True for arg in expr.args: p = ask(arg, assumptions=assumptions) if p is False: return False if p is None: result = None return result @IsTruePredicate.register(Implies) # type: ignore def _(expr, assumptions): p, q = expr.args return ask(~p | q, assumptions=assumptions) @IsTruePredicate.register(Equivalent) # type: ignore def _(expr, assumptions): p, q = expr.args pt = ask(p, assumptions=assumptions) if pt is None: return None qt = ask(q, assumptions=assumptions) if qt is None: return None return pt == qt #### Helper methods def test_closed_group(expr, assumptions, key): """ Test for membership in a group with respect to the current operation. """ return _fuzzy_group( (ask(key(a), assumptions) for a in expr.args), quick_exit=True)
8d018b79ad9c436e420638d93df6a8a7344a13fc8bf7d6302ce94ea9677119a9
""" This module contains query handlers responsible for Matrices queries: Square, Symmetric, Invertible etc. """ from sympy.logic.boolalg import conjuncts from sympy.assumptions import Q, ask from sympy.assumptions.handlers import test_closed_group from sympy.matrices import MatrixBase from sympy.matrices.expressions import (BlockMatrix, BlockDiagMatrix, Determinant, DiagMatrix, DiagonalMatrix, HadamardProduct, Identity, Inverse, MatAdd, MatMul, MatPow, MatrixExpr, MatrixSlice, MatrixSymbol, OneMatrix, Trace, Transpose, ZeroMatrix) from sympy.matrices.expressions.factorizations import Factorization from sympy.matrices.expressions.fourier import DFT from sympy.core.logic import fuzzy_and from sympy.utilities.iterables import sift from sympy.core import Basic from ..predicates.matrices import (SquarePredicate, SymmetricPredicate, InvertiblePredicate, OrthogonalPredicate, UnitaryPredicate, FullRankPredicate, PositiveDefinitePredicate, UpperTriangularPredicate, LowerTriangularPredicate, DiagonalPredicate, IntegerElementsPredicate, RealElementsPredicate, ComplexElementsPredicate) def _Factorization(predicate, expr, assumptions): if predicate in expr.predicates: return True # SquarePredicate @SquarePredicate.register(MatrixExpr) # type: ignore def _(expr, assumptions): return expr.shape[0] == expr.shape[1] # SymmetricPredicate @SymmetricPredicate.register(MatMul) # type: ignore def _(expr, assumptions): factor, mmul = expr.as_coeff_mmul() if all(ask(Q.symmetric(arg), assumptions) for arg in mmul.args): return True # TODO: implement sathandlers system for the matrices. # Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric). if ask(Q.diagonal(expr), assumptions): return True if len(mmul.args) >= 2 and mmul.args[0] == mmul.args[-1].T: if len(mmul.args) == 2: return True return ask(Q.symmetric(MatMul(*mmul.args[1:-1])), assumptions) @SymmetricPredicate.register(MatPow) # type: ignore def _(expr, assumptions): # only for integer powers base, exp = expr.args int_exp = ask(Q.integer(exp), assumptions) if not int_exp: return None non_negative = ask(~Q.negative(exp), assumptions) if (non_negative or non_negative == False and ask(Q.invertible(base), assumptions)): return ask(Q.symmetric(base), assumptions) return None @SymmetricPredicate.register(MatAdd) # type: ignore def _(expr, assumptions): return all(ask(Q.symmetric(arg), assumptions) for arg in expr.args) @SymmetricPredicate.register(MatrixSymbol) # type: ignore def _(expr, assumptions): if not expr.is_square: return False # TODO: implement sathandlers system for the matrices. # Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric). if ask(Q.diagonal(expr), assumptions): return True if Q.symmetric(expr) in conjuncts(assumptions): return True @SymmetricPredicate.register_many(OneMatrix, ZeroMatrix) # type: ignore def _(expr, assumptions): return ask(Q.square(expr), assumptions) @SymmetricPredicate.register_many(Inverse, Transpose) # type: ignore def _(expr, assumptions): return ask(Q.symmetric(expr.arg), assumptions) @SymmetricPredicate.register(MatrixSlice) # type: ignore def _(expr, assumptions): # TODO: implement sathandlers system for the matrices. # Now it duplicates the general fact: Implies(Q.diagonal, Q.symmetric). if ask(Q.diagonal(expr), assumptions): return True if not expr.on_diag: return None else: return ask(Q.symmetric(expr.parent), assumptions) @SymmetricPredicate.register(Identity) # type: ignore def _(expr, assumptions): return True # InvertiblePredicate @InvertiblePredicate.register(MatMul) # type: ignore def _(expr, assumptions): factor, mmul = expr.as_coeff_mmul() if all(ask(Q.invertible(arg), assumptions) for arg in mmul.args): return True if any(ask(Q.invertible(arg), assumptions) is False for arg in mmul.args): return False @InvertiblePredicate.register(MatPow) # type: ignore def _(expr, assumptions): # only for integer powers base, exp = expr.args int_exp = ask(Q.integer(exp), assumptions) if not int_exp: return None if exp.is_negative == False: return ask(Q.invertible(base), assumptions) return None @InvertiblePredicate.register(MatAdd) # type: ignore def _(expr, assumptions): return None @InvertiblePredicate.register(MatrixSymbol) # type: ignore def _(expr, assumptions): if not expr.is_square: return False if Q.invertible(expr) in conjuncts(assumptions): return True @InvertiblePredicate.register_many(Identity, Inverse) # type: ignore def _(expr, assumptions): return True @InvertiblePredicate.register(ZeroMatrix) # type: ignore def _(expr, assumptions): return False @InvertiblePredicate.register(OneMatrix) # type: ignore def _(expr, assumptions): return expr.shape[0] == 1 and expr.shape[1] == 1 @InvertiblePredicate.register(Transpose) # type: ignore def _(expr, assumptions): return ask(Q.invertible(expr.arg), assumptions) @InvertiblePredicate.register(MatrixSlice) # type: ignore def _(expr, assumptions): if not expr.on_diag: return None else: return ask(Q.invertible(expr.parent), assumptions) @InvertiblePredicate.register(MatrixBase) # type: ignore def _(expr, assumptions): if not expr.is_square: return False return expr.rank() == expr.rows @InvertiblePredicate.register(MatrixExpr) # type: ignore def _(expr, assumptions): if not expr.is_square: return False return None @InvertiblePredicate.register(BlockMatrix) # type: ignore def _(expr, assumptions): from sympy.matrices.expressions.blockmatrix import reblock_2x2 if not expr.is_square: return False if expr.blockshape == (1, 1): return ask(Q.invertible(expr.blocks[0, 0]), assumptions) expr = reblock_2x2(expr) if expr.blockshape == (2, 2): [[A, B], [C, D]] = expr.blocks.tolist() if ask(Q.invertible(A), assumptions) == True: invertible = ask(Q.invertible(D - C * A.I * B), assumptions) if invertible is not None: return invertible if ask(Q.invertible(B), assumptions) == True: invertible = ask(Q.invertible(C - D * B.I * A), assumptions) if invertible is not None: return invertible if ask(Q.invertible(C), assumptions) == True: invertible = ask(Q.invertible(B - A * C.I * D), assumptions) if invertible is not None: return invertible if ask(Q.invertible(D), assumptions) == True: invertible = ask(Q.invertible(A - B * D.I * C), assumptions) if invertible is not None: return invertible return None @InvertiblePredicate.register(BlockDiagMatrix) # type: ignore def _(expr, assumptions): if expr.rowblocksizes != expr.colblocksizes: return None return fuzzy_and([ask(Q.invertible(a), assumptions) for a in expr.diag]) # OrthogonalPredicate @OrthogonalPredicate.register(MatMul) # type: ignore def _(expr, assumptions): factor, mmul = expr.as_coeff_mmul() if (all(ask(Q.orthogonal(arg), assumptions) for arg in mmul.args) and factor == 1): return True if any(ask(Q.invertible(arg), assumptions) is False for arg in mmul.args): return False @OrthogonalPredicate.register(MatPow) # type: ignore def _(expr, assumptions): # only for integer powers base, exp = expr.args int_exp = ask(Q.integer(exp), assumptions) if int_exp: return ask(Q.orthogonal(base), assumptions) return None @OrthogonalPredicate.register(MatAdd) # type: ignore def _(expr, assumptions): if (len(expr.args) == 1 and ask(Q.orthogonal(expr.args[0]), assumptions)): return True @OrthogonalPredicate.register(MatrixSymbol) # type: ignore def _(expr, assumptions): if (not expr.is_square or ask(Q.invertible(expr), assumptions) is False): return False if Q.orthogonal(expr) in conjuncts(assumptions): return True @OrthogonalPredicate.register(Identity) # type: ignore def _(expr, assumptions): return True @OrthogonalPredicate.register(ZeroMatrix) # type: ignore def _(expr, assumptions): return False @OrthogonalPredicate.register_many(Inverse, Transpose) # type: ignore def _(expr, assumptions): return ask(Q.orthogonal(expr.arg), assumptions) @OrthogonalPredicate.register(MatrixSlice) # type: ignore def _(expr, assumptions): if not expr.on_diag: return None else: return ask(Q.orthogonal(expr.parent), assumptions) @OrthogonalPredicate.register(Factorization) # type: ignore def _(expr, assumptions): return _Factorization(Q.orthogonal, expr, assumptions) # UnitaryPredicate @UnitaryPredicate.register(MatMul) # type: ignore def _(expr, assumptions): factor, mmul = expr.as_coeff_mmul() if (all(ask(Q.unitary(arg), assumptions) for arg in mmul.args) and abs(factor) == 1): return True if any(ask(Q.invertible(arg), assumptions) is False for arg in mmul.args): return False @UnitaryPredicate.register(MatPow) # type: ignore def _(expr, assumptions): # only for integer powers base, exp = expr.args int_exp = ask(Q.integer(exp), assumptions) if int_exp: return ask(Q.unitary(base), assumptions) return None @UnitaryPredicate.register(MatrixSymbol) # type: ignore def _(expr, assumptions): if (not expr.is_square or ask(Q.invertible(expr), assumptions) is False): return False if Q.unitary(expr) in conjuncts(assumptions): return True @UnitaryPredicate.register_many(Inverse, Transpose) # type: ignore def _(expr, assumptions): return ask(Q.unitary(expr.arg), assumptions) @UnitaryPredicate.register(MatrixSlice) # type: ignore def _(expr, assumptions): if not expr.on_diag: return None else: return ask(Q.unitary(expr.parent), assumptions) @UnitaryPredicate.register_many(DFT, Identity) # type: ignore def _(expr, assumptions): return True @UnitaryPredicate.register(ZeroMatrix) # type: ignore def _(expr, assumptions): return False @UnitaryPredicate.register(Factorization) # type: ignore def _(expr, assumptions): return _Factorization(Q.unitary, expr, assumptions) # FullRankPredicate @FullRankPredicate.register(MatMul) # type: ignore def _(expr, assumptions): if all(ask(Q.fullrank(arg), assumptions) for arg in expr.args): return True @FullRankPredicate.register(MatPow) # type: ignore def _(expr, assumptions): # only for integer powers base, exp = expr.args int_exp = ask(Q.integer(exp), assumptions) if int_exp and ask(~Q.negative(exp), assumptions): return ask(Q.fullrank(base), assumptions) return None @FullRankPredicate.register(Identity) # type: ignore def _(expr, assumptions): return True @FullRankPredicate.register(ZeroMatrix) # type: ignore def _(expr, assumptions): return False @FullRankPredicate.register(OneMatrix) # type: ignore def _(expr, assumptions): return expr.shape[0] == 1 and expr.shape[1] == 1 @FullRankPredicate.register_many(Inverse, Transpose) # type: ignore def _(expr, assumptions): return ask(Q.fullrank(expr.arg), assumptions) @FullRankPredicate.register(MatrixSlice) # type: ignore def _(expr, assumptions): if ask(Q.orthogonal(expr.parent), assumptions): return True # PositiveDefinitePredicate @PositiveDefinitePredicate.register(MatMul) # type: ignore def _(expr, assumptions): factor, mmul = expr.as_coeff_mmul() if (all(ask(Q.positive_definite(arg), assumptions) for arg in mmul.args) and factor > 0): return True if (len(mmul.args) >= 2 and mmul.args[0] == mmul.args[-1].T and ask(Q.fullrank(mmul.args[0]), assumptions)): return ask(Q.positive_definite( MatMul(*mmul.args[1:-1])), assumptions) @PositiveDefinitePredicate.register(MatPow) # type: ignore def _(expr, assumptions): # a power of a positive definite matrix is positive definite if ask(Q.positive_definite(expr.args[0]), assumptions): return True @PositiveDefinitePredicate.register(MatAdd) # type: ignore def _(expr, assumptions): if all(ask(Q.positive_definite(arg), assumptions) for arg in expr.args): return True @PositiveDefinitePredicate.register(MatrixSymbol) # type: ignore def _(expr, assumptions): if not expr.is_square: return False if Q.positive_definite(expr) in conjuncts(assumptions): return True @PositiveDefinitePredicate.register(Identity) # type: ignore def _(expr, assumptions): return True @PositiveDefinitePredicate.register(ZeroMatrix) # type: ignore def _(expr, assumptions): return False @PositiveDefinitePredicate.register(OneMatrix) # type: ignore def _(expr, assumptions): return expr.shape[0] == 1 and expr.shape[1] == 1 @PositiveDefinitePredicate.register_many(Inverse, Transpose) # type: ignore def _(expr, assumptions): return ask(Q.positive_definite(expr.arg), assumptions) @PositiveDefinitePredicate.register(MatrixSlice) # type: ignore def _(expr, assumptions): if not expr.on_diag: return None else: return ask(Q.positive_definite(expr.parent), assumptions) # UpperTriangularPredicate @UpperTriangularPredicate.register(MatMul) # type: ignore def _(expr, assumptions): factor, matrices = expr.as_coeff_matrices() if all(ask(Q.upper_triangular(m), assumptions) for m in matrices): return True @UpperTriangularPredicate.register(MatAdd) # type: ignore def _(expr, assumptions): if all(ask(Q.upper_triangular(arg), assumptions) for arg in expr.args): return True @UpperTriangularPredicate.register(MatPow) # type: ignore def _(expr, assumptions): # only for integer powers base, exp = expr.args int_exp = ask(Q.integer(exp), assumptions) if not int_exp: return None non_negative = ask(~Q.negative(exp), assumptions) if (non_negative or non_negative == False and ask(Q.invertible(base), assumptions)): return ask(Q.upper_triangular(base), assumptions) return None @UpperTriangularPredicate.register(MatrixSymbol) # type: ignore def _(expr, assumptions): if Q.upper_triangular(expr) in conjuncts(assumptions): return True @UpperTriangularPredicate.register_many(Identity, ZeroMatrix) # type: ignore def _(expr, assumptions): return True @UpperTriangularPredicate.register(OneMatrix) # type: ignore def _(expr, assumptions): return expr.shape[0] == 1 and expr.shape[1] == 1 @UpperTriangularPredicate.register(Transpose) # type: ignore def _(expr, assumptions): return ask(Q.lower_triangular(expr.arg), assumptions) @UpperTriangularPredicate.register(Inverse) # type: ignore def _(expr, assumptions): return ask(Q.upper_triangular(expr.arg), assumptions) @UpperTriangularPredicate.register(MatrixSlice) # type: ignore def _(expr, assumptions): if not expr.on_diag: return None else: return ask(Q.upper_triangular(expr.parent), assumptions) @UpperTriangularPredicate.register(Factorization) # type: ignore def _(expr, assumptions): return _Factorization(Q.upper_triangular, expr, assumptions) # LowerTriangularPredicate @LowerTriangularPredicate.register(MatMul) # type: ignore def _(expr, assumptions): factor, matrices = expr.as_coeff_matrices() if all(ask(Q.lower_triangular(m), assumptions) for m in matrices): return True @LowerTriangularPredicate.register(MatAdd) # type: ignore def _(expr, assumptions): if all(ask(Q.lower_triangular(arg), assumptions) for arg in expr.args): return True @LowerTriangularPredicate.register(MatPow) # type: ignore def _(expr, assumptions): # only for integer powers base, exp = expr.args int_exp = ask(Q.integer(exp), assumptions) if not int_exp: return None non_negative = ask(~Q.negative(exp), assumptions) if (non_negative or non_negative == False and ask(Q.invertible(base), assumptions)): return ask(Q.lower_triangular(base), assumptions) return None @LowerTriangularPredicate.register(MatrixSymbol) # type: ignore def _(expr, assumptions): if Q.lower_triangular(expr) in conjuncts(assumptions): return True @LowerTriangularPredicate.register_many(Identity, ZeroMatrix) # type: ignore def _(expr, assumptions): return True @LowerTriangularPredicate.register(OneMatrix) # type: ignore def _(expr, assumptions): return expr.shape[0] == 1 and expr.shape[1] == 1 @LowerTriangularPredicate.register(Transpose) # type: ignore def _(expr, assumptions): return ask(Q.upper_triangular(expr.arg), assumptions) @LowerTriangularPredicate.register(Inverse) # type: ignore def _(expr, assumptions): return ask(Q.lower_triangular(expr.arg), assumptions) @LowerTriangularPredicate.register(MatrixSlice) # type: ignore def _(expr, assumptions): if not expr.on_diag: return None else: return ask(Q.lower_triangular(expr.parent), assumptions) @LowerTriangularPredicate.register(Factorization) # type: ignore def _(expr, assumptions): return _Factorization(Q.lower_triangular, expr, assumptions) # DiagonalPredicate def _is_empty_or_1x1(expr): return expr.shape in ((0, 0), (1, 1)) @DiagonalPredicate.register(MatMul) # type: ignore def _(expr, assumptions): if _is_empty_or_1x1(expr): return True factor, matrices = expr.as_coeff_matrices() if all(ask(Q.diagonal(m), assumptions) for m in matrices): return True @DiagonalPredicate.register(MatPow) # type: ignore def _(expr, assumptions): # only for integer powers base, exp = expr.args int_exp = ask(Q.integer(exp), assumptions) if not int_exp: return None non_negative = ask(~Q.negative(exp), assumptions) if (non_negative or non_negative == False and ask(Q.invertible(base), assumptions)): return ask(Q.diagonal(base), assumptions) return None @DiagonalPredicate.register(MatAdd) # type: ignore def _(expr, assumptions): if all(ask(Q.diagonal(arg), assumptions) for arg in expr.args): return True @DiagonalPredicate.register(MatrixSymbol) # type: ignore def _(expr, assumptions): if _is_empty_or_1x1(expr): return True if Q.diagonal(expr) in conjuncts(assumptions): return True @DiagonalPredicate.register(OneMatrix) # type: ignore def _(expr, assumptions): return expr.shape[0] == 1 and expr.shape[1] == 1 @DiagonalPredicate.register_many(Inverse, Transpose) # type: ignore def _(expr, assumptions): return ask(Q.diagonal(expr.arg), assumptions) @DiagonalPredicate.register(MatrixSlice) # type: ignore def _(expr, assumptions): if _is_empty_or_1x1(expr): return True if not expr.on_diag: return None else: return ask(Q.diagonal(expr.parent), assumptions) @DiagonalPredicate.register_many(DiagonalMatrix, DiagMatrix, Identity, ZeroMatrix) # type: ignore def _(expr, assumptions): return True @DiagonalPredicate.register(Factorization) # type: ignore def _(expr, assumptions): return _Factorization(Q.diagonal, expr, assumptions) # IntegerElementsPredicate def BM_elements(predicate, expr, assumptions): """ Block Matrix elements. """ return all(ask(predicate(b), assumptions) for b in expr.blocks) def MS_elements(predicate, expr, assumptions): """ Matrix Slice elements. """ return ask(predicate(expr.parent), assumptions) def MatMul_elements(matrix_predicate, scalar_predicate, expr, assumptions): d = sift(expr.args, lambda x: isinstance(x, MatrixExpr)) factors, matrices = d[False], d[True] return fuzzy_and([ test_closed_group(Basic(*factors), assumptions, scalar_predicate), test_closed_group(Basic(*matrices), assumptions, matrix_predicate)]) @IntegerElementsPredicate.register_many(Determinant, HadamardProduct, MatAdd, # type: ignore Trace, Transpose) def _(expr, assumptions): return test_closed_group(expr, assumptions, Q.integer_elements) @IntegerElementsPredicate.register(MatPow) # type: ignore def _(expr, assumptions): # only for integer powers base, exp = expr.args int_exp = ask(Q.integer(exp), assumptions) if not int_exp: return None if exp.is_negative == False: return ask(Q.integer_elements(base), assumptions) return None @IntegerElementsPredicate.register_many(Identity, OneMatrix, ZeroMatrix) # type: ignore def _(expr, assumptions): return True @IntegerElementsPredicate.register(MatMul) # type: ignore def _(expr, assumptions): return MatMul_elements(Q.integer_elements, Q.integer, expr, assumptions) @IntegerElementsPredicate.register(MatrixSlice) # type: ignore def _(expr, assumptions): return MS_elements(Q.integer_elements, expr, assumptions) @IntegerElementsPredicate.register(BlockMatrix) # type: ignore def _(expr, assumptions): return BM_elements(Q.integer_elements, expr, assumptions) # RealElementsPredicate @RealElementsPredicate.register_many(Determinant, Factorization, HadamardProduct, # type: ignore MatAdd, Trace, Transpose) def _(expr, assumptions): return test_closed_group(expr, assumptions, Q.real_elements) @RealElementsPredicate.register(MatPow) # type: ignore def _(expr, assumptions): # only for integer powers base, exp = expr.args int_exp = ask(Q.integer(exp), assumptions) if not int_exp: return None non_negative = ask(~Q.negative(exp), assumptions) if (non_negative or non_negative == False and ask(Q.invertible(base), assumptions)): return ask(Q.real_elements(base), assumptions) return None @RealElementsPredicate.register(MatMul) # type: ignore def _(expr, assumptions): return MatMul_elements(Q.real_elements, Q.real, expr, assumptions) @RealElementsPredicate.register(MatrixSlice) # type: ignore def _(expr, assumptions): return MS_elements(Q.real_elements, expr, assumptions) @RealElementsPredicate.register(BlockMatrix) # type: ignore def _(expr, assumptions): return BM_elements(Q.real_elements, expr, assumptions) # ComplexElementsPredicate @ComplexElementsPredicate.register_many(Determinant, Factorization, HadamardProduct, # type: ignore Inverse, MatAdd, Trace, Transpose) def _(expr, assumptions): return test_closed_group(expr, assumptions, Q.complex_elements) @ComplexElementsPredicate.register(MatPow) # type: ignore def _(expr, assumptions): # only for integer powers base, exp = expr.args int_exp = ask(Q.integer(exp), assumptions) if not int_exp: return None non_negative = ask(~Q.negative(exp), assumptions) if (non_negative or non_negative == False and ask(Q.invertible(base), assumptions)): return ask(Q.complex_elements(base), assumptions) return None @ComplexElementsPredicate.register(MatMul) # type: ignore def _(expr, assumptions): return MatMul_elements(Q.complex_elements, Q.complex, expr, assumptions) @ComplexElementsPredicate.register(MatrixSlice) # type: ignore def _(expr, assumptions): return MS_elements(Q.complex_elements, expr, assumptions) @ComplexElementsPredicate.register(BlockMatrix) # type: ignore def _(expr, assumptions): return BM_elements(Q.complex_elements, expr, assumptions) @ComplexElementsPredicate.register(DFT) # type: ignore def _(expr, assumptions): return True
21bcdbd20c2c78de1dd4626eb382d2d7b5421244ca1d529550780a613dca011f
""" Handlers related to order relations: positive, negative, etc. """ from sympy.assumptions import Q, ask from sympy.core import Add, Basic, Expr, Mul, Pow from sympy.core.logic import fuzzy_not, fuzzy_and, fuzzy_or from sympy.core.numbers import E, ImaginaryUnit, NaN, I, pi from sympy.functions import Abs, acos, acot, asin, atan, exp, factorial, log from sympy.matrices import Determinant, Trace from sympy.matrices.expressions.matexpr import MatrixElement from sympy.multipledispatch import MDNotImplementedError from ..predicates.order import (NegativePredicate, NonNegativePredicate, NonZeroPredicate, ZeroPredicate, NonPositivePredicate, PositivePredicate, ExtendedNegativePredicate, ExtendedNonNegativePredicate, ExtendedNonPositivePredicate, ExtendedNonZeroPredicate, ExtendedPositivePredicate,) # NegativePredicate def _NegativePredicate_number(expr, assumptions): r, i = expr.as_real_imag() # If the imaginary part can symbolically be shown to be zero then # we just evaluate the real part; otherwise we evaluate the imaginary # part to see if it actually evaluates to zero and if it does then # we make the comparison between the real part and zero. if not i: r = r.evalf(2) if r._prec != 1: return r < 0 else: i = i.evalf(2) if i._prec != 1: if i != 0: return False r = r.evalf(2) if r._prec != 1: return r < 0 @NegativePredicate.register(Basic) # type: ignore def _(expr, assumptions): if expr.is_number: return _NegativePredicate_number(expr, assumptions) @NegativePredicate.register(Expr) # type: ignore def _(expr, assumptions): ret = expr.is_negative if ret is None: raise MDNotImplementedError return ret @NegativePredicate.register(Add) # type: ignore def _(expr, assumptions): """ Positive + Positive -> Positive, Negative + Negative -> Negative """ if expr.is_number: return _NegativePredicate_number(expr, assumptions) r = ask(Q.real(expr), assumptions) if r is not True: return r nonpos = 0 for arg in expr.args: if ask(Q.negative(arg), assumptions) is not True: if ask(Q.positive(arg), assumptions) is False: nonpos += 1 else: break else: if nonpos < len(expr.args): return True @NegativePredicate.register(Mul) # type: ignore def _(expr, assumptions): if expr.is_number: return _NegativePredicate_number(expr, assumptions) result = None for arg in expr.args: if result is None: result = False if ask(Q.negative(arg), assumptions): result = not result elif ask(Q.positive(arg), assumptions): pass else: return return result @NegativePredicate.register(Pow) # type: ignore def _(expr, assumptions): """ Real ** Even -> NonNegative Real ** Odd -> same_as_base NonNegative ** Positive -> NonNegative """ if expr.base == E: # Exponential is always positive: if ask(Q.real(expr.exp), assumptions): return False return if expr.is_number: return _NegativePredicate_number(expr, assumptions) if ask(Q.real(expr.base), assumptions): if ask(Q.positive(expr.base), assumptions): if ask(Q.real(expr.exp), assumptions): return False if ask(Q.even(expr.exp), assumptions): return False if ask(Q.odd(expr.exp), assumptions): return ask(Q.negative(expr.base), assumptions) @NegativePredicate.register_many(Abs, ImaginaryUnit) # type: ignore def _(expr, assumptions): return False @NegativePredicate.register(exp) # type: ignore def _(expr, assumptions): if ask(Q.real(expr.exp), assumptions): return False raise MDNotImplementedError # NonNegativePredicate @NonNegativePredicate.register(Basic) # type: ignore def _(expr, assumptions): if expr.is_number: notnegative = fuzzy_not(_NegativePredicate_number(expr, assumptions)) if notnegative: return ask(Q.real(expr), assumptions) else: return notnegative @NonNegativePredicate.register(Expr) # type: ignore def _(expr, assumptions): ret = expr.is_nonnegative if ret is None: raise MDNotImplementedError return ret # NonZeroPredicate @NonZeroPredicate.register(Expr) # type: ignore def _(expr, assumptions): ret = expr.is_nonzero if ret is None: raise MDNotImplementedError return ret @NonZeroPredicate.register(Basic) # type: ignore def _(expr, assumptions): if ask(Q.real(expr)) is False: return False if expr.is_number: # if there are no symbols just evalf i = expr.evalf(2) def nonz(i): if i._prec != 1: return i != 0 return fuzzy_or(nonz(i) for i in i.as_real_imag()) @NonZeroPredicate.register(Add) # type: ignore def _(expr, assumptions): if all(ask(Q.positive(x), assumptions) for x in expr.args) \ or all(ask(Q.negative(x), assumptions) for x in expr.args): return True @NonZeroPredicate.register(Mul) # type: ignore def _(expr, assumptions): for arg in expr.args: result = ask(Q.nonzero(arg), assumptions) if result: continue return result return True @NonZeroPredicate.register(Pow) # type: ignore def _(expr, assumptions): return ask(Q.nonzero(expr.base), assumptions) @NonZeroPredicate.register(Abs) # type: ignore def _(expr, assumptions): return ask(Q.nonzero(expr.args[0]), assumptions) @NonZeroPredicate.register(NaN) # type: ignore def _(expr, assumptions): return None # ZeroPredicate @ZeroPredicate.register(Expr) # type: ignore def _(expr, assumptions): ret = expr.is_zero if ret is None: raise MDNotImplementedError return ret @ZeroPredicate.register(Basic) # type: ignore def _(expr, assumptions): return fuzzy_and([fuzzy_not(ask(Q.nonzero(expr), assumptions)), ask(Q.real(expr), assumptions)]) @ZeroPredicate.register(Mul) # type: ignore def _(expr, assumptions): # TODO: This should be deducible from the nonzero handler return fuzzy_or(ask(Q.zero(arg), assumptions) for arg in expr.args) # NonPositivePredicate @NonPositivePredicate.register(Expr) # type: ignore def _(expr, assumptions): ret = expr.is_nonpositive if ret is None: raise MDNotImplementedError return ret @NonPositivePredicate.register(Basic) # type: ignore def _(expr, assumptions): if expr.is_number: notpositive = fuzzy_not(_PositivePredicate_number(expr, assumptions)) if notpositive: return ask(Q.real(expr), assumptions) else: return notpositive # PositivePredicate def _PositivePredicate_number(expr, assumptions): r, i = expr.as_real_imag() # If the imaginary part can symbolically be shown to be zero then # we just evaluate the real part; otherwise we evaluate the imaginary # part to see if it actually evaluates to zero and if it does then # we make the comparison between the real part and zero. if not i: r = r.evalf(2) if r._prec != 1: return r > 0 else: i = i.evalf(2) if i._prec != 1: if i != 0: return False r = r.evalf(2) if r._prec != 1: return r > 0 @PositivePredicate.register(Expr) # type: ignore def _(expr, assumptions): ret = expr.is_positive if ret is None: raise MDNotImplementedError return ret @PositivePredicate.register(Basic) # type: ignore def _(expr, assumptions): if expr.is_number: return _PositivePredicate_number(expr, assumptions) @PositivePredicate.register(Mul) # type: ignore def _(expr, assumptions): if expr.is_number: return _PositivePredicate_number(expr, assumptions) result = True for arg in expr.args: if ask(Q.positive(arg), assumptions): continue elif ask(Q.negative(arg), assumptions): result = result ^ True else: return return result @PositivePredicate.register(Add) # type: ignore def _(expr, assumptions): if expr.is_number: return _PositivePredicate_number(expr, assumptions) r = ask(Q.real(expr), assumptions) if r is not True: return r nonneg = 0 for arg in expr.args: if ask(Q.positive(arg), assumptions) is not True: if ask(Q.negative(arg), assumptions) is False: nonneg += 1 else: break else: if nonneg < len(expr.args): return True @PositivePredicate.register(Pow) # type: ignore def _(expr, assumptions): if expr.base == E: if ask(Q.real(expr.exp), assumptions): return True if ask(Q.imaginary(expr.exp), assumptions): return ask(Q.even(expr.exp/(I*pi)), assumptions) return if expr.is_number: return _PositivePredicate_number(expr, assumptions) if ask(Q.positive(expr.base), assumptions): if ask(Q.real(expr.exp), assumptions): return True if ask(Q.negative(expr.base), assumptions): if ask(Q.even(expr.exp), assumptions): return True if ask(Q.odd(expr.exp), assumptions): return False @PositivePredicate.register(exp) # type: ignore def _(expr, assumptions): if ask(Q.real(expr.exp), assumptions): return True if ask(Q.imaginary(expr.exp), assumptions): return ask(Q.even(expr.exp/(I*pi)), assumptions) @PositivePredicate.register(log) # type: ignore def _(expr, assumptions): r = ask(Q.real(expr.args[0]), assumptions) if r is not True: return r if ask(Q.positive(expr.args[0] - 1), assumptions): return True if ask(Q.negative(expr.args[0] - 1), assumptions): return False @PositivePredicate.register(factorial) # type: ignore def _(expr, assumptions): x = expr.args[0] if ask(Q.integer(x) & Q.positive(x), assumptions): return True @PositivePredicate.register(ImaginaryUnit) # type: ignore def _(expr, assumptions): return False @PositivePredicate.register(Abs) # type: ignore def _(expr, assumptions): return ask(Q.nonzero(expr), assumptions) @PositivePredicate.register(Trace) # type: ignore def _(expr, assumptions): if ask(Q.positive_definite(expr.arg), assumptions): return True @PositivePredicate.register(Determinant) # type: ignore def _(expr, assumptions): if ask(Q.positive_definite(expr.arg), assumptions): return True @PositivePredicate.register(MatrixElement) # type: ignore def _(expr, assumptions): if (expr.i == expr.j and ask(Q.positive_definite(expr.parent), assumptions)): return True @PositivePredicate.register(atan) # type: ignore def _(expr, assumptions): return ask(Q.positive(expr.args[0]), assumptions) @PositivePredicate.register(asin) # type: ignore def _(expr, assumptions): x = expr.args[0] if ask(Q.positive(x) & Q.nonpositive(x - 1), assumptions): return True if ask(Q.negative(x) & Q.nonnegative(x + 1), assumptions): return False @PositivePredicate.register(acos) # type: ignore def _(expr, assumptions): x = expr.args[0] if ask(Q.nonpositive(x - 1) & Q.nonnegative(x + 1), assumptions): return True @PositivePredicate.register(acot) # type: ignore def _(expr, assumptions): return ask(Q.real(expr.args[0]), assumptions) @PositivePredicate.register(NaN) # type: ignore def _(expr, assumptions): return None # ExtendedNegativePredicate @ExtendedNegativePredicate.register(object) # type: ignore def _(expr, assumptions): return ask(Q.negative(expr) | Q.negative_infinite(expr), assumptions) # ExtendedPositivePredicate @ExtendedPositivePredicate.register(object) # type: ignore def _(expr, assumptions): return ask(Q.positive(expr) | Q.positive_infinite(expr), assumptions) # ExtendedNonZeroPredicate @ExtendedNonZeroPredicate.register(object) # type: ignore def _(expr, assumptions): return ask( Q.negative_infinite(expr) | Q.negative(expr) | Q.positive(expr) | Q.positive_infinite(expr), assumptions) # ExtendedNonPositivePredicate @ExtendedNonPositivePredicate.register(object) # type: ignore def _(expr, assumptions): return ask( Q.negative_infinite(expr) | Q.negative(expr) | Q.zero(expr), assumptions) # ExtendedNonNegativePredicate @ExtendedNonNegativePredicate.register(object) # type: ignore def _(expr, assumptions): return ask( Q.zero(expr) | Q.positive(expr) | Q.positive_infinite(expr), assumptions)
6fa525c26ea11a628d2867758d3050b0a7af20778d04f4764fb11e7925726357
""" Handlers for predicates related to set membership: integer, rational, etc. """ from sympy.assumptions import Q, ask from sympy.core import Add, Basic, Expr, Mul, Pow, S from sympy.core.numbers import (AlgebraicNumber, ComplexInfinity, Exp1, Float, GoldenRatio, ImaginaryUnit, Infinity, Integer, NaN, NegativeInfinity, Number, NumberSymbol, Pi, pi, Rational, TribonacciConstant, E) from sympy.core.logic import fuzzy_bool from sympy.functions import (Abs, acos, acot, asin, atan, cos, cot, exp, im, log, re, sin, tan) from sympy.core.numbers import I from sympy.core.relational import Eq from sympy.functions.elementary.complexes import conjugate from sympy.matrices import Determinant, MatrixBase, Trace from sympy.matrices.expressions.matexpr import MatrixElement from sympy.multipledispatch import MDNotImplementedError from .common import test_closed_group from ..predicates.sets import (IntegerPredicate, RationalPredicate, IrrationalPredicate, RealPredicate, ExtendedRealPredicate, HermitianPredicate, ComplexPredicate, ImaginaryPredicate, AntihermitianPredicate, AlgebraicPredicate) # IntegerPredicate def _IntegerPredicate_number(expr, assumptions): # helper function try: i = int(expr.round()) if not (expr - i).equals(0): raise TypeError return True except TypeError: return False @IntegerPredicate.register_many(int, Integer) # type:ignore def _(expr, assumptions): return True @IntegerPredicate.register_many(Exp1, GoldenRatio, ImaginaryUnit, Infinity, # type: ignore NegativeInfinity, Pi, Rational, TribonacciConstant) def _(expr, assumptions): return False @IntegerPredicate.register(Expr) # type: ignore def _(expr, assumptions): ret = expr.is_integer if ret is None: raise MDNotImplementedError return ret @IntegerPredicate.register_many(Add, Pow) # type: ignore def _(expr, assumptions): """ * Integer + Integer -> Integer * Integer + !Integer -> !Integer * !Integer + !Integer -> ? """ if expr.is_number: return _IntegerPredicate_number(expr, assumptions) return test_closed_group(expr, assumptions, Q.integer) @IntegerPredicate.register(Mul) # type: ignore def _(expr, assumptions): """ * Integer*Integer -> Integer * Integer*Irrational -> !Integer * Odd/Even -> !Integer * Integer*Rational -> ? """ if expr.is_number: return _IntegerPredicate_number(expr, assumptions) _output = True for arg in expr.args: if not ask(Q.integer(arg), assumptions): if arg.is_Rational: if arg.q == 2: return ask(Q.even(2*expr), assumptions) if ~(arg.q & 1): return None elif ask(Q.irrational(arg), assumptions): if _output: _output = False else: return else: return return _output @IntegerPredicate.register(Abs) # type: ignore def _(expr, assumptions): return ask(Q.integer(expr.args[0]), assumptions) @IntegerPredicate.register_many(Determinant, MatrixElement, Trace) # type: ignore def _(expr, assumptions): return ask(Q.integer_elements(expr.args[0]), assumptions) # RationalPredicate @RationalPredicate.register(Rational) # type: ignore def _(expr, assumptions): return True @RationalPredicate.register(Float) # type: ignore def _(expr, assumptions): return None @RationalPredicate.register_many(Exp1, GoldenRatio, ImaginaryUnit, Infinity, # type: ignore NegativeInfinity, Pi, TribonacciConstant) def _(expr, assumptions): return False @RationalPredicate.register(Expr) # type: ignore def _(expr, assumptions): ret = expr.is_rational if ret is None: raise MDNotImplementedError return ret @RationalPredicate.register_many(Add, Mul) # type: ignore def _(expr, assumptions): """ * Rational + Rational -> Rational * Rational + !Rational -> !Rational * !Rational + !Rational -> ? """ if expr.is_number: if expr.as_real_imag()[1]: return False return test_closed_group(expr, assumptions, Q.rational) @RationalPredicate.register(Pow) # type: ignore def _(expr, assumptions): """ * Rational ** Integer -> Rational * Irrational ** Rational -> Irrational * Rational ** Irrational -> ? """ if expr.base == E: x = expr.exp if ask(Q.rational(x), assumptions): return ask(~Q.nonzero(x), assumptions) return if ask(Q.integer(expr.exp), assumptions): return ask(Q.rational(expr.base), assumptions) elif ask(Q.rational(expr.exp), assumptions): if ask(Q.prime(expr.base), assumptions): return False @RationalPredicate.register_many(asin, atan, cos, sin, tan) # type: ignore def _(expr, assumptions): x = expr.args[0] if ask(Q.rational(x), assumptions): return ask(~Q.nonzero(x), assumptions) @RationalPredicate.register(exp) # type: ignore def _(expr, assumptions): x = expr.exp if ask(Q.rational(x), assumptions): return ask(~Q.nonzero(x), assumptions) @RationalPredicate.register_many(acot, cot) # type: ignore def _(expr, assumptions): x = expr.args[0] if ask(Q.rational(x), assumptions): return False @RationalPredicate.register_many(acos, log) # type: ignore def _(expr, assumptions): x = expr.args[0] if ask(Q.rational(x), assumptions): return ask(~Q.nonzero(x - 1), assumptions) # IrrationalPredicate @IrrationalPredicate.register(Expr) # type: ignore def _(expr, assumptions): ret = expr.is_irrational if ret is None: raise MDNotImplementedError return ret @IrrationalPredicate.register(Basic) # type: ignore def _(expr, assumptions): _real = ask(Q.real(expr), assumptions) if _real: _rational = ask(Q.rational(expr), assumptions) if _rational is None: return None return not _rational else: return _real # RealPredicate def _RealPredicate_number(expr, assumptions): # let as_real_imag() work first since the expression may # be simpler to evaluate i = expr.as_real_imag()[1].evalf(2) if i._prec != 1: return not i # allow None to be returned if we couldn't show for sure # that i was 0 @RealPredicate.register_many(Abs, Exp1, Float, GoldenRatio, im, Pi, Rational, # type: ignore re, TribonacciConstant) def _(expr, assumptions): return True @RealPredicate.register_many(ImaginaryUnit, Infinity, NegativeInfinity) # type: ignore def _(expr, assumptions): return False @RealPredicate.register(Expr) # type: ignore def _(expr, assumptions): ret = expr.is_real if ret is None: raise MDNotImplementedError return ret @RealPredicate.register(Add) # type: ignore def _(expr, assumptions): """ * Real + Real -> Real * Real + (Complex & !Real) -> !Real """ if expr.is_number: return _RealPredicate_number(expr, assumptions) return test_closed_group(expr, assumptions, Q.real) @RealPredicate.register(Mul) # type: ignore def _(expr, assumptions): """ * Real*Real -> Real * Real*Imaginary -> !Real * Imaginary*Imaginary -> Real """ if expr.is_number: return _RealPredicate_number(expr, assumptions) result = True for arg in expr.args: if ask(Q.real(arg), assumptions): pass elif ask(Q.imaginary(arg), assumptions): result = result ^ True else: break else: return result @RealPredicate.register(Pow) # type: ignore def _(expr, assumptions): """ * Real**Integer -> Real * Positive**Real -> Real * Real**(Integer/Even) -> Real if base is nonnegative * Real**(Integer/Odd) -> Real * Imaginary**(Integer/Even) -> Real * Imaginary**(Integer/Odd) -> not Real * Imaginary**Real -> ? since Real could be 0 (giving real) or 1 (giving imaginary) * b**Imaginary -> Real if log(b) is imaginary and b != 0 and exponent != integer multiple of I*pi/log(b) * Real**Real -> ? e.g. sqrt(-1) is imaginary and sqrt(2) is not """ if expr.is_number: return _RealPredicate_number(expr, assumptions) if expr.base == E: return ask( Q.integer(expr.exp/I/pi) | Q.real(expr.exp), assumptions ) if expr.base.func == exp or (expr.base.is_Pow and expr.base.base == E): if ask(Q.imaginary(expr.base.exp), assumptions): if ask(Q.imaginary(expr.exp), assumptions): return True # If the i = (exp's arg)/(I*pi) is an integer or half-integer # multiple of I*pi then 2*i will be an integer. In addition, # exp(i*I*pi) = (-1)**i so the overall realness of the expr # can be determined by replacing exp(i*I*pi) with (-1)**i. i = expr.base.exp/I/pi if ask(Q.integer(2*i), assumptions): return ask(Q.real((S.NegativeOne**i)**expr.exp), assumptions) return if ask(Q.imaginary(expr.base), assumptions): if ask(Q.integer(expr.exp), assumptions): odd = ask(Q.odd(expr.exp), assumptions) if odd is not None: return not odd return if ask(Q.imaginary(expr.exp), assumptions): imlog = ask(Q.imaginary(log(expr.base)), assumptions) if imlog is not None: # I**i -> real, log(I) is imag; # (2*I)**i -> complex, log(2*I) is not imag return imlog if ask(Q.real(expr.base), assumptions): if ask(Q.real(expr.exp), assumptions): if expr.exp.is_Rational and \ ask(Q.even(expr.exp.q), assumptions): return ask(Q.positive(expr.base), assumptions) elif ask(Q.integer(expr.exp), assumptions): return True elif ask(Q.positive(expr.base), assumptions): return True elif ask(Q.negative(expr.base), assumptions): return False @RealPredicate.register_many(cos, sin) # type: ignore def _(expr, assumptions): if ask(Q.real(expr.args[0]), assumptions): return True @RealPredicate.register(exp) # type: ignore def _(expr, assumptions): return ask( Q.integer(expr.exp/I/pi) | Q.real(expr.exp), assumptions ) @RealPredicate.register(log) # type: ignore def _(expr, assumptions): return ask(Q.positive(expr.args[0]), assumptions) @RealPredicate.register_many(Determinant, MatrixElement, Trace) # type: ignore def _(expr, assumptions): return ask(Q.real_elements(expr.args[0]), assumptions) # ExtendedRealPredicate @ExtendedRealPredicate.register(object) # type: ignore def _(expr, assumptions): return ask(Q.negative_infinite(expr) | Q.negative(expr) | Q.zero(expr) | Q.positive(expr) | Q.positive_infinite(expr), assumptions) @ExtendedRealPredicate.register_many(Infinity, NegativeInfinity) # type: ignore def _(expr, assumptions): return True @ExtendedRealPredicate.register_many(Add, Mul, Pow) # type:ignore def _(expr, assumptions): return test_closed_group(expr, assumptions, Q.extended_real) # HermitianPredicate @HermitianPredicate.register(object) # type:ignore def _(expr, assumptions): if isinstance(expr, MatrixBase): return None return ask(Q.real(expr), assumptions) @HermitianPredicate.register(Add) # type:ignore def _(expr, assumptions): """ * Hermitian + Hermitian -> Hermitian * Hermitian + !Hermitian -> !Hermitian """ if expr.is_number: raise MDNotImplementedError return test_closed_group(expr, assumptions, Q.hermitian) @HermitianPredicate.register(Mul) # type:ignore def _(expr, assumptions): """ As long as there is at most only one noncommutative term: * Hermitian*Hermitian -> Hermitian * Hermitian*Antihermitian -> !Hermitian * Antihermitian*Antihermitian -> Hermitian """ if expr.is_number: raise MDNotImplementedError nccount = 0 result = True for arg in expr.args: if ask(Q.antihermitian(arg), assumptions): result = result ^ True elif not ask(Q.hermitian(arg), assumptions): break if ask(~Q.commutative(arg), assumptions): nccount += 1 if nccount > 1: break else: return result @HermitianPredicate.register(Pow) # type:ignore def _(expr, assumptions): """ * Hermitian**Integer -> Hermitian """ if expr.is_number: raise MDNotImplementedError if expr.base == E: if ask(Q.hermitian(expr.exp), assumptions): return True raise MDNotImplementedError if ask(Q.hermitian(expr.base), assumptions): if ask(Q.integer(expr.exp), assumptions): return True raise MDNotImplementedError @HermitianPredicate.register_many(cos, sin) # type:ignore def _(expr, assumptions): if ask(Q.hermitian(expr.args[0]), assumptions): return True raise MDNotImplementedError @HermitianPredicate.register(exp) # type:ignore def _(expr, assumptions): if ask(Q.hermitian(expr.exp), assumptions): return True raise MDNotImplementedError @HermitianPredicate.register(MatrixBase) # type:ignore def _(mat, assumptions): rows, cols = mat.shape ret_val = True for i in range(rows): for j in range(i, cols): cond = fuzzy_bool(Eq(mat[i, j], conjugate(mat[j, i]))) if cond is None: ret_val = None if cond == False: return False if ret_val is None: raise MDNotImplementedError return ret_val # ComplexPredicate @ComplexPredicate.register_many(Abs, cos, exp, im, ImaginaryUnit, log, Number, # type:ignore NumberSymbol, re, sin) def _(expr, assumptions): return True @ComplexPredicate.register_many(Infinity, NegativeInfinity) # type:ignore def _(expr, assumptions): return False @ComplexPredicate.register(Expr) # type:ignore def _(expr, assumptions): ret = expr.is_complex if ret is None: raise MDNotImplementedError return ret @ComplexPredicate.register_many(Add, Mul) # type:ignore def _(expr, assumptions): return test_closed_group(expr, assumptions, Q.complex) @ComplexPredicate.register(Pow) # type:ignore def _(expr, assumptions): if expr.base == E: return True return test_closed_group(expr, assumptions, Q.complex) @ComplexPredicate.register_many(Determinant, MatrixElement, Trace) # type:ignore def _(expr, assumptions): return ask(Q.complex_elements(expr.args[0]), assumptions) @ComplexPredicate.register(NaN) # type:ignore def _(expr, assumptions): return None # ImaginaryPredicate def _Imaginary_number(expr, assumptions): # let as_real_imag() work first since the expression may # be simpler to evaluate r = expr.as_real_imag()[0].evalf(2) if r._prec != 1: return not r # allow None to be returned if we couldn't show for sure # that r was 0 @ImaginaryPredicate.register(ImaginaryUnit) # type:ignore def _(expr, assumptions): return True @ImaginaryPredicate.register(Expr) # type:ignore def _(expr, assumptions): ret = expr.is_imaginary if ret is None: raise MDNotImplementedError return ret @ImaginaryPredicate.register(Add) # type:ignore def _(expr, assumptions): """ * Imaginary + Imaginary -> Imaginary * Imaginary + Complex -> ? * Imaginary + Real -> !Imaginary """ if expr.is_number: return _Imaginary_number(expr, assumptions) reals = 0 for arg in expr.args: if ask(Q.imaginary(arg), assumptions): pass elif ask(Q.real(arg), assumptions): reals += 1 else: break else: if reals == 0: return True if reals in (1, len(expr.args)): # two reals could sum 0 thus giving an imaginary return False @ImaginaryPredicate.register(Mul) # type:ignore def _(expr, assumptions): """ * Real*Imaginary -> Imaginary * Imaginary*Imaginary -> Real """ if expr.is_number: return _Imaginary_number(expr, assumptions) result = False reals = 0 for arg in expr.args: if ask(Q.imaginary(arg), assumptions): result = result ^ True elif not ask(Q.real(arg), assumptions): break else: if reals == len(expr.args): return False return result @ImaginaryPredicate.register(Pow) # type:ignore def _(expr, assumptions): """ * Imaginary**Odd -> Imaginary * Imaginary**Even -> Real * b**Imaginary -> !Imaginary if exponent is an integer multiple of I*pi/log(b) * Imaginary**Real -> ? * Positive**Real -> Real * Negative**Integer -> Real * Negative**(Integer/2) -> Imaginary * Negative**Real -> not Imaginary if exponent is not Rational """ if expr.is_number: return _Imaginary_number(expr, assumptions) if expr.base == E: a = expr.exp/I/pi return ask(Q.integer(2*a) & ~Q.integer(a), assumptions) if expr.base.func == exp or (expr.base.is_Pow and expr.base.base == E): if ask(Q.imaginary(expr.base.exp), assumptions): if ask(Q.imaginary(expr.exp), assumptions): return False i = expr.base.exp/I/pi if ask(Q.integer(2*i), assumptions): return ask(Q.imaginary((S.NegativeOne**i)**expr.exp), assumptions) if ask(Q.imaginary(expr.base), assumptions): if ask(Q.integer(expr.exp), assumptions): odd = ask(Q.odd(expr.exp), assumptions) if odd is not None: return odd return if ask(Q.imaginary(expr.exp), assumptions): imlog = ask(Q.imaginary(log(expr.base)), assumptions) if imlog is not None: # I**i -> real; (2*I)**i -> complex ==> not imaginary return False if ask(Q.real(expr.base) & Q.real(expr.exp), assumptions): if ask(Q.positive(expr.base), assumptions): return False else: rat = ask(Q.rational(expr.exp), assumptions) if not rat: return rat if ask(Q.integer(expr.exp), assumptions): return False else: half = ask(Q.integer(2*expr.exp), assumptions) if half: return ask(Q.negative(expr.base), assumptions) return half @ImaginaryPredicate.register(log) # type:ignore def _(expr, assumptions): if ask(Q.real(expr.args[0]), assumptions): if ask(Q.positive(expr.args[0]), assumptions): return False return # XXX it should be enough to do # return ask(Q.nonpositive(expr.args[0]), assumptions) # but ask(Q.nonpositive(exp(x)), Q.imaginary(x)) -> None; # it should return True since exp(x) will be either 0 or complex if expr.args[0].func == exp or (expr.args[0].is_Pow and expr.args[0].base == E): if expr.args[0].exp in [I, -I]: return True im = ask(Q.imaginary(expr.args[0]), assumptions) if im is False: return False @ImaginaryPredicate.register(exp) # type:ignore def _(expr, assumptions): a = expr.exp/I/pi return ask(Q.integer(2*a) & ~Q.integer(a), assumptions) @ImaginaryPredicate.register_many(Number, NumberSymbol) # type:ignore def _(expr, assumptions): return not (expr.as_real_imag()[1] == 0) @ImaginaryPredicate.register(NaN) # type:ignore def _(expr, assumptions): return None # AntihermitianPredicate @AntihermitianPredicate.register(object) # type:ignore def _(expr, assumptions): if isinstance(expr, MatrixBase): return None if ask(Q.zero(expr), assumptions): return True return ask(Q.imaginary(expr), assumptions) @AntihermitianPredicate.register(Add) # type:ignore def _(expr, assumptions): """ * Antihermitian + Antihermitian -> Antihermitian * Antihermitian + !Antihermitian -> !Antihermitian """ if expr.is_number: raise MDNotImplementedError return test_closed_group(expr, assumptions, Q.antihermitian) @AntihermitianPredicate.register(Mul) # type:ignore def _(expr, assumptions): """ As long as there is at most only one noncommutative term: * Hermitian*Hermitian -> !Antihermitian * Hermitian*Antihermitian -> Antihermitian * Antihermitian*Antihermitian -> !Antihermitian """ if expr.is_number: raise MDNotImplementedError nccount = 0 result = False for arg in expr.args: if ask(Q.antihermitian(arg), assumptions): result = result ^ True elif not ask(Q.hermitian(arg), assumptions): break if ask(~Q.commutative(arg), assumptions): nccount += 1 if nccount > 1: break else: return result @AntihermitianPredicate.register(Pow) # type:ignore def _(expr, assumptions): """ * Hermitian**Integer -> !Antihermitian * Antihermitian**Even -> !Antihermitian * Antihermitian**Odd -> Antihermitian """ if expr.is_number: raise MDNotImplementedError if ask(Q.hermitian(expr.base), assumptions): if ask(Q.integer(expr.exp), assumptions): return False elif ask(Q.antihermitian(expr.base), assumptions): if ask(Q.even(expr.exp), assumptions): return False elif ask(Q.odd(expr.exp), assumptions): return True raise MDNotImplementedError @AntihermitianPredicate.register(MatrixBase) # type:ignore def _(mat, assumptions): rows, cols = mat.shape ret_val = True for i in range(rows): for j in range(i, cols): cond = fuzzy_bool(Eq(mat[i, j], -conjugate(mat[j, i]))) if cond is None: ret_val = None if cond == False: return False if ret_val is None: raise MDNotImplementedError return ret_val # AlgebraicPredicate @AlgebraicPredicate.register_many(AlgebraicNumber, Float, GoldenRatio, # type:ignore ImaginaryUnit, TribonacciConstant) def _(expr, assumptions): return True @AlgebraicPredicate.register_many(ComplexInfinity, Exp1, Infinity, # type:ignore NegativeInfinity, Pi) def _(expr, assumptions): return False @AlgebraicPredicate.register_many(Add, Mul) # type:ignore def _(expr, assumptions): return test_closed_group(expr, assumptions, Q.algebraic) @AlgebraicPredicate.register(Pow) # type:ignore def _(expr, assumptions): if expr.base == E: if ask(Q.algebraic(expr.exp), assumptions): return ask(~Q.nonzero(expr.exp), assumptions) return return expr.exp.is_Rational and ask(Q.algebraic(expr.base), assumptions) @AlgebraicPredicate.register(Rational) # type:ignore def _(expr, assumptions): return expr.q != 0 @AlgebraicPredicate.register_many(asin, atan, cos, sin, tan) # type:ignore def _(expr, assumptions): x = expr.args[0] if ask(Q.algebraic(x), assumptions): return ask(~Q.nonzero(x), assumptions) @AlgebraicPredicate.register(exp) # type:ignore def _(expr, assumptions): x = expr.exp if ask(Q.algebraic(x), assumptions): return ask(~Q.nonzero(x), assumptions) @AlgebraicPredicate.register_many(acot, cot) # type:ignore def _(expr, assumptions): x = expr.args[0] if ask(Q.algebraic(x), assumptions): return False @AlgebraicPredicate.register_many(acos, log) # type:ignore def _(expr, assumptions): x = expr.args[0] if ask(Q.algebraic(x), assumptions): return ask(~Q.nonzero(x - 1), assumptions)
ed96b8913bc464ebef607a200f76189c8c77bbbf3fc396823d1cdded8a788d9e
from sympy.assumptions.ask import Q from sympy.assumptions.refine import refine from sympy.core.expr import Expr from sympy.core.numbers import (I, Rational, nan, pi) from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.functions.elementary.complexes import (Abs, arg, im, re, sign) from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (atan, atan2) from sympy.abc import w, x, y, z from sympy.core.relational import Eq, Ne from sympy.functions.elementary.piecewise import Piecewise from sympy.matrices.expressions.matexpr import MatrixSymbol def test_Abs(): assert refine(Abs(x), Q.positive(x)) == x assert refine(1 + Abs(x), Q.positive(x)) == 1 + x assert refine(Abs(x), Q.negative(x)) == -x assert refine(1 + Abs(x), Q.negative(x)) == 1 - x assert refine(Abs(x**2)) != x**2 assert refine(Abs(x**2), Q.real(x)) == x**2 def test_pow1(): assert refine((-1)**x, Q.even(x)) == 1 assert refine((-1)**x, Q.odd(x)) == -1 assert refine((-2)**x, Q.even(x)) == 2**x # nested powers assert refine(sqrt(x**2)) != Abs(x) assert refine(sqrt(x**2), Q.complex(x)) != Abs(x) assert refine(sqrt(x**2), Q.real(x)) == Abs(x) assert refine(sqrt(x**2), Q.positive(x)) == x assert refine((x**3)**Rational(1, 3)) != x assert refine((x**3)**Rational(1, 3), Q.real(x)) != x assert refine((x**3)**Rational(1, 3), Q.positive(x)) == x assert refine(sqrt(1/x), Q.real(x)) != 1/sqrt(x) assert refine(sqrt(1/x), Q.positive(x)) == 1/sqrt(x) # powers of (-1) assert refine((-1)**(x + y), Q.even(x)) == (-1)**y assert refine((-1)**(x + y + z), Q.odd(x) & Q.odd(z)) == (-1)**y assert refine((-1)**(x + y + 1), Q.odd(x)) == (-1)**y assert refine((-1)**(x + y + 2), Q.odd(x)) == (-1)**(y + 1) assert refine((-1)**(x + 3)) == (-1)**(x + 1) # continuation assert refine((-1)**((-1)**x/2 - S.Half), Q.integer(x)) == (-1)**x assert refine((-1)**((-1)**x/2 + S.Half), Q.integer(x)) == (-1)**(x + 1) assert refine((-1)**((-1)**x/2 + 5*S.Half), Q.integer(x)) == (-1)**(x + 1) def test_pow2(): assert refine((-1)**((-1)**x/2 - 7*S.Half), Q.integer(x)) == (-1)**(x + 1) assert refine((-1)**((-1)**x/2 - 9*S.Half), Q.integer(x)) == (-1)**x # powers of Abs assert refine(Abs(x)**2, Q.real(x)) == x**2 assert refine(Abs(x)**3, Q.real(x)) == Abs(x)**3 assert refine(Abs(x)**2) == Abs(x)**2 def test_exp(): x = Symbol('x', integer=True) assert refine(exp(pi*I*2*x)) == 1 assert refine(exp(pi*I*2*(x + S.Half))) == -1 assert refine(exp(pi*I*2*(x + Rational(1, 4)))) == I assert refine(exp(pi*I*2*(x + Rational(3, 4)))) == -I def test_Piecewise(): assert refine(Piecewise((1, x < 0), (3, True)), (x < 0)) == 1 assert refine(Piecewise((1, x < 0), (3, True)), ~(x < 0)) == 3 assert refine(Piecewise((1, x < 0), (3, True)), (y < 0)) == \ Piecewise((1, x < 0), (3, True)) assert refine(Piecewise((1, x > 0), (3, True)), (x > 0)) == 1 assert refine(Piecewise((1, x > 0), (3, True)), ~(x > 0)) == 3 assert refine(Piecewise((1, x > 0), (3, True)), (y > 0)) == \ Piecewise((1, x > 0), (3, True)) assert refine(Piecewise((1, x <= 0), (3, True)), (x <= 0)) == 1 assert refine(Piecewise((1, x <= 0), (3, True)), ~(x <= 0)) == 3 assert refine(Piecewise((1, x <= 0), (3, True)), (y <= 0)) == \ Piecewise((1, x <= 0), (3, True)) assert refine(Piecewise((1, x >= 0), (3, True)), (x >= 0)) == 1 assert refine(Piecewise((1, x >= 0), (3, True)), ~(x >= 0)) == 3 assert refine(Piecewise((1, x >= 0), (3, True)), (y >= 0)) == \ Piecewise((1, x >= 0), (3, True)) assert refine(Piecewise((1, Eq(x, 0)), (3, True)), (Eq(x, 0)))\ == 1 assert refine(Piecewise((1, Eq(x, 0)), (3, True)), (Eq(0, x)))\ == 1 assert refine(Piecewise((1, Eq(x, 0)), (3, True)), ~(Eq(x, 0)))\ == 3 assert refine(Piecewise((1, Eq(x, 0)), (3, True)), ~(Eq(0, x)))\ == 3 assert refine(Piecewise((1, Eq(x, 0)), (3, True)), (Eq(y, 0)))\ == Piecewise((1, Eq(x, 0)), (3, True)) assert refine(Piecewise((1, Ne(x, 0)), (3, True)), (Ne(x, 0)))\ == 1 assert refine(Piecewise((1, Ne(x, 0)), (3, True)), ~(Ne(x, 0)))\ == 3 assert refine(Piecewise((1, Ne(x, 0)), (3, True)), (Ne(y, 0)))\ == Piecewise((1, Ne(x, 0)), (3, True)) def test_atan2(): assert refine(atan2(y, x), Q.real(y) & Q.positive(x)) == atan(y/x) assert refine(atan2(y, x), Q.negative(y) & Q.positive(x)) == atan(y/x) assert refine(atan2(y, x), Q.negative(y) & Q.negative(x)) == atan(y/x) - pi assert refine(atan2(y, x), Q.positive(y) & Q.negative(x)) == atan(y/x) + pi assert refine(atan2(y, x), Q.zero(y) & Q.negative(x)) == pi assert refine(atan2(y, x), Q.positive(y) & Q.zero(x)) == pi/2 assert refine(atan2(y, x), Q.negative(y) & Q.zero(x)) == -pi/2 assert refine(atan2(y, x), Q.zero(y) & Q.zero(x)) is nan def test_re(): assert refine(re(x), Q.real(x)) == x assert refine(re(x), Q.imaginary(x)) is S.Zero assert refine(re(x+y), Q.real(x) & Q.real(y)) == x + y assert refine(re(x+y), Q.real(x) & Q.imaginary(y)) == x assert refine(re(x*y), Q.real(x) & Q.real(y)) == x * y assert refine(re(x*y), Q.real(x) & Q.imaginary(y)) == 0 assert refine(re(x*y*z), Q.real(x) & Q.real(y) & Q.real(z)) == x * y * z def test_im(): assert refine(im(x), Q.imaginary(x)) == -I*x assert refine(im(x), Q.real(x)) is S.Zero assert refine(im(x+y), Q.imaginary(x) & Q.imaginary(y)) == -I*x - I*y assert refine(im(x+y), Q.real(x) & Q.imaginary(y)) == -I*y assert refine(im(x*y), Q.imaginary(x) & Q.real(y)) == -I*x*y assert refine(im(x*y), Q.imaginary(x) & Q.imaginary(y)) == 0 assert refine(im(1/x), Q.imaginary(x)) == -I/x assert refine(im(x*y*z), Q.imaginary(x) & Q.imaginary(y) & Q.imaginary(z)) == -I*x*y*z def test_complex(): assert refine(re(1/(x + I*y)), Q.real(x) & Q.real(y)) == \ x/(x**2 + y**2) assert refine(im(1/(x + I*y)), Q.real(x) & Q.real(y)) == \ -y/(x**2 + y**2) assert refine(re((w + I*x) * (y + I*z)), Q.real(w) & Q.real(x) & Q.real(y) & Q.real(z)) == w*y - x*z assert refine(im((w + I*x) * (y + I*z)), Q.real(w) & Q.real(x) & Q.real(y) & Q.real(z)) == w*z + x*y def test_sign(): x = Symbol('x', real = True) assert refine(sign(x), Q.positive(x)) == 1 assert refine(sign(x), Q.negative(x)) == -1 assert refine(sign(x), Q.zero(x)) == 0 assert refine(sign(x), True) == sign(x) assert refine(sign(Abs(x)), Q.nonzero(x)) == 1 x = Symbol('x', imaginary=True) assert refine(sign(x), Q.positive(im(x))) == S.ImaginaryUnit assert refine(sign(x), Q.negative(im(x))) == -S.ImaginaryUnit assert refine(sign(x), True) == sign(x) x = Symbol('x', complex=True) assert refine(sign(x), Q.zero(x)) == 0 def test_arg(): x = Symbol('x', complex = True) assert refine(arg(x), Q.positive(x)) == 0 assert refine(arg(x), Q.negative(x)) == pi def test_func_args(): class MyClass(Expr): # A class with nontrivial .func def __init__(self, *args): self.my_member = "" @property def func(self): def my_func(*args): obj = MyClass(*args) obj.my_member = self.my_member return obj return my_func x = MyClass() x.my_member = "A very important value" assert x.my_member == refine(x).my_member def test_eval_refine(): class MockExpr(Expr): def _eval_refine(self, assumptions): return True mock_obj = MockExpr() assert refine(mock_obj) def test_refine_issue_12724(): expr1 = refine(Abs(x * y), Q.positive(x)) expr2 = refine(Abs(x * y * z), Q.positive(x)) assert expr1 == x * Abs(y) assert expr2 == x * Abs(y * z) y1 = Symbol('y1', real = True) expr3 = refine(Abs(x * y1**2 * z), Q.positive(x)) assert expr3 == x * y1**2 * Abs(z) def test_matrixelement(): x = MatrixSymbol('x', 3, 3) i = Symbol('i', positive = True) j = Symbol('j', positive = True) assert refine(x[0, 1], Q.symmetric(x)) == x[0, 1] assert refine(x[1, 0], Q.symmetric(x)) == x[0, 1] assert refine(x[i, j], Q.symmetric(x)) == x[j, i] assert refine(x[j, i], Q.symmetric(x)) == x[j, i]
208aaa231ce42df00da53341284b02182a77066f339839d8776df0a2a2a1f441
from sympy.assumptions.ask import Q from sympy.assumptions.assume import assuming from sympy.core.numbers import (I, pi) from sympy.core.relational import (Eq, Gt) from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.functions.elementary.complexes import Abs from sympy.logic.boolalg import Implies from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.assumptions.cnf import CNF, Literal from sympy.assumptions.satask import (satask, extract_predargs, get_relevant_clsfacts) from sympy.testing.pytest import raises, XFAIL x, y, z = symbols('x y z') def test_satask(): # No relevant facts assert satask(Q.real(x), Q.real(x)) is True assert satask(Q.real(x), ~Q.real(x)) is False assert satask(Q.real(x)) is None assert satask(Q.real(x), Q.positive(x)) is True assert satask(Q.positive(x), Q.real(x)) is None assert satask(Q.real(x), ~Q.positive(x)) is None assert satask(Q.positive(x), ~Q.real(x)) is False raises(ValueError, lambda: satask(Q.real(x), Q.real(x) & ~Q.real(x))) with assuming(Q.positive(x)): assert satask(Q.real(x)) is True assert satask(~Q.positive(x)) is False raises(ValueError, lambda: satask(Q.real(x), ~Q.positive(x))) assert satask(Q.zero(x), Q.nonzero(x)) is False assert satask(Q.positive(x), Q.zero(x)) is False assert satask(Q.real(x), Q.zero(x)) is True assert satask(Q.zero(x), Q.zero(x*y)) is None assert satask(Q.zero(x*y), Q.zero(x)) def test_zero(): """ Everything in this test doesn't work with the ask handlers, and most things would be very difficult or impossible to make work under that model. """ assert satask(Q.zero(x) | Q.zero(y), Q.zero(x*y)) is True assert satask(Q.zero(x*y), Q.zero(x) | Q.zero(y)) is True assert satask(Implies(Q.zero(x), Q.zero(x*y))) is True # This one in particular requires computing the fixed-point of the # relevant facts, because going from Q.nonzero(x*y) -> ~Q.zero(x*y) and # Q.zero(x*y) -> Equivalent(Q.zero(x*y), Q.zero(x) | Q.zero(y)) takes two # steps. assert satask(Q.zero(x) | Q.zero(y), Q.nonzero(x*y)) is False assert satask(Q.zero(x), Q.zero(x**2)) is True def test_zero_positive(): assert satask(Q.zero(x + y), Q.positive(x) & Q.positive(y)) is False assert satask(Q.positive(x) & Q.positive(y), Q.zero(x + y)) is False assert satask(Q.nonzero(x + y), Q.positive(x) & Q.positive(y)) is True assert satask(Q.positive(x) & Q.positive(y), Q.nonzero(x + y)) is None # This one requires several levels of forward chaining assert satask(Q.zero(x*(x + y)), Q.positive(x) & Q.positive(y)) is False assert satask(Q.positive(pi*x*y + 1), Q.positive(x) & Q.positive(y)) is True assert satask(Q.positive(pi*x*y - 5), Q.positive(x) & Q.positive(y)) is None def test_zero_pow(): assert satask(Q.zero(x**y), Q.zero(x) & Q.positive(y)) is True assert satask(Q.zero(x**y), Q.nonzero(x) & Q.zero(y)) is False assert satask(Q.zero(x), Q.zero(x**y)) is True assert satask(Q.zero(x**y), Q.zero(x)) is None @XFAIL # Requires correct Q.square calculation first def test_invertible(): A = MatrixSymbol('A', 5, 5) B = MatrixSymbol('B', 5, 5) assert satask(Q.invertible(A*B), Q.invertible(A) & Q.invertible(B)) is True assert satask(Q.invertible(A), Q.invertible(A*B)) is True assert satask(Q.invertible(A) & Q.invertible(B), Q.invertible(A*B)) is True def test_prime(): assert satask(Q.prime(5)) is True assert satask(Q.prime(6)) is False assert satask(Q.prime(-5)) is False assert satask(Q.prime(x*y), Q.integer(x) & Q.integer(y)) is None assert satask(Q.prime(x*y), Q.prime(x) & Q.prime(y)) is False def test_old_assump(): assert satask(Q.positive(1)) is True assert satask(Q.positive(-1)) is False assert satask(Q.positive(0)) is False assert satask(Q.positive(I)) is False assert satask(Q.positive(pi)) is True assert satask(Q.negative(1)) is False assert satask(Q.negative(-1)) is True assert satask(Q.negative(0)) is False assert satask(Q.negative(I)) is False assert satask(Q.negative(pi)) is False assert satask(Q.zero(1)) is False assert satask(Q.zero(-1)) is False assert satask(Q.zero(0)) is True assert satask(Q.zero(I)) is False assert satask(Q.zero(pi)) is False assert satask(Q.nonzero(1)) is True assert satask(Q.nonzero(-1)) is True assert satask(Q.nonzero(0)) is False assert satask(Q.nonzero(I)) is False assert satask(Q.nonzero(pi)) is True assert satask(Q.nonpositive(1)) is False assert satask(Q.nonpositive(-1)) is True assert satask(Q.nonpositive(0)) is True assert satask(Q.nonpositive(I)) is False assert satask(Q.nonpositive(pi)) is False assert satask(Q.nonnegative(1)) is True assert satask(Q.nonnegative(-1)) is False assert satask(Q.nonnegative(0)) is True assert satask(Q.nonnegative(I)) is False assert satask(Q.nonnegative(pi)) is True def test_rational_irrational(): assert satask(Q.irrational(2)) is False assert satask(Q.rational(2)) is True assert satask(Q.irrational(pi)) is True assert satask(Q.rational(pi)) is False assert satask(Q.irrational(I)) is False assert satask(Q.rational(I)) is False assert satask(Q.irrational(x*y*z), Q.irrational(x) & Q.irrational(y) & Q.rational(z)) is None assert satask(Q.irrational(x*y*z), Q.irrational(x) & Q.rational(y) & Q.rational(z)) is True assert satask(Q.irrational(pi*x*y), Q.rational(x) & Q.rational(y)) is True assert satask(Q.irrational(x + y + z), Q.irrational(x) & Q.irrational(y) & Q.rational(z)) is None assert satask(Q.irrational(x + y + z), Q.irrational(x) & Q.rational(y) & Q.rational(z)) is True assert satask(Q.irrational(pi + x + y), Q.rational(x) & Q.rational(y)) is True assert satask(Q.irrational(x*y*z), Q.rational(x) & Q.rational(y) & Q.rational(z)) is False assert satask(Q.rational(x*y*z), Q.rational(x) & Q.rational(y) & Q.rational(z)) is True assert satask(Q.irrational(x + y + z), Q.rational(x) & Q.rational(y) & Q.rational(z)) is False assert satask(Q.rational(x + y + z), Q.rational(x) & Q.rational(y) & Q.rational(z)) is True def test_even_satask(): assert satask(Q.even(2)) is True assert satask(Q.even(3)) is False assert satask(Q.even(x*y), Q.even(x) & Q.odd(y)) is True assert satask(Q.even(x*y), Q.even(x) & Q.integer(y)) is True assert satask(Q.even(x*y), Q.even(x) & Q.even(y)) is True assert satask(Q.even(x*y), Q.odd(x) & Q.odd(y)) is False assert satask(Q.even(x*y), Q.even(x)) is None assert satask(Q.even(x*y), Q.odd(x) & Q.integer(y)) is None assert satask(Q.even(x*y), Q.odd(x) & Q.odd(y)) is False assert satask(Q.even(abs(x)), Q.even(x)) is True assert satask(Q.even(abs(x)), Q.odd(x)) is False assert satask(Q.even(x), Q.even(abs(x))) is None # x could be complex def test_odd_satask(): assert satask(Q.odd(2)) is False assert satask(Q.odd(3)) is True assert satask(Q.odd(x*y), Q.even(x) & Q.odd(y)) is False assert satask(Q.odd(x*y), Q.even(x) & Q.integer(y)) is False assert satask(Q.odd(x*y), Q.even(x) & Q.even(y)) is False assert satask(Q.odd(x*y), Q.odd(x) & Q.odd(y)) is True assert satask(Q.odd(x*y), Q.even(x)) is None assert satask(Q.odd(x*y), Q.odd(x) & Q.integer(y)) is None assert satask(Q.odd(x*y), Q.odd(x) & Q.odd(y)) is True assert satask(Q.odd(abs(x)), Q.even(x)) is False assert satask(Q.odd(abs(x)), Q.odd(x)) is True assert satask(Q.odd(x), Q.odd(abs(x))) is None # x could be complex def test_integer(): assert satask(Q.integer(1)) is True assert satask(Q.integer(S.Half)) is False assert satask(Q.integer(x + y), Q.integer(x) & Q.integer(y)) is True assert satask(Q.integer(x + y), Q.integer(x)) is None assert satask(Q.integer(x + y), Q.integer(x) & ~Q.integer(y)) is False assert satask(Q.integer(x + y + z), Q.integer(x) & Q.integer(y) & ~Q.integer(z)) is False assert satask(Q.integer(x + y + z), Q.integer(x) & ~Q.integer(y) & ~Q.integer(z)) is None assert satask(Q.integer(x + y + z), Q.integer(x) & ~Q.integer(y)) is None assert satask(Q.integer(x + y), Q.integer(x) & Q.irrational(y)) is False assert satask(Q.integer(x*y), Q.integer(x) & Q.integer(y)) is True assert satask(Q.integer(x*y), Q.integer(x)) is None assert satask(Q.integer(x*y), Q.integer(x) & ~Q.integer(y)) is None assert satask(Q.integer(x*y), Q.integer(x) & ~Q.rational(y)) is False assert satask(Q.integer(x*y*z), Q.integer(x) & Q.integer(y) & ~Q.rational(z)) is False assert satask(Q.integer(x*y*z), Q.integer(x) & ~Q.rational(y) & ~Q.rational(z)) is None assert satask(Q.integer(x*y*z), Q.integer(x) & ~Q.rational(y)) is None assert satask(Q.integer(x*y), Q.integer(x) & Q.irrational(y)) is False def test_abs(): assert satask(Q.nonnegative(abs(x))) is True assert satask(Q.positive(abs(x)), ~Q.zero(x)) is True assert satask(Q.zero(x), ~Q.zero(abs(x))) is False assert satask(Q.zero(x), Q.zero(abs(x))) is True assert satask(Q.nonzero(x), ~Q.zero(abs(x))) is None # x could be complex assert satask(Q.zero(abs(x)), Q.zero(x)) is True def test_imaginary(): assert satask(Q.imaginary(2*I)) is True assert satask(Q.imaginary(x*y), Q.imaginary(x)) is None assert satask(Q.imaginary(x*y), Q.imaginary(x) & Q.real(y)) is True assert satask(Q.imaginary(x), Q.real(x)) is False assert satask(Q.imaginary(1)) is False assert satask(Q.imaginary(x*y), Q.real(x) & Q.real(y)) is False assert satask(Q.imaginary(x + y), Q.real(x) & Q.real(y)) is False def test_real(): assert satask(Q.real(x*y), Q.real(x) & Q.real(y)) is True assert satask(Q.real(x + y), Q.real(x) & Q.real(y)) is True assert satask(Q.real(x*y*z), Q.real(x) & Q.real(y) & Q.real(z)) is True assert satask(Q.real(x*y*z), Q.real(x) & Q.real(y)) is None assert satask(Q.real(x*y*z), Q.real(x) & Q.real(y) & Q.imaginary(z)) is False assert satask(Q.real(x + y + z), Q.real(x) & Q.real(y) & Q.real(z)) is True assert satask(Q.real(x + y + z), Q.real(x) & Q.real(y)) is None def test_pos_neg(): assert satask(~Q.positive(x), Q.negative(x)) is True assert satask(~Q.negative(x), Q.positive(x)) is True assert satask(Q.positive(x + y), Q.positive(x) & Q.positive(y)) is True assert satask(Q.negative(x + y), Q.negative(x) & Q.negative(y)) is True assert satask(Q.positive(x + y), Q.negative(x) & Q.negative(y)) is False assert satask(Q.negative(x + y), Q.positive(x) & Q.positive(y)) is False def test_pow_pos_neg(): assert satask(Q.nonnegative(x**2), Q.positive(x)) is True assert satask(Q.nonpositive(x**2), Q.positive(x)) is False assert satask(Q.positive(x**2), Q.positive(x)) is True assert satask(Q.negative(x**2), Q.positive(x)) is False assert satask(Q.real(x**2), Q.positive(x)) is True assert satask(Q.nonnegative(x**2), Q.negative(x)) is True assert satask(Q.nonpositive(x**2), Q.negative(x)) is False assert satask(Q.positive(x**2), Q.negative(x)) is True assert satask(Q.negative(x**2), Q.negative(x)) is False assert satask(Q.real(x**2), Q.negative(x)) is True assert satask(Q.nonnegative(x**2), Q.nonnegative(x)) is True assert satask(Q.nonpositive(x**2), Q.nonnegative(x)) is None assert satask(Q.positive(x**2), Q.nonnegative(x)) is None assert satask(Q.negative(x**2), Q.nonnegative(x)) is False assert satask(Q.real(x**2), Q.nonnegative(x)) is True assert satask(Q.nonnegative(x**2), Q.nonpositive(x)) is True assert satask(Q.nonpositive(x**2), Q.nonpositive(x)) is None assert satask(Q.positive(x**2), Q.nonpositive(x)) is None assert satask(Q.negative(x**2), Q.nonpositive(x)) is False assert satask(Q.real(x**2), Q.nonpositive(x)) is True assert satask(Q.nonnegative(x**3), Q.positive(x)) is True assert satask(Q.nonpositive(x**3), Q.positive(x)) is False assert satask(Q.positive(x**3), Q.positive(x)) is True assert satask(Q.negative(x**3), Q.positive(x)) is False assert satask(Q.real(x**3), Q.positive(x)) is True assert satask(Q.nonnegative(x**3), Q.negative(x)) is False assert satask(Q.nonpositive(x**3), Q.negative(x)) is True assert satask(Q.positive(x**3), Q.negative(x)) is False assert satask(Q.negative(x**3), Q.negative(x)) is True assert satask(Q.real(x**3), Q.negative(x)) is True assert satask(Q.nonnegative(x**3), Q.nonnegative(x)) is True assert satask(Q.nonpositive(x**3), Q.nonnegative(x)) is None assert satask(Q.positive(x**3), Q.nonnegative(x)) is None assert satask(Q.negative(x**3), Q.nonnegative(x)) is False assert satask(Q.real(x**3), Q.nonnegative(x)) is True assert satask(Q.nonnegative(x**3), Q.nonpositive(x)) is None assert satask(Q.nonpositive(x**3), Q.nonpositive(x)) is True assert satask(Q.positive(x**3), Q.nonpositive(x)) is False assert satask(Q.negative(x**3), Q.nonpositive(x)) is None assert satask(Q.real(x**3), Q.nonpositive(x)) is True # If x is zero, x**negative is not real. assert satask(Q.nonnegative(x**-2), Q.nonpositive(x)) is None assert satask(Q.nonpositive(x**-2), Q.nonpositive(x)) is None assert satask(Q.positive(x**-2), Q.nonpositive(x)) is None assert satask(Q.negative(x**-2), Q.nonpositive(x)) is None assert satask(Q.real(x**-2), Q.nonpositive(x)) is None # We could deduce things for negative powers if x is nonzero, but it # isn't implemented yet. def test_prime_composite(): assert satask(Q.prime(x), Q.composite(x)) is False assert satask(Q.composite(x), Q.prime(x)) is False assert satask(Q.composite(x), ~Q.prime(x)) is None assert satask(Q.prime(x), ~Q.composite(x)) is None # since 1 is neither prime nor composite the following should hold assert satask(Q.prime(x), Q.integer(x) & Q.positive(x) & ~Q.composite(x)) is None assert satask(Q.prime(2)) is True assert satask(Q.prime(4)) is False assert satask(Q.prime(1)) is False assert satask(Q.composite(1)) is False def test_extract_predargs(): props = CNF.from_prop(Q.zero(Abs(x*y)) & Q.zero(x*y)) assump = CNF.from_prop(Q.zero(x)) context = CNF.from_prop(Q.zero(y)) assert extract_predargs(props) == {Abs(x*y), x*y} assert extract_predargs(props, assump) == {Abs(x*y), x*y, x} assert extract_predargs(props, assump, context) == {Abs(x*y), x*y, x, y} props = CNF.from_prop(Eq(x, y)) assump = CNF.from_prop(Gt(y, z)) assert extract_predargs(props, assump) == {x, y, z} def test_get_relevant_clsfacts(): exprs = {Abs(x*y)} exprs, facts = get_relevant_clsfacts(exprs) assert exprs == {x*y} assert facts.clauses == \ {frozenset({Literal(Q.odd(Abs(x*y)), False), Literal(Q.odd(x*y), True)}), frozenset({Literal(Q.zero(Abs(x*y)), False), Literal(Q.zero(x*y), True)}), frozenset({Literal(Q.even(Abs(x*y)), False), Literal(Q.even(x*y), True)}), frozenset({Literal(Q.zero(Abs(x*y)), True), Literal(Q.zero(x*y), False)}), frozenset({Literal(Q.even(Abs(x*y)), False), Literal(Q.odd(Abs(x*y)), False), Literal(Q.odd(x*y), True)}), frozenset({Literal(Q.even(Abs(x*y)), False), Literal(Q.even(x*y), True), Literal(Q.odd(Abs(x*y)), False)}), frozenset({Literal(Q.positive(Abs(x*y)), False), Literal(Q.zero(Abs(x*y)), False)})}
9f34a87ee6b0735f2135ef4d8f474dfe54de0f06b629b3e3b782b6aef6f7c66c
from sympy.assumptions.ask import (Q, ask) from sympy.core.symbol import Symbol from sympy.matrices.expressions.diagonal import (DiagMatrix, DiagonalMatrix) from sympy.matrices.dense import Matrix from sympy.matrices.expressions import (MatrixSymbol, Identity, ZeroMatrix, OneMatrix, Trace, MatrixSlice, Determinant, BlockMatrix, BlockDiagMatrix) from sympy.matrices.expressions.factorizations import LofLU from sympy.testing.pytest import XFAIL X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 3) Z = MatrixSymbol('Z', 2, 2) A1x1 = MatrixSymbol('A1x1', 1, 1) B1x1 = MatrixSymbol('B1x1', 1, 1) C0x0 = MatrixSymbol('C0x0', 0, 0) V1 = MatrixSymbol('V1', 2, 1) V2 = MatrixSymbol('V2', 2, 1) def test_square(): assert ask(Q.square(X)) assert not ask(Q.square(Y)) assert ask(Q.square(Y*Y.T)) def test_invertible(): assert ask(Q.invertible(X), Q.invertible(X)) assert ask(Q.invertible(Y)) is False assert ask(Q.invertible(X*Y), Q.invertible(X)) is False assert ask(Q.invertible(X*Z), Q.invertible(X)) is None assert ask(Q.invertible(X*Z), Q.invertible(X) & Q.invertible(Z)) is True assert ask(Q.invertible(X.T)) is None assert ask(Q.invertible(X.T), Q.invertible(X)) is True assert ask(Q.invertible(X.I)) is True assert ask(Q.invertible(Identity(3))) is True assert ask(Q.invertible(ZeroMatrix(3, 3))) is False assert ask(Q.invertible(OneMatrix(1, 1))) is True assert ask(Q.invertible(OneMatrix(3, 3))) is False assert ask(Q.invertible(X), Q.fullrank(X) & Q.square(X)) def test_singular(): assert ask(Q.singular(X)) is None assert ask(Q.singular(X), Q.invertible(X)) is False assert ask(Q.singular(X), ~Q.invertible(X)) is True @XFAIL def test_invertible_fullrank(): assert ask(Q.invertible(X), Q.fullrank(X)) is True def test_invertible_BlockMatrix(): assert ask(Q.invertible(BlockMatrix([Identity(3)]))) == True assert ask(Q.invertible(BlockMatrix([ZeroMatrix(3, 3)]))) == False X = Matrix([[1, 2, 3], [3, 5, 4]]) Y = Matrix([[4, 2, 7], [2, 3, 5]]) # non-invertible A block assert ask(Q.invertible(BlockMatrix([ [Matrix.ones(3, 3), Y.T], [X, Matrix.eye(2)], ]))) == True # non-invertible B block assert ask(Q.invertible(BlockMatrix([ [Y.T, Matrix.ones(3, 3)], [Matrix.eye(2), X], ]))) == True # non-invertible C block assert ask(Q.invertible(BlockMatrix([ [X, Matrix.eye(2)], [Matrix.ones(3, 3), Y.T], ]))) == True # non-invertible D block assert ask(Q.invertible(BlockMatrix([ [Matrix.eye(2), X], [Y.T, Matrix.ones(3, 3)], ]))) == True def test_invertible_BlockDiagMatrix(): assert ask(Q.invertible(BlockDiagMatrix(Identity(3), Identity(5)))) == True assert ask(Q.invertible(BlockDiagMatrix(ZeroMatrix(3, 3), Identity(5)))) == False assert ask(Q.invertible(BlockDiagMatrix(Identity(3), OneMatrix(5, 5)))) == False def test_symmetric(): assert ask(Q.symmetric(X), Q.symmetric(X)) assert ask(Q.symmetric(X*Z), Q.symmetric(X)) is None assert ask(Q.symmetric(X*Z), Q.symmetric(X) & Q.symmetric(Z)) is True assert ask(Q.symmetric(X + Z), Q.symmetric(X) & Q.symmetric(Z)) is True assert ask(Q.symmetric(Y)) is False assert ask(Q.symmetric(Y*Y.T)) is True assert ask(Q.symmetric(Y.T*X*Y)) is None assert ask(Q.symmetric(Y.T*X*Y), Q.symmetric(X)) is True assert ask(Q.symmetric(X**10), Q.symmetric(X)) is True assert ask(Q.symmetric(A1x1)) is True assert ask(Q.symmetric(A1x1 + B1x1)) is True assert ask(Q.symmetric(A1x1 * B1x1)) is True assert ask(Q.symmetric(V1.T*V1)) is True assert ask(Q.symmetric(V1.T*(V1 + V2))) is True assert ask(Q.symmetric(V1.T*(V1 + V2) + A1x1)) is True assert ask(Q.symmetric(MatrixSlice(Y, (0, 1), (1, 2)))) is True assert ask(Q.symmetric(Identity(3))) is True assert ask(Q.symmetric(ZeroMatrix(3, 3))) is True assert ask(Q.symmetric(OneMatrix(3, 3))) is True def _test_orthogonal_unitary(predicate): assert ask(predicate(X), predicate(X)) assert ask(predicate(X.T), predicate(X)) is True assert ask(predicate(X.I), predicate(X)) is True assert ask(predicate(X**2), predicate(X)) assert ask(predicate(Y)) is False assert ask(predicate(X)) is None assert ask(predicate(X), ~Q.invertible(X)) is False assert ask(predicate(X*Z*X), predicate(X) & predicate(Z)) is True assert ask(predicate(Identity(3))) is True assert ask(predicate(ZeroMatrix(3, 3))) is False assert ask(Q.invertible(X), predicate(X)) assert not ask(predicate(X + Z), predicate(X) & predicate(Z)) def test_orthogonal(): _test_orthogonal_unitary(Q.orthogonal) def test_unitary(): _test_orthogonal_unitary(Q.unitary) assert ask(Q.unitary(X), Q.orthogonal(X)) def test_fullrank(): assert ask(Q.fullrank(X), Q.fullrank(X)) assert ask(Q.fullrank(X**2), Q.fullrank(X)) assert ask(Q.fullrank(X.T), Q.fullrank(X)) is True assert ask(Q.fullrank(X)) is None assert ask(Q.fullrank(Y)) is None assert ask(Q.fullrank(X*Z), Q.fullrank(X) & Q.fullrank(Z)) is True assert ask(Q.fullrank(Identity(3))) is True assert ask(Q.fullrank(ZeroMatrix(3, 3))) is False assert ask(Q.fullrank(OneMatrix(1, 1))) is True assert ask(Q.fullrank(OneMatrix(3, 3))) is False assert ask(Q.invertible(X), ~Q.fullrank(X)) == False def test_positive_definite(): assert ask(Q.positive_definite(X), Q.positive_definite(X)) assert ask(Q.positive_definite(X.T), Q.positive_definite(X)) is True assert ask(Q.positive_definite(X.I), Q.positive_definite(X)) is True assert ask(Q.positive_definite(Y)) is False assert ask(Q.positive_definite(X)) is None assert ask(Q.positive_definite(X**3), Q.positive_definite(X)) assert ask(Q.positive_definite(X*Z*X), Q.positive_definite(X) & Q.positive_definite(Z)) is True assert ask(Q.positive_definite(X), Q.orthogonal(X)) assert ask(Q.positive_definite(Y.T*X*Y), Q.positive_definite(X) & Q.fullrank(Y)) is True assert not ask(Q.positive_definite(Y.T*X*Y), Q.positive_definite(X)) assert ask(Q.positive_definite(Identity(3))) is True assert ask(Q.positive_definite(ZeroMatrix(3, 3))) is False assert ask(Q.positive_definite(OneMatrix(1, 1))) is True assert ask(Q.positive_definite(OneMatrix(3, 3))) is False assert ask(Q.positive_definite(X + Z), Q.positive_definite(X) & Q.positive_definite(Z)) is True assert not ask(Q.positive_definite(-X), Q.positive_definite(X)) assert ask(Q.positive(X[1, 1]), Q.positive_definite(X)) def test_triangular(): assert ask(Q.upper_triangular(X + Z.T + Identity(2)), Q.upper_triangular(X) & Q.lower_triangular(Z)) is True assert ask(Q.upper_triangular(X*Z.T), Q.upper_triangular(X) & Q.lower_triangular(Z)) is True assert ask(Q.lower_triangular(Identity(3))) is True assert ask(Q.lower_triangular(ZeroMatrix(3, 3))) is True assert ask(Q.upper_triangular(ZeroMatrix(3, 3))) is True assert ask(Q.lower_triangular(OneMatrix(1, 1))) is True assert ask(Q.upper_triangular(OneMatrix(1, 1))) is True assert ask(Q.lower_triangular(OneMatrix(3, 3))) is False assert ask(Q.upper_triangular(OneMatrix(3, 3))) is False assert ask(Q.triangular(X), Q.unit_triangular(X)) assert ask(Q.upper_triangular(X**3), Q.upper_triangular(X)) assert ask(Q.lower_triangular(X**3), Q.lower_triangular(X)) def test_diagonal(): assert ask(Q.diagonal(X + Z.T + Identity(2)), Q.diagonal(X) & Q.diagonal(Z)) is True assert ask(Q.diagonal(ZeroMatrix(3, 3))) assert ask(Q.diagonal(OneMatrix(1, 1))) is True assert ask(Q.diagonal(OneMatrix(3, 3))) is False assert ask(Q.lower_triangular(X) & Q.upper_triangular(X), Q.diagonal(X)) assert ask(Q.diagonal(X), Q.lower_triangular(X) & Q.upper_triangular(X)) assert ask(Q.symmetric(X), Q.diagonal(X)) assert ask(Q.triangular(X), Q.diagonal(X)) assert ask(Q.diagonal(C0x0)) assert ask(Q.diagonal(A1x1)) assert ask(Q.diagonal(A1x1 + B1x1)) assert ask(Q.diagonal(A1x1*B1x1)) assert ask(Q.diagonal(V1.T*V2)) assert ask(Q.diagonal(V1.T*(X + Z)*V1)) assert ask(Q.diagonal(MatrixSlice(Y, (0, 1), (1, 2)))) is True assert ask(Q.diagonal(V1.T*(V1 + V2))) is True assert ask(Q.diagonal(X**3), Q.diagonal(X)) assert ask(Q.diagonal(Identity(3))) assert ask(Q.diagonal(DiagMatrix(V1))) assert ask(Q.diagonal(DiagonalMatrix(X))) def test_non_atoms(): assert ask(Q.real(Trace(X)), Q.positive(Trace(X))) @XFAIL def test_non_trivial_implies(): X = MatrixSymbol('X', 3, 3) Y = MatrixSymbol('Y', 3, 3) assert ask(Q.lower_triangular(X+Y), Q.lower_triangular(X) & Q.lower_triangular(Y)) is True assert ask(Q.triangular(X), Q.lower_triangular(X)) is True assert ask(Q.triangular(X+Y), Q.lower_triangular(X) & Q.lower_triangular(Y)) is True def test_MatrixSlice(): X = MatrixSymbol('X', 4, 4) B = MatrixSlice(X, (1, 3), (1, 3)) C = MatrixSlice(X, (0, 3), (1, 3)) assert ask(Q.symmetric(B), Q.symmetric(X)) assert ask(Q.invertible(B), Q.invertible(X)) assert ask(Q.diagonal(B), Q.diagonal(X)) assert ask(Q.orthogonal(B), Q.orthogonal(X)) assert ask(Q.upper_triangular(B), Q.upper_triangular(X)) assert not ask(Q.symmetric(C), Q.symmetric(X)) assert not ask(Q.invertible(C), Q.invertible(X)) assert not ask(Q.diagonal(C), Q.diagonal(X)) assert not ask(Q.orthogonal(C), Q.orthogonal(X)) assert not ask(Q.upper_triangular(C), Q.upper_triangular(X)) def test_det_trace_positive(): X = MatrixSymbol('X', 4, 4) assert ask(Q.positive(Trace(X)), Q.positive_definite(X)) assert ask(Q.positive(Determinant(X)), Q.positive_definite(X)) def test_field_assumptions(): X = MatrixSymbol('X', 4, 4) Y = MatrixSymbol('Y', 4, 4) assert ask(Q.real_elements(X), Q.real_elements(X)) assert not ask(Q.integer_elements(X), Q.real_elements(X)) assert ask(Q.complex_elements(X), Q.real_elements(X)) assert ask(Q.complex_elements(X**2), Q.real_elements(X)) assert ask(Q.real_elements(X**2), Q.integer_elements(X)) assert ask(Q.real_elements(X+Y), Q.real_elements(X)) is None assert ask(Q.real_elements(X+Y), Q.real_elements(X) & Q.real_elements(Y)) from sympy.matrices.expressions.hadamard import HadamardProduct assert ask(Q.real_elements(HadamardProduct(X, Y)), Q.real_elements(X) & Q.real_elements(Y)) assert ask(Q.complex_elements(X+Y), Q.real_elements(X) & Q.complex_elements(Y)) assert ask(Q.real_elements(X.T), Q.real_elements(X)) assert ask(Q.real_elements(X.I), Q.real_elements(X) & Q.invertible(X)) assert ask(Q.real_elements(Trace(X)), Q.real_elements(X)) assert ask(Q.integer_elements(Determinant(X)), Q.integer_elements(X)) assert not ask(Q.integer_elements(X.I), Q.integer_elements(X)) alpha = Symbol('alpha') assert ask(Q.real_elements(alpha*X), Q.real_elements(X) & Q.real(alpha)) assert ask(Q.real_elements(LofLU(X)), Q.real_elements(X)) e = Symbol('e', integer=True, negative=True) assert ask(Q.real_elements(X**e), Q.real_elements(X) & Q.invertible(X)) assert ask(Q.real_elements(X**e), Q.real_elements(X)) is None def test_matrix_element_sets(): X = MatrixSymbol('X', 4, 4) assert ask(Q.real(X[1, 2]), Q.real_elements(X)) assert ask(Q.integer(X[1, 2]), Q.integer_elements(X)) assert ask(Q.complex(X[1, 2]), Q.complex_elements(X)) assert ask(Q.integer_elements(Identity(3))) assert ask(Q.integer_elements(ZeroMatrix(3, 3))) assert ask(Q.integer_elements(OneMatrix(3, 3))) from sympy.matrices.expressions.fourier import DFT assert ask(Q.complex_elements(DFT(3))) def test_matrix_element_sets_slices_blocks(): X = MatrixSymbol('X', 4, 4) assert ask(Q.integer_elements(X[:, 3]), Q.integer_elements(X)) assert ask(Q.integer_elements(BlockMatrix([[X], [X]])), Q.integer_elements(X)) def test_matrix_element_sets_determinant_trace(): assert ask(Q.integer(Determinant(X)), Q.integer_elements(X)) assert ask(Q.integer(Trace(X)), Q.integer_elements(X))
8cc09941bdc6ea9550e4c1da493595ff47942c768217c328c2ed762e5ef6ae0b
from sympy.assumptions.ask import Q from sympy.core.basic import Basic from sympy.core.expr import Expr from sympy.core.mul import Mul from sympy.core.symbol import symbols from sympy.logic.boolalg import (And, Or) from sympy.assumptions.sathandlers import (ClassFactRegistry, allargs, anyarg, exactlyonearg,) x, y, z = symbols('x y z') def test_class_handler_registry(): my_handler_registry = ClassFactRegistry() # The predicate doesn't matter here, so just pass @my_handler_registry.register(Mul) def fact1(expr): pass @my_handler_registry.multiregister(Expr) def fact2(expr): pass assert my_handler_registry[Basic] == (frozenset(), frozenset()) assert my_handler_registry[Expr] == (frozenset(), frozenset({fact2})) assert my_handler_registry[Mul] == (frozenset({fact1}), frozenset({fact2})) def test_allargs(): assert allargs(x, Q.zero(x), x*y) == And(Q.zero(x), Q.zero(y)) assert allargs(x, Q.positive(x) | Q.negative(x), x*y) == And(Q.positive(x) | Q.negative(x), Q.positive(y) | Q.negative(y)) def test_anyarg(): assert anyarg(x, Q.zero(x), x*y) == Or(Q.zero(x), Q.zero(y)) assert anyarg(x, Q.positive(x) & Q.negative(x), x*y) == \ Or(Q.positive(x) & Q.negative(x), Q.positive(y) & Q.negative(y)) def test_exactlyonearg(): assert exactlyonearg(x, Q.zero(x), x*y) == \ Or(Q.zero(x) & ~Q.zero(y), Q.zero(y) & ~Q.zero(x)) assert exactlyonearg(x, Q.zero(x), x*y*z) == \ Or(Q.zero(x) & ~Q.zero(y) & ~Q.zero(z), Q.zero(y) & ~Q.zero(x) & ~Q.zero(z), Q.zero(z) & ~Q.zero(x) & ~Q.zero(y)) assert exactlyonearg(x, Q.positive(x) | Q.negative(x), x*y) == \ Or((Q.positive(x) | Q.negative(x)) & ~(Q.positive(y) | Q.negative(y)), (Q.positive(y) | Q.negative(y)) & ~(Q.positive(x) | Q.negative(x)))
281ed502d6906d449dc21f7f069d12eb7450c27d5e9f61ad7391dfb39d08c258
from sympy.assumptions.ask import Q from sympy.core.symbol import Symbol from sympy.assumptions.wrapper import (AssumptionsWrapper, is_infinite, is_extended_real) def test_AssumptionsWrapper(): x = Symbol('x', positive=True) y = Symbol('y') assert AssumptionsWrapper(x).is_positive assert AssumptionsWrapper(y).is_positive is None assert AssumptionsWrapper(y, Q.positive(y)).is_positive def test_is_infinite(): x = Symbol('x', infinite=True) y = Symbol('y', infinite=False) z = Symbol('z') assert is_infinite(x) assert not is_infinite(y) assert is_infinite(z) is None assert is_infinite(z, Q.infinite(z)) def test_is_extended_real(): x = Symbol('x', extended_real=True) y = Symbol('y', extended_real=False) z = Symbol('z') assert is_extended_real(x) assert not is_extended_real(y) assert is_extended_real(z) is None assert is_extended_real(z, Q.extended_real(z))
76952670a7f58a8643ca0717255765cea2c76efe73808fddeca8387a7da7e55d
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 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, finite=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('mp1') mp2 = MyPredicate('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))
4e3a3217bc1de9faf85f377e644919531174eda336cd4957ff6e959118654867
""" 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 not m 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))))
78d9a32a83feca81b85e07c704da166766337507d819895c4242c38a0b9638ab
from typing import List from functools import reduce from sympy.core import S, sympify, Dummy, Mod from sympy.core.cache import cacheit from sympy.core.function import Function, ArgumentIndexError, PoleError from sympy.core.logic import fuzzy_and from sympy.core.numbers import Integer, pi, I from sympy.core.relational import Eq from sympy.external.gmpy import HAS_GMPY, gmpy from sympy.ntheory import sieve from sympy.polys.polytools import Poly from math import sqrt as _sqrt class CombinatorialFunction(Function): """Base class for combinatorial functions. """ def _eval_simplify(self, **kwargs): from sympy.simplify.combsimp import combsimp # combinatorial function with non-integer arguments is # automatically passed to gammasimp expr = combsimp(self) measure = kwargs['measure'] if measure(expr) <= kwargs['ratio']*measure(self): return expr return self ############################################################################### ######################## FACTORIAL and MULTI-FACTORIAL ######################## ############################################################################### class factorial(CombinatorialFunction): r"""Implementation of factorial function over nonnegative integers. By convention (consistent with the gamma function and the binomial coefficients), factorial of a negative integer is complex infinity. The factorial is very important in combinatorics where it gives the number of ways in which `n` objects can be permuted. It also arises in calculus, probability, number theory, etc. There is strict relation of factorial with gamma function. In fact `n! = gamma(n+1)` for nonnegative integers. Rewrite of this kind is very useful in case of combinatorial simplification. Computation of the factorial is done using two algorithms. For small arguments a precomputed look up table is used. However for bigger input algorithm Prime-Swing is used. It is the fastest algorithm known and computes `n!` via prime factorization of special class of numbers, called here the 'Swing Numbers'. Examples ======== >>> from sympy import Symbol, factorial, S >>> n = Symbol('n', integer=True) >>> factorial(0) 1 >>> factorial(7) 5040 >>> factorial(-2) zoo >>> factorial(n) factorial(n) >>> factorial(2*n) factorial(2*n) >>> factorial(S(1)/2) factorial(1/2) See Also ======== factorial2, RisingFactorial, FallingFactorial """ def fdiff(self, argindex=1): from sympy.functions.special.gamma_functions import (gamma, polygamma) if argindex == 1: return gamma(self.args[0] + 1)*polygamma(0, self.args[0] + 1) else: raise ArgumentIndexError(self, argindex) _small_swing = [ 1, 1, 1, 3, 3, 15, 5, 35, 35, 315, 63, 693, 231, 3003, 429, 6435, 6435, 109395, 12155, 230945, 46189, 969969, 88179, 2028117, 676039, 16900975, 1300075, 35102025, 5014575, 145422675, 9694845, 300540195, 300540195 ] _small_factorials = [] # type: List[int] @classmethod def _swing(cls, n): if n < 33: return cls._small_swing[n] else: N, primes = int(_sqrt(n)), [] for prime in sieve.primerange(3, N + 1): p, q = 1, n while True: q //= prime if q > 0: if q & 1 == 1: p *= prime else: break if p > 1: primes.append(p) for prime in sieve.primerange(N + 1, n//3 + 1): if (n // prime) & 1 == 1: primes.append(prime) L_product = R_product = 1 for prime in sieve.primerange(n//2 + 1, n + 1): L_product *= prime for prime in primes: R_product *= prime return L_product*R_product @classmethod def _recursive(cls, n): if n < 2: return 1 else: return (cls._recursive(n//2)**2)*cls._swing(n) @classmethod def eval(cls, n): n = sympify(n) if n.is_Number: if n.is_zero: return S.One elif n is S.Infinity: return S.Infinity elif n.is_Integer: if n.is_negative: return S.ComplexInfinity else: n = n.p if n < 20: if not cls._small_factorials: result = 1 for i in range(1, 20): result *= i cls._small_factorials.append(result) result = cls._small_factorials[n-1] # GMPY factorial is faster, use it when available elif HAS_GMPY: result = gmpy.fac(n) else: bits = bin(n).count('1') result = cls._recursive(n)*2**(n - bits) return Integer(result) def _facmod(self, n, q): res, N = 1, int(_sqrt(n)) # Exponent of prime p in n! is e_p(n) = [n/p] + [n/p**2] + ... # for p > sqrt(n), e_p(n) < sqrt(n), the primes with [n/p] = m, # occur consecutively and are grouped together in pw[m] for # simultaneous exponentiation at a later stage pw = [1]*N m = 2 # to initialize the if condition below for prime in sieve.primerange(2, n + 1): if m > 1: m, y = 0, n // prime while y: m += y y //= prime if m < N: pw[m] = pw[m]*prime % q else: res = res*pow(prime, m, q) % q for ex, bs in enumerate(pw): if ex == 0 or bs == 1: continue if bs == 0: return 0 res = res*pow(bs, ex, q) % q return res def _eval_Mod(self, q): n = self.args[0] if n.is_integer and n.is_nonnegative and q.is_integer: aq = abs(q) d = aq - n if d.is_nonpositive: return S.Zero else: isprime = aq.is_prime if d == 1: # Apply Wilson's theorem (if a natural number n > 1 # is a prime number, then (n-1)! = -1 mod n) and # its inverse (if n > 4 is a composite number, then # (n-1)! = 0 mod n) if isprime: return -1 % q elif isprime is False and (aq - 6).is_nonnegative: return S.Zero elif n.is_Integer and q.is_Integer: n, d, aq = map(int, (n, d, aq)) if isprime and (d - 1 < n): fc = self._facmod(d - 1, aq) fc = pow(fc, aq - 2, aq) if d%2: fc = -fc else: fc = self._facmod(n, aq) return fc % q def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs): from sympy.functions.special.gamma_functions import gamma return gamma(n + 1) def _eval_rewrite_as_Product(self, n, **kwargs): from sympy.concrete.products import Product if n.is_nonnegative and n.is_integer: i = Dummy('i', integer=True) return Product(i, (i, 1, 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_integer and self.args[0].is_nonnegative: return True def _eval_is_even(self): x = self.args[0] if x.is_integer and x.is_nonnegative: return (x - 2).is_nonnegative def _eval_is_composite(self): x = self.args[0] if x.is_integer and x.is_nonnegative: return (x - 3).is_nonnegative def _eval_is_real(self): x = self.args[0] if x.is_nonnegative or x.is_noninteger: return True def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[0].as_leading_term(x) arg0 = arg.subs(x, 0) if arg0.is_zero: return S.One elif not arg0.is_infinite: return self.func(arg) raise PoleError("Cannot expand %s around 0" % (self)) class MultiFactorial(CombinatorialFunction): pass class subfactorial(CombinatorialFunction): r"""The subfactorial counts the derangements of n items and is defined for non-negative integers as: .. math:: !n = \begin{cases} 1 & n = 0 \\ 0 & n = 1 \\ (n-1)(!(n-1) + !(n-2)) & n > 1 \end{cases} It can also be written as ``int(round(n!/exp(1)))`` but the recursive definition with caching is implemented for this function. An interesting analytic expression is the following [2]_ .. math:: !x = \Gamma(x + 1, -1)/e which is valid for non-negative integers `x`. The above formula is not very useful incase of non-integers. :math:`\Gamma(x + 1, -1)` is single-valued only for integral arguments `x`, elsewhere on the positive real axis it has an infinite number of branches none of which are real. References ========== .. [1] https://en.wikipedia.org/wiki/Subfactorial .. [2] http://mathworld.wolfram.com/Subfactorial.html Examples ======== >>> from sympy import subfactorial >>> from sympy.abc import n >>> subfactorial(n + 1) subfactorial(n + 1) >>> subfactorial(5) 44 See Also ======== sympy.functions.combinatorial.factorials.factorial, sympy.utilities.iterables.generate_derangements, sympy.functions.special.gamma_functions.uppergamma """ @classmethod @cacheit def _eval(self, n): if not n: return S.One elif n == 1: return S.Zero else: z1, z2 = 1, 0 for i in range(2, n + 1): z1, z2 = z2, (i - 1)*(z2 + z1) return z2 @classmethod def eval(cls, arg): if arg.is_Number: if arg.is_Integer and arg.is_nonnegative: return cls._eval(arg) elif arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity def _eval_is_even(self): if self.args[0].is_odd and self.args[0].is_nonnegative: return True def _eval_is_integer(self): if self.args[0].is_integer and self.args[0].is_nonnegative: return True def _eval_rewrite_as_factorial(self, arg, **kwargs): from sympy.concrete.summations import summation i = Dummy('i') f = S.NegativeOne**i / factorial(i) return factorial(arg) * summation(f, (i, 0, arg)) def _eval_rewrite_as_gamma(self, arg, piecewise=True, **kwargs): from sympy.functions.elementary.exponential import exp from sympy.functions.special.gamma_functions import (gamma, lowergamma) return (S.NegativeOne**(arg + 1)*exp(-I*pi*arg)*lowergamma(arg + 1, -1) + gamma(arg + 1))*exp(-1) def _eval_rewrite_as_uppergamma(self, arg, **kwargs): from sympy.functions.special.gamma_functions import uppergamma return uppergamma(arg + 1, -1)/S.Exp1 def _eval_is_nonnegative(self): if self.args[0].is_integer and self.args[0].is_nonnegative: return True def _eval_is_odd(self): if self.args[0].is_even and self.args[0].is_nonnegative: return True class factorial2(CombinatorialFunction): r"""The double factorial `n!!`, not to be confused with `(n!)!` The double factorial is defined for nonnegative integers and for odd negative integers as: .. math:: n!! = \begin{cases} 1 & n = 0 \\ n(n-2)(n-4) \cdots 1 & n\ \text{positive odd} \\ n(n-2)(n-4) \cdots 2 & n\ \text{positive even} \\ (n+2)!!/(n+2) & n\ \text{negative odd} \end{cases} References ========== .. [1] https://en.wikipedia.org/wiki/Double_factorial Examples ======== >>> from sympy import factorial2, var >>> n = var('n') >>> n n >>> factorial2(n + 1) factorial2(n + 1) >>> factorial2(5) 15 >>> factorial2(-1) 1 >>> factorial2(-5) 1/3 See Also ======== factorial, RisingFactorial, FallingFactorial """ @classmethod def eval(cls, arg): # TODO: extend this to complex numbers? if arg.is_Number: if not arg.is_Integer: raise ValueError("argument must be nonnegative integer " "or negative odd integer") # This implementation is faster than the recursive one # It also avoids "maximum recursion depth exceeded" runtime error if arg.is_nonnegative: if arg.is_even: k = arg / 2 return 2**k * factorial(k) return factorial(arg) / factorial2(arg - 1) if arg.is_odd: return arg*(S.NegativeOne)**((1 - arg)/2) / factorial2(-arg) raise ValueError("argument must be nonnegative integer " "or negative odd integer") def _eval_is_even(self): # Double factorial is even for every positive even input n = self.args[0] if n.is_integer: if n.is_odd: return False if n.is_even: if n.is_positive: return True if n.is_zero: return False def _eval_is_integer(self): # Double factorial is an integer for every nonnegative input, and for # -1 and -3 n = self.args[0] if n.is_integer: if (n + 1).is_nonnegative: return True if n.is_odd: return (n + 3).is_nonnegative def _eval_is_odd(self): # Double factorial is odd for every odd input not smaller than -3, and # for 0 n = self.args[0] if n.is_odd: return (n + 3).is_nonnegative if n.is_even: if n.is_positive: return False if n.is_zero: return True def _eval_is_positive(self): # Double factorial is positive for every nonnegative input, and for # every odd negative input which is of the form -1-4k for an # nonnegative integer k n = self.args[0] if n.is_integer: if (n + 1).is_nonnegative: return True if n.is_odd: return ((n + 1) / 2).is_even def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs): from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.special.gamma_functions import gamma return 2**(n/2)*gamma(n/2 + 1) * Piecewise((1, Eq(Mod(n, 2), 0)), (sqrt(2/pi), Eq(Mod(n, 2), 1))) ############################################################################### ######################## RISING and FALLING FACTORIALS ######################## ############################################################################### class RisingFactorial(CombinatorialFunction): r""" Rising factorial (also called Pochhammer symbol) is a double valued function arising in concrete mathematics, hypergeometric functions and series expansions. It is defined by: .. math:: rf(x,k) = x \cdot (x+1) \cdots (x+k-1) where `x` can be arbitrary expression and `k` is an integer. For more information check "Concrete mathematics" by Graham, pp. 66 or visit http://mathworld.wolfram.com/RisingFactorial.html page. When `x` is a Poly instance of degree >= 1 with a single variable, `rf(x,k) = x(y) \cdot x(y+1) \cdots x(y+k-1)`, where `y` is the variable of `x`. This is as described in Peter Paule, "Greatest Factorial Factorization and Symbolic Summation", Journal of Symbolic Computation, vol. 20, pp. 235-268, 1995. Examples ======== >>> from sympy import rf, Poly >>> from sympy.abc import x >>> rf(x, 0) 1 >>> rf(1, 5) 120 >>> rf(x, 5) == x*(1 + x)*(2 + x)*(3 + x)*(4 + x) True >>> rf(Poly(x**3, x), 2) Poly(x**6 + 3*x**5 + 3*x**4 + x**3, x, domain='ZZ') Rewriting is complicated unless the relationship between the arguments is known, but rising factorial can be rewritten in terms of gamma, factorial and binomial and falling factorial. >>> from sympy import Symbol, factorial, ff, binomial, gamma >>> n = Symbol('n', integer=True, positive=True) >>> R = rf(n, n + 2) >>> for i in (rf, ff, factorial, binomial, gamma): ... R.rewrite(i) ... RisingFactorial(n, n + 2) FallingFactorial(2*n + 1, n + 2) factorial(2*n + 1)/factorial(n - 1) binomial(2*n + 1, n + 2)*factorial(n + 2) gamma(2*n + 2)/gamma(n) See Also ======== factorial, factorial2, FallingFactorial References ========== .. [1] https://en.wikipedia.org/wiki/Pochhammer_symbol """ @classmethod def eval(cls, x, k): x = sympify(x) k = sympify(k) if x is S.NaN or k is S.NaN: return S.NaN elif x is S.One: return factorial(k) elif k.is_Integer: if k.is_zero: return S.One else: if k.is_positive: if x is S.Infinity: return S.Infinity elif x is S.NegativeInfinity: if k.is_odd: return S.NegativeInfinity else: return S.Infinity else: if isinstance(x, Poly): gens = x.gens if len(gens)!= 1: raise ValueError("rf only defined for " "polynomials on one generator") else: return reduce(lambda r, i: r*(x.shift(i)), range(0, int(k)), 1) else: return reduce(lambda r, i: r*(x + i), range(0, int(k)), 1) else: if x is S.Infinity: return S.Infinity elif x is S.NegativeInfinity: return S.Infinity else: if isinstance(x, Poly): gens = x.gens if len(gens)!= 1: raise ValueError("rf only defined for " "polynomials on one generator") else: return 1/reduce(lambda r, i: r*(x.shift(-i)), range(1, abs(int(k)) + 1), 1) else: return 1/reduce(lambda r, i: r*(x - i), range(1, abs(int(k)) + 1), 1) if k.is_integer == False: if x.is_integer and x.is_negative: return S.Zero def _eval_rewrite_as_gamma(self, x, k, piecewise=True, **kwargs): from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.special.gamma_functions import gamma if not piecewise: if (x <= 0) == True: return S.NegativeOne**k*gamma(1 - x) / gamma(-k - x + 1) return gamma(x + k) / gamma(x) return Piecewise( (gamma(x + k) / gamma(x), x > 0), (S.NegativeOne**k*gamma(1 - x) / gamma(-k - x + 1), True)) def _eval_rewrite_as_FallingFactorial(self, x, k, **kwargs): return FallingFactorial(x + k - 1, k) def _eval_rewrite_as_factorial(self, x, k, **kwargs): from sympy.functions.elementary.piecewise import Piecewise if x.is_integer and k.is_integer: return Piecewise( (factorial(k + x - 1)/factorial(x - 1), x > 0), (S.NegativeOne**k*factorial(-x)/factorial(-k - x), True)) def _eval_rewrite_as_binomial(self, x, k, **kwargs): if k.is_integer: return factorial(k) * binomial(x + k - 1, k) def _eval_rewrite_as_tractable(self, x, k, limitvar=None, **kwargs): from sympy.functions.special.gamma_functions import gamma if limitvar: k_lim = k.subs(limitvar, S.Infinity) if k_lim is S.Infinity: return (gamma(x + k).rewrite('tractable', deep=True) / gamma(x)) elif k_lim is S.NegativeInfinity: return (S.NegativeOne**k*gamma(1 - x) / gamma(-k - x + 1).rewrite('tractable', deep=True)) return self.rewrite(gamma).rewrite('tractable', deep=True) def _eval_is_integer(self): return fuzzy_and((self.args[0].is_integer, self.args[1].is_integer, self.args[1].is_nonnegative)) class FallingFactorial(CombinatorialFunction): r""" Falling factorial (related to rising factorial) is a double valued function arising in concrete mathematics, hypergeometric functions and series expansions. It is defined by .. math:: ff(x,k) = x \cdot (x-1) \cdots (x-k+1) where `x` can be arbitrary expression and `k` is an integer. For more information check "Concrete mathematics" by Graham, pp. 66 or visit http://mathworld.wolfram.com/FallingFactorial.html page. When `x` is a Poly instance of degree >= 1 with single variable, `ff(x,k) = x(y) \cdot x(y-1) \cdots x(y-k+1)`, where `y` is the variable of `x`. This is as described in Peter Paule, "Greatest Factorial Factorization and Symbolic Summation", Journal of Symbolic Computation, vol. 20, pp. 235-268, 1995. >>> from sympy import ff, Poly, Symbol >>> from sympy.abc import x >>> n = Symbol('n', integer=True) >>> ff(x, 0) 1 >>> ff(5, 5) 120 >>> ff(x, 5) == x*(x - 1)*(x - 2)*(x - 3)*(x - 4) True >>> ff(Poly(x**2, x), 2) Poly(x**4 - 2*x**3 + x**2, x, domain='ZZ') >>> ff(n, n) factorial(n) Rewriting is complicated unless the relationship between the arguments is known, but falling factorial can be rewritten in terms of gamma, factorial and binomial and rising factorial. >>> from sympy import factorial, rf, gamma, binomial, Symbol >>> n = Symbol('n', integer=True, positive=True) >>> F = ff(n, n - 2) >>> for i in (rf, ff, factorial, binomial, gamma): ... F.rewrite(i) ... RisingFactorial(3, n - 2) FallingFactorial(n, n - 2) factorial(n)/2 binomial(n, n - 2)*factorial(n - 2) gamma(n + 1)/2 See Also ======== factorial, factorial2, RisingFactorial References ========== .. [1] http://mathworld.wolfram.com/FallingFactorial.html """ @classmethod def eval(cls, x, k): x = sympify(x) k = sympify(k) if x is S.NaN or k is S.NaN: return S.NaN elif k.is_integer and x == k: return factorial(x) elif k.is_Integer: if k.is_zero: return S.One else: if k.is_positive: if x is S.Infinity: return S.Infinity elif x is S.NegativeInfinity: if k.is_odd: return S.NegativeInfinity else: return S.Infinity else: if isinstance(x, Poly): gens = x.gens if len(gens)!= 1: raise ValueError("ff only defined for " "polynomials on one generator") else: return reduce(lambda r, i: r*(x.shift(-i)), range(0, int(k)), 1) else: return reduce(lambda r, i: r*(x - i), range(0, int(k)), 1) else: if x is S.Infinity: return S.Infinity elif x is S.NegativeInfinity: return S.Infinity else: if isinstance(x, Poly): gens = x.gens if len(gens)!= 1: raise ValueError("rf only defined for " "polynomials on one generator") else: return 1/reduce(lambda r, i: r*(x.shift(i)), range(1, abs(int(k)) + 1), 1) else: return 1/reduce(lambda r, i: r*(x + i), range(1, abs(int(k)) + 1), 1) def _eval_rewrite_as_gamma(self, x, k, piecewise=True, **kwargs): from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.special.gamma_functions import gamma if not piecewise: if (x < 0) == True: return S.NegativeOne**k*gamma(k - x) / gamma(-x) return gamma(x + 1) / gamma(x - k + 1) return Piecewise( (gamma(x + 1) / gamma(x - k + 1), x >= 0), (S.NegativeOne**k*gamma(k - x) / gamma(-x), True)) def _eval_rewrite_as_RisingFactorial(self, x, k, **kwargs): return rf(x - k + 1, k) def _eval_rewrite_as_binomial(self, x, k, **kwargs): if k.is_integer: return factorial(k) * binomial(x, k) def _eval_rewrite_as_factorial(self, x, k, **kwargs): from sympy.functions.elementary.piecewise import Piecewise if x.is_integer and k.is_integer: return Piecewise( (factorial(x)/factorial(-k + x), x >= 0), (S.NegativeOne**k*factorial(k - x - 1)/factorial(-x - 1), True)) def _eval_rewrite_as_tractable(self, x, k, limitvar=None, **kwargs): from sympy.functions.special.gamma_functions import gamma if limitvar: k_lim = k.subs(limitvar, S.Infinity) if k_lim is S.Infinity: return (S.NegativeOne**k*gamma(k - x).rewrite('tractable', deep=True) / gamma(-x)) elif k_lim is S.NegativeInfinity: return (gamma(x + 1) / gamma(x - k + 1).rewrite('tractable', deep=True)) return self.rewrite(gamma).rewrite('tractable', deep=True) def _eval_is_integer(self): return fuzzy_and((self.args[0].is_integer, self.args[1].is_integer, self.args[1].is_nonnegative)) rf = RisingFactorial ff = FallingFactorial ############################################################################### ########################### BINOMIAL COEFFICIENTS ############################# ############################################################################### class binomial(CombinatorialFunction): r"""Implementation of the binomial coefficient. It can be defined in two ways depending on its desired interpretation: .. math:: \binom{n}{k} = \frac{n!}{k!(n-k)!}\ \text{or}\ \binom{n}{k} = \frac{ff(n, k)}{k!} First, in a strict combinatorial sense it defines the number of ways we can choose `k` elements from a set of `n` elements. In this case both arguments are nonnegative integers and binomial is computed using an efficient algorithm based on prime factorization. The other definition is generalization for arbitrary `n`, however `k` must also be nonnegative. This case is very useful when evaluating summations. For the sake of convenience for negative integer `k` this function will return zero no matter what valued is the other argument. To expand the binomial when `n` is a symbol, use either ``expand_func()`` or ``expand(func=True)``. The former will keep the polynomial in factored form while the latter will expand the polynomial itself. See examples for details. Examples ======== >>> from sympy import Symbol, Rational, binomial, expand_func >>> n = Symbol('n', integer=True, positive=True) >>> binomial(15, 8) 6435 >>> binomial(n, -1) 0 Rows of Pascal's triangle can be generated with the binomial function: >>> for N in range(8): ... print([binomial(N, i) for i in range(N + 1)]) ... [1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1] [1, 5, 10, 10, 5, 1] [1, 6, 15, 20, 15, 6, 1] [1, 7, 21, 35, 35, 21, 7, 1] As can a given diagonal, e.g. the 4th diagonal: >>> N = -4 >>> [binomial(N, i) for i in range(1 - N)] [1, -4, 10, -20, 35] >>> binomial(Rational(5, 4), 3) -5/128 >>> binomial(Rational(-5, 4), 3) -195/128 >>> binomial(n, 3) binomial(n, 3) >>> binomial(n, 3).expand(func=True) n**3/6 - n**2/2 + n/3 >>> expand_func(binomial(n, 3)) n*(n - 2)*(n - 1)/6 References ========== .. [1] https://www.johndcook.com/blog/binomial_coefficients/ """ def fdiff(self, argindex=1): from sympy.functions.special.gamma_functions import polygamma if argindex == 1: # http://functions.wolfram.com/GammaBetaErf/Binomial/20/01/01/ n, k = self.args return binomial(n, k)*(polygamma(0, n + 1) - \ polygamma(0, n - k + 1)) elif argindex == 2: # http://functions.wolfram.com/GammaBetaErf/Binomial/20/01/02/ n, k = self.args return binomial(n, k)*(polygamma(0, n - k + 1) - \ polygamma(0, k + 1)) else: raise ArgumentIndexError(self, argindex) @classmethod def _eval(self, n, k): # n.is_Number and k.is_Integer and k != 1 and n != k if k.is_Integer: if n.is_Integer and n >= 0: n, k = int(n), int(k) if k > n: return S.Zero elif k > n // 2: k = n - k if HAS_GMPY: return Integer(gmpy.bincoef(n, k)) d, result = n - k, 1 for i in range(1, k + 1): d += 1 result = result * d // i return Integer(result) else: d, result = n - k, 1 for i in range(1, k + 1): d += 1 result *= d result /= i return result @classmethod def eval(cls, n, k): n, k = map(sympify, (n, k)) d = n - k n_nonneg, n_isint = n.is_nonnegative, n.is_integer if k.is_zero or ((n_nonneg or n_isint is False) and d.is_zero): return S.One if (k - 1).is_zero or ((n_nonneg or n_isint is False) and (d - 1).is_zero): return n if k.is_integer: if k.is_negative or (n_nonneg and n_isint and d.is_negative): return S.Zero elif n.is_number: res = cls._eval(n, k) return res.expand(basic=True) if res else res elif n_nonneg is False and n_isint: # a special case when binomial evaluates to complex infinity return S.ComplexInfinity elif k.is_number: from sympy.functions.special.gamma_functions import gamma return gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1)) def _eval_Mod(self, q): n, k = self.args if any(x.is_integer is False for x in (n, k, q)): raise ValueError("Integers expected for binomial Mod") if all(x.is_Integer for x in (n, k, q)): n, k = map(int, (n, k)) aq, res = abs(q), 1 # handle negative integers k or n if k < 0: return S.Zero if n < 0: n = -n + k - 1 res = -1 if k%2 else 1 # non negative integers k and n if k > n: return S.Zero isprime = aq.is_prime aq = int(aq) if isprime: if aq < n: # use Lucas Theorem N, K = n, k while N or K: res = res*binomial(N % aq, K % aq) % aq N, K = N // aq, K // aq else: # use Factorial Modulo d = n - k if k > d: k, d = d, k kf = 1 for i in range(2, k + 1): kf = kf*i % aq df = kf for i in range(k + 1, d + 1): df = df*i % aq res *= df for i in range(d + 1, n + 1): res = res*i % aq res *= pow(kf*df % aq, aq - 2, aq) res %= aq else: # Binomial Factorization is performed by calculating the # exponents of primes <= n in `n! /(k! (n - k)!)`, # for non-negative integers n and k. As the exponent of # prime in n! is e_p(n) = [n/p] + [n/p**2] + ... # the exponent of prime in binomial(n, k) would be # e_p(n) - e_p(k) - e_p(n - k) M = int(_sqrt(n)) for prime in sieve.primerange(2, n + 1): if prime > n - k: res = res*prime % aq elif prime > n // 2: continue elif prime > M: if n % prime < k % prime: res = res*prime % aq else: N, K = n, k exp = a = 0 while N > 0: a = int((N % prime) < (K % prime + a)) N, K = N // prime, K // prime exp += a if exp > 0: res *= pow(prime, exp, aq) res %= aq return S(res % q) def _eval_expand_func(self, **hints): """ Function to expand binomial(n, k) when m is positive integer Also, n is self.args[0] and k is self.args[1] while using binomial(n, k) """ n = self.args[0] if n.is_Number: return binomial(*self.args) k = self.args[1] if (n-k).is_Integer: k = n - k if k.is_Integer: if k.is_zero: return S.One elif k.is_negative: return S.Zero else: n, result = self.args[0], 1 for i in range(1, k + 1): result *= n - k + i result /= i return result else: return binomial(*self.args) def _eval_rewrite_as_factorial(self, n, k, **kwargs): return factorial(n)/(factorial(k)*factorial(n - k)) def _eval_rewrite_as_gamma(self, n, k, piecewise=True, **kwargs): from sympy.functions.special.gamma_functions import gamma return gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1)) def _eval_rewrite_as_tractable(self, n, k, limitvar=None, **kwargs): return self._eval_rewrite_as_gamma(n, k).rewrite('tractable') def _eval_rewrite_as_FallingFactorial(self, n, k, **kwargs): if k.is_integer: return ff(n, k) / factorial(k) def _eval_is_integer(self): n, k = self.args if n.is_integer and k.is_integer: return True elif k.is_integer is False: return False def _eval_is_nonnegative(self): n, k = self.args if n.is_integer and k.is_integer: if n.is_nonnegative or k.is_negative or k.is_even: return True elif k.is_even is False: return False def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.functions.special.gamma_functions import gamma return self.rewrite(gamma)._eval_as_leading_term(x, logx=logx, cdir=cdir)
f5ef6fd705008447bca804fa42b8d27e42043ab421dfca59126e102939925565
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.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 import AccumBounds from sympy.sets.setexpr import SetExpr 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.util 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.util import AccumBounds from sympy.sets.setexpr import SetExpr 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.util 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.util 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.util 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.util 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)
677596a478dfd406ce1c80b6e50e39cf93c267d00d66fd151eeb7c917145c108
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) Traceback (most recent call last): ... sympy.core.sympify.SympifyError: SympifyError: <function sqrt at 0x10e8900d0> 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
f519f1665ccece26438d621651719099e3d6ede911082f3ea59cb918053ae3d0
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.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) if sum == Undefined: sum = 0 sum += anti._eval_interval(x, a, x) # 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)
2bca0e8d69dfdb3865d9fead736818f86d059e94c72df9da96884fd4da5753d1
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.util 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.util 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.util 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
ba7457dc5816f3576a1e1ad961921530a40346d4c618a15e53f52b61d36e385c
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 # 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.sets.setexpr import SetExpr 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 not self.args[0] is 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.sets.setexpr import SetExpr 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])
65e740e218f41240602b009851e687bab931479e56cb98448ba38b581e0ad5f1
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.util 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.util 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
7f2eb3a394e54321860c9ea7a19918bfad588f3b1fbccb08654ebb6aab4ecafd
from typing import Tuple as tTuple from sympy.core import S, Add, Mul, sympify, Symbol, Dummy, Basic from sympy.core.expr import Expr from sympy.core.exprtools import factor_terms from sympy.core.function import (Function, Derivative, ArgumentIndexError, AppliedUndef, expand_mul) from sympy.core.logic import fuzzy_not, fuzzy_or from sympy.core.numbers import pi, I, oo from sympy.core.power import Pow from sympy.core.relational import Eq from sympy.functions.elementary.exponential import exp, exp_polar, log from sympy.functions.elementary.integers import ceiling from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import atan, atan2 ############################################################################### ######################### REAL and IMAGINARY PARTS ############################ ############################################################################### class re(Function): """ Returns real part of expression. This function performs only elementary analysis and so it will fail to decompose properly more complicated expressions. If completely simplified result is needed then use Basic.as_real_imag() or perform complex expansion on instance of this function. Examples ======== >>> from sympy import re, im, I, E, symbols >>> x, y = symbols('x y', real=True) >>> re(2*E) 2*E >>> re(2*I + 17) 17 >>> re(2*I) 0 >>> re(im(x) + x*I + 2) 2 >>> re(5 + I + 2) 7 Parameters ========== arg : Expr Real or complex expression. Returns ======= expr : Expr Real part of expression. See Also ======== im """ args: tTuple[Expr] is_extended_real = True unbranched = True # implicitly works on the projection to C _singularities = True # non-holomorphic @classmethod def eval(cls, arg): if arg is S.NaN: return S.NaN elif arg is S.ComplexInfinity: return S.NaN elif arg.is_extended_real: return arg elif arg.is_imaginary or (S.ImaginaryUnit*arg).is_extended_real: return S.Zero elif arg.is_Matrix: return arg.as_real_imag()[0] elif arg.is_Function and isinstance(arg, conjugate): return re(arg.args[0]) else: included, reverted, excluded = [], [], [] args = Add.make_args(arg) for term in args: coeff = term.as_coefficient(S.ImaginaryUnit) if coeff is not None: if not coeff.is_extended_real: reverted.append(coeff) elif not term.has(S.ImaginaryUnit) and term.is_extended_real: excluded.append(term) else: # Try to do some advanced expansion. If # impossible, don't try to do re(arg) again # (because this is what we are trying to do now). real_imag = term.as_real_imag(ignore=arg) if real_imag: excluded.append(real_imag[0]) else: included.append(term) if len(args) != len(included): a, b, c = (Add(*xs) for xs in [included, reverted, excluded]) return cls(a) - im(b) + c def as_real_imag(self, deep=True, **hints): """ Returns the real number with a zero imaginary part. """ return (self, S.Zero) def _eval_derivative(self, x): if x.is_extended_real or self.args[0].is_extended_real: return re(Derivative(self.args[0], x, evaluate=True)) if x.is_imaginary or self.args[0].is_imaginary: return -S.ImaginaryUnit \ * im(Derivative(self.args[0], x, evaluate=True)) def _eval_rewrite_as_im(self, arg, **kwargs): return self.args[0] - S.ImaginaryUnit*im(self.args[0]) def _eval_is_algebraic(self): return self.args[0].is_algebraic def _eval_is_zero(self): # is_imaginary implies nonzero return fuzzy_or([self.args[0].is_imaginary, self.args[0].is_zero]) def _eval_is_finite(self): if self.args[0].is_finite: return True def _eval_is_complex(self): if self.args[0].is_finite: return True class im(Function): """ Returns imaginary part of expression. This function performs only elementary analysis and so it will fail to decompose properly more complicated expressions. If completely simplified result is needed then use Basic.as_real_imag() or perform complex expansion on instance of this function. Examples ======== >>> from sympy import re, im, E, I >>> from sympy.abc import x, y >>> im(2*E) 0 >>> im(2*I + 17) 2 >>> im(x*I) re(x) >>> im(re(x) + y) im(y) >>> im(2 + 3*I) 3 Parameters ========== arg : Expr Real or complex expression. Returns ======= expr : Expr Imaginary part of expression. See Also ======== re """ args: tTuple[Expr] is_extended_real = True unbranched = True # implicitly works on the projection to C _singularities = True # non-holomorphic @classmethod def eval(cls, arg): if arg is S.NaN: return S.NaN elif arg is S.ComplexInfinity: return S.NaN elif arg.is_extended_real: return S.Zero elif arg.is_imaginary or (S.ImaginaryUnit*arg).is_extended_real: return -S.ImaginaryUnit * arg elif arg.is_Matrix: return arg.as_real_imag()[1] elif arg.is_Function and isinstance(arg, conjugate): return -im(arg.args[0]) else: included, reverted, excluded = [], [], [] args = Add.make_args(arg) for term in args: coeff = term.as_coefficient(S.ImaginaryUnit) if coeff is not None: if not coeff.is_extended_real: reverted.append(coeff) else: excluded.append(coeff) elif term.has(S.ImaginaryUnit) or not term.is_extended_real: # Try to do some advanced expansion. If # impossible, don't try to do im(arg) again # (because this is what we are trying to do now). real_imag = term.as_real_imag(ignore=arg) if real_imag: excluded.append(real_imag[1]) else: included.append(term) if len(args) != len(included): a, b, c = (Add(*xs) for xs in [included, reverted, excluded]) return cls(a) + re(b) + c def as_real_imag(self, deep=True, **hints): """ Return the imaginary part with a zero real part. """ return (self, S.Zero) def _eval_derivative(self, x): if x.is_extended_real or self.args[0].is_extended_real: return im(Derivative(self.args[0], x, evaluate=True)) if x.is_imaginary or self.args[0].is_imaginary: return -S.ImaginaryUnit \ * re(Derivative(self.args[0], x, evaluate=True)) def _eval_rewrite_as_re(self, arg, **kwargs): return -S.ImaginaryUnit*(self.args[0] - re(self.args[0])) def _eval_is_algebraic(self): return self.args[0].is_algebraic def _eval_is_zero(self): return self.args[0].is_extended_real def _eval_is_finite(self): if self.args[0].is_finite: return True def _eval_is_complex(self): if self.args[0].is_finite: return True ############################################################################### ############### SIGN, ABSOLUTE VALUE, ARGUMENT and CONJUGATION ################ ############################################################################### class sign(Function): """ Returns the complex sign of an expression: Explanation =========== If the expression is real the sign will be: * 1 if expression is positive * 0 if expression is equal to zero * -1 if expression is negative If the expression is imaginary the sign will be: * I if im(expression) is positive * -I if im(expression) is negative Otherwise an unevaluated expression will be returned. When evaluated, the result (in general) will be ``cos(arg(expr)) + I*sin(arg(expr))``. Examples ======== >>> from sympy import sign, I >>> sign(-1) -1 >>> sign(0) 0 >>> sign(-3*I) -I >>> sign(1 + I) sign(1 + I) >>> _.evalf() 0.707106781186548 + 0.707106781186548*I Parameters ========== arg : Expr Real or imaginary expression. Returns ======= expr : Expr Complex sign of expression. See Also ======== Abs, conjugate """ is_complex = True _singularities = True def doit(self, **hints): s = super().doit() if s == self and self.args[0].is_zero is False: return self.args[0] / Abs(self.args[0]) return s @classmethod def eval(cls, arg): # handle what we can if arg.is_Mul: c, args = arg.as_coeff_mul() unk = [] s = sign(c) for a in args: if a.is_extended_negative: s = -s elif a.is_extended_positive: pass else: if a.is_imaginary: ai = im(a) if ai.is_comparable: # i.e. a = I*real s *= S.ImaginaryUnit if ai.is_extended_negative: # can't use sign(ai) here since ai might not be # a Number s = -s else: unk.append(a) else: unk.append(a) if c is S.One and len(unk) == len(args): return None return s * cls(arg._new_rawargs(*unk)) if arg is S.NaN: return S.NaN if arg.is_zero: # it may be an Expr that is zero return S.Zero if arg.is_extended_positive: return S.One if arg.is_extended_negative: return S.NegativeOne if arg.is_Function: if isinstance(arg, sign): return arg if arg.is_imaginary: if arg.is_Pow and arg.exp is S.Half: # we catch this because non-trivial sqrt args are not expanded # e.g. sqrt(1-sqrt(2)) --x--> to I*sqrt(sqrt(2) - 1) return S.ImaginaryUnit arg2 = -S.ImaginaryUnit * arg if arg2.is_extended_positive: return S.ImaginaryUnit if arg2.is_extended_negative: return -S.ImaginaryUnit def _eval_Abs(self): if fuzzy_not(self.args[0].is_zero): return S.One def _eval_conjugate(self): return sign(conjugate(self.args[0])) def _eval_derivative(self, x): if self.args[0].is_extended_real: from sympy.functions.special.delta_functions import DiracDelta return 2 * Derivative(self.args[0], x, evaluate=True) \ * DiracDelta(self.args[0]) elif self.args[0].is_imaginary: from sympy.functions.special.delta_functions import DiracDelta return 2 * Derivative(self.args[0], x, evaluate=True) \ * DiracDelta(-S.ImaginaryUnit * self.args[0]) def _eval_is_nonnegative(self): if self.args[0].is_nonnegative: return True def _eval_is_nonpositive(self): if self.args[0].is_nonpositive: return True def _eval_is_imaginary(self): return self.args[0].is_imaginary def _eval_is_integer(self): return self.args[0].is_extended_real def _eval_is_zero(self): return self.args[0].is_zero def _eval_power(self, other): if ( fuzzy_not(self.args[0].is_zero) and other.is_integer and other.is_even ): return S.One def _eval_nseries(self, x, n, logx, cdir=0): arg0 = self.args[0] x0 = arg0.subs(x, 0) if x0 != 0: return self.func(x0) if cdir != 0: cdir = arg0.dir(x, cdir) return -S.One if re(cdir) < 0 else S.One def _eval_rewrite_as_Piecewise(self, arg, **kwargs): if arg.is_extended_real: return Piecewise((1, arg > 0), (-1, arg < 0), (0, True)) def _eval_rewrite_as_Heaviside(self, arg, **kwargs): from sympy.functions.special.delta_functions import Heaviside if arg.is_extended_real: return Heaviside(arg) * 2 - 1 def _eval_rewrite_as_Abs(self, arg, **kwargs): return Piecewise((0, Eq(arg, 0)), (arg / Abs(arg), True)) def _eval_simplify(self, **kwargs): return self.func(factor_terms(self.args[0])) # XXX include doit? class Abs(Function): """ Return the absolute value of the argument. Explanation =========== This is an extension of the built-in function abs() to accept symbolic values. If you pass a SymPy expression to the built-in abs(), it will pass it automatically to Abs(). Examples ======== >>> from sympy import Abs, Symbol, S, I >>> Abs(-1) 1 >>> x = Symbol('x', real=True) >>> Abs(-x) Abs(x) >>> Abs(x**2) x**2 >>> abs(-x) # The Python built-in Abs(x) >>> Abs(3*x + 2*I) sqrt(9*x**2 + 4) >>> Abs(8*I) 8 Note that the Python built-in will return either an Expr or int depending on the argument:: >>> type(abs(-1)) <... 'int'> >>> type(abs(S.NegativeOne)) <class 'sympy.core.numbers.One'> Abs will always return a SymPy object. Parameters ========== arg : Expr Real or complex expression. Returns ======= expr : Expr Absolute value returned can be an expression or integer depending on input arg. See Also ======== sign, conjugate """ args: tTuple[Expr] is_extended_real = True is_extended_negative = False is_extended_nonnegative = True unbranched = True _singularities = True # non-holomorphic def fdiff(self, argindex=1): """ Get the first derivative of the argument to Abs(). """ if argindex == 1: return sign(self.args[0]) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): from sympy.simplify.simplify import signsimp if hasattr(arg, '_eval_Abs'): obj = arg._eval_Abs() if obj is not None: return obj if not isinstance(arg, Expr): raise TypeError("Bad argument type for Abs(): %s" % type(arg)) # handle what we can arg = signsimp(arg, evaluate=False) n, d = arg.as_numer_denom() if d.free_symbols and not n.free_symbols: return cls(n)/cls(d) if arg.is_Mul: known = [] unk = [] for t in arg.args: if t.is_Pow and t.exp.is_integer and t.exp.is_negative: bnew = cls(t.base) if isinstance(bnew, cls): unk.append(t) else: known.append(Pow(bnew, t.exp)) else: tnew = cls(t) if isinstance(tnew, cls): unk.append(t) else: known.append(tnew) known = Mul(*known) unk = cls(Mul(*unk), evaluate=False) if unk else S.One return known*unk if arg is S.NaN: return S.NaN if arg is S.ComplexInfinity: return S.Infinity if arg.is_Pow: base, exponent = arg.as_base_exp() if base.is_extended_real: if exponent.is_integer: if exponent.is_even: return arg if base is S.NegativeOne: return S.One return Abs(base)**exponent if base.is_extended_nonnegative: return base**re(exponent) if base.is_extended_negative: return (-base)**re(exponent)*exp(-S.Pi*im(exponent)) return elif not base.has(Symbol): # complex base # express base**exponent as exp(exponent*log(base)) a, b = log(base).as_real_imag() z = a + I*b return exp(re(exponent*z)) if isinstance(arg, exp): return exp(re(arg.args[0])) if isinstance(arg, AppliedUndef): if arg.is_positive: return arg elif arg.is_negative: return -arg return if arg.is_Add and arg.has(S.Infinity, S.NegativeInfinity): if any(a.is_infinite for a in arg.as_real_imag()): return S.Infinity if arg.is_zero: return S.Zero if arg.is_extended_nonnegative: return arg if arg.is_extended_nonpositive: return -arg if arg.is_imaginary: arg2 = -S.ImaginaryUnit * arg if arg2.is_extended_nonnegative: return arg2 if arg.is_extended_real: return # reject result if all new conjugates are just wrappers around # an expression that was already in the arg conj = signsimp(arg.conjugate(), evaluate=False) new_conj = conj.atoms(conjugate) - arg.atoms(conjugate) if new_conj and all(arg.has(i.args[0]) for i in new_conj): return if arg != conj and arg != -conj: ignore = arg.atoms(Abs) abs_free_arg = arg.xreplace({i: Dummy(real=True) for i in ignore}) unk = [a for a in abs_free_arg.free_symbols if a.is_extended_real is None] if not unk or not all(conj.has(conjugate(u)) for u in unk): return sqrt(expand_mul(arg*conj)) def _eval_is_real(self): if self.args[0].is_finite: return True def _eval_is_integer(self): if self.args[0].is_extended_real: return self.args[0].is_integer def _eval_is_extended_nonzero(self): return fuzzy_not(self._args[0].is_zero) def _eval_is_zero(self): return self._args[0].is_zero def _eval_is_extended_positive(self): is_z = self.is_zero if is_z is not None: return not is_z def _eval_is_rational(self): if self.args[0].is_extended_real: return self.args[0].is_rational def _eval_is_even(self): if self.args[0].is_extended_real: return self.args[0].is_even def _eval_is_odd(self): if self.args[0].is_extended_real: return self.args[0].is_odd def _eval_is_algebraic(self): return self.args[0].is_algebraic def _eval_power(self, exponent): if self.args[0].is_extended_real and exponent.is_integer: if exponent.is_even: return self.args[0]**exponent elif exponent is not S.NegativeOne and exponent.is_Integer: return self.args[0]**(exponent - 1)*self return def _eval_nseries(self, x, n, logx, cdir=0): direction = self.args[0].leadterm(x)[0] if direction.has(log(x)): direction = direction.subs(log(x), logx) s = self.args[0]._eval_nseries(x, n=n, logx=logx) return (sign(direction)*s).expand() def _eval_derivative(self, x): if self.args[0].is_extended_real or self.args[0].is_imaginary: return Derivative(self.args[0], x, evaluate=True) \ * sign(conjugate(self.args[0])) rv = (re(self.args[0]) * Derivative(re(self.args[0]), x, evaluate=True) + im(self.args[0]) * Derivative(im(self.args[0]), x, evaluate=True)) / Abs(self.args[0]) return rv.rewrite(sign) def _eval_rewrite_as_Heaviside(self, arg, **kwargs): # Note this only holds for real arg (since Heaviside is not defined # for complex arguments). from sympy.functions.special.delta_functions import Heaviside if arg.is_extended_real: return arg*(Heaviside(arg) - Heaviside(-arg)) def _eval_rewrite_as_Piecewise(self, arg, **kwargs): if arg.is_extended_real: return Piecewise((arg, arg >= 0), (-arg, True)) elif arg.is_imaginary: return Piecewise((I*arg, I*arg >= 0), (-I*arg, True)) def _eval_rewrite_as_sign(self, arg, **kwargs): return arg/sign(arg) def _eval_rewrite_as_conjugate(self, arg, **kwargs): return (arg*conjugate(arg))**S.Half class arg(Function): """ returns the argument (in radians) of a complex number. The argument is evaluated in consistent convention with atan2 where the branch-cut is taken along the negative real axis and arg(z) is in the interval (-pi,pi]. For a positive number, the argument is always 0; the argument of a negative number is pi; and the argument of 0 is undefined and returns nan. So the ``arg`` function will never nest greater than 3 levels since at the 4th application, the result must be nan; for a real number, nan is returned on the 3rd application. Examples ======== >>> from sympy import arg, I, sqrt, Dummy >>> from sympy.abc import x >>> arg(2.0) 0 >>> arg(I) pi/2 >>> arg(sqrt(2) + I*sqrt(2)) pi/4 >>> arg(sqrt(3)/2 + I/2) pi/6 >>> arg(4 + 3*I) atan(3/4) >>> arg(0.8 + 0.6*I) 0.643501108793284 >>> arg(arg(arg(arg(x)))) nan >>> real = Dummy(real=True) >>> arg(arg(arg(real))) nan Parameters ========== arg : Expr Real or complex expression. Returns ======= value : Expr Returns arc tangent of arg measured in radians. """ is_extended_real = True is_real = True is_finite = True _singularities = True # non-holomorphic @classmethod def eval(cls, arg): a = arg for i in range(3): if isinstance(a, cls): a = a.args[0] else: if i == 2 and a.is_extended_real: return S.NaN break else: return S.NaN if isinstance(arg, exp_polar): return periodic_argument(arg, oo) if not arg.is_Atom: c, arg_ = factor_terms(arg).as_coeff_Mul() if arg_.is_Mul: arg_ = Mul(*[a if (sign(a) not in (-1, 1)) else sign(a) for a in arg_.args]) arg_ = sign(c)*arg_ else: arg_ = arg if any(i.is_extended_positive is None for i in arg_.atoms(AppliedUndef)): return x, y = arg_.as_real_imag() rv = atan2(y, x) if rv.is_number: return rv if arg_ != arg: return cls(arg_, evaluate=False) def _eval_derivative(self, t): x, y = self.args[0].as_real_imag() return (x * Derivative(y, t, evaluate=True) - y * Derivative(x, t, evaluate=True)) / (x**2 + y**2) def _eval_rewrite_as_atan2(self, arg, **kwargs): x, y = self.args[0].as_real_imag() return atan2(y, x) class conjugate(Function): """ Returns the `complex conjugate` Ref[1] of an argument. In mathematics, the complex conjugate of a complex number is given by changing the sign of the imaginary part. Thus, the conjugate of the complex number :math:`a + ib` (where a and b are real numbers) is :math:`a - ib` Examples ======== >>> from sympy import conjugate, I >>> conjugate(2) 2 >>> conjugate(I) -I >>> conjugate(3 + 2*I) 3 - 2*I >>> conjugate(5 - I) 5 + I Parameters ========== arg : Expr Real or complex expression. Returns ======= arg : Expr Complex conjugate of arg as real, imaginary or mixed expression. See Also ======== sign, Abs References ========== .. [1] https://en.wikipedia.org/wiki/Complex_conjugation """ _singularities = True # non-holomorphic @classmethod def eval(cls, arg): obj = arg._eval_conjugate() if obj is not None: return obj def inverse(self): return conjugate def _eval_Abs(self): return Abs(self.args[0], evaluate=True) def _eval_adjoint(self): return transpose(self.args[0]) def _eval_conjugate(self): return self.args[0] def _eval_derivative(self, x): if x.is_real: return conjugate(Derivative(self.args[0], x, evaluate=True)) elif x.is_imaginary: return -conjugate(Derivative(self.args[0], x, evaluate=True)) def _eval_transpose(self): return adjoint(self.args[0]) def _eval_is_algebraic(self): return self.args[0].is_algebraic class transpose(Function): """ Linear map transposition. Examples ======== >>> from sympy import transpose, Matrix, MatrixSymbol >>> A = MatrixSymbol('A', 25, 9) >>> transpose(A) A.T >>> B = MatrixSymbol('B', 9, 22) >>> transpose(B) B.T >>> transpose(A*B) B.T*A.T >>> M = Matrix([[4, 5], [2, 1], [90, 12]]) >>> M Matrix([ [ 4, 5], [ 2, 1], [90, 12]]) >>> transpose(M) Matrix([ [4, 2, 90], [5, 1, 12]]) Parameters ========== arg : Matrix Matrix or matrix expression to take the transpose of. Returns ======= value : Matrix Transpose of arg. """ @classmethod def eval(cls, arg): obj = arg._eval_transpose() if obj is not None: return obj def _eval_adjoint(self): return conjugate(self.args[0]) def _eval_conjugate(self): return adjoint(self.args[0]) def _eval_transpose(self): return self.args[0] class adjoint(Function): """ Conjugate transpose or Hermite conjugation. Examples ======== >>> from sympy import adjoint, MatrixSymbol >>> A = MatrixSymbol('A', 10, 5) >>> adjoint(A) Adjoint(A) Parameters ========== arg : Matrix Matrix or matrix expression to take the adjoint of. Returns ======= value : Matrix Represents the conjugate transpose or Hermite conjugation of arg. """ @classmethod def eval(cls, arg): obj = arg._eval_adjoint() if obj is not None: return obj obj = arg._eval_transpose() if obj is not None: return conjugate(obj) def _eval_adjoint(self): return self.args[0] def _eval_conjugate(self): return transpose(self.args[0]) def _eval_transpose(self): return conjugate(self.args[0]) def _latex(self, printer, exp=None, *args): arg = printer._print(self.args[0]) tex = r'%s^{\dagger}' % arg if exp: tex = r'\left(%s\right)^{%s}' % (tex, exp) return tex def _pretty(self, printer, *args): from sympy.printing.pretty.stringpict import prettyForm pform = printer._print(self.args[0], *args) if printer._use_unicode: pform = pform**prettyForm('\N{DAGGER}') else: pform = pform**prettyForm('+') return pform ############################################################################### ############### HANDLING OF POLAR NUMBERS ##################################### ############################################################################### class polar_lift(Function): """ Lift argument to the Riemann surface of the logarithm, using the standard branch. Examples ======== >>> from sympy import Symbol, polar_lift, I >>> p = Symbol('p', polar=True) >>> x = Symbol('x') >>> polar_lift(4) 4*exp_polar(0) >>> polar_lift(-4) 4*exp_polar(I*pi) >>> polar_lift(-I) exp_polar(-I*pi/2) >>> polar_lift(I + 2) polar_lift(2 + I) >>> polar_lift(4*x) 4*polar_lift(x) >>> polar_lift(4*p) 4*p Parameters ========== arg : Expr Real or complex expression. See Also ======== sympy.functions.elementary.exponential.exp_polar periodic_argument """ is_polar = True is_comparable = False # Cannot be evalf'd. @classmethod def eval(cls, arg): from sympy.functions.elementary.complexes import arg as argument if arg.is_number: ar = argument(arg) # In general we want to affirm that something is known, # e.g. `not ar.has(argument) and not ar.has(atan)` # but for now we will just be more restrictive and # see that it has evaluated to one of the known values. if ar in (0, pi/2, -pi/2, pi): return exp_polar(I*ar)*abs(arg) if arg.is_Mul: args = arg.args else: args = [arg] included = [] excluded = [] positive = [] for arg in args: if arg.is_polar: included += [arg] elif arg.is_positive: positive += [arg] else: excluded += [arg] if len(excluded) < len(args): if excluded: return Mul(*(included + positive))*polar_lift(Mul(*excluded)) elif included: return Mul(*(included + positive)) else: return Mul(*positive)*exp_polar(0) def _eval_evalf(self, prec): """ Careful! any evalf of polar numbers is flaky """ return self.args[0]._eval_evalf(prec) def _eval_Abs(self): return Abs(self.args[0], evaluate=True) class periodic_argument(Function): """ Represent the argument on a quotient of the Riemann surface of the logarithm. That is, given a period $P$, always return a value in (-P/2, P/2], by using exp(P*I) == 1. Examples ======== >>> from sympy import exp_polar, periodic_argument >>> from sympy import I, pi >>> periodic_argument(exp_polar(10*I*pi), 2*pi) 0 >>> periodic_argument(exp_polar(5*I*pi), 4*pi) pi >>> from sympy import exp_polar, periodic_argument >>> from sympy import I, pi >>> periodic_argument(exp_polar(5*I*pi), 2*pi) pi >>> periodic_argument(exp_polar(5*I*pi), 3*pi) -pi >>> periodic_argument(exp_polar(5*I*pi), pi) 0 Parameters ========== ar : Expr A polar number. period : ExprT The period $P$. See Also ======== sympy.functions.elementary.exponential.exp_polar polar_lift : Lift argument to the Riemann surface of the logarithm principal_branch """ @classmethod def _getunbranched(cls, ar): if ar.is_Mul: args = ar.args else: args = [ar] unbranched = 0 for a in args: if not a.is_polar: unbranched += arg(a) elif isinstance(a, exp_polar): unbranched += a.exp.as_real_imag()[1] elif a.is_Pow: re, im = a.exp.as_real_imag() unbranched += re*unbranched_argument( a.base) + im*log(abs(a.base)) elif isinstance(a, polar_lift): unbranched += arg(a.args[0]) else: return None return unbranched @classmethod def eval(cls, ar, period): # Our strategy is to evaluate the argument on the Riemann surface of the # logarithm, and then reduce. # NOTE evidently this means it is a rather bad idea to use this with # period != 2*pi and non-polar numbers. if not period.is_extended_positive: return None if period == oo and isinstance(ar, principal_branch): return periodic_argument(*ar.args) if isinstance(ar, polar_lift) and period >= 2*pi: return periodic_argument(ar.args[0], period) if ar.is_Mul: newargs = [x for x in ar.args if not x.is_positive] if len(newargs) != len(ar.args): return periodic_argument(Mul(*newargs), period) unbranched = cls._getunbranched(ar) if unbranched is None: return None if unbranched.has(periodic_argument, atan2, atan): return None if period == oo: return unbranched if period != oo: n = ceiling(unbranched/period - S.Half)*period if not n.has(ceiling): return unbranched - n def _eval_evalf(self, prec): z, period = self.args if period == oo: unbranched = periodic_argument._getunbranched(z) if unbranched is None: return self return unbranched._eval_evalf(prec) ub = periodic_argument(z, oo)._eval_evalf(prec) return (ub - ceiling(ub/period - S.Half)*period)._eval_evalf(prec) def unbranched_argument(arg): ''' Returns periodic argument of arg with period as infinity. Examples ======== >>> from sympy import exp_polar, unbranched_argument >>> from sympy import I, pi >>> unbranched_argument(exp_polar(15*I*pi)) 15*pi >>> unbranched_argument(exp_polar(7*I*pi)) 7*pi See also ======== periodic_argument ''' return periodic_argument(arg, oo) class principal_branch(Function): """ Represent a polar number reduced to its principal branch on a quotient of the Riemann surface of the logarithm. Explanation =========== This is a function of two arguments. The first argument is a polar number `z`, and the second one a positive real number or infinity, `p`. The result is "z mod exp_polar(I*p)". Examples ======== >>> from sympy import exp_polar, principal_branch, oo, I, pi >>> from sympy.abc import z >>> principal_branch(z, oo) z >>> principal_branch(exp_polar(2*pi*I)*3, 2*pi) 3*exp_polar(0) >>> principal_branch(exp_polar(2*pi*I)*3*z, 2*pi) 3*principal_branch(z, 2*pi) Parameters ========== x : Expr A polar number. period : Expr Positive real number or infinity. See Also ======== sympy.functions.elementary.exponential.exp_polar polar_lift : Lift argument to the Riemann surface of the logarithm periodic_argument """ is_polar = True is_comparable = False # cannot always be evalf'd @classmethod def eval(self, x, period): if isinstance(x, polar_lift): return principal_branch(x.args[0], period) if period == oo: return x ub = periodic_argument(x, oo) barg = periodic_argument(x, period) if ub != barg and not ub.has(periodic_argument) \ and not barg.has(periodic_argument): pl = polar_lift(x) def mr(expr): if not isinstance(expr, Symbol): return polar_lift(expr) return expr pl = pl.replace(polar_lift, mr) # Recompute unbranched argument ub = periodic_argument(pl, oo) if not pl.has(polar_lift): if ub != barg: res = exp_polar(I*(barg - ub))*pl else: res = pl if not res.is_polar and not res.has(exp_polar): res *= exp_polar(0) return res if not x.free_symbols: c, m = x, () else: c, m = x.as_coeff_mul(*x.free_symbols) others = [] for y in m: if y.is_positive: c *= y else: others += [y] m = tuple(others) arg = periodic_argument(c, period) if arg.has(periodic_argument): return None if arg.is_number and (unbranched_argument(c) != arg or (arg == 0 and m != () and c != 1)): if arg == 0: return abs(c)*principal_branch(Mul(*m), period) return principal_branch(exp_polar(I*arg)*Mul(*m), period)*abs(c) if arg.is_number and ((abs(arg) < period/2) == True or arg == period/2) \ and m == (): return exp_polar(arg*I)*abs(c) def _eval_evalf(self, prec): z, period = self.args p = periodic_argument(z, period)._eval_evalf(prec) if abs(p) > pi or p == -pi: return self # Cannot evalf for this argument. return (abs(z)*exp(I*p))._eval_evalf(prec) def _polarify(eq, lift, pause=False): from sympy.integrals.integrals import Integral if eq.is_polar: return eq if eq.is_number and not pause: return polar_lift(eq) if isinstance(eq, Symbol) and not pause and lift: return polar_lift(eq) elif eq.is_Atom: return eq elif eq.is_Add: r = eq.func(*[_polarify(arg, lift, pause=True) for arg in eq.args]) if lift: return polar_lift(r) return r elif eq.is_Pow and eq.base == S.Exp1: return eq.func(S.Exp1, _polarify(eq.exp, lift, pause=False)) elif eq.is_Function: return eq.func(*[_polarify(arg, lift, pause=False) for arg in eq.args]) elif isinstance(eq, Integral): # Don't lift the integration variable func = _polarify(eq.function, lift, pause=pause) limits = [] for limit in eq.args[1:]: var = _polarify(limit[0], lift=False, pause=pause) rest = _polarify(limit[1:], lift=lift, pause=pause) limits.append((var,) + rest) return Integral(*((func,) + tuple(limits))) else: return eq.func(*[_polarify(arg, lift, pause=pause) if isinstance(arg, Expr) else arg for arg in eq.args]) def polarify(eq, subs=True, lift=False): """ Turn all numbers in eq into their polar equivalents (under the standard choice of argument). Note that no attempt is made to guess a formal convention of adding polar numbers, expressions like 1 + x will generally not be altered. Note also that this function does not promote exp(x) to exp_polar(x). If ``subs`` is True, all symbols which are not already polar will be substituted for polar dummies; in this case the function behaves much like posify. If ``lift`` is True, both addition statements and non-polar symbols are changed to their polar_lift()ed versions. Note that lift=True implies subs=False. Examples ======== >>> from sympy import polarify, sin, I >>> from sympy.abc import x, y >>> expr = (-x)**y >>> expr.expand() (-x)**y >>> polarify(expr) ((_x*exp_polar(I*pi))**_y, {_x: x, _y: y}) >>> polarify(expr)[0].expand() _x**_y*exp_polar(_y*I*pi) >>> polarify(x, lift=True) polar_lift(x) >>> polarify(x*(1+y), lift=True) polar_lift(x)*polar_lift(y + 1) Adds are treated carefully: >>> polarify(1 + sin((1 + I)*x)) (sin(_x*polar_lift(1 + I)) + 1, {_x: x}) """ if lift: subs = False eq = _polarify(sympify(eq), lift) if not subs: return eq reps = {s: Dummy(s.name, polar=True) for s in eq.free_symbols} eq = eq.subs(reps) return eq, {r: s for s, r in reps.items()} def _unpolarify(eq, exponents_only, pause=False): if not isinstance(eq, Basic) or eq.is_Atom: return eq if not pause: if isinstance(eq, exp_polar): return exp(_unpolarify(eq.exp, exponents_only)) if isinstance(eq, principal_branch) and eq.args[1] == 2*pi: return _unpolarify(eq.args[0], exponents_only) if ( eq.is_Add or eq.is_Mul or eq.is_Boolean or eq.is_Relational and ( eq.rel_op in ('==', '!=') and 0 in eq.args or eq.rel_op not in ('==', '!=')) ): return eq.func(*[_unpolarify(x, exponents_only) for x in eq.args]) if isinstance(eq, polar_lift): return _unpolarify(eq.args[0], exponents_only) if eq.is_Pow: expo = _unpolarify(eq.exp, exponents_only) base = _unpolarify(eq.base, exponents_only, not (expo.is_integer and not pause)) return base**expo if eq.is_Function and getattr(eq.func, 'unbranched', False): return eq.func(*[_unpolarify(x, exponents_only, exponents_only) for x in eq.args]) return eq.func(*[_unpolarify(x, exponents_only, True) for x in eq.args]) def unpolarify(eq, subs=None, exponents_only=False): """ If p denotes the projection from the Riemann surface of the logarithm to the complex line, return a simplified version eq' of `eq` such that p(eq') == p(eq). Also apply the substitution subs in the end. (This is a convenience, since ``unpolarify``, in a certain sense, undoes polarify.) Examples ======== >>> from sympy import unpolarify, polar_lift, sin, I >>> unpolarify(polar_lift(I + 2)) 2 + I >>> unpolarify(sin(polar_lift(I + 7))) sin(7 + I) """ if isinstance(eq, bool): return eq eq = sympify(eq) if subs is not None: return unpolarify(eq.subs(subs)) changed = True pause = False if exponents_only: pause = True while changed: changed = False res = _unpolarify(eq, exponents_only, pause) if res != eq: changed = True eq = res if isinstance(res, bool): return res # Finally, replacing Exp(0) by 1 is always correct. # So is polar_lift(0) -> 0. return res.subs({exp_polar(0): 1, polar_lift(0): 0})
5cc30db9aad93426b08f535ba96a63cf5372c7b3674b8bb8da5070f621cf65f9
"""Hypergeometric and Meijer G-functions""" from functools import reduce from sympy.core import S, I, pi, oo, zoo, ilcm, Mod from sympy.core.add import Add from sympy.core.expr import Expr from sympy.core.function import Function, Derivative, ArgumentIndexError from sympy.core.containers import Tuple from sympy.core.mul import Mul from sympy.core.relational import Ne from sympy.core.sorting import default_sort_key from sympy.core.symbol import Dummy from sympy.functions import (sqrt, exp, log, sin, cos, asin, atan, sinh, cosh, asinh, acosh, atanh, acoth, Abs, re, factorial, RisingFactorial) from sympy.logic.boolalg import (And, Or) class TupleArg(Tuple): def limit(self, x, xlim, dir='+'): """ Compute limit x->xlim. """ from sympy.series.limits import limit return TupleArg(*[limit(f, x, xlim, dir) for f in self.args]) # TODO should __new__ accept **options? # TODO should constructors should check if parameters are sensible? def _prep_tuple(v): """ Turn an iterable argument *v* into a tuple and unpolarify, since both hypergeometric and meijer g-functions are unbranched in their parameters. Examples ======== >>> from sympy.functions.special.hyper import _prep_tuple >>> _prep_tuple([1, 2, 3]) (1, 2, 3) >>> _prep_tuple((4, 5)) (4, 5) >>> _prep_tuple((7, 8, 9)) (7, 8, 9) """ from sympy.functions.elementary.complexes import unpolarify return TupleArg(*[unpolarify(x) for x in v]) class TupleParametersBase(Function): """ Base class that takes care of differentiation, when some of the arguments are actually tuples. """ # This is not deduced automatically since there are Tuples as arguments. is_commutative = True def _eval_derivative(self, s): try: res = 0 if self.args[0].has(s) or self.args[1].has(s): for i, p in enumerate(self._diffargs): m = self._diffargs[i].diff(s) if m != 0: res += self.fdiff((1, i))*m return res + self.fdiff(3)*self.args[2].diff(s) except (ArgumentIndexError, NotImplementedError): return Derivative(self, s) class hyper(TupleParametersBase): r""" The generalized hypergeometric function is defined by a series where the ratios of successive terms are a rational function of the summation index. When convergent, it is continued analytically to the largest possible domain. Explanation =========== The hypergeometric function depends on two vectors of parameters, called the numerator parameters $a_p$, and the denominator parameters $b_q$. It also has an argument $z$. The series definition is .. math :: {}_pF_q\left(\begin{matrix} a_1, \cdots, a_p \\ b_1, \cdots, b_q \end{matrix} \middle| z \right) = \sum_{n=0}^\infty \frac{(a_1)_n \cdots (a_p)_n}{(b_1)_n \cdots (b_q)_n} \frac{z^n}{n!}, where $(a)_n = (a)(a+1)\cdots(a+n-1)$ denotes the rising factorial. If one of the $b_q$ is a non-positive integer then the series is undefined unless one of the $a_p$ is a larger (i.e., smaller in magnitude) non-positive integer. If none of the $b_q$ is a non-positive integer and one of the $a_p$ is a non-positive integer, then the series reduces to a polynomial. To simplify the following discussion, we assume that none of the $a_p$ or $b_q$ is a non-positive integer. For more details, see the references. The series converges for all $z$ if $p \le q$, and thus defines an entire single-valued function in this case. If $p = q+1$ the series converges for $|z| < 1$, and can be continued analytically into a half-plane. If $p > q+1$ the series is divergent for all $z$. Please note the hypergeometric function constructor currently does *not* check if the parameters actually yield a well-defined function. Examples ======== The parameters $a_p$ and $b_q$ can be passed as arbitrary iterables, for example: >>> from sympy import hyper >>> from sympy.abc import x, n, a >>> hyper((1, 2, 3), [3, 4], x) hyper((1, 2, 3), (3, 4), x) There is also pretty printing (it looks better using Unicode): >>> from sympy import pprint >>> pprint(hyper((1, 2, 3), [3, 4], x), use_unicode=False) _ |_ /1, 2, 3 | \ | | | x| 3 2 \ 3, 4 | / The parameters must always be iterables, even if they are vectors of length one or zero: >>> hyper((1, ), [], x) hyper((1,), (), x) But of course they may be variables (but if they depend on $x$ then you should not expect much implemented functionality): >>> hyper((n, a), (n**2,), x) hyper((n, a), (n**2,), x) The hypergeometric function generalizes many named special functions. The function ``hyperexpand()`` tries to express a hypergeometric function using named special functions. For example: >>> from sympy import hyperexpand >>> hyperexpand(hyper([], [], x)) exp(x) You can also use ``expand_func()``: >>> from sympy import expand_func >>> expand_func(x*hyper([1, 1], [2], -x)) log(x + 1) More examples: >>> from sympy import S >>> hyperexpand(hyper([], [S(1)/2], -x**2/4)) cos(x) >>> hyperexpand(x*hyper([S(1)/2, S(1)/2], [S(3)/2], x**2)) asin(x) We can also sometimes ``hyperexpand()`` parametric functions: >>> from sympy.abc import a >>> hyperexpand(hyper([-a], [], x)) (1 - x)**a See Also ======== sympy.simplify.hyperexpand gamma meijerg References ========== .. [1] Luke, Y. L. (1969), The Special Functions and Their Approximations, Volume 1 .. [2] https://en.wikipedia.org/wiki/Generalized_hypergeometric_function """ def __new__(cls, ap, bq, z, **kwargs): # TODO should we check convergence conditions? return Function.__new__(cls, _prep_tuple(ap), _prep_tuple(bq), z, **kwargs) @classmethod def eval(cls, ap, bq, z): from sympy.functions.elementary.complexes import unpolarify if len(ap) <= len(bq) or (len(ap) == len(bq) + 1 and (Abs(z) <= 1) == True): nz = unpolarify(z) if z != nz: return hyper(ap, bq, nz) def fdiff(self, argindex=3): if argindex != 3: raise ArgumentIndexError(self, argindex) nap = Tuple(*[a + 1 for a in self.ap]) nbq = Tuple(*[b + 1 for b in self.bq]) fac = Mul(*self.ap)/Mul(*self.bq) return fac*hyper(nap, nbq, self.argument) def _eval_expand_func(self, **hints): from sympy.functions.special.gamma_functions import gamma from sympy.simplify.hyperexpand import hyperexpand if len(self.ap) == 2 and len(self.bq) == 1 and self.argument == 1: a, b = self.ap c = self.bq[0] return gamma(c)*gamma(c - a - b)/gamma(c - a)/gamma(c - b) return hyperexpand(self) def _eval_rewrite_as_Sum(self, ap, bq, z, **kwargs): from sympy.functions import factorial, RisingFactorial, Piecewise from sympy.concrete.summations import Sum n = Dummy("n", integer=True) rfap = Tuple(*[RisingFactorial(a, n) for a in ap]) rfbq = Tuple(*[RisingFactorial(b, n) for b in bq]) coeff = Mul(*rfap) / Mul(*rfbq) return Piecewise((Sum(coeff * z**n / factorial(n), (n, 0, oo)), self.convergence_statement), (self, True)) def _eval_as_leading_term(self, x, logx=None, cdir=0): arg = self.args[2] x0 = arg.subs(x, 0) if x0 is S.NaN: x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if x0 is S.Zero: return S.One return super()._eval_as_leading_term(x, logx=logx, cdir=cdir) def _eval_nseries(self, x, n, logx, cdir=0): from sympy.series.order import Order arg = self.args[2] x0 = arg.limit(x, 0) ap = self.args[0] bq = self.args[1] if x0 != 0: return super()._eval_nseries(x, n, logx) terms = [] for i in range(n): num = 1 den = 1 for a in ap: num *= RisingFactorial(a, i) for b in bq: den *= RisingFactorial(b, i) terms.append(((num/den) * (arg**i)) / factorial(i)) return (Add(*terms) + Order(x**n,x)) @property def argument(self): """ Argument of the hypergeometric function. """ return self.args[2] @property def ap(self): """ Numerator parameters of the hypergeometric function. """ return Tuple(*self.args[0]) @property def bq(self): """ Denominator parameters of the hypergeometric function. """ return Tuple(*self.args[1]) @property def _diffargs(self): return self.ap + self.bq @property def eta(self): """ A quantity related to the convergence of the series. """ return sum(self.ap) - sum(self.bq) @property def radius_of_convergence(self): """ Compute the radius of convergence of the defining series. Explanation =========== Note that even if this is not ``oo``, the function may still be evaluated outside of the radius of convergence by analytic continuation. But if this is zero, then the function is not actually defined anywhere else. Examples ======== >>> from sympy import hyper >>> from sympy.abc import z >>> hyper((1, 2), [3], z).radius_of_convergence 1 >>> hyper((1, 2, 3), [4], z).radius_of_convergence 0 >>> hyper((1, 2), (3, 4), z).radius_of_convergence oo """ if any(a.is_integer and (a <= 0) == True for a in self.ap + self.bq): aints = [a for a in self.ap if a.is_Integer and (a <= 0) == True] bints = [a for a in self.bq if a.is_Integer and (a <= 0) == True] if len(aints) < len(bints): return S.Zero popped = False for b in bints: cancelled = False while aints: a = aints.pop() if a >= b: cancelled = True break popped = True if not cancelled: return S.Zero if aints or popped: # There are still non-positive numerator parameters. # This is a polynomial. return oo if len(self.ap) == len(self.bq) + 1: return S.One elif len(self.ap) <= len(self.bq): return oo else: return S.Zero @property def convergence_statement(self): """ Return a condition on z under which the series converges. """ R = self.radius_of_convergence if R == 0: return False if R == oo: return True # The special functions and their approximations, page 44 e = self.eta z = self.argument c1 = And(re(e) < 0, abs(z) <= 1) c2 = And(0 <= re(e), re(e) < 1, abs(z) <= 1, Ne(z, 1)) c3 = And(re(e) >= 1, abs(z) < 1) return Or(c1, c2, c3) def _eval_simplify(self, **kwargs): from sympy.simplify.hyperexpand import hyperexpand return hyperexpand(self) class meijerg(TupleParametersBase): r""" The Meijer G-function is defined by a Mellin-Barnes type integral that resembles an inverse Mellin transform. It generalizes the hypergeometric functions. Explanation =========== The Meijer G-function depends on four sets of parameters. There are "*numerator parameters*" $a_1, \ldots, a_n$ and $a_{n+1}, \ldots, a_p$, and there are "*denominator parameters*" $b_1, \ldots, b_m$ and $b_{m+1}, \ldots, b_q$. Confusingly, it is traditionally denoted as follows (note the position of $m$, $n$, $p$, $q$, and how they relate to the lengths of the four parameter vectors): .. math :: G_{p,q}^{m,n} \left(\begin{matrix}a_1, \cdots, a_n & a_{n+1}, \cdots, a_p \\ b_1, \cdots, b_m & b_{m+1}, \cdots, b_q \end{matrix} \middle| z \right). However, in SymPy the four parameter vectors are always available separately (see examples), so that there is no need to keep track of the decorating sub- and super-scripts on the G symbol. The G function is defined as the following integral: .. math :: \frac{1}{2 \pi i} \int_L \frac{\prod_{j=1}^m \Gamma(b_j - s) \prod_{j=1}^n \Gamma(1 - a_j + s)}{\prod_{j=m+1}^q \Gamma(1- b_j +s) \prod_{j=n+1}^p \Gamma(a_j - s)} z^s \mathrm{d}s, where $\Gamma(z)$ is the gamma function. There are three possible contours which we will not describe in detail here (see the references). If the integral converges along more than one of them, the definitions agree. The contours all separate the poles of $\Gamma(1-a_j+s)$ from the poles of $\Gamma(b_k-s)$, so in particular the G function is undefined if $a_j - b_k \in \mathbb{Z}_{>0}$ for some $j \le n$ and $k \le m$. The conditions under which one of the contours yields a convergent integral are complicated and we do not state them here, see the references. Please note currently the Meijer G-function constructor does *not* check any convergence conditions. Examples ======== You can pass the parameters either as four separate vectors: >>> from sympy import meijerg, Tuple, pprint >>> from sympy.abc import x, a >>> pprint(meijerg((1, 2), (a, 4), (5,), [], x), use_unicode=False) __1, 2 /1, 2 a, 4 | \ /__ | | x| \_|4, 1 \ 5 | / Or as two nested vectors: >>> pprint(meijerg([(1, 2), (3, 4)], ([5], Tuple()), x), use_unicode=False) __1, 2 /1, 2 3, 4 | \ /__ | | x| \_|4, 1 \ 5 | / As with the hypergeometric function, the parameters may be passed as arbitrary iterables. Vectors of length zero and one also have to be passed as iterables. The parameters need not be constants, but if they depend on the argument then not much implemented functionality should be expected. All the subvectors of parameters are available: >>> from sympy import pprint >>> g = meijerg([1], [2], [3], [4], x) >>> pprint(g, use_unicode=False) __1, 1 /1 2 | \ /__ | | x| \_|2, 2 \3 4 | / >>> g.an (1,) >>> g.ap (1, 2) >>> g.aother (2,) >>> g.bm (3,) >>> g.bq (3, 4) >>> g.bother (4,) The Meijer G-function generalizes the hypergeometric functions. In some cases it can be expressed in terms of hypergeometric functions, using Slater's theorem. For example: >>> from sympy import hyperexpand >>> from sympy.abc import a, b, c >>> hyperexpand(meijerg([a], [], [c], [b], x), allow_hyper=True) x**c*gamma(-a + c + 1)*hyper((-a + c + 1,), (-b + c + 1,), -x)/gamma(-b + c + 1) Thus the Meijer G-function also subsumes many named functions as special cases. You can use ``expand_func()`` or ``hyperexpand()`` to (try to) rewrite a Meijer G-function in terms of named special functions. For example: >>> from sympy import expand_func, S >>> expand_func(meijerg([[],[]], [[0],[]], -x)) exp(x) >>> hyperexpand(meijerg([[],[]], [[S(1)/2],[0]], (x/2)**2)) sin(x)/sqrt(pi) See Also ======== hyper sympy.simplify.hyperexpand References ========== .. [1] Luke, Y. L. (1969), The Special Functions and Their Approximations, Volume 1 .. [2] https://en.wikipedia.org/wiki/Meijer_G-function """ def __new__(cls, *args, **kwargs): if len(args) == 5: args = [(args[0], args[1]), (args[2], args[3]), args[4]] if len(args) != 3: raise TypeError("args must be either as, as', bs, bs', z or " "as, bs, z") def tr(p): if len(p) != 2: raise TypeError("wrong argument") return TupleArg(_prep_tuple(p[0]), _prep_tuple(p[1])) arg0, arg1 = tr(args[0]), tr(args[1]) if Tuple(arg0, arg1).has(oo, zoo, -oo): raise ValueError("G-function parameters must be finite") if any((a - b).is_Integer and a - b > 0 for a in arg0[0] for b in arg1[0]): raise ValueError("no parameter a1, ..., an may differ from " "any b1, ..., bm by a positive integer") # TODO should we check convergence conditions? return Function.__new__(cls, arg0, arg1, args[2], **kwargs) def fdiff(self, argindex=3): if argindex != 3: return self._diff_wrt_parameter(argindex[1]) if len(self.an) >= 1: a = list(self.an) a[0] -= 1 G = meijerg(a, self.aother, self.bm, self.bother, self.argument) return 1/self.argument * ((self.an[0] - 1)*self + G) elif len(self.bm) >= 1: b = list(self.bm) b[0] += 1 G = meijerg(self.an, self.aother, b, self.bother, self.argument) return 1/self.argument * (self.bm[0]*self - G) else: return S.Zero def _diff_wrt_parameter(self, idx): # Differentiation wrt a parameter can only be done in very special # cases. In particular, if we want to differentiate with respect to # `a`, all other gamma factors have to reduce to rational functions. # # Let MT denote mellin transform. Suppose T(-s) is the gamma factor # appearing in the definition of G. Then # # MT(log(z)G(z)) = d/ds T(s) = d/da T(s) + ... # # Thus d/da G(z) = log(z)G(z) - ... # The ... can be evaluated as a G function under the above conditions, # the formula being most easily derived by using # # d Gamma(s + n) Gamma(s + n) / 1 1 1 \ # -- ------------ = ------------ | - + ---- + ... + --------- | # ds Gamma(s) Gamma(s) \ s s + 1 s + n - 1 / # # which follows from the difference equation of the digamma function. # (There is a similar equation for -n instead of +n). # We first figure out how to pair the parameters. an = list(self.an) ap = list(self.aother) bm = list(self.bm) bq = list(self.bother) if idx < len(an): an.pop(idx) else: idx -= len(an) if idx < len(ap): ap.pop(idx) else: idx -= len(ap) if idx < len(bm): bm.pop(idx) else: bq.pop(idx - len(bm)) pairs1 = [] pairs2 = [] for l1, l2, pairs in [(an, bq, pairs1), (ap, bm, pairs2)]: while l1: x = l1.pop() found = None for i, y in enumerate(l2): if not Mod((x - y).simplify(), 1): found = i break if found is None: raise NotImplementedError('Derivative not expressible ' 'as G-function?') y = l2[i] l2.pop(i) pairs.append((x, y)) # Now build the result. res = log(self.argument)*self for a, b in pairs1: sign = 1 n = a - b base = b if n < 0: sign = -1 n = b - a base = a for k in range(n): res -= sign*meijerg(self.an + (base + k + 1,), self.aother, self.bm, self.bother + (base + k + 0,), self.argument) for a, b in pairs2: sign = 1 n = b - a base = a if n < 0: sign = -1 n = a - b base = b for k in range(n): res -= sign*meijerg(self.an, self.aother + (base + k + 1,), self.bm + (base + k + 0,), self.bother, self.argument) return res def get_period(self): """ Return a number $P$ such that $G(x*exp(I*P)) == G(x)$. Examples ======== >>> from sympy import meijerg, pi, S >>> from sympy.abc import z >>> meijerg([1], [], [], [], z).get_period() 2*pi >>> meijerg([pi], [], [], [], z).get_period() oo >>> meijerg([1, 2], [], [], [], z).get_period() oo >>> meijerg([1,1], [2], [1, S(1)/2, S(1)/3], [1], z).get_period() 12*pi """ # This follows from slater's theorem. def compute(l): # first check that no two differ by an integer for i, b in enumerate(l): if not b.is_Rational: return oo for j in range(i + 1, len(l)): if not Mod((b - l[j]).simplify(), 1): return oo return reduce(ilcm, (x.q for x in l), 1) beta = compute(self.bm) alpha = compute(self.an) p, q = len(self.ap), len(self.bq) if p == q: if oo in (alpha, beta): return oo return 2*pi*ilcm(alpha, beta) elif p < q: return 2*pi*beta else: return 2*pi*alpha def _eval_expand_func(self, **hints): from sympy.simplify.hyperexpand import hyperexpand return hyperexpand(self) def _eval_evalf(self, prec): # The default code is insufficient for polar arguments. # mpmath provides an optional argument "r", which evaluates # G(z**(1/r)). I am not sure what its intended use is, but we hijack it # here in the following way: to evaluate at a number z of |argument| # less than (say) n*pi, we put r=1/n, compute z' = root(z, n) # (carefully so as not to loose the branch information), and evaluate # G(z'**(1/r)) = G(z'**n) = G(z). from sympy.functions import exp_polar, ceiling import mpmath znum = self.argument._eval_evalf(prec) if znum.has(exp_polar): znum, branch = znum.as_coeff_mul(exp_polar) if len(branch) != 1: return branch = branch[0].args[0]/I else: branch = S.Zero n = ceiling(abs(branch/S.Pi)) + 1 znum = znum**(S.One/n)*exp(I*branch / n) # Convert all args to mpf or mpc try: [z, r, ap, bq] = [arg._to_mpmath(prec) for arg in [znum, 1/n, self.args[0], self.args[1]]] except ValueError: return with mpmath.workprec(prec): v = mpmath.meijerg(ap, bq, z, r) return Expr._from_mpmath(v, prec) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.simplify.hyperexpand import hyperexpand return hyperexpand(self).as_leading_term(x, logx=logx, cdir=cdir) def integrand(self, s): """ Get the defining integrand D(s). """ from sympy.functions.special.gamma_functions import gamma return self.argument**s \ * Mul(*(gamma(b - s) for b in self.bm)) \ * Mul(*(gamma(1 - a + s) for a in self.an)) \ / Mul(*(gamma(1 - b + s) for b in self.bother)) \ / Mul(*(gamma(a - s) for a in self.aother)) @property def argument(self): """ Argument of the Meijer G-function. """ return self.args[2] @property def an(self): """ First set of numerator parameters. """ return Tuple(*self.args[0][0]) @property def ap(self): """ Combined numerator parameters. """ return Tuple(*(self.args[0][0] + self.args[0][1])) @property def aother(self): """ Second set of numerator parameters. """ return Tuple(*self.args[0][1]) @property def bm(self): """ First set of denominator parameters. """ return Tuple(*self.args[1][0]) @property def bq(self): """ Combined denominator parameters. """ return Tuple(*(self.args[1][0] + self.args[1][1])) @property def bother(self): """ Second set of denominator parameters. """ return Tuple(*self.args[1][1]) @property def _diffargs(self): return self.ap + self.bq @property def nu(self): """ A quantity related to the convergence region of the integral, c.f. references. """ return sum(self.bq) - sum(self.ap) @property def delta(self): """ A quantity related to the convergence region of the integral, c.f. references. """ return len(self.bm) + len(self.an) - S(len(self.ap) + len(self.bq))/2 @property def is_number(self): """ Returns true if expression has numeric data only. """ return not self.free_symbols class HyperRep(Function): """ A base class for "hyper representation functions". This is used exclusively in ``hyperexpand()``, but fits more logically here. pFq is branched at 1 if p == q+1. For use with slater-expansion, we want define an "analytic continuation" to all polar numbers, which is continuous on circles and on the ray t*exp_polar(I*pi). Moreover, we want a "nice" expression for the various cases. This base class contains the core logic, concrete derived classes only supply the actual functions. """ @classmethod def eval(cls, *args): from sympy.functions.elementary.complexes import unpolarify newargs = tuple(map(unpolarify, args[:-1])) + args[-1:] if args != newargs: return cls(*newargs) @classmethod def _expr_small(cls, x): """ An expression for F(x) which holds for |x| < 1. """ raise NotImplementedError @classmethod def _expr_small_minus(cls, x): """ An expression for F(-x) which holds for |x| < 1. """ raise NotImplementedError @classmethod def _expr_big(cls, x, n): """ An expression for F(exp_polar(2*I*pi*n)*x), |x| > 1. """ raise NotImplementedError @classmethod def _expr_big_minus(cls, x, n): """ An expression for F(exp_polar(2*I*pi*n + pi*I)*x), |x| > 1. """ raise NotImplementedError def _eval_rewrite_as_nonrep(self, *args, **kwargs): from sympy.functions.elementary.piecewise import Piecewise x, n = self.args[-1].extract_branch_factor(allow_half=True) minus = False newargs = self.args[:-1] + (x,) if not n.is_Integer: minus = True n -= S.Half newerargs = newargs + (n,) if minus: small = self._expr_small_minus(*newargs) big = self._expr_big_minus(*newerargs) else: small = self._expr_small(*newargs) big = self._expr_big(*newerargs) if big == small: return small return Piecewise((big, abs(x) > 1), (small, True)) def _eval_rewrite_as_nonrepsmall(self, *args, **kwargs): x, n = self.args[-1].extract_branch_factor(allow_half=True) args = self.args[:-1] + (x,) if not n.is_Integer: return self._expr_small_minus(*args) return self._expr_small(*args) class HyperRep_power1(HyperRep): """ Return a representative for hyper([-a], [], z) == (1 - z)**a. """ @classmethod def _expr_small(cls, a, x): return (1 - x)**a @classmethod def _expr_small_minus(cls, a, x): return (1 + x)**a @classmethod def _expr_big(cls, a, x, n): if a.is_integer: return cls._expr_small(a, x) return (x - 1)**a*exp((2*n - 1)*pi*I*a) @classmethod def _expr_big_minus(cls, a, x, n): if a.is_integer: return cls._expr_small_minus(a, x) return (1 + x)**a*exp(2*n*pi*I*a) class HyperRep_power2(HyperRep): """ Return a representative for hyper([a, a - 1/2], [2*a], z). """ @classmethod def _expr_small(cls, a, x): return 2**(2*a - 1)*(1 + sqrt(1 - x))**(1 - 2*a) @classmethod def _expr_small_minus(cls, a, x): return 2**(2*a - 1)*(1 + sqrt(1 + x))**(1 - 2*a) @classmethod def _expr_big(cls, a, x, n): sgn = -1 if n.is_odd: sgn = 1 n -= 1 return 2**(2*a - 1)*(1 + sgn*I*sqrt(x - 1))**(1 - 2*a) \ *exp(-2*n*pi*I*a) @classmethod def _expr_big_minus(cls, a, x, n): sgn = 1 if n.is_odd: sgn = -1 return sgn*2**(2*a - 1)*(sqrt(1 + x) + sgn)**(1 - 2*a)*exp(-2*pi*I*a*n) class HyperRep_log1(HyperRep): """ Represent -z*hyper([1, 1], [2], z) == log(1 - z). """ @classmethod def _expr_small(cls, x): return log(1 - x) @classmethod def _expr_small_minus(cls, x): return log(1 + x) @classmethod def _expr_big(cls, x, n): return log(x - 1) + (2*n - 1)*pi*I @classmethod def _expr_big_minus(cls, x, n): return log(1 + x) + 2*n*pi*I class HyperRep_atanh(HyperRep): """ Represent hyper([1/2, 1], [3/2], z) == atanh(sqrt(z))/sqrt(z). """ @classmethod def _expr_small(cls, x): return atanh(sqrt(x))/sqrt(x) def _expr_small_minus(cls, x): return atan(sqrt(x))/sqrt(x) def _expr_big(cls, x, n): if n.is_even: return (acoth(sqrt(x)) + I*pi/2)/sqrt(x) else: return (acoth(sqrt(x)) - I*pi/2)/sqrt(x) def _expr_big_minus(cls, x, n): if n.is_even: return atan(sqrt(x))/sqrt(x) else: return (atan(sqrt(x)) - pi)/sqrt(x) class HyperRep_asin1(HyperRep): """ Represent hyper([1/2, 1/2], [3/2], z) == asin(sqrt(z))/sqrt(z). """ @classmethod def _expr_small(cls, z): return asin(sqrt(z))/sqrt(z) @classmethod def _expr_small_minus(cls, z): return asinh(sqrt(z))/sqrt(z) @classmethod def _expr_big(cls, z, n): return S.NegativeOne**n*((S.Half - n)*pi/sqrt(z) + I*acosh(sqrt(z))/sqrt(z)) @classmethod def _expr_big_minus(cls, z, n): return S.NegativeOne**n*(asinh(sqrt(z))/sqrt(z) + n*pi*I/sqrt(z)) class HyperRep_asin2(HyperRep): """ Represent hyper([1, 1], [3/2], z) == asin(sqrt(z))/sqrt(z)/sqrt(1-z). """ # TODO this can be nicer @classmethod def _expr_small(cls, z): return HyperRep_asin1._expr_small(z) \ /HyperRep_power1._expr_small(S.Half, z) @classmethod def _expr_small_minus(cls, z): return HyperRep_asin1._expr_small_minus(z) \ /HyperRep_power1._expr_small_minus(S.Half, z) @classmethod def _expr_big(cls, z, n): return HyperRep_asin1._expr_big(z, n) \ /HyperRep_power1._expr_big(S.Half, z, n) @classmethod def _expr_big_minus(cls, z, n): return HyperRep_asin1._expr_big_minus(z, n) \ /HyperRep_power1._expr_big_minus(S.Half, z, n) class HyperRep_sqrts1(HyperRep): """ Return a representative for hyper([-a, 1/2 - a], [1/2], z). """ @classmethod def _expr_small(cls, a, z): return ((1 - sqrt(z))**(2*a) + (1 + sqrt(z))**(2*a))/2 @classmethod def _expr_small_minus(cls, a, z): return (1 + z)**a*cos(2*a*atan(sqrt(z))) @classmethod def _expr_big(cls, a, z, n): if n.is_even: return ((sqrt(z) + 1)**(2*a)*exp(2*pi*I*n*a) + (sqrt(z) - 1)**(2*a)*exp(2*pi*I*(n - 1)*a))/2 else: n -= 1 return ((sqrt(z) - 1)**(2*a)*exp(2*pi*I*a*(n + 1)) + (sqrt(z) + 1)**(2*a)*exp(2*pi*I*a*n))/2 @classmethod def _expr_big_minus(cls, a, z, n): if n.is_even: return (1 + z)**a*exp(2*pi*I*n*a)*cos(2*a*atan(sqrt(z))) else: return (1 + z)**a*exp(2*pi*I*n*a)*cos(2*a*atan(sqrt(z)) - 2*pi*a) class HyperRep_sqrts2(HyperRep): """ Return a representative for sqrt(z)/2*[(1-sqrt(z))**2a - (1 + sqrt(z))**2a] == -2*z/(2*a+1) d/dz hyper([-a - 1/2, -a], [1/2], z)""" @classmethod def _expr_small(cls, a, z): return sqrt(z)*((1 - sqrt(z))**(2*a) - (1 + sqrt(z))**(2*a))/2 @classmethod def _expr_small_minus(cls, a, z): return sqrt(z)*(1 + z)**a*sin(2*a*atan(sqrt(z))) @classmethod def _expr_big(cls, a, z, n): if n.is_even: return sqrt(z)/2*((sqrt(z) - 1)**(2*a)*exp(2*pi*I*a*(n - 1)) - (sqrt(z) + 1)**(2*a)*exp(2*pi*I*a*n)) else: n -= 1 return sqrt(z)/2*((sqrt(z) - 1)**(2*a)*exp(2*pi*I*a*(n + 1)) - (sqrt(z) + 1)**(2*a)*exp(2*pi*I*a*n)) def _expr_big_minus(cls, a, z, n): if n.is_even: return (1 + z)**a*exp(2*pi*I*n*a)*sqrt(z)*sin(2*a*atan(sqrt(z))) else: return (1 + z)**a*exp(2*pi*I*n*a)*sqrt(z) \ *sin(2*a*atan(sqrt(z)) - 2*pi*a) class HyperRep_log2(HyperRep): """ Represent log(1/2 + sqrt(1 - z)/2) == -z/4*hyper([3/2, 1, 1], [2, 2], z) """ @classmethod def _expr_small(cls, z): return log(S.Half + sqrt(1 - z)/2) @classmethod def _expr_small_minus(cls, z): return log(S.Half + sqrt(1 + z)/2) @classmethod def _expr_big(cls, z, n): if n.is_even: return (n - S.Half)*pi*I + log(sqrt(z)/2) + I*asin(1/sqrt(z)) else: return (n - S.Half)*pi*I + log(sqrt(z)/2) - I*asin(1/sqrt(z)) def _expr_big_minus(cls, z, n): if n.is_even: return pi*I*n + log(S.Half + sqrt(1 + z)/2) else: return pi*I*n + log(sqrt(1 + z)/2 - S.Half) class HyperRep_cosasin(HyperRep): """ Represent hyper([a, -a], [1/2], z) == cos(2*a*asin(sqrt(z))). """ # Note there are many alternative expressions, e.g. as powers of a sum of # square roots. @classmethod def _expr_small(cls, a, z): return cos(2*a*asin(sqrt(z))) @classmethod def _expr_small_minus(cls, a, z): return cosh(2*a*asinh(sqrt(z))) @classmethod def _expr_big(cls, a, z, n): return cosh(2*a*acosh(sqrt(z)) + a*pi*I*(2*n - 1)) @classmethod def _expr_big_minus(cls, a, z, n): return cosh(2*a*asinh(sqrt(z)) + 2*a*pi*I*n) class HyperRep_sinasin(HyperRep): """ Represent 2*a*z*hyper([1 - a, 1 + a], [3/2], z) == sqrt(z)/sqrt(1-z)*sin(2*a*asin(sqrt(z))) """ @classmethod def _expr_small(cls, a, z): return sqrt(z)/sqrt(1 - z)*sin(2*a*asin(sqrt(z))) @classmethod def _expr_small_minus(cls, a, z): return -sqrt(z)/sqrt(1 + z)*sinh(2*a*asinh(sqrt(z))) @classmethod def _expr_big(cls, a, z, n): return -1/sqrt(1 - 1/z)*sinh(2*a*acosh(sqrt(z)) + a*pi*I*(2*n - 1)) @classmethod def _expr_big_minus(cls, a, z, n): return -1/sqrt(1 + 1/z)*sinh(2*a*asinh(sqrt(z)) + 2*a*pi*I*n) class appellf1(Function): r""" This is the Appell hypergeometric function of two variables as: .. math :: F_1(a,b_1,b_2,c,x,y) = \sum_{m=0}^{\infty} \sum_{n=0}^{\infty} \frac{(a)_{m+n} (b_1)_m (b_2)_n}{(c)_{m+n}} \frac{x^m y^n}{m! n!}. Examples ======== >>> from sympy import appellf1, symbols >>> x, y, a, b1, b2, c = symbols('x y a b1 b2 c') >>> appellf1(2., 1., 6., 4., 5., 6.) 0.0063339426292673 >>> appellf1(12., 12., 6., 4., 0.5, 0.12) 172870711.659936 >>> appellf1(40, 2, 6, 4, 15, 60) appellf1(40, 2, 6, 4, 15, 60) >>> appellf1(20., 12., 10., 3., 0.5, 0.12) 15605338197184.4 >>> appellf1(40, 2, 6, 4, x, y) appellf1(40, 2, 6, 4, x, y) >>> appellf1(a, b1, b2, c, x, y) appellf1(a, b1, b2, c, x, y) References ========== .. [1] https://en.wikipedia.org/wiki/Appell_series .. [2] http://functions.wolfram.com/HypergeometricFunctions/AppellF1/ """ @classmethod def eval(cls, a, b1, b2, c, x, y): if default_sort_key(b1) > default_sort_key(b2): b1, b2 = b2, b1 x, y = y, x return cls(a, b1, b2, c, x, y) elif b1 == b2 and default_sort_key(x) > default_sort_key(y): x, y = y, x return cls(a, b1, b2, c, x, y) if x == 0 and y == 0: return S.One def fdiff(self, argindex=5): a, b1, b2, c, x, y = self.args if argindex == 5: return (a*b1/c)*appellf1(a + 1, b1 + 1, b2, c + 1, x, y) elif argindex == 6: return (a*b2/c)*appellf1(a + 1, b1, b2 + 1, c + 1, x, y) elif argindex in (1, 2, 3, 4): return Derivative(self, self.args[argindex-1]) else: raise ArgumentIndexError(self, argindex)
2ecf31945c1d95b237bc6bb588739951f7d269f94564109627572d14ad011d79
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 not z 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 not z 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
53aa32236aead5cf231020905d44baf7d4daaac6c26c3cd7c6b37f56fe828e08
from sympy.core import S, sympify, diff from sympy.core.function import Function, ArgumentIndexError from sympy.core.logic import fuzzy_not from sympy.core.relational import Eq, Ne from sympy.functions.elementary.complexes import im, sign from sympy.functions.elementary.piecewise import Piecewise from sympy.polys.polyerrors import PolynomialError from sympy.utilities.decorator import deprecated from sympy.utilities.misc import filldedent ############################################################################### ################################ DELTA FUNCTION ############################### ############################################################################### class DiracDelta(Function): r""" The DiracDelta function and its derivatives. Explanation =========== DiracDelta is not an ordinary function. It can be rigorously defined either as a distribution or as a measure. DiracDelta only makes sense in definite integrals, and in particular, integrals of the form ``Integral(f(x)*DiracDelta(x - x0), (x, a, b))``, where it equals ``f(x0)`` if ``a <= x0 <= b`` and ``0`` otherwise. Formally, DiracDelta acts in some ways like a function that is ``0`` everywhere except at ``0``, but in many ways it also does not. It can often be useful to treat DiracDelta in formal ways, building up and manipulating expressions with delta functions (which may eventually be integrated), but care must be taken to not treat it as a real function. SymPy's ``oo`` is similar. It only truly makes sense formally in certain contexts (such as integration limits), but SymPy allows its use everywhere, and it tries to be consistent with operations on it (like ``1/oo``), but it is easy to get into trouble and get wrong results if ``oo`` is treated too much like a number. Similarly, if DiracDelta is treated too much like a function, it is easy to get wrong or nonsensical results. DiracDelta function has the following properties: 1) $\frac{d}{d x} \theta(x) = \delta(x)$ 2) $\int_{-\infty}^\infty \delta(x - a)f(x)\, dx = f(a)$ and $\int_{a- \epsilon}^{a+\epsilon} \delta(x - a)f(x)\, dx = f(a)$ 3) $\delta(x) = 0$ for all $x \neq 0$ 4) $\delta(g(x)) = \sum_i \frac{\delta(x - x_i)}{\|g'(x_i)\|}$ where $x_i$ are the roots of $g$ 5) $\delta(-x) = \delta(x)$ Derivatives of ``k``-th order of DiracDelta have the following properties: 6) $\delta(x, k) = 0$ for all $x \neq 0$ 7) $\delta(-x, k) = -\delta(x, k)$ for odd $k$ 8) $\delta(-x, k) = \delta(x, k)$ for even $k$ Examples ======== >>> from sympy import DiracDelta, diff, pi >>> from sympy.abc import x, y >>> DiracDelta(x) DiracDelta(x) >>> DiracDelta(1) 0 >>> DiracDelta(-1) 0 >>> DiracDelta(pi) 0 >>> DiracDelta(x - 4).subs(x, 4) DiracDelta(0) >>> diff(DiracDelta(x)) DiracDelta(x, 1) >>> diff(DiracDelta(x - 1),x,2) DiracDelta(x - 1, 2) >>> diff(DiracDelta(x**2 - 1),x,2) 2*(2*x**2*DiracDelta(x**2 - 1, 2) + DiracDelta(x**2 - 1, 1)) >>> DiracDelta(3*x).is_simple(x) True >>> DiracDelta(x**2).is_simple(x) False >>> DiracDelta((x**2 - 1)*y).expand(diracdelta=True, wrt=x) DiracDelta(x - 1)/(2*Abs(y)) + DiracDelta(x + 1)/(2*Abs(y)) See Also ======== Heaviside sympy.simplify.simplify.simplify, is_simple sympy.functions.special.tensor_functions.KroneckerDelta References ========== .. [1] http://mathworld.wolfram.com/DeltaFunction.html """ is_real = True def fdiff(self, argindex=1): """ Returns the first derivative of a DiracDelta Function. Explanation =========== The difference between ``diff()`` and ``fdiff()`` is: ``diff()`` is the user-level function and ``fdiff()`` is an object method. ``fdiff()`` is a convenience method available in the ``Function`` class. It returns the derivative of the function without considering the chain rule. ``diff(function, x)`` calls ``Function._eval_derivative`` which in turn calls ``fdiff()`` internally to compute the derivative of the function. Examples ======== >>> from sympy import DiracDelta, diff >>> from sympy.abc import x >>> DiracDelta(x).fdiff() DiracDelta(x, 1) >>> DiracDelta(x, 1).fdiff() DiracDelta(x, 2) >>> DiracDelta(x**2 - 1).fdiff() DiracDelta(x**2 - 1, 1) >>> diff(DiracDelta(x, 1)).fdiff() DiracDelta(x, 3) Parameters ========== argindex : integer degree of derivative """ if argindex == 1: #I didn't know if there is a better way to handle default arguments k = 0 if len(self.args) > 1: k = self.args[1] return self.func(self.args[0], k + 1) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg, k=0): """ Returns a simplified form or a value of DiracDelta depending on the argument passed by the DiracDelta object. Explanation =========== The ``eval()`` method is automatically called when the ``DiracDelta`` class is about to be instantiated and it returns either some simplified instance or the unevaluated instance depending on the argument passed. In other words, ``eval()`` method is not needed to be called explicitly, it is being called and evaluated once the object is called. Examples ======== >>> from sympy import DiracDelta, S >>> from sympy.abc import x >>> DiracDelta(x) DiracDelta(x) >>> DiracDelta(-x, 1) -DiracDelta(x, 1) >>> DiracDelta(1) 0 >>> DiracDelta(5, 1) 0 >>> DiracDelta(0) DiracDelta(0) >>> DiracDelta(-1) 0 >>> DiracDelta(S.NaN) nan >>> DiracDelta(x).eval(1) 0 >>> DiracDelta(x - 100).subs(x, 5) 0 >>> DiracDelta(x - 100).subs(x, 100) DiracDelta(0) Parameters ========== k : integer order of derivative arg : argument passed to DiracDelta """ k = sympify(k) if not k.is_Integer or k.is_negative: raise ValueError("Error: the second argument of DiracDelta must be \ a non-negative integer, %s given instead." % (k,)) arg = sympify(arg) if arg is S.NaN: return S.NaN if arg.is_nonzero: return S.Zero if fuzzy_not(im(arg).is_zero): raise ValueError(filldedent(''' Function defined only for Real Values. Complex part: %s found in %s .''' % ( repr(im(arg)), repr(arg)))) c, nc = arg.args_cnc() if c and c[0] is S.NegativeOne: # keep this fast and simple instead of using # could_extract_minus_sign if k.is_odd: return -cls(-arg, k) elif k.is_even: return cls(-arg, k) if k else cls(-arg) @deprecated(useinstead="expand(diracdelta=True, wrt=x)", issue=12859, deprecated_since_version="1.1") def simplify(self, x, **kwargs): return self.expand(diracdelta=True, wrt=x) def _eval_expand_diracdelta(self, **hints): """ Compute a simplified representation of the function using property number 4. Pass ``wrt`` as a hint to expand the expression with respect to a particular variable. Explanation =========== ``wrt`` is: - a variable with respect to which a DiracDelta expression will get expanded. Examples ======== >>> from sympy import DiracDelta >>> from sympy.abc import x, y >>> DiracDelta(x*y).expand(diracdelta=True, wrt=x) DiracDelta(x)/Abs(y) >>> DiracDelta(x*y).expand(diracdelta=True, wrt=y) DiracDelta(y)/Abs(x) >>> DiracDelta(x**2 + x - 2).expand(diracdelta=True, wrt=x) DiracDelta(x - 1)/3 + DiracDelta(x + 2)/3 See Also ======== is_simple, Diracdelta """ from sympy.polys.polyroots import roots wrt = hints.get('wrt', None) if wrt is None: free = self.free_symbols if len(free) == 1: wrt = free.pop() else: raise TypeError(filldedent(''' When there is more than 1 free symbol or variable in the expression, the 'wrt' keyword is required as a hint to expand when using the DiracDelta hint.''')) if not self.args[0].has(wrt) or (len(self.args) > 1 and self.args[1] != 0 ): return self try: argroots = roots(self.args[0], wrt) result = 0 valid = True darg = abs(diff(self.args[0], wrt)) for r, m in argroots.items(): if r.is_real is not False and m == 1: result += self.func(wrt - r)/darg.subs(wrt, r) else: # don't handle non-real and if m != 1 then # a polynomial will have a zero in the derivative (darg) # at r valid = False break if valid: return result except PolynomialError: pass return self def is_simple(self, x): """ Tells whether the argument(args[0]) of DiracDelta is a linear expression in *x*. Examples ======== >>> from sympy import DiracDelta, cos >>> from sympy.abc import x, y >>> DiracDelta(x*y).is_simple(x) True >>> DiracDelta(x*y).is_simple(y) True >>> DiracDelta(x**2 + x - 2).is_simple(x) False >>> DiracDelta(cos(x)).is_simple(x) False Parameters ========== x : can be a symbol See Also ======== sympy.simplify.simplify.simplify, DiracDelta """ p = self.args[0].as_poly(x) if p: return p.degree() == 1 return False def _eval_rewrite_as_Piecewise(self, *args, **kwargs): """ Represents DiracDelta in a piecewise form. Examples ======== >>> from sympy import DiracDelta, Piecewise, Symbol >>> x = Symbol('x') >>> DiracDelta(x).rewrite(Piecewise) Piecewise((DiracDelta(0), Eq(x, 0)), (0, True)) >>> DiracDelta(x - 5).rewrite(Piecewise) Piecewise((DiracDelta(0), Eq(x, 5)), (0, True)) >>> DiracDelta(x**2 - 5).rewrite(Piecewise) Piecewise((DiracDelta(0), Eq(x**2, 5)), (0, True)) >>> DiracDelta(x - 5, 4).rewrite(Piecewise) DiracDelta(x - 5, 4) """ if len(args) == 1: return Piecewise((DiracDelta(0), Eq(args[0], 0)), (0, True)) def _eval_rewrite_as_SingularityFunction(self, *args, **kwargs): """ Returns the DiracDelta expression written in the form of Singularity Functions. """ from sympy.solvers import solve from sympy.functions import SingularityFunction if self == DiracDelta(0): return SingularityFunction(0, 0, -1) if self == DiracDelta(0, 1): return SingularityFunction(0, 0, -2) free = self.free_symbols if len(free) == 1: x = (free.pop()) if len(args) == 1: return SingularityFunction(x, solve(args[0], x)[0], -1) return SingularityFunction(x, solve(args[0], x)[0], -args[1] - 1) else: # I don't know how to handle the case for DiracDelta expressions # having arguments with more than one variable. raise TypeError(filldedent(''' rewrite(SingularityFunction) doesn't support arguments with more that 1 variable.''')) ############################################################################### ############################## HEAVISIDE FUNCTION ############################# ############################################################################### class Heaviside(Function): r""" Heaviside step function. Explanation =========== The Heaviside step function has the following properties: 1) $\frac{d}{d x} \theta(x) = \delta(x)$ 2) $\theta(x) = \begin{cases} 0 & \text{for}\: x < 0 \\ \frac{1}{2} & \text{for}\: x = 0 \\1 & \text{for}\: x > 0 \end{cases}$ 3) $\frac{d}{d x} \max(x, 0) = \theta(x)$ Heaviside(x) is printed as $\theta(x)$ with the SymPy LaTeX printer. The value at 0 is set differently in different fields. SymPy uses 1/2, which is a convention from electronics and signal processing, and is consistent with solving improper integrals by Fourier transform and convolution. To specify a different value of Heaviside at ``x=0``, a second argument can be given. Using ``Heaviside(x, nan)`` gives an expression that will evaluate to nan for x=0. .. versionchanged:: 1.9 ``Heaviside(0)`` now returns 1/2 (before: undefined) Examples ======== >>> from sympy import Heaviside, nan >>> from sympy.abc import x >>> Heaviside(9) 1 >>> Heaviside(-9) 0 >>> Heaviside(0) 1/2 >>> Heaviside(0, nan) nan >>> (Heaviside(x) + 1).replace(Heaviside(x), Heaviside(x, 1)) Heaviside(x, 1) + 1 See Also ======== DiracDelta References ========== .. [1] http://mathworld.wolfram.com/HeavisideStepFunction.html .. [2] http://dlmf.nist.gov/1.16#iv """ is_real = True def fdiff(self, argindex=1): """ Returns the first derivative of a Heaviside Function. Examples ======== >>> from sympy import Heaviside, diff >>> from sympy.abc import x >>> Heaviside(x).fdiff() DiracDelta(x) >>> Heaviside(x**2 - 1).fdiff() DiracDelta(x**2 - 1) >>> diff(Heaviside(x)).fdiff() DiracDelta(x, 1) Parameters ========== argindex : integer order of derivative """ if argindex == 1: return DiracDelta(self.args[0]) else: raise ArgumentIndexError(self, argindex) def __new__(cls, arg, H0=S.Half, **options): if isinstance(H0, Heaviside) and len(H0.args) == 1: H0 = S.Half return super(cls, cls).__new__(cls, arg, H0, **options) @property def pargs(self): """Args without default S.Half""" args = self.args if args[1] is S.Half: args = args[:1] return args @classmethod def eval(cls, arg, H0=S.Half): """ Returns a simplified form or a value of Heaviside depending on the argument passed by the Heaviside object. Explanation =========== The ``eval()`` method is automatically called when the ``Heaviside`` class is about to be instantiated and it returns either some simplified instance or the unevaluated instance depending on the argument passed. In other words, ``eval()`` method is not needed to be called explicitly, it is being called and evaluated once the object is called. Examples ======== >>> from sympy import Heaviside, S >>> from sympy.abc import x >>> Heaviside(x) Heaviside(x) >>> Heaviside(19) 1 >>> Heaviside(0) 1/2 >>> Heaviside(0, 1) 1 >>> Heaviside(-5) 0 >>> Heaviside(S.NaN) nan >>> Heaviside(x).eval(42) 1 >>> Heaviside(x - 100).subs(x, 5) 0 >>> Heaviside(x - 100).subs(x, 105) 1 Parameters ========== arg : argument passed by Heaviside object H0 : value of Heaviside(0) """ H0 = sympify(H0) arg = sympify(arg) if arg.is_extended_negative: return S.Zero elif arg.is_extended_positive: return S.One elif arg.is_zero: return H0 elif arg is S.NaN: return S.NaN elif fuzzy_not(im(arg).is_zero): raise ValueError("Function defined only for Real Values. Complex part: %s found in %s ." % (repr(im(arg)), repr(arg)) ) def _eval_rewrite_as_Piecewise(self, arg, H0=None, **kwargs): """ Represents Heaviside in a Piecewise form. Examples ======== >>> from sympy import Heaviside, Piecewise, Symbol, nan >>> x = Symbol('x') >>> Heaviside(x).rewrite(Piecewise) Piecewise((0, x < 0), (1/2, Eq(x, 0)), (1, x > 0)) >>> Heaviside(x,nan).rewrite(Piecewise) Piecewise((0, x < 0), (nan, Eq(x, 0)), (1, x > 0)) >>> Heaviside(x - 5).rewrite(Piecewise) Piecewise((0, x < 5), (1/2, Eq(x, 5)), (1, x > 5)) >>> Heaviside(x**2 - 1).rewrite(Piecewise) Piecewise((0, x**2 < 1), (1/2, Eq(x**2, 1)), (1, x**2 > 1)) """ if H0 == 0: return Piecewise((0, arg <= 0), (1, arg > 0)) if H0 == 1: return Piecewise((0, arg < 0), (1, arg >= 0)) return Piecewise((0, arg < 0), (H0, Eq(arg, 0)), (1, arg > 0)) def _eval_rewrite_as_sign(self, arg, H0=S.Half, **kwargs): """ Represents the Heaviside function in the form of sign function. Explanation =========== The value of Heaviside(0) must be 1/2 for rewritting as sign to be strictly equivalent. For easier usage, we also allow this rewriting when Heaviside(0) is undefined. Examples ======== >>> from sympy import Heaviside, Symbol, sign, nan >>> x = Symbol('x', real=True) >>> y = Symbol('y') >>> Heaviside(x).rewrite(sign) sign(x)/2 + 1/2 >>> Heaviside(x, 0).rewrite(sign) Piecewise((sign(x)/2 + 1/2, Ne(x, 0)), (0, True)) >>> Heaviside(x, nan).rewrite(sign) Piecewise((sign(x)/2 + 1/2, Ne(x, 0)), (nan, True)) >>> Heaviside(x - 2).rewrite(sign) sign(x - 2)/2 + 1/2 >>> Heaviside(x**2 - 2*x + 1).rewrite(sign) sign(x**2 - 2*x + 1)/2 + 1/2 >>> Heaviside(y).rewrite(sign) Heaviside(y) >>> Heaviside(y**2 - 2*y + 1).rewrite(sign) Heaviside(y**2 - 2*y + 1) See Also ======== sign """ if arg.is_extended_real: pw1 = Piecewise( ((sign(arg) + 1)/2, Ne(arg, 0)), (Heaviside(0, H0=H0), True)) pw2 = Piecewise( ((sign(arg) + 1)/2, Eq(Heaviside(0, H0=H0), S.Half)), (pw1, True)) return pw2 def _eval_rewrite_as_SingularityFunction(self, args, H0=S.Half, **kwargs): """ Returns the Heaviside expression written in the form of Singularity Functions. """ from sympy.solvers import solve from sympy.functions import SingularityFunction if self == Heaviside(0): return SingularityFunction(0, 0, 0) free = self.free_symbols if len(free) == 1: x = (free.pop()) return SingularityFunction(x, solve(args, x)[0], 0) # TODO # ((x - 5)**3*Heaviside(x - 5)).rewrite(SingularityFunction) should output # SingularityFunction(x, 5, 0) instead of (x - 5)**3*SingularityFunction(x, 5, 0) else: # I don't know how to handle the case for Heaviside expressions # having arguments with more than one variable. raise TypeError(filldedent(''' rewrite(SingularityFunction) doesn't support arguments with more that 1 variable.'''))
d3dd9cb2699e1067b9e944302315d1b9b122d7b25f18f6b649c6ec41d000568f
from sympy.core.expr import Expr from sympy.core.function import Function, ArgumentIndexError from sympy.core.numbers import I, pi from sympy.core.singleton import S from sympy.core.symbol import Dummy from sympy.core.sympify import sympify from sympy.functions import assoc_legendre from sympy.functions.combinatorial.factorials import factorial 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 sin, cos, cot _x = Dummy("x") class Ynm(Function): r""" Spherical harmonics defined as .. math:: Y_n^m(\theta, \varphi) := \sqrt{\frac{(2n+1)(n-m)!}{4\pi(n+m)!}} \exp(i m \varphi) \mathrm{P}_n^m\left(\cos(\theta)\right) Explanation =========== ``Ynm()`` gives the spherical harmonic function of order $n$ and $m$ in $\theta$ and $\varphi$, $Y_n^m(\theta, \varphi)$. The four parameters are as follows: $n \geq 0$ an integer and $m$ an integer such that $-n \leq m \leq n$ holds. The two angles are real-valued with $\theta \in [0, \pi]$ and $\varphi \in [0, 2\pi]$. Examples ======== >>> from sympy import Ynm, Symbol, simplify >>> from sympy.abc import n,m >>> theta = Symbol("theta") >>> phi = Symbol("phi") >>> Ynm(n, m, theta, phi) Ynm(n, m, theta, phi) Several symmetries are known, for the order: >>> Ynm(n, -m, theta, phi) (-1)**m*exp(-2*I*m*phi)*Ynm(n, m, theta, phi) As well as for the angles: >>> Ynm(n, m, -theta, phi) Ynm(n, m, theta, phi) >>> Ynm(n, m, theta, -phi) exp(-2*I*m*phi)*Ynm(n, m, theta, phi) For specific integers $n$ and $m$ we can evaluate the harmonics to more useful expressions: >>> simplify(Ynm(0, 0, theta, phi).expand(func=True)) 1/(2*sqrt(pi)) >>> simplify(Ynm(1, -1, theta, phi).expand(func=True)) sqrt(6)*exp(-I*phi)*sin(theta)/(4*sqrt(pi)) >>> simplify(Ynm(1, 0, theta, phi).expand(func=True)) sqrt(3)*cos(theta)/(2*sqrt(pi)) >>> simplify(Ynm(1, 1, theta, phi).expand(func=True)) -sqrt(6)*exp(I*phi)*sin(theta)/(4*sqrt(pi)) >>> simplify(Ynm(2, -2, theta, phi).expand(func=True)) sqrt(30)*exp(-2*I*phi)*sin(theta)**2/(8*sqrt(pi)) >>> simplify(Ynm(2, -1, theta, phi).expand(func=True)) sqrt(30)*exp(-I*phi)*sin(2*theta)/(8*sqrt(pi)) >>> simplify(Ynm(2, 0, theta, phi).expand(func=True)) sqrt(5)*(3*cos(theta)**2 - 1)/(4*sqrt(pi)) >>> simplify(Ynm(2, 1, theta, phi).expand(func=True)) -sqrt(30)*exp(I*phi)*sin(2*theta)/(8*sqrt(pi)) >>> simplify(Ynm(2, 2, theta, phi).expand(func=True)) sqrt(30)*exp(2*I*phi)*sin(theta)**2/(8*sqrt(pi)) We can differentiate the functions with respect to both angles: >>> from sympy import Ynm, Symbol, diff >>> from sympy.abc import n,m >>> theta = Symbol("theta") >>> phi = Symbol("phi") >>> diff(Ynm(n, m, theta, phi), theta) m*cot(theta)*Ynm(n, m, theta, phi) + sqrt((-m + n)*(m + n + 1))*exp(-I*phi)*Ynm(n, m + 1, theta, phi) >>> diff(Ynm(n, m, theta, phi), phi) I*m*Ynm(n, m, theta, phi) Further we can compute the complex conjugation: >>> from sympy import Ynm, Symbol, conjugate >>> from sympy.abc import n,m >>> theta = Symbol("theta") >>> phi = Symbol("phi") >>> conjugate(Ynm(n, m, theta, phi)) (-1)**(2*m)*exp(-2*I*m*phi)*Ynm(n, m, theta, phi) To get back the well known expressions in spherical coordinates, we use full expansion: >>> from sympy import Ynm, Symbol, expand_func >>> from sympy.abc import n,m >>> theta = Symbol("theta") >>> phi = Symbol("phi") >>> expand_func(Ynm(n, m, theta, phi)) sqrt((2*n + 1)*factorial(-m + n)/factorial(m + n))*exp(I*m*phi)*assoc_legendre(n, m, cos(theta))/(2*sqrt(pi)) See Also ======== Ynm_c, Znm References ========== .. [1] https://en.wikipedia.org/wiki/Spherical_harmonics .. [2] http://mathworld.wolfram.com/SphericalHarmonic.html .. [3] http://functions.wolfram.com/Polynomials/SphericalHarmonicY/ .. [4] http://dlmf.nist.gov/14.30 """ @classmethod def eval(cls, n, m, theta, phi): n, m, theta, phi = [sympify(x) for x in (n, m, theta, phi)] # Handle negative index m and arguments theta, phi if m.could_extract_minus_sign(): m = -m return S.NegativeOne**m * exp(-2*I*m*phi) * Ynm(n, m, theta, phi) if theta.could_extract_minus_sign(): theta = -theta return Ynm(n, m, theta, phi) if phi.could_extract_minus_sign(): phi = -phi return exp(-2*I*m*phi) * Ynm(n, m, theta, phi) # TODO Add more simplififcation here def _eval_expand_func(self, **hints): n, m, theta, phi = self.args rv = (sqrt((2*n + 1)/(4*pi) * factorial(n - m)/factorial(n + m)) * exp(I*m*phi) * assoc_legendre(n, m, cos(theta))) # We can do this because of the range of theta return rv.subs(sqrt(-cos(theta)**2 + 1), sin(theta)) def fdiff(self, argindex=4): if argindex == 1: # Diff wrt n raise ArgumentIndexError(self, argindex) elif argindex == 2: # Diff wrt m raise ArgumentIndexError(self, argindex) elif argindex == 3: # Diff wrt theta n, m, theta, phi = self.args return (m * cot(theta) * Ynm(n, m, theta, phi) + sqrt((n - m)*(n + m + 1)) * exp(-I*phi) * Ynm(n, m + 1, theta, phi)) elif argindex == 4: # Diff wrt phi n, m, theta, phi = self.args return I * m * Ynm(n, m, theta, phi) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_polynomial(self, n, m, theta, phi, **kwargs): # TODO: Make sure n \in N # TODO: Assert |m| <= n ortherwise we should return 0 return self.expand(func=True) def _eval_rewrite_as_sin(self, n, m, theta, phi, **kwargs): return self.rewrite(cos) def _eval_rewrite_as_cos(self, n, m, theta, phi, **kwargs): # This method can be expensive due to extensive use of simplification! from sympy.simplify import simplify, trigsimp # TODO: Make sure n \in N # TODO: Assert |m| <= n ortherwise we should return 0 term = simplify(self.expand(func=True)) # We can do this because of the range of theta term = term.xreplace({Abs(sin(theta)):sin(theta)}) return simplify(trigsimp(term)) def _eval_conjugate(self): # TODO: Make sure theta \in R and phi \in R n, m, theta, phi = self.args return S.NegativeOne**m * self.func(n, -m, theta, phi) def as_real_imag(self, deep=True, **hints): # TODO: Handle deep and hints n, m, theta, phi = self.args re = (sqrt((2*n + 1)/(4*pi) * factorial(n - m)/factorial(n + m)) * cos(m*phi) * assoc_legendre(n, m, cos(theta))) im = (sqrt((2*n + 1)/(4*pi) * factorial(n - m)/factorial(n + m)) * sin(m*phi) * assoc_legendre(n, m, cos(theta))) return (re, im) def _eval_evalf(self, prec): # Note: works without this function by just calling # mpmath for Legendre polynomials. But using # the dedicated function directly is cleaner. from mpmath import mp, workprec n = self.args[0]._to_mpmath(prec) m = self.args[1]._to_mpmath(prec) theta = self.args[2]._to_mpmath(prec) phi = self.args[3]._to_mpmath(prec) with workprec(prec): res = mp.spherharm(n, m, theta, phi) return Expr._from_mpmath(res, prec) def Ynm_c(n, m, theta, phi): r""" Conjugate spherical harmonics defined as .. math:: \overline{Y_n^m(\theta, \varphi)} := (-1)^m Y_n^{-m}(\theta, \varphi). Examples ======== >>> from sympy import Ynm_c, Symbol, simplify >>> from sympy.abc import n,m >>> theta = Symbol("theta") >>> phi = Symbol("phi") >>> Ynm_c(n, m, theta, phi) (-1)**(2*m)*exp(-2*I*m*phi)*Ynm(n, m, theta, phi) >>> Ynm_c(n, m, -theta, phi) (-1)**(2*m)*exp(-2*I*m*phi)*Ynm(n, m, theta, phi) For specific integers $n$ and $m$ we can evaluate the harmonics to more useful expressions: >>> simplify(Ynm_c(0, 0, theta, phi).expand(func=True)) 1/(2*sqrt(pi)) >>> simplify(Ynm_c(1, -1, theta, phi).expand(func=True)) sqrt(6)*exp(I*(-phi + 2*conjugate(phi)))*sin(theta)/(4*sqrt(pi)) See Also ======== Ynm, Znm References ========== .. [1] https://en.wikipedia.org/wiki/Spherical_harmonics .. [2] http://mathworld.wolfram.com/SphericalHarmonic.html .. [3] http://functions.wolfram.com/Polynomials/SphericalHarmonicY/ """ from sympy.functions.elementary.complexes import conjugate return conjugate(Ynm(n, m, theta, phi)) class Znm(Function): r""" Real spherical harmonics defined as .. math:: Z_n^m(\theta, \varphi) := \begin{cases} \frac{Y_n^m(\theta, \varphi) + \overline{Y_n^m(\theta, \varphi)}}{\sqrt{2}} &\quad m > 0 \\ Y_n^m(\theta, \varphi) &\quad m = 0 \\ \frac{Y_n^m(\theta, \varphi) - \overline{Y_n^m(\theta, \varphi)}}{i \sqrt{2}} &\quad m < 0 \\ \end{cases} which gives in simplified form .. math:: Z_n^m(\theta, \varphi) = \begin{cases} \frac{Y_n^m(\theta, \varphi) + (-1)^m Y_n^{-m}(\theta, \varphi)}{\sqrt{2}} &\quad m > 0 \\ Y_n^m(\theta, \varphi) &\quad m = 0 \\ \frac{Y_n^m(\theta, \varphi) - (-1)^m Y_n^{-m}(\theta, \varphi)}{i \sqrt{2}} &\quad m < 0 \\ \end{cases} Examples ======== >>> from sympy import Znm, Symbol, simplify >>> from sympy.abc import n, m >>> theta = Symbol("theta") >>> phi = Symbol("phi") >>> Znm(n, m, theta, phi) Znm(n, m, theta, phi) For specific integers n and m we can evaluate the harmonics to more useful expressions: >>> simplify(Znm(0, 0, theta, phi).expand(func=True)) 1/(2*sqrt(pi)) >>> simplify(Znm(1, 1, theta, phi).expand(func=True)) -sqrt(3)*sin(theta)*cos(phi)/(2*sqrt(pi)) >>> simplify(Znm(2, 1, theta, phi).expand(func=True)) -sqrt(15)*sin(2*theta)*cos(phi)/(4*sqrt(pi)) See Also ======== Ynm, Ynm_c References ========== .. [1] https://en.wikipedia.org/wiki/Spherical_harmonics .. [2] http://mathworld.wolfram.com/SphericalHarmonic.html .. [3] http://functions.wolfram.com/Polynomials/SphericalHarmonicY/ """ @classmethod def eval(cls, n, m, theta, phi): n, m, th, ph = [sympify(x) for x in (n, m, theta, phi)] if m.is_positive: zz = (Ynm(n, m, th, ph) + Ynm_c(n, m, th, ph)) / sqrt(2) return zz elif m.is_zero: return Ynm(n, m, th, ph) elif m.is_negative: zz = (Ynm(n, m, th, ph) - Ynm_c(n, m, th, ph)) / (sqrt(2)*I) return zz
475c3d7ebc5008ff3f09d2cd7bbf53e044a48a8bfb0e57f33d7c4a6afd9351e9
from sympy.core import S, sympify from sympy.core.symbol import (Dummy, symbols) from sympy.functions import Piecewise, piecewise_fold from sympy.sets.sets import Interval from functools import lru_cache def _ivl(cond, x): """return the interval corresponding to the condition Conditions in spline's Piecewise give the range over which an expression is valid like (lo <= x) & (x <= hi). This function returns (lo, hi). """ from sympy.logic.boolalg import And if isinstance(cond, And) and len(cond.args) == 2: a, b = cond.args if a.lts == x: a, b = b, a return a.lts, b.gts raise TypeError('unexpected cond type: %s' % cond) def _add_splines(c, b1, d, b2, x): """Construct c*b1 + d*b2.""" if S.Zero in (b1, c): rv = piecewise_fold(d * b2) elif S.Zero in (b2, d): rv = piecewise_fold(c * b1) else: new_args = [] # Just combining the Piecewise without any fancy optimization p1 = piecewise_fold(c * b1) p2 = piecewise_fold(d * b2) # Search all Piecewise arguments except (0, True) p2args = list(p2.args[:-1]) # This merging algorithm assumes the conditions in # p1 and p2 are sorted for arg in p1.args[:-1]: expr = arg.expr cond = arg.cond lower = _ivl(cond, x)[0] # Check p2 for matching conditions that can be merged for i, arg2 in enumerate(p2args): expr2 = arg2.expr cond2 = arg2.cond lower_2, upper_2 = _ivl(cond2, x) if cond2 == cond: # Conditions match, join expressions expr += expr2 # Remove matching element del p2args[i] # No need to check the rest break elif lower_2 < lower and upper_2 <= lower: # Check if arg2 condition smaller than arg1, # add to new_args by itself (no match expected # in p1) new_args.append(arg2) del p2args[i] break # Checked all, add expr and cond new_args.append((expr, cond)) # Add remaining items from p2args new_args.extend(p2args) # Add final (0, True) new_args.append((0, True)) rv = Piecewise(*new_args, evaluate=False) return rv.expand() @lru_cache(maxsize=128) def bspline_basis(d, knots, n, x): """ The $n$-th B-spline at $x$ of degree $d$ with knots. Explanation =========== B-Splines are piecewise polynomials of degree $d$. They are defined on a set of knots, which is a sequence of integers or floats. Examples ======== The 0th degree splines have a value of 1 on a single interval: >>> from sympy import bspline_basis >>> from sympy.abc import x >>> d = 0 >>> knots = tuple(range(5)) >>> bspline_basis(d, knots, 0, x) Piecewise((1, (x >= 0) & (x <= 1)), (0, True)) For a given ``(d, knots)`` there are ``len(knots)-d-1`` B-splines defined, that are indexed by ``n`` (starting at 0). Here is an example of a cubic B-spline: >>> bspline_basis(3, tuple(range(5)), 0, x) Piecewise((x**3/6, (x >= 0) & (x <= 1)), (-x**3/2 + 2*x**2 - 2*x + 2/3, (x >= 1) & (x <= 2)), (x**3/2 - 4*x**2 + 10*x - 22/3, (x >= 2) & (x <= 3)), (-x**3/6 + 2*x**2 - 8*x + 32/3, (x >= 3) & (x <= 4)), (0, True)) By repeating knot points, you can introduce discontinuities in the B-splines and their derivatives: >>> d = 1 >>> knots = (0, 0, 2, 3, 4) >>> bspline_basis(d, knots, 0, x) Piecewise((1 - x/2, (x >= 0) & (x <= 2)), (0, True)) It is quite time consuming to construct and evaluate B-splines. If you need to evaluate a B-spline many times, it is best to lambdify them first: >>> from sympy import lambdify >>> d = 3 >>> knots = tuple(range(10)) >>> b0 = bspline_basis(d, knots, 0, x) >>> f = lambdify(x, b0) >>> y = f(0.5) Parameters ========== d : integer degree of bspline knots : list of integer values list of knots points of bspline n : integer $n$-th B-spline x : symbol See Also ======== bspline_basis_set References ========== .. [1] https://en.wikipedia.org/wiki/B-spline """ # make sure x has no assumptions so conditions don't evaluate xvar = x x = Dummy() knots = tuple(sympify(k) for k in knots) d = int(d) n = int(n) n_knots = len(knots) n_intervals = n_knots - 1 if n + d + 1 > n_intervals: raise ValueError("n + d + 1 must not exceed len(knots) - 1") if d == 0: result = Piecewise( (S.One, Interval(knots[n], knots[n + 1]).contains(x)), (0, True) ) elif d > 0: denom = knots[n + d + 1] - knots[n + 1] if denom != S.Zero: B = (knots[n + d + 1] - x) / denom b2 = bspline_basis(d - 1, knots, n + 1, x) else: b2 = B = S.Zero denom = knots[n + d] - knots[n] if denom != S.Zero: A = (x - knots[n]) / denom b1 = bspline_basis(d - 1, knots, n, x) else: b1 = A = S.Zero result = _add_splines(A, b1, B, b2, x) else: raise ValueError("degree must be non-negative: %r" % n) # return result with user-given x return result.xreplace({x: xvar}) def bspline_basis_set(d, knots, x): """ Return the ``len(knots)-d-1`` B-splines at *x* of degree *d* with *knots*. Explanation =========== This function returns a list of piecewise polynomials that are the ``len(knots)-d-1`` B-splines of degree *d* for the given knots. This function calls ``bspline_basis(d, knots, n, x)`` for different values of *n*. Examples ======== >>> from sympy import bspline_basis_set >>> from sympy.abc import x >>> d = 2 >>> knots = range(5) >>> splines = bspline_basis_set(d, knots, x) >>> splines [Piecewise((x**2/2, (x >= 0) & (x <= 1)), (-x**2 + 3*x - 3/2, (x >= 1) & (x <= 2)), (x**2/2 - 3*x + 9/2, (x >= 2) & (x <= 3)), (0, True)), Piecewise((x**2/2 - x + 1/2, (x >= 1) & (x <= 2)), (-x**2 + 5*x - 11/2, (x >= 2) & (x <= 3)), (x**2/2 - 4*x + 8, (x >= 3) & (x <= 4)), (0, True))] Parameters ========== d : integer degree of bspline knots : list of integers list of knots points of bspline x : symbol See Also ======== bspline_basis """ n_splines = len(knots) - d - 1 return [bspline_basis(d, tuple(knots), i, x) for i in range(n_splines)] def interpolating_spline(d, x, X, Y): """ Return spline of degree *d*, passing through the given *X* and *Y* values. Explanation =========== This function returns a piecewise function such that each part is a polynomial of degree not greater than *d*. The value of *d* must be 1 or greater and the values of *X* must be strictly increasing. Examples ======== >>> from sympy import interpolating_spline >>> from sympy.abc import x >>> interpolating_spline(1, x, [1, 2, 4, 7], [3, 6, 5, 7]) Piecewise((3*x, (x >= 1) & (x <= 2)), (7 - x/2, (x >= 2) & (x <= 4)), (2*x/3 + 7/3, (x >= 4) & (x <= 7))) >>> interpolating_spline(3, x, [-2, 0, 1, 3, 4], [4, 2, 1, 1, 3]) Piecewise((7*x**3/117 + 7*x**2/117 - 131*x/117 + 2, (x >= -2) & (x <= 1)), (10*x**3/117 - 2*x**2/117 - 122*x/117 + 77/39, (x >= 1) & (x <= 4))) Parameters ========== d : integer Degree of Bspline strictly greater than equal to one x : symbol X : list of strictly increasing integer values list of X coordinates through which the spline passes Y : list of strictly increasing integer values list of Y coordinates through which the spline passes See Also ======== bspline_basis_set, interpolating_poly """ from sympy.solvers.solveset import linsolve from sympy.matrices.dense import Matrix # Input sanitization d = sympify(d) if not (d.is_Integer and d.is_positive): raise ValueError("Spline degree must be a positive integer, not %s." % d) if len(X) != len(Y): raise ValueError("Number of X and Y coordinates must be the same.") if len(X) < d + 1: raise ValueError("Degree must be less than the number of control points.") if not all(a < b for a, b in zip(X, X[1:])): raise ValueError("The x-coordinates must be strictly increasing.") X = [sympify(i) for i in X] # Evaluating knots value if d.is_odd: j = (d + 1) // 2 interior_knots = X[j:-j] else: j = d // 2 interior_knots = [ (a + b)/2 for a, b in zip(X[j : -j - 1], X[j + 1 : -j]) ] knots = [X[0]] * (d + 1) + list(interior_knots) + [X[-1]] * (d + 1) basis = bspline_basis_set(d, knots, x) A = [[b.subs(x, v) for b in basis] for v in X] coeff = linsolve((Matrix(A), Matrix(Y)), symbols("c0:{}".format(len(X)), cls=Dummy)) coeff = list(coeff)[0] intervals = {c for b in basis for (e, c) in b.args if c != True} # Sorting the intervals # ival contains the end-points of each interval ival = [_ivl(c, x) for c in intervals] com = zip(ival, intervals) com = sorted(com, key=lambda x: x[0]) intervals = [y for x, y in com] basis_dicts = [{c: e for (e, c) in b.args} for b in basis] spline = [] for i in intervals: piece = sum( [c * d.get(i, S.Zero) for (c, d) in zip(coeff, basis_dicts)], S.Zero ) spline.append((piece, i)) return Piecewise(*spline)
88b579d92885537b776d7b2af91cb5ddce882006bc31f3c2e111ba0d4f7f9eda
""" Riemann zeta and related function. """ from sympy.core.add import Add from sympy.core import Function, S, sympify, pi, I from sympy.core.function import ArgumentIndexError, expand_mul from sympy.core.symbol import Dummy from sympy.functions.combinatorial.numbers import bernoulli, factorial, harmonic from sympy.functions.elementary.complexes import re, unpolarify, Abs, polar_lift from sympy.functions.elementary.exponential import log, exp_polar, exp from sympy.functions.elementary.integers import floor from sympy.functions.elementary.miscellaneous import sqrt ############################################################################### ###################### LERCH TRANSCENDENT ##################################### ############################################################################### class lerchphi(Function): r""" Lerch transcendent (Lerch phi function). Explanation =========== For $\operatorname{Re}(a) > 0$, $|z| < 1$ and $s \in \mathbb{C}$, the Lerch transcendent is defined as .. math :: \Phi(z, s, a) = \sum_{n=0}^\infty \frac{z^n}{(n + a)^s}, where the standard branch of the argument is used for $n + a$, and by analytic continuation for other values of the parameters. A commonly used related function is the Lerch zeta function, defined by .. math:: L(q, s, a) = \Phi(e^{2\pi i q}, s, a). **Analytic Continuation and Branching Behavior** It can be shown that .. math:: \Phi(z, s, a) = z\Phi(z, s, a+1) + a^{-s}. This provides the analytic continuation to $\operatorname{Re}(a) \le 0$. Assume now $\operatorname{Re}(a) > 0$. The integral representation .. math:: \Phi_0(z, s, a) = \int_0^\infty \frac{t^{s-1} e^{-at}}{1 - ze^{-t}} \frac{\mathrm{d}t}{\Gamma(s)} provides an analytic continuation to $\mathbb{C} - [1, \infty)$. Finally, for $x \in (1, \infty)$ we find .. math:: \lim_{\epsilon \to 0^+} \Phi_0(x + i\epsilon, s, a) -\lim_{\epsilon \to 0^+} \Phi_0(x - i\epsilon, s, a) = \frac{2\pi i \log^{s-1}{x}}{x^a \Gamma(s)}, using the standard branch for both $\log{x}$ and $\log{\log{x}}$ (a branch of $\log{\log{x}}$ is needed to evaluate $\log{x}^{s-1}$). This concludes the analytic continuation. The Lerch transcendent is thus branched at $z \in \{0, 1, \infty\}$ and $a \in \mathbb{Z}_{\le 0}$. For fixed $z, a$ outside these branch points, it is an entire function of $s$. Examples ======== The Lerch transcendent is a fairly general function, for this reason it does not automatically evaluate to simpler functions. Use ``expand_func()`` to achieve this. If $z=1$, the Lerch transcendent reduces to the Hurwitz zeta function: >>> from sympy import lerchphi, expand_func >>> from sympy.abc import z, s, a >>> expand_func(lerchphi(1, s, a)) zeta(s, a) More generally, if $z$ is a root of unity, the Lerch transcendent reduces to a sum of Hurwitz zeta functions: >>> expand_func(lerchphi(-1, s, a)) zeta(s, a/2)/2**s - zeta(s, a/2 + 1/2)/2**s If $a=1$, the Lerch transcendent reduces to the polylogarithm: >>> expand_func(lerchphi(z, s, 1)) polylog(s, z)/z More generally, if $a$ is rational, the Lerch transcendent reduces to a sum of polylogarithms: >>> from sympy import S >>> expand_func(lerchphi(z, s, S(1)/2)) 2**(s - 1)*(polylog(s, sqrt(z))/sqrt(z) - polylog(s, sqrt(z)*exp_polar(I*pi))/sqrt(z)) >>> expand_func(lerchphi(z, s, S(3)/2)) -2**s/z + 2**(s - 1)*(polylog(s, sqrt(z))/sqrt(z) - polylog(s, sqrt(z)*exp_polar(I*pi))/sqrt(z))/z The derivatives with respect to $z$ and $a$ can be computed in closed form: >>> lerchphi(z, s, a).diff(z) (-a*lerchphi(z, s, a) + lerchphi(z, s - 1, a))/z >>> lerchphi(z, s, a).diff(a) -s*lerchphi(z, s + 1, a) See Also ======== polylog, zeta References ========== .. [1] Bateman, H.; Erdelyi, A. (1953), Higher Transcendental Functions, Vol. I, New York: McGraw-Hill. Section 1.11. .. [2] http://dlmf.nist.gov/25.14 .. [3] https://en.wikipedia.org/wiki/Lerch_transcendent """ def _eval_expand_func(self, **hints): from sympy.polys.polytools import Poly z, s, a = self.args if z == 1: return zeta(s, a) if s.is_Integer and s <= 0: t = Dummy('t') p = Poly((t + a)**(-s), t) start = 1/(1 - t) res = S.Zero for c in reversed(p.all_coeffs()): res += c*start start = t*start.diff(t) return res.subs(t, z) if a.is_Rational: # See section 18 of # Kelly B. Roach. Hypergeometric Function Representations. # In: Proceedings of the 1997 International Symposium on Symbolic and # Algebraic Computation, pages 205-211, New York, 1997. ACM. # TODO should something be polarified here? add = S.Zero mul = S.One # First reduce a to the interaval (0, 1] if a > 1: n = floor(a) if n == a: n -= 1 a -= n mul = z**(-n) add = Add(*[-z**(k - n)/(a + k)**s for k in range(n)]) elif a <= 0: n = floor(-a) + 1 a += n mul = z**n add = Add(*[z**(n - 1 - k)/(a - k - 1)**s for k in range(n)]) m, n = S([a.p, a.q]) zet = exp_polar(2*pi*I/n) root = z**(1/n) return add + mul*n**(s - 1)*Add( *[polylog(s, zet**k*root)._eval_expand_func(**hints) / (unpolarify(zet)**k*root)**m for k in range(n)]) # TODO use minpoly instead of ad-hoc methods when issue 5888 is fixed if isinstance(z, exp) and (z.args[0]/(pi*I)).is_Rational or z in [-1, I, -I]: # TODO reference? if z == -1: p, q = S([1, 2]) elif z == I: p, q = S([1, 4]) elif z == -I: p, q = S([-1, 4]) else: arg = z.args[0]/(2*pi*I) p, q = S([arg.p, arg.q]) return Add(*[exp(2*pi*I*k*p/q)/q**s*zeta(s, (k + a)/q) for k in range(q)]) return lerchphi(z, s, a) def fdiff(self, argindex=1): z, s, a = self.args if argindex == 3: return -s*lerchphi(z, s + 1, a) elif argindex == 1: return (lerchphi(z, s - 1, a) - a*lerchphi(z, s, a))/z else: raise ArgumentIndexError def _eval_rewrite_helper(self, z, s, a, target): res = self._eval_expand_func() if res.has(target): return res else: return self def _eval_rewrite_as_zeta(self, z, s, a, **kwargs): return self._eval_rewrite_helper(z, s, a, zeta) def _eval_rewrite_as_polylog(self, z, s, a, **kwargs): return self._eval_rewrite_helper(z, s, a, polylog) ############################################################################### ###################### POLYLOGARITHM ########################################## ############################################################################### class polylog(Function): r""" Polylogarithm function. Explanation =========== For $|z| < 1$ and $s \in \mathbb{C}$, the polylogarithm is defined by .. math:: \operatorname{Li}_s(z) = \sum_{n=1}^\infty \frac{z^n}{n^s}, where the standard branch of the argument is used for $n$. It admits an analytic continuation which is branched at $z=1$ (notably not on the sheet of initial definition), $z=0$ and $z=\infty$. The name polylogarithm comes from the fact that for $s=1$, the polylogarithm is related to the ordinary logarithm (see examples), and that .. math:: \operatorname{Li}_{s+1}(z) = \int_0^z \frac{\operatorname{Li}_s(t)}{t} \mathrm{d}t. The polylogarithm is a special case of the Lerch transcendent: .. math:: \operatorname{Li}_{s}(z) = z \Phi(z, s, 1). Examples ======== For $z \in \{0, 1, -1\}$, the polylogarithm is automatically expressed using other functions: >>> from sympy import polylog >>> from sympy.abc import s >>> polylog(s, 0) 0 >>> polylog(s, 1) zeta(s) >>> polylog(s, -1) -dirichlet_eta(s) If $s$ is a negative integer, $0$ or $1$, the polylogarithm can be expressed using elementary functions. This can be done using ``expand_func()``: >>> from sympy import expand_func >>> from sympy.abc import z >>> expand_func(polylog(1, z)) -log(1 - z) >>> expand_func(polylog(0, z)) z/(1 - z) The derivative with respect to $z$ can be computed in closed form: >>> polylog(s, z).diff(z) polylog(s - 1, z)/z The polylogarithm can be expressed in terms of the lerch transcendent: >>> from sympy import lerchphi >>> polylog(s, z).rewrite(lerchphi) z*lerchphi(z, s, 1) See Also ======== zeta, lerchphi """ @classmethod def eval(cls, s, z): s, z = sympify((s, z)) if z is S.One: return zeta(s) elif z is S.NegativeOne: return -dirichlet_eta(s) elif z is S.Zero: return S.Zero elif s == 2: if z == S.Half: return pi**2/12 - log(2)**2/2 elif z == 2: return pi**2/4 - I*pi*log(2) elif z == -(sqrt(5) - 1)/2: return -pi**2/15 + log((sqrt(5)-1)/2)**2/2 elif z == -(sqrt(5) + 1)/2: return -pi**2/10 - log((sqrt(5)+1)/2)**2 elif z == (3 - sqrt(5))/2: return pi**2/15 - log((sqrt(5)-1)/2)**2 elif z == (sqrt(5) - 1)/2: return pi**2/10 - log((sqrt(5)-1)/2)**2 if z.is_zero: return S.Zero # Make an effort to determine if z is 1 to avoid replacing into # expression with singularity zone = z.equals(S.One) if zone: return zeta(s) elif zone is False: # For s = 0 or -1 use explicit formulas to evaluate, but # automatically expanding polylog(1, z) to -log(1-z) seems # undesirable for summation methods based on hypergeometric # functions if s is S.Zero: return z/(1 - z) elif s is S.NegativeOne: return z/(1 - z)**2 if s.is_zero: return z/(1 - z) # polylog is branched, but not over the unit disk if z.has(exp_polar, polar_lift) and (zone or (Abs(z) <= S.One) == True): return cls(s, unpolarify(z)) def fdiff(self, argindex=1): s, z = self.args if argindex == 2: return polylog(s - 1, z)/z raise ArgumentIndexError def _eval_rewrite_as_lerchphi(self, s, z, **kwargs): return z*lerchphi(z, s, 1) def _eval_expand_func(self, **hints): s, z = self.args if s == 1: return -log(1 - z) if s.is_Integer and s <= 0: u = Dummy('u') start = u/(1 - u) for _ in range(-s): start = u*start.diff(u) return expand_mul(start).subs(u, z) return polylog(s, z) def _eval_is_zero(self): z = self.args[1] if z.is_zero: return True def _eval_nseries(self, x, n, logx, cdir=0): from sympy.functions.elementary.integers import ceiling from sympy.series.order import Order nu, z = self.args z0 = z.subs(x, 0) if z0 is S.NaN: z0 = z.limit(x, 0, dir='-' if re(cdir).is_negative else '+') if z0.is_zero: # In case of powers less than 1, number of terms need to be computed # separately to avoid repeated callings of _eval_nseries with wrong n try: _, exp = z.leadterm(x) except (ValueError, NotImplementedError): return self if exp.is_positive: newn = ceiling(n/exp) o = Order(x**n, x) r = z._eval_nseries(x, n, logx, cdir).removeO() if r is S.Zero: return o term = r s = [term] for k in range(2, newn): term *= r s.append(term/k**nu) return Add(*s) + o return super(polylog, self)._eval_nseries(x, n, logx, cdir) ############################################################################### ###################### HURWITZ GENERALIZED ZETA FUNCTION ###################### ############################################################################### class zeta(Function): r""" Hurwitz zeta function (or Riemann zeta function). Explanation =========== For $\operatorname{Re}(a) > 0$ and $\operatorname{Re}(s) > 1$, this function is defined as .. math:: \zeta(s, a) = \sum_{n=0}^\infty \frac{1}{(n + a)^s}, where the standard choice of argument for $n + a$ is used. For fixed $a$ with $\operatorname{Re}(a) > 0$ the Hurwitz zeta function admits a meromorphic continuation to all of $\mathbb{C}$, it is an unbranched function with a simple pole at $s = 1$. Analytic continuation to other $a$ is possible under some circumstances, but this is not typically done. The Hurwitz zeta function is a special case of the Lerch transcendent: .. math:: \zeta(s, a) = \Phi(1, s, a). This formula defines an analytic continuation for all possible values of $s$ and $a$ (also $\operatorname{Re}(a) < 0$), see the documentation of :class:`lerchphi` for a description of the branching behavior. If no value is passed for $a$, by this function assumes a default value of $a = 1$, yielding the Riemann zeta function. Examples ======== For $a = 1$ the Hurwitz zeta function reduces to the famous Riemann zeta function: .. math:: \zeta(s, 1) = \zeta(s) = \sum_{n=1}^\infty \frac{1}{n^s}. >>> from sympy import zeta >>> from sympy.abc import s >>> zeta(s, 1) zeta(s) >>> zeta(s) zeta(s) The Riemann zeta function can also be expressed using the Dirichlet eta function: >>> from sympy import dirichlet_eta >>> zeta(s).rewrite(dirichlet_eta) dirichlet_eta(s)/(1 - 2**(1 - s)) The Riemann zeta function at positive even integer and negative odd integer values is related to the Bernoulli numbers: >>> zeta(2) pi**2/6 >>> zeta(4) pi**4/90 >>> zeta(-1) -1/12 The specific formulae are: .. math:: \zeta(2n) = (-1)^{n+1} \frac{B_{2n} (2\pi)^{2n}}{2(2n)!} .. math:: \zeta(-n) = -\frac{B_{n+1}}{n+1} At negative even integers the Riemann zeta function is zero: >>> zeta(-4) 0 No closed-form expressions are known at positive odd integers, but numerical evaluation is possible: >>> zeta(3).n() 1.20205690315959 The derivative of $\zeta(s, a)$ with respect to $a$ can be computed: >>> from sympy.abc import a >>> zeta(s, a).diff(a) -s*zeta(s + 1, a) However the derivative with respect to $s$ has no useful closed form expression: >>> zeta(s, a).diff(s) Derivative(zeta(s, a), s) The Hurwitz zeta function can be expressed in terms of the Lerch transcendent, :class:`~.lerchphi`: >>> from sympy import lerchphi >>> zeta(s, a).rewrite(lerchphi) lerchphi(1, s, a) See Also ======== dirichlet_eta, lerchphi, polylog References ========== .. [1] http://dlmf.nist.gov/25.11 .. [2] https://en.wikipedia.org/wiki/Hurwitz_zeta_function """ @classmethod def eval(cls, z, a_=None): if a_ is None: z, a = list(map(sympify, (z, 1))) else: z, a = list(map(sympify, (z, a_))) if a.is_Number: if a is S.NaN: return S.NaN elif a is S.One and a_ is not None: return cls(z) # TODO Should a == 0 return S.NaN as well? if z.is_Number: if z is S.NaN: return S.NaN elif z is S.Infinity: return S.One elif z.is_zero: return S.Half - a elif z is S.One: return S.ComplexInfinity if z.is_integer: if a.is_Integer: if z.is_negative: zeta = S.NegativeOne**z * bernoulli(-z + 1)/(-z + 1) elif z.is_even and z.is_positive: B, F = bernoulli(z), factorial(z) zeta = (S.NegativeOne**(z/2+1) * 2**(z - 1) * B * pi**z) / F else: return if a.is_negative: return zeta + harmonic(abs(a), z) else: return zeta - harmonic(a - 1, z) if z.is_zero: return S.Half - a def _eval_rewrite_as_dirichlet_eta(self, s, a=1, **kwargs): if a != 1: return self s = self.args[0] return dirichlet_eta(s)/(1 - 2**(1 - s)) def _eval_rewrite_as_lerchphi(self, s, a=1, **kwargs): return lerchphi(1, s, a) def _eval_is_finite(self): arg_is_one = (self.args[0] - 1).is_zero if arg_is_one is not None: return not arg_is_one def fdiff(self, argindex=1): if len(self.args) == 2: s, a = self.args else: s, a = self.args + (1,) if argindex == 2: return -s*zeta(s + 1, a) else: raise ArgumentIndexError class dirichlet_eta(Function): r""" Dirichlet eta function. Explanation =========== For $\operatorname{Re}(s) > 0$, this function is defined as .. math:: \eta(s) = \sum_{n=1}^\infty \frac{(-1)^{n-1}}{n^s}. It admits a unique analytic continuation to all of $\mathbb{C}$. It is an entire, unbranched function. Examples ======== The Dirichlet eta function is closely related to the Riemann zeta function: >>> from sympy import dirichlet_eta, zeta >>> from sympy.abc import s >>> dirichlet_eta(s).rewrite(zeta) (1 - 2**(1 - s))*zeta(s) See Also ======== zeta References ========== .. [1] https://en.wikipedia.org/wiki/Dirichlet_eta_function """ @classmethod def eval(cls, s): if s == 1: return log(2) z = zeta(s) if not z.has(zeta): return (1 - 2**(1 - s))*z def _eval_rewrite_as_zeta(self, s, **kwargs): return (1 - 2**(1 - s)) * zeta(s) class riemann_xi(Function): r""" Riemann Xi function. Examples ======== The Riemann Xi function is closely related to the Riemann zeta function. The zeros of Riemann Xi function are precisely the non-trivial zeros of the zeta function. >>> from sympy import riemann_xi, zeta >>> from sympy.abc import s >>> riemann_xi(s).rewrite(zeta) s*(s - 1)*gamma(s/2)*zeta(s)/(2*pi**(s/2)) References ========== .. [1] https://en.wikipedia.org/wiki/Riemann_Xi_function """ @classmethod def eval(cls, s): from sympy.functions.special.gamma_functions import gamma z = zeta(s) if s in (S.Zero, S.One): return S.Half if not isinstance(z, zeta): return s*(s - 1)*gamma(s/2)*z/(2*pi**(s/2)) def _eval_rewrite_as_zeta(self, s, **kwargs): from sympy.functions.special.gamma_functions import gamma return s*(s - 1)*gamma(s/2)*zeta(s)/(2*pi**(s/2)) class stieltjes(Function): r""" Represents Stieltjes constants, $\gamma_{k}$ that occur in Laurent Series expansion of the Riemann zeta function. Examples ======== >>> from sympy import stieltjes >>> from sympy.abc import n, m >>> stieltjes(n) stieltjes(n) The zero'th stieltjes constant: >>> stieltjes(0) EulerGamma >>> stieltjes(0, 1) EulerGamma For generalized stieltjes constants: >>> stieltjes(n, m) stieltjes(n, m) Constants are only defined for integers >= 0: >>> stieltjes(-1) zoo References ========== .. [1] https://en.wikipedia.org/wiki/Stieltjes_constants """ @classmethod def eval(cls, n, a=None): n = sympify(n) if a is not None: a = sympify(a) if a is S.NaN: return S.NaN if a.is_Integer and a.is_nonpositive: return S.ComplexInfinity if n.is_Number: if n is S.NaN: return S.NaN elif n < 0: return S.ComplexInfinity elif not n.is_Integer: return S.ComplexInfinity elif n is S.Zero and a in [None, 1]: return S.EulerGamma if n.is_extended_negative: return S.ComplexInfinity if n.is_zero and a in [None, 1]: return S.EulerGamma if n.is_integer == False: return S.ComplexInfinity
4f1ace3cae9275d3af9eeec587139a90d912a2ba5e44a395c353b42196893f6a
from sympy.core import S, sympify, oo, diff from sympy.core.function import Function, ArgumentIndexError from sympy.core.logic import fuzzy_not from sympy.core.relational import Eq from sympy.functions.elementary.complexes import im from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.special.delta_functions import Heaviside ############################################################################### ############################# SINGULARITY FUNCTION ############################ ############################################################################### class SingularityFunction(Function): r""" Singularity functions are a class of discontinuous functions. Explanation =========== Singularity functions take a variable, an offset, and an exponent as arguments. These functions are represented using Macaulay brackets as: SingularityFunction(x, a, n) := <x - a>^n The singularity function will automatically evaluate to ``Derivative(DiracDelta(x - a), x, -n - 1)`` if ``n < 0`` and ``(x - a)**n*Heaviside(x - a)`` if ``n >= 0``. Examples ======== >>> from sympy import SingularityFunction, diff, Piecewise, DiracDelta, Heaviside, Symbol >>> from sympy.abc import x, a, n >>> SingularityFunction(x, a, n) SingularityFunction(x, a, n) >>> y = Symbol('y', positive=True) >>> n = Symbol('n', nonnegative=True) >>> SingularityFunction(y, -10, n) (y + 10)**n >>> y = Symbol('y', negative=True) >>> SingularityFunction(y, 10, n) 0 >>> SingularityFunction(x, 4, -1).subs(x, 4) oo >>> SingularityFunction(x, 10, -2).subs(x, 10) oo >>> SingularityFunction(4, 1, 5) 243 >>> diff(SingularityFunction(x, 1, 5) + SingularityFunction(x, 1, 4), x) 4*SingularityFunction(x, 1, 3) + 5*SingularityFunction(x, 1, 4) >>> diff(SingularityFunction(x, 4, 0), x, 2) SingularityFunction(x, 4, -2) >>> SingularityFunction(x, 4, 5).rewrite(Piecewise) Piecewise(((x - 4)**5, x > 4), (0, True)) >>> expr = SingularityFunction(x, a, n) >>> y = Symbol('y', positive=True) >>> n = Symbol('n', nonnegative=True) >>> expr.subs({x: y, a: -10, n: n}) (y + 10)**n The methods ``rewrite(DiracDelta)``, ``rewrite(Heaviside)``, and ``rewrite('HeavisideDiracDelta')`` returns the same output. One can use any of these methods according to their choice. >>> expr = SingularityFunction(x, 4, 5) + SingularityFunction(x, -3, -1) - SingularityFunction(x, 0, -2) >>> expr.rewrite(Heaviside) (x - 4)**5*Heaviside(x - 4) + DiracDelta(x + 3) - DiracDelta(x, 1) >>> expr.rewrite(DiracDelta) (x - 4)**5*Heaviside(x - 4) + DiracDelta(x + 3) - DiracDelta(x, 1) >>> expr.rewrite('HeavisideDiracDelta') (x - 4)**5*Heaviside(x - 4) + DiracDelta(x + 3) - DiracDelta(x, 1) See Also ======== DiracDelta, Heaviside References ========== .. [1] https://en.wikipedia.org/wiki/Singularity_function """ is_real = True def fdiff(self, argindex=1): """ Returns the first derivative of a DiracDelta Function. Explanation =========== The difference between ``diff()`` and ``fdiff()`` is: ``diff()`` is the user-level function and ``fdiff()`` is an object method. ``fdiff()`` is a convenience method available in the ``Function`` class. It returns the derivative of the function without considering the chain rule. ``diff(function, x)`` calls ``Function._eval_derivative`` which in turn calls ``fdiff()`` internally to compute the derivative of the function. """ if argindex == 1: x = sympify(self.args[0]) a = sympify(self.args[1]) n = sympify(self.args[2]) if n in (S.Zero, S.NegativeOne): return self.func(x, a, n-1) elif n.is_positive: return n*self.func(x, a, n-1) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, variable, offset, exponent): """ Returns a simplified form or a value of Singularity Function depending on the argument passed by the object. Explanation =========== The ``eval()`` method is automatically called when the ``SingularityFunction`` class is about to be instantiated and it returns either some simplified instance or the unevaluated instance depending on the argument passed. In other words, ``eval()`` method is not needed to be called explicitly, it is being called and evaluated once the object is called. Examples ======== >>> from sympy import SingularityFunction, Symbol, nan >>> from sympy.abc import x, a, n >>> SingularityFunction(x, a, n) SingularityFunction(x, a, n) >>> SingularityFunction(5, 3, 2) 4 >>> SingularityFunction(x, a, nan) nan >>> SingularityFunction(x, 3, 0).subs(x, 3) 1 >>> SingularityFunction(x, a, n).eval(3, 5, 1) 0 >>> SingularityFunction(x, a, n).eval(4, 1, 5) 243 >>> x = Symbol('x', positive = True) >>> a = Symbol('a', negative = True) >>> n = Symbol('n', nonnegative = True) >>> SingularityFunction(x, a, n) (-a + x)**n >>> x = Symbol('x', negative = True) >>> a = Symbol('a', positive = True) >>> SingularityFunction(x, a, n) 0 """ x = sympify(variable) a = sympify(offset) n = sympify(exponent) shift = (x - a) if fuzzy_not(im(shift).is_zero): raise ValueError("Singularity Functions are defined only for Real Numbers.") if fuzzy_not(im(n).is_zero): raise ValueError("Singularity Functions are not defined for imaginary exponents.") if shift is S.NaN or n is S.NaN: return S.NaN if (n + 2).is_negative: raise ValueError("Singularity Functions are not defined for exponents less than -2.") if shift.is_extended_negative: return S.Zero if n.is_nonnegative and shift.is_extended_nonnegative: return (x - a)**n if n in (S.NegativeOne, -2): if shift.is_negative or shift.is_extended_positive: return S.Zero if shift.is_zero: return S.Infinity def _eval_rewrite_as_Piecewise(self, *args, **kwargs): ''' Converts a Singularity Function expression into its Piecewise form. ''' x = self.args[0] a = self.args[1] n = sympify(self.args[2]) if n in (S.NegativeOne, -2): return Piecewise((oo, Eq((x - a), 0)), (0, True)) elif n.is_nonnegative: return Piecewise(((x - a)**n, (x - a) > 0), (0, True)) def _eval_rewrite_as_Heaviside(self, *args, **kwargs): ''' Rewrites a Singularity Function expression using Heavisides and DiracDeltas. ''' x = self.args[0] a = self.args[1] n = sympify(self.args[2]) if n == -2: return diff(Heaviside(x - a), x.free_symbols.pop(), 2) if n == -1: return diff(Heaviside(x - a), x.free_symbols.pop(), 1) if n.is_nonnegative: return (x - a)**n*Heaviside(x - a) def _eval_as_leading_term(self, x, logx=None, cdir=0): z, a, n = self.args shift = (z - a).subs(x, 0) if n < 0: return S.Zero elif n.is_zero and shift.is_zero: return S.Zero if cdir == -1 else S.One elif shift.is_positive: return shift**n return S.Zero def _eval_nseries(self, x, n, logx=None, cdir=0): z, a, n = self.args shift = (z - a).subs(x, 0) if n < 0: return S.Zero elif n.is_zero and shift.is_zero: return S.Zero if cdir == -1 else S.One elif shift.is_positive: return ((z - a)**n)._eval_nseries(x, n, logx=logx, cdir=cdir) return S.Zero _eval_rewrite_as_DiracDelta = _eval_rewrite_as_Heaviside _eval_rewrite_as_HeavisideDiracDelta = _eval_rewrite_as_Heaviside
db78655f3e4146d01f6f582bf0e7caed36fa884cc6077f2097195c3d419d43f2
from functools import wraps from sympy.core import S from sympy.core.add import Add from sympy.core.cache import cacheit from sympy.core.expr import Expr from sympy.core.function import Function, ArgumentIndexError, _mexpand from sympy.core.logic import fuzzy_or, fuzzy_not from sympy.core.numbers import Rational, pi, I from sympy.core.power import Pow from sympy.core.symbol import Dummy, Wild from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.trigonometric import sin, cos, csc, cot from sympy.functions.elementary.integers import ceiling from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.exponential import exp, log from sympy.functions.elementary.miscellaneous import sqrt, root from sympy.functions.elementary.complexes import re, im from sympy.functions.special.gamma_functions import gamma, digamma, uppergamma from sympy.functions.special.hyper import hyper from sympy.polys.orthopolys import spherical_bessel_fn from mpmath import mp, workprec # TODO # o Scorer functions G1 and G2 # o Asymptotic expansions # These are possible, e.g. for fixed order, but since the bessel type # functions are oscillatory they are not actually tractable at # infinity, so this is not particularly useful right now. # o Nicer series expansions. # o More rewriting. # o Add solvers to ode.py (or rather add solvers for the hypergeometric equation). class BesselBase(Function): """ Abstract base class for Bessel-type functions. This class is meant to reduce code duplication. All Bessel-type functions can 1) be differentiated, with the derivatives expressed in terms of similar functions, and 2) be rewritten in terms of other Bessel-type functions. Here, Bessel-type functions are assumed to have one complex parameter. To use this base class, define class attributes ``_a`` and ``_b`` such that ``2*F_n' = -_a*F_{n+1} + b*F_{n-1}``. """ @property def order(self): """ The order of the Bessel-type function. """ return self.args[0] @property def argument(self): """ The argument of the Bessel-type function. """ return self.args[1] @classmethod def eval(cls, nu, z): return def fdiff(self, argindex=2): if argindex != 2: raise ArgumentIndexError(self, argindex) return (self._b/2 * self.__class__(self.order - 1, self.argument) - self._a/2 * self.__class__(self.order + 1, self.argument)) def _eval_conjugate(self): z = self.argument if z.is_extended_negative is False: return self.__class__(self.order.conjugate(), z.conjugate()) def _eval_is_meromorphic(self, x, a): nu, z = self.order, self.argument if nu.has(x): return False if not z._eval_is_meromorphic(x, a): return None z0 = z.subs(x, a) if nu.is_integer: if isinstance(self, (besselj, besseli, hn1, hn2, jn, yn)) or not nu.is_zero: return fuzzy_not(z0.is_infinite) return fuzzy_not(fuzzy_or([z0.is_zero, z0.is_infinite])) def _eval_expand_func(self, **hints): nu, z, f = self.order, self.argument, self.__class__ if nu.is_real: if (nu - 1).is_positive: return (-self._a*self._b*f(nu - 2, z)._eval_expand_func() + 2*self._a*(nu - 1)*f(nu - 1, z)._eval_expand_func()/z) elif (nu + 1).is_negative: return (2*self._b*(nu + 1)*f(nu + 1, z)._eval_expand_func()/z - self._a*self._b*f(nu + 2, z)._eval_expand_func()) return self def _eval_simplify(self, **kwargs): from sympy.simplify.simplify import besselsimp return besselsimp(self) class besselj(BesselBase): r""" Bessel function of the first kind. Explanation =========== The Bessel $J$ function of order $\nu$ is defined to be the function satisfying Bessel's differential equation .. math :: z^2 \frac{\mathrm{d}^2 w}{\mathrm{d}z^2} + z \frac{\mathrm{d}w}{\mathrm{d}z} + (z^2 - \nu^2) w = 0, with Laurent expansion .. math :: J_\nu(z) = z^\nu \left(\frac{1}{\Gamma(\nu + 1) 2^\nu} + O(z^2) \right), if $\nu$ is not a negative integer. If $\nu=-n \in \mathbb{Z}_{<0}$ *is* a negative integer, then the definition is .. math :: J_{-n}(z) = (-1)^n J_n(z). Examples ======== Create a Bessel function object: >>> from sympy import besselj, jn >>> from sympy.abc import z, n >>> b = besselj(n, z) Differentiate it: >>> b.diff(z) besselj(n - 1, z)/2 - besselj(n + 1, z)/2 Rewrite in terms of spherical Bessel functions: >>> b.rewrite(jn) sqrt(2)*sqrt(z)*jn(n - 1/2, z)/sqrt(pi) Access the parameter and argument: >>> b.order n >>> b.argument z See Also ======== bessely, besseli, besselk References ========== .. [1] Abramowitz, Milton; Stegun, Irene A., eds. (1965), "Chapter 9", Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables .. [2] Luke, Y. L. (1969), The Special Functions and Their Approximations, Volume 1 .. [3] https://en.wikipedia.org/wiki/Bessel_function .. [4] http://functions.wolfram.com/Bessel-TypeFunctions/BesselJ/ """ _a = S.One _b = S.One @classmethod def eval(cls, nu, z): if z.is_zero: if nu.is_zero: return S.One elif (nu.is_integer and nu.is_zero is False) or re(nu).is_positive: return S.Zero elif re(nu).is_negative and not (nu.is_integer is True): return S.ComplexInfinity elif nu.is_imaginary: return S.NaN if z in (S.Infinity, S.NegativeInfinity): return S.Zero if z.could_extract_minus_sign(): return (z)**nu*(-z)**(-nu)*besselj(nu, -z) if nu.is_integer: if nu.could_extract_minus_sign(): return S.NegativeOne**(-nu)*besselj(-nu, z) newz = z.extract_multiplicatively(I) if newz: # NOTE we don't want to change the function if z==0 return I**(nu)*besseli(nu, newz) # branch handling: from sympy.functions.elementary.complexes import unpolarify if nu.is_integer: newz = unpolarify(z) if newz != z: return besselj(nu, newz) else: newz, n = z.extract_branch_factor() if n != 0: return exp(2*n*pi*nu*I)*besselj(nu, newz) nnu = unpolarify(nu) if nu != nnu: return besselj(nnu, z) def _eval_rewrite_as_besseli(self, nu, z, **kwargs): from sympy.functions.elementary.complexes import polar_lift return exp(I*pi*nu/2)*besseli(nu, polar_lift(-I)*z) def _eval_rewrite_as_bessely(self, nu, z, **kwargs): if nu.is_integer is False: return csc(pi*nu)*bessely(-nu, z) - cot(pi*nu)*bessely(nu, z) def _eval_rewrite_as_jn(self, nu, z, **kwargs): return sqrt(2*z/pi)*jn(nu - S.Half, self.argument) def _eval_as_leading_term(self, x, logx=None, cdir=0): nu, z = self.args arg = z.as_leading_term(x) if x in arg.free_symbols: return arg**nu/(2**nu*gamma(nu + 1)) else: return self.func(nu, z.subs(x, 0)) def _eval_is_extended_real(self): nu, z = self.args if nu.is_integer and z.is_extended_real: return True def _eval_nseries(self, x, n, logx, cdir=0): from sympy.series.order import Order nu, z = self.args # In case of powers less than 1, number of terms need to be computed # separately to avoid repeated callings of _eval_nseries with wrong n try: _, exp = z.leadterm(x) except (ValueError, NotImplementedError): return self if exp.is_positive: newn = ceiling(n/exp) o = Order(x**n, x) r = (z/2)._eval_nseries(x, n, logx, cdir).removeO() if r is S.Zero: return o t = (_mexpand(r**2) + o).removeO() term = r**nu/gamma(nu + 1) s = [term] for k in range(1, (newn + 1)//2): term *= -t/(k*(nu + k)) term = (_mexpand(term) + o).removeO() s.append(term) return Add(*s) + o return super(besselj, self)._eval_nseries(x, n, logx, cdir) class bessely(BesselBase): r""" Bessel function of the second kind. Explanation =========== The Bessel $Y$ function of order $\nu$ is defined as .. math :: Y_\nu(z) = \lim_{\mu \to \nu} \frac{J_\mu(z) \cos(\pi \mu) - J_{-\mu}(z)}{\sin(\pi \mu)}, where $J_\mu(z)$ is the Bessel function of the first kind. It is a solution to Bessel's equation, and linearly independent from $J_\nu$. Examples ======== >>> from sympy import bessely, yn >>> from sympy.abc import z, n >>> b = bessely(n, z) >>> b.diff(z) bessely(n - 1, z)/2 - bessely(n + 1, z)/2 >>> b.rewrite(yn) sqrt(2)*sqrt(z)*yn(n - 1/2, z)/sqrt(pi) See Also ======== besselj, besseli, besselk References ========== .. [1] http://functions.wolfram.com/Bessel-TypeFunctions/BesselY/ """ _a = S.One _b = S.One @classmethod def eval(cls, nu, z): if z.is_zero: if nu.is_zero: return S.NegativeInfinity elif re(nu).is_zero is False: return S.ComplexInfinity elif re(nu).is_zero: return S.NaN if z in (S.Infinity, S.NegativeInfinity): return S.Zero if nu.is_integer: if nu.could_extract_minus_sign(): return S.NegativeOne**(-nu)*bessely(-nu, z) def _eval_rewrite_as_besselj(self, nu, z, **kwargs): if nu.is_integer is False: return csc(pi*nu)*(cos(pi*nu)*besselj(nu, z) - besselj(-nu, z)) def _eval_rewrite_as_besseli(self, nu, z, **kwargs): aj = self._eval_rewrite_as_besselj(*self.args) if aj: return aj.rewrite(besseli) def _eval_rewrite_as_yn(self, nu, z, **kwargs): return sqrt(2*z/pi) * yn(nu - S.Half, self.argument) def _eval_as_leading_term(self, x, logx=None, cdir=0): nu, z = self.args term_one = ((2/pi)*log(z/2)*besselj(nu, z)) term_two = (z/2)**(-nu)*factorial(nu - 1)/pi if (nu - 1).is_positive else S.Zero term_three = (z/2)**nu/(pi*factorial(nu))*(digamma(nu + 1) - S.EulerGamma) arg = Add(*[term_one, term_two, term_three]).as_leading_term(x) if x in arg.free_symbols: return arg else: return self.func(nu, z.subs(x, 0).cancel()) def _eval_is_extended_real(self): nu, z = self.args if nu.is_integer and z.is_positive: return True def _eval_nseries(self, x, n, logx, cdir=0): from sympy.series.order import Order nu, z = self.args # In case of powers less than 1, number of terms need to be computed # separately to avoid repeated callings of _eval_nseries with wrong n try: _, exp = z.leadterm(x) except (ValueError, NotImplementedError): return self if exp.is_positive and nu.is_integer: newn = ceiling(n/exp) bn = besselj(nu, z) a = ((2/pi)*log(z/2)*bn)._eval_nseries(x, n, logx, cdir) b, c = [], [] o = Order(x**n, x) r = (z/2)._eval_nseries(x, n, logx, cdir).removeO() if r is S.Zero: return o t = (_mexpand(r**2) + o).removeO() if nu > S.One: term = r**(-nu)*factorial(nu - 1)/pi b.append(term) for k in range(1, nu - 1): term *= t*(nu - k - 1)/k term = (_mexpand(term) + o).removeO() b.append(term) p = r**nu/(pi*factorial(nu)) term = p*(digamma(nu + 1) - S.EulerGamma) c.append(term) for k in range(1, (newn + 1)//2): p *= -t/(k*(k + nu)) p = (_mexpand(p) + o).removeO() term = p*(digamma(k + nu + 1) + digamma(k + 1)) c.append(term) return a - Add(*b) - Add(*c) # Order term comes from a return super(bessely, self)._eval_nseries(x, n, logx, cdir) class besseli(BesselBase): r""" Modified Bessel function of the first kind. Explanation =========== The Bessel $I$ function is a solution to the modified Bessel equation .. math :: z^2 \frac{\mathrm{d}^2 w}{\mathrm{d}z^2} + z \frac{\mathrm{d}w}{\mathrm{d}z} + (z^2 + \nu^2)^2 w = 0. It can be defined as .. math :: I_\nu(z) = i^{-\nu} J_\nu(iz), where $J_\nu(z)$ is the Bessel function of the first kind. Examples ======== >>> from sympy import besseli >>> from sympy.abc import z, n >>> besseli(n, z).diff(z) besseli(n - 1, z)/2 + besseli(n + 1, z)/2 See Also ======== besselj, bessely, besselk References ========== .. [1] http://functions.wolfram.com/Bessel-TypeFunctions/BesselI/ """ _a = -S.One _b = S.One @classmethod def eval(cls, nu, z): if z.is_zero: if nu.is_zero: return S.One elif (nu.is_integer and nu.is_zero is False) or re(nu).is_positive: return S.Zero elif re(nu).is_negative and not (nu.is_integer is True): return S.ComplexInfinity elif nu.is_imaginary: return S.NaN if im(z) in (S.Infinity, S.NegativeInfinity): return S.Zero if z.could_extract_minus_sign(): return (z)**nu*(-z)**(-nu)*besseli(nu, -z) if nu.is_integer: if nu.could_extract_minus_sign(): return besseli(-nu, z) newz = z.extract_multiplicatively(I) if newz: # NOTE we don't want to change the function if z==0 return I**(-nu)*besselj(nu, -newz) # branch handling: from sympy.functions.elementary.complexes import unpolarify if nu.is_integer: newz = unpolarify(z) if newz != z: return besseli(nu, newz) else: newz, n = z.extract_branch_factor() if n != 0: return exp(2*n*pi*nu*I)*besseli(nu, newz) nnu = unpolarify(nu) if nu != nnu: return besseli(nnu, z) def _eval_rewrite_as_besselj(self, nu, z, **kwargs): from sympy.functions.elementary.complexes import polar_lift return exp(-I*pi*nu/2)*besselj(nu, polar_lift(I)*z) def _eval_rewrite_as_bessely(self, nu, z, **kwargs): aj = self._eval_rewrite_as_besselj(*self.args) if aj: return aj.rewrite(bessely) def _eval_rewrite_as_jn(self, nu, z, **kwargs): return self._eval_rewrite_as_besselj(*self.args).rewrite(jn) def _eval_is_extended_real(self): nu, z = self.args if nu.is_integer and z.is_extended_real: return True class besselk(BesselBase): r""" Modified Bessel function of the second kind. Explanation =========== The Bessel $K$ function of order $\nu$ is defined as .. math :: K_\nu(z) = \lim_{\mu \to \nu} \frac{\pi}{2} \frac{I_{-\mu}(z) -I_\mu(z)}{\sin(\pi \mu)}, where $I_\mu(z)$ is the modified Bessel function of the first kind. It is a solution of the modified Bessel equation, and linearly independent from $Y_\nu$. Examples ======== >>> from sympy import besselk >>> from sympy.abc import z, n >>> besselk(n, z).diff(z) -besselk(n - 1, z)/2 - besselk(n + 1, z)/2 See Also ======== besselj, besseli, bessely References ========== .. [1] http://functions.wolfram.com/Bessel-TypeFunctions/BesselK/ """ _a = S.One _b = -S.One @classmethod def eval(cls, nu, z): if z.is_zero: if nu.is_zero: return S.Infinity elif re(nu).is_zero is False: return S.ComplexInfinity elif re(nu).is_zero: return S.NaN if z in (S.Infinity, I*S.Infinity, I*S.NegativeInfinity): return S.Zero if nu.is_integer: if nu.could_extract_minus_sign(): return besselk(-nu, z) def _eval_rewrite_as_besseli(self, nu, z, **kwargs): if nu.is_integer is False: return pi*csc(pi*nu)*(besseli(-nu, z) - besseli(nu, z))/2 def _eval_rewrite_as_besselj(self, nu, z, **kwargs): ai = self._eval_rewrite_as_besseli(*self.args) if ai: return ai.rewrite(besselj) def _eval_rewrite_as_bessely(self, nu, z, **kwargs): aj = self._eval_rewrite_as_besselj(*self.args) if aj: return aj.rewrite(bessely) def _eval_rewrite_as_yn(self, nu, z, **kwargs): ay = self._eval_rewrite_as_bessely(*self.args) if ay: return ay.rewrite(yn) def _eval_is_extended_real(self): nu, z = self.args if nu.is_integer and z.is_positive: return True class hankel1(BesselBase): r""" Hankel function of the first kind. Explanation =========== This function is defined as .. math :: H_\nu^{(1)} = J_\nu(z) + iY_\nu(z), where $J_\nu(z)$ is the Bessel function of the first kind, and $Y_\nu(z)$ is the Bessel function of the second kind. It is a solution to Bessel's equation. Examples ======== >>> from sympy import hankel1 >>> from sympy.abc import z, n >>> hankel1(n, z).diff(z) hankel1(n - 1, z)/2 - hankel1(n + 1, z)/2 See Also ======== hankel2, besselj, bessely References ========== .. [1] http://functions.wolfram.com/Bessel-TypeFunctions/HankelH1/ """ _a = S.One _b = S.One def _eval_conjugate(self): z = self.argument if z.is_extended_negative is False: return hankel2(self.order.conjugate(), z.conjugate()) class hankel2(BesselBase): r""" Hankel function of the second kind. Explanation =========== This function is defined as .. math :: H_\nu^{(2)} = J_\nu(z) - iY_\nu(z), where $J_\nu(z)$ is the Bessel function of the first kind, and $Y_\nu(z)$ is the Bessel function of the second kind. It is a solution to Bessel's equation, and linearly independent from $H_\nu^{(1)}$. Examples ======== >>> from sympy import hankel2 >>> from sympy.abc import z, n >>> hankel2(n, z).diff(z) hankel2(n - 1, z)/2 - hankel2(n + 1, z)/2 See Also ======== hankel1, besselj, bessely References ========== .. [1] http://functions.wolfram.com/Bessel-TypeFunctions/HankelH2/ """ _a = S.One _b = S.One def _eval_conjugate(self): z = self.argument if z.is_extended_negative is False: return hankel1(self.order.conjugate(), z.conjugate()) def assume_integer_order(fn): @wraps(fn) def g(self, nu, z): if nu.is_integer: return fn(self, nu, z) return g class SphericalBesselBase(BesselBase): """ Base class for spherical Bessel functions. These are thin wrappers around ordinary Bessel functions, since spherical Bessel functions differ from the ordinary ones just by a slight change in order. To use this class, define the ``_eval_evalf()`` and ``_expand()`` methods. """ def _expand(self, **hints): """ Expand self into a polynomial. Nu is guaranteed to be Integer. """ raise NotImplementedError('expansion') def _eval_expand_func(self, **hints): if self.order.is_Integer: return self._expand(**hints) return self def fdiff(self, argindex=2): if argindex != 2: raise ArgumentIndexError(self, argindex) return self.__class__(self.order - 1, self.argument) - \ self * (self.order + 1)/self.argument def _jn(n, z): return (spherical_bessel_fn(n, z)*sin(z) + S.NegativeOne**(n + 1)*spherical_bessel_fn(-n - 1, z)*cos(z)) def _yn(n, z): # (-1)**(n + 1) * _jn(-n - 1, z) return (S.NegativeOne**(n + 1) * spherical_bessel_fn(-n - 1, z)*sin(z) - spherical_bessel_fn(n, z)*cos(z)) class jn(SphericalBesselBase): r""" Spherical Bessel function of the first kind. Explanation =========== This function is a solution to the spherical Bessel equation .. math :: z^2 \frac{\mathrm{d}^2 w}{\mathrm{d}z^2} + 2z \frac{\mathrm{d}w}{\mathrm{d}z} + (z^2 - \nu(\nu + 1)) w = 0. It can be defined as .. math :: j_\nu(z) = \sqrt{\frac{\pi}{2z}} J_{\nu + \frac{1}{2}}(z), where $J_\nu(z)$ is the Bessel function of the first kind. The spherical Bessel functions of integral order are calculated using the formula: .. math:: j_n(z) = f_n(z) \sin{z} + (-1)^{n+1} f_{-n-1}(z) \cos{z}, where the coefficients $f_n(z)$ are available as :func:`sympy.polys.orthopolys.spherical_bessel_fn`. Examples ======== >>> from sympy import Symbol, jn, sin, cos, expand_func, besselj, bessely >>> z = Symbol("z") >>> nu = Symbol("nu", integer=True) >>> print(expand_func(jn(0, z))) sin(z)/z >>> expand_func(jn(1, z)) == sin(z)/z**2 - cos(z)/z True >>> expand_func(jn(3, z)) (-6/z**2 + 15/z**4)*sin(z) + (1/z - 15/z**3)*cos(z) >>> jn(nu, z).rewrite(besselj) sqrt(2)*sqrt(pi)*sqrt(1/z)*besselj(nu + 1/2, z)/2 >>> jn(nu, z).rewrite(bessely) (-1)**nu*sqrt(2)*sqrt(pi)*sqrt(1/z)*bessely(-nu - 1/2, z)/2 >>> jn(2, 5.2+0.3j).evalf(20) 0.099419756723640344491 - 0.054525080242173562897*I See Also ======== besselj, bessely, besselk, yn References ========== .. [1] http://dlmf.nist.gov/10.47 """ @classmethod def eval(cls, nu, z): if z.is_zero: if nu.is_zero: return S.One elif nu.is_integer: if nu.is_positive: return S.Zero else: return S.ComplexInfinity if z in (S.NegativeInfinity, S.Infinity): return S.Zero def _eval_rewrite_as_besselj(self, nu, z, **kwargs): return sqrt(pi/(2*z)) * besselj(nu + S.Half, z) def _eval_rewrite_as_bessely(self, nu, z, **kwargs): return S.NegativeOne**nu * sqrt(pi/(2*z)) * bessely(-nu - S.Half, z) def _eval_rewrite_as_yn(self, nu, z, **kwargs): return S.NegativeOne**(nu) * yn(-nu - 1, z) def _expand(self, **hints): return _jn(self.order, self.argument) def _eval_evalf(self, prec): if self.order.is_Integer: return self.rewrite(besselj)._eval_evalf(prec) class yn(SphericalBesselBase): r""" Spherical Bessel function of the second kind. Explanation =========== This function is another solution to the spherical Bessel equation, and linearly independent from $j_n$. It can be defined as .. math :: y_\nu(z) = \sqrt{\frac{\pi}{2z}} Y_{\nu + \frac{1}{2}}(z), where $Y_\nu(z)$ is the Bessel function of the second kind. For integral orders $n$, $y_n$ is calculated using the formula: .. math:: y_n(z) = (-1)^{n+1} j_{-n-1}(z) Examples ======== >>> from sympy import Symbol, yn, sin, cos, expand_func, besselj, bessely >>> z = Symbol("z") >>> nu = Symbol("nu", integer=True) >>> print(expand_func(yn(0, z))) -cos(z)/z >>> expand_func(yn(1, z)) == -cos(z)/z**2-sin(z)/z True >>> yn(nu, z).rewrite(besselj) (-1)**(nu + 1)*sqrt(2)*sqrt(pi)*sqrt(1/z)*besselj(-nu - 1/2, z)/2 >>> yn(nu, z).rewrite(bessely) sqrt(2)*sqrt(pi)*sqrt(1/z)*bessely(nu + 1/2, z)/2 >>> yn(2, 5.2+0.3j).evalf(20) 0.18525034196069722536 + 0.014895573969924817587*I See Also ======== besselj, bessely, besselk, jn References ========== .. [1] http://dlmf.nist.gov/10.47 """ @assume_integer_order def _eval_rewrite_as_besselj(self, nu, z, **kwargs): return S.NegativeOne**(nu+1) * sqrt(pi/(2*z)) * besselj(-nu - S.Half, z) @assume_integer_order def _eval_rewrite_as_bessely(self, nu, z, **kwargs): return sqrt(pi/(2*z)) * bessely(nu + S.Half, z) def _eval_rewrite_as_jn(self, nu, z, **kwargs): return S.NegativeOne**(nu + 1) * jn(-nu - 1, z) def _expand(self, **hints): return _yn(self.order, self.argument) def _eval_evalf(self, prec): if self.order.is_Integer: return self.rewrite(bessely)._eval_evalf(prec) class SphericalHankelBase(SphericalBesselBase): @assume_integer_order def _eval_rewrite_as_besselj(self, nu, z, **kwargs): # jn +- I*yn # jn as beeselj: sqrt(pi/(2*z)) * besselj(nu + S.Half, z) # yn as besselj: (-1)**(nu+1) * sqrt(pi/(2*z)) * besselj(-nu - S.Half, z) hks = self._hankel_kind_sign return sqrt(pi/(2*z))*(besselj(nu + S.Half, z) + hks*I*S.NegativeOne**(nu+1)*besselj(-nu - S.Half, z)) @assume_integer_order def _eval_rewrite_as_bessely(self, nu, z, **kwargs): # jn +- I*yn # jn as bessely: (-1)**nu * sqrt(pi/(2*z)) * bessely(-nu - S.Half, z) # yn as bessely: sqrt(pi/(2*z)) * bessely(nu + S.Half, z) hks = self._hankel_kind_sign return sqrt(pi/(2*z))*(S.NegativeOne**nu*bessely(-nu - S.Half, z) + hks*I*bessely(nu + S.Half, z)) def _eval_rewrite_as_yn(self, nu, z, **kwargs): hks = self._hankel_kind_sign return jn(nu, z).rewrite(yn) + hks*I*yn(nu, z) def _eval_rewrite_as_jn(self, nu, z, **kwargs): hks = self._hankel_kind_sign return jn(nu, z) + hks*I*yn(nu, z).rewrite(jn) def _eval_expand_func(self, **hints): if self.order.is_Integer: return self._expand(**hints) else: nu = self.order z = self.argument hks = self._hankel_kind_sign return jn(nu, z) + hks*I*yn(nu, z) def _expand(self, **hints): n = self.order z = self.argument hks = self._hankel_kind_sign # fully expanded version # return ((fn(n, z) * sin(z) + # (-1)**(n + 1) * fn(-n - 1, z) * cos(z)) + # jn # (hks * I * (-1)**(n + 1) * # (fn(-n - 1, z) * hk * I * sin(z) + # (-1)**(-n) * fn(n, z) * I * cos(z))) # +-I*yn # ) return (_jn(n, z) + hks*I*_yn(n, z)).expand() def _eval_evalf(self, prec): if self.order.is_Integer: return self.rewrite(besselj)._eval_evalf(prec) class hn1(SphericalHankelBase): r""" Spherical Hankel function of the first kind. Explanation =========== This function is defined as .. math:: h_\nu^(1)(z) = j_\nu(z) + i y_\nu(z), where $j_\nu(z)$ and $y_\nu(z)$ are the spherical Bessel function of the first and second kinds. For integral orders $n$, $h_n^(1)$ is calculated using the formula: .. math:: h_n^(1)(z) = j_{n}(z) + i (-1)^{n+1} j_{-n-1}(z) Examples ======== >>> from sympy import Symbol, hn1, hankel1, expand_func, yn, jn >>> z = Symbol("z") >>> nu = Symbol("nu", integer=True) >>> print(expand_func(hn1(nu, z))) jn(nu, z) + I*yn(nu, z) >>> print(expand_func(hn1(0, z))) sin(z)/z - I*cos(z)/z >>> print(expand_func(hn1(1, z))) -I*sin(z)/z - cos(z)/z + sin(z)/z**2 - I*cos(z)/z**2 >>> hn1(nu, z).rewrite(jn) (-1)**(nu + 1)*I*jn(-nu - 1, z) + jn(nu, z) >>> hn1(nu, z).rewrite(yn) (-1)**nu*yn(-nu - 1, z) + I*yn(nu, z) >>> hn1(nu, z).rewrite(hankel1) sqrt(2)*sqrt(pi)*sqrt(1/z)*hankel1(nu, z)/2 See Also ======== hn2, jn, yn, hankel1, hankel2 References ========== .. [1] http://dlmf.nist.gov/10.47 """ _hankel_kind_sign = S.One @assume_integer_order def _eval_rewrite_as_hankel1(self, nu, z, **kwargs): return sqrt(pi/(2*z))*hankel1(nu, z) class hn2(SphericalHankelBase): r""" Spherical Hankel function of the second kind. Explanation =========== This function is defined as .. math:: h_\nu^(2)(z) = j_\nu(z) - i y_\nu(z), where $j_\nu(z)$ and $y_\nu(z)$ are the spherical Bessel function of the first and second kinds. For integral orders $n$, $h_n^(2)$ is calculated using the formula: .. math:: h_n^(2)(z) = j_{n} - i (-1)^{n+1} j_{-n-1}(z) Examples ======== >>> from sympy import Symbol, hn2, hankel2, expand_func, jn, yn >>> z = Symbol("z") >>> nu = Symbol("nu", integer=True) >>> print(expand_func(hn2(nu, z))) jn(nu, z) - I*yn(nu, z) >>> print(expand_func(hn2(0, z))) sin(z)/z + I*cos(z)/z >>> print(expand_func(hn2(1, z))) I*sin(z)/z - cos(z)/z + sin(z)/z**2 + I*cos(z)/z**2 >>> hn2(nu, z).rewrite(hankel2) sqrt(2)*sqrt(pi)*sqrt(1/z)*hankel2(nu, z)/2 >>> hn2(nu, z).rewrite(jn) -(-1)**(nu + 1)*I*jn(-nu - 1, z) + jn(nu, z) >>> hn2(nu, z).rewrite(yn) (-1)**nu*yn(-nu - 1, z) - I*yn(nu, z) See Also ======== hn1, jn, yn, hankel1, hankel2 References ========== .. [1] http://dlmf.nist.gov/10.47 """ _hankel_kind_sign = -S.One @assume_integer_order def _eval_rewrite_as_hankel2(self, nu, z, **kwargs): return sqrt(pi/(2*z))*hankel2(nu, z) def jn_zeros(n, k, method="sympy", dps=15): """ Zeros of the spherical Bessel function of the first kind. Explanation =========== This returns an array of zeros of $jn$ up to the $k$-th zero. * method = "sympy": uses `mpmath.besseljzero <http://mpmath.org/doc/current/functions/bessel.html#mpmath.besseljzero>`_ * method = "scipy": uses the `SciPy's sph_jn <http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.jn_zeros.html>`_ and `newton <http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.newton.html>`_ to find all roots, which is faster than computing the zeros using a general numerical solver, but it requires SciPy and only works with low precision floating point numbers. (The function used with method="sympy" is a recent addition to mpmath; before that a general solver was used.) Examples ======== >>> from sympy import jn_zeros >>> jn_zeros(2, 4, dps=5) [5.7635, 9.095, 12.323, 15.515] See Also ======== jn, yn, besselj, besselk, bessely Parameters ========== n : integer order of Bessel function k : integer number of zeros to return """ from math import pi as math_pi if method == "sympy": from mpmath import besseljzero from mpmath.libmp.libmpf import dps_to_prec prec = dps_to_prec(dps) return [Expr._from_mpmath(besseljzero(S(n + 0.5)._to_mpmath(prec), int(l)), prec) for l in range(1, k + 1)] elif method == "scipy": from scipy.optimize import newton try: from scipy.special import spherical_jn f = lambda x: spherical_jn(n, x) except ImportError: from scipy.special import sph_jn f = lambda x: sph_jn(n, x)[0][-1] else: raise NotImplementedError("Unknown method.") def solver(f, x): if method == "scipy": root = newton(f, x) else: raise NotImplementedError("Unknown method.") return root # we need to approximate the position of the first root: root = n + math_pi # determine the first root exactly: root = solver(f, root) roots = [root] for i in range(k - 1): # estimate the position of the next root using the last root + pi: root = solver(f, root + math_pi) roots.append(root) return roots class AiryBase(Function): """ Abstract base class for Airy functions. This class is meant to reduce code duplication. """ def _eval_conjugate(self): return self.func(self.args[0].conjugate()) def _eval_is_extended_real(self): return self.args[0].is_extended_real def as_real_imag(self, deep=True, **hints): z = self.args[0] zc = z.conjugate() f = self.func u = (f(z)+f(zc))/2 v = I*(f(zc)-f(z))/2 return u, v 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 class airyai(AiryBase): r""" The Airy function $\operatorname{Ai}$ of the first kind. Explanation =========== The Airy function $\operatorname{Ai}(z)$ is defined to be the function satisfying Airy's differential equation .. math:: \frac{\mathrm{d}^2 w(z)}{\mathrm{d}z^2} - z w(z) = 0. Equivalently, for real $z$ .. math:: \operatorname{Ai}(z) := \frac{1}{\pi} \int_0^\infty \cos\left(\frac{t^3}{3} + z t\right) \mathrm{d}t. Examples ======== Create an Airy function object: >>> from sympy import airyai >>> from sympy.abc import z >>> airyai(z) airyai(z) Several special values are known: >>> airyai(0) 3**(1/3)/(3*gamma(2/3)) >>> from sympy import oo >>> airyai(oo) 0 >>> airyai(-oo) 0 The Airy function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(airyai(z)) airyai(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(airyai(z), z) airyaiprime(z) >>> diff(airyai(z), z, 2) z*airyai(z) Series expansion is also supported: >>> from sympy import series >>> series(airyai(z), z, 0, 3) 3**(5/6)*gamma(1/3)/(6*pi) - 3**(1/6)*z*gamma(2/3)/(2*pi) + O(z**3) We can numerically evaluate the Airy function to arbitrary precision on the whole complex plane: >>> airyai(-2).evalf(50) 0.22740742820168557599192443603787379946077222541710 Rewrite $\operatorname{Ai}(z)$ in terms of hypergeometric functions: >>> from sympy import hyper >>> airyai(z).rewrite(hyper) -3**(2/3)*z*hyper((), (4/3,), z**3/9)/(3*gamma(1/3)) + 3**(1/3)*hyper((), (2/3,), z**3/9)/(3*gamma(2/3)) See Also ======== airybi: Airy function of the second kind. airyaiprime: Derivative of the Airy function of the first kind. airybiprime: Derivative of the Airy function of the second kind. References ========== .. [1] https://en.wikipedia.org/wiki/Airy_function .. [2] http://dlmf.nist.gov/9 .. [3] http://www.encyclopediaofmath.org/index.php/Airy_functions .. [4] http://mathworld.wolfram.com/AiryFunctions.html """ nargs = 1 unbranched = True @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.One / (3**Rational(2, 3) * gamma(Rational(2, 3))) if arg.is_zero: return S.One / (3**Rational(2, 3) * gamma(Rational(2, 3))) def fdiff(self, argindex=1): if argindex == 1: return airyaiprime(self.args[0]) else: raise ArgumentIndexError(self, argindex) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0: return S.Zero else: x = sympify(x) if len(previous_terms) > 1: p = previous_terms[-1] return ((3**Rational(1, 3)*x)**(-n)*(3**Rational(1, 3)*x)**(n + 1)*sin(pi*(n*Rational(2, 3) + Rational(4, 3)))*factorial(n) * gamma(n/3 + Rational(2, 3))/(sin(pi*(n*Rational(2, 3) + Rational(2, 3)))*factorial(n + 1)*gamma(n/3 + Rational(1, 3))) * p) else: return (S.One/(3**Rational(2, 3)*pi) * gamma((n+S.One)/S(3)) * sin(2*pi*(n+S.One)/S(3)) / factorial(n) * (root(3, 3)*x)**n) def _eval_rewrite_as_besselj(self, z, **kwargs): ot = Rational(1, 3) tt = Rational(2, 3) a = Pow(-z, Rational(3, 2)) if re(z).is_negative: return ot*sqrt(-z) * (besselj(-ot, tt*a) + besselj(ot, tt*a)) def _eval_rewrite_as_besseli(self, z, **kwargs): ot = Rational(1, 3) tt = Rational(2, 3) a = Pow(z, Rational(3, 2)) if re(z).is_positive: return ot*sqrt(z) * (besseli(-ot, tt*a) - besseli(ot, tt*a)) else: return ot*(Pow(a, ot)*besseli(-ot, tt*a) - z*Pow(a, -ot)*besseli(ot, tt*a)) def _eval_rewrite_as_hyper(self, z, **kwargs): pf1 = S.One / (3**Rational(2, 3)*gamma(Rational(2, 3))) pf2 = z / (root(3, 3)*gamma(Rational(1, 3))) return pf1 * hyper([], [Rational(2, 3)], z**3/9) - pf2 * hyper([], [Rational(4, 3)], z**3/9) def _eval_expand_func(self, **hints): arg = self.args[0] symbs = arg.free_symbols if len(symbs) == 1: z = symbs.pop() c = Wild("c", exclude=[z]) d = Wild("d", exclude=[z]) m = Wild("m", exclude=[z]) n = Wild("n", exclude=[z]) M = arg.match(c*(d*z**n)**m) if M is not None: m = M[m] # The transformation is given by 03.05.16.0001.01 # http://functions.wolfram.com/Bessel-TypeFunctions/AiryAi/16/01/01/0001/ if (3*m).is_integer: c = M[c] d = M[d] n = M[n] pf = (d * z**n)**m / (d**m * z**(m*n)) newarg = c * d**m * z**(m*n) return S.Half * ((pf + S.One)*airyai(newarg) - (pf - S.One)/sqrt(3)*airybi(newarg)) class airybi(AiryBase): r""" The Airy function $\operatorname{Bi}$ of the second kind. Explanation =========== The Airy function $\operatorname{Bi}(z)$ is defined to be the function satisfying Airy's differential equation .. math:: \frac{\mathrm{d}^2 w(z)}{\mathrm{d}z^2} - z w(z) = 0. Equivalently, for real $z$ .. math:: \operatorname{Bi}(z) := \frac{1}{\pi} \int_0^\infty \exp\left(-\frac{t^3}{3} + z t\right) + \sin\left(\frac{t^3}{3} + z t\right) \mathrm{d}t. Examples ======== Create an Airy function object: >>> from sympy import airybi >>> from sympy.abc import z >>> airybi(z) airybi(z) Several special values are known: >>> airybi(0) 3**(5/6)/(3*gamma(2/3)) >>> from sympy import oo >>> airybi(oo) oo >>> airybi(-oo) 0 The Airy function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(airybi(z)) airybi(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(airybi(z), z) airybiprime(z) >>> diff(airybi(z), z, 2) z*airybi(z) Series expansion is also supported: >>> from sympy import series >>> series(airybi(z), z, 0, 3) 3**(1/3)*gamma(1/3)/(2*pi) + 3**(2/3)*z*gamma(2/3)/(2*pi) + O(z**3) We can numerically evaluate the Airy function to arbitrary precision on the whole complex plane: >>> airybi(-2).evalf(50) -0.41230258795639848808323405461146104203453483447240 Rewrite $\operatorname{Bi}(z)$ in terms of hypergeometric functions: >>> from sympy import hyper >>> airybi(z).rewrite(hyper) 3**(1/6)*z*hyper((), (4/3,), z**3/9)/gamma(1/3) + 3**(5/6)*hyper((), (2/3,), z**3/9)/(3*gamma(2/3)) See Also ======== airyai: Airy function of the first kind. airyaiprime: Derivative of the Airy function of the first kind. airybiprime: Derivative of the Airy function of the second kind. References ========== .. [1] https://en.wikipedia.org/wiki/Airy_function .. [2] http://dlmf.nist.gov/9 .. [3] http://www.encyclopediaofmath.org/index.php/Airy_functions .. [4] http://mathworld.wolfram.com/AiryFunctions.html """ nargs = 1 unbranched = True @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 arg is S.NegativeInfinity: return S.Zero elif arg.is_zero: return S.One / (3**Rational(1, 6) * gamma(Rational(2, 3))) if arg.is_zero: return S.One / (3**Rational(1, 6) * gamma(Rational(2, 3))) def fdiff(self, argindex=1): if argindex == 1: return airybiprime(self.args[0]) else: raise ArgumentIndexError(self, argindex) @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n < 0: return S.Zero else: x = sympify(x) if len(previous_terms) > 1: p = previous_terms[-1] return (3**Rational(1, 3)*x * Abs(sin(2*pi*(n + S.One)/S(3))) * factorial((n - S.One)/S(3)) / ((n + S.One) * Abs(cos(2*pi*(n + S.Half)/S(3))) * factorial((n - 2)/S(3))) * p) else: return (S.One/(root(3, 6)*pi) * gamma((n + S.One)/S(3)) * Abs(sin(2*pi*(n + S.One)/S(3))) / factorial(n) * (root(3, 3)*x)**n) def _eval_rewrite_as_besselj(self, z, **kwargs): ot = Rational(1, 3) tt = Rational(2, 3) a = Pow(-z, Rational(3, 2)) if re(z).is_negative: return sqrt(-z/3) * (besselj(-ot, tt*a) - besselj(ot, tt*a)) def _eval_rewrite_as_besseli(self, z, **kwargs): ot = Rational(1, 3) tt = Rational(2, 3) a = Pow(z, Rational(3, 2)) if re(z).is_positive: return sqrt(z)/sqrt(3) * (besseli(-ot, tt*a) + besseli(ot, tt*a)) else: b = Pow(a, ot) c = Pow(a, -ot) return sqrt(ot)*(b*besseli(-ot, tt*a) + z*c*besseli(ot, tt*a)) def _eval_rewrite_as_hyper(self, z, **kwargs): pf1 = S.One / (root(3, 6)*gamma(Rational(2, 3))) pf2 = z*root(3, 6) / gamma(Rational(1, 3)) return pf1 * hyper([], [Rational(2, 3)], z**3/9) + pf2 * hyper([], [Rational(4, 3)], z**3/9) def _eval_expand_func(self, **hints): arg = self.args[0] symbs = arg.free_symbols if len(symbs) == 1: z = symbs.pop() c = Wild("c", exclude=[z]) d = Wild("d", exclude=[z]) m = Wild("m", exclude=[z]) n = Wild("n", exclude=[z]) M = arg.match(c*(d*z**n)**m) if M is not None: m = M[m] # The transformation is given by 03.06.16.0001.01 # http://functions.wolfram.com/Bessel-TypeFunctions/AiryBi/16/01/01/0001/ if (3*m).is_integer: c = M[c] d = M[d] n = M[n] pf = (d * z**n)**m / (d**m * z**(m*n)) newarg = c * d**m * z**(m*n) return S.Half * (sqrt(3)*(S.One - pf)*airyai(newarg) + (S.One + pf)*airybi(newarg)) class airyaiprime(AiryBase): r""" The derivative $\operatorname{Ai}^\prime$ of the Airy function of the first kind. Explanation =========== The Airy function $\operatorname{Ai}^\prime(z)$ is defined to be the function .. math:: \operatorname{Ai}^\prime(z) := \frac{\mathrm{d} \operatorname{Ai}(z)}{\mathrm{d} z}. Examples ======== Create an Airy function object: >>> from sympy import airyaiprime >>> from sympy.abc import z >>> airyaiprime(z) airyaiprime(z) Several special values are known: >>> airyaiprime(0) -3**(2/3)/(3*gamma(1/3)) >>> from sympy import oo >>> airyaiprime(oo) 0 The Airy function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(airyaiprime(z)) airyaiprime(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(airyaiprime(z), z) z*airyai(z) >>> diff(airyaiprime(z), z, 2) z*airyaiprime(z) + airyai(z) Series expansion is also supported: >>> from sympy import series >>> series(airyaiprime(z), z, 0, 3) -3**(2/3)/(3*gamma(1/3)) + 3**(1/3)*z**2/(6*gamma(2/3)) + O(z**3) We can numerically evaluate the Airy function to arbitrary precision on the whole complex plane: >>> airyaiprime(-2).evalf(50) 0.61825902074169104140626429133247528291577794512415 Rewrite $\operatorname{Ai}^\prime(z)$ in terms of hypergeometric functions: >>> from sympy import hyper >>> airyaiprime(z).rewrite(hyper) 3**(1/3)*z**2*hyper((), (5/3,), z**3/9)/(6*gamma(2/3)) - 3**(2/3)*hyper((), (1/3,), z**3/9)/(3*gamma(1/3)) See Also ======== airyai: Airy function of the first kind. airybi: Airy function of the second kind. airybiprime: Derivative of the Airy function of the second kind. References ========== .. [1] https://en.wikipedia.org/wiki/Airy_function .. [2] http://dlmf.nist.gov/9 .. [3] http://www.encyclopediaofmath.org/index.php/Airy_functions .. [4] http://mathworld.wolfram.com/AiryFunctions.html """ nargs = 1 unbranched = True @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 if arg.is_zero: return S.NegativeOne / (3**Rational(1, 3) * gamma(Rational(1, 3))) def fdiff(self, argindex=1): if argindex == 1: return self.args[0]*airyai(self.args[0]) else: raise ArgumentIndexError(self, argindex) def _eval_evalf(self, prec): z = self.args[0]._to_mpmath(prec) with workprec(prec): res = mp.airyai(z, derivative=1) return Expr._from_mpmath(res, prec) def _eval_rewrite_as_besselj(self, z, **kwargs): tt = Rational(2, 3) a = Pow(-z, Rational(3, 2)) if re(z).is_negative: return z/3 * (besselj(-tt, tt*a) - besselj(tt, tt*a)) def _eval_rewrite_as_besseli(self, z, **kwargs): ot = Rational(1, 3) tt = Rational(2, 3) a = tt * Pow(z, Rational(3, 2)) if re(z).is_positive: return z/3 * (besseli(tt, a) - besseli(-tt, a)) else: a = Pow(z, Rational(3, 2)) b = Pow(a, tt) c = Pow(a, -tt) return ot * (z**2*c*besseli(tt, tt*a) - b*besseli(-ot, tt*a)) def _eval_rewrite_as_hyper(self, z, **kwargs): pf1 = z**2 / (2*3**Rational(2, 3)*gamma(Rational(2, 3))) pf2 = 1 / (root(3, 3)*gamma(Rational(1, 3))) return pf1 * hyper([], [Rational(5, 3)], z**3/9) - pf2 * hyper([], [Rational(1, 3)], z**3/9) def _eval_expand_func(self, **hints): arg = self.args[0] symbs = arg.free_symbols if len(symbs) == 1: z = symbs.pop() c = Wild("c", exclude=[z]) d = Wild("d", exclude=[z]) m = Wild("m", exclude=[z]) n = Wild("n", exclude=[z]) M = arg.match(c*(d*z**n)**m) if M is not None: m = M[m] # The transformation is in principle # given by 03.07.16.0001.01 but note # that there is an error in this formula. # http://functions.wolfram.com/Bessel-TypeFunctions/AiryAiPrime/16/01/01/0001/ if (3*m).is_integer: c = M[c] d = M[d] n = M[n] pf = (d**m * z**(n*m)) / (d * z**n)**m newarg = c * d**m * z**(n*m) return S.Half * ((pf + S.One)*airyaiprime(newarg) + (pf - S.One)/sqrt(3)*airybiprime(newarg)) class airybiprime(AiryBase): r""" The derivative $\operatorname{Bi}^\prime$ of the Airy function of the first kind. Explanation =========== The Airy function $\operatorname{Bi}^\prime(z)$ is defined to be the function .. math:: \operatorname{Bi}^\prime(z) := \frac{\mathrm{d} \operatorname{Bi}(z)}{\mathrm{d} z}. Examples ======== Create an Airy function object: >>> from sympy import airybiprime >>> from sympy.abc import z >>> airybiprime(z) airybiprime(z) Several special values are known: >>> airybiprime(0) 3**(1/6)/gamma(1/3) >>> from sympy import oo >>> airybiprime(oo) oo >>> airybiprime(-oo) 0 The Airy function obeys the mirror symmetry: >>> from sympy import conjugate >>> conjugate(airybiprime(z)) airybiprime(conjugate(z)) Differentiation with respect to $z$ is supported: >>> from sympy import diff >>> diff(airybiprime(z), z) z*airybi(z) >>> diff(airybiprime(z), z, 2) z*airybiprime(z) + airybi(z) Series expansion is also supported: >>> from sympy import series >>> series(airybiprime(z), z, 0, 3) 3**(1/6)/gamma(1/3) + 3**(5/6)*z**2/(6*gamma(2/3)) + O(z**3) We can numerically evaluate the Airy function to arbitrary precision on the whole complex plane: >>> airybiprime(-2).evalf(50) 0.27879516692116952268509756941098324140300059345163 Rewrite $\operatorname{Bi}^\prime(z)$ in terms of hypergeometric functions: >>> from sympy import hyper >>> airybiprime(z).rewrite(hyper) 3**(5/6)*z**2*hyper((), (5/3,), z**3/9)/(6*gamma(2/3)) + 3**(1/6)*hyper((), (1/3,), z**3/9)/gamma(1/3) See Also ======== airyai: Airy function of the first kind. airybi: Airy function of the second kind. airyaiprime: Derivative of the Airy function of the first kind. References ========== .. [1] https://en.wikipedia.org/wiki/Airy_function .. [2] http://dlmf.nist.gov/9 .. [3] http://www.encyclopediaofmath.org/index.php/Airy_functions .. [4] http://mathworld.wolfram.com/AiryFunctions.html """ nargs = 1 unbranched = True @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 arg is S.NegativeInfinity: return S.Zero elif arg.is_zero: return 3**Rational(1, 6) / gamma(Rational(1, 3)) if arg.is_zero: return 3**Rational(1, 6) / gamma(Rational(1, 3)) def fdiff(self, argindex=1): if argindex == 1: return self.args[0]*airybi(self.args[0]) else: raise ArgumentIndexError(self, argindex) def _eval_evalf(self, prec): z = self.args[0]._to_mpmath(prec) with workprec(prec): res = mp.airybi(z, derivative=1) return Expr._from_mpmath(res, prec) def _eval_rewrite_as_besselj(self, z, **kwargs): tt = Rational(2, 3) a = tt * Pow(-z, Rational(3, 2)) if re(z).is_negative: return -z/sqrt(3) * (besselj(-tt, a) + besselj(tt, a)) def _eval_rewrite_as_besseli(self, z, **kwargs): ot = Rational(1, 3) tt = Rational(2, 3) a = tt * Pow(z, Rational(3, 2)) if re(z).is_positive: return z/sqrt(3) * (besseli(-tt, a) + besseli(tt, a)) else: a = Pow(z, Rational(3, 2)) b = Pow(a, tt) c = Pow(a, -tt) return sqrt(ot) * (b*besseli(-tt, tt*a) + z**2*c*besseli(tt, tt*a)) def _eval_rewrite_as_hyper(self, z, **kwargs): pf1 = z**2 / (2*root(3, 6)*gamma(Rational(2, 3))) pf2 = root(3, 6) / gamma(Rational(1, 3)) return pf1 * hyper([], [Rational(5, 3)], z**3/9) + pf2 * hyper([], [Rational(1, 3)], z**3/9) def _eval_expand_func(self, **hints): arg = self.args[0] symbs = arg.free_symbols if len(symbs) == 1: z = symbs.pop() c = Wild("c", exclude=[z]) d = Wild("d", exclude=[z]) m = Wild("m", exclude=[z]) n = Wild("n", exclude=[z]) M = arg.match(c*(d*z**n)**m) if M is not None: m = M[m] # The transformation is in principle # given by 03.08.16.0001.01 but note # that there is an error in this formula. # http://functions.wolfram.com/Bessel-TypeFunctions/AiryBiPrime/16/01/01/0001/ if (3*m).is_integer: c = M[c] d = M[d] n = M[n] pf = (d**m * z**(n*m)) / (d * z**n)**m newarg = c * d**m * z**(n*m) return S.Half * (sqrt(3)*(pf - S.One)*airyaiprime(newarg) + (pf + S.One)*airybiprime(newarg)) class marcumq(Function): r""" The Marcum Q-function. Explanation =========== The Marcum Q-function is defined by the meromorphic continuation of .. math:: Q_m(a, b) = a^{- m + 1} \int_{b}^{\infty} x^{m} e^{- \frac{a^{2}}{2} - \frac{x^{2}}{2}} I_{m - 1}\left(a x\right)\, dx Examples ======== >>> from sympy import marcumq >>> from sympy.abc import m, a, b >>> marcumq(m, a, b) marcumq(m, a, b) Special values: >>> marcumq(m, 0, b) uppergamma(m, b**2/2)/gamma(m) >>> marcumq(0, 0, 0) 0 >>> marcumq(0, a, 0) 1 - exp(-a**2/2) >>> marcumq(1, a, a) 1/2 + exp(-a**2)*besseli(0, a**2)/2 >>> marcumq(2, a, a) 1/2 + exp(-a**2)*besseli(0, a**2)/2 + exp(-a**2)*besseli(1, a**2) Differentiation with respect to $a$ and $b$ is supported: >>> from sympy import diff >>> diff(marcumq(m, a, b), a) a*(-marcumq(m, a, b) + marcumq(m + 1, a, b)) >>> diff(marcumq(m, a, b), b) -a**(1 - m)*b**m*exp(-a**2/2 - b**2/2)*besseli(m - 1, a*b) References ========== .. [1] https://en.wikipedia.org/wiki/Marcum_Q-function .. [2] http://mathworld.wolfram.com/MarcumQ-Function.html """ @classmethod def eval(cls, m, a, b): if a is S.Zero: if m is S.Zero and b is S.Zero: return S.Zero return uppergamma(m, b**2 * S.Half) / gamma(m) if m is S.Zero and b is S.Zero: return 1 - 1 / exp(a**2 * S.Half) if a == b: if m is S.One: return (1 + exp(-a**2) * besseli(0, a**2))*S.Half if m == 2: return S.Half + S.Half * exp(-a**2) * besseli(0, a**2) + exp(-a**2) * besseli(1, a**2) if a.is_zero: if m.is_zero and b.is_zero: return S.Zero return uppergamma(m, b**2*S.Half) / gamma(m) if m.is_zero and b.is_zero: return 1 - 1 / exp(a**2*S.Half) def fdiff(self, argindex=2): m, a, b = self.args if argindex == 2: return a * (-marcumq(m, a, b) + marcumq(1+m, a, b)) elif argindex == 3: return (-b**m / a**(m-1)) * exp(-(a**2 + b**2)/2) * besseli(m-1, a*b) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_Integral(self, m, a, b, **kwargs): from sympy.integrals.integrals import Integral x = kwargs.get('x', Dummy('x')) return a ** (1 - m) * \ Integral(x**m * exp(-(x**2 + a**2)/2) * besseli(m-1, a*x), [x, b, S.Infinity]) def _eval_rewrite_as_Sum(self, m, a, b, **kwargs): from sympy.concrete.summations import Sum k = kwargs.get('k', Dummy('k')) return exp(-(a**2 + b**2) / 2) * Sum((a/b)**k * besseli(k, a*b), [k, 1-m, S.Infinity]) def _eval_rewrite_as_besseli(self, m, a, b, **kwargs): if a == b: if m == 1: return (1 + exp(-a**2) * besseli(0, a**2)) / 2 if m.is_Integer and m >= 2: s = sum([besseli(i, a**2) for i in range(1, m)]) return S.Half + exp(-a**2) * besseli(0, a**2) / 2 + exp(-a**2) * s def _eval_is_zero(self): if all(arg.is_zero for arg in self.args): return True