Ejemplo n.º 1
0
def test_catalan():
    n = Symbol('n', integer=True)
    m = Symbol('n', integer=True, positive=True)

    catalans = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786]
    for i, c in enumerate(catalans):
        assert catalan(i) == c
        assert catalan(n).rewrite(factorial).subs(n, i) == c
        assert catalan(n).rewrite(Product).subs(n, i).doit() == c

    assert catalan(x) == catalan(x)
    assert catalan(2 *
                   x).rewrite(binomial) == binomial(4 * x, 2 * x) / (2 * x + 1)
    assert catalan(Rational(1, 2)).rewrite(gamma) == 8 / (3 * pi)
    assert catalan(Rational(1, 2)).rewrite(factorial).rewrite(gamma) ==\
        8 / (3 * pi)
    assert catalan(3 * x).rewrite(gamma) == 4**(
        3 * x) * gamma(3 * x + Rational(1, 2)) / (sqrt(pi) * gamma(3 * x + 2))
    assert catalan(x).rewrite(hyper) == hyper((-x + 1, -x), (2, ), 1)

    assert catalan(n).rewrite(factorial) == factorial(
        2 * n) / (factorial(n + 1) * factorial(n))
    assert isinstance(catalan(n).rewrite(Product), catalan)
    assert isinstance(catalan(m).rewrite(Product), Product)

    assert diff(catalan(x), x) == (polygamma(0, x + Rational(1, 2)) -
                                   polygamma(0, x + 2) + log(4)) * catalan(x)

    assert catalan(x).evalf() == catalan(x)
    c = catalan(S.Half).evalf()
    assert str(c) == '0.848826363156775'
    c = catalan(I).evalf(3)
    assert str((re(c), im(c))) == '(0.398, -0.0209)'
Ejemplo n.º 2
0
def test_catalan():
    n = Symbol('n', integer=True)
    m = Symbol('n', integer=True, positive=True)

    catalans = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786]
    for i, c in enumerate(catalans):
        assert catalan(i) == c
        assert catalan(n).rewrite(factorial).subs(n, i) == c
        assert catalan(n).rewrite(Product).subs(n, i).doit() == c

    assert catalan(x) == catalan(x)
    assert catalan(2*x).rewrite(binomial) == binomial(4*x, 2*x)/(2*x + 1)
    assert catalan(Rational(1, 2)).rewrite(gamma) == 8/(3*pi)
    assert catalan(Rational(1, 2)).rewrite(factorial).rewrite(gamma) ==\
        8 / (3 * pi)
    assert catalan(3*x).rewrite(gamma) == 4**(
        3*x)*gamma(3*x + Rational(1, 2))/(sqrt(pi)*gamma(3*x + 2))
    assert catalan(x).rewrite(hyper) == hyper((-x + 1, -x), (2,), 1)

    assert catalan(n).rewrite(factorial) == factorial(2*n) / (factorial(n + 1)
                                                              * factorial(n))
    assert isinstance(catalan(n).rewrite(Product), catalan)
    assert isinstance(catalan(m).rewrite(Product), Product)

    assert diff(catalan(x), x) == (polygamma(
        0, x + Rational(1, 2)) - polygamma(0, x + 2) + log(4))*catalan(x)

    assert catalan(x).evalf() == catalan(x)
    c = catalan(S.Half).evalf()
    assert str(c) == '0.848826363156775'
    c = catalan(I).evalf(3)
    assert str((re(c), im(c))) == '(0.398, -0.0209)'
Ejemplo n.º 3
0
 def gamma_rat(x):
     # helper to simplify ratios of gammas
     was = x.count(gamma)
     xx = x.replace(gamma, lambda n: _rf(1, (n - 1).expand()
         ).replace(_rf, lambda a, b: gamma(a + b)/gamma(a)))
     if xx.count(gamma) < was:
         x = xx
     return x
Ejemplo n.º 4
0
 def gamma_rat(x):
     # helper to simplify ratios of gammas
     was = x.count(gamma)
     xx = x.replace(gamma, lambda n: _rf(1, (n - 1).expand()
         ).replace(_rf, lambda a, b: gamma(a + b)/gamma(a)))
     if xx.count(gamma) < was:
         x = xx
     return x
Ejemplo n.º 5
0
def test_ccode_exceptions():
    assert ccode(gamma(x), standard='C99') == "tgamma(x)"
    gamma_c89 = ccode(gamma(x), standard='C89')
    assert 'not supported in c' in gamma_c89.lower()
    gamma_c89 = ccode(gamma(x), standard='C89', allow_unknown_functions=False)
    assert 'not supported in c' in gamma_c89.lower()
    gamma_c89 = ccode(gamma(x), standard='C89', allow_unknown_functions=True)
    assert 'not supported in c' not in gamma_c89.lower()
Ejemplo n.º 6
0
def test_ccode_exceptions():
    assert ccode(gamma(x), standard='C99') == "tgamma(x)"
    assert 'not supported in c' in ccode(gamma(x), standard='C89').lower()
    assert ccode(ceiling(x)) == "ceil(x)"
    assert ccode(Abs(x)) == "fabs(x)"
    assert ccode(gamma(x)) == "tgamma(x)"
    r, s = symbols('r,s', real=True)
    assert ccode(Mod(ceiling(r), ceiling(s))) == "((ceil(r)) % (ceil(s)))"
    assert ccode(Mod(r, s)) == "fmod(r, s)"
Ejemplo n.º 7
0
def test_ccode_exceptions():
    assert ccode(gamma(x), standard='C99') == "tgamma(x)"
    gamma_c89 = ccode(gamma(x), standard='C89')
    assert 'not supported in c' in gamma_c89.lower()
    gamma_c89 = ccode(gamma(x), standard='C89', allow_unknown_functions=False)
    assert 'not supported in c' in gamma_c89.lower()
    gamma_c89 = ccode(gamma(x), standard='C89', allow_unknown_functions=True)
    assert not 'not supported in c' in gamma_c89.lower()
    assert ccode(ceiling(x)) == "ceil(x)"
    assert ccode(Abs(x)) == "fabs(x)"
    assert ccode(gamma(x)) == "tgamma(x)"
    r, s = symbols('r,s', real=True)
    assert ccode(Mod(ceiling(r), ceiling(s))) == "((ceil(r)) % (ceil(s)))"
    assert ccode(Mod(r, s)) == "fmod(r, s)"
Ejemplo n.º 8
0
def test_ccode_exceptions():
    assert ccode(gamma(x), standard='C99') == "tgamma(x)"
    gamma_c89 = ccode(gamma(x), standard='C89')
    assert 'not supported in c' in gamma_c89.lower()
    gamma_c89 = ccode(gamma(x), standard='C89', allow_unknown_functions=False)
    assert 'not supported in c' in gamma_c89.lower()
    gamma_c89 = ccode(gamma(x), standard='C89', allow_unknown_functions=True)
    assert not 'not supported in c' in gamma_c89.lower()
    assert ccode(ceiling(x)) == "ceil(x)"
    assert ccode(Abs(x)) == "fabs(x)"
    assert ccode(gamma(x)) == "tgamma(x)"
    r, s = symbols('r,s', real=True)
    assert ccode(Mod(ceiling(r), ceiling(s))) == "((ceil(r)) % (ceil(s)))"
    assert ccode(Mod(r, s)) == "fmod(r, s)"
Ejemplo n.º 9
0
def test_Function():
    assert mcode(f(x, y, z)) == "f[x, y, z]"
    assert mcode(sin(x)**cos(x)) == "Sin[x]^Cos[x]"
    assert mcode(conjugate(x)) == "Conjugate[x]"
    assert mcode(Max(x, y, z) * Min(y, z)) == "Max[x, y, z]*Min[y, z]"
    assert mcode(fresnelc(x)) == "FresnelC[x]"
    assert mcode(fresnels(x)) == "FresnelS[x]"
    assert mcode(gamma(x)) == "Gamma[x]"
    assert mcode(uppergamma(x, y)) == "Gamma[x, y]"
    assert mcode(polygamma(x, y)) == "PolyGamma[x, y]"
    assert mcode(loggamma(x)) == "LogGamma[x]"
    assert mcode(erf(x)) == "Erf[x]"
    assert mcode(erfc(x)) == "Erfc[x]"
    assert mcode(erfi(x)) == "Erfi[x]"
    assert mcode(erf2(x, y)) == "Erf[x, y]"
    assert mcode(expint(x, y)) == "ExpIntegralE[x, y]"
    assert mcode(erfcinv(x)) == "InverseErfc[x]"
    assert mcode(erfinv(x)) == "InverseErf[x]"
    assert mcode(erf2inv(x, y)) == "InverseErf[x, y]"
    assert mcode(Ei(x)) == "ExpIntegralEi[x]"
    assert mcode(Ci(x)) == "CosIntegral[x]"
    assert mcode(li(x)) == "LogIntegral[x]"
    assert mcode(Si(x)) == "SinIntegral[x]"
    assert mcode(Shi(x)) == "SinhIntegral[x]"
    assert mcode(Chi(x)) == "CoshIntegral[x]"
    assert mcode(beta(x, y)) == "Beta[x, y]"
    assert mcode(factorial(x)) == "Factorial[x]"
    assert mcode(factorial2(x)) == "Factorial2[x]"
    assert mcode(subfactorial(x)) == "Subfactorial[x]"
    assert mcode(FallingFactorial(x, y)) == "FactorialPower[x, y]"
    assert mcode(RisingFactorial(x, y)) == "Pochhammer[x, y]"
    assert mcode(catalan(x)) == "CatalanNumber[x]"
    assert mcode(harmonic(x)) == "HarmonicNumber[x]"
    assert mcode(harmonic(x, y)) == "HarmonicNumber[x, y]"
