示例#1
0
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))
    )
示例#2
0
def inv_ε_expan(η_iter, z, h, N):
    ηiη0 = 0
    for q, η in enumerate(η_iter):
        ηiη0 += η * (z * h) ** q / (η_iter[0] * sy.factorial(q))
    εiε0 = sy.series(ηiη0 ** 2, x=h, n=N)
    ε0iε = sy.series(1 / εiε0, x=h, n=N)
    return (-ε0iε / η_iter[0] ** 2).expand().removeO()
示例#3
0
def Problem2():
    t, x = symbols('t x')
    f = exp(t)
    expr = series(f, t, 0, 5)
    expr = expr.removeO()
    print('')
    print('Taylor expansion of f(t) = exp(t) around t=0')
    print(expr)

    func = sin(x)
    N = 100
    for i in range(2, 7):

        expr = series(func, x, 0, i * 2)
        expr = expr.removeO()
        taylorEval = lambdify(x, expr, 'numpy')
        x = np.linspace(0, 2 * np.pi, N)
        plt.plot(x, taylorEval(x))
        x = symbols('x')

    plt.ylim([-2.0, 2.0])
    plt.xlim([0.0, 2 * np.pi])
    x = np.linspace(0, 2 * np.pi, N)
    plt.plot(x, np.sin(x))
    plt.legend([
        'series, N = 4', 'series, N = 6', 'series, N = 8', 'series, N = 10',
        'series, N = 12', 'series, N = 14'
    ])
    plt.show()
示例#4
0
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_sec():
    x = symbols('x', real=True)
    z = symbols('z')

    assert sec.nargs == FiniteSet(1)

    assert sec(0) == 1
    assert sec(pi) == -1
    assert sec(pi / 2) == zoo
    assert sec(-pi / 2) == zoo
    assert sec(pi / 6) == 2 * sqrt(3) / 3
    assert sec(pi / 3) == 2
    assert sec(5 * pi / 2) == zoo
    assert sec(9 * pi / 7) == -sec(2 * pi / 7)
    assert sec(I) == 1 / cosh(1)
    assert sec(x * I) == 1 / cosh(x)
    assert sec(-x) == sec(x)

    assert sec(x).rewrite(exp) == 1 / (exp(I * x) / 2 + exp(-I * x) / 2)
    assert sec(x).rewrite(sin) == sec(x)
    assert sec(x).rewrite(cos) == 1 / cos(x)
    assert sec(x).rewrite(tan) == (tan(x / 2)**2 + 1) / (-tan(x / 2)**2 + 1)
    assert sec(x).rewrite(pow) == sec(x)
    assert sec(x).rewrite(sqrt) == sec(x)

    assert sec(z).conjugate() == sec(conjugate(z))

    assert (sec(z).as_real_imag() == (
        cos(re(z)) * cosh(im(z)) /
        (sin(re(z))**2 * sinh(im(z))**2 + cos(re(z))**2 * cosh(im(z))**2),
        sin(re(z)) * sinh(im(z)) /
        (sin(re(z))**2 * sinh(im(z))**2 + cos(re(z))**2 * cosh(im(z))**2)))

    assert sec(x).expand(trig=True) == 1 / cos(x)
    assert sec(2 * x).expand(trig=True) == 1 / (2 * cos(x)**2 - 1)

    assert sec(x).is_real == True
    assert sec(z).is_real == None

    assert sec(x).as_leading_term() == sec(x)

    assert sec(0).is_bounded == True
    assert sec(x).is_bounded == None
    assert sec(pi / 2).is_bounded == False

    assert series(sec(x), x, x0=0,
                  n=6) == 1 + x**2 / 2 + 5 * x**4 / 24 + O(x**6)

    # https://github.com/sympy/sympy/issues/7166
    assert series(sqrt(sec(x))) == 1 + x**2 / 4 + 7 * x**4 / 96 + O(x**6)

    assert sec(x).diff(x) == tan(x) * sec(x)

    # Taylor Term checks
    assert sec(z).taylor_term(4, z) == 5 * z**4 / 24
    assert sec(z).taylor_term(6, z) == 61 * z**6 / 720
    assert sec(z).taylor_term(5, z) == 0
示例#6
0
def test_csc():
    x = symbols('x', real=True)
    z = symbols('z')

    # https://github.com/sympy/sympy/issues/6707
    cosecant = csc('x')
    alternate = 1/sin('x')
    assert cosecant.equals(alternate) == True
    assert alternate.equals(cosecant) == True

    assert csc.nargs == FiniteSet(1)

    assert csc(0) == zoo
    assert csc(pi) == zoo

    assert csc(pi/2) == 1
    assert csc(-pi/2) == -1
    assert csc(pi/6) == 2
    assert csc(pi/3) == 2*sqrt(3)/3
    assert csc(5*pi/2) == 1
    assert csc(9*pi/7) == -csc(2*pi/7)
    assert csc(I) == -I/sinh(1)
    assert csc(x*I) == -I/sinh(x)
    assert csc(-x) == -csc(x)

    assert csc(x).rewrite(exp) == 2*I/(exp(I*x) - exp(-I*x))
    assert csc(x).rewrite(sin) == 1/sin(x)
    assert csc(x).rewrite(cos) == csc(x)
    assert csc(x).rewrite(tan) == (tan(x/2)**2 + 1)/(2*tan(x/2))

    assert csc(z).conjugate() == csc(conjugate(z))

    assert (csc(z).as_real_imag() ==
            (sin(re(z))*cosh(im(z))/(sin(re(z))**2*cosh(im(z))**2 +
                                     cos(re(z))**2*sinh(im(z))**2),
             -cos(re(z))*sinh(im(z))/(sin(re(z))**2*cosh(im(z))**2 +
                          cos(re(z))**2*sinh(im(z))**2)))

    assert csc(x).expand(trig=True) == 1/sin(x)
    assert csc(2*x).expand(trig=True) == 1/(2*sin(x)*cos(x))

    assert csc(x).is_real == True
    assert csc(z).is_real == None

    assert csc(x).as_leading_term() == csc(x)

    assert csc(0).is_bounded == False
    assert csc(x).is_bounded == None
    assert csc(pi/2).is_bounded == True

    assert series(csc(x), x, x0=pi/2, n=6) == \
        1 + (x - pi/2)**2/2 + 5*(x - pi/2)**4/24 + O((x - pi/2)**6, (x, pi/2))
    assert series(csc(x), x, x0=0, n=6) == \
            1/x + x/6 + 7*x**3/360 + 31*x**5/15120 + O(x**6)

    assert csc(x).diff(x) == -cot(x)*csc(x)
