def test_issue_1888(): f = Function('f') assert integrate(f(x).diff(x)**2, x).has(Integral)
def test_big_expr(): f = Function('f') x = symbols('x') e1 = Dagger( AntiCommutator( Operator('A') + Operator('B'), Pow(DifferentialOperator(Derivative(f(x), x), f(x)), 3)) * TensorProduct(Jz**2, Operator('A') + Operator('B'))) * (JzBra(1, 0) + JzBra( 1, 1)) * (JzKet(0, 0) + JzKet(1, -1)) e2 = Commutator(Jz**2, Operator('A') + Operator('B')) * AntiCommutator( Dagger(Operator('C') * Operator('D')), Operator('E').inv()**2) * Dagger(Commutator(Jz, J2)) e3 = Wigner3j(1, 2, 3, 4, 5, 6) * TensorProduct( Commutator( Operator('A') + Dagger(Operator('B')), Operator('C') + Operator('D')), Jz - J2) * Dagger( OuterProduct(Dagger(JzBra(1, 1)), JzBra( 1, 0))) * TensorProduct( JzKetCoupled(1, 1, (1, 1)) + JzKetCoupled(1, 0, (1, 1)), JzKetCoupled(1, -1, (1, 1))) e4 = (ComplexSpace(1) * ComplexSpace(2) + FockSpace()**2) * (L2(Interval(0, oo)) + HilbertSpace()) assert str( e1 ) == '(Jz**2)x(Dagger(A) + Dagger(B))*{Dagger(DifferentialOperator(Derivative(f(x), x),f(x)))**3,Dagger(A) + Dagger(B)}*(<1,0| + <1,1|)*(|0,0> + |1,-1>)' ascii_str = \ """\ / 3 \\ \n\ |/ +\\ | \n\ 2 / + +\\ <| /d \\ | + +> \n\ /J \\ x \\A + B /*||DifferentialOperator|--(f(x)),f(x)| | ,A + B |*(<1,0| + <1,1|)*(|0,0> + |1,-1>)\n\ \\ z/ \\\\ \\dx / / / \ """ ucode_str = \ """\ ⎧ 3 ⎫ \n\ ⎪⎛ †⎞ ⎪ \n\ 2 ⎛ † †⎞ ⎨⎜ ⎛d ⎞ ⎟ † †⎬ \n\ ⎛J ⎞ ⨂ ⎝A + B ⎠⋅⎪⎜DifferentialOperator⎜──(f(x)),f(x)⎟ ⎟ ,A + B ⎪⋅(⟨1,0❘ + ⟨1,1❘)⋅(❘0,0⟩ + ❘1,-1⟩)\n\ ⎝ z⎠ ⎩⎝ ⎝dx ⎠ ⎠ ⎭ \ """ assert pretty(e1) == ascii_str assert upretty(e1) == ucode_str assert latex(e1) == \ r'{J_z^{2}}\otimes \left({A^{\dagger} + B^{\dagger}}\right) \left\{\left(DifferentialOperator\left(\frac{d}{d x} f{\left(x \right)},f{\left(x \right)}\right)^{\dagger}\right)^{3},A^{\dagger} + B^{\dagger}\right\} \left({\left\langle 1,0\right|} + {\left\langle 1,1\right|}\right) \left({\left|0,0\right\rangle } + {\left|1,-1\right\rangle }\right)' sT( e1, "Mul(TensorProduct(Pow(JzOp(Symbol('J')), Integer(2)), Add(Dagger(Operator(Symbol('A'))), Dagger(Operator(Symbol('B'))))), AntiCommutator(Pow(Dagger(DifferentialOperator(Derivative(Function('f')(Symbol('x')), Tuple(Symbol('x'), Integer(1))),Function('f')(Symbol('x')))), Integer(3)),Add(Dagger(Operator(Symbol('A'))), Dagger(Operator(Symbol('B'))))), Add(JzBra(Integer(1),Integer(0)), JzBra(Integer(1),Integer(1))), Add(JzKet(Integer(0),Integer(0)), JzKet(Integer(1),Integer(-1))))" ) assert str(e2) == '[Jz**2,A + B]*{E**(-2),Dagger(D)*Dagger(C)}*[J2,Jz]' ascii_str = \ """\ [ 2 ] / -2 + +\\ [ 2 ]\n\ [/J \\ ,A + B]*<E ,D *C >*[J ,J ]\n\ [\\ z/ ] \\ / [ z]\ """ ucode_str = \ """\ ⎡ 2 ⎤ ⎧ -2 † †⎫ ⎡ 2 ⎤\n\ ⎢⎛J ⎞ ,A + B⎥⋅⎨E ,D ⋅C ⎬⋅⎢J ,J ⎥\n\ ⎣⎝ z⎠ ⎦ ⎩ ⎭ ⎣ z⎦\ """ assert pretty(e2) == ascii_str assert upretty(e2) == ucode_str assert latex(e2) == \ r'\left[J_z^{2},A + B\right] \left\{E^{-2},D^{\dagger} C^{\dagger}\right\} \left[J^2,J_z\right]' sT( e2, "Mul(Commutator(Pow(JzOp(Symbol('J')), Integer(2)),Add(Operator(Symbol('A')), Operator(Symbol('B')))), AntiCommutator(Pow(Operator(Symbol('E')), Integer(-2)),Mul(Dagger(Operator(Symbol('D'))), Dagger(Operator(Symbol('C'))))), Commutator(J2Op(Symbol('J')),JzOp(Symbol('J'))))" ) assert str(e3) == \ "Wigner3j(1, 2, 3, 4, 5, 6)*[Dagger(B) + A,C + D]x(-J2 + Jz)*|1,0><1,1|*(|1,0,j1=1,j2=1> + |1,1,j1=1,j2=1>)x|1,-1,j1=1,j2=1>" ascii_str = \ """\ [ + ] / 2 \\ \n\ /1 3 5\\*[B + A,C + D]x |- J + J |*|1,0><1,1|*(|1,0,j1=1,j2=1> + |1,1,j1=1,j2=1>)x |1,-1,j1=1,j2=1>\n\ | | \\ z/ \n\ \\2 4 6/ \ """ ucode_str = \ """\ ⎡ † ⎤ ⎛ 2 ⎞ \n\ ⎛1 3 5⎞⋅⎣B + A,C + D⎦⨂ ⎜- J + J ⎟⋅❘1,0⟩⟨1,1❘⋅(❘1,0,j₁=1,j₂=1⟩ + ❘1,1,j₁=1,j₂=1⟩)⨂ ❘1,-1,j₁=1,j₂=1⟩\n\ ⎜ ⎟ ⎝ z⎠ \n\ ⎝2 4 6⎠ \ """ assert pretty(e3) == ascii_str assert upretty(e3) == ucode_str assert latex(e3) == \ r'\left(\begin{array}{ccc} 1 & 3 & 5 \\ 2 & 4 & 6 \end{array}\right) {\left[B^{\dagger} + A,C + D\right]}\otimes \left({- J^2 + J_z}\right) {\left|1,0\right\rangle }{\left\langle 1,1\right|} \left({{\left|1,0,j_{1}=1,j_{2}=1\right\rangle } + {\left|1,1,j_{1}=1,j_{2}=1\right\rangle }}\right)\otimes {{\left|1,-1,j_{1}=1,j_{2}=1\right\rangle }}' sT( e3, "Mul(Wigner3j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6)), TensorProduct(Commutator(Add(Dagger(Operator(Symbol('B'))), Operator(Symbol('A'))),Add(Operator(Symbol('C')), Operator(Symbol('D')))), Add(Mul(Integer(-1), J2Op(Symbol('J'))), JzOp(Symbol('J')))), OuterProduct(JzKet(Integer(1),Integer(0)),JzBra(Integer(1),Integer(1))), TensorProduct(Add(JzKetCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1)))), JzKetCoupled(Integer(1),Integer(1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))), JzKetCoupled(Integer(1),Integer(-1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))))" ) assert str(e4) == '(C(1)*C(2)+F**2)*(L2(Interval(0, oo))+H)' ascii_str = \ """\ // 1 2\\ x2\\ / 2 \\\n\ \\\\C x C / + F / x \\L + H/\ """ ucode_str = \ """\ ⎛⎛ 1 2⎞ ⨂2⎞ ⎛ 2 ⎞\n\ ⎝⎝C ⨂ C ⎠ ⊕ F ⎠ ⨂ ⎝L ⊕ H⎠\ """ assert pretty(e4) == ascii_str assert upretty(e4) == ucode_str assert latex(e4) == \ r'\left(\left(\mathcal{C}^{1}\otimes \mathcal{C}^{2}\right)\oplus {\mathcal{F}}^{\otimes 2}\right)\otimes \left({\mathcal{L}^2}\left( \left[0, \infty\right) \right)\oplus \mathcal{H}\right)' sT( e4, "TensorProductHilbertSpace((DirectSumHilbertSpace(TensorProductHilbertSpace(ComplexSpace(Integer(1)),ComplexSpace(Integer(2))),TensorPowerHilbertSpace(FockSpace(),Integer(2)))),(DirectSumHilbertSpace(L2(Interval(Integer(0), oo, false, true)),HilbertSpace())))" )
def test_substitute_dummies_new_indices(): i, j = symbols('i j', below_fermi=True, cls=Dummy) a, b = symbols('a b', above_fermi=True, cls=Dummy) p, q = symbols('p q', cls=Dummy) f = Function('f') assert substitute_dummies(f(i, a, p) - f(j, b, q), new_indices=True) == 0
def test_derivative_subs_self_bug(): f = Function('f') d = diff(f(x), x) assert d.subs(d, y) == y
from IPython.display import display import sympy from sympy import Function, dsolve, Symbol # symbols t = Symbol('t', positive=True) m = Symbol('m', positive=True) k = Symbol('k', positive=True) c = Symbol('c', positive=True) # unknown function u = Function('u')(t) # solving ODE sol = dsolve(m * u.diff(t, t) + c * u.diff(t) + k * u) # sol.lhs ==> u(t) # sol.rhs ==> solution display(sol.rhs)
def test_karr_convention(): # Test the Karr summation convention that we want to hold. # See his paper "Summation in Finite Terms" for a detailed # reasoning why we really want exactly this definition. # The convention is described on page 309 and essentially # in section 1.4, definition 3: # # \sum_{m <= i < n} f(i) 'has the obvious meaning' for m < n # \sum_{m <= i < n} f(i) = 0 for m = n # \sum_{m <= i < n} f(i) = - \sum_{n <= i < m} f(i) for m > n # # It is important to note that he defines all sums with # the upper limit being *exclusive*. # In contrast, sympy and the usual mathematical notation has: # # sum_{i = a}^b f(i) = f(a) + f(a+1) + ... + f(b-1) + f(b) # # with the upper limit *inclusive*. So translating between # the two we find that: # # \sum_{m <= i < n} f(i) = \sum_{i = m}^{n-1} f(i) # # where we intentionally used two different ways to typeset the # sum and its limits. i = Symbol("i", integer=True) k = Symbol("k", integer=True) j = Symbol("j", integer=True) # A simple example with a concrete summand and symbolic limits. # The normal sum: m = k and n = k + j and therefore m < n: m = k n = k + j a = m b = n - 1 S1 = Sum(i**2, (i, a, b)).doit() # The reversed sum: m = k + j and n = k and therefore m > n: m = k + j n = k a = m b = n - 1 S2 = Sum(i**2, (i, a, b)).doit() assert simplify(S1 + S2) == 0 # Test the empty sum: m = k and n = k and therefore m = n: m = k n = k a = m b = n - 1 Sz = Sum(i**2, (i, a, b)).doit() assert Sz == 0 # Another example this time with an unspecified summand and # numeric limits. (We can not do both tests in the same example.) f = Function("f") # The normal sum with m < n: m = 2 n = 11 a = m b = n - 1 S1 = Sum(f(i), (i, a, b)).doit() # The reversed sum with m > n: m = 11 n = 2 a = m b = n - 1 S2 = Sum(f(i), (i, a, b)).doit() assert simplify(S1 + S2) == 0 # Test the empty sum with m = n: m = 5 n = 5 a = m b = n - 1 Sz = Sum(f(i), (i, a, b)).doit() assert Sz == 0 e = Piecewise((exp(-i), Mod(i, 2) > 0), (0, True)) s = Sum(e, (i, 0, 11)) assert s.n(3) == s.doit().n(3)
def test_deriv1(): f = Function('f') g = Function('g') x = Symbol('x') # this is a place where the polys12 Pure() symbol could be used rather than unique dummies assert str(f(g(x)).diff(x)) == 'D(f(_u), _u)*D(g(x), x)'
def test_function(): f = Function('f') l, x = map(Symbol, 'lx') assert exp(l(x))*l(x)/exp(l(x)) == l(x) assert exp(f(x))*f(x)/exp(f(x)) == f(x)
from sympy.utilities.pytest import raises, skip, XFAIL from sympy.external import import_module from sympy import (Symbol, Mul, Add, Eq, Abs, sin, asin, cos, Pow, csc, sec, Limit, oo, Derivative, Integral, factorial, sqrt, root, StrictLessThan, LessThan, StrictGreaterThan, GreaterThan, Sum, Product, E, log, tan, Function) from sympy.abc import x, y, z, a, b, c, t, k, n antlr4 = import_module("antlr4") # disable tests if antlr4-python*-runtime is not present if not antlr4: disabled = True theta = Symbol('theta') f = Function('f') # shorthand definitions def _Add(a, b): return Add(a, b, evaluate=False) def _Mul(a, b): return Mul(a, b, evaluate=False) def _Pow(a, b): return Pow(a, b, evaluate=False)
def test_separatevars(): x, y, z, n = symbols('x,y,z,n') assert separatevars(2*n*x*z + 2*x*y*z) == 2*x*z*(n + y) assert separatevars(x*z + x*y*z) == x*z*(1 + y) assert separatevars(pi*x*z + pi*x*y*z) == pi*x*z*(1 + y) assert separatevars(x*y**2*sin(x) + x*sin(x)*sin(y)) == \ x*(sin(y) + y**2)*sin(x) assert separatevars(x*exp(x + y) + x*exp(x)) == x*(1 + exp(y))*exp(x) assert separatevars((x*(y + 1))**z).is_Pow # != x**z*(1 + y)**z assert separatevars(1 + x + y + x*y) == (x + 1)*(y + 1) assert separatevars(y/pi*exp(-(z - x)/cos(n))) == \ y*exp(x/cos(n))*exp(-z/cos(n))/pi assert separatevars((x + y)*(x - y) + y**2 + 2*x + 1) == (x + 1)**2 # issue 4858 p = Symbol('p', positive=True) assert separatevars(sqrt(p**2 + x*p**2)) == p*sqrt(1 + x) assert separatevars(sqrt(y*(p**2 + x*p**2))) == p*sqrt(y*(1 + x)) assert separatevars(sqrt(y*(p**2 + x*p**2)), force=True) == \ p*sqrt(y)*sqrt(1 + x) # issue 4865 assert separatevars(sqrt(x*y)).is_Pow assert separatevars(sqrt(x*y), force=True) == sqrt(x)*sqrt(y) # issue 4957 # any type sequence for symbols is fine assert separatevars(((2*x + 2)*y), dict=True, symbols=()) == \ {'coeff': 1, x: 2*x + 2, y: y} # separable assert separatevars(((2*x + 2)*y), dict=True, symbols=[x]) == \ {'coeff': y, x: 2*x + 2} assert separatevars(((2*x + 2)*y), dict=True, symbols=[]) == \ {'coeff': 1, x: 2*x + 2, y: y} assert separatevars(((2*x + 2)*y), dict=True) == \ {'coeff': 1, x: 2*x + 2, y: y} assert separatevars(((2*x + 2)*y), dict=True, symbols=None) == \ {'coeff': y*(2*x + 2)} # not separable assert separatevars(3, dict=True) is None assert separatevars(2*x + y, dict=True, symbols=()) is None assert separatevars(2*x + y, dict=True) is None assert separatevars(2*x + y, dict=True, symbols=None) == {'coeff': 2*x + y} # issue 4808 n, m = symbols('n,m', commutative=False) assert separatevars(m + n*m) == (1 + n)*m assert separatevars(x + x*n) == x*(1 + n) # issue 4910 f = Function('f') assert separatevars(f(x) + x*f(x)) == f(x) + x*f(x) # a noncommutable object present eq = x*(1 + hyper((), (), y*z)) assert separatevars(eq) == eq s = separatevars(abs(x*y)) assert s == abs(x)*abs(y) and s.is_Mul z = cos(1)**2 + sin(1)**2 - 1 a = abs(x*z) s = separatevars(a) assert not a.is_Mul and s.is_Mul and s == abs(x)*abs(z) s = separatevars(abs(x*y*z)) assert s == abs(x)*abs(y)*abs(z) # abs(x+y)/abs(z) would be better but we test this here to # see that it doesn't raise assert separatevars(abs((x+y)/z)) == abs((x+y)/z)
def test_simplify_expr(): x, y, z, k, n, m, w, s, A = symbols('x,y,z,k,n,m,w,s,A') f = Function('f') assert all(simplify(tmp) == tmp for tmp in [I, E, oo, x, -x, -oo, -E, -I]) e = 1/x + 1/y assert e != (x + y)/(x*y) assert simplify(e) == (x + y)/(x*y) e = A**2*s**4/(4*pi*k*m**3) assert simplify(e) == e e = (4 + 4*x - 2*(2 + 2*x))/(2 + 2*x) assert simplify(e) == 0 e = (-4*x*y**2 - 2*y**3 - 2*x**2*y)/(x + y)**2 assert simplify(e) == -2*y e = -x - y - (x + y)**(-1)*y**2 + (x + y)**(-1)*x**2 assert simplify(e) == -2*y e = (x + x*y)/x assert simplify(e) == 1 + y e = (f(x) + y*f(x))/f(x) assert simplify(e) == 1 + y e = (2 * (1/n - cos(n * pi)/n))/pi assert simplify(e) == (-cos(pi*n) + 1)/(pi*n)*2 e = integrate(1/(x**3 + 1), x).diff(x) assert simplify(e) == 1/(x**3 + 1) e = integrate(x/(x**2 + 3*x + 1), x).diff(x) assert simplify(e) == x/(x**2 + 3*x + 1) f = Symbol('f') A = Matrix([[2*k - m*w**2, -k], [-k, k - m*w**2]]).inv() assert simplify((A*Matrix([0, f]))[1]) == \ -f*(2*k - m*w**2)/(k**2 - (k - m*w**2)*(2*k - m*w**2)) f = -x + y/(z + t) + z*x/(z + t) + z*a/(z + t) + t*x/(z + t) assert simplify(f) == (y + a*z)/(z + t) # issue 10347 expr = -x*(y**2 - 1)*(2*y**2*(x**2 - 1)/(a*(x**2 - y**2)**2) + (x**2 - 1) /(a*(x**2 - y**2)))/(a*(x**2 - y**2)) + x*(-2*x**2*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(a*(x**2 - y**2)**2) - x**2*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(a*(x**2 - 1)*(x**2 - y**2)) + (x**2*sqrt((-x**2 + 1)* (y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(x**2 - 1) + sqrt( (-x**2 + 1)*(y**2 - 1))*(x*(-x*y**2 + x)/sqrt(-x**2*y**2 + x**2 + y**2 - 1) + sqrt(-x**2*y**2 + x**2 + y**2 - 1))*sin(z))/(a*sqrt((-x**2 + 1)*( y**2 - 1))*(x**2 - y**2)))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(a* (x**2 - y**2)) + x*(-2*x**2*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(a* (x**2 - y**2)**2) - x**2*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(a* (x**2 - 1)*(x**2 - y**2)) + (x**2*sqrt((-x**2 + 1)*(y**2 - 1))*sqrt(-x**2 *y**2 + x**2 + y**2 - 1)*cos(z)/(x**2 - 1) + x*sqrt((-x**2 + 1)*(y**2 - 1))*(-x*y**2 + x)*cos(z)/sqrt(-x**2*y**2 + x**2 + y**2 - 1) + sqrt((-x**2 + 1)*(y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z))/(a*sqrt((-x**2 + 1)*(y**2 - 1))*(x**2 - y**2)))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos( z)/(a*(x**2 - y**2)) - y*sqrt((-x**2 + 1)*(y**2 - 1))*(-x*y*sqrt(-x**2* y**2 + x**2 + y**2 - 1)*sin(z)/(a*(x**2 - y**2)*(y**2 - 1)) + 2*x*y*sqrt( -x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(a*(x**2 - y**2)**2) + (x*y*sqrt(( -x**2 + 1)*(y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(y**2 - 1) + x*sqrt((-x**2 + 1)*(y**2 - 1))*(-x**2*y + y)*sin(z)/sqrt(-x**2*y**2 + x**2 + y**2 - 1))/(a*sqrt((-x**2 + 1)*(y**2 - 1))*(x**2 - y**2)))*sin( z)/(a*(x**2 - y**2)) + y*(x**2 - 1)*(-2*x*y*(x**2 - 1)/(a*(x**2 - y**2) **2) + 2*x*y/(a*(x**2 - y**2)))/(a*(x**2 - y**2)) + y*(x**2 - 1)*(y**2 - 1)*(-x*y*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(a*(x**2 - y**2)*(y**2 - 1)) + 2*x*y*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(a*(x**2 - y**2) **2) + (x*y*sqrt((-x**2 + 1)*(y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(y**2 - 1) + x*sqrt((-x**2 + 1)*(y**2 - 1))*(-x**2*y + y)*cos( z)/sqrt(-x**2*y**2 + x**2 + y**2 - 1))/(a*sqrt((-x**2 + 1)*(y**2 - 1) )*(x**2 - y**2)))*cos(z)/(a*sqrt((-x**2 + 1)*(y**2 - 1))*(x**2 - y**2) ) - x*sqrt((-x**2 + 1)*(y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin( z)**2/(a**2*(x**2 - 1)*(x**2 - y**2)*(y**2 - 1)) - x*sqrt((-x**2 + 1)*( y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)**2/(a**2*(x**2 - 1)*( x**2 - y**2)*(y**2 - 1)) assert simplify(expr) == 2*x/(a**2*(x**2 - y**2)) A, B = symbols('A,B', commutative=False) assert simplify(A*B - B*A) == A*B - B*A assert simplify(A/(1 + y/x)) == x*A/(x + y) assert simplify(A*(1/x + 1/y)) == A/x + A/y #(x + y)*A/(x*y) assert simplify(log(2) + log(3)) == log(6) assert simplify(log(2*x) - log(2)) == log(x) assert simplify(hyper([], [], x)) == exp(x)
return sqrt(x**2 + y**2 + sigma**2) mydfdx = x / sqrt(r**2 + sigma**2) print diff(phi(x, y, sigma), x) print mydfdx - diff(phi(x, y, sigma), x) from sympy import integrate print integrate(2 * x, (x, 0, 1)) print float(integrate(x**2, (x, 0, 2))) print integrate(x**2, x) from sympy import Symbol, dsolve, Function, Derivative, Eq y = Function("y") x = Symbol('x') y_ = Derivative(y(x), x) print dsolve(y_ + 5 * y(x), y(x)) print dsolve(Eq(y_ + 5 * y(x), 0), y(x)) print dsolve(Eq(y_ + 5 * y(x), 12), y(x)) z = dsolve(y_ + 5 * y(x), y(x)) print print z print z.rhs print C1 = Symbol('C1') y3 = z.subs({C1: 2, x: 3}) print print y3 print y3.evalf(10)
def test_2d_scalar_3(): print('============== test_2d_scalar_3 ================') x, y = symbols('x y') u = Symbol('u') v = Symbol('v') b = Function('b') a = Lambda((x, y, v, u), Dot(Grad(u), Grad(v)) + b(x, y) * u * v) print('> input := {0}'.format(a)) # ... create a finite element space p1 = 2 p2 = 2 ne1 = 8 ne2 = 8 print('> Grid :: [{ne1},{ne2}]'.format(ne1=ne1, ne2=ne2)) print('> Degree :: [{p1},{p2}]'.format(p1=p1, p2=p2)) grid_1 = linspace(0., 1., ne1 + 1) grid_2 = linspace(0., 1., ne2 + 1) V1 = SplineSpace(p1, grid=grid_1) V2 = SplineSpace(p2, grid=grid_2) V = TensorFemSpace(V1, V2) # ... # ... create a glt symbol from a string without evaluation expr = glt_symbol(a, space=V) print('> glt symbol := {0}'.format(expr)) # ... # ... user defined function def b(x, y): r = 1. + x * y return r # ... # ... create an interactive pyccel context from pyccel.epyccel import ContextPyccel context = ContextPyccel(name='context_scalar_3') context.insert_function(b, ['double', 'double'], kind='function', results=['double']) context.compile() # ... # ... symbol_f90 = compile_symbol('symbol_scalar_3', a, V, context=context, backend='fortran') # ... # ... example of symbol evaluation t1 = linspace(-pi, pi, ne1 + 1) t2 = linspace(-pi, pi, ne2 + 1) x1 = linspace(0., 1., ne1 + 1) x2 = linspace(0., 1., ne2 + 1) e = zeros((ne1 + 1, ne2 + 1), order='F') symbol_f90(x1, x2, t1, t2, e) # ... print('')
def test_issue_4754_derivative_conjugate(): x = Symbol('x', real=True) y = Symbol('y', imaginary=True) f = Function('f') assert (f(x).conjugate()).diff(x) == (f(x).diff(x)).conjugate() assert (f(y).conjugate()).diff(y) == -(f(y).diff(y)).conjugate()
def test_latex_printer(): r = Function('r')('t') assert VectorLatexPrinter().doprint(r**2) == "r^{2}"
def test_var(self): from sympy.abc import x, y, z m = Function('m', commutative=False) n = Function('n', commutative=False) g = Function('g') assert Expect(Bind(Bind(Lebesgue(3,6), x, m(x)), y, n(y)), Lambda(z, g(z))).dummy_eq(integrate(Expect(m(x), Lambda(y, Expect(n(y), Lambda(z, g(z))))), (x,3,6)))
# systems of differential equations # notice solving systems of differential equations in sympy require the # sympy version 0.7.6 import numpy as np import sympy from sympy.abc import t, a, C from sympy import Function, Derivative, dsolve, Eq, solve import matplotlib.pyplot as plt import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D y1 = Function('y1') y2 = Function('y2') eqs = [ Eq(y1(t).diff(t), y1(t) + 2 * y2(t)), Eq(y2(t).diff(t), -2 * y1(t) + y2(t) + 2 * sympy.exp(t)) ] s = dsolve(eqs) # fox and rabbit example R = Function('R') F = Function('F') formulaR = 2 * R(t) - 1.2 * R(t) * F(t) formulaF = -1 * F(t) + 0.9 * R(t) * F(t) eqs = [Eq(Derivative(R(t), t), formulaR), Eq(Derivative(F(t), t), formulaF)] # try numerical method
class Bind(Function('Bind', nargs=3, commutative=False)): def __new__(cls, before, variable, after): if not variable.is_symbol: variable = Symbol(variable) return Expr.__new__(cls, sympify(before), variable, sympify(after, {variable.name: variable})) @property def before(self): return self._args[0] def enter(self, avoid): # Rename self.variable in self.after to avoid free_symbols var = self._args[1] aft = self._args[2] if isinstance(self._args[0], Lebesgue): x = Dummy(var.name, real = True, positive = self._args[0].lower >= 0 and self._args[0].upper >= 0, negative = self._args[0].lower <= 0 and self._args[0].upper <= 0) return (x, aft.subs(var, x)) elif isinstance(self._args[0], Counting): x = Dummy(var.name, integer = True, positive = self._args[0].lower >= 0 and self._args[0].upper >= 0, negative = self._args[0].lower <= 0 and self._args[0].upper <= 0) x = Idx(x, self._args[0].lower, self._args[0].upper) return (x, aft.subs(var, x)) elif any(self.variable in object.free_symbols for object in avoid): x = Dummy(var.name) return (x, aft.subs(var, x)) else: return (var, aft) @property def variable(self): return self._args[1] @property def after(self): return self._args[2] @property def bound_symbols(self): return (self.variable,) @property def free_symbols(self): return (self.before.free_symbols | (self.after.free_symbols - {self.variable})) def _eval_subs(self, old, new, **hints): if self.variable == old: new_before = self.before._subs(old, new, **hints) if new_before == None: return None else: return self.func(new_before, self.variable, self.after) else: return None
def test_distribution_over_equality(): f = Function('f') assert Product(Eq(x*2, f(x)), (x, 1, 3)).doit() == Eq(48, f(1)*f(2)*f(3)) assert Sum(Eq(f(x), x**2), (x, 0, y)) == \ Eq(Sum(f(x), (x, 0, y)), Sum(x**2, (x, 0, y)))
def ham(p, q): p, q, v, mass = symbols("p q v mass") v = Function("v") return Operator(lin_mom(q, 2) / (2 * mass)) + Operator(v(q))
def test_function_nargs(): f = Function('f') x = Symbol('x') assert f.nargs == None assert f(x).nargs == 1 assert f(x, x, x, x).nargs == 4
def time_deriv1(var, order=1): pq_s = Symbol("pq_s") aux = Operator(Function("f")(q)) pq_s = (Operator(p) * Operator(q) + Operator(q) * Operator(p)) / 2 h1 = (expand(((Commutator(Operator(var**(order)), ham( p, q)).expand(commutator=True)) * aux).doit())) if var == V: der = f'((p)*(Derivative(V, q, {order}+1))+(Derivative(V, q, {order}+1))*(p))/2/m' if var == p: p1 = lin_mom(q, order) h1 = (str(simplify(h1)).replace("p", str(Operator(p1)))) else: h1 = str( expand(((Commutator(ham(p, q), Operator( var**(order))).expand(commutator=True)) * aux).doit())) h1 = h1.replace("pq_s", "((p*q+q*p))/2") start_points = [] end_points = [] start = 0 s = h1.find("Derivative(1, q)", start) while s != -1: s = h1.find("Derivative(1, q)", start) if var == pq_s: start = s + len(f"Derivative(1, q) ") else: start = s + len(f"Derivative(1, q)") start_points.append(s) if s == -1: break if var == pq_s: e = h1.find(" ", start + 1) else: e = h1.find("f(q)", start) + 4 end_points.append(e) if start_points[-1] == -1: start_points.remove(start_points[-1]) new_derivative_function = [] replace_spot = [] for i in range(len(start_points)): func = h1[start_points[i]:end_points[i]] func = start_points[i] + len(f"Derivative(1, q)") func1 = h1.find("*", func, end_points[i]) repl = h1[start_points[i]:end_points[i]].find("1") + start_points[i] replace_spot.append(repl) if var == p: new_func = h1[func1:end_points[i]] new_derivative_function.append(new_func) else: new_func = h1[func1 - 3:end_points[i]] new_derivative_function.append(new_func) temp = h1.split(" ") position_list = [] temp_list = [] for i in range(len(temp)): if var == p: st = 1 else: st = 0 for r in range(st, len(new_derivative_function)): if temp[i].find(new_derivative_function[r]) != -1: temp[i] = temp[i].replace(new_derivative_function[r], "") if temp[i].find("Derivative") == -1: continue else: position = temp[i].find("1,") if position != -1: position_list.append(position) temp_list.append(i) TL = len(temp_list) - 1 nested_list = [] while TL > -1: r = [temp_list[TL], position_list[TL]] nested_list.append(r) TL -= 1 if TL == -1: break nested_list.reverse() if var == p: for i in range(len(nested_list)): temp[nested_list[i][0]] = \ temp[nested_list[i][0]].replace(temp[nested_list[i][0]][nested_list[i][1]], new_derivative_function[i][1:]) else: for i in range(len(nested_list)): temp[nested_list[i][0]] = \ temp[nested_list[i][0]].replace(temp[nested_list[i][0]][nested_list[i][1]], "1/" + new_derivative_function[i][1:]) string = " ".join(temp) if "(*" in string: string = string.replace("(*", "(") s = sympify(string) s1 = expand(s.doit()) if var == p: repl = 1 if order == 2: s1 = s1 / 2 else: repl = 0 s2 = str(s1).replace("hbar*i", "1").replace("I", "1").replace( "f(q)", f"{repl}").replace(f"hbar**2*i**2*Derivative({repl}, q)", "p").replace(f"Derivative({repl}, q)", "p").replace( "hbar**2*i**2", "1").replace("Derivative(v(q), (q, 2))", "0") if var == V: return sympify(der) #/(i*hbar) else: return sympify(s2) #/(i*hbar)
def _test_f(): # FIXME: we get infinite recursion here: f = Function("f") assert residue(f(x) / x**5, x, 0) == f.diff(x, 4) / 24
def test_powsimp(): x, y, z, n = symbols('x,y,z,n') f = Function('f') assert powsimp(4**x * 2**(-x) * 2**(-x)) == 1 assert powsimp((-4)**x * (-2)**(-x) * 2**(-x)) == 1 assert powsimp(f(4**x * 2**(-x) * 2**(-x))) == f(4**x * 2**(-x) * 2**(-x)) assert powsimp(f(4**x * 2**(-x) * 2**(-x)), deep=True) == f(1) assert exp(x) * exp(y) == exp(x) * exp(y) assert powsimp(exp(x) * exp(y)) == exp(x + y) assert powsimp(exp(x) * exp(y) * 2**x * 2**y) == (2 * E)**(x + y) assert powsimp(exp(x) * exp(y) * 2**x * 2**y, combine='exp') == exp(x + y) * 2**(x + y) assert powsimp(exp(x) * exp(y) * exp(2) * sin(x) + sin(y) + 2**x * 2**y) == exp(2 + x + y) * sin(x) + sin(y) + 2**(x + y) assert powsimp(sin(exp(x) * exp(y))) == sin(exp(x) * exp(y)) assert powsimp(sin(exp(x) * exp(y)), deep=True) == sin(exp(x + y)) assert powsimp(x**2 * x**y) == x**(2 + y) # This should remain factored, because 'exp' with deep=True is supposed # to act like old automatic exponent combining. assert powsimp((1 + E * exp(E)) * exp(-E), combine='exp', deep=True) == (1 + exp(1 + E)) * exp(-E) assert powsimp((1 + E * exp(E)) * exp(-E), deep=True) == exp(1) + exp(-E) # This should not change without deep. Otherwise, simplify() will fail. assert powsimp((1 + E * exp(E)) * exp(-E)) == (1 + E * exp(E)) * exp(-E) assert powsimp((1 + E * exp(E)) * exp(-E), combine='exp') == (1 + E * exp(E)) * exp(-E) assert powsimp((1 + E * exp(E)) * exp(-E), combine='base') == (1 + E * exp(E)) * exp(-E) x, y = symbols('x,y', nonnegative=True) n = Symbol('n', real=True) assert powsimp(y**n * (y / x)**(-n)) == x**n assert powsimp(x**(x**(x * y) * y**(x * y)) * y**(x**(x * y) * y**(x * y)), deep=True) == (x * y)**(x * y)**(x * y) assert powsimp(2**(2**(2 * x) * x), deep=False) == 2**(2**(2 * x) * x) assert powsimp(2**(2**(2 * x) * x), deep=True) == 2**(x * 4**x) assert powsimp(exp(-x + exp(-x) * exp(-x * log(x))), deep=False, combine='exp') == exp(-x + exp(-x) * exp(-x * log(x))) assert powsimp(exp(-x + exp(-x) * exp(-x * log(x))), deep=False, combine='exp') == exp(-x + exp(-x) * exp(-x * log(x))) assert powsimp((x + y) / (3 * z), deep=False, combine='exp') == (x + y) / (3 * z) assert powsimp((x / 3 + y / 3) / z, deep=True, combine='exp') == (x / 3 + y / 3) / z assert powsimp(exp(x) / (1 + exp(x) * exp(y)), deep=True) == exp(x) / (1 + exp(x + y)) assert powsimp(x * y**(z**x * z**y), deep=True) == x * y**(z**(x + y)) assert powsimp((z**x * z**y)**x, deep=True) == (z**(x + y))**x assert powsimp(x * (z**x * z**y)**x, deep=True) == x * (z**(x + y))**x p = symbols('p', positive=True) assert powsimp((1 / x)**log(2) / x) == (1 / x)**(1 + log(2)) assert powsimp((1 / p)**log(2) / p) == p**(-1 - log(2)) # coefficient of exponent can only be simplified for positive bases assert powsimp(2**(2 * x)) == 4**x assert powsimp((-1)**(2 * x)) == (-1)**(2 * x) i = symbols('i', integer=True) assert powsimp((-1)**(2 * i)) == 1 assert powsimp((-1)**(-x)) != (-1)**x # could be 1/((-1)**x), but is not # force=True overrides assumptions assert powsimp((-1)**(2 * x), force=True) == 1
from sympy import Eq, factorial, Function, Lambda, rf, S, sqrt, symbols, I, expand_func, binomial, gamma from sympy.solvers.recurr import rsolve, rsolve_hyper, rsolve_poly, rsolve_ratio from sympy.utilities.pytest import raises from sympy.abc import a, b, c y = Function('y') n, k = symbols('n,k', integer=True) C0, C1, C2 = symbols('C0,C1,C2') def test_rsolve_poly(): assert rsolve_poly([-1, -1, 1], 0, n) == 0 assert rsolve_poly([-1, -1, 1], 1, n) == -1 assert rsolve_poly([-1, n + 1], n, n) == 1 assert rsolve_poly([-1, 1], n, n) == C0 + (n**2 - n) / 2 assert rsolve_poly([-n - 1, n], 1, n) == C1 * n - 1 assert rsolve_poly([-4 * n - 2, 1], 4 * n + 1, n) == -1 assert rsolve_poly([-1, 1], n**5 + n**3, n) == \ C0 - n**3 / 2 - n**5 / 2 + n**2 / 6 + n**6 / 6 + 2*n**4 / 3 def test_rsolve_ratio(): solution = rsolve_ratio([ -2 * n**3 + n**2 + 2 * n - 1, 2 * n**3 + n**2 - 6 * n, -2 * n**3 - 11 * n**2 - 18 * n - 9, 2 * n**3 + 13 * n**2 + 22 * n + 8 ], 0, n) assert solution in [ C1 * ((-2 * n + 3) / (n**2 - 1)) / 3,
def test_issue_1095(): # simplify should call cancel from sympy.abc import x, y f = Function('f') assert simplify((4 * x + 6 * f(y)) / (2 * x + 3 * f(y))) == 2
# [0,1/Iyy,0], # [0,0,0], # [0,0,1/Izz], # ]) # # C = Matrix([1,1,1,1,1,1]) # # # Ak = exp(A)*dt # Bk = A.inv()*(Ak-eye(len(A)))*B # # print(Bk) t = Symbol("t") x = Function("x")(t) y = Function("y")(t) z = Function("z")(t) x_dot = diff(x, t) y_dot = diff(y, t) z_dot = diff(z, t) phi = Function("phi")(t) theta = Function("theta")(t) psi = Function("psi")(t) phi_dot = diff(phi, t) theta_dot = diff(theta, t) psi_dot = diff(psi, t) #
from sympy import Rational, sqrt, symbols, sin, exp, log, sinh, cosh, cos, pi, \ I, S, erf, tan, asin, asinh, acos, acosh, Function, Derivative, diff, simplify, \ LambertW from sympy.integrals.risch import heurisch, components from sympy.utilities.pytest import XFAIL, skip, slow x, y, z = symbols('x,y,z') f = Function('f') def test_components(): assert components(x * y, x) == set([x]) assert components(1 / (x + y), x) == set([x]) assert components(sin(x), x) == set([sin(x), x]) assert components(sin(x)*sqrt(log(x)), x) == \ set([log(x), sin(x), sqrt(log(x)), x]) assert components(x*sin(exp(x)*y), x) == \ set([sin(y*exp(x)), x, exp(x)]) assert components(x**Rational(17,54)/sqrt(sin(x)), x) == \ set([sin(x), x**Rational(1,54), sqrt(sin(x)), x]) assert components(f(x), x) == \ set([x, f(x)]) assert components(Derivative(f(x),x), x) == \ set([x, f(x), Derivative(f(x), x)]) assert components(f(x)*diff(f(x), x), x) == \ set([x, f(x), Derivative(f(x), x), Derivative(f(x), x)]) def test_heurisch_polynomials(): assert heurisch(1, x) == x
def test_substitute_dummies_substitution_order(): i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy) f = Function('f') from sympy.utilities.iterables import variations for permut in variations([i, j, k, l], 4): assert substitute_dummies(f(*permut) - f(i, j, k, l)) == 0
def test_issue_4703(): g = Function('g') assert integrate(exp(x) * g(x), x).has(Integral)