我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sympy.sin()。
def __init__(self, n): self.degree = 2 self.dim = n n2 = fr(n, 2) if n % 2 == 0 else fr(n-1, 2) pts = [[ [sqrt(fr(2, n+2)) * cos(2*k*i*pi / (n+1)) for i in range(n+1)], [sqrt(fr(2, n+2)) * sin(2*k*i*pi / (n+1)) for i in range(n+1)], ] for k in range(1, n2+1)] if n % 2 == 1: sqrt3pm = numpy.full(n+1, 1/sqrt(n+2)) sqrt3pm[1::2] *= -1 pts.append(sqrt3pm) pts = numpy.vstack(pts).T data = [(fr(1, n+1), pts)] self.points, self.weights = untangle(data) self.weights *= volume_unit_ball(n) return
def test_lie_derivative(self): Lfh = pm.lie_derivatives(self.h, self.f, self.x, 0) self.assertEqual(Lfh, [self.h]) Lfh = pm.lie_derivatives(self.h, self.f, self.x, 1) self.assertEqual(Lfh, [self.h, sp.Matrix([-2*self._x1*self._x2**2 - sp.sin(self._x1)*sp.cos(self._x2)]) ]) Lfh = pm.lie_derivatives(self.h, self.f, self.x, 2) self.assertEqual(Lfh, [self.h, sp.Matrix([-2*self._x1*self._x2**2 - sp.sin(self._x1)*sp.cos(self._x2)]), sp.Matrix([ -self._x2**2*( -2*self._x2**2 - sp.cos(self._x1)*sp.cos(self._x2) ) + sp.sin(self._x1)*( - 4*self._x1*self._x2 + sp.sin(self._x1)*sp.sin(self._x2) )]) ])
def test_issue_3210(): eqs = (sin(2)*cos(3) + sin(3)*cos(2), -sin(2)*sin(3) + cos(2)*cos(3), sin(2)*cos(3) - sin(3)*cos(2), sin(2)*sin(3) + cos(2)*cos(3), sin(2)*sin(3) + cos(2)*cos(3) + cos(2), sinh(2)*cosh(3) + sinh(3)*cosh(2), sinh(2)*sinh(3) + cosh(2)*cosh(3), ) assert [trigsimp(e) for e in eqs] == [ sin(5), cos(5), -sin(1), cos(1), cos(1) + cos(2), sinh(5), cosh(5), ]
def test_simplify_other(): assert simplify(sin(x)**2 + cos(x)**2) == 1 assert simplify(gamma(x + 1)/gamma(x)) == x assert simplify(sin(x)**2 + cos(x)**2 + factorial(x)/gamma(x)) == 1 + x assert simplify( Eq(sin(x)**2 + cos(x)**2, factorial(x)/gamma(x))) == Eq(1, x) nc = symbols('nc', commutative=False) assert simplify(x + x*nc) == x*(1 + nc) # issue 6123 # f = exp(-I*(k*sqrt(t) + x/(2*sqrt(t)))**2) # ans = integrate(f, (k, -oo, oo), conds='none') ans = I*(-pi*x*exp(-3*I*pi/4 + I*x**2/(4*t))*erf(x*exp(-3*I*pi/4)/ (2*sqrt(t)))/(2*sqrt(t)) + pi*x*exp(-3*I*pi/4 + I*x**2/(4*t))/ (2*sqrt(t)))*exp(-I*x**2/(4*t))/(sqrt(pi)*x) - I*sqrt(pi) * \ (-erf(x*exp(I*pi/4)/(2*sqrt(t))) + 1)*exp(I*pi/4)/(2*sqrt(t)) assert simplify(ans) == -(-1)**(S(3)/4)*sqrt(pi)/sqrt(t) # issue 6370 assert simplify(2**(2 + x)/4) == 2**x
def test_powsimp_polar(): from sympy import polar_lift, exp_polar x, y, z = symbols('x y z') p, q, r = symbols('p q r', polar=True) assert (polar_lift(-1))**(2*x) == exp_polar(2*pi*I*x) assert powsimp(p**x * q**x) == (p*q)**x assert p**x * (1/p)**x == 1 assert (1/p)**x == p**(-x) assert exp_polar(x)*exp_polar(y) == exp_polar(x)*exp_polar(y) assert powsimp(exp_polar(x)*exp_polar(y)) == exp_polar(x + y) assert powsimp(exp_polar(x)*exp_polar(y)*p**x*p**y) == \ (p*exp_polar(1))**(x + y) assert powsimp(exp_polar(x)*exp_polar(y)*p**x*p**y, combine='exp') == \ exp_polar(x + y)*p**(x + y) assert powsimp( exp_polar(x)*exp_polar(y)*exp_polar(2)*sin(x) + sin(y) + p**x*p**y) \ == p**(x + y) + sin(x)*exp_polar(2 + x + y) + sin(y) assert powsimp(sin(exp_polar(x)*exp_polar(y))) == \ sin(exp_polar(x)*exp_polar(y)) assert powsimp(sin(exp_polar(x)*exp_polar(y)), deep=True) == \ sin(exp_polar(x + y))
def test_collect_order(): a, b, x, t = symbols('a,b,x,t') assert collect(t + t*x + t*x**2 + O(x**3), t) == t*(1 + x + x**2 + O(x**3)) assert collect(t + t*x + x**2 + O(x**3), t) == \ t*(1 + x + O(x**3)) + x**2 + O(x**3) f = a*x + b*x + c*x**2 + d*x**2 + O(x**3) g = x*(a + b) + x**2*(c + d) + O(x**3) assert collect(f, x) == g assert collect(f, x, distribute_order_term=False) == g f = sin(a + b).series(b, 0, 10) assert collect(f, [sin(a), cos(a)]) == \ sin(a)*cos(b).series(b, 0, 10) + cos(a)*sin(b).series(b, 0, 10) assert collect(f, [sin(a), cos(a)], distribute_order_term=False) == \ sin(a)*cos(b).series(b, 0, 10).removeO() + \ cos(a)*sin(b).series(b, 0, 10).removeO() + O(b**10)
def test_besselsimp(): from sympy import besselj, besseli, besselk, bessely, jn, yn, exp_polar, cosh, cosine_transform assert besselsimp(exp(-I*pi*y/2)*besseli(y, z*exp_polar(I*pi/2))) == \ besselj(y, z) assert besselsimp(exp(-I*pi*a/2)*besseli(a, 2*sqrt(x)*exp_polar(I*pi/2))) == \ besselj(a, 2*sqrt(x)) assert besselsimp(sqrt(2)*sqrt(pi)*x**(S(1)/4)*exp(I*pi/4)*exp(-I*pi*a/2) * besseli(-S(1)/2, sqrt(x)*exp_polar(I*pi/2)) * besseli(a, sqrt(x)*exp_polar(I*pi/2))/2) == \ besselj(a, sqrt(x)) * cos(sqrt(x)) assert besselsimp(besseli(S(-1)/2, z)) == \ sqrt(2)*cosh(z)/(sqrt(pi)*sqrt(z)) assert besselsimp(besseli(a, z*exp_polar(-I*pi/2))) == \ exp(-I*pi*a/2)*besselj(a, z) assert cosine_transform(1/t*sin(a/t), t, y) == \ sqrt(2)*sqrt(pi)*besselj(0, 2*sqrt(a)*sqrt(y))/2
def test_issue_2827_trigsimp_methods(): measure1 = lambda expr: len(str(expr)) measure2 = lambda expr: -count_ops(expr) # Return the most complicated result expr = (x + 1)/(x + sin(x)**2 + cos(x)**2) ans = Matrix([1]) M = Matrix([expr]) assert trigsimp(M, method='fu', measure=measure1) == ans assert trigsimp(M, method='fu', measure=measure2) != ans # all methods should work with Basic expressions even if they # aren't Expr M = Matrix.eye(1) assert all(trigsimp(M, method=m) == M for m in 'fu matching groebner old'.split()) # watch for E in exptrigsimp, not only exp() eq = 1/sqrt(E) + E assert exptrigsimp(eq) == eq
def test_call(): x, y = symbols('x y') # See the long history of this in issues 1927 and 2006. raises(TypeError, lambda: sin(x)({ x : 1, sin(x) : 2})) raises(TypeError, lambda: sin(x)(1)) # No effect as there are no callables assert sin(x).rcall(1) == sin(x) assert (1 + sin(x)).rcall(1) == 1 + sin(x) # Effect in the pressence of callables l = Lambda(x, 2*x) assert (l + x).rcall(y) == 2*y + x assert (x**l).rcall(2) == x**4 # TODO UndefinedFunction does not subclass Expr #f = Function('f') #assert (2*f)(x) == 2*f(x) assert (Q.real & Q.positive).rcall(x) == Q.real(x) & Q.positive(x)
def test_hypersum(): from sympy import simplify, sin, hyper assert simplify(summation(x**n/fac(n), (n, 1, oo))) == -1 + exp(x) assert summation((-1)**n * x**(2*n) / fac(2*n), (n, 0, oo)) == cos(x) assert simplify(summation((-1)**n*x**(2*n + 1) / factorial(2*n + 1), (n, 3, oo))) == -x + sin(x) + x**3/6 - x**5/120 assert summation(1/(n + 2)**3, (n, 1, oo)) == -S(9)/8 + zeta(3) assert summation(1/n**4, (n, 1, oo)) == pi**4/90 s = summation(x**n*n, (n, -oo, 0)) assert s.is_Piecewise assert s.args[0].args[0] == -1/(x*(1 - 1/x)**2) assert s.args[0].args[1] == (abs(1/x) < 1) m = Symbol('n', integer=True, positive=True) assert summation(binomial(m, k), (k, 0, m)) == 2**m
def test_pend(): q, u = dynamicsymbols('q u') qd, ud = dynamicsymbols('q u', 1) m, l, g = symbols('m l g') N = ReferenceFrame('N') P = Point('P') P.set_vel(N, -l * u * sin(q) * N.x + l * u * cos(q) * N.y) kd = [qd - u] FL = [(P, m * g * N.x)] pa = Particle('pa', P, m) BL = [pa] KM = KanesMethod(N, [q], [u], kd) KM.kanes_equations(FL, BL) MM = KM.mass_matrix forcing = KM.forcing rhs = MM.inv() * forcing rhs.simplify() assert expand(rhs[0]) == expand(-g / l * sin(q))
def test_dot_different_frames(): assert dot(N.x, A.x) == cos(q1) assert dot(N.x, A.y) == -sin(q1) assert dot(N.x, A.z) == 0 assert dot(N.y, A.x) == sin(q1) assert dot(N.y, A.y) == cos(q1) assert dot(N.y, A.z) == 0 assert dot(N.z, A.x) == 0 assert dot(N.z, A.y) == 0 assert dot(N.z, A.z) == 1 assert dot(N.x, A.x + A.y) == sqrt(2)*cos(q1 + pi/4) == dot(A.x + A.y, N.x) assert dot(A.x, C.x) == cos(q3) assert dot(A.x, C.y) == 0 assert dot(A.x, C.z) == sin(q3) assert dot(A.y, C.x) == sin(q2)*sin(q3) assert dot(A.y, C.y) == cos(q2) assert dot(A.y, C.z) == -sin(q2)*cos(q3) assert dot(A.z, C.x) == -cos(q2)*sin(q3) assert dot(A.z, C.y) == sin(q2) assert dot(A.z, C.z) == cos(q2)*cos(q3)
def test_cross_different_frames(): assert cross(N.x, A.x) == sin(q1)*A.z assert cross(N.x, A.y) == cos(q1)*A.z assert cross(N.x, A.z) == -sin(q1)*A.x - cos(q1)*A.y assert cross(N.y, A.x) == -cos(q1)*A.z assert cross(N.y, A.y) == sin(q1)*A.z assert cross(N.y, A.z) == cos(q1)*A.x - sin(q1)*A.y assert cross(N.z, A.x) == A.y assert cross(N.z, A.y) == -A.x assert cross(N.z, A.z) == 0 assert cross(N.x, A.x) == sin(q1)*A.z assert cross(N.x, A.y) == cos(q1)*A.z assert cross(N.x, A.x + A.y) == sin(q1)*A.z + cos(q1)*A.z assert cross(A.x + A.y, N.x) == -sin(q1)*A.z - cos(q1)*A.z assert cross(A.x, C.x) == sin(q3)*C.y assert cross(A.x, C.y) == -sin(q3)*C.x + cos(q3)*C.z assert cross(A.x, C.z) == -cos(q3)*C.y assert cross(C.x, A.x) == -sin(q3)*C.y assert cross(C.y, A.x) == sin(q3)*C.x - cos(q3)*C.z assert cross(C.z, A.x) == cos(q3)*C.y
def test_vector_pretty_print(): # TODO : The unit vectors should print with subscripts but they just # print as `n_x` instead of making `x` a subscritp with unicode. # TODO : The pretty print division does not print correctly here: # w = alpha * N.x + sin(omega) * N.y + alpha / beta * N.z pp = VectorPrettyPrinter() expected = u(' 2\na n_x + b n_y + c\u22c5sin(\u03b1) n_z') assert expected == pp.doprint(v) assert expected == v._pretty().render() expected = u('\u03b1 n_x + sin(\u03c9) n_y + \u03b1\u22c5\u03b2 n_z') assert expected == pp.doprint(w) assert expected == w._pretty().render()
def test_expand(): m0 = Matrix([[x*(x + y), 2], [((x + y)*y)*x, x*(y + x*(x + y))]]) # Test if expand() returns a matrix m1 = m0.expand() assert m1 == Matrix( [[x*y + x**2, 2], [x*y**2 + y*x**2, x*y + y*x**2 + x**3]]) a = Symbol('a', real=True) assert Matrix([exp(I*a)]).expand(complex=True) == \ Matrix([cos(a) + I*sin(a)]) assert Matrix([[0, 1, 2], [0, 0, -1], [0, 0, 0]]).exp() == Matrix([ [1, 1, Rational(3, 2)], [0, 1, -1], [0, 0, 1]] )
def test_function_series1(): """Create our new "sin" function.""" class my_function(Function): def fdiff(self, argindex=1): return cos(self.args[0]) @classmethod def eval(cls, arg): arg = sympify(arg) if arg == 0: return sympify(0) #Test that the taylor series is correct assert my_function(x).series(x, 0, 10) == sin(x).series(x, 0, 10) assert limit(my_function(x)/x, x, 0) == 1
def test_function_series2(): """Create our new "cos" function.""" class my_function2(Function): def fdiff(self, argindex=1): return -sin(self.args[0]) @classmethod def eval(cls, arg): arg = sympify(arg) if arg == 0: return sympify(1) #Test that the taylor series is correct assert my_function2(x).series(x, 0, 10) == cos(x).series(x, 0, 10)
def _compute_transform(self, F, s, x, **hints): from sympy import postorder_traversal global _allowed if _allowed is None: from sympy import ( exp, gamma, sin, cos, tan, cot, cosh, sinh, tanh, coth, factorial, rf) _allowed = set( [exp, gamma, sin, cos, tan, cot, cosh, sinh, tanh, coth, factorial, rf]) for f in postorder_traversal(F): if f.is_Function and f.has(s) and f.func not in _allowed: raise IntegralTransformError('Inverse Mellin', F, 'Component %s not recognised.' % f) strip = self.fundamental_strip return _inverse_mellin_transform(F, s, x, strip, **hints)
def _sine_cosine_transform(f, x, k, a, b, K, name, simplify=True): """ Compute a general sine or cosine-type transform F(k) = a int_0^oo b*sin(x*k) f(x) dx. F(k) = a int_0^oo b*cos(x*k) f(x) dx. For suitable choice of a and b, this reduces to the standard sine/cosine and inverse sine/cosine transforms. """ F = integrate(a*f*K(b*x*k), (x, 0, oo)) if not F.has(Integral): return _simplify(F, simplify), True if not F.is_Piecewise: raise IntegralTransformError(name, f, 'could not compute integral') F, cond = F.args[0] if F.has(Integral): raise IntegralTransformError(name, f, 'integral in unexpected form') return _simplify(F, simplify), cond
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))
def trig_cotcsc_rule(integral): integrand, symbol = integral integrand = integrand.subs({ 1 / sympy.sin(symbol): sympy.csc(symbol), 1 / sympy.tan(symbol): sympy.cot(symbol), sympy.cos(symbol) / sympy.tan(symbol): sympy.cot(symbol) }) if any(integrand.has(f) for f in (sympy.cot, sympy.csc)): pattern, a, b, m, n = cotcsc_pattern(symbol) match = integrand.match(pattern) if match: a, b, m, n = match.get(a, 0),match.get(b, 0), match.get(m, 0), match.get(n, 0) return multiplexer({ cotcsc_cotodd_condition: cotcsc_cotodd, cotcsc_csceven_condition: cotcsc_csceven })((a, b, m, n, integrand, symbol))
def test_dup_clear_denoms(): assert dup_clear_denoms([], QQ, ZZ) == (ZZ(1), []) assert dup_clear_denoms([QQ(1)], QQ, ZZ) == (ZZ(1), [QQ(1)]) assert dup_clear_denoms([QQ(7)], QQ, ZZ) == (ZZ(1), [QQ(7)]) assert dup_clear_denoms([QQ(7, 3)], QQ) == (ZZ(3), [QQ(7)]) assert dup_clear_denoms([QQ(7, 3)], QQ, ZZ) == (ZZ(3), [QQ(7)]) assert dup_clear_denoms( [QQ(3), QQ(1), QQ(0)], QQ, ZZ) == (ZZ(1), [QQ(3), QQ(1), QQ(0)]) assert dup_clear_denoms( [QQ(1), QQ(1, 2), QQ(0)], QQ, ZZ) == (ZZ(2), [QQ(2), QQ(1), QQ(0)]) assert dup_clear_denoms([QQ(3), QQ( 1), QQ(0)], QQ, ZZ, convert=True) == (ZZ(1), [ZZ(3), ZZ(1), ZZ(0)]) assert dup_clear_denoms([QQ(1), QQ( 1, 2), QQ(0)], QQ, ZZ, convert=True) == (ZZ(2), [ZZ(2), ZZ(1), ZZ(0)]) assert dup_clear_denoms( [EX(S(3)/2), EX(S(9)/4)], EX) == (EX(4), [EX(6), EX(9)]) assert dup_clear_denoms([EX(7)], EX) == (EX(1), [EX(7)]) assert dup_clear_denoms([EX(sin(x)/x), EX(0)], EX) == (EX(x), [EX(sin(x)), EX(0)])
def test_output_arg_c(): from sympy import sin, cos, Equality x, y, z = symbols("x,y,z") r = Routine("foo", [Equality(y, sin(x)), cos(x)]) c = CCodeGen() result = c.write([r], "test", header=False, empty=False) assert result[0][0] == "test.c" expected = ( '#include "test.h"\n' '#include <math.h>\n' 'double foo(double x, double &y) {\n' ' y = sin(x);\n' ' return cos(x);\n' '}\n' ) assert result[0][1] == expected
def test_output_arg_f(): from sympy import sin, cos, Equality x, y, z = symbols("x,y,z") r = Routine("foo", [Equality(y, sin(x)), cos(x)]) c = FCodeGen() result = c.write([r], "test", header=False, empty=False) assert result[0][0] == "test.f90" assert result[0][1] == ( 'REAL*8 function foo(x, y)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'REAL*8, intent(out) :: y\n' 'y = sin(x)\n' 'foo = cos(x)\n' 'end function\n' )
def test_maxima_functions(): assert parse_maxima('expand( (x+1)^2)') == x**2 + 2*x + 1 assert parse_maxima('factor( x**2 + 2*x + 1)') == (x + 1)**2 assert parse_maxima('2*cos(x)^2 + sin(x)^2') == 2*cos(x)**2 + sin(x)**2 assert parse_maxima('trigexpand(sin(2*x)+cos(2*x))') == \ -1 + 2*cos(x)**2 + 2*cos(x)*sin(x) assert parse_maxima('solve(x^2-4,x)') == [-2, 2] assert parse_maxima('limit((1+1/x)^x,x,inf)') == E assert parse_maxima('limit(sqrt(-x)/x,x,0,minus)') == -oo assert parse_maxima('diff(x^x, x)') == x**x*(1 + log(x)) assert parse_maxima('sum(k, k, 1, n)', name_dict=dict( n=Symbol('n', integer=True), k=Symbol('k', integer=True) )) == (n**2 + n)/2 assert parse_maxima('product(k, k, 1, n)', name_dict=dict( n=Symbol('n', integer=True), k=Symbol('k', integer=True) )) == factorial(n) assert parse_maxima('ratsimp((x^2-1)/(x+1))') == x - 1 assert Abs( parse_maxima( 'float(sec(%pi/3) + csc(%pi/3))') - 3.154700538379252) < 10**(-5)
def derivatives_in_spherical_coordinates(): Print_Function() X = (r, th, phi) = symbols('r theta phi') curv = [[r*cos(phi)*sin(th), r*sin(phi)*sin(th), r*cos(th)], [1, r, r*sin(th)]] (er, eth, ephi, grad) = MV.setup('e_r e_theta e_phi', metric='[1,1,1]', coords=X, curv=curv) f = MV('f', 'scalar', fct=True) A = MV('A', 'vector', fct=True) B = MV('B', 'grade2', fct=True) print('f =', f) print('A =', A) print('B =', B) print('grad*f =', grad*f) print('grad|A =', grad | A) print('-I*(grad^A) =', -MV.I*(grad ^ A)) print('grad^B =', grad ^ B) return
def derivatives_in_spherical_coordinates(): Print_Function() X = (r, th, phi) = symbols('r theta phi') curv = [[r*cos(phi)*sin(th), r*sin(phi)*sin(th), r*cos(th)], [1, r, r*sin(th)]] (er, eth, ephi, grad) = MV.setup('e_r e_theta e_phi', metric='[1,1,1]', coords=X, curv=curv) f = MV('f', 'scalar', fct=True) A = MV('A', 'vector', fct=True) B = MV('B', 'grade2', fct=True) print('f =', f) print('A =', A) print('B =', B) print('grad*f =', grad*f) print('grad|A =', grad | A) print('-I*(grad^A) =', (-MV.I*(grad ^ A)).simplify()) print('grad^B =', grad ^ B)
def real(self, nested_scope=None): """Return the correspond floating point number.""" op = self.children[0].name expr = self.children[1] dispatch = { 'sin': sympy.sin, 'cos': sympy.cos, 'tan': sympy.tan, 'asin': sympy.asin, 'acos': sympy.acos, 'atan': sympy.atan, 'exp': sympy.exp, 'ln': sympy.log, 'sqrt': sympy.sqrt } if op in dispatch: arg = expr.real(nested_scope) return dispatch[op](arg) else: raise NodeException("internal error: undefined external")
def sym(self, nested_scope=None): """Return the corresponding symbolic expression.""" op = self.children[0].name expr = self.children[1] dispatch = { 'sin': sympy.sin, 'cos': sympy.cos, 'tan': sympy.tan, 'asin': sympy.asin, 'acos': sympy.acos, 'atan': sympy.atan, 'exp': sympy.exp, 'ln': sympy.log, 'sqrt': sympy.sqrt } if op in dispatch: arg = expr.sym(nested_scope) return dispatch[op](arg) else: raise NodeException("internal error: undefined external")
def two_wheel_2d_model(x, u, dt): """Two wheel 2D motion model Parameters ---------- x : u : dt : Returns ------- """ gdot = np.array([[u[0, 0] * cos(x[2, 0]) * dt], [u[0, 0] * sin(x[2, 0]) * dt], [u[1, 0] * dt]]) return x + gdot
def two_wheel_3d_model(x, u, dt): """Two wheel 3D motion model Parameters ---------- x : u : dt : Returns ------- """ g1 = x[0, 0] + u[0] * cos(x[3, 0]) * dt g2 = x[1, 0] + u[0] * sin(x[3, 0]) * dt g3 = x[2, 0] + u[1] * dt g4 = x[3, 0] + u[2] * dt return np.array([g1, g2, g3, g4])
def two_wheel_3d_deriv(): """ """ x1, x2, x3, x4, x5, x6, x7 = sympy.symbols("x1,x2,x3,x4,x5,x6,x7") dt = sympy.symbols("dt") # x1 - x # x2 - y # x3 - z # x4 - theta # x5 - v # x6 - omega # x7 - vz # x, y, z, theta, v, omega, vz f1 = x1 + x5 * sympy.cos(x4) * dt f2 = x2 + x5 * sympy.sin(x4) * dt f3 = x3 + x7 * dt f4 = x4 + x6 * dt f5 = x5 f6 = x6 f7 = x7 F = sympy.Matrix([f1, f2, f3, f4, f5, f6, f7]) pprint(F.jacobian([x1, x2, x3, x4, x5, x6, x7]))
def linearity_index_inverse_depth(): """Linearity index of Inverse Depth Parameterization""" D, rho, rho_0, d_1, sigma_rho = sympy.symbols("D,rho,rho_0,d_1,sigma_rho") alpha = sympy.symbols("alpha") u = (rho * sympy.sin(alpha)) / (rho_0 * d_1 * (rho_0 - rho) + rho * sympy.cos(alpha)) # NOQA # first order derivative of u u_p = sympy.diff(u, rho) u_p = sympy.simplify(u_p) # second order derivative of u u_pp = sympy.diff(u_p, rho) u_pp = sympy.simplify(u_pp) # Linearity index L = (u_pp * 2 * sigma_rho) / (u_p) L = sympy.simplify(L) print() print("u: ", u) print("u': ", u_p) print("u'': ", u_pp) # print("L = ", L) print("L = ", L.subs(rho, 0)) print()
def test_epath_apply(): expr = [((x, 1, t), 2), ((3, y, 4), z)] func = lambda expr: expr**2 assert epath("/*", expr, list) == [[(x, 1, t), 2], [(3, y, 4), z]] assert epath("/*/[0]", expr, list) == [([x, 1, t], 2), ([3, y, 4], z)] assert epath("/*/[1]", expr, func) == [((x, 1, t), 4), ((3, y, 4), z**2)] assert epath("/*/[2]", expr, list) == expr assert epath("/*/[0]/int", expr, func) == [((x, 1, t), 2), ((9, y, 16), z)] assert epath("/*/[0]/Symbol", expr, func) == [((x**2, 1, t**2), 2), ((3, y**2, 4), z)] assert epath( "/*/[0]/int[1:]", expr, func) == [((x, 1, t), 2), ((3, y, 16), z)] assert epath("/*/[0]/Symbol[1:]", expr, func) == [((x, 1, t**2), 2), ((3, y**2, 4), z)] assert epath("/Symbol", x + y + z + 1, func) == x**2 + y**2 + z**2 + 1 assert epath("/*/*/Symbol", t + sin(x + 1) + cos(x + y + E), func) == \ t + sin(x**2 + 1) + cos(x**2 + y**2 + E)
def test_call(): x, y = symbols('x y') # See the long history of this in issues 5026 and 5105. raises(TypeError, lambda: sin(x)({ x : 1, sin(x) : 2})) raises(TypeError, lambda: sin(x)(1)) # No effect as there are no callables assert sin(x).rcall(1) == sin(x) assert (1 + sin(x)).rcall(1) == 1 + sin(x) # Effect in the pressence of callables l = Lambda(x, 2*x) assert (l + x).rcall(y) == 2*y + x assert (x**l).rcall(2) == x**4 # TODO UndefinedFunction does not subclass Expr #f = Function('f') #assert (2*f)(x) == 2*f(x) assert (Q.real & Q.positive).rcall(x) == Q.real(x) & Q.positive(x)
def test_hypersum(): from sympy import sin assert simplify(summation(x**n/fac(n), (n, 1, oo))) == -1 + exp(x) assert summation((-1)**n * x**(2*n) / fac(2*n), (n, 0, oo)) == cos(x) assert simplify(summation((-1)**n*x**(2*n + 1) / factorial(2*n + 1), (n, 3, oo))) == -x + sin(x) + x**3/6 - x**5/120 assert summation(1/(n + 2)**3, (n, 1, oo)) == -S(9)/8 + zeta(3) assert summation(1/n**4, (n, 1, oo)) == pi**4/90 s = summation(x**n*n, (n, -oo, 0)) assert s.is_Piecewise assert s.args[0].args[0] == -1/(x*(1 - 1/x)**2) assert s.args[0].args[1] == (abs(1/x) < 1) m = Symbol('n', integer=True, positive=True) assert summation(binomial(m, k), (k, 0, m)) == 2**m
def __init__(self, n, index): self.dim = n if index == 2: self.degree = 2 r = sqrt(3) / 6 data = [ (1.0, numpy.array([numpy.full(n, 2*r)])), (+r, _s(n, -1, r)), (-r, _s(n, +1, r)), ] else: assert index == 3 self.degree = 3 n2 = n // 2 if n % 2 == 0 else (n-1)//2 i_range = range(1, 2*n+1) pts = [[ [sqrt(fr(2, 3)) * cos((2*k-1)*i*pi / n) for i in i_range], [sqrt(fr(2, 3)) * sin((2*k-1)*i*pi / n) for i in i_range], ] for k in range(1, n2+1)] if n % 2 == 1: sqrt3pm = numpy.full(2*n, 1/sqrt(3)) sqrt3pm[1::2] *= -1 pts.append(sqrt3pm) pts = numpy.vstack(pts).T data = [(fr(1, 2*n), pts)] self.points, self.weights = untangle(data) reference_volume = 2**n self.weights *= reference_volume return
def __init__(self, n): self.weights = numpy.full(n, 2*sympy.pi/n) self.points = numpy.column_stack([ [sympy.cos(sympy.pi * sympy.Rational(2*k, n)) for k in range(n)], [sympy.sin(sympy.pi * sympy.Rational(2*k, n)) for k in range(n)], ]) self.degree = n - 1 return
def _gen4_1(): pts = 2 * sqrt(5) * numpy.array([ [cos(2*i*pi/5) for i in range(5)], [sin(2*i*pi/5) for i in range(5)], ]).T data = [ (fr(7, 10), numpy.array([[0, 0]])), (fr(3, 50), pts), ] return 4, data # The boolean tells whether the factor 2*pi is already in the weights
def __init__(self, settings): settings.update(output_dim=4) super().__init__(settings) params = sp.symbols('x1, x2, x3, x4, tau') x1, x2, x3, x4, tau = params x = [x1, x2, x3, x4] h = sp.Matrix([[x1]]) f = sp.Matrix([[x2], [st.B * x1 * x4 ** 2 - st.B * st.G * sin(x3)], [x4], [(tau - 2 * st.M * x1 * x2 * x4 - st.M * st.G * x1 * cos(x3)) / ( st.M * x1 ** 2 + st.J + st.Jb)]]) q = sp.Matrix(pm.lie_derivatives(h, f, x, len(x) - 1)) dq = q.jacobian(x) if dq.rank() != len(x): raise Exception("System might not be observable") # gets p = [p0, p1, ... pn-1] p = pm.char_coefficients(self._settings["poles"]) k = p[::-1] l = dq.inv() @ k mat2array = [{'ImmutableMatrix': np.array}, 'numpy'] self.h_func = sp.lambdify((x1, x2, x3, x4, tau), h, modules=mat2array) self.l_func = sp.lambdify((x1, x2, x3, x4, tau), l, modules=mat2array) self.f_func = sp.lambdify((x1, x2, x3, x4, tau), f, modules=mat2array) self.output = np.array(self._settings["initial state"], dtype=float)
def setUp(self): self._x1, self._x2 = sp.symbols("x y") self.x = sp.Matrix([self._x1, self._x2]) self.f = sp.Matrix([-self._x2**2, sp.sin(self._x1)]) self.h = sp.Matrix([self._x1**2 - sp.sin(self._x2)])
def __init__(self, settings): Trajectory.__init__(self, settings) # calculate symbolic derivatives up to order n t, a, f, off, p = sp.symbols("t, a, f, off, p") self.yd_sym = [] harmonic = a * sp.sin(2 * sp.pi * f * t + p) + off for idx in range(settings["differential_order"] + 1): self.yd_sym.append(harmonic.diff(t, idx)) # lambdify for idx, val in enumerate(self.yd_sym): self.yd_sym[idx] = sp.lambdify((t, a, f, off, p), val, "numpy")
def test_sin(): e = sin(x).lseries(x) assert next(e) == x assert next(e) == -x**3/6 assert next(e) == x**5/120
def test_issue_5183(): s = (x + 1/x).lseries() assert [si for si in s] == [1/x, x] assert next((x + x**2).lseries()) == x assert next(((1 + x)**7).lseries(x)) == 1 assert next((sin(x + y)).series(x, n=3).lseries(y)) == x # it would be nice if all terms were grouped, but in the # following case that would mean that all the terms would have # to be known since, for example, every term has a constant in it. s = ((1 + x)**7).series(x, 1, n=None) assert [next(s) for i in range(2)] == [128, -448 + 448*x]
def test_finite_diff(): assert finite_diff(x**2 + 2*x + 1, x) == 2*x + 3 assert finite_diff(y**3 + 2*y**2 + 3*y + 5, y) == 3*y**2 + 7*y + 6 assert finite_diff(z**2 - 2*z + 3, z) == 2*z - 1 assert finite_diff(w**2 + 3*w - 2, w) == 2*w + 4 assert finite_diff(sin(x), x, pi/6) == -sin(x) + sin(x + pi/6) assert finite_diff(cos(y), y, pi/3) == -cos(y) + cos(y + pi/3) assert finite_diff(x**2 - 2*x + 3, x, 2) == 4*x assert finite_diff(n**2 - 2*n + 3, n, 3) == 6*n + 3
def test_functions(): assert residue(1/sin(x), x, 0) == 1 assert residue(2/sin(x), x, 0) == 2 assert residue(1/sin(x)**2, x, 0) == 0 assert residue(1/sin(x)**5, x, 0) == S(3)/8
def test_epath_select(): expr = [((x, 1, t), 2), ((3, y, 4), z)] assert epath("/*", expr) == [((x, 1, t), 2), ((3, y, 4), z)] assert epath("/*/*", expr) == [(x, 1, t), 2, (3, y, 4), z] assert epath("/*/*/*", expr) == [x, 1, t, 3, y, 4] assert epath("/*/*/*/*", expr) == [] assert epath("/[:]", expr) == [((x, 1, t), 2), ((3, y, 4), z)] assert epath("/[:]/[:]", expr) == [(x, 1, t), 2, (3, y, 4), z] assert epath("/[:]/[:]/[:]", expr) == [x, 1, t, 3, y, 4] assert epath("/[:]/[:]/[:]/[:]", expr) == [] assert epath("/*/[:]", expr) == [(x, 1, t), 2, (3, y, 4), z] assert epath("/*/[0]", expr) == [(x, 1, t), (3, y, 4)] assert epath("/*/[1]", expr) == [2, z] assert epath("/*/[2]", expr) == [] assert epath("/*/int", expr) == [2] assert epath("/*/Symbol", expr) == [z] assert epath("/*/tuple", expr) == [(x, 1, t), (3, y, 4)] assert epath("/*/__iter__?", expr) == [(x, 1, t), (3, y, 4)] assert epath("/*/int|tuple", expr) == [(x, 1, t), 2, (3, y, 4)] assert epath("/*/Symbol|tuple", expr) == [(x, 1, t), (3, y, 4), z] assert epath("/*/int|Symbol|tuple", expr) == [(x, 1, t), 2, (3, y, 4), z] assert epath("/*/int|__iter__?", expr) == [(x, 1, t), 2, (3, y, 4)] assert epath("/*/Symbol|__iter__?", expr) == [(x, 1, t), (3, y, 4), z] assert epath( "/*/int|Symbol|__iter__?", expr) == [(x, 1, t), 2, (3, y, 4), z] assert epath("/*/[0]/int", expr) == [1, 3, 4] assert epath("/*/[0]/Symbol", expr) == [x, t, y] assert epath("/*/[0]/int[1:]", expr) == [1, 4] assert epath("/*/[0]/Symbol[1:]", expr) == [t, y] assert epath("/Symbol", x + y + z + 1) == [x, y, z] assert epath("/*/*/Symbol", t + sin(x + 1) + cos(x + y + E)) == [x, x, y]
def test_trigsimp1(): x, y = symbols('x,y') assert trigsimp(1 - sin(x)**2) == cos(x)**2 assert trigsimp(1 - cos(x)**2) == sin(x)**2 assert trigsimp(sin(x)**2 + cos(x)**2) == 1 assert trigsimp(1 + tan(x)**2) == 1/cos(x)**2 assert trigsimp(1/cos(x)**2 - 1) == tan(x)**2 assert trigsimp(1/cos(x)**2 - tan(x)**2) == 1 assert trigsimp(1 + cot(x)**2) == 1/sin(x)**2 assert trigsimp(1/sin(x)**2 - 1) == 1/tan(x)**2 assert trigsimp(1/sin(x)**2 - cot(x)**2) == 1 assert trigsimp(5*cos(x)**2 + 5*sin(x)**2) == 5 assert trigsimp(5*cos(x/2)**2 + 2*sin(x/2)**2) == 3*cos(x)/2 + S(7)/2 assert trigsimp(sin(x)/cos(x)) == tan(x) assert trigsimp(2*tan(x)*cos(x)) == 2*sin(x) assert trigsimp(cot(x)**3*sin(x)**3) == cos(x)**3 assert trigsimp(y*tan(x)**2/sin(x)**2) == y/cos(x)**2 assert trigsimp(cot(x)/cos(x)) == 1/sin(x) assert trigsimp(sin(x + y) + sin(x - y)) == 2*sin(x)*cos(y) assert trigsimp(sin(x + y) - sin(x - y)) == 2*sin(y)*cos(x) assert trigsimp(cos(x + y) + cos(x - y)) == 2*cos(x)*cos(y) assert trigsimp(cos(x + y) - cos(x - y)) == -2*sin(x)*sin(y) assert ratsimp(trigsimp(tan(x + y) - tan(x)/(1 - tan(x)*tan(y)))) == \ sin(y)/(-sin(y)*tan(x) + cos(y)) # -tan(y)/(tan(x)*tan(y) - 1) assert trigsimp(sinh(x + y) + sinh(x - y)) == 2*sinh(x)*cosh(y) assert trigsimp(sinh(x + y) - sinh(x - y)) == 2*sinh(y)*cosh(x) assert trigsimp(cosh(x + y) + cosh(x - y)) == 2*cosh(x)*cosh(y) assert trigsimp(cosh(x + y) - cosh(x - y)) == 2*sinh(x)*sinh(y) assert ratsimp(trigsimp(tanh(x + y) - tanh(x)/(1 + tanh(x)*tanh(y)))) == \ sinh(y)/(sinh(y)*tanh(x) + cosh(y)) assert trigsimp(cos(0.12345)**2 + sin(0.12345)**2) == 1 e = 2*sin(x)**2 + 2*cos(x)**2 assert trigsimp(log(e)) == log(2)
def test_trigsimp1a(): assert trigsimp(sin(2)**2*cos(3)*exp(2)/cos(2)**2) == tan(2)**2*cos(3)*exp(2) assert trigsimp(tan(2)**2*cos(3)*exp(2)*cos(2)**2) == sin(2)**2*cos(3)*exp(2) assert trigsimp(cot(2)*cos(3)*exp(2)*sin(2)) == cos(3)*exp(2)*cos(2) assert trigsimp(tan(2)*cos(3)*exp(2)/sin(2)) == cos(3)*exp(2)/cos(2) assert trigsimp(cot(2)*cos(3)*exp(2)/cos(2)) == cos(3)*exp(2)/sin(2) assert trigsimp(cot(2)*cos(3)*exp(2)*tan(2)) == cos(3)*exp(2) assert trigsimp(sinh(2)*cos(3)*exp(2)/cosh(2)) == tanh(2)*cos(3)*exp(2) assert trigsimp(tanh(2)*cos(3)*exp(2)*cosh(2)) == sinh(2)*cos(3)*exp(2) assert trigsimp(coth(2)*cos(3)*exp(2)*sinh(2)) == cosh(2)*cos(3)*exp(2) assert trigsimp(tanh(2)*cos(3)*exp(2)/sinh(2)) == cos(3)*exp(2)/cosh(2) assert trigsimp(coth(2)*cos(3)*exp(2)/cosh(2)) == cos(3)*exp(2)/sinh(2) assert trigsimp(coth(2)*cos(3)*exp(2)*tanh(2)) == cos(3)*exp(2)