示例#7
0
def test_sec():
    x = symbols('x', real=True)
    z = symbols('z')

    assert sec.nargs == FiniteSet(1)

    assert sec(0) == 1
    assert sec(pi) == -1
    assert sec(pi/2) == zoo
    assert sec(-pi/2) == zoo
    assert sec(pi/6) == 2*sqrt(3)/3
    assert sec(pi/3) == 2
    assert sec(5*pi/2) == zoo
    assert sec(9*pi/7) == -sec(2*pi/7)
    assert sec(I) == 1/cosh(1)
    assert sec(x*I) == 1/cosh(x)
    assert sec(-x) == sec(x)

    assert sec(x).rewrite(exp) == 1/(exp(I*x)/2 + exp(-I*x)/2)
    assert sec(x).rewrite(sin) == sec(x)
    assert sec(x).rewrite(cos) == 1/cos(x)
    assert sec(x).rewrite(tan) == (tan(x/2)**2 + 1)/(-tan(x/2)**2 + 1)
    assert sec(x).rewrite(pow) == sec(x)
    assert sec(x).rewrite(sqrt) == sec(x)

    assert sec(z).conjugate() == sec(conjugate(z))

    assert (sec(z).as_real_imag() ==
    (cos(re(z))*cosh(im(z))/(sin(re(z))**2*sinh(im(z))**2 +
                             cos(re(z))**2*cosh(im(z))**2),
     sin(re(z))*sinh(im(z))/(sin(re(z))**2*sinh(im(z))**2 +
                             cos(re(z))**2*cosh(im(z))**2)))

    assert sec(x).expand(trig=True) == 1/cos(x)
    assert sec(2*x).expand(trig=True) == 1/(2*cos(x)**2 - 1)

    assert sec(x).is_real == True
    assert sec(z).is_real == None

    assert sec(x).as_leading_term() == sec(x)

    assert sec(0).is_bounded == True
    assert sec(x).is_bounded == None
    assert sec(pi/2).is_bounded == False

    assert series(sec(x), x, x0=0, n=6) == 1 + x**2/2 + 5*x**4/24 + O(x**6)

    # https://github.com/sympy/sympy/issues/7166
    assert series(sqrt(sec(x))) == 1 + x**2/4 + 7*x**4/96 + O(x**6)

    assert sec(x).diff(x) == tan(x)*sec(x)

    # Taylor Term checks
    assert sec(z).taylor_term(4, z) == 5*z**4/24
    assert sec(z).taylor_term(6, z) == 61*z**6/720
    assert sec(z).taylor_term(5, z) == 0
def exercise_6_43():

    z = sp.Symbol('z')

    b_of_z = 1/(1 - z)

    sp.pprint('\n' + 'b_of_z:')
    sp.pprint(b_of_z)

    e_b_prime_of_z = z**2/(1 - z)**2

    sp.pprint('\n' +'e_b_prime_of_z:')
    sp.pprint(e_b_prime_of_z)

    e_b_prime_of_n = sp.series(e_b_prime_of_z, z, 0, 10)

    sp.pprint('\n' +'e_b_prime_of_n:')
    sp.pprint(e_b_prime_of_n)

    e_b_of_z = sp.integrate(e_b_prime_of_z, z)
    constant = e_b_of_z.subs(z, 0)
    e_b_of_z = e_b_of_z - constant

    sp.pprint('\n' +'e_b_of_z:')
    sp.pprint(e_b_of_z)

    e_b_of_n = sp.series(e_b_of_z, z, 0, 10)

    sp.pprint('\n' +'e_b_of_n:')
    sp.pprint(e_b_of_n)

    e_b_prime_of_z = sp.diff(e_b_of_z, z)

    sp.pprint('\n' +'e_b_prime_of_z:')
    sp.pprint(e_b_prime_of_z)

    f_of_z = sp.together((1 - z)**2*e_b_prime_of_z)

    sp.pprint('\n' +'f_of_z:')
    sp.pprint(f_of_z)

    F_of_z = sp.integrate(f_of_z, z)

    sp.pprint('\n' +'F_of_z:')
    sp.pprint(F_of_z)

    c_b_of_z = (e_b_of_z.subs(z, 0) + F_of_z)/(1 - z)**2

    sp.pprint('\n' +'c_b_of_z:')
    sp.pprint(c_b_of_z)

    c_b_of_n = sp.series(c_b_of_z, z, 0, 10)

    sp.pprint('\n' +'c_b_of_n:')
    sp.pprint(c_b_of_n)
示例#9
0
def test_sec():
    x = symbols('x', real=True)
    z = symbols('z')

    assert sec.nargs == 1

    assert sec(0) == 1
    assert sec(pi) == -1
    assert sec(pi/2) == oo
    assert sec(-pi/2) == oo
    assert sec(pi/6) == 2*sqrt(3)/3
    assert sec(pi/3) == 2
    assert sec(5*pi/2) == oo
    assert sec(9*pi/7) == -sec(2*pi/7)
    assert sec(I) == 1/cosh(1)
    assert sec(x*I) == 1/cosh(x)
    assert sec(-x) == sec(x)

    assert sec(x).rewrite(exp) == 1/(exp(I*x)/2 + exp(-I*x)/2)
    assert sec(x).rewrite(sin) == sec(x)
    assert sec(x).rewrite(cos) == 1/cos(x)
    assert sec(x).rewrite(tan) == (tan(x/2)**2 + 1)/(-tan(x/2)**2 + 1)
    assert sec(x).rewrite(pow) == sec(x)
    assert sec(x).rewrite(sqrt) == sec(x)

    assert sec(z).conjugate() == sec(conjugate(z))

    assert (sec(z).as_real_imag() ==
    (cos(re(z))*cosh(im(z))/(sin(re(z))**2*sinh(im(z))**2 +
                             cos(re(z))**2*cosh(im(z))**2),
     sin(re(z))*sinh(im(z))/(sin(re(z))**2*sinh(im(z))**2 +
                             cos(re(z))**2*cosh(im(z))**2)))

    assert sec(x).expand(trig=True) == 1/cos(x)
    assert sec(2*x).expand(trig=True) == 1/(2*cos(x)**2 - 1)

    assert sec(x).is_real == True
    assert sec(z).is_real == None

    assert sec(x).as_leading_term() == sec(x)

    assert sec(0).is_bounded == True
    assert sec(x).is_bounded == None
    assert sec(pi/2).is_bounded == False

    assert series(sec(x), x, x0=0, n=6) == 1 + x**2/2 + 5*x**4/24 + O(x**6)

    # https://code.google.com/p/sympy/issues/detail?id=4067
    assert series(sqrt(sec(x))) == 1 + x**2/4 + 7*x**4/96 + O(x**6)

    # https://code.google.com/p/sympy/issues/detail?id=4068
    assert (series(sqrt(sec(x)), x, x0=pi*3/2, n=4) ==
            1/sqrt(x) +x**(S(3)/2)/12 + x**(S(7)/2)/160 + O(x**4))

    assert sec(x).diff(x) == tan(x)*sec(x)