Ejemplo n.º 10
0
def test_C99CodePrinter__precision():
    n = symbols('n', integer=True)
    f32_printer = C99CodePrinter(dict(type_aliases={real: float32}))
    f64_printer = C99CodePrinter(dict(type_aliases={real: float64}))
    f80_printer = C99CodePrinter(dict(type_aliases={real: float80}))
    assert f32_printer.doprint(sin(x+2.1)) == 'sinf(x + 2.1F)'
    assert f64_printer.doprint(sin(x+2.1)) == 'sin(x + 2.1000000000000001)'
    assert f80_printer.doprint(sin(x+Float('2.0'))) == 'sinl(x + 2.0L)'

    for printer, suffix in zip([f32_printer, f64_printer, f80_printer], ['f', '', 'l']):
        def check(expr, ref):
            assert printer.doprint(expr) == ref.format(s=suffix, S=suffix.upper())
        check(Abs(n), 'abs(n)')
        check(Abs(x + 2.0), 'fabs{s}(x + 2.0{S})')
        check(sin(x + 4.0)**cos(x - 2.0), 'pow{s}(sin{s}(x + 4.0{S}), cos{s}(x - 2.0{S}))')
        check(exp(x*8.0), 'exp{s}(8.0{S}*x)')
        check(exp2(x), 'exp2{s}(x)')
        check(expm1(x*4.0), 'expm1{s}(4.0{S}*x)')
        check(Mod(n, 2), '((n) % (2))')
        check(Mod(2*n + 3, 3*n + 5), '((2*n + 3) % (3*n + 5))')
        check(Mod(x + 2.0, 3.0), 'fmod{s}(1.0{S}*x + 2.0{S}, 3.0{S})')
        check(Mod(x, 2.0*x + 3.0), 'fmod{s}(1.0{S}*x, 2.0{S}*x + 3.0{S})')
        check(log(x/2), 'log{s}((1.0{S}/2.0{S})*x)')
        check(log10(3*x/2), 'log10{s}((3.0{S}/2.0{S})*x)')
        check(log2(x*8.0), 'log2{s}(8.0{S}*x)')
        check(log1p(x), 'log1p{s}(x)')
        check(2**x, 'pow{s}(2, x)')
        check(2.0**x, 'pow{s}(2.0{S}, x)')
        check(x**3, 'pow{s}(x, 3)')
        check(x**4.0, 'pow{s}(x, 4.0{S})')
        check(sqrt(3+x), 'sqrt{s}(x + 3)')
        check(Cbrt(x-2.0), 'cbrt{s}(x - 2.0{S})')
        check(hypot(x, y), 'hypot{s}(x, y)')
        check(sin(3.*x + 2.), 'sin{s}(3.0{S}*x + 2.0{S})')
        check(cos(3.*x - 1.), 'cos{s}(3.0{S}*x - 1.0{S})')
        check(tan(4.*y + 2.), 'tan{s}(4.0{S}*y + 2.0{S})')
        check(asin(3.*x + 2.), 'asin{s}(3.0{S}*x + 2.0{S})')
        check(acos(3.*x + 2.), 'acos{s}(3.0{S}*x + 2.0{S})')
        check(atan(3.*x + 2.), 'atan{s}(3.0{S}*x + 2.0{S})')
        check(atan2(3.*x, 2.*y), 'atan2{s}(3.0{S}*x, 2.0{S}*y)')

        check(sinh(3.*x + 2.), 'sinh{s}(3.0{S}*x + 2.0{S})')
        check(cosh(3.*x - 1.), 'cosh{s}(3.0{S}*x - 1.0{S})')
        check(tanh(4.0*y + 2.), 'tanh{s}(4.0{S}*y + 2.0{S})')
        check(asinh(3.*x + 2.), 'asinh{s}(3.0{S}*x + 2.0{S})')
        check(acosh(3.*x + 2.), 'acosh{s}(3.0{S}*x + 2.0{S})')
        check(atanh(3.*x + 2.), 'atanh{s}(3.0{S}*x + 2.0{S})')
        check(erf(42.*x), 'erf{s}(42.0{S}*x)')
        check(erfc(42.*x), 'erfc{s}(42.0{S}*x)')
        check(gamma(x), 'tgamma{s}(x)')
        check(loggamma(x), 'lgamma{s}(x)')

        check(ceiling(x + 2.), "ceil{s}(x + 2.0{S})")
        check(floor(x + 2.), "floor{s}(x + 2.0{S})")
        check(fma(x, y, -z), 'fma{s}(x, y, -z)')
        check(Max(x, 8.0, x**4.0), 'fmax{s}(8.0{S}, fmax{s}(x, pow{s}(x, 4.0{S})))')
        check(Min(x, 2.0), 'fmin{s}(2.0{S}, x)')
Ejemplo n.º 11
0
def test_C99CodePrinter__precision():
    n = symbols('n', integer=True)
    f32_printer = C99CodePrinter(dict(type_aliases={real: float32}))
    f64_printer = C99CodePrinter(dict(type_aliases={real: float64}))
    f80_printer = C99CodePrinter(dict(type_aliases={real: float80}))
    assert f32_printer.doprint(sin(x+2.1)) == 'sinf(x + 2.1F)'
    assert f64_printer.doprint(sin(x+2.1)) == 'sin(x + 2.1000000000000001)'
    assert f80_printer.doprint(sin(x+Float('2.0'))) == 'sinl(x + 2.0L)'

    for printer, suffix in zip([f32_printer, f64_printer, f80_printer], ['f', '', 'l']):
        def check(expr, ref):
            assert printer.doprint(expr) == ref.format(s=suffix, S=suffix.upper())
        check(Abs(n), 'abs(n)')
        check(Abs(x + 2.0), 'fabs{s}(x + 2.0{S})')
        check(sin(x + 4.0)**cos(x - 2.0), 'pow{s}(sin{s}(x + 4.0{S}), cos{s}(x - 2.0{S}))')
        check(exp(x*8.0), 'exp{s}(8.0{S}*x)')
        check(exp2(x), 'exp2{s}(x)')
        check(expm1(x*4.0), 'expm1{s}(4.0{S}*x)')
        check(Mod(n, 2), '((n) % (2))')
        check(Mod(2*n + 3, 3*n + 5), '((2*n + 3) % (3*n + 5))')
        check(Mod(x + 2.0, 3.0), 'fmod{s}(1.0{S}*x + 2.0{S}, 3.0{S})')
        check(Mod(x, 2.0*x + 3.0), 'fmod{s}(1.0{S}*x, 2.0{S}*x + 3.0{S})')
        check(log(x/2), 'log{s}((1.0{S}/2.0{S})*x)')
        check(log10(3*x/2), 'log10{s}((3.0{S}/2.0{S})*x)')
        check(log2(x*8.0), 'log2{s}(8.0{S}*x)')
        check(log1p(x), 'log1p{s}(x)')
        check(2**x, 'pow{s}(2, x)')
        check(2.0**x, 'pow{s}(2.0{S}, x)')
        check(x**3, 'pow{s}(x, 3)')
        check(x**4.0, 'pow{s}(x, 4.0{S})')
        check(sqrt(3+x), 'sqrt{s}(x + 3)')
        check(Cbrt(x-2.0), 'cbrt{s}(x - 2.0{S})')
        check(hypot(x, y), 'hypot{s}(x, y)')
        check(sin(3.*x + 2.), 'sin{s}(3.0{S}*x + 2.0{S})')
        check(cos(3.*x - 1.), 'cos{s}(3.0{S}*x - 1.0{S})')
        check(tan(4.*y + 2.), 'tan{s}(4.0{S}*y + 2.0{S})')
        check(asin(3.*x + 2.), 'asin{s}(3.0{S}*x + 2.0{S})')
        check(acos(3.*x + 2.), 'acos{s}(3.0{S}*x + 2.0{S})')
        check(atan(3.*x + 2.), 'atan{s}(3.0{S}*x + 2.0{S})')
        check(atan2(3.*x, 2.*y), 'atan2{s}(3.0{S}*x, 2.0{S}*y)')

        check(sinh(3.*x + 2.), 'sinh{s}(3.0{S}*x + 2.0{S})')
        check(cosh(3.*x - 1.), 'cosh{s}(3.0{S}*x - 1.0{S})')
        check(tanh(4.0*y + 2.), 'tanh{s}(4.0{S}*y + 2.0{S})')
        check(asinh(3.*x + 2.), 'asinh{s}(3.0{S}*x + 2.0{S})')
        check(acosh(3.*x + 2.), 'acosh{s}(3.0{S}*x + 2.0{S})')
        check(atanh(3.*x + 2.), 'atanh{s}(3.0{S}*x + 2.0{S})')
        check(erf(42.*x), 'erf{s}(42.0{S}*x)')
        check(erfc(42.*x), 'erfc{s}(42.0{S}*x)')
        check(gamma(x), 'tgamma{s}(x)')
        check(loggamma(x), 'lgamma{s}(x)')

        check(ceiling(x + 2.), "ceil{s}(x + 2.0{S})")
        check(floor(x + 2.), "floor{s}(x + 2.0{S})")
        check(fma(x, y, -z), 'fma{s}(x, y, -z)')
        check(Max(x, 8.0, x**4.0), 'fmax{s}(8.0{S}, fmax{s}(x, pow{s}(x, 4.0{S})))')
        check(Min(x, 2.0), 'fmin{s}(2.0{S}, x)')
