def test_integrate_Abs_sign(): assert integrate(Abs(x), (x, -2, 1)) == S(5)/2 assert integrate(Abs(x), (x, 0, 1)) == S(1)/2 assert integrate(Abs(x + 1), (x, 0, 1)) == S(3)/2 assert integrate(Abs(x**2 - 1), (x, -2, 2)) == 4 assert integrate(Abs(x**2 - 3*x), (x, -15, 15)) == 2259 assert integrate(sign(x), (x, -1, 2)) == 1 assert integrate(sign(x)*sin(x), (x, -pi, pi)) == 4 assert integrate(sign(x - 2) * x**2, (x, 0, 3)) == S(11)/3 t, s = symbols('t s', real=True) assert integrate(Abs(t), t) == Piecewise( (-t**2/2, t <= 0), (t**2/2, True)) assert integrate(Abs(2*t - 6), t) == Piecewise( (-t**2 + 6*t, t <= 3), (t**2 - 6*t + 18, True)) assert (integrate(abs(t - s**2), (t, 0, 2)) == 2*s**2*Min(2, s**2) - 2*s**2 - Min(2, s**2)**2 + 2) assert integrate(exp(-Abs(t)), t) == Piecewise( (exp(t), t <= 0), (2 - exp(-t), True)) assert integrate(sign(2*t - 6), t) == Piecewise( (-t, t < 3), (t - 6, True)) assert integrate(2*t*sign(t**2 - 1), t) == Piecewise( (t**2, t < -1), (-t**2 + 2, t < 1), (t**2, True)) assert integrate(sign(t), (t, s + 1)) == Piecewise( (s + 1, s + 1 > 0), (-s - 1, s + 1 < 0), (0, True))
def test_issue_1572_1364_1368(): assert solve((sqrt(x**2 - 1) - 2)) in ([sqrt(5), -sqrt(5)], [-sqrt(5), sqrt(5)]) assert set(solve((2**exp(y**2/x) + 2)/(x**2 + 15), y)) == set([ -sqrt(x)*sqrt(-log(log(2)) + log(log(2) + I*pi)), sqrt(x)*sqrt(-log(log(2)) + log(log(2) + I*pi))]) C1, C2 = symbols('C1 C2') f = Function('f') assert solve(C1 + C2/x**2 - exp(-f(x)), f(x)) == [log(x**2/(C1*x**2 + C2))] a = Symbol('a') E = S.Exp1 assert solve(1 - log(a + 4*x**2), x) in ( [-sqrt(-a + E)/2, sqrt(-a + E)/2], [sqrt(-a + E)/2, -sqrt(-a + E)/2] ) assert solve(log(a**(-3) - x**2)/a, x) in ( [-sqrt(-1 + a**(-3)), sqrt(-1 + a**(-3))], [sqrt(-1 + a**(-3)), -sqrt(-1 + a**(-3))],) assert solve(1 - log(a + 4*x**2), x) in ( [-sqrt(-a + E)/2, sqrt(-a + E)/2], [sqrt(-a + E)/2, -sqrt(-a + E)/2],) assert set(solve(( a**2 + 1) * (sin(a*x) + cos(a*x)), x)) == set([-pi/(4*a), 3*pi/(4*a)]) assert solve(3 - (sinh(a*x) + cosh(a*x)), x) == [2*atanh(S.Half)/a] assert set(solve(3 - (sinh(a*x) + cosh(a*x)**2), x)) == \ set([ 2*atanh(-1 + sqrt(2))/a, 2*atanh(S(1)/2 + sqrt(5)/2)/a, 2*atanh(-sqrt(2) - 1)/a, 2*atanh(-sqrt(5)/2 + S(1)/2)/a ]) assert solve(atan(x) - 1) == [tan(1)]
def test_tan_rewrite(): x = Symbol('x') neg_exp, pos_exp = exp(-x*I), exp(x*I) assert tan(x).rewrite(exp) == I*(neg_exp-pos_exp)/(neg_exp+pos_exp) assert tan(x).rewrite(sin) == 2*sin(x)**2/sin(2*x) assert tan(x).rewrite(cos) == -cos(x + S.Pi/2)/cos(x) assert tan(x).rewrite(cot) == 1/cot(x)
def test_derivative_by_array(): from sympy.abc import a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z bexpr = x*y**2*exp(z)*log(t) sexpr = sin(bexpr) cexpr = cos(bexpr) a = Array([sexpr]) assert derive_by_array(sexpr, t) == x*y**2*exp(z)*cos(x*y**2*exp(z)*log(t))/t assert derive_by_array(sexpr, [x, y, z]) == Array([bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr, bexpr*cexpr]) assert derive_by_array(a, [x, y, z]) == Array([[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr], [bexpr*cexpr]]) assert derive_by_array(sexpr, [[x, y], [z, t]]) == Array([[bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr], [bexpr*cexpr, bexpr/log(t)/t*cexpr]]) assert derive_by_array(a, [[x, y], [z, t]]) == Array([[[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr]], [[bexpr*cexpr], [bexpr/log(t)/t*cexpr]]]) assert derive_by_array([[x, y], [z, t]], [x, y]) == Array([[[1, 0], [0, 0]], [[0, 1], [0, 0]]]) assert derive_by_array([[x, y], [z, t]], [[x, y], [z, t]]) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]]) assert diff(sexpr, t) == x*y**2*exp(z)*cos(x*y**2*exp(z)*log(t))/t assert diff(sexpr, Array([x, y, z])) == Array([bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr, bexpr*cexpr]) assert diff(a, Array([x, y, z])) == Array([[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr], [bexpr*cexpr]]) assert diff(sexpr, Array([[x, y], [z, t]])) == Array([[bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr], [bexpr*cexpr, bexpr/log(t)/t*cexpr]]) assert diff(a, Array([[x, y], [z, t]])) == Array([[[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr]], [[bexpr*cexpr], [bexpr/log(t)/t*cexpr]]]) assert diff(Array([[x, y], [z, t]]), Array([x, y])) == Array([[[1, 0], [0, 0]], [[0, 1], [0, 0]]]) assert diff(Array([[x, y], [z, t]]), Array([[x, y], [z, t]])) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
def test_cot_rewrite(): x = Symbol('x') neg_exp, pos_exp = exp(-x*I), exp(x*I) assert cot(x).rewrite(exp) == I*(pos_exp+neg_exp)/(pos_exp-neg_exp) assert cot(x).rewrite(sin) == 2*sin(2*x)/sin(x)**2 assert cot(x).rewrite(cos) == -cos(x)/cos(x + S.Pi/2) assert cot(x).rewrite(tan) == 1/tan(x)
def __init__(self, difficulty): a = not_named_yet.randint_no_zero(-3, 2) k = not_named_yet.randint_no_zero(-2, 2) c = not_named_yet.randint_no_zero(-5, 5) if a == 1: a += 1 if difficulty == 1: self.equation = sympy.exp(k * x) + c elif difficulty == 2: self.equation = a * sympy.exp(k * x) + c elif difficulty == 3: inner_function = request_linear(difficulty=3).equation self.equation = a * sympy.exp(inner_function) + c else: raise ValueError('You have given an invalid difficulty level! Please use difficulty levels 1-3') self.domain = sympy.Interval(-sympy.oo, sympy.oo, True, True) if a < 0: self.range = sympy.Interval(-sympy.oo, c, True, True) else: self.range = sympy.Interval(c, sympy.oo, True, True)
def test_simple_3(): assert Order(x) + x == Order(x) assert Order(x) + 2 == 2 + Order(x) assert Order(x) + x ** 2 == Order(x) assert Order(x) + 1 / x == 1 / x + Order(x) assert Order(1 / x) + 1 / x ** 2 == 1 / x ** 2 + Order(1 / x) assert Order(x) + exp(1 / x) == Order(x) + exp(1 / x)
def test_evalf_ramanujan(): assert NS(exp(pi*sqrt(163)) - 640320**3 - 744, 10) == '-7.499274028e-13' # A related identity A = 262537412640768744*exp(-pi*sqrt(163)) B = 196884*exp(-2*pi*sqrt(163)) C = 103378831900730205293632*exp(-3*pi*sqrt(163)) assert NS(1 - A - B + C, 10) == '1.613679005e-59'
def eq_sympy(input_dim, output_dim, ARD=False): """ Latent force model covariance, exponentiated quadratic with multiple outputs. Derived from a diffusion equation with the initial spatial condition layed down by a Gaussian process with lengthscale given by shared_lengthscale. See IEEE Trans Pattern Anal Mach Intell. 2013 Nov;35(11):2693-705. doi: 10.1109/TPAMI.2013.86. Linear latent force models using Gaussian processes. Alvarez MA, Luengo D, Lawrence ND. :param input_dim: Dimensionality of the kernel :type input_dim: int :param output_dim: number of outputs in the covariance function. :type output_dim: int :param ARD: whether or not to user ARD (default False). :type ARD: bool """ real_input_dim = input_dim if output_dim>1: real_input_dim -= 1 X = sp.symbols('x_:' + str(real_input_dim)) Z = sp.symbols('z_:' + str(real_input_dim)) scale = sp.var('scale_i scale_j',positive=True) if ARD: lengthscales = [sp.var('lengthscale%i_i lengthscale%i_j' % i, positive=True) for i in range(real_input_dim)] shared_lengthscales = [sp.var('shared_lengthscale%i' % i, positive=True) for i in range(real_input_dim)] dist_string = ' + '.join(['(x_%i-z_%i)**2/(shared_lengthscale%i**2 + lengthscale%i_i**2 + lengthscale%i_j**2)' % (i, i, i) for i in range(real_input_dim)]) dist = parse_expr(dist_string) f = variance*sp.exp(-dist/2.) else: lengthscales = sp.var('lengthscale_i lengthscale_j',positive=True) shared_lengthscale = sp.var('shared_lengthscale',positive=True) dist_string = ' + '.join(['(x_%i-z_%i)**2' % (i, i) for i in range(real_input_dim)]) dist = parse_expr(dist_string) f = scale_i*scale_j*sp.exp(-dist/(2*(lengthscale_i**2 + lengthscale_j**2 + shared_lengthscale**2))) return kern(input_dim, [spkern(input_dim, f, output_dim=output_dim, name='eq_sympy')])
def test_issue_1364(): assert solve(-a*x + 2*x*log(x), x) == [exp(a/2)] assert solve(a/x + exp(x/2), x) == [2*LambertW(-a/2)] assert solve(x**x) == [] assert solve(x**x - 2) == [exp(LambertW(log(2)))] assert solve(((x - 3)*(x - 2))**((x - 3)*(x - 4))) == [2] assert solve((a/x + exp(x/2)).diff(x), x) == [4*LambertW(sqrt(2)*sqrt(a)/4)]
def test_solve_args(): #implicit symbol to solve for assert set(int(tmp) for tmp in solve(x**2-4)) == set([2,-2]) assert solve([x+y-3,x-y-5]) == {x: 4, y: -1} #no symbol to solve for assert solve(42) == [] assert solve([1, 2]) is None #multiple symbols: take the first linear solution assert solve(x + y - 3, [x, y]) == [{x: 3 - y}] # unless it is an undetermined coefficients system assert solve(a + b*x - 2, [a, b]) == {a: 2, b: 0} # failing undetermined system assert solve(a*x + b**2/(x + 4) - 3*x - 4/x, a, b) == \ [{a: (-b**2*x + 3*x**3 + 12*x**2 + 4*x + 16)/(x**2*(x + 4))}] # failed single equation assert solve(1/(1/x - y + exp(y))) == [] raises(NotImplementedError, 'solve(exp(x) + sin(x) + exp(y) + sin(y))') # failed system # -- when no symbols given, 1 fails assert solve([y, exp(x) + x]) == [{x: -LambertW(1), y: 0}] # both fail assert solve((exp(x) - x, exp(y) - y)) == [{x: -LambertW(-1), y: -LambertW(-1)}] # -- when symbols given solve([y, exp(x) + x], x, y) == [(-LambertW(1), 0)] #symbol is not a symbol or function raises(TypeError, "solve(x**2-pi, pi)") # no equations assert solve([], [x]) == [] # overdetermined system # - nonlinear assert solve([(x + y)**2 - 4, x + y - 2]) == [{x: -y + 2}] # - linear assert solve((x + y - 2, 2*x + 2*y - 4)) == {x: -y + 2}
def test_branching(): from sympy import exp_polar, polar_lift, Symbol, I, exp assert besselj(polar_lift(k), x) == besselj(k, x) assert besseli(polar_lift(k), x) == besseli(k, x) n = Symbol('n', integer=True) assert besselj(n, exp_polar(2*pi*I)*x) == besselj(n, x) assert besselj(n, polar_lift(x)) == besselj(n, x) assert besseli(n, exp_polar(2*pi*I)*x) == besseli(n, x) assert besseli(n, polar_lift(x)) == besseli(n, x) def tn(func, s): from random import uniform c = uniform(1, 5) expr = func(s, c*exp_polar(I*pi)) - func(s, c*exp_polar(-I*pi)) eps = 1e-15 expr2 = func(s + eps, -c + eps*I) - func(s + eps, -c - eps*I) return abs(expr.n() - expr2.n()).n() < 1e-10 nu = Symbol('nu') assert besselj(nu, exp_polar(2*pi*I)*x) == exp(2*pi*I*nu)*besselj(nu, x) assert besseli(nu, exp_polar(2*pi*I)*x) == exp(2*pi*I*nu)*besseli(nu, x) assert tn(besselj, 2) assert tn(besselj, pi) assert tn(besselj, I) assert tn(besseli, 2) assert tn(besseli, pi) assert tn(besseli, I)
def test_polarify(): from sympy import polar_lift, polarify x = Symbol('x') z = Symbol('z', polar=True) f = Function('f') ES = {} assert polarify(-1) == (polar_lift(-1), ES) assert polarify(1 + I) == (polar_lift(1 + I), ES) assert polarify(exp(x), subs=False) == exp(x) assert polarify(1 + x, subs=False) == 1 + x assert polarify(f(I) + x, subs=False) == f(polar_lift(I)) + x assert polarify(x, lift=True) == polar_lift(x) assert polarify(z, lift=True) == z assert polarify(f(x), lift=True) == f(polar_lift(x)) assert polarify(1 + x, lift=True) == polar_lift(1 + x) assert polarify(1 + f(x), lift=True) == polar_lift(1 + f(polar_lift(x))) newex, subs = polarify(f(x) + z) assert newex.subs(subs) == f(x) + z mu = Symbol("mu") sigma = Symbol("sigma", positive=True) # Make sure polarify(lift=True) doesn't try to lift the integration # variable assert polarify( Integral(sqrt(2)*x*exp(-(-mu + x)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (x, -oo, oo)), lift=True) == Integral(sqrt(2)*(sigma*exp_polar(0))**exp_polar(I*pi)* exp((sigma*exp_polar(0))**(2*exp_polar(I*pi))*exp_polar(I*pi)*polar_lift(-mu + x)** (2*exp_polar(0))/2)*exp_polar(0)*polar_lift(x)/(2*sqrt(pi)), (x, -oo, oo))
def test_issue_6920(): e = [cos(x) + I*sin(x), cos(x) - I*sin(x), cosh(x) - sinh(x), cosh(x) + sinh(x)] ok = [exp(I*x), exp(-I*x), exp(-x), exp(x)] # wrap in f to show that the change happens wherever ei occurs f = Function('f') assert [simplify(f(ei)).args[0] for ei in e] == ok
def test_evalf_bugs(): assert NS(sin(1)+exp(-10**10),10) == NS(sin(1),10) assert NS(exp(10**10)+sin(1),10) == NS(exp(10**10),10) assert NS('log(1+1/10**50)',20) == '1.0000000000000000000e-50' assert NS('log(10**100,10)',10) == '100.0000000' assert NS('log(2)',10) == '0.6931471806' assert NS('(sin(x)-x)/x**3', 15, subs={x:'1/10**50'}) == '-0.166666666666667' assert NS(sin(1)+Rational(1,10**100)*I,15) == '0.841470984807897 + 1.00000000000000e-100*I' assert x.evalf() == x assert NS((1+I)**2*I, 6) == '-2.00000' d={n: (-1)**Rational(6,7), y: (-1)**Rational(4,7), x: (-1)**Rational(2,7)} assert NS((x*(1+y*(1 + n))).subs(d).evalf(),6) == '0.346011 + 0.433884*I' assert NS(((-I-sqrt(2)*I)**2).evalf()) == '-5.82842712474619' assert NS((1+I)**2*I,15) == '-2.00000000000000' #1659 (1/2): assert NS(pi.evalf(69) - pi) == '-4.43863937855894e-71' #1659 (2/2): With the bug present, this still only fails if the # terms are in the order given here. This is not generally the case, # because the order depends on the hashes of the terms. assert NS(20 - 5008329267844*n**25 - 477638700*n**37 - 19*n, subs={n:.01}) == '19.8100000000000' assert NS(((x - 1)*((1 - x))**1000).n()) == '(-x + 1.00000000000000)**1000*(x - 1.00000000000000)' assert NS((-x).n()) == '-x' assert NS((-2*x).n()) == '-2.00000000000000*x' assert NS((-2*x*y).n()) == '-2.00000000000000*x*y'
def test_case(): ob = FCodePrinter() x,x_,x__,y,X,X_,Y = symbols('x,x_,x__,y,X,X_,Y') assert fcode(exp(x_) + sin(x*y) + cos(X*Y)) == \ ' exp(x_) + sin(x*y) + cos(X__*Y_)' assert fcode(exp(x__) + 2*x*Y*X_**Rational(7, 2)) == \ ' 2*X_**(7.0d0/2.0d0)*Y*x + exp(x__)' assert fcode(exp(x_) + sin(x*y) + cos(X*Y), name_mangling=False) == \ ' exp(x_) + sin(x*y) + cos(X*Y)' assert fcode(x - cos(X), name_mangling=False) == ' x - cos(X)' assert ob.doprint(X*sin(x) + x_, assign_to='me') == ' me = X*sin(x_) + x__' assert ob.doprint(X*sin(x), assign_to='mu') == ' mu = X*sin(x_)' assert ob.doprint(x_, assign_to='ad') == ' ad = x__' n, m = symbols('n,m', integer=True) A = IndexedBase('A') x = IndexedBase('x') y = IndexedBase('y') i = Idx('i', m) I = Idx('I', n) assert fcode(A[i, I]*x[I], assign_to=y[i], source_format='free') == ( "do i = 1, m\n" " y(i) = 0\n" "end do\n" "do i = 1, m\n" " do I_ = 1, n\n" " y(i) = A(i, I_)*x(I_) + y(i)\n" " end do\n" "end do" )
def test_pde_separate_add(): x, y, z, t = symbols("x,y,z,t") F, T, X, Y, Z, u = map(Function, 'FTXYZu') eq = Eq(D(u(x, t), x), D(u(x, t), t)*exp(u(x, t))) res = pde_separate_add(eq, u(x, t), [X(x), T(t)]) assert res == [D(X(x), x)*exp(-X(x)), D(T(t), t)*exp(T(t))]
def test_manualintegrate_exponentials(): assert manualintegrate(exp(2*x), x) == exp(2*x) / 2 assert manualintegrate(2**x, x) == (2 ** x) / log(2) assert manualintegrate(1 / x, x) == log(x) assert manualintegrate(1 / (2*x + 3), x) == log(2*x + 3) / 2 assert manualintegrate(log(x)**2 / x, x) == log(x)**3 / 3
def test_manual_subs(): x, y = symbols('x y') expr = log(x) + exp(x) # if log(x) is y, then exp(y) is x assert manual_subs(expr, log(x), y) == y + exp(exp(y)) # if exp(x) is y, then log(y) need not be x assert manual_subs(expr, exp(x), y) == log(x) + y
def test_fisher_z(): d1 = Symbol("d1", positive=True) d2 = Symbol("d2", positive=True) X = FisherZ("x", d1, d2) assert density(X)(x) == (2*d1**(d1/2)*d2**(d2/2)*(d1*exp(2*x) + d2) **(-d1/2 - d2/2)*exp(d1*x)/beta(d1/2, d2/2))
def test_lognormal(): mean = Symbol('mu', real=True, finite=True) std = Symbol('sigma', positive=True, real=True, finite=True) X = LogNormal('x', mean, std) # The sympy integrator can't do this too well #assert E(X) == exp(mean+std**2/2) #assert variance(X) == (exp(std**2)-1) * exp(2*mean + std**2) # Right now, only density function and sampling works # Test sampling: Only e^mean in sample std of 0 for i in range(3): X = LogNormal('x', i, 0) assert S(sample(X)) == N(exp(i)) # The sympy integrator can't do this too well #assert E(X) == mu = Symbol("mu", real=True) sigma = Symbol("sigma", positive=True) X = LogNormal('x', mu, sigma) assert density(X)(x) == (sqrt(2)*exp(-(-mu + log(x))**2 /(2*sigma**2))/(2*x*sqrt(pi)*sigma)) X = LogNormal('x', 0, 1) # Mean 0, standard deviation 1 assert density(X)(x) == sqrt(2)*exp(-log(x)**2/2)/(2*x*sqrt(pi))
def test_hankel_transform(): from sympy import sinh, cosh, gamma, sqrt, exp r = Symbol("r") k = Symbol("k") nu = Symbol("nu") m = Symbol("m") a = symbols("a") assert hankel_transform(1/r, r, k, 0) == 1/k assert inverse_hankel_transform(1/k, k, r, 0) == 1/r assert hankel_transform( 1/r**m, r, k, 0) == 2**(-m + 1)*k**(m - 2)*gamma(-m/2 + 1)/gamma(m/2) assert inverse_hankel_transform( 2**(-m + 1)*k**(m - 2)*gamma(-m/2 + 1)/gamma(m/2), k, r, 0) == r**(-m) assert hankel_transform(1/r**m, r, k, nu) == ( 2*2**(-m)*k**(m - 2)*gamma(-m/2 + nu/2 + 1)/gamma(m/2 + nu/2)) assert inverse_hankel_transform(2**(-m + 1)*k**( m - 2)*gamma(-m/2 + nu/2 + 1)/gamma(m/2 + nu/2), k, r, nu) == r**(-m) assert hankel_transform(r**nu*exp(-a*r), r, k, nu) == \ 2**(nu + 1)*a*k**(-nu - 3)*(a**2/k**2 + 1)**(-nu - S( 3)/2)*gamma(nu + S(3)/2)/sqrt(pi) assert inverse_hankel_transform( 2**(nu + 1)*a*k**(-nu - 3)*(a**2/k**2 + 1)**(-nu - S(3)/2)*gamma( nu + S(3)/2)/sqrt(pi), k, r, nu) == r**nu*exp(-a*r)
def test_deriv_wrt_function(): t = Symbol('t') xfunc = Function('x') yfunc = Function('y') x = xfunc(t) xd = diff(x, t) xdd = diff(xd, t) y = yfunc(t) yd = diff(y, t) ydd = diff(yd, t) assert diff(x, t) == xd assert diff(2 * x + 4, t) == 2 * xd assert diff(2 * x + 4 + y, t) == 2 * xd + yd assert diff(2 * x + 4 + y * x, t) == 2 * xd + x * yd + xd * y assert diff(2 * x + 4 + y * x, x) == 2 + y assert (diff(4 * x**2 + 3 * x + x * y, t) == 3 * xd + x * yd + xd * y + 8 * x * xd) assert (diff(4 * x**2 + 3 * xd + x * y, t) == 3 * xdd + x * yd + xd * y + 8 * x * xd) assert diff(4 * x**2 + 3 * xd + x * y, xd) == 3 assert diff(4 * x**2 + 3 * xd + x * y, xdd) == 0 assert diff(sin(x), t) == xd * cos(x) assert diff(exp(x), t) == xd * exp(x) assert diff(sqrt(x), t) == xd / (2 * sqrt(x))
def test_integrate_linearterm_pow(): # check integrate((a*x+b)^c, x) -- issue 3499 y = Symbol('y', positive=True) # TODO: Remove conds='none' below, let the assumption take care of it. assert integrate(x**y, x, conds='none') == x**(y + 1)/(y + 1) assert integrate((exp(y)*x + 1/y)**(1 + sin(y)), x, conds='none') == \ exp(-y)*(exp(y)*x + 1/y)**(2 + sin(y)) / (2 + sin(y))
def test_transform(): a = Integral(x**2 + 1, (x, -1, 2)) fx = x fy = 3*y + 1 assert a.doit() == a.transform(fx, fy).doit() assert a.transform(fx, fy).transform(fy, fx) == a fx = 3*x + 1 fy = y assert a.transform(fx, fy).transform(fy, fx) == a a = Integral(sin(1/x), (x, 0, 1)) assert a.transform(x, 1/y) == Integral(sin(y)/y**2, (y, 1, oo)) assert a.transform(x, 1/y).transform(y, 1/x) == a a = Integral(exp(-x**2), (x, -oo, oo)) assert a.transform(x, 2*y) == Integral(2*exp(-4*y**2), (y, -oo, oo)) # < 3 arg limit handled properly assert Integral(x, x).transform(x, a*y).doit() == \ Integral(y*a**2, y).doit() _3 = S(3) assert Integral(x, (x, 0, -_3)).transform(x, 1/y).doit() == \ Integral(-1/x**3, (x, -oo, -1/_3)).doit() assert Integral(x, (x, 0, _3)).transform(x, 1/y) == \ Integral(y**(-3), (y, 1/_3, oo)) # issue 8400 i = Integral(x + y, (x, 1, 2), (y, 1, 2)) assert i.transform(x, (x + 2*y, x)).doit() == \ i.transform(x, (x + 2*z, x)).doit() == 3
def test_tan_rewrite(): neg_exp, pos_exp = exp(-x*I), exp(x*I) assert tan(x).rewrite(exp) == I*(neg_exp - pos_exp)/(neg_exp + pos_exp) assert tan(x).rewrite(sin) == 2*sin(x)**2/sin(2*x) assert tan(x).rewrite(cos) == -cos(x + S.Pi/2)/cos(x) assert tan(x).rewrite(cot) == 1/cot(x) assert tan(sinh(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, sinh(3)).n() assert tan(cosh(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cosh(3)).n() assert tan(tanh(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, tanh(3)).n() assert tan(coth(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, coth(3)).n() assert tan(sin(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, sin(3)).n() assert tan(cos(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cos(3)).n() assert tan(tan(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, tan(3)).n() assert tan(cot(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cot(3)).n() assert tan(log(x)).rewrite(Pow) == I*(x**-I - x**I)/(x**-I + x**I) assert 0 == (cos(pi/15)*tan(pi/15) - sin(pi/15)).rewrite(pow) assert tan(pi/19).rewrite(pow) == tan(pi/19) assert tan(8*pi/19).rewrite(sqrt) == tan(8*pi/19)
def test_issue_8368(): assert integrate(exp(-s*x)*cosh(x), (x, 0, oo)) == \ Piecewise( ( pi*Piecewise( ( -s/(pi*(-s**2 + 1)), Abs(s**2) < 1), ( 1/(pi*s*(1 - 1/s**2)), Abs(s**(-2)) < 1), ( meijerg( ((S(1)/2,), (0, 0)), ((0, S(1)/2), (0,)), polar_lift(s)**2), True) ), And( Abs(periodic_argument(polar_lift(s)**2, oo)) < pi, cos(Abs(periodic_argument(polar_lift(s)**2, oo))/2)*sqrt(Abs(s**2)) - 1 > 0, Ne(s**2, 1)) ), ( Integral(exp(-s*x)*cosh(x), (x, 0, oo)), True)) assert integrate(exp(-s*x)*sinh(x), (x, 0, oo)) == \ Piecewise( ( -1/(s + 1)/2 - 1/(-s + 1)/2, And( Ne(1/s, 1), Abs(periodic_argument(s, oo)) < pi/2, Abs(periodic_argument(s, oo)) <= pi/2, cos(Abs(periodic_argument(s, oo)))*Abs(s) - 1 > 0)), ( Integral(exp(-s*x)*sinh(x), (x, 0, oo)), True))
def test_ode_solutions(): # only a few examples here, the rest will be tested in the actual dsolve tests assert ode_renumber(constantsimp(C1*exp(2*x)+exp(x)*(C2+C3), x, 3), 'C', 1, 3) == \ ode_renumber(C1*exp(x)+C2*exp(2*x), 'C', 1, 2) assert ode_renumber(constantsimp(Eq(f(x),I*C1*sinh(x/3) + C2*cosh(x/3)), x, 2), 'C', 1, 2) == ode_renumber(Eq(f(x), C1*sinh(x/3) + C2*cosh(x/3)), 'C', 1, 2) assert ode_renumber(constantsimp(Eq(f(x),acos((-C1)/cos(x))), x, 1), 'C', 1, 1) == \ Eq(f(x),acos(C1/cos(x))) assert ode_renumber(constantsimp(Eq(log(f(x)/C1) + 2*exp(x/f(x)), 0), x, 1), 'C', 1, 1) == Eq(log(C1*f(x)) + 2*exp(x/f(x)), 0) assert ode_renumber(constantsimp(Eq(log(x*2**Rational(1,2)*(1/x)**Rational(1,2)*f(x)\ **Rational(1,2)/C1) + x**2/(2*f(x)**2), 0), x, 1), 'C', 1, 1) == \ Eq(log(C1*x*(1/x)**Rational(1,2)*f(x)**Rational(1,2)) + x**2/(2*f(x)**2), 0) assert ode_renumber(constantsimp(Eq(-exp(-f(x)/x)*sin(f(x)/x)/2 + log(x/C1) - \ cos(f(x)/x)*exp(-f(x)/x)/2, 0), x, 1), 'C', 1, 1) == \ Eq(-exp(-f(x)/x)*sin(f(x)/x)/2 + log(C1*x) - cos(f(x)/x)*exp(-f(x)/x)/2, 0) u2 = Symbol('u2') _a = Symbol('_a') assert ode_renumber(constantsimp(Eq(-Integral(-1/((1 - u2**2)**Rational(1,2)*u2), \ (u2, _a, x/f(x))) + log(f(x)/C1), 0), x, 1), 'C', 1, 1) == \ Eq(-Integral(-1/(u2*(1 - u2**2)**Rational(1,2)), (u2, _a, x/f(x))) + \ log(C1*f(x)), 0) assert map(lambda i: ode_renumber(constantsimp(i, x, 1), 'C', 1, 1), [Eq(f(x), (-C1*x + x**2)**Rational(1,2)), Eq(f(x), -(-C1*x + x**2)**Rational(1,2))]) == [Eq(f(x), (C1*x + x**2)**Rational(1,2)), Eq(f(x), -(C1*x + x**2)**Rational(1,2))]
def test_convolution_fft(): assert all(convolution_fft([], x, dps=y) == [] for x in ([], [1]) for y in (None, 3)) assert convolution_fft([1, 2, 3], [4, 5, 6]) == [4, 13, 28, 27, 18] assert convolution_fft([1], [5, 6, 7]) == [5, 6, 7] assert convolution_fft([1, 3], [5, 6, 7]) == [5, 21, 25, 21] assert convolution_fft([1 + 2*I], [2 + 3*I]) == [-4 + 7*I] assert convolution_fft([1 + 2*I, 3 + 4*I, 5 + S(3)/5*I], [S(2)/5 + S(4)/7*I]) == \ [-S(26)/35 + 48*I/35, -S(38)/35 + 116*I/35, S(58)/35 + 542*I/175] assert convolution_fft([S(3)/4, S(5)/6], [S(7)/8, S(1)/3, S(2)/5]) == \ [S(21)/32, S(47)/48, S(26)/45, S(1)/3] assert convolution_fft([S(1)/9, S(2)/3, S(3)/5], [S(2)/5, S(3)/7, S(4)/9]) == \ [S(2)/45, S(11)/35, S(8152)/14175, S(523)/945, S(4)/15] assert convolution_fft([pi, E, sqrt(2)], [sqrt(3), 1/pi, 1/E]) == \ [sqrt(3)*pi, 1 + sqrt(3)*E, E/pi + pi*exp(-1) + sqrt(6), sqrt(2)/pi + 1, sqrt(2)*exp(-1)] assert convolution_fft([2321, 33123], [5321, 6321, 71323]) == \ [12350041, 190918524, 374911166, 2362431729] assert convolution_fft([312313, 31278232], [32139631, 319631]) == \ [10037624576503, 1005370659728895, 9997492572392] raises(TypeError, lambda: convolution_fft(x, y)) raises(ValueError, lambda: convolution_fft([x, y], [y, x]))
def test_ode_solutions(): # only a few examples here, the rest will be tested in the actual dsolve tests assert constant_renumber(constantsimp(C1*exp(2*x)+exp(x)*(C2+C3), x, 3), 'C', 1, 3) == \ constant_renumber(C1*exp(x)+C2*exp(2*x), 'C', 1, 2) assert constant_renumber(constantsimp(Eq(f(x),I*C1*sinh(x/3) + C2*cosh(x/3)), x, 2), 'C', 1, 2) == constant_renumber(Eq(f(x), C1*sinh(x/3) + C2*cosh(x/3)), 'C', 1, 2) assert constant_renumber(constantsimp(Eq(f(x),acos((-C1)/cos(x))), x, 1), 'C', 1, 1) == \ Eq(f(x),acos(C1/cos(x))) assert constant_renumber(constantsimp(Eq(log(f(x)/C1) + 2*exp(x/f(x)), 0), x, 1), 'C', 1, 1) == Eq(log(C1*f(x)) + 2*exp(x/f(x)), 0) assert constant_renumber(constantsimp(Eq(log(x*sqrt(2)*sqrt(1/x)*sqrt(f(x))\ /C1) + x**2/(2*f(x)**2), 0), x, 1), 'C', 1, 1) == \ Eq(log(C1*x*sqrt(1/x)*sqrt(f(x))) + x**2/(2*f(x)**2), 0) assert constant_renumber(constantsimp(Eq(-exp(-f(x)/x)*sin(f(x)/x)/2 + log(x/C1) - \ cos(f(x)/x)*exp(-f(x)/x)/2, 0), x, 1), 'C', 1, 1) == \ Eq(-exp(-f(x)/x)*sin(f(x)/x)/2 + log(C1*x) - cos(f(x)/x)*exp(-f(x)/x)/2, 0) u2 = Symbol('u2') _a = Symbol('_a') assert constant_renumber(constantsimp(Eq(-Integral(-1/(sqrt(1 - u2**2)*u2), \ (u2, _a, x/f(x))) + log(f(x)/C1), 0), x, 1), 'C', 1, 1) == \ Eq(-Integral(-1/(u2*sqrt(1 - u2**2)), (u2, _a, x/f(x))) + \ log(C1*f(x)), 0) assert [constant_renumber(constantsimp(i, x, 1), 'C', 1, 1) for i in [Eq(f(x), sqrt(-C1*x + x**2)), Eq(f(x), -sqrt(-C1*x + x**2))]] == [Eq(f(x), sqrt(C1*x + x**2)), Eq(f(x), -sqrt(C1*x + x**2))]
def test_collect_respecting_exponentials(): # If this test passes, lines 1306-1311 (at the time of this commit) # of sympy/solvers/ode.py should be removed. sol = 1 + exp(x / 2) assert sol == collect(sol, exp(x / 3))
def test_exp(): x = Symbol('x', integer=True) assert refine(exp(pi * I * 2 * x)) == 1 assert refine(exp(pi * I * 2 * (x + S.Half))) == -1 assert refine(exp(pi * I * 2 * (x + Rational(1, 4)))) == I assert refine(exp(pi * I * 2 * (x + Rational(3, 4)))) == -I
# vector containing the system variables U = [tau, u, e, z] # system parameters parameters = [nu, kappa, D, cnu, A, q, k, G] # # f_0(U)_t + F_1(U)_x = (B(U)U_x)_x # f0 = [tau, u, e + u**2 / 2, z] f1 = [ -u - spd * tau, G * e / tau - spd * u, G * e * u / tau - spd * (e + u**2 / 2), -spd * z ] BU = [[0, 0, 0, 0], [0, nu / tau, 0, 0], [0, nu * u / tau, kappa / (cnu * tau), 0], [0, 0, 0, D / tau**2]] G = [ 0, 0, -q * k * exp(-A / (e / cnu - Ti)) * z, k * exp(-A / (e / cnu - Ti)) * z ] # file path to location where code will be written file_path = '/Users/blake/Dropbox/stablab20/rNS/matlab' create_code(U, parameters, f0, f1, G, BU, file_path)
def test_ceiling(): assert ceiling(nan) == nan assert ceiling(oo) == oo assert ceiling(-oo) == -oo assert ceiling(zoo) == zoo assert ceiling(0) == 0 assert ceiling(1) == 1 assert ceiling(-1) == -1 assert ceiling(E) == 3 assert ceiling(-E) == -2 assert ceiling(2 * E) == 6 assert ceiling(-2 * E) == -5 assert ceiling(pi) == 4 assert ceiling(-pi) == -3 assert ceiling(Rational(1, 2)) == 1 assert ceiling(-Rational(1, 2)) == 0 assert ceiling(Rational(7, 3)) == 3 assert ceiling(-Rational(7, 3)) == -2 assert ceiling(Float(17.0)) == 17 assert ceiling(-Float(17.0)) == -17 assert ceiling(Float(7.69)) == 8 assert ceiling(-Float(7.69)) == -7 assert ceiling(I) == I assert ceiling(-I) == -I e = ceiling(i) assert e.func is ceiling and e.args[0] == i assert ceiling(oo * I) == oo * I assert ceiling(-oo * I) == -oo * I assert ceiling(exp(I * pi / 4) * oo) == exp(I * pi / 4) * oo assert ceiling(2 * I) == 2 * I assert ceiling(-2 * I) == -2 * I assert ceiling(I / 2) == I assert ceiling(-I / 2) == 0 assert ceiling(E + 17) == 20 assert ceiling(pi + 2) == 6 assert ceiling(E + pi) == ceiling(E + pi) assert ceiling(I + pi) == ceiling(I + pi) assert ceiling(ceiling(pi)) == 4 assert ceiling(ceiling(y)) == ceiling(y) assert ceiling(ceiling(x)) == ceiling(ceiling(x)) assert ceiling(x) == ceiling(x) assert ceiling(2 * x) == ceiling(2 * x) assert ceiling(k * x) == ceiling(k * x) assert ceiling(k) == k assert ceiling(2 * k) == 2 * k assert ceiling(k * n) == k * n assert ceiling(k / 2) == ceiling(k / 2) assert ceiling(x + y) == ceiling(x + y) assert ceiling(x + 3) == ceiling(x + 3) assert ceiling(x + k) == ceiling(x + k) assert ceiling(y + 3) == ceiling(y) + 3 assert ceiling(y + k) == ceiling(y) + k assert ceiling(3 + pi + y * I) == 7 + ceiling(y) * I assert ceiling(k + n) == k + n assert ceiling(x * I) == ceiling(x * I) assert ceiling(k * I) == k * I assert ceiling(Rational(23, 10) - E * I) == 3 - 2 * I assert ceiling(sin(1)) == 1 assert ceiling(sin(-1)) == 0 assert ceiling(exp(2)) == 8 assert ceiling(-log(8) / log(2)) != -2 assert int(ceiling(-log(8) / log(2)).evalf(chop=True)) == -3 assert ceiling(factorial(50)/exp(1)) == \ 11188719610782480504630258070757734324011354208865721592720336801 assert (ceiling(y) >= y) == True assert (ceiling(y) < y) == False assert (ceiling(x) >= x).is_Relational # x could be non-real assert (ceiling(x) < x).is_Relational assert (ceiling(x) >= y).is_Relational # arg is not same as rhs assert (ceiling(x) < y).is_Relational assert ceiling(y).rewrite(floor) == -floor(-y) assert ceiling(y).rewrite(frac) == y + frac(-y) assert ceiling(y).rewrite(floor).subs(y, -pi) == -floor(pi) assert ceiling(y).rewrite(floor).subs(y, E) == -floor(-E) assert ceiling(y).rewrite(frac).subs(y, pi) == ceiling(pi) assert ceiling(y).rewrite(frac).subs(y, -E) == ceiling(-E) assert Eq(ceiling(y), y + frac(-y)) assert Eq(ceiling(y), -floor(-y))
def test_floor(): assert floor(nan) == nan assert floor(oo) == oo assert floor(-oo) == -oo assert floor(zoo) == zoo assert floor(0) == 0 assert floor(1) == 1 assert floor(-1) == -1 assert floor(E) == 2 assert floor(-E) == -3 assert floor(2 * E) == 5 assert floor(-2 * E) == -6 assert floor(pi) == 3 assert floor(-pi) == -4 assert floor(Rational(1, 2)) == 0 assert floor(-Rational(1, 2)) == -1 assert floor(Rational(7, 3)) == 2 assert floor(-Rational(7, 3)) == -3 assert floor(Float(17.0)) == 17 assert floor(-Float(17.0)) == -17 assert floor(Float(7.69)) == 7 assert floor(-Float(7.69)) == -8 assert floor(I) == I assert floor(-I) == -I e = floor(i) assert e.func is floor and e.args[0] == i assert floor(oo * I) == oo * I assert floor(-oo * I) == -oo * I assert floor(exp(I * pi / 4) * oo) == exp(I * pi / 4) * oo assert floor(2 * I) == 2 * I assert floor(-2 * I) == -2 * I assert floor(I / 2) == 0 assert floor(-I / 2) == -I assert floor(E + 17) == 19 assert floor(pi + 2) == 5 assert floor(E + pi) == floor(E + pi) assert floor(I + pi) == floor(I + pi) assert floor(floor(pi)) == 3 assert floor(floor(y)) == floor(y) assert floor(floor(x)) == floor(floor(x)) assert floor(x) == floor(x) assert floor(2 * x) == floor(2 * x) assert floor(k * x) == floor(k * x) assert floor(k) == k assert floor(2 * k) == 2 * k assert floor(k * n) == k * n assert floor(k / 2) == floor(k / 2) assert floor(x + y) == floor(x + y) assert floor(x + 3) == floor(x + 3) assert floor(x + k) == floor(x + k) assert floor(y + 3) == floor(y) + 3 assert floor(y + k) == floor(y) + k assert floor(3 + I * y + pi) == 6 + floor(y) * I assert floor(k + n) == k + n assert floor(x * I) == floor(x * I) assert floor(k * I) == k * I assert floor(Rational(23, 10) - E * I) == 2 - 3 * I assert floor(sin(1)) == 0 assert floor(sin(-1)) == -1 assert floor(exp(2)) == 7 assert floor(log(8) / log(2)) != 2 assert int(floor(log(8) / log(2)).evalf(chop=True)) == 3 assert floor(factorial(50)/exp(1)) == \ 11188719610782480504630258070757734324011354208865721592720336800 assert (floor(y) <= y) == True assert (floor(y) > y) == False assert (floor(x) <= x).is_Relational # x could be non-real assert (floor(x) > x).is_Relational assert (floor(x) <= y).is_Relational # arg is not same as rhs assert (floor(x) > y).is_Relational assert floor(y).rewrite(frac) == y - frac(y) assert floor(y).rewrite(ceiling) == -ceiling(-y) assert floor(y).rewrite(frac).subs(y, -pi) == floor(-pi) assert floor(y).rewrite(frac).subs(y, E) == floor(E) assert floor(y).rewrite(ceiling).subs(y, E) == -ceiling(-E) assert floor(y).rewrite(ceiling).subs(y, -pi) == -ceiling(pi) assert Eq(floor(y), y - frac(y)) assert Eq(floor(y), -ceiling(-y))
def test_constantsimp_take_problem(): c = exp(C1) + 2 assert len(Poly(constantsimp(exp(C1) + c + c * x, [C1])).gens) == 2
def test_undetermined_coefficients_match(): assert _undetermined_coefficients_match(g(x), x) == {'test': False} assert _undetermined_coefficients_match(sin(2*x + sqrt(5)), x) == \ {'test': True, 'trialset': {cos(2*x + sqrt(5)), sin(2*x + sqrt(5))}} assert _undetermined_coefficients_match(sin(x)*cos(x), x) == \ {'test': False} s = {cos(x), x * cos(x), x**2 * cos(x), x**2 * sin(x), x * sin(x), sin(x)} assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \ {'test': True, 'trialset': s} assert _undetermined_coefficients_match( sin(x) * x**2 + sin(x) * x + sin(x), x) == { 'test': True, 'trialset': s } assert _undetermined_coefficients_match( exp(2 * x) * sin(x) * (x**2 + x + 1), x) == { 'test': True, 'trialset': { exp(2 * x) * sin(x), x**2 * exp(2 * x) * sin(x), cos(x) * exp(2 * x), x**2 * cos(x) * exp(2 * x), x * cos(x) * exp(2 * x), x * exp(2 * x) * sin(x) } } assert _undetermined_coefficients_match(1 / sin(x), x) == {'test': False} assert _undetermined_coefficients_match(log(x), x) == {'test': False} assert _undetermined_coefficients_match(2**(x)*(x**2 + x + 1), x) == \ {'test': True, 'trialset': {2**x, x*2**x, x**2*2**x}} assert _undetermined_coefficients_match(x**y, x) == {'test': False} assert _undetermined_coefficients_match(exp(x)*exp(2*x + 1), x) == \ {'test': True, 'trialset': {exp(1 + 3*x)}} assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \ {'test': True, 'trialset': {x*cos(x), x*sin(x), x**2*cos(x), x**2*sin(x), cos(x), sin(x)}} assert _undetermined_coefficients_match(sin(x)*(x + sin(x)), x) == \ {'test': False} assert _undetermined_coefficients_match(sin(x)*(x + sin(2*x)), x) == \ {'test': False} assert _undetermined_coefficients_match(sin(x)*tan(x), x) == \ {'test': False} assert _undetermined_coefficients_match( x**2 * sin(x) * exp(x) + x * sin(x) + x, x) == { 'test': True, 'trialset': { x**2 * cos(x) * exp(x), x, cos(x), S.One, exp(x) * sin(x), sin(x), x * exp(x) * sin(x), x * cos(x), x * cos(x) * exp(x), x * sin(x), cos(x) * exp(x), x**2 * exp(x) * sin(x) } } assert _undetermined_coefficients_match(4 * x * sin(x - 2), x) == { 'trialset': {x * cos(x - 2), x * sin(x - 2), cos(x - 2), sin(x - 2)}, 'test': True, } assert _undetermined_coefficients_match(2**x*x, x) == \ {'test': True, 'trialset': {2**x, x*2**x}} assert _undetermined_coefficients_match(2**x*exp(2*x), x) == \ {'test': True, 'trialset': {2**x*exp(2*x)}} assert _undetermined_coefficients_match(exp(-x)/x, x) == \ {'test': False} # Below are from Ordinary Differential Equations, # Tenenbaum and Pollard, pg. 231 assert _undetermined_coefficients_match(S(4), x) == \ {'test': True, 'trialset': {S.One}} assert _undetermined_coefficients_match(12*exp(x), x) == \ {'test': True, 'trialset': {exp(x)}} assert _undetermined_coefficients_match(exp(I*x), x) == \ {'test': True, 'trialset': {exp(I*x)}} assert _undetermined_coefficients_match(sin(x), x) == \ {'test': True, 'trialset': {cos(x), sin(x)}} assert _undetermined_coefficients_match(cos(x), x) == \ {'test': True, 'trialset': {cos(x), sin(x)}} assert _undetermined_coefficients_match(8 + 6*exp(x) + 2*sin(x), x) == \ {'test': True, 'trialset': {S.One, cos(x), sin(x), exp(x)}} assert _undetermined_coefficients_match(x**2, x) == \ {'test': True, 'trialset': {S.One, x, x**2}} assert _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x) == \ {'test': True, 'trialset': {x*exp(x), exp(x), exp(-x)}} assert _undetermined_coefficients_match(2*exp(2*x)*sin(x), x) == \ {'test': True, 'trialset': {exp(2*x)*sin(x), cos(x)*exp(2*x)}} assert _undetermined_coefficients_match(x - sin(x), x) == \ {'test': True, 'trialset': {S.One, x, cos(x), sin(x)}} assert _undetermined_coefficients_match(x**2 + 2*x, x) == \ {'test': True, 'trialset': {S.One, x, x**2}} assert _undetermined_coefficients_match(4*x*sin(x), x) == \ {'test': True, 'trialset': {x*cos(x), x*sin(x), cos(x), sin(x)}} assert _undetermined_coefficients_match(x*sin(2*x), x) == \ {'test': True, 'trialset': {x*cos(2*x), x*sin(2*x), cos(2*x), sin(2*x)}} assert _undetermined_coefficients_match(x**2*exp(-x), x) == \ {'test': True, 'trialset': {x*exp(-x), x**2*exp(-x), exp(-x)}} assert _undetermined_coefficients_match(2*exp(-x) - x**2*exp(-x), x) == \ {'test': True, 'trialset': {x*exp(-x), x**2*exp(-x), exp(-x)}} assert _undetermined_coefficients_match(exp(-2*x) + x**2, x) == \ {'test': True, 'trialset': {S.One, x, x**2, exp(-2*x)}} assert _undetermined_coefficients_match(x*exp(-x), x) == \ {'test': True, 'trialset': {x*exp(-x), exp(-x)}} assert _undetermined_coefficients_match(x + exp(2*x), x) == \ {'test': True, 'trialset': {S.One, x, exp(2*x)}} assert _undetermined_coefficients_match(sin(x) + exp(-x), x) == \ {'test': True, 'trialset': {cos(x), sin(x), exp(-x)}} assert _undetermined_coefficients_match(exp(x), x) == \ {'test': True, 'trialset': {exp(x)}} # converted from sin(x)**2 assert _undetermined_coefficients_match(S.Half - cos(2*x)/2, x) == \ {'test': True, 'trialset': {S.One, cos(2*x), sin(2*x)}} # converted from exp(2*x)*sin(x)**2 assert _undetermined_coefficients_match( exp(2 * x) * (S.Half + cos(2 * x) / 2), x) == { 'test': True, 'trialset': {exp(2 * x) * sin(2 * x), cos(2 * x) * exp(2 * x), exp(2 * x)} } assert _undetermined_coefficients_match(2*x + sin(x) + cos(x), x) == \ {'test': True, 'trialset': {S.One, x, cos(x), sin(x)}} # converted from sin(2*x)*sin(x) assert _undetermined_coefficients_match(cos(x)/2 - cos(3*x)/2, x) == \ {'test': True, 'trialset': {cos(x), cos(3*x), sin(x), sin(3*x)}} assert _undetermined_coefficients_match(cos(x**2), x) == {'test': False} assert _undetermined_coefficients_match(2**(x**2), x) == {'test': False}
def test_classify_ode(): assert classify_ode(f(x).diff(x, 2), f(x)) == \ ( 'nth_algebraic', 'nth_linear_constant_coeff_homogeneous', 'nth_linear_euler_eq_homogeneous', 'Liouville', '2nd_power_series_ordinary', 'nth_algebraic_Integral', 'Liouville_Integral', ) assert classify_ode(f(x), f(x)) == ('nth_algebraic', 'nth_algebraic_Integral') assert classify_ode( Eq(f(x).diff(x), 0), f(x)) == ('nth_algebraic', 'separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_homogeneous', 'nth_linear_euler_eq_homogeneous', 'nth_algebraic_Integral', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral') assert classify_ode( f(x).diff(x)**2, f(x)) == ('factorable', 'nth_algebraic', 'separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', 'nth_linear_euler_eq_homogeneous', 'nth_algebraic_Integral', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral') # issue 4749: f(x) should be cleared from highest derivative before classifying a = classify_ode(Eq(f(x).diff(x) + f(x), x), f(x)) b = classify_ode(f(x).diff(x) * f(x) + f(x) * f(x) - x * f(x), f(x)) c = classify_ode(f(x).diff(x) / f(x) + f(x) / f(x) - x / f(x), f(x)) assert a == ('1st_exact', '1st_linear', 'Bernoulli', 'almost_linear', '1st_power_series', "lie_group", 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral', 'almost_linear_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral') assert b == ('factorable', '1st_linear', 'Bernoulli', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', '1st_linear_Integral', 'Bernoulli_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral') assert c == ('1st_linear', 'Bernoulli', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', '1st_linear_Integral', 'Bernoulli_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral') assert classify_ode( 2 * x * f(x) * f(x).diff(x) + (1 + x) * f(x)**2 - exp(x), f(x)) == ('1st_exact', 'Bernoulli', 'almost_linear', 'lie_group', '1st_exact_Integral', 'Bernoulli_Integral', 'almost_linear_Integral') assert 'Riccati_special_minus2' in \ classify_ode(2*f(x).diff(x) + f(x)**2 - f(x)/x + 3*x**(-2), f(x)) raises(ValueError, lambda: classify_ode(x + f(x, y).diff(x).diff(y), f(x, y))) # issue 5176 k = Symbol('k') assert classify_ode(f(x).diff(x)/(k*f(x) + k*x*f(x)) + 2*f(x)/(k*f(x) + k*x*f(x)) + x*f(x).diff(x)/(k*f(x) + k*x*f(x)) + z, f(x)) == \ ('separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_power_series', 'lie_group', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral') # preprocessing ans = ( 'nth_algebraic', 'separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', 'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters', 'nth_algebraic_Integral', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral', 'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral') # w/o f(x) given assert classify_ode(diff(f(x) + x, x) + diff(f(x), x)) == ans # w/ f(x) and prep=True assert classify_ode(diff(f(x) + x, x) + diff(f(x), x), f(x), prep=True) == ans assert classify_ode(Eq(2*x**3*f(x).diff(x), 0), f(x)) == \ ('factorable', 'nth_algebraic', 'separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_power_series', 'lie_group', 'nth_linear_euler_eq_homogeneous', 'nth_algebraic_Integral', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral') assert classify_ode(Eq(2*f(x)**3*f(x).diff(x), 0), f(x)) == \ ('factorable', 'nth_algebraic', 'separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_power_series', 'lie_group', 'nth_algebraic_Integral', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral') # test issue 13864 assert classify_ode(Eq(diff(f(x), x) - f(x)**x, 0), f(x)) == \ ('1st_power_series', 'lie_group') assert isinstance(classify_ode(Eq(f(x), 5), f(x), dict=True), dict) #This is for new behavior of classify_ode when called internally with default, It should # return the first hint which matches therefore, 'ordered_hints' key will not be there. assert sorted(classify_ode(Eq(f(x).diff(x), 0), f(x), dict=True).keys()) == \ ['default', 'nth_linear_constant_coeff_homogeneous', 'order'] a = classify_ode(2 * x * f(x) * f(x).diff(x) + (1 + x) * f(x)**2 - exp(x), f(x), dict=True, hint='Bernoulli') assert sorted(a.keys()) == [ 'Bernoulli', 'Bernoulli_Integral', 'default', 'order', 'ordered_hints' ]
def get_sympy_expr(self, params): """Generate the required variables for creating a Dfun to be used in the fitting procedure. Parameters ---------- params : dict a dictionary of the model parameters, possibly created by :py:method:`guess`. Returns ------- dNdt : sympy.expr.Expr expression for the derivate of the model function t : sympy.symbol.symbol ma time symbol args : tuple of sympy.symbol.symbol tuple of symbols of model parameters See also -------- curveball.models.make_Dfun """ t, y0, K, r, nu, q0, v = sympy.symbols('t y0 K r nu q0 v') args = [y0, K, r, nu, q0, v] # remove fixed params and replace their symbols by their values # for params that don't exist (in inherited models), remove them and replace with a default value if not params['y0'].vary: args.remove(y0) y0 = params['y0'].value if 'K' not in self.param_names: args.remove(K) K = np.inf elif not params['K'].vary: args.remove(K) K = params['K'].value if not params['r'].vary: args.remove(r) r = params['r'].value if 'nu' not in self.param_names: args.remove(nu) nu = 1.0 elif not params['nu'].vary: args.remove(nu) nu = params['nu'].value if 'q0' not in self.param_names: args.remove(q0) q0 = np.inf elif not params['q0'].vary: args.remove(q0) q0 = params['q0'].value if 'v' not in self.param_names: args.remove(v) v = r elif not params['v'].vary: args.remove(v) v = params['v'].value if (isinstance(q0, float) and np.isinf(q0)) or (isinstance(v, float) and np.isinf(v)): At = t else: At = t + 1.0 / v * sympy.log((sympy.exp(-v * t) + q0) / (1 + q0)) dNdt = K / (1.0 - (1.0 - (K / y0)**nu) * sympy.exp(-r * nu * At))**(1.0 / nu) return dNdt, t, tuple(args)
def test_solve_ics(): # Basic tests that things work from dsolve. assert dsolve(f(x).diff(x) - 1/f(x), f(x), ics={f(1): 2}) == \ Eq(f(x), sqrt(2 * x + 2)) assert dsolve(f(x).diff(x) - f(x), f(x), ics={f(0): 1}) == Eq(f(x), exp(x)) assert dsolve(f(x).diff(x) - f(x), f(x), ics={f(x).diff(x).subs(x, 0): 1}) == Eq(f(x), exp(x)) assert dsolve(f(x).diff(x, x) + f(x), f(x), ics={ f(0): 1, f(x).diff(x).subs(x, 0): 1 }) == Eq(f(x), sin(x) + cos(x)) assert dsolve([f(x).diff(x) - f(x) + g(x), g(x).diff(x) - g(x) - f(x)], [f(x), g(x)], ics={ f(0): 1, g(0): 0 }) == [Eq(f(x), exp(x) * cos(x)), Eq(g(x), exp(x) * sin(x))] # Test cases where dsolve returns two solutions. eq = (x**2 * f(x)**2 - x).diff(x) assert dsolve(eq, f(x), ics={f(1): 0}) == [ Eq(f(x), -sqrt(x - 1) / x), Eq(f(x), sqrt(x - 1) / x) ] assert dsolve(eq, f(x), ics={f(x).diff(x).subs(x, 1): 0}) == [ Eq(f(x), -sqrt(x - S.Half) / x), Eq(f(x), sqrt(x - S.Half) / x) ] eq = cos(f(x)) - (x * sin(f(x)) - f(x)**2) * f(x).diff(x) assert dsolve(eq, f(x), ics={f(0): 1}, hint='1st_exact', simplify=False) == Eq(x * cos(f(x)) + f(x)**3 / 3, Rational(1, 3)) assert dsolve(eq, f(x), ics={f(0): 1}, hint='1st_exact', simplify=True) == Eq(x * cos(f(x)) + f(x)**3 / 3, Rational(1, 3)) assert solve_ics([Eq(f(x), C1 * exp(x))], [f(x)], [C1], {f(0): 1}) == { C1: 1 } assert solve_ics([Eq(f(x), C1 * sin(x) + C2 * cos(x))], [f(x)], [C1, C2], { f(0): 1, f(pi / 2): 1 }) == { C1: 1, C2: 1 } assert solve_ics([Eq(f(x), C1 * sin(x) + C2 * cos(x))], [f(x)], [C1, C2], { f(0): 1, f(x).diff(x).subs(x, 0): 1 }) == { C1: 1, C2: 1 } assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1}) == \ {C2: 1} # Some more complicated tests Refer to PR #16098 assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0, f(x).diff(x).subs(x, 1):0})) == \ {Eq(f(x), 0), Eq(f(x), x ** 3 / 6 - x / 2)} assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0})) == \ {Eq(f(x), 0), Eq(f(x), C2*x + x**3/6)} K, r, f0 = symbols('K r f0') sol = Eq( f(x), K * f0 * exp(r * x) / ((-K + f0) * (f0 * exp(r * x) / (-K + f0) - 1))) assert (dsolve(Eq(f(x).diff(x), r * f(x) * (1 - f(x) / K)), f(x), ics={f(0): f0})) == sol #Order dependent issues Refer to PR #16098 assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(x).diff(x).subs(x,0):0, f(0):0})) == \ {Eq(f(x), 0), Eq(f(x), x ** 3 / 6)} assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0, f(x).diff(x).subs(x,0):0})) == \ {Eq(f(x), 0), Eq(f(x), x ** 3 / 6)} # XXX: Ought to be ValueError raises( ValueError, lambda: solve_ics([Eq(f(x), C1 * sin(x) + C2 * cos(x))], [f(x)], [C1, C2], { f(0): 1, f(pi): 1 })) # Degenerate case. f'(0) is identically 0. raises( ValueError, lambda: solve_ics([Eq(f(x), sqrt(C1 - x**2))], [f(x)], [C1], {f(x).diff(x).subs(x, 0): 0})) EI, q, L = symbols('EI q L') # eq = Eq(EI*diff(f(x), x, 4), q) sols = [ Eq(f(x), C1 + C2 * x + C3 * x**2 + C4 * x**3 + q * x**4 / (24 * EI)) ] funcs = [f(x)] constants = [C1, C2, C3, C4] # Test both cases, Derivative (the default from f(x).diff(x).subs(x, L)), # and Subs ics1 = { f(0): 0, f(x).diff(x).subs(x, 0): 0, f(L).diff(L, 2): 0, f(L).diff(L, 3): 0 } ics2 = { f(0): 0, f(x).diff(x).subs(x, 0): 0, Subs(f(x).diff(x, 2), x, L): 0, Subs(f(x).diff(x, 3), x, L): 0 } solved_constants1 = solve_ics(sols, funcs, constants, ics1) solved_constants2 = solve_ics(sols, funcs, constants, ics2) assert solved_constants1 == solved_constants2 == { C1: 0, C2: 0, C3: L**2 * q / (4 * EI), C4: -L * q / (6 * EI) }
def test_shiftedgompertz(): b = Symbol("b", positive=True) eta = Symbol("eta", positive=True) X = ShiftedGompertz("x", b, eta) assert density(X)(x) == b * (eta * (1 - exp(-b * x)) + 1) * exp( -b * x) * exp(-eta * exp(-b * x))
def test_dsolve_options(): eq = x * f(x).diff(x) + f(x) a = dsolve(eq, hint='all') b = dsolve(eq, hint='all', simplify=False) c = dsolve(eq, hint='all_Integral') keys = [ '1st_exact', '1st_exact_Integral', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_homogeneous_coeff_subs_dep_div_indep_Integral', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear', '1st_linear_Integral', 'Bernoulli', 'Bernoulli_Integral', 'almost_linear', 'almost_linear_Integral', 'best', 'best_hint', 'default', 'lie_group', 'nth_linear_euler_eq_homogeneous', 'order', 'separable', 'separable_Integral' ] Integral_keys = [ '1st_exact_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear_Integral', 'Bernoulli_Integral', 'almost_linear_Integral', 'best', 'best_hint', 'default', 'nth_linear_euler_eq_homogeneous', 'order', 'separable_Integral' ] assert sorted(a.keys()) == keys assert a['order'] == ode_order(eq, f(x)) assert a['best'] == Eq(f(x), C1 / x) assert dsolve(eq, hint='best') == Eq(f(x), C1 / x) assert a['default'] == 'separable' assert a['best_hint'] == 'separable' assert not a['1st_exact'].has(Integral) assert not a['separable'].has(Integral) assert not a['1st_homogeneous_coeff_best'].has(Integral) assert not a['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral) assert not a['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral) assert not a['1st_linear'].has(Integral) assert a['1st_linear_Integral'].has(Integral) assert a['1st_exact_Integral'].has(Integral) assert a['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral) assert a['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral) assert a['separable_Integral'].has(Integral) assert sorted(b.keys()) == keys assert b['order'] == ode_order(eq, f(x)) assert b['best'] == Eq(f(x), C1 / x) assert dsolve(eq, hint='best', simplify=False) == Eq(f(x), C1 / x) assert b['default'] == 'separable' assert b['best_hint'] == '1st_linear' assert a['separable'] != b['separable'] assert a['1st_homogeneous_coeff_subs_dep_div_indep'] != \ b['1st_homogeneous_coeff_subs_dep_div_indep'] assert a['1st_homogeneous_coeff_subs_indep_div_dep'] != \ b['1st_homogeneous_coeff_subs_indep_div_dep'] assert not b['1st_exact'].has(Integral) assert not b['separable'].has(Integral) assert not b['1st_homogeneous_coeff_best'].has(Integral) assert not b['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral) assert not b['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral) assert not b['1st_linear'].has(Integral) assert b['1st_linear_Integral'].has(Integral) assert b['1st_exact_Integral'].has(Integral) assert b['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral) assert b['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral) assert b['separable_Integral'].has(Integral) assert sorted(c.keys()) == Integral_keys raises(ValueError, lambda: dsolve(eq, hint='notarealhint')) raises(ValueError, lambda: dsolve(eq, hint='Liouville')) assert dsolve(f(x).diff(x) - 1/f(x)**2, hint='all')['best'] == \ dsolve(f(x).diff(x) - 1/f(x)**2, hint='best') assert dsolve(f(x) + f(x).diff(x) + sin(x).diff(x) + 1, f(x), hint="1st_linear_Integral") == \ Eq(f(x), (C1 + Integral((-sin(x).diff(x) - 1)* exp(Integral(1, x)), x))*exp(-Integral(1, x)))
from numpy import inf from numpy import exp from scipy.io import savemat #from mpmath import lambertw from scipy.special import lambertw from scipy import optimize from scipy import interpolate import sympy I0, Iph, Rs, Rsh, n, I, V, Vth, V_I0, I_I0, V_n, I_n = sympy.symbols( 'I0 Iph Rs Rsh n I V Vth V_I0 I_I0 V_n I_n') #this stuff is from http://dx.doi.org/10.1016/j.solmat.2003.11.018 #symbolic representation for solar cell equation: lhs = I rhs = Iph - ((V + I * Rs) / Rsh) - I0 * (sympy.exp( (V + I * Rs) / (n * Vth)) - 1) charEqn = sympy.Eq(lhs, rhs) #isolate current term in solar cell equation #current = sympy.solve(charEqn,I) #isolate voltage term in solar cell equation #voltage = sympy.solve(charEqn,V) #isolate I0 in solar cell equation eyeNot = sympy.solve(charEqn, I0) #import matplotlib.pyplot as plt #plt.switch_backend("Qt5Agg") # the data to be fit
def test_von_mises(): mu = Symbol("mu") k = Symbol("k", positive=True) X = VonMises("x", mu, k) assert density(X)(x) == exp(k * cos(x - mu)) / (2 * pi * besseli(0, k))
def test_cse_ignore_issue_15002(): l = [w * exp(x) * exp(-z), exp(y) * exp(x) * exp(-z)] substs, reduced = cse(l, ignore=(x, )) rl = [e.subs(reversed(substs)) for e in reduced] assert rl == l
def test_moment_generating_function(): t = symbols('t', positive=True) # Symbolic tests a, b, c = symbols('a b c') mgf = moment_generating_function(Beta('x', a, b))(t) assert mgf == hyper((a, ), (a + b, ), t) mgf = moment_generating_function(Chi('x', a))(t) assert mgf == sqrt(2)*t*gamma(a/2 + S(1)/2)*\ hyper((a/2 + S(1)/2,), (S(3)/2,), t**2/2)/gamma(a/2) +\ hyper((a/2,), (S(1)/2,), t**2/2) mgf = moment_generating_function(ChiSquared('x', a))(t) assert mgf == (1 - 2 * t)**(-a / 2) mgf = moment_generating_function(Erlang('x', a, b))(t) assert mgf == (1 - t / b)**(-a) mgf = moment_generating_function(Exponential('x', a))(t) assert mgf == a / (a - t) mgf = moment_generating_function(Gamma('x', a, b))(t) assert mgf == (-b * t + 1)**(-a) mgf = moment_generating_function(Gumbel('x', a, b))(t) assert mgf == exp(b * t) * gamma(-a * t + 1) mgf = moment_generating_function(Gompertz('x', a, b))(t) assert mgf == b * exp(b) * expint(t / a, b) mgf = moment_generating_function(Laplace('x', a, b))(t) assert mgf == exp(a * t) / (-b**2 * t**2 + 1) mgf = moment_generating_function(Logistic('x', a, b))(t) assert mgf == exp(a * t) * beta(-b * t + 1, b * t + 1) mgf = moment_generating_function(Normal('x', a, b))(t) assert mgf == exp(a * t + b**2 * t**2 / 2) mgf = moment_generating_function(Pareto('x', a, b))(t) assert mgf == b * (-a * t)**b * uppergamma(-b, -a * t) mgf = moment_generating_function(QuadraticU('x', a, b))(t) assert str(mgf) == ( "(3*(t*(-4*b + (a + b)**2) + 4)*exp(b*t) - " "3*(t*(a**2 + 2*a*(b - 2) + b**2) + 4)*exp(a*t))/(t**2*(a - b)**3)") mgf = moment_generating_function(RaisedCosine('x', a, b))(t) assert mgf == pi**2 * exp(a * t) * sinh(b * t) / (b * t * (b**2 * t**2 + pi**2)) mgf = moment_generating_function(Rayleigh('x', a))(t) assert mgf == sqrt(2)*sqrt(pi)*a*t*(erf(sqrt(2)*a*t/2) + 1)\ *exp(a**2*t**2/2)/2 + 1 mgf = moment_generating_function(Triangular('x', a, b, c))(t) assert str(mgf) == ("(-2*(-a + b)*exp(c*t) + 2*(-a + c)*exp(b*t) + " "2*(b - c)*exp(a*t))/(t**2*(-a + b)*(-a + c)*(b - c))") mgf = moment_generating_function(Uniform('x', a, b))(t) assert mgf == (-exp(a * t) + exp(b * t)) / (t * (-a + b)) mgf = moment_generating_function(UniformSum('x', a))(t) assert mgf == ((exp(t) - 1) / t)**a mgf = moment_generating_function(WignerSemicircle('x', a))(t) assert mgf == 2 * besseli(1, a * t) / (a * t) # Numeric tests mgf = moment_generating_function(Beta('x', 1, 1))(t) assert mgf.diff(t).subs(t, 1) == hyper((2, ), (3, ), 1) / 2 mgf = moment_generating_function(Chi('x', 1))(t) assert mgf.diff(t).subs(t, 1) == sqrt(2) * hyper( (1, ), (S(3) / 2, ), S(1) / 2) / sqrt(pi) + hyper((S(3) / 2, ), (S(3) / 2, ), S(1) / 2) + 2 * sqrt(2) * hyper( (2, ), (S(5) / 2, ), S(1) / 2) / (3 * sqrt(pi)) mgf = moment_generating_function(ChiSquared('x', 1))(t) assert mgf.diff(t).subs(t, 1) == I mgf = moment_generating_function(Erlang('x', 1, 1))(t) assert mgf.diff(t).subs(t, 0) == 1 mgf = moment_generating_function(Exponential('x', 1))(t) assert mgf.diff(t).subs(t, 0) == 1 mgf = moment_generating_function(Gamma('x', 1, 1))(t) assert mgf.diff(t).subs(t, 0) == 1 mgf = moment_generating_function(Gumbel('x', 1, 1))(t) assert mgf.diff(t).subs(t, 0) == EulerGamma + 1 mgf = moment_generating_function(Gompertz('x', 1, 1))(t) assert mgf.diff(t).subs(t, 1) == -e * meijerg(((), (1, 1)), ((0, 0, 0), ()), 1) mgf = moment_generating_function(Laplace('x', 1, 1))(t) assert mgf.diff(t).subs(t, 0) == 1 mgf = moment_generating_function(Logistic('x', 1, 1))(t) assert mgf.diff(t).subs(t, 0) == beta(1, 1) mgf = moment_generating_function(Normal('x', 0, 1))(t) assert mgf.diff(t).subs(t, 1) == exp(S(1) / 2) mgf = moment_generating_function(Pareto('x', 1, 1))(t) assert mgf.diff(t).subs(t, 0) == expint(1, 0) mgf = moment_generating_function(QuadraticU('x', 1, 2))(t) assert mgf.diff(t).subs(t, 1) == -12 * e - 3 * exp(2) mgf = moment_generating_function(RaisedCosine('x', 1, 1))(t) assert mgf.diff(t).subs(t, 1) == -2*e*pi**2*sinh(1)/\ (1 + pi**2)**2 + e*pi**2*cosh(1)/(1 + pi**2) mgf = moment_generating_function(Rayleigh('x', 1))(t) assert mgf.diff(t).subs(t, 0) == sqrt(2) * sqrt(pi) / 2 mgf = moment_generating_function(Triangular('x', 1, 3, 2))(t) assert mgf.diff(t).subs(t, 1) == -e + exp(3) mgf = moment_generating_function(Uniform('x', 0, 1))(t) assert mgf.diff(t).subs(t, 1) == 1 mgf = moment_generating_function(UniformSum('x', 1))(t) assert mgf.diff(t).subs(t, 1) == 1 mgf = moment_generating_function(WignerSemicircle('x', 1))(t) assert mgf.diff(t).subs(t, 1) == -2*besseli(1, 1) + besseli(2, 1) +\ besseli(0, 1)
def test_postprocess(): eq = (x + 1 + exp((x + 1) / (y + 1)) + cos(y + 1)) assert cse([eq, Eq(x, z + 1), z - 2, (z + 1)*(x + 1)], postprocess=cse_main.cse_separate) == \ [[(x0, y + 1), (x2, z + 1), (x, x2), (x1, x + 1)], [x1 + exp(x1/x0) + cos(x0), z - 2, x1*x2]]
def test_tsolve_1(): a, b = symbols('ab') x, y, z = symbols('xyz') assert solve(exp(x) - 3, x) == [log(3)] assert solve((a * x + b) * (exp(x) - 3), x) == [-b / a, log(3)] assert solve(cos(x) - y, x) == [acos(y)] assert solve(2 * cos(x) - y, x) == [acos(y / 2)] raises(NotImplementedError, "solve(Eq(cos(x), sin(x)), x)") # XXX in the following test, log(2*y + 2*...) should -> log(2) + log(y +...) assert solve(exp(x) + exp(-x) - y, x) == [ -log(4) + log(2 * y + 2 * (-4 + y**2)**Rational(1, 2)), -log(4) + log(2 * y - 2 * (-4 + y**2)**Rational(1, 2)) ] assert solve(exp(x) - 3, x) == [log(3)] assert solve(Eq(exp(x), 3), x) == [log(3)] assert solve(log(x) - 3, x) == [exp(3)] assert solve(sqrt(3 * x) - 4, x) == [Rational(16, 3)] assert solve(3**(x + 2), x) == [-oo] assert solve(3**(2 - x), x) == [oo] assert solve(4 * 3**(5 * x + 2) - 7, x) == [(-log(4) - 2 * log(3) + log(7)) / (5 * log(3))] assert solve(x + 2**x, x) == [-LambertW(log(2)) / log(2)] assert solve(3*x+5+2**(-5*x+3), x) in \ [[-Rational(5,3) + LambertW(-10240*2**Rational(1,3)*log(2)/3)/(5*log(2))],\ [(-25*log(2) + 3*LambertW(-10240*2**(Rational(1, 3))*log(2)/3))/(15*log(2))]] assert solve(5*x-1+3*exp(2-7*x), x) == \ [Rational(1,5) + LambertW(-21*exp(Rational(3,5))/5)/7] assert solve(2*x+5+log(3*x-2), x) == \ [Rational(2,3) + LambertW(2*exp(-Rational(19,3))/3)/2] assert solve(3 * x + log(4 * x), x) == [LambertW(Rational(3, 4)) / 3] assert solve((2 * x + 8) * (8 + exp(x)), x) == [-4, log(8) + pi * I] assert solve(2*exp(3*x+4)-3, x) in [ [-Rational(4,3)+log(Rational(3,2))/3],\ [Rational(-4, 3) - log(2)/3 + log(3)/3]] assert solve(2 * log(3 * x + 4) - 3, x) == [(exp(Rational(3, 2)) - 4) / 3] assert solve(exp(x) + 1, x) == [pi * I] assert solve(x**2 - 2**x, x) == [2] assert solve(x**3 - 3**x, x) == [-3 / log(3) * LambertW(-log(3) / 3)] assert solve(2*(3*x+4)**5 - 6*7**(3*x+9), x) in \ [[Rational(-4,3) - 5/log(7)/3*LambertW(-7*2**Rational(4,5)*6**Rational(1,5)*log(7)/10)],\ [(-5*LambertW(-7*2**(Rational(4, 5))*6**(Rational(1, 5))*log(7)/10) - 4*log(7))/(3*log(7))], \ [-((4*log(7) + 5*LambertW(-7*2**Rational(4,5)*6**Rational(1,5)*log(7)/10))/(3*log(7)))]] assert solve(z * cos(x) - y, x) == [acos(y / z)] assert solve(z * cos(2 * x) - y, x) == [acos(y / z) / 2] assert solve(z * cos(sin(x)) - y, x) == [asin(acos(y / z))] assert solve(z * cos(x), x) == [acos(0)] assert solve(exp(x) + exp(-x) - y, x) == [ -log(4) + log(2 * y + 2 * (-4 + y**2)**(Rational(1, 2))), -log(4) + log(2 * y - 2 * (-4 + y**2)**(Rational(1, 2))) ] # issue #1409 assert solve(y - b * x / (a + x), x) == [a * y / (b - y)] assert solve(y - b * exp(a / x), x) == [a / (-log(b) + log(y))] # issue #1408 assert solve(y - b / (1 + a * x), x) == [(b - y) / (a * y)] # issue #1407 assert solve(y - a * x**b, x) == [y**(1 / b) * (1 / a)**(1 / b)] # issue #1406 assert solve(z**x - y, x) == [log(y) / log(z)] # issue #1405 assert solve(2**x - 10, x) == [log(10) / log(2)]
def test_sample_continuous(): Z = ContinuousRV(z, exp(-z), set=Interval(0, oo)) assert sample(Z) in Z.pspace.domain.set sym, val = list(Z.pspace.sample().items())[0] assert sym == Z and val in Interval(0, oo) assert density(Z)(-1) == 0
def test_ignore_order_terms(): eq = exp(x).series(x, 0, 3) + sin(y + x**3) - 1 assert cse(eq) == ([], [sin(x**3 + y) + x + x**2 / 2 + O(x**3)])
def test_piecewise(): # Test canonicalization assert Piecewise((x, x < 1), (0, True)) == Piecewise((x, x < 1), (0, True)) assert Piecewise((x, x < 1), (0, True), (1, True)) == \ Piecewise((x, x < 1), (0, True)) assert Piecewise((x, x < 1), (0, False), (-1, 1 > 2)) == \ Piecewise((x, x < 1)) assert Piecewise((x, x < 1), (0, x < 1), (0, True)) == \ Piecewise((x, x < 1), (0, True)) assert Piecewise((x, x < 1), (0, x < 2), (0, True)) == \ Piecewise((x, x < 1), (0, True)) assert Piecewise((x, x < 1), (x, x < 2), (0, True)) == \ Piecewise((x, Or(x < 1, x < 2)), (0, True)) assert Piecewise((x, x < 1), (x, x < 2), (x, True)) == x assert Piecewise((x, True)) == x # False condition is never retained assert Piecewise((x, False)) == Piecewise( (x, False), evaluate=False) == Piecewise() raises(TypeError, lambda: Piecewise(x)) assert Piecewise((x, 1)) == x # 1 and 0 are accepted as True/False raises(TypeError, lambda: Piecewise((x, 2))) raises(TypeError, lambda: Piecewise((x, x**2))) raises(TypeError, lambda: Piecewise(([1], True))) assert Piecewise(((1, 2), True)) == Tuple(1, 2) cond = (Piecewise((1, x < 0), (2, True)) < y) assert Piecewise((1, cond)) == Piecewise((1, ITE(x < 0, y > 1, y > 2))) assert Piecewise((1, x > 0), (2, And(x <= 0, x > -1))) == Piecewise( (1, x > 0), (2, x > -1)) # Test subs p = Piecewise((-1, x < -1), (x**2, x < 0), (log(x), x >= 0)) p_x2 = Piecewise((-1, x**2 < -1), (x**4, x**2 < 0), (log(x**2), x**2 >= 0)) assert p.subs(x, x**2) == p_x2 assert p.subs(x, -5) == -1 assert p.subs(x, -1) == 1 assert p.subs(x, 1) == log(1) # More subs tests p2 = Piecewise((1, x < pi), (-1, x < 2 * pi), (0, x > 2 * pi)) p3 = Piecewise((1, Eq(x, 0)), (1 / x, True)) p4 = Piecewise((1, Eq(x, 0)), (2, 1 / x > 2)) assert p2.subs(x, 2) == 1 assert p2.subs(x, 4) == -1 assert p2.subs(x, 10) == 0 assert p3.subs(x, 0.0) == 1 assert p4.subs(x, 0.0) == 1 f, g, h = symbols('f,g,h', cls=Function) pf = Piecewise((f(x), x < -1), (f(x) + h(x) + 2, x <= 1)) pg = Piecewise((g(x), x < -1), (g(x) + h(x) + 2, x <= 1)) assert pg.subs(g, f) == pf assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 0) == 1 assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 1) == 0 assert Piecewise((1, Eq(x, y)), (0, True)).subs(x, y) == 1 assert Piecewise((1, Eq(x, z)), (0, True)).subs(x, z) == 1 assert Piecewise((1, Eq(exp(x), cos(z))), (0, True)).subs(x, z) == \ Piecewise((1, Eq(exp(z), cos(z))), (0, True)) p5 = Piecewise((0, Eq(cos(x) + y, 0)), (1, True)) assert p5.subs(y, 0) == Piecewise((0, Eq(cos(x), 0)), (1, True)) assert Piecewise((-1, y < 1), (0, x < 0), (1, Eq(x, 0)), (2, True)).subs(x, 1) == Piecewise((-1, y < 1), (2, True)) assert Piecewise((1, Eq(x**2, -1)), (2, x < 0)).subs(x, I) == 1 # Test evalf assert p.evalf() == p assert p.evalf(subs={x: -2}) == -1 assert p.evalf(subs={x: -1}) == 1 assert p.evalf(subs={x: 1}) == log(1) # Test doit f_int = Piecewise((Integral(x, (x, 0, 1)), x < 1)) assert f_int.doit() == Piecewise((1 / 2, x < 1)) # Test differentiation f = x fp = x * p dp = Piecewise((0, x < -1), (2 * x, x < 0), (1 / x, x >= 0)) fp_dx = x * dp + p assert diff(p, x) == dp assert diff(f * p, x) == fp_dx # Test simple arithmetic assert x * p == fp assert x * p + p == p + x * p assert p + f == f + p assert p + dp == dp + p assert p - dp == -(dp - p) # Test power dp2 = Piecewise((0, x < -1), (4 * x**2, x < 0), (1 / x**2, x >= 0)) assert dp**2 == dp2 # Test _eval_interval f1 = x * y + 2 f2 = x * y**2 + 3 peval = Piecewise((f1, x < 0), (f2, x > 0)) peval_interval = f1.subs(x, 0) - f1.subs(x, -1) + f2.subs(x, 1) - f2.subs( x, 0) assert peval._eval_interval(x, 0, 0) == 0 assert peval._eval_interval(x, -1, 1) == peval_interval peval2 = Piecewise((f1, x < 0), (f2, True)) assert peval2._eval_interval(x, 0, 0) == 0 assert peval2._eval_interval(x, 1, -1) == -peval_interval assert peval2._eval_interval(x, -1, -2) == f1.subs(x, -2) - f1.subs(x, -1) assert peval2._eval_interval(x, -1, 1) == peval_interval assert peval2._eval_interval(x, None, 0) == peval2.subs(x, 0) assert peval2._eval_interval(x, -1, None) == -peval2.subs(x, -1) # Test integration assert p.integrate() == Piecewise((-x, x < -1), (x**3 / 3 + 4 / 3, x < 0), (x * log(x) - x + 4 / 3, True)) p = Piecewise((x, x < 1), (x**2, -1 <= x), (x, 3 < x)) assert integrate(p, (x, -2, 2)) == 5 / 6.0 assert integrate(p, (x, 2, -2)) == -5 / 6.0 p = Piecewise((0, x < 0), (1, x < 1), (0, x < 2), (1, x < 3), (0, True)) assert integrate(p, (x, -oo, oo)) == 2 p = Piecewise((x, x < -10), (x**2, x <= -1), (x, 1 < x)) assert integrate(p, (x, -2, 2)) == Undefined # Test commutativity assert isinstance(p, Piecewise) and p.is_commutative is True
def test_gumbel(): beta = Symbol("beta", positive=True) mu = Symbol("mu") x = Symbol("x") y = Symbol("y") X = Gumbel("x", beta, mu) Y = Gumbel("y", beta, mu, minimum=True) assert density(X)(x).expand() == \ exp(mu/beta)*exp(-x/beta)*exp(-exp(mu/beta)*exp(-x/beta))/beta assert density(Y)(y).expand() == \ exp(-mu/beta)*exp(y/beta)*exp(-exp(-mu/beta)*exp(y/beta))/beta assert cdf(X)(x).expand() == \ exp(-exp(mu/beta)*exp(-x/beta))
def test_issue_18482(): assert limit((2 * exp(3 * x) / (exp(2 * x) + 1))**(1 / x), x, oo) == exp(1)
def s(x, y): return sp.exp(x)
def test_issue_17792(): assert limit(factorial(n) / sqrt(n) * (exp(1) / n)**n, n, oo) == sqrt(2) * sqrt(pi)
def test_issue_18992(): assert limit(n / (factorial(n)**(1 / n)), n, oo) == exp(1)
def test_issue_16222(): assert limit(exp(x), x, 1000000000) == exp(1000000000)
def test_issue_18378(): assert limit(log(exp(3 * x) + x) / log(exp(x) + x**100), x, oo) == 3
def test_issue_14556(): assert limit( factorial(n + 1)**(1 / (n + 1)) - factorial(n)**(1 / n), n, oo) == exp(-1)
def test_issue_16714(): assert limit(((x**(x + 1) + (x + 1)**x) / x**(x + 1))**x, x, oo) == exp(exp(1))