示例#10
0
def test_2124():
    assert series(1, x) == 1
    assert S(0).lseries(x).next() == 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).removeO().subs(x, x - 1) -
            cos(x + 1).series(x).removeO().subs(x, x - 1)).expand() == 0
    e = cos(x).series(x, 1, n=None)
    assert [e.next() for i in range(2)] == [cos(1), -((x - 1) * sin(1))]
    e = cos(x).series(x, 1, n=None, dir='-')
    assert [e.next() 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().subs(x, x - 1) == \
        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 D(cos(x), x).lseries().next() == D(1, x)
    assert D(exp(x),
             x).series(n=3) == D(1, x) + D(x, x) + D(x**2 / 2, 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

    assert ((1 / sin(x))**oo).series() == oo
    logx = Symbol('logx')
    assert ((sin(x))**y).nseries(x, n=1, logx=logx) == \
        exp(y*logx) + O(x*exp(y*logx), x)

    raises(NotImplementedError, lambda: series(Function("f")(x)))

    assert sin(1 / x).series(x, oo, n=5) == 1 / x - 1 / (6 * x**3)
    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)
示例#11
0
def test_2124():
    assert series(1, x) == 1
    assert S(0).lseries(x).next() == 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).removeO().subs(x, x - 1) -
            cos(x + 1).series(x).removeO().subs(x, x - 1)).expand() == 0
    e = cos(x).series(x, 1, n=None)
    assert [e.next() for i in range(2)] == [cos(1), -((x - 1)*sin(1))]
    e = cos(x).series(x, 1, n=None, dir='-')
    assert [e.next() 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().subs(x, x - 1) == \
           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 D(cos(x), x).lseries().next() == D(1, x)
    assert D(
        exp(x), x).series(n=3) == D(1, x) + D(x, x) + D(x**2/2, 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

    assert ((1/sin(x))**oo).series() == oo
    logx = Symbol('logx')
    assert ((sin(x))**y).nseries(x, n=1, logx=logx) \
           == exp(y*logx) + O(x*exp(y*logx), x)

    raises(NotImplementedError, lambda: series(Function("f")(x)))

    assert sin(1/x).series(x, oo, n=5) == 1/x - 1/(6*x**3)
    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)
示例#12
0
def test_132_genf():
    searcher = TileScope([Perm((0, 2, 1))], point_placements)
    spec = searcher.auto_search(smallest=True)
    spec = spec.expand_verified()
    av = Av([Perm((0, 2, 1))])
    for i in range(10):
        assert set(av.of_length(i)) == set(
            gp.patt for gp in spec.generate_objects_of_size(i))
        assert spec.random_sample_object_of_size(i).patt in av
    gf = spec.get_genf()
    gf = sympy.series(spec.get_genf(), n=15)
    x = sympy.Symbol("x")
    assert [gf.coeff(x, n) for n in range(13)] == [
        1,
        1,
        2,
        5,
        14,
        42,
        132,
        429,
        1430,
        4862,
        16796,
        58786,
        208012,
    ]
示例#13
0
def test_airybiprime():
    z = Symbol('z', real=False)
    t = Symbol('t', negative=True)
    p = Symbol('p', positive=True)

    assert isinstance(airybiprime(z), airybiprime)

    assert airybiprime(0) == 3**(S(1)/6)/gamma(S(1)/3)
    assert airybiprime(oo) == oo
    assert airybiprime(-oo) == 0

    assert diff(airybiprime(z), z) == z*airybi(z)

    assert series(airybiprime(z), z, 0, 3) == (
        3**(S(1)/6)/gamma(S(1)/3) + 3**(S(5)/6)*z**2/(6*gamma(S(2)/3)) + O(z**3))

    assert airybiprime(z).rewrite(hyper) == (
        3**(S(5)/6)*z**2*hyper((), (S(5)/3,), z**S(3)/9)/(6*gamma(S(2)/3)) +
        3**(S(1)/6)*hyper((), (S(1)/3,), z**S(3)/9)/gamma(S(1)/3))

    assert isinstance(airybiprime(z).rewrite(besselj), airybiprime)
    assert airyai(t).rewrite(besselj) == (
        sqrt(-t)*(besselj(-S(1)/3, 2*(-t)**(S(3)/2)/3) +
                  besselj(S(1)/3, 2*(-t)**(S(3)/2)/3))/3)
    assert airybiprime(z).rewrite(besseli) == (
        sqrt(3)*(z**2*besseli(S(2)/3, 2*z**(S(3)/2)/3)/(z**(S(3)/2))**(S(2)/3) +
                 (z**(S(3)/2))**(S(2)/3)*besseli(-S(2)/3, 2*z**(S(3)/2)/3))/3)
    assert airybiprime(p).rewrite(besseli) == (
        sqrt(3)*p*(besseli(-S(2)/3, 2*p**(S(3)/2)/3) + besseli(S(2)/3, 2*p**(S(3)/2)/3))/3)

    assert expand_func(airybiprime(2*(3*z**5)**(S(1)/3))) == (
        sqrt(3)*(z**(S(5)/3)/(z**5)**(S(1)/3) - 1)*airyaiprime(2*3**(S(1)/3)*z**(S(5)/3))/2 +
        (z**(S(5)/3)/(z**5)**(S(1)/3) + 1)*airybiprime(2*3**(S(1)/3)*z**(S(5)/3))/2)
示例#14
0
def get_massless(exp,replace=[],n=3):
    if len(replace)>0:
        for _ in replace:
            A,B=_
            exp=exp.subs(A,B)
    exp=exp.subs(Q,1/eps)        
    return sp.series(exp,eps,0,n=n).subs(eps,1/Q).removeO()
示例#15
0
def compute_conf_intervals_via_shock_poly(a_t,
                                          p_poly,
                                          d_poly,
                                          q_poly,
                                          num_coeffs,
                                          max_lag=100):
    # computes the confidence interval by rewriting the ts in shock form.
    # a_t: the residuals
    # p_poly: the AR polynomial. Should have constant 1.
    # q_poly: the MA polynomial. Should have constant 1.
    # num_coeffs: number of parameters used. You should count the estimated mean of the ts as a parameter.

    v = len(a_t) - num_coeffs
    var = sum(a_t**2) * (1 / v)

    if p_poly is None and q_poly is None and d_poly is None:
        const_shock = 1.96 * np.sqrt((var).astype(float))
        return np.asarray([const_shock] * max_lag)

    # compute_memory_shock_terms
    if p_poly is None: p_poly = 1
    if d_poly is None: d_poly = 1
    if q_poly is None: q_poly = 1

    shock_poly: poly = (series(q_poly / (d_poly * p_poly),
                               x=B,
                               x0=0,
                               n=max_lag + 1)).as_expr().removeO().as_poly()
    shock_coeffs = shock_poly.coeffs()

    s_t = np.cumsum(np.flip(shock_coeffs)**2)
    std_errors = 1.96 * np.sqrt((var * s_t).astype(float))

    return std_errors
def symbol_calc_2d_taylor(n,
                          x_taylor="x1lin",
                          order=2,
                          x1_neg=True,
                          slope="slope",
                          Iext1="Iext1",
                          shape=None):
    fx1ser, v = symbol_eqtn_fx1(n,
                                model="2d",
                                x1_neg=x1_neg,
                                slope=slope,
                                Iext1=Iext1)[1:]
    fx1ser = fx1ser.tolist()
    x_taylor = symbol_vars(n, [x_taylor])[0]
    v.update({"x_taylor": x_taylor})
    for ix in range(shape_to_size(v["x1"].shape)):
        fx1ser[ix] = series(fx1ser[ix],
                            x=v["x1"][ix],
                            x0=x_taylor[ix],
                            n=order).removeO()  #
    fx1ser = Array(fx1ser)
    if shape is not None:
        if len(shape) > 1:
            fx1ser = fx1ser.reshape(shape[0], shape[1])
        else:
            fx1ser = fx1ser.reshape(shape[0], )
    return lambdify([
        v["x1"], x_taylor, v["z"], v["y1"], v[Iext1], v[slope], v["a"], v["b"],
        v["d"], v["tau1"]
    ], fx1ser, "numpy"), fx1ser, v
示例#17
0
 def _series_expand(self, param, about, order):
     if isinstance(self.val, sympy.Basic):
         if about != 0:
             c = self.val.subs({param: about + param})
         else:
             c = self.val
         series = sympy.series(c, x=param, x0=0, n=None)
         res = []
         next_order = 0
         for term in series:
             c, o = term.as_coeff_exponent(param)
             if o < 0 or o.is_noninteger:
                 raise ValueError(
                     "%s is singular at expansion point %s=%s."
                     % (self, param, about)
                 )
             if o > order:
                 break
             res.extend([0] * (o - next_order))
             res.append(c)
             next_order = o + 1
         res.extend([0] * (order + 1 - next_order))
         return tuple([ScalarValue.create(c) for c in res])
     else:
         return tuple([self] + [Zero] * order)
def Cauchy_form_poly(equations, X):
    #####Computing the Taylor polynomial#######################
    n = len(X)
    P_str = [Pi.replace('\n', '') for Pi in open(equations, 'r').readlines()]
    P_pluse = [P_stri for P_stri in P_str]
    P_minus = [P_stri for P_stri in P_str]
    for i in range(2, n):
        P_pluse = [
            P_plusei.replace("x" + str(i + 1),
                             "(x" + str(i + 1) + "+ r" + str(i + 1) + "*t)")
            for P_plusei in P_pluse
        ]
        P_minus = [
            P_minusi.replace("x" + str(i + 1),
                             "(x" + str(i + 1) + "- r" + str(i + 1) + "*t)")
            for P_minusi in P_minus
        ]
    DP = [("0.5*(" + P_plusei + "- (" + P_minusi + ") )").replace("^", "**")
          for P_plusei, P_minusi in zip(P_pluse, P_minus)]
    #X_Ball=list(parse_expr(DP[0]).free_symbols)
    #t_in= X_Ball.index(sp.Symbol('t'))
    #t=X_Ball[t_in]
    t = sp.Symbol('t')
    D_ser = [sp.series(parse_expr(DPi), t).removeO() for DPi in DP]
    D_ser = [sp.expand(seri / t) for seri in D_ser]
    D_ser = [seri.subs(t, sp.sqrt(t)) for seri in D_ser]
    return D_ser
示例#19
0
def test_airyai():
    z = Symbol('z', real=False)
    t = Symbol('t', negative=True)
    p = Symbol('p', positive=True)

    assert isinstance(airyai(z), airyai)

    assert airyai(0) == 3**(S(1)/3)/(3*gamma(S(2)/3))
    assert airyai(oo) == 0
    assert airyai(-oo) == 0

    assert diff(airyai(z), z) == airyaiprime(z)

    assert series(airyai(z), z, 0, 3) == (
        3**(S(5)/6)*gamma(S(1)/3)/(6*pi) - 3**(S(1)/6)*z*gamma(S(2)/3)/(2*pi) + O(z**3))

    assert airyai(z).rewrite(hyper) == (
        -3**(S(2)/3)*z*hyper((), (S(4)/3,), z**S(3)/9)/(3*gamma(S(1)/3)) +
         3**(S(1)/3)*hyper((), (S(2)/3,), z**S(3)/9)/(3*gamma(S(2)/3)))

    assert isinstance(airyai(z).rewrite(besselj), airyai)
    assert airyai(t).rewrite(besselj) == (
        sqrt(-t)*(besselj(-S(1)/3, 2*(-t)**(S(3)/2)/3) +
                  besselj(S(1)/3, 2*(-t)**(S(3)/2)/3))/3)
    assert airyai(z).rewrite(besseli) == (
        -z*besseli(S(1)/3, 2*z**(S(3)/2)/3)/(3*(z**(S(3)/2))**(S(1)/3)) +
         (z**(S(3)/2))**(S(1)/3)*besseli(-S(1)/3, 2*z**(S(3)/2)/3)/3)
    assert airyai(p).rewrite(besseli) == (
        sqrt(p)*(besseli(-S(1)/3, 2*p**(S(3)/2)/3) -
                 besseli(S(1)/3, 2*p**(S(3)/2)/3))/3)

    assert expand_func(airyai(2*(3*z**5)**(S(1)/3))) == (
        -sqrt(3)*(-1 + (z**5)**(S(1)/3)/z**(S(5)/3))*airybi(2*3**(S(1)/3)*z**(S(5)/3))/6 +
         (1 + (z**5)**(S(1)/3)/z**(S(5)/3))*airyai(2*3**(S(1)/3)*z**(S(5)/3))/2)
def main(k, terms):
    d = diff(func(x), x, k)
    print(d)
    a = series(d, x, n=terms)
    print("The derivative of the order {} with first  {} terms in the Taylor series is \n{}".format(k, terms, a))

    return a
示例#21
0
    def __init__(self, a, b, omega, gamma, Nmax):
        import time
        """
        Initialize the object: do the Taylor series expansion etc
        """
        self.a = a
        self.b = b

        # define symbols
        x, y, u = sy.symbols('x y u', real=True)
        # define a density function we want to integrate
        rho = sy.sin(omega * y) * sy.exp(gamma * y)
        #
        # make a Taylor series expansion of this density
        # up to Nmax terms
        rho_taylor = sy.series(rho, y, (a + b) / 2, Nmax).removeO()
        # Now we substitute y=u+x and represent the result as a polynomial wrt u
        pu_coeffs = rho_taylor.subs(y, u + x).as_poly(u).all_coeffs()
        self.pu_coeffs_str = []
        for coeff in pu_coeffs:
            self.pu_coeffs_str.append(str(coeff))
        # for evaluation we would like to convert these functions
        # to lambda-function, but those cannot be stored (pickled)
        # we will store the lambda functions in the following list:
        self.cns = []
示例#22
0
def test_airyai():
    z = Symbol('z', real=False)
    t = Symbol('t', negative=True)
    p = Symbol('p', positive=True)

    assert isinstance(airyai(z), airyai)

    assert airyai(0) == 3**Rational(1, 3)/(3*gamma(Rational(2, 3)))
    assert airyai(oo) == 0
    assert airyai(-oo) == 0

    assert diff(airyai(z), z) == airyaiprime(z)

    assert series(airyai(z), z, 0, 3) == (
        3**Rational(5, 6)*gamma(Rational(1, 3))/(6*pi) - 3**Rational(1, 6)*z*gamma(Rational(2, 3))/(2*pi) + O(z**3))

    assert airyai(z).rewrite(hyper) == (
        -3**Rational(2, 3)*z*hyper((), (Rational(4, 3),), z**3/9)/(3*gamma(Rational(1, 3))) +
         3**Rational(1, 3)*hyper((), (Rational(2, 3),), z**3/9)/(3*gamma(Rational(2, 3))))

    assert isinstance(airyai(z).rewrite(besselj), airyai)
    assert airyai(t).rewrite(besselj) == (
        sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) +
                  besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3)
    assert airyai(z).rewrite(besseli) == (
        -z*besseli(Rational(1, 3), 2*z**Rational(3, 2)/3)/(3*(z**Rational(3, 2))**Rational(1, 3)) +
         (z**Rational(3, 2))**Rational(1, 3)*besseli(Rational(-1, 3), 2*z**Rational(3, 2)/3)/3)
    assert airyai(p).rewrite(besseli) == (
        sqrt(p)*(besseli(Rational(-1, 3), 2*p**Rational(3, 2)/3) -
                 besseli(Rational(1, 3), 2*p**Rational(3, 2)/3))/3)

    assert expand_func(airyai(2*(3*z**5)**Rational(1, 3))) == (
        -sqrt(3)*(-1 + (z**5)**Rational(1, 3)/z**Rational(5, 3))*airybi(2*3**Rational(1, 3)*z**Rational(5, 3))/6 +
         (1 + (z**5)**Rational(1, 3)/z**Rational(5, 3))*airyai(2*3**Rational(1, 3)*z**Rational(5, 3))/2)