Ejemplo n.º 12
0
def test_catalan():
    assert catalan(1) == 1
    assert catalan(2) == 2
    assert catalan(3) == 5
    assert catalan(4) == 14

    assert catalan(x) == catalan(x)
    assert catalan(2*x).rewrite(binomial) == binomial(4*x, 2*x)/(2*x + 1)
    assert catalan(Rational(1, 2)).rewrite(gamma) == 8/(3*pi)
    assert catalan(3*x).rewrite(gamma) == 4**(
        3*x)*gamma(3*x + Rational(1, 2))/(sqrt(pi)*gamma(3*x + 2))
    assert catalan(x).rewrite(hyper) == hyper((-x + 1, -x), (2,), 1)

    assert diff(catalan(x), x) == (polygamma(
        0, x + Rational(1, 2)) - polygamma(0, x + 2) + log(4))*catalan(x)

    c = catalan(0.5).evalf()
    assert str(c) == '0.848826363156775'
Ejemplo n.º 13
0
def test_catalan():
    assert catalan(1) == 1
    assert catalan(2) == 2
    assert catalan(3) == 5
    assert catalan(4) == 14

    assert catalan(x) == catalan(x)
    assert catalan(2 *
                   x).rewrite(binomial) == binomial(4 * x, 2 * x) / (2 * x + 1)
    assert catalan(Rational(1, 2)).rewrite(gamma) == 8 / (3 * pi)
    assert catalan(3 * x).rewrite(gamma) == 4**(
        3 * x) * gamma(3 * x + Rational(1, 2)) / (sqrt(pi) * gamma(3 * x + 2))
    assert catalan(x).rewrite(hyper) == hyper((-x + 1, -x), (2, ), 1)

    assert diff(catalan(x), x) == (polygamma(0, x + Rational(1, 2)) -
                                   polygamma(0, x + 2) + log(4)) * catalan(x)

    c = catalan(0.5).evalf()
    assert str(c) == '0.848826363156775'
Ejemplo n.º 14
0
def test_catalan():
    n = Symbol("n", integer=True)
    m = Symbol("m", integer=True, positive=True)
    k = Symbol("k", integer=True, nonnegative=True)
    p = Symbol("p", nonnegative=True)

    catalans = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786]
    for i, c in enumerate(catalans):
        assert catalan(i) == c
        assert catalan(n).rewrite(factorial).subs(n, i) == c
        assert catalan(n).rewrite(Product).subs(n, i).doit() == c

    assert unchanged(catalan, x)
    assert catalan(2 *
                   x).rewrite(binomial) == binomial(4 * x, 2 * x) / (2 * x + 1)
    assert catalan(S.Half).rewrite(gamma) == 8 / (3 * pi)
    assert catalan(S.Half).rewrite(factorial).rewrite(gamma) == 8 / (3 * pi)
    assert catalan(3 * x).rewrite(gamma) == 4**(
        3 * x) * gamma(3 * x + S.Half) / (sqrt(pi) * gamma(3 * x + 2))
    assert catalan(x).rewrite(hyper) == hyper((-x + 1, -x), (2, ), 1)

    assert catalan(n).rewrite(factorial) == factorial(
        2 * n) / (factorial(n + 1) * factorial(n))
    assert isinstance(catalan(n).rewrite(Product), catalan)
    assert isinstance(catalan(m).rewrite(Product), Product)

    assert diff(catalan(x), x) == (polygamma(0, x + S.Half) -
                                   polygamma(0, x + 2) + log(4)) * catalan(x)

    assert catalan(x).evalf() == catalan(x)
    c = catalan(S.Half).evalf()
    assert str(c) == "0.848826363156775"
    c = catalan(I).evalf(3)
    assert str((re(c), im(c))) == "(0.398, -0.0209)"

    # Assumptions
    assert catalan(p).is_positive is True
    assert catalan(k).is_integer is True
    assert catalan(m + 3).is_composite is True
Ejemplo n.º 15
0
def test_ccode_functions2():
    assert ccode(ceiling(x)) == "ceil(x)"
    assert ccode(Abs(x)) == "fabs(x)"
    assert ccode(gamma(x)) == "tgamma(x)"
    r, s = symbols('r,s', real=True)
    assert ccode(Mod(ceiling(r), ceiling(s))) == '((ceil(r) % ceil(s)) + '\
                                                 'ceil(s)) % ceil(s)'
    assert ccode(Mod(r, s)) == "fmod(r, s)"
    p1, p2 = symbols('p1 p2', integer=True, positive=True)
    assert ccode(Mod(p1, p2)) == 'p1 % p2'
    assert ccode(Mod(p1, p2 + 3)) == 'p1 % (p2 + 3)'
    assert ccode(Mod(-3, -7, evaluate=False)) == '(-3) % (-7)'
    assert ccode(-Mod(3, 7, evaluate=False)) == '-(3 % 7)'
    assert ccode(r * Mod(p1, p2)) == 'r*(p1 % p2)'
    assert ccode(Mod(p1, p2)**s) == 'pow(p1 % p2, s)'
    n = symbols('n', integer=True, negative=True)
    assert ccode(Mod(-n, p2)) == '(-n) % p2'
Ejemplo n.º 16
0
def test_ccode_functions():
    assert ccode(sin(x) ** cos(x)) == "pow(sin(x), cos(x))"
    assert ccode(ceiling(x)) == "ceil(x)"
    assert ccode(Abs(x)) == "fabs(x)"
    assert ccode(gamma(x)) == "tgamma(x)"
Ejemplo n.º 17
0
def test_C99CodePrinter__precision():
    n = symbols("n", integer=True)
    f32_printer = C99CodePrinter(dict(type_aliases={real: float32}))
    f64_printer = C99CodePrinter(dict(type_aliases={real: float64}))
    f80_printer = C99CodePrinter(dict(type_aliases={real: float80}))
    assert f32_printer.doprint(sin(x + 2.1)) == "sinf(x + 2.1F)"
    assert f64_printer.doprint(sin(x + 2.1)) == "sin(x + 2.1000000000000001)"
    assert f80_printer.doprint(sin(x + Float("2.0"))) == "sinl(x + 2.0L)"

    for printer, suffix in zip([f32_printer, f64_printer, f80_printer], ["f", "", "l"]):

        def check(expr, ref):
            assert printer.doprint(expr) == ref.format(s=suffix, S=suffix.upper())

        check(Abs(n), "abs(n)")
        check(Abs(x + 2.0), "fabs{s}(x + 2.0{S})")
        check(
            sin(x + 4.0) ** cos(x - 2.0),
            "pow{s}(sin{s}(x + 4.0{S}), cos{s}(x - 2.0{S}))",
        )
        check(exp(x * 8.0), "exp{s}(8.0{S}*x)")
        check(exp2(x), "exp2{s}(x)")
        check(expm1(x * 4.0), "expm1{s}(4.0{S}*x)")
        check(Mod(n, 2), "((n) % (2))")
        check(Mod(2 * n + 3, 3 * n + 5), "((2*n + 3) % (3*n + 5))")
        check(Mod(x + 2.0, 3.0), "fmod{s}(1.0{S}*x + 2.0{S}, 3.0{S})")
        check(Mod(x, 2.0 * x + 3.0), "fmod{s}(1.0{S}*x, 2.0{S}*x + 3.0{S})")
        check(log(x / 2), "log{s}((1.0{S}/2.0{S})*x)")
        check(log10(3 * x / 2), "log10{s}((3.0{S}/2.0{S})*x)")
        check(log2(x * 8.0), "log2{s}(8.0{S}*x)")
        check(log1p(x), "log1p{s}(x)")
        check(2 ** x, "pow{s}(2, x)")
        check(2.0 ** x, "pow{s}(2.0{S}, x)")
        check(x ** 3, "pow{s}(x, 3)")
        check(x ** 4.0, "pow{s}(x, 4.0{S})")
        check(sqrt(3 + x), "sqrt{s}(x + 3)")
        check(Cbrt(x - 2.0), "cbrt{s}(x - 2.0{S})")
        check(hypot(x, y), "hypot{s}(x, y)")
        check(sin(3.0 * x + 2.0), "sin{s}(3.0{S}*x + 2.0{S})")
        check(cos(3.0 * x - 1.0), "cos{s}(3.0{S}*x - 1.0{S})")
        check(tan(4.0 * y + 2.0), "tan{s}(4.0{S}*y + 2.0{S})")
        check(asin(3.0 * x + 2.0), "asin{s}(3.0{S}*x + 2.0{S})")
        check(acos(3.0 * x + 2.0), "acos{s}(3.0{S}*x + 2.0{S})")
        check(atan(3.0 * x + 2.0), "atan{s}(3.0{S}*x + 2.0{S})")
        check(atan2(3.0 * x, 2.0 * y), "atan2{s}(3.0{S}*x, 2.0{S}*y)")

        check(sinh(3.0 * x + 2.0), "sinh{s}(3.0{S}*x + 2.0{S})")
        check(cosh(3.0 * x - 1.0), "cosh{s}(3.0{S}*x - 1.0{S})")
        check(tanh(4.0 * y + 2.0), "tanh{s}(4.0{S}*y + 2.0{S})")
        check(asinh(3.0 * x + 2.0), "asinh{s}(3.0{S}*x + 2.0{S})")
        check(acosh(3.0 * x + 2.0), "acosh{s}(3.0{S}*x + 2.0{S})")
        check(atanh(3.0 * x + 2.0), "atanh{s}(3.0{S}*x + 2.0{S})")
        check(erf(42.0 * x), "erf{s}(42.0{S}*x)")
        check(erfc(42.0 * x), "erfc{s}(42.0{S}*x)")
        check(gamma(x), "tgamma{s}(x)")
        check(loggamma(x), "lgamma{s}(x)")

        check(ceiling(x + 2.0), "ceil{s}(x + 2.0{S})")
        check(floor(x + 2.0), "floor{s}(x + 2.0{S})")
        check(fma(x, y, -z), "fma{s}(x, y, -z)")
        check(Max(x, 8.0, x ** 4.0), "fmax{s}(8.0{S}, fmax{s}(x, pow{s}(x, 4.0{S})))")
        check(Min(x, 2.0), "fmin{s}(2.0{S}, x)")