示例#23
0
def test_airybiprime():
    z = Symbol('z', real=False)
    t = Symbol('t', negative=True)
    p = Symbol('p', positive=True)

    assert isinstance(airybiprime(z), airybiprime)

    assert airybiprime(0) == 3**Rational(1, 6)/gamma(Rational(1, 3))
    assert airybiprime(oo) is oo
    assert airybiprime(-oo) == 0

    assert diff(airybiprime(z), z) == z*airybi(z)

    assert series(airybiprime(z), z, 0, 3) == (
        3**Rational(1, 6)/gamma(Rational(1, 3)) + 3**Rational(5, 6)*z**2/(6*gamma(Rational(2, 3))) + O(z**3))

    assert airybiprime(z).rewrite(hyper) == (
        3**Rational(5, 6)*z**2*hyper((), (Rational(5, 3),), z**3/9)/(6*gamma(Rational(2, 3))) +
        3**Rational(1, 6)*hyper((), (Rational(1, 3),), z**3/9)/gamma(Rational(1, 3)))

    assert isinstance(airybiprime(z).rewrite(besselj), airybiprime)
    assert airyai(t).rewrite(besselj) == (
        sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) +
                  besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3)
    assert airybiprime(z).rewrite(besseli) == (
        sqrt(3)*(z**2*besseli(Rational(2, 3), 2*z**Rational(3, 2)/3)/(z**Rational(3, 2))**Rational(2, 3) +
                 (z**Rational(3, 2))**Rational(2, 3)*besseli(Rational(-2, 3), 2*z**Rational(3, 2)/3))/3)
    assert airybiprime(p).rewrite(besseli) == (
        sqrt(3)*p*(besseli(Rational(-2, 3), 2*p**Rational(3, 2)/3) + besseli(Rational(2, 3), 2*p**Rational(3, 2)/3))/3)

    assert expand_func(airybiprime(2*(3*z**5)**Rational(1, 3))) == (
        sqrt(3)*(z**Rational(5, 3)/(z**5)**Rational(1, 3) - 1)*airyaiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/2 +
        (z**Rational(5, 3)/(z**5)**Rational(1, 3) + 1)*airybiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/2)
示例#24
0
def test_airybi():
    z = Symbol('z', real=False)
    t = Symbol('t', negative=True)
    p = Symbol('p', positive=True)

    assert isinstance(airybi(z), airybi)

    assert airybi(0) == 3**(S(5)/6)/(3*gamma(S(2)/3))
    assert airybi(oo) == oo
    assert airybi(-oo) == 0

    assert diff(airybi(z), z) == airybiprime(z)

    assert series(airybi(z), z, 0, 3) == (
        3**(S(1)/3)*gamma(S(1)/3)/(2*pi) + 3**(S(2)/3)*z*gamma(S(2)/3)/(2*pi) + O(z**3))

    assert airybi(z).rewrite(hyper) == (
        3**(S(1)/6)*z*hyper((), (S(4)/3,), z**S(3)/9)/gamma(S(1)/3) +
        3**(S(5)/6)*hyper((), (S(2)/3,), z**S(3)/9)/(3*gamma(S(2)/3)))

    assert isinstance(airybi(z).rewrite(besselj), airybi)
    assert airyai(t).rewrite(besselj) == (
        sqrt(-t)*(besselj(-S(1)/3, 2*(-t)**(S(3)/2)/3) +
                  besselj(S(1)/3, 2*(-t)**(S(3)/2)/3))/3)
    assert airybi(z).rewrite(besseli) == (
        sqrt(3)*(z*besseli(S(1)/3, 2*z**(S(3)/2)/3)/(z**(S(3)/2))**(S(1)/3) +
                 (z**(S(3)/2))**(S(1)/3)*besseli(-S(1)/3, 2*z**(S(3)/2)/3))/3)
    assert airybi(p).rewrite(besseli) == (
        sqrt(3)*sqrt(p)*(besseli(-S(1)/3, 2*p**(S(3)/2)/3) +
                         besseli(S(1)/3, 2*p**(S(3)/2)/3))/3)

    assert expand_func(airybi(2*(3*z**5)**(S(1)/3))) == (
        sqrt(3)*(1 - (z**5)**(S(1)/3)/z**(S(5)/3))*airyai(2*3**(S(1)/3)*z**(S(5)/3))/2 +
        (1 + (z**5)**(S(1)/3)/z**(S(5)/3))*airybi(2*3**(S(1)/3)*z**(S(5)/3))/2)