Ejemplo n.º 18
0
def test_rcode_exceptions():
    assert rcode(ceiling(x)) == "ceiling(x)"
    assert rcode(Abs(x)) == "abs(x)"
    assert rcode(gamma(x)) == "gamma(x)"
Ejemplo n.º 19
0
def _gammasimp(expr, as_comb):
    """
    Helper function for gammasimp and combsimp.

    Explanation
    ===========

    Simplifies expressions written in terms of gamma function. If
    as_comb is True, it tries to preserve integer arguments. See
    docstring of gammasimp for more information. This was part of
    combsimp() in combsimp.py.
    """
    expr = expr.replace(gamma, lambda n: _rf(1, (n - 1).expand()))

    if as_comb:
        expr = expr.replace(_rf, lambda a, b: gamma(b + 1))
    else:
        expr = expr.replace(_rf, lambda a, b: gamma(a + b) / gamma(a))

    def rule_gamma(expr, level=0):
        """ Simplify products of gamma functions further. """

        if expr.is_Atom:
            return expr

        def gamma_rat(x):
            # helper to simplify ratios of gammas
            was = x.count(gamma)
            xx = x.replace(
                gamma, lambda n: _rf(1, (n - 1).expand()).replace(
                    _rf, lambda a, b: gamma(a + b) / gamma(a)))
            if xx.count(gamma) < was:
                x = xx
            return x

        def gamma_factor(x):
            # return True if there is a gamma factor in shallow args
            if isinstance(x, gamma):
                return True
            if x.is_Add or x.is_Mul:
                return any(gamma_factor(xi) for xi in x.args)
            if x.is_Pow and (x.exp.is_integer or x.base.is_positive):
                return gamma_factor(x.base)
            return False

        # recursion step
        if level == 0:
            expr = expr.func(*[rule_gamma(x, level + 1) for x in expr.args])
            level += 1

        if not expr.is_Mul:
            return expr

        # non-commutative step
        if level == 1:
            args, nc = expr.args_cnc()
            if not args:
                return expr
            if nc:
                return rule_gamma(Mul._from_args(args),
                                  level + 1) * Mul._from_args(nc)
            level += 1

        # pure gamma handling, not factor absorption
        if level == 2:
            T, F = sift(expr.args, gamma_factor, binary=True)
            gamma_ind = Mul(*F)
            d = Mul(*T)

            nd, dd = d.as_numer_denom()
            for ipass in range(2):
                args = list(ordered(Mul.make_args(nd)))
                for i, ni in enumerate(args):
                    if ni.is_Add:
                        ni, dd = Add(*[
                            rule_gamma(gamma_rat(a / dd), level + 1)
                            for a in ni.args
                        ]).as_numer_denom()
                        args[i] = ni
                        if not dd.has(gamma):
                            break
                nd = Mul(*args)
                if ipass == 0 and not gamma_factor(nd):
                    break
                nd, dd = dd, nd  # now process in reversed order
            expr = gamma_ind * nd / dd
            if not (expr.is_Mul and (gamma_factor(dd) or gamma_factor(nd))):
                return expr
            level += 1

        # iteration until constant
        if level == 3:
            while True:
                was = expr
                expr = rule_gamma(expr, 4)
                if expr == was:
                    return expr

        numer_gammas = []
        denom_gammas = []
        numer_others = []
        denom_others = []

        def explicate(p):
            if p is S.One:
                return None, []
            b, e = p.as_base_exp()
            if e.is_Integer:
                if isinstance(b, gamma):
                    return True, [b.args[0]] * e
                else:
                    return False, [b] * e
            else:
                return False, [p]

        newargs = list(ordered(expr.args))
        while newargs:
            n, d = newargs.pop().as_numer_denom()
            isg, l = explicate(n)
            if isg:
                numer_gammas.extend(l)
            elif isg is False:
                numer_others.extend(l)
            isg, l = explicate(d)
            if isg:
                denom_gammas.extend(l)
            elif isg is False:
                denom_others.extend(l)

        # =========== level 2 work: pure gamma manipulation =========

        if not as_comb:
            # Try to reduce the number of gamma factors by applying the
            # reflection formula gamma(x)*gamma(1-x) = pi/sin(pi*x)
            for gammas, numer, denom in [
                (numer_gammas, numer_others, denom_others),
                (denom_gammas, denom_others, numer_others)
            ]:
                new = []
                while gammas:
                    g1 = gammas.pop()
                    if g1.is_integer:
                        new.append(g1)
                        continue
                    for i, g2 in enumerate(gammas):
                        n = g1 + g2 - 1
                        if not n.is_Integer:
                            continue
                        numer.append(S.Pi)
                        denom.append(sin(S.Pi * g1))
                        gammas.pop(i)
                        if n > 0:
                            for k in range(n):
                                numer.append(1 - g1 + k)
                        elif n < 0:
                            for k in range(-n):
                                denom.append(-g1 - k)
                        break
                    else:
                        new.append(g1)
                # /!\ updating IN PLACE
                gammas[:] = new

            # Try to reduce the number of gammas by using the duplication
            # theorem to cancel an upper and lower: gamma(2*s)/gamma(s) =
            # 2**(2*s + 1)/(4*sqrt(pi))*gamma(s + 1/2). Although this could
            # be done with higher argument ratios like gamma(3*x)/gamma(x),
            # this would not reduce the number of gammas as in this case.
            for ng, dg, no, do in [
                (numer_gammas, denom_gammas, numer_others, denom_others),
                (denom_gammas, numer_gammas, denom_others, numer_others)
            ]:

                while True:
                    for x in ng:
                        for y in dg:
                            n = x - 2 * y
                            if n.is_Integer:
                                break
                        else:
                            continue
                        break
                    else:
                        break
                    ng.remove(x)
                    dg.remove(y)
                    if n > 0:
                        for k in range(n):
                            no.append(2 * y + k)
                    elif n < 0:
                        for k in range(-n):
                            do.append(2 * y - 1 - k)
                    ng.append(y + S.Half)
                    no.append(2**(2 * y - 1))
                    do.append(sqrt(S.Pi))

            # Try to reduce the number of gamma factors by applying the
            # multiplication theorem (used when n gammas with args differing
            # by 1/n mod 1 are encountered).
            #
            # run of 2 with args differing by 1/2
            #
            # >>> gammasimp(gamma(x)*gamma(x+S.Half))
            # 2*sqrt(2)*2**(-2*x - 1/2)*sqrt(pi)*gamma(2*x)
            #
            # run of 3 args differing by 1/3 (mod 1)
            #
            # >>> gammasimp(gamma(x)*gamma(x+S(1)/3)*gamma(x+S(2)/3))
            # 6*3**(-3*x - 1/2)*pi*gamma(3*x)
            # >>> gammasimp(gamma(x)*gamma(x+S(1)/3)*gamma(x+S(5)/3))
            # 2*3**(-3*x - 1/2)*pi*(3*x + 2)*gamma(3*x)
            #
            def _run(coeffs):
                # find runs in coeffs such that the difference in terms (mod 1)
                # of t1, t2, ..., tn is 1/n
                u = list(uniq(coeffs))
                for i in range(len(u)):
                    dj = ([((u[j] - u[i]) % 1, j)
                           for j in range(i + 1, len(u))])
                    for one, j in dj:
                        if one.p == 1 and one.q != 1:
                            n = one.q
                            got = [i]
                            get = list(range(1, n))
                            for d, j in dj:
                                m = n * d
                                if m.is_Integer and m in get:
                                    get.remove(m)
                                    got.append(j)
                                    if not get:
                                        break
                            else:
                                continue
                            for i, j in enumerate(got):
                                c = u[j]
                                coeffs.remove(c)
                                got[i] = c
                            return one.q, got[0], got[1:]

            def _mult_thm(gammas, numer, denom):
                # pull off and analyze the leading coefficient from each gamma arg
                # looking for runs in those Rationals

                # expr -> coeff + resid -> rats[resid] = coeff
                rats = {}
                for g in gammas:
                    c, resid = g.as_coeff_Add()
                    rats.setdefault(resid, []).append(c)

                # look for runs in Rationals for each resid
                keys = sorted(rats, key=default_sort_key)
                for resid in keys:
                    coeffs = list(sorted(rats[resid]))
                    new = []
                    while True:
                        run = _run(coeffs)
                        if run is None:
                            break

                        # process the sequence that was found:
                        # 1) convert all the gamma functions to have the right
                        #    argument (could be off by an integer)
                        # 2) append the factors corresponding to the theorem
                        # 3) append the new gamma function

                        n, ui, other = run

                        # (1)
                        for u in other:
                            con = resid + u - 1
                            for k in range(int(u - ui)):
                                numer.append(con - k)

                        con = n * (resid + ui)  # for (2) and (3)

                        # (2)
                        numer.append(
                            (2 * S.Pi)**(S(n - 1) / 2) * n**(S.Half - con))
                        # (3)
                        new.append(con)

                    # restore resid to coeffs
                    rats[resid] = [resid + c for c in coeffs] + new

                # rebuild the gamma arguments
                g = []
                for resid in keys:
                    g += rats[resid]
                # /!\ updating IN PLACE
                gammas[:] = g

            for l, numer, denom in [(numer_gammas, numer_others, denom_others),
                                    (denom_gammas, denom_others, numer_others)
                                    ]:
                _mult_thm(l, numer, denom)

        # =========== level >= 2 work: factor absorption =========

        if level >= 2:
            # Try to absorb factors into the gammas: x*gamma(x) -> gamma(x + 1)
            # and gamma(x)/(x - 1) -> gamma(x - 1)
            # This code (in particular repeated calls to find_fuzzy) can be very
            # slow.
            def find_fuzzy(l, x):
                if not l:
                    return
                S1, T1 = compute_ST(x)
                for y in l:
                    S2, T2 = inv[y]
                    if T1 != T2 or (not S1.intersection(S2) and
                                    (S1 != set() or S2 != set())):
                        continue
                    # XXX we want some simplification (e.g. cancel or
                    # simplify) but no matter what it's slow.
                    a = len(cancel(x / y).free_symbols)
                    b = len(x.free_symbols)
                    c = len(y.free_symbols)
                    # TODO is there a better heuristic?
                    if a == 0 and (b > 0 or c > 0):
                        return y

            # We thus try to avoid expensive calls by building the following
            # "invariants": For every factor or gamma function argument
            #   - the set of free symbols S
            #   - the set of functional components T
            # We will only try to absorb if T1==T2 and (S1 intersect S2 != emptyset
            # or S1 == S2 == emptyset)
            inv = {}

            def compute_ST(expr):
                if expr in inv:
                    return inv[expr]
                return (expr.free_symbols, expr.atoms(Function).union(
                    {e.exp
                     for e in expr.atoms(Pow)}))

            def update_ST(expr):
                inv[expr] = compute_ST(expr)

            for expr in numer_gammas + denom_gammas + numer_others + denom_others:
                update_ST(expr)

            for gammas, numer, denom in [
                (numer_gammas, numer_others, denom_others),
                (denom_gammas, denom_others, numer_others)
            ]:
                new = []
                while gammas:
                    g = gammas.pop()
                    cont = True
                    while cont:
                        cont = False
                        y = find_fuzzy(numer, g)
                        if y is not None:
                            numer.remove(y)
                            if y != g:
                                numer.append(y / g)
                                update_ST(y / g)
                            g += 1
                            cont = True
                        y = find_fuzzy(denom, g - 1)
                        if y is not None:
                            denom.remove(y)
                            if y != g - 1:
                                numer.append((g - 1) / y)
                                update_ST((g - 1) / y)
                            g -= 1
                            cont = True
                    new.append(g)
                # /!\ updating IN PLACE
                gammas[:] = new

        # =========== rebuild expr ==================================

        return Mul(*[gamma(g) for g in numer_gammas]) \
            / Mul(*[gamma(g) for g in denom_gammas]) \
            * Mul(*numer_others) / Mul(*denom_others)

    was = factor(expr)
    # (for some reason we cannot use Basic.replace in this case)
    expr = rule_gamma(was)
    if expr != was:
        expr = factor(expr)

    expr = expr.replace(
        gamma, lambda n: expand_func(gamma(n)) if n.is_Rational else gamma(n))

    return expr