示例#25
0
文件: drv.py 项目: yatna/sympy
    def expectation(self, expr, var, evaluate=True, **kwargs):
        """ Expectation of expression over distribution """
        # TODO: support discrete sets with non integer stepsizes

        if evaluate:
            try:
                p = poly(expr, var)

                t = Dummy('t', real=True)

                mgf = self.moment_generating_function(t)
                deg = p.degree()
                taylor = poly(series(mgf, t, 0, deg + 1).removeO(), t)
                result = 0
                for k in range(deg+1):
                    result += p.coeff_monomial(var ** k) * taylor.coeff_monomial(t ** k) * factorial(k)

                return result

            except PolynomialError:
                return summation(expr * self.pdf(var),
                                 (var, self.set.inf, self.set.sup), **kwargs)

        else:
            return Sum(expr * self.pdf(var),
                         (var, self.set.inf, self.set.sup), **kwargs)
示例#26
0
def euler76():
	import sympy
	x=sympy.symbols("x")
	poly=1
	for i in range(1,101):
		poly*=1/(1-x**i)
	print (sympy.series(poly,x,0,101)).coeff(x**100)-1
示例#27
0
    def expectation(self, expr, var, evaluate=True, **kwargs):
        """ Expectation of expression over distribution """
        # TODO: support discrete sets with non integer stepsizes

        if evaluate:
            try:
                # note: in order for this algorithm to be valid,
                #   the characteristic function must have continuous
                #   derivatives up to the highest power of the variable in the expression

                p = poly(expr, var)

                t = Dummy('t', real=True)

                cf = self.characteristic_function(t)
                deg = p.degree()
                taylor = poly(
                    series(cf.subs(t, t / I), t, 0, deg + 1).removeO(), t)
                result = 0
                for k in range(deg + 1):
                    result += p.coeff_monomial(var**k) * taylor.coeff_monomial(
                        t**k) * factorial(k)

                return result

            except PolynomialError:
                return summation(expr * self.pdf(var),
                                 (var, self.set.inf, self.set.sup), **kwargs)

        else:
            return Sum(expr * self.pdf(var), (var, self.set.inf, self.set.sup),
                       **kwargs)
示例#28
0
def metric_expan(z, h, N):
    if N == 1:
        return (1, 1)
    else:
        g = 1 + z * h
        ig1 = sy.series(1 / g, x=h, n=N)
        return (g, ig1.removeO())
示例#29
0
def poincare1d_BCH():
    """
		Calculations are not quite right, see Poincare1D.ipynb.
	"""
    from sympy import Symbol, Matrix, series, exp, var

    ncvar = lambda s: Symbol(s, commutative=False)

    A, B, C = map(ncvar, ['A', 'B', 'C'])
    chi, t0, x0 = var('chi,t0,x0')

    P = LieAlgebra([A, B, C], {1: [(A, B, C), (A, C, B)]})
    BCH_series = sum([
        term.simplify() for term in Dynkin_BCH(
            chi * A, (t0 * B + x0 * C), 6, commutator=P.commutator)
    ])
    match_series = series(-chi / (1 - exp(chi)), chi, 0, 8)

    expr = lambda A, B, C: exp(chi * (A + (t0 - x0) / 2 * (B - C) - 1 /
                                      (1 - exp(chi)) * (t0 * B + x0 * C)))

    sexpr = expr(A, B, C)

    A = Matrix([[0, 1, 0], [1, 0, 0], [0, 0, 0]])

    B = Matrix([[0, 0, 1], [0, 0, 0], [0, 0, 0]])

    C = Matrix([[0, 0, 0], [0, 0, 1], [0, 0, 0]])

    mexpr = expr(A, B, C).simplify()

    return BCH_series, match_series, sexpr, (A, B, C), mexpr
示例#30
0
def test_airyaiprime():
    z = Symbol('z', real=False)
    t = Symbol('t', negative=True)
    p = Symbol('p', positive=True)

    assert isinstance(airyaiprime(z), airyaiprime)

    assert airyaiprime(0) == -3**(S(2)/3)/(3*gamma(S(1)/3))
    assert airyaiprime(oo) == 0

    assert diff(airyaiprime(z), z) == z*airyai(z)

    assert series(airyaiprime(z), z, 0, 3) == (
        -3**(S(2)/3)/(3*gamma(S(1)/3)) + 3**(S(1)/3)*z**2/(6*gamma(S(2)/3)) + O(z**3))

    assert airyaiprime(z).rewrite(hyper) == (
        3**(S(1)/3)*z**2*hyper((), (S(5)/3,), z**S(3)/9)/(6*gamma(S(2)/3)) -
        3**(S(2)/3)*hyper((), (S(1)/3,), z**S(3)/9)/(3*gamma(S(1)/3)))

    assert isinstance(airyaiprime(z).rewrite(besselj), airyaiprime)
    assert airyai(t).rewrite(besselj) == (
        sqrt(-t)*(besselj(-S(1)/3, 2*(-t)**(S(3)/2)/3) +
                  besselj(S(1)/3, 2*(-t)**(S(3)/2)/3))/3)
    assert airyaiprime(z).rewrite(besseli) == (
        z**2*besseli(S(2)/3, 2*z**(S(3)/2)/3)/(3*(z**(S(3)/2))**(S(2)/3)) -
        (z**(S(3)/2))**(S(2)/3)*besseli(-S(1)/3, 2*z**(S(3)/2)/3)/3)
    assert airyaiprime(p).rewrite(besseli) == (
        p*(-besseli(-S(2)/3, 2*p**(S(3)/2)/3) + besseli(S(2)/3, 2*p**(S(3)/2)/3))/3)

    assert expand_func(airyaiprime(2*(3*z**5)**(S(1)/3))) == (
        sqrt(3)*(z**(S(5)/3)/(z**5)**(S(1)/3) - 1)*airybiprime(2*3**(S(1)/3)*z**(S(5)/3))/6 +
        (z**(S(5)/3)/(z**5)**(S(1)/3) + 1)*airyaiprime(2*3**(S(1)/3)*z**(S(5)/3))/2)
示例#31
0
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
    )
示例#32
0
def test_power_series_counts_language(re, i):
    dfa = rd.build_dfa(re)
    z, gfs = compute_generating_functions(*dfa)
    f = gfs[0]
    note(f)
    power_series = series(f, n=i + 1)
    counter = rd.LanguageCounter(*dfa)
    assert counter.count(i) == power_series.coeff(z, i)