Ejemplo n.º 20
0
def test_ccode_exceptions():
    assert ccode(ceiling(x)) == "ceil(x)"
    assert ccode(Abs(x)) == "fabs(x)"
    assert ccode(gamma(x)) == "tgamma(x)"
Ejemplo n.º 21
0
def test_rcode_functions():
    assert rcode(sin(x)**cos(x)) == "sin(x)^cos(x)"
    assert rcode(factorial(x) + gamma(y)) == "factorial(x) + gamma(y)"
    assert rcode(beta(Min(x, y), Max(x, y))) == "beta(min(x, y), max(x, y))"
Ejemplo n.º 22
0
def combsimp(expr):
    r"""
    Simplify combinatorial expressions.

    This function takes as input an expression containing factorials,
    binomials, Pochhammer symbol and other "combinatorial" functions,
    and tries to minimize the number of those functions and reduce
    the size of their arguments. The result is be given in terms of
    binomials and factorials.

    The algorithm works by rewriting all combinatorial functions as
    expressions involving rising factorials (Pochhammer symbols) and
    applies recurrence relations and other transformations applicable
    to rising factorials, to reduce their arguments, possibly letting
    the resulting rising factorial to cancel. Rising factorials with
    the second argument being an integer are expanded into polynomial
    forms and finally all other rising factorial are rewritten in terms
    more familiar functions. If the initial expression contained any
    combinatorial functions, the result is expressed using binomial
    coefficients and gamma functions. If the initial expression consisted
    of gamma functions alone, the result is expressed in terms of gamma
    functions.

    If the result is expressed using gamma functions, the following three
    additional steps are performed:

    1. Reduce the number of gammas by applying the reflection theorem
       gamma(x)*gamma(1-x) == pi/sin(pi*x).
    2. Reduce the number of gammas by applying the multiplication theorem
       gamma(x)*gamma(x+1/n)*...*gamma(x+(n-1)/n) == C*gamma(n*x).
    3. Reduce the number of prefactors by absorbing them into gammas, where
       possible.

    All transformation rules can be found (or was derived from) here:

    1. http://functions.wolfram.com/GammaBetaErf/Pochhammer/17/01/02/
    2. http://functions.wolfram.com/GammaBetaErf/Pochhammer/27/01/0005/

    Examples
    ========

    >>> from sympy.simplify import combsimp
    >>> from sympy import factorial, binomial
    >>> from sympy.abc import n, k

    >>> combsimp(factorial(n)/factorial(n - 3))
    n*(n - 2)*(n - 1)
    >>> combsimp(binomial(n+1, k+1)/binomial(n, k))
    (n + 1)/(k + 1)

    """

    # as a rule of thumb, if the expression contained gammas initially, it
    # probably makes sense to retain them
    as_gamma = not expr.has(factorial, binomial)

    expr = expr.replace(
        binomial, lambda n, k: _rf(
            (n - k + 1).expand(), k.expand()) / _rf(1, k.expand()))
    expr = expr.replace(factorial, lambda n: _rf(1, n.expand()))
    expr = expr.rewrite(gamma)
    expr = expr.replace(gamma, lambda n: _rf(1, (n - 1).expand()))

    if as_gamma:
        expr = expr.replace(_rf, lambda a, b: gamma(a + b) / gamma(a))
    else:
        expr = expr.replace(_rf,
                            lambda a, b: binomial(a + b - 1, b) * factorial(b))

    def rule(n, k):
        coeff, rewrite = S.One, False

        cn, _n = n.as_coeff_Add()

        if _n and cn.is_Integer and cn:
            coeff *= _rf(_n + 1, cn) / _rf(_n - k + 1, cn)
            rewrite = True
            n = _n

        # this sort of binomial has already been removed by
        # rising factorials but is left here in case the order
        # of rule application is changed
        if k.is_Add:
            ck, _k = k.as_coeff_Add()
            if _k and ck.is_Integer and ck:
                coeff *= _rf(n - ck - _k + 1, ck) / _rf(_k + 1, ck)
                rewrite = True
                k = _k

        if rewrite:
            return coeff * binomial(n, k)

    expr = expr.replace(binomial, rule)

    def rule_gamma(expr, level=0):
        """ Simplify products of gamma functions further. """

        if expr.is_Atom:
            return expr

        def gamma_rat(x):
            # helper to simplify ratios of gammas
            was = x.count(gamma)
            xx = x.replace(
                gamma, lambda n: _rf(1, (n - 1).expand()).replace(
                    _rf, lambda a, b: gamma(a + b) / gamma(a)))
            if xx.count(gamma) < was:
                x = xx
            return x

        def gamma_factor(x):
            # return True if there is a gamma factor in shallow args
            if x.func is gamma:
                return True
            if x.is_Add or x.is_Mul:
                return any(gamma_factor(xi) for xi in x.args)
            if x.is_Pow and (x.exp.is_integer or x.base.is_positive):
                return gamma_factor(x.base)
            return False

        # recursion step
        if level == 0:
            expr = expr.func(*[rule_gamma(x, level + 1) for x in expr.args])
            level += 1

        if not expr.is_Mul:
            return expr

        # non-commutative step
        if level == 1:
            args, nc = expr.args_cnc()
            if not args:
                return expr
            if nc:
                return rule_gamma(Mul._from_args(args),
                                  level + 1) * Mul._from_args(nc)
            level += 1

        # pure gamma handling, not factor absorbtion
        if level == 2:
            sifted = sift(expr.args, gamma_factor)
            gamma_ind = Mul(*sifted.pop(False, []))
            d = Mul(*sifted.pop(True, []))
            assert not sifted

            nd, dd = d.as_numer_denom()
            for ipass in range(2):
                args = list(ordered(Mul.make_args(nd)))
                for i, ni in enumerate(args):
                    if ni.is_Add:
                        ni, dd = Add(*[
                            rule_gamma(gamma_rat(a / dd), level + 1)
                            for a in ni.args
                        ]).as_numer_denom()
                        args[i] = ni
                        if not dd.has(gamma):
                            break
                nd = Mul(*args)
                if ipass == 0 and not gamma_factor(nd):
                    break
                nd, dd = dd, nd  # now process in reversed order
            expr = gamma_ind * nd / dd
            if not (expr.is_Mul and (gamma_factor(dd) or gamma_factor(nd))):
                return expr
            level += 1

        # iteration until constant
        if level == 3:
            while True:
                was = expr
                expr = rule_gamma(expr, 4)
                if expr == was:
                    return expr

        numer_gammas = []
        denom_gammas = []
        numer_others = []
        denom_others = []

        def explicate(p):
            if p is S.One:
                return None, []
            b, e = p.as_base_exp()
            if e.is_Integer:
                if b.func is gamma:
                    return True, [b.args[0]] * e
                else:
                    return False, [b] * e
            else:
                return False, [p]

        newargs = list(ordered(expr.args))
        while newargs:
            n, d = newargs.pop().as_numer_denom()
            isg, l = explicate(n)
            if isg:
                numer_gammas.extend(l)
            elif isg is False:
                numer_others.extend(l)
            isg, l = explicate(d)
            if isg:
                denom_gammas.extend(l)
            elif isg is False:
                denom_others.extend(l)

        # =========== level 2 work: pure gamma manipulation =========

        # Try to reduce the number of gamma factors by applying the
        # reflection formula gamma(x)*gamma(1-x) = pi/sin(pi*x)
        for gammas, numer, denom in [
            (numer_gammas, numer_others, denom_others),
            (denom_gammas, denom_others, numer_others)
        ]:
            new = []
            while gammas:
                g1 = gammas.pop()
                if g1.is_integer:
                    new.append(g1)
                    continue
                for i, g2 in enumerate(gammas):
                    n = g1 + g2 - 1
                    if not n.is_Integer:
                        continue
                    numer.append(S.Pi)
                    denom.append(sin(S.Pi * g1))
                    gammas.pop(i)
                    if n > 0:
                        for k in range(n):
                            numer.append(1 - g1 + k)
                    elif n < 0:
                        for k in range(-n):
                            denom.append(-g1 - k)
                    break
                else:
                    new.append(g1)
            # /!\ updating IN PLACE
            gammas[:] = new

        # Try to reduce the number of gammas by using the duplication
        # theorem to cancel an upper and lower: gamma(2*s)/gamma(s) =
        # 2**(2*s + 1)/(4*sqrt(pi))*gamma(s + 1/2). Although this could
        # be done with higher argument ratios like gamma(3*x)/gamma(x),
        # this would not reduce the number of gammas as in this case.
        for ng, dg, no, do in [
            (numer_gammas, denom_gammas, numer_others, denom_others),
            (denom_gammas, numer_gammas, denom_others, numer_others)
        ]:

            while True:
                for x in ng:
                    for y in dg:
                        n = x - 2 * y
                        if n.is_Integer:
                            break
                    else:
                        continue
                    break
                else:
                    break
                ng.remove(x)
                dg.remove(y)
                if n > 0:
                    for k in range(n):
                        no.append(2 * y + k)
                elif n < 0:
                    for k in range(-n):
                        do.append(2 * y - 1 - k)
                ng.append(y + S(1) / 2)
                no.append(2**(2 * y - 1))
                do.append(sqrt(S.Pi))

        # Try to reduce the number of gamma factors by applying the
        # multiplication theorem (used when n gammas with args differing
        # by 1/n mod 1 are encountered).
        #
        # run of 2 with args differing by 1/2
        #
        # >>> combsimp(gamma(x)*gamma(x+S.Half))
        # 2*sqrt(2)*2**(-2*x - 1/2)*sqrt(pi)*gamma(2*x)
        #
        # run of 3 args differing by 1/3 (mod 1)
        #
        # >>> combsimp(gamma(x)*gamma(x+S(1)/3)*gamma(x+S(2)/3))
        # 6*3**(-3*x - 1/2)*pi*gamma(3*x)
        # >>> combsimp(gamma(x)*gamma(x+S(1)/3)*gamma(x+S(5)/3))
        # 2*3**(-3*x - 1/2)*pi*(3*x + 2)*gamma(3*x)
        #
        def _run(coeffs):
            # find runs in coeffs such that the difference in terms (mod 1)
            # of t1, t2, ..., tn is 1/n
            u = list(uniq(coeffs))
            for i in range(len(u)):
                dj = ([((u[j] - u[i]) % 1, j) for j in range(i + 1, len(u))])
                for one, j in dj:
                    if one.p == 1 and one.q != 1:
                        n = one.q
                        got = [i]
                        get = list(range(1, n))
                        for d, j in dj:
                            m = n * d
                            if m.is_Integer and m in get:
                                get.remove(m)
                                got.append(j)
                                if not get:
                                    break
                        else:
                            continue
                        for i, j in enumerate(got):
                            c = u[j]
                            coeffs.remove(c)
                            got[i] = c
                        return one.q, got[0], got[1:]

        def _mult_thm(gammas, numer, denom):
            # pull off and analyze the leading coefficient from each gamma arg
            # looking for runs in those Rationals

            # expr -> coeff + resid -> rats[resid] = coeff
            rats = {}
            for g in gammas:
                c, resid = g.as_coeff_Add()
                rats.setdefault(resid, []).append(c)

            # look for runs in Rationals for each resid
            keys = sorted(rats, key=default_sort_key)
            for resid in keys:
                coeffs = list(sorted(rats[resid]))
                new = []
                while True:
                    run = _run(coeffs)
                    if run is None:
                        break

                    # process the sequence that was found:
                    # 1) convert all the gamma functions to have the right
                    #    argument (could be off by an integer)
                    # 2) append the factors corresponding to the theorem
                    # 3) append the new gamma function

                    n, ui, other = run

                    # (1)
                    for u in other:
                        con = resid + u - 1
                        for k in range(int(u - ui)):
                            numer.append(con - k)

                    con = n * (resid + ui)  # for (2) and (3)

                    # (2)
                    numer.append(
                        (2 * S.Pi)**(S(n - 1) / 2) * n**(S(1) / 2 - con))
                    # (3)
                    new.append(con)

                # restore resid to coeffs
                rats[resid] = [resid + c for c in coeffs] + new

            # rebuild the gamma arguments
            g = []
            for resid in keys:
                g += rats[resid]
            # /!\ updating IN PLACE
            gammas[:] = g

        for l, numer, denom in [(numer_gammas, numer_others, denom_others),
                                (denom_gammas, denom_others, numer_others)]:
            _mult_thm(l, numer, denom)

        # =========== level >= 2 work: factor absorbtion =========

        if level >= 2:
            # Try to absorb factors into the gammas: x*gamma(x) -> gamma(x + 1)
            # and gamma(x)/(x - 1) -> gamma(x - 1)
            # This code (in particular repeated calls to find_fuzzy) can be very
            # slow.
            def find_fuzzy(l, x):
                if not l:
                    return
                S1, T1 = compute_ST(x)
                for y in l:
                    S2, T2 = inv[y]
                    if T1 != T2 or (not S1.intersection(S2) and
                                    (S1 != set() or S2 != set())):
                        continue
                    # XXX we want some simplification (e.g. cancel or
                    # simplify) but no matter what it's slow.
                    a = len(cancel(x / y).free_symbols)
                    b = len(x.free_symbols)
                    c = len(y.free_symbols)
                    # TODO is there a better heuristic?
                    if a == 0 and (b > 0 or c > 0):
                        return y

            # We thus try to avoid expensive calls by building the following
            # "invariants": For every factor or gamma function argument
            #   - the set of free symbols S
            #   - the set of functional components T
            # We will only try to absorb if T1==T2 and (S1 intersect S2 != emptyset
            # or S1 == S2 == emptyset)
            inv = {}

            def compute_ST(expr):
                if expr in inv:
                    return inv[expr]
                return (expr.free_symbols, expr.atoms(Function).union(
                    set(e.exp for e in expr.atoms(Pow))))

            def update_ST(expr):
                inv[expr] = compute_ST(expr)

            for expr in numer_gammas + denom_gammas + numer_others + denom_others:
                update_ST(expr)

            for gammas, numer, denom in [
                (numer_gammas, numer_others, denom_others),
                (denom_gammas, denom_others, numer_others)
            ]:
                new = []
                while gammas:
                    g = gammas.pop()
                    cont = True
                    while cont:
                        cont = False
                        y = find_fuzzy(numer, g)
                        if y is not None:
                            numer.remove(y)
                            if y != g:
                                numer.append(y / g)
                                update_ST(y / g)
                            g += 1
                            cont = True
                        y = find_fuzzy(denom, g - 1)
                        if y is not None:
                            denom.remove(y)
                            if y != g - 1:
                                numer.append((g - 1) / y)
                                update_ST((g - 1) / y)
                            g -= 1
                            cont = True
                    new.append(g)
                # /!\ updating IN PLACE
                gammas[:] = new

        # =========== rebuild expr ==================================

        return Mul(*[gamma(g) for g in numer_gammas]) \
            / Mul(*[gamma(g) for g in denom_gammas]) \
            * Mul(*numer_others) / Mul(*denom_others)

    # (for some reason we cannot use Basic.replace in this case)
    was = factor(expr)
    expr = rule_gamma(was)
    if expr != was:
        expr = factor(expr)

    return expr
Ejemplo n.º 23
0
def test_ccode_exceptions():
    assert ccode(ceiling(x)) == "ceil(x)"
    assert ccode(Abs(x)) == "fabs(x)"
    assert ccode(gamma(x)) == "tgamma(x)"
Ejemplo n.º 24
0
 def fdiff(self, argindex=1):
     if argindex == 1:
         from sympy.functions import gamma, polygamma
         return gamma(self[0]+1)*polygamma(0,self[0]+1)
     else:
         raise ArgumentIndexError(self, argindex)
Ejemplo n.º 25
0
def test_rcode_functions():
    assert rcode(sin(x) ** cos(x)) == "sin(x)^cos(x)"
    assert rcode(factorial(x) + gamma(y)) == "factorial(x) + gamma(y)"
    assert rcode(beta(Min(x, y), Max(x, y))) == "beta(min(x, y), max(x, y))"
Ejemplo n.º 26
0
def test_functions_special():
    assert oclcode(erf(x)) == "erf(x)"
    assert oclcode(erfc(x)) == "erfc(x)"
    assert oclcode(gamma(x)) == "tgamma(x)"
    assert oclcode(loggamma(x)) == "lgamma(x)"
Ejemplo n.º 27
0
def _gammasimp(expr, as_comb):
    """
    Helper function for gammasimp and combsimp.

    Simplifies expressions written in terms of gamma function. If
    as_comb is True, it tries to preserve integer arguments. See
    docstring of gammasimp for more information. This was part of
    combsimp() in combsimp.py.
    """

    expr = expr.replace(gamma,
        lambda n: _rf(1, (n - 1).expand()))

    if as_comb:
        expr = expr.replace(_rf,
            lambda a, b: gamma(b + 1))
    else:
        expr = expr.replace(_rf,
            lambda a, b: gamma(a + b)/gamma(a))

    def rule(n, k):
        coeff, rewrite = S.One, False

        cn, _n = n.as_coeff_Add()

        if _n and cn.is_Integer and cn:
            coeff *= _rf(_n + 1, cn)/_rf(_n - k + 1, cn)
            rewrite = True
            n = _n

        # this sort of binomial has already been removed by
        # rising factorials but is left here in case the order
        # of rule application is changed
        if k.is_Add:
            ck, _k = k.as_coeff_Add()
            if _k and ck.is_Integer and ck:
                coeff *= _rf(n - ck - _k + 1, ck)/_rf(_k + 1, ck)
                rewrite = True
                k = _k

        if count_ops(k) > count_ops(n - k):
            rewrite = True
            k = n - k

        if rewrite:
            return coeff*binomial(n, k)

    expr = expr.replace(binomial, rule)

    def rule_gamma(expr, level=0):
        """ Simplify products of gamma functions further. """

        if expr.is_Atom:
            return expr

        def gamma_rat(x):
            # helper to simplify ratios of gammas
            was = x.count(gamma)
            xx = x.replace(gamma, lambda n: _rf(1, (n - 1).expand()
                ).replace(_rf, lambda a, b: gamma(a + b)/gamma(a)))
            if xx.count(gamma) < was:
                x = xx
            return x

        def gamma_factor(x):
            # return True if there is a gamma factor in shallow args
            if isinstance(x, gamma):
                return True
            if x.is_Add or x.is_Mul:
                return any(gamma_factor(xi) for xi in x.args)
            if x.is_Pow and (x.exp.is_integer or x.base.is_positive):
                return gamma_factor(x.base)
            return False

        # recursion step
        if level == 0:
            expr = expr.func(*[rule_gamma(x, level + 1) for x in expr.args])
            level += 1

        if not expr.is_Mul:
            return expr

        # non-commutative step
        if level == 1:
            args, nc = expr.args_cnc()
            if not args:
                return expr
            if nc:
                return rule_gamma(Mul._from_args(args), level + 1)*Mul._from_args(nc)
            level += 1

        # pure gamma handling, not factor absorption
        if level == 2:
            T, F = sift(expr.args, gamma_factor, binary=True)
            gamma_ind = Mul(*F)
            d = Mul(*T)

            nd, dd = d.as_numer_denom()
            for ipass in range(2):
                args = list(ordered(Mul.make_args(nd)))
                for i, ni in enumerate(args):
                    if ni.is_Add:
                        ni, dd = Add(*[
                            rule_gamma(gamma_rat(a/dd), level + 1) for a in ni.args]
                            ).as_numer_denom()
                        args[i] = ni
                        if not dd.has(gamma):
                            break
                nd = Mul(*args)
                if ipass ==  0 and not gamma_factor(nd):
                    break
                nd, dd = dd, nd  # now process in reversed order
            expr = gamma_ind*nd/dd
            if not (expr.is_Mul and (gamma_factor(dd) or gamma_factor(nd))):
                return expr
            level += 1

        # iteration until constant
        if level == 3:
            while True:
                was = expr
                expr = rule_gamma(expr, 4)
                if expr == was:
                    return expr

        numer_gammas = []
        denom_gammas = []
        numer_others = []
        denom_others = []
        def explicate(p):
            if p is S.One:
                return None, []
            b, e = p.as_base_exp()
            if e.is_Integer:
                if isinstance(b, gamma):
                    return True, [b.args[0]]*e
                else:
                    return False, [b]*e
            else:
                return False, [p]

        newargs = list(ordered(expr.args))
        while newargs:
            n, d = newargs.pop().as_numer_denom()
            isg, l = explicate(n)
            if isg:
                numer_gammas.extend(l)
            elif isg is False:
                numer_others.extend(l)
            isg, l = explicate(d)
            if isg:
                denom_gammas.extend(l)
            elif isg is False:
                denom_others.extend(l)

        # =========== level 2 work: pure gamma manipulation =========

        if not as_comb:
            # Try to reduce the number of gamma factors by applying the
            # reflection formula gamma(x)*gamma(1-x) = pi/sin(pi*x)
            for gammas, numer, denom in [(
                numer_gammas, numer_others, denom_others),
                    (denom_gammas, denom_others, numer_others)]:
                new = []
                while gammas:
                    g1 = gammas.pop()
                    if g1.is_integer:
                        new.append(g1)
                        continue
                    for i, g2 in enumerate(gammas):
                        n = g1 + g2 - 1
                        if not n.is_Integer:
                            continue
                        numer.append(S.Pi)
                        denom.append(sin(S.Pi*g1))
                        gammas.pop(i)
                        if n > 0:
                            for k in range(n):
                                numer.append(1 - g1 + k)
                        elif n < 0:
                            for k in range(-n):
                                denom.append(-g1 - k)
                        break
                    else:
                        new.append(g1)
                # /!\ updating IN PLACE
                gammas[:] = new

            # Try to reduce the number of gammas by using the duplication
            # theorem to cancel an upper and lower: gamma(2*s)/gamma(s) =
            # 2**(2*s + 1)/(4*sqrt(pi))*gamma(s + 1/2). Although this could
            # be done with higher argument ratios like gamma(3*x)/gamma(x),
            # this would not reduce the number of gammas as in this case.
            for ng, dg, no, do in [(numer_gammas, denom_gammas, numer_others,
                                    denom_others),
                                   (denom_gammas, numer_gammas, denom_others,
                                    numer_others)]:

                while True:
                    for x in ng:
                        for y in dg:
                            n = x - 2*y
                            if n.is_Integer:
                                break
                        else:
                            continue
                        break
                    else:
                        break
                    ng.remove(x)
                    dg.remove(y)
                    if n > 0:
                        for k in range(n):
                            no.append(2*y + k)
                    elif n < 0:
                        for k in range(-n):
                            do.append(2*y - 1 - k)
                    ng.append(y + S(1)/2)
                    no.append(2**(2*y - 1))
                    do.append(sqrt(S.Pi))

            # Try to reduce the number of gamma factors by applying the
            # multiplication theorem (used when n gammas with args differing
            # by 1/n mod 1 are encountered).
            #
            # run of 2 with args differing by 1/2
            #
            # >>> gammasimp(gamma(x)*gamma(x+S.Half))
            # 2*sqrt(2)*2**(-2*x - 1/2)*sqrt(pi)*gamma(2*x)
            #
            # run of 3 args differing by 1/3 (mod 1)
            #
            # >>> gammasimp(gamma(x)*gamma(x+S(1)/3)*gamma(x+S(2)/3))
            # 6*3**(-3*x - 1/2)*pi*gamma(3*x)
            # >>> gammasimp(gamma(x)*gamma(x+S(1)/3)*gamma(x+S(5)/3))
            # 2*3**(-3*x - 1/2)*pi*(3*x + 2)*gamma(3*x)
            #
            def _run(coeffs):
                # find runs in coeffs such that the difference in terms (mod 1)
                # of t1, t2, ..., tn is 1/n
                u = list(uniq(coeffs))
                for i in range(len(u)):
                    dj = ([((u[j] - u[i]) % 1, j) for j in range(i + 1, len(u))])
                    for one, j in dj:
                        if one.p == 1 and one.q != 1:
                            n = one.q
                            got = [i]
                            get = list(range(1, n))
                            for d, j in dj:
                                m = n*d
                                if m.is_Integer and m in get:
                                    get.remove(m)
                                    got.append(j)
                                    if not get:
                                        break
                            else:
                                continue
                            for i, j in enumerate(got):
                                c = u[j]
                                coeffs.remove(c)
                                got[i] = c
                            return one.q, got[0], got[1:]

            def _mult_thm(gammas, numer, denom):
                # pull off and analyze the leading coefficient from each gamma arg
                # looking for runs in those Rationals

                # expr -> coeff + resid -> rats[resid] = coeff
                rats = {}
                for g in gammas:
                    c, resid = g.as_coeff_Add()
                    rats.setdefault(resid, []).append(c)

                # look for runs in Rationals for each resid
                keys = sorted(rats, key=default_sort_key)
                for resid in keys:
                    coeffs = list(sorted(rats[resid]))
                    new = []
                    while True:
                        run = _run(coeffs)
                        if run is None:
                            break

                        # process the sequence that was found:
                        # 1) convert all the gamma functions to have the right
                        #    argument (could be off by an integer)
                        # 2) append the factors corresponding to the theorem
                        # 3) append the new gamma function

                        n, ui, other = run

                        # (1)
                        for u in other:
                            con = resid + u - 1
                            for k in range(int(u - ui)):
                                numer.append(con - k)

                        con = n*(resid + ui)  # for (2) and (3)

                        # (2)
                        numer.append((2*S.Pi)**(S(n - 1)/2)*
                                     n**(S(1)/2 - con))
                        # (3)
                        new.append(con)

                    # restore resid to coeffs
                    rats[resid] = [resid + c for c in coeffs] + new

                # rebuild the gamma arguments
                g = []
                for resid in keys:
                    g += rats[resid]
                # /!\ updating IN PLACE
                gammas[:] = g

            for l, numer, denom in [(numer_gammas, numer_others, denom_others),
                                    (denom_gammas, denom_others, numer_others)]:
                _mult_thm(l, numer, denom)

        # =========== level >= 2 work: factor absorption =========

        if level >= 2:
            # Try to absorb factors into the gammas: x*gamma(x) -> gamma(x + 1)
            # and gamma(x)/(x - 1) -> gamma(x - 1)
            # This code (in particular repeated calls to find_fuzzy) can be very
            # slow.
            def find_fuzzy(l, x):
                if not l:
                    return
                S1, T1 = compute_ST(x)
                for y in l:
                    S2, T2 = inv[y]
                    if T1 != T2 or (not S1.intersection(S2) and
                                    (S1 != set() or S2 != set())):
                        continue
                    # XXX we want some simplification (e.g. cancel or
                    # simplify) but no matter what it's slow.
                    a = len(cancel(x/y).free_symbols)
                    b = len(x.free_symbols)
                    c = len(y.free_symbols)
                    # TODO is there a better heuristic?
                    if a == 0 and (b > 0 or c > 0):
                        return y

            # We thus try to avoid expensive calls by building the following
            # "invariants": For every factor or gamma function argument
            #   - the set of free symbols S
            #   - the set of functional components T
            # We will only try to absorb if T1==T2 and (S1 intersect S2 != emptyset
            # or S1 == S2 == emptyset)
            inv = {}

            def compute_ST(expr):
                if expr in inv:
                    return inv[expr]
                return (expr.free_symbols, expr.atoms(Function).union(
                        set(e.exp for e in expr.atoms(Pow))))

            def update_ST(expr):
                inv[expr] = compute_ST(expr)
            for expr in numer_gammas + denom_gammas + numer_others + denom_others:
                update_ST(expr)

            for gammas, numer, denom in [(
                numer_gammas, numer_others, denom_others),
                    (denom_gammas, denom_others, numer_others)]:
                new = []
                while gammas:
                    g = gammas.pop()
                    cont = True
                    while cont:
                        cont = False
                        y = find_fuzzy(numer, g)
                        if y is not None:
                            numer.remove(y)
                            if y != g:
                                numer.append(y/g)
                                update_ST(y/g)
                            g += 1
                            cont = True
                        y = find_fuzzy(denom, g - 1)
                        if y is not None:
                            denom.remove(y)
                            if y != g - 1:
                                numer.append((g - 1)/y)
                                update_ST((g - 1)/y)
                            g -= 1
                            cont = True
                    new.append(g)
                # /!\ updating IN PLACE
                gammas[:] = new

        # =========== rebuild expr ==================================

        return Mul(*[gamma(g) for g in numer_gammas]) \
            / Mul(*[gamma(g) for g in denom_gammas]) \
            * Mul(*numer_others) / Mul(*denom_others)

    # (for some reason we cannot use Basic.replace in this case)
    was = factor(expr)
    expr = rule_gamma(was)
    if expr != was:
        expr = factor(expr)

    expr = expr.replace(gamma,
        lambda n: expand_func(gamma(n)) if n.is_Rational else gamma(n))

    return expr
Ejemplo n.º 28
0
def test_ccode_functions():
    assert ccode(sin(x)**cos(x)) == "pow(sin(x), cos(x))"
    assert ccode(ceiling(x)) == "ceil(x)"
    assert ccode(Abs(x)) == "fabs(x)"
    assert ccode(gamma(x)) == "tgamma(x)"
Ejemplo n.º 29
0
def test_ccode_exceptions():
    assert ccode(gamma(x), standard='C99') == "tgamma(x)"
    assert 'not supported in c' in ccode(gamma(x), standard='C89').lower()
    assert ccode(ceiling(x)) == "ceil(x)"
    assert ccode(Abs(x)) == "fabs(x)"
    assert ccode(gamma(x)) == "tgamma(x)"
Ejemplo n.º 30
0
def test_ccode_exceptions():
    assert ccode(gamma(x), standard='C99') == "tgamma(x)"
    assert 'not supported in c' in ccode(gamma(x), standard='C89').lower()
    assert ccode(ceiling(x)) == "ceil(x)"
    assert ccode(Abs(x)) == "fabs(x)"
    assert ccode(gamma(x)) == "tgamma(x)"