def Validate(Butcher_dict, Butcher_key, yn, tn, rhs_key):
    # Set needed symbolic expressions
    t, dt = sp.symbols('t dt')

    # 1. First we solve the ODE exactly
    y = sp.Function('y')
    sol = sp.dsolve(sp.Eq(y(t).diff(t), rhs_dict[rhs_key](y(t), t)), y(t)).rhs
    constants = sp.solve([sol.subs(t,tn)-yn])
    exact = sol.subs(constants)

    # 2. Now we solve the ODE numerically using specified Butcher table

    # Access the requested Butcher table
    Butcher = Butcher_dict[Butcher_key][0]
    # Determine number of predictor-corrector steps
    L = len(Butcher)-1
    # Set a temporary array for update values
    k = np.zeros(L, dtype=object)
    # Initialize intermediate variable
    yhat = 0
    # Initialize the updated solution
    ynp1 = 0
    for i in range(L):
        #Initialize and approximate update for solution
        yhat = yn
        for j in range(i):
            # Update yhat for solution using a_ij Butcher table coefficients
            yhat += Butcher[i][j+1]*k[j]
            if Butcher_key == "DP8" or Butcher_key == "L6":
                yhat = 1.0*sp.N(yhat,20) # Otherwise the adding of fractions kills performance.
        # Determine the next corrector variable k_i using c_i Butcher table coefficients
        k[i] = dt*rhs_dict[rhs_key](yhat, tn + Butcher[i][0]*dt)
        # Update the solution at the next iteration ynp1 using Butcher table coefficients
        ynp1 += Butcher[L][i+1]*k[i]
    # Finish determining the solution for the next iteration
    ynp1 += yn

    # Determine the order of the RK method
    order = Butcher_dict[Butcher_key][1]+2
    # Produces Taylor series of exact solution at t=tn about t = 0 with the specified order
    exact_series = sp.series(exact.subs(t, dt),dt, 0, order)
    num_series = sp.series(ynp1, dt, 0, order)
    diff = exact_series-num_series
    return diff
示例#34
0
 def __sections(self):
     t = sp.symbols('t')
     GenSec = sp.prod(1 / (1 - (t * zz)) for zz in self.coordinates)
     poly = sp.series(GenSec, t,
                      n=self.dimensions + 1).coeff(t**(self.dimensions))
     sections = []
     while poly != 0:
         sections.append(sp.LT(poly))
         poly = poly - sp.LT(poly)
     return (np.array(sections), len(sections))
示例#35
0
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

    assert ((1 / sin(x)) ** oo).series() is oo
    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)
示例#36
0
文件: kswcf.py 项目: chan-y-park/mose
def t_expand(expr, max_deg):
    """
    Takes an expression f(x,y) and computes the Taylor expansion 
    in x and y up to bi-degree fixed by max_deg.
    For example: 
    x / (1 - y) 
    with value of max_deg = 3 will give 
    x + x * y
    up to bi-degree 2.
    """
    f = expr.subs([(x, t*x), (y, t*y)])
    return series(f, t, 0, max_deg).removeO().subs(t, 1)
示例#37
0
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)
    )
示例#38
0
文件: kswcf.py 项目: chan-y-park/mose
def t_degree(expr, max_deg):
    """
    Takes an expression f(x,y) and computes the Taylor expansion 
    in x and y up to bi-degree fixed by max_deg. Then, picks the term 
    of highest bi-degree, and returns the value of the degree.
    For example: 
    x / (1 - y) 
    with value of max_deg = 3 will give 
    t * x + t**2 * x * y
    up to bi-degree 2. Will return 2.
    """
    f = expr.subs([(x, t*x), (y, t*y)])
    return degree(series(f, t, 0, max_deg).removeO(), t)
示例#39
0
文件: kswcf.py 项目: chan-y-park/mose
def t_min_degree(expr, max_deg, large_number=1000):
    """
    Takes an expression f(x,y) and computes the Taylor expansion 
    in x and y up to bi-degree fixed by max_deg. Then, picks the term 
    of lowest bi-degree.
    For example: 
    x / (1 - y) 
    with value of max_deg = 3 will give 
    t * x + t**2 * x * y
    up to bi-degree 2. Will return x.
    """
    f = expr.subs([(x, x / t), (y, y / t)])
    f_t_series = t**large_number * series(f, t, 0, max_deg).removeO() 
    leading_term = LT(f_t_series.expand(), t).subs(t, 1)
    return leading_term 
示例#40
0
文件: crv.py 项目: Lenqth/sympy
 def expectation(self, expr, var, evaluate=True, **kwargs):
     """ Expectation of expression over distribution """
     if evaluate:
         try:
             p = poly(expr, var)
             t = Dummy('t', real=True)
             mgf = self._moment_generating_function(t)
             if mgf is None:
                 return integrate(expr * self.pdf(var), (var, self.set), **kwargs)
             deg = p.degree()
             taylor = poly(series(mgf, t, 0, deg + 1).removeO(), t)
             result = 0
             for k in range(deg+1):
                 result += p.coeff_monomial(var ** k) * taylor.coeff_monomial(t ** k) * factorial(k)
             return result
         except PolynomialError:
             return integrate(expr * self.pdf(var), (var, self.set), **kwargs)
     else:
         return Integral(expr * self.pdf(var), (var, self.set), **kwargs)
示例#41
0
    def _get_dict(self, other):
        """
        Returns a dictionary representing the (exponent, coefficient) pairs
        of the Puiseux series expansion of `other`.

        If `other` is a `PuiseuxSeries` then we take the minimum order
        of `other` and self. If `other is a SymPy expression then we
        compute the Taylor series in (x-alpha) of other up to `self.order`.
        """
        # if other is a Puiseux series (also centered at self.alpha)
        # then the order of the new puiseux series is the smaller of
        # the two
        if isinstance(other, PuiseuxSeries):
            if self.alpha != other.alpha:
                raise ValueError("Puiseux series must be centered at " + \
                                 "the same point.")         
            order = min(self.order, other.order)
            d = other.d

        # if other is a SymPy Expr then compute the series expansion
        # of other up to self's order and store the exponent, coeff
        # pairs in d
        elif isinstance(other, sympy.Expr):
            d = {}
            order = self.order
         
            s = sympy.series(other, self.var, x0=self.alpha, n=None)
            for term in s:
                # we have to shift because SymPy has trouble
                # collecting expressions such as c*(x-a) in terms of
                # (x-a). Example: 1-x should be -1*(x-1) but SymPy
                # cannot detect this.
                term = term.subs(x,x+self.alpha)
                coeff, exp = term.as_coeff_exponent(self.var)
                if exp < order:
                    d[exp] = coeff
                else:
                    break

        return order,d
def get_coefficients(function, p, x0, n):

	taylor_series = sp.series(expr=function, x=p, x0=x0, n=n).removeO()
	
	coefficients_dict_sympy_pow_keys = taylor_series.as_coefficients_dict()

	coefficients_dict_string_keys = {}
	for key in coefficients_dict_sympy_pow_keys.keys():
		coefficients_dict_string_keys[str(key)] = coefficients_dict_sympy_pow_keys[key]

	taylor_coefficients = []
	for i in range(n):
		if i == 0:
			key = '1'
		elif i == 1:
			key = 'p'
		else:
			key = "(p - 0.5)**{}".format(i)
		taylor_coefficients.append( coefficients_dict_string_keys[key] / (2**i) )


	coeffs = [ sp.N(c, precision) for c in taylor_coefficients ]

	return coeffs
示例#43
0
def test_cos():
    e1 = cos(x).series(x, 0)
    e2 = series(cos(x), x, 0)
    assert e1 == e2
示例#44
0
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)))
示例#45
0
def test_issue_14885():
    assert series(x**(-S(3)/2)*exp(x), x, 0) == (x**(-S(3)/2) + 1/sqrt(x) +
        sqrt(x)/2 + x**(S(3)/2)/6 + x**(S(5)/2)/24 + x**(S(7)/2)/120 +
        x**(S(9)/2)/720 + x**(S(11)/2)/5040 + O(x**6))
示例#46
0
    sym_DxyyyG_near = pickle.load(open(prefix+'DxyyyG_near.dat','r'))    
    sym_DyyyyG_near = pickle.load(open(prefix+'DyyyyG_near.dat','r'))    
    sym_DxxxxxG_near = pickle.load(open(prefix+'DxxxxxG_near.dat','r'))    
    sym_DxxxxyG_near = pickle.load(open(prefix+'DxxxxyG_near.dat','r'))    
    sym_DxxxyyG_near = pickle.load(open(prefix+'DxxxyyG_near.dat','r'))    
    sym_DxxyyyG_near = pickle.load(open(prefix+'DxxyyyG_near.dat','r'))    
    sym_DxyyyyG_near = pickle.load(open(prefix+'DxyyyyG_near.dat','r'))    
    sym_DyyyyyG_near = pickle.load(open(prefix+'DyyyyyG_near.dat','r'))    
    print "Complete."
else:
    print "Calculating derivatives of kernel symbolically..."
    rr = x**2 + y**2
    rho = rr / delta**2
    sym_DxG = x*(sp.exp( - rho ) - 1 )/(2*sp.pi*rr)
    sym_DyG = y*(sp.exp( - rho ) - 1 )/(2*sp.pi*rr)
    sym_DxG_near = sp.series(sp.series(sym_DxG,x).removeO()\
                             ,y).removeO()
    sym_DyG_near = sp.series(sp.series(sym_DyG,x).removeO()\
                             ,y).removeO()
    pickle.dump(sym_DxG,open(prefix+'DxG.dat','w'))
    pickle.dump(sym_DyG,open(prefix+'DyG.dat','w'))
    pickle.dump(sym_DxG_near,open(prefix+'DxG_near.dat','w'))
    pickle.dump(sym_DyG_near,open(prefix+'DyG_near.dat','w'))
    print "Computed first order derivatives"
    sym_DxxG = sp.diff( sym_DxG , x )
    sym_DxyG = sp.diff( sym_DxG , y )
    sym_DyyG = sp.diff( sym_DyG , y )
    sym_DxxG_near = sp.series(sp.series(sym_DxxG,x).removeO()\
                             ,y).removeO()
    sym_DxyG_near = sp.series(sp.series(sym_DxyG,x).removeO()\
                             ,y).removeO()
    sym_DyyG_near = sp.series(sp.series(sym_DyyG,x).removeO()\
def exercise_5_3():
    u, z = sp.symbols('u, z')
    quadratic = z*u**2 - u + z
    u_of_z = sp.simplify(sp.solve(quadratic, u)[0])
    sp.pprint(u_of_z)
    sp.pprint(sp.series(u_of_z, z, 0, 13), num_columns=100)
示例#48
0
def test_sin():
    e1 = sin(x).series(x, 0)
    e2 = series(sin(x), x, 0)
    assert e1 == e2
示例#49
0
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)
示例#50
0
def test_issue_8805():
    assert series(1, n=8) == 1
示例#51
0
def test_issue_10761():
    assert series(1/(x**-2 + x**-3), x, 0) == x**3 - x**4 + x**5 + O(x**6)
def exercise_5_1():
    z = sp.symbols('z')
    sp.pprint(sp.series((1+z+z**2)/(1-z-z**2-z**3),z,0,10), num_columns=100)
示例#53
0
def test_exp():
    e1 = exp(x).series(x, 0)
    e2 = series(exp(x), x, 0)
    assert e1 == e2
示例#54
0
def test_issue_7203():
    assert series(cos(x), x, pi, 3) == \
        -1 + (x - pi)**2/2 + O((x - pi)**3, (x, pi))
示例#55
0
def test_exp2():
    e1 = exp(cos(x)).series(x, 0)
    e2 = series(exp(cos(x)), x, 0)
    assert e1 == e2
示例#56
0
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)
from matplotlib import animation

#plt.rcParams['animation.ffmpeg_path'] = "C:/ffmpeg/bin/ffmpeg.exe"

fig = plt.figure()

x = Symbol('x')
f = exp((sin(x) - cos(x)) / 4) / (x ** 2 + 10)
xdata = np.linspace(-10, 10, 200)
ydata = lambdify(x, f, "numpy")(xdata)
y0 = lambdify(x, f, "numpy")(0)
orders = 10
yydata = []

for o in range(orders):
    dl = series(f, x, 0, o + 1).removeO()
    if o == 0:
        yydata.append([y0] * len(xdata))
    else:
        yydata.append(lambdify(x, dl, "numpy")(xdata))

func, = plt.plot(xdata, ydata, color="b")
dl, = plt.plot([], [], color="g")
point, = plt.plot([], [], color="r", marker='.', markersize=10)

legend_func = plt.text(-9, 0.10, r"", {'color': 'b', 'fontsize': 16})
legend_dl = plt.text(-9, 0.08, r"", {'color': 'g', 'fontsize': 16})


def init():
    func.set_data([], [])
from sympy import Symbol, Rational, cos, sin, series

x = Symbol('x') 
print cos(x).series(x, 0.5, 10)
print cos(x).series(x, 0.5, 10).removeO()
from sympy.series import series
print series(cos(x), x0=Rational(0.5), n=10)
print series(cos(x), x0=0, n=10)