def test_acos_series(): assert acos(x).series(x, 0, 8) == \ pi/2 - x - x**3/6 - 3*x**5/40 - 5*x**7/112 + O(x**8) assert acos(x).series(x, 0, 8) == pi/2 - asin(x).series(x, 0, 8) t5 = acos(x).taylor_term(5, x) assert t5 == -3*x**5/40 assert acos(x).taylor_term(7, x, t5, 0) == -5*x**7/112
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), [C1, C2, C3])) == \ constant_renumber((C1*exp(x) + C2*exp(2*x))) assert constant_renumber( constantsimp(Eq(f(x), I*C1*sinh(x/3) + C2*cosh(x/3)), [C1, C2]) ) == constant_renumber(Eq(f(x), C1*sinh(x/3) + C2*cosh(x/3))) assert constant_renumber(constantsimp(Eq(f(x), acos((-C1)/cos(x))), [C1])) == \ Eq(f(x), acos(C1/cos(x))) assert constant_renumber( constantsimp(Eq(log(f(x)/C1) + 2*exp(x/f(x)), 0), [C1]) ) == 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), [C1])) == \ Eq(log(C1*sqrt(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), [C1])) == \ Eq(-exp(-f(x)/x)*sin(f(x)/x)/2 + log(C1*x) - cos(f(x)/x)* exp(-f(x)/x)/2, 0) assert constant_renumber(constantsimp(Eq(-Integral(-1/(sqrt(1 - u2**2)*u2), (u2, _a, x/f(x))) + log(f(x)/C1), 0), [C1])) == \ Eq(-Integral(-1/(u2*sqrt(1 - u2**2)), (u2, _a, x/f(x))) + log(C1*f(x)), 0) assert [constantsimp(i, [C1]) for i in [Eq(f(x), sqrt(-C1*x + x**2)), Eq(f(x), -sqrt(-C1*x + x**2))]] == \ [Eq(f(x), sqrt(x*(C1 + x))), Eq(f(x), -sqrt(x*(C1 + 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_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_issue_2850(): assert manualintegrate(asin(x)*log(x), x) == -x*asin(x) - sqrt(-x**2 + 1) \ + (x*asin(x) + sqrt(-x**2 + 1))*log(x) - Integral(sqrt(-x**2 + 1)/x, x) assert manualintegrate(acos(x)*log(x), x) == -x*acos(x) + sqrt(-x**2 + 1) + \ (x*acos(x) - sqrt(-x**2 + 1))*log(x) + Integral(sqrt(-x**2 + 1)/x, x) assert manualintegrate(atan(x)*log(x), x) == -x*atan(x) + (x*atan(x) - \ log(x**2 + 1)/2)*log(x) + log(x**2 + 1)/2 + Integral(log(x**2 + 1)/x, x)/2
def test_logcombine_1(): x, y = symbols("x,y") a = Symbol("a") z, w = symbols("z,w", positive=True) b = Symbol("b", real=True) assert logcombine(log(x) + 2*log(y)) == log(x) + 2*log(y) assert logcombine(log(x) + 2*log(y), force=True) == log(x*y**2) assert logcombine(a*log(w) + log(z)) == a*log(w) + log(z) assert logcombine(b*log(z) + b*log(x)) == log(z**b) + b*log(x) assert logcombine(b*log(z) - log(w)) == log(z**b/w) assert logcombine(log(x)*log(z)) == log(x)*log(z) assert logcombine(log(w)*log(x)) == log(w)*log(x) assert logcombine(cos(-2*log(z) + b*log(w))) in [cos(log(w**b/z**2)), cos(log(z**2/w**b))] assert logcombine(log(log(x) - log(y)) - log(z), force=True) == \ log(log(x/y)/z) assert logcombine((2 + I)*log(x), force=True) == (2 + I)*log(x) assert logcombine((x**2 + log(x) - log(y))/(x*y), force=True) == \ (x**2 + log(x/y))/(x*y) # the following could also give log(z*x**log(y**2)), what we # are testing is that a canonical result is obtained assert logcombine(log(x)*2*log(y) + log(z), force=True) == \ log(z*y**log(x**2)) assert logcombine((x*y + sqrt(x**4 + y**4) + log(x) - log(y))/(pi*x**Rational(2, 3)* sqrt(y)**3), force=True) == ( x*y + sqrt(x**4 + y**4) + log(x/y))/(pi*x**(S(2)/3)*y**(S(3)/2)) assert logcombine(gamma(-log(x/y))*acos(-log(x/y)), force=True) == \ acos(-log(x/y))*gamma(-log(x/y)) assert logcombine(2*log(z)*log(w)*log(x) + log(z) + log(w)) == \ log(z**log(w**2))*log(x) + log(w*z) assert logcombine(3*log(w) + 3*log(z)) == log(w**3*z**3) assert logcombine(x*(y + 1) + log(2) + log(3)) == x*(y + 1) + log(6) assert logcombine((x + y)*log(w) + (-x - y)*log(3)) == (x + y)*log(w/3)
def test_heurisch_trigonometric(): assert heurisch(sin(x), x) == -cos(x) assert heurisch(pi*sin(x) + 1, x) == x - pi*cos(x) assert heurisch(cos(x), x) == sin(x) assert heurisch(tan(x), x) in [ log(1 + tan(x)**2)/2, log(tan(x) + I) + I*x, log(tan(x) - I) - I*x, ] assert heurisch(sin(x)*sin(y), x) == -cos(x)*sin(y) assert heurisch(sin(x)*sin(y), y) == -cos(y)*sin(x) # gives sin(x) in answer when run via setup.py and cos(x) when run via py.test assert heurisch(sin(x)*cos(x), x) in [sin(x)**2 / 2, -cos(x)**2 / 2] assert heurisch(cos(x)/sin(x), x) == log(sin(x)) assert heurisch(x*sin(7*x), x) == sin(7*x) / 49 - x*cos(7*x) / 7 assert heurisch(1/pi/4 * x**2*cos(x), x) == 1/pi/4*(x**2*sin(x) - 2*sin(x) + 2*x*cos(x)) assert heurisch(acos(x/4) * asin(x/4), x) == 2*x - (sqrt(16 - x**2))*asin(x/4) \ + (sqrt(16 - x**2))*acos(x/4) + x*asin(x/4)*acos(x/4) assert heurisch(sin(x)/(cos(x)**2+1), x) == -atan(cos(x)) #fixes issue 13723 assert heurisch(1/(cos(x)+2), x) == 2*sqrt(3)*atan(sqrt(3)*tan(x/2)/3)/3 assert heurisch(2*sin(x)*cos(x)/(sin(x)**4 + 1), x) == atan(sqrt(2)*sin(x) - 1) - atan(sqrt(2)*sin(x) + 1) assert heurisch(1/cosh(x), x) == 2*atan(tanh(x/2))
def test_quaternion_conversions(): q1 = Quaternion(1, 2, 3, 4) assert q1.to_axis_angle() == ((2 * sqrt(29)/29, 3 * sqrt(29)/29, 4 * sqrt(29)/29), 2 * acos(sqrt(30)/30)) assert q1.to_rotation_matrix() == Matrix([[-S(2)/3, S(2)/15, S(11)/15], [S(2)/3, -S(1)/3, S(14)/15], [S(1)/3, S(14)/15, S(2)/15]]) assert q1.to_rotation_matrix((1, 1, 1)) == Matrix([[-S(2)/3, S(2)/15, S(11)/15, S(4)/5], [S(2)/3, -S(1)/3, S(14)/15, -S(4)/15], [S(1)/3, S(14)/15, S(2)/15, -S(2)/5], [S(0), S(0), S(0), S(1)]]) theta = symbols("theta", real=True) q2 = Quaternion(cos(theta/2), 0, 0, sin(theta/2)) assert trigsimp(q2.to_rotation_matrix()) == Matrix([ [cos(theta), -sin(theta), 0], [sin(theta), cos(theta), 0], [0, 0, 1]]) assert q2.to_axis_angle() == ((0, 0, sin(theta/2)/Abs(sin(theta/2))), 2*acos(cos(theta/2))) assert trigsimp(q2.to_rotation_matrix((1, 1, 1))) == Matrix([ [cos(theta), -sin(theta), 0, sin(theta) - cos(theta) + 1], [sin(theta), cos(theta), 0, -sin(theta) - cos(theta) + 1], [0, 0, 1, 0], [0, 0, 0, 1]])
def test_logcombine_1(): x, y = symbols("x,y") a = Symbol("a") z, w = symbols("z,w", positive=True) b = Symbol("b", real=True) assert logcombine(log(x)+2*log(y)) == log(x) + 2*log(y) assert logcombine(log(x)+2*log(y), force=True) == log(x*y**2) assert logcombine(a*log(w)+log(z)) == a*log(w) + log(z) assert logcombine(b*log(z)+b*log(x)) == log(z**b) + b*log(x) assert logcombine(b*log(z)-log(w)) == log(z**b/w) assert logcombine(log(x)*log(z)) == log(x)*log(z) assert logcombine(log(w)*log(x)) == log(w)*log(x) assert logcombine(cos(-2*log(z)+b*log(w))) in [cos(log(w**b/z**2)), cos(log(z**2/w**b))] assert logcombine(log(log(x)-log(y))-log(z), force=True) == \ log(log((x/y)**(1/z))) assert logcombine((2+I)*log(x), force=True) == I*log(x)+log(x**2) assert logcombine((x**2+log(x)-log(y))/(x*y), force=True) == \ log(x**(1/(x*y))*y**(-1/(x*y)))+x/y assert logcombine(log(x)*2*log(y)+log(z), force=True) == \ log(z*y**log(x**2)) assert logcombine((x*y+sqrt(x**4+y**4)+log(x)-log(y))/(pi*x**Rational(2, 3)*\ sqrt(y)**3), force=True) == \ log(x**(1/(pi*x**Rational(2, 3)*sqrt(y)**3))*y**(-1/(pi*\ x**Rational(2, 3)*sqrt(y)**3))) + sqrt(x**4 + y**4)/(pi*\ x**Rational(2, 3)*sqrt(y)**3) + x**Rational(1, 3)/(pi*sqrt(y)) assert logcombine(Eq(log(x), -2*log(y)), force=True) == \ Eq(log(x*y**2), Integer(0)) assert logcombine(Eq(y, x*acos(-log(x/y))), force=True) == \ Eq(y, x*acos(log(y/x))) assert logcombine(gamma(-log(x/y))*acos(-log(x/y)), force=True) == \ acos(log(y/x))*gamma(log(y/x)) assert logcombine((2+3*I)*log(x), force=True) == \ log(x**2)+3*I*log(x) assert logcombine(Eq(y, -log(x)), force=True) == Eq(y, log(1/x))
def eval(cls, arg): from sympy import acos arg = sympify(arg) if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.Infinity: return S.Infinity elif arg is S.NegativeInfinity: return S.Infinity elif arg is S.Zero: return S.Pi*S.ImaginaryUnit / 2 elif arg is S.One: return S.Zero elif arg is S.NegativeOne: return S.Pi*S.ImaginaryUnit if arg.is_number: cst_table = { S.ImaginaryUnit: log(S.ImaginaryUnit*(1 + sqrt(2))), -S.ImaginaryUnit: log(-S.ImaginaryUnit*(1 + sqrt(2))), S.Half: S.Pi/3, -S.Half: 2*S.Pi/3, sqrt(2)/2: S.Pi/4, -sqrt(2)/2: 3*S.Pi/4, 1/sqrt(2): S.Pi/4, -1/sqrt(2): 3*S.Pi/4, sqrt(3)/2: S.Pi/6, -sqrt(3)/2: 5*S.Pi/6, (sqrt(3) - 1)/sqrt(2**3): 5*S.Pi/12, -(sqrt(3) - 1)/sqrt(2**3): 7*S.Pi/12, sqrt(2 + sqrt(2))/2: S.Pi/8, -sqrt(2 + sqrt(2))/2: 7*S.Pi/8, sqrt(2 - sqrt(2))/2: 3*S.Pi/8, -sqrt(2 - sqrt(2))/2: 5*S.Pi/8, (1 + sqrt(3))/(2*sqrt(2)): S.Pi/12, -(1 + sqrt(3))/(2*sqrt(2)): 11*S.Pi/12, (sqrt(5) + 1)/4: S.Pi/5, -(sqrt(5) + 1)/4: 4*S.Pi/5 } if arg in cst_table: if arg.is_real: return cst_table[arg]*S.ImaginaryUnit return cst_table[arg] if arg is S.ComplexInfinity: return S.Infinity i_coeff = arg.as_coefficient(S.ImaginaryUnit) if i_coeff is not None: if _coeff_isneg(i_coeff): return S.ImaginaryUnit * acos(i_coeff) return S.ImaginaryUnit * acos(-i_coeff) else: if _coeff_isneg(arg): return -cls(-arg)
def test_asech(): x = Symbol('x') assert asech(-x) == asech(-x) # values at fixed points assert asech(1) == 0 assert asech(-1) == pi*I assert asech(0) == oo assert asech(2) == I*pi/3 assert asech(-2) == 2*I*pi / 3 # at infinites assert asech(oo) == I*pi/2 assert asech(-oo) == I*pi/2 assert asech(zoo) == nan assert asech(I) == log(1 + sqrt(2)) - I*pi/2 assert asech(-I) == log(1 + sqrt(2)) + I*pi/2 assert asech(sqrt(2) - sqrt(6)) == 11*I*pi / 12 assert asech(sqrt(2 - 2/sqrt(5))) == I*pi / 10 assert asech(-sqrt(2 - 2/sqrt(5))) == 9*I*pi / 10 assert asech(2 / sqrt(2 + sqrt(2))) == I*pi / 8 assert asech(-2 / sqrt(2 + sqrt(2))) == 7*I*pi / 8 assert asech(sqrt(5) - 1) == I*pi / 5 assert asech(1 - sqrt(5)) == 4*I*pi / 5 assert asech(-sqrt(2*(2 + sqrt(2)))) == 5*I*pi / 8 # properties # asech(x) == acosh(1/x) assert asech(sqrt(2)) == acosh(1/sqrt(2)) assert asech(2/sqrt(3)) == acosh(sqrt(3)/2) assert asech(2/sqrt(2 + sqrt(2))) == acosh(sqrt(2 + sqrt(2))/2) assert asech(S(2)) == acosh(1/S(2)) # asech(x) == I*acos(1/x) # (Note: the exact formula is asech(x) == +/- I*acos(1/x)) assert asech(-sqrt(2)) == I*acos(-1/sqrt(2)) assert asech(-2/sqrt(3)) == I*acos(-sqrt(3)/2) assert asech(-S(2)) == I*acos(-S.Half) assert asech(-2/sqrt(2)) == I*acos(-sqrt(2)/2) # sech(asech(x)) / x == 1 assert expand_mul(sech(asech(sqrt(6) - sqrt(2))) / (sqrt(6) - sqrt(2))) == 1 assert expand_mul(sech(asech(sqrt(6) + sqrt(2))) / (sqrt(6) + sqrt(2))) == 1 assert (sech(asech(sqrt(2 + 2/sqrt(5)))) / (sqrt(2 + 2/sqrt(5)))).simplify() == 1 assert (sech(asech(-sqrt(2 + 2/sqrt(5)))) / (-sqrt(2 + 2/sqrt(5)))).simplify() == 1 assert (sech(asech(sqrt(2*(2 + sqrt(2))))) / (sqrt(2*(2 + sqrt(2))))).simplify() == 1 assert expand_mul(sech(asech((1 + sqrt(5)))) / ((1 + sqrt(5)))) == 1 assert expand_mul(sech(asech((-1 - sqrt(5)))) / ((-1 - sqrt(5)))) == 1 assert expand_mul(sech(asech((-sqrt(6) - sqrt(2)))) / ((-sqrt(6) - sqrt(2)))) == 1 # numerical evaluation assert str(asech(5*I).n(6)) == '0.19869 - 1.5708*I' assert str(asech(-5*I).n(6)) == '0.19869 + 1.5708*I'
def test_main_trig_functions_numeric(self): print "\n\n\n" + " Test if sin, cos and tan and inverses Work Numerically ".center(75, "#") from sympy import symbols, sin, cos, tan, asin, acos, atan x, y = symbols('x,y') test_expr = sin(x) + cos(x) + tan(x) + asin(y) + acos(y) + atan(y) target_expr = sin(x) + cos(x) + tan(x) + asin(y) + acos(y) + atan(y) print "Target expression: '%s'" % target_expr print "Test expression: '%s'" % test_expr equal = api.numeric_equality(test_expr, target_expr) self.assertTrue(equal, "Expected expressions to be found numerically equal!") print " PASS ".center(75, "#")
def test_acos_rewrite(): assert acos(x).rewrite(log) == pi/2 + I*log(I*x + sqrt(1 - x**2)) assert acos(x).rewrite(atan) == \ atan(sqrt(1 - x**2)/x) + (pi/2)*(1 - x*sqrt(1/x**2)) assert acos(0).rewrite(atan) == S.Pi/2 assert acos(0.5).rewrite(atan) == acos(0.5).rewrite(log) assert acos(x).rewrite(asin) == S.Pi/2 - asin(x) assert acos(x).rewrite(acot) == -2*acot((sqrt(-x**2 + 1) + 1)/x) + pi/2 assert acos(x).rewrite(asec) == asec(1/x) assert acos(x).rewrite(acsc) == -acsc(1/x) + pi/2
def get_rec_cell_parameters(a, b, c, alpha, beta, gamma): import sympy as sp """ Returns cell vectors in direkt and reciprocal space and reciprocal lattice parameters of given cell parameters (vectors in direct crystal fixed carthesian system). """ # Metric Tensor: G = sp.Matrix([[a**2, a*b*sp.cos(gamma), a*c*sp.cos(beta)], [a*b*sp.cos(gamma), b**2, b*c*sp.cos(alpha)], [a*c*sp.cos(beta), b*c*sp.cos(alpha), c**2]]) G_r = G.inv() # reciprocal Metric G_r.simplify() # volume of crystall system cell in carthesian system # V = sp.sqrt(G.det()) # reciprocal cell lengths ar = sp.sqrt(G_r[0,0]) br = sp.sqrt(G_r[1,1]) cr = sp.sqrt(G_r[2,2]) #alphar = sp.acos(G_r[1,2]/(br*cr)).simplify() alphar = sp.acos((-sp.cos(alpha) + sp.cos(beta)*sp.cos(gamma))/(sp.Abs(sp.sin(beta))*sp.Abs(sp.sin(gamma)))) betar = sp.acos(G_r[0,2]/(ar*cr)) #gammar = sp.acos(G_r[0,1]/(ar*br)).simplify() gammar = sp.acos((sp.cos(alpha)*sp.cos(beta) - sp.cos(gamma))/(sp.Abs(sp.sin(alpha))*sp.Abs(sp.sin(beta)))) # x parallel to a* and z parallel to a* x b* (ITC Vol B Ch. 3.3.1.1.1) #B = sp.Matrix([[ar, br*sp.cos(gammar), cr*sp.cos(betar)], # [0, br*sp.sin(gammar), -cr*sp.sin(betar)*sp.cos(alpha)], # [0, 0, 1/c]]) #B_0 = sp.Matrix([[1, sp.cos(gammar), sp.cos(betar)], # [0, sp.sin(gammar), -sp.sin(betar)*sp.cos(alpha)], # [0, 0, 1]]) #V_0 = sp.sqrt(1 - sp.cos(alphar)**2 - sp.cos(betar)**2 - sp.cos(gammar)**2 + 2*sp.cos(alphar)*sp.cos(betar)*sp.cos(gammar)) # x parallel to a and z parallel to a x b (ITC Vol B Ch. 3.3.1.1.1) V0 = sp.sin(alpha) * sp.sin(beta) * sp.sin(gammar) M = sp.Matrix([[a, b*sp.cos(gamma), c*sp.cos(beta)], [0, b*sp.sin(gamma), c*(sp.cos(alpha) - sp.cos(beta)*sp.cos(gamma))/sp.sin(gamma)], [0, 0, c*V0/sp.sin(gamma)]]) Mi = sp.Matrix([[1/a,-1/(a*sp.tan(gamma)), (sp.cos(alpha)*sp.cos(gamma) - sp.cos(beta))/(a*V0*sp.sin(gamma))], [0, 1/(b*sp.sin(gamma)), (sp.cos(beta)*sp.cos(gamma) - sp.cos(alpha))/(b*V0*sp.sin(gamma))], [0, 0, sp.sin(gamma)/(c*V0)]]) return (ar, br, cr, alphar, betar, gammar, M, Mi, G, G_r)
def test_function__eval_nseries(): n = Symbol('n') assert sin(x)._eval_nseries(x, 2, None) == x + O(x**2) assert sin(x + 1)._eval_nseries(x, 2, None) == x*cos(1) + sin(1) + O(x**2) assert sin(pi*(1 - x))._eval_nseries(x, 2, None) == pi*x + O(x**2) assert acos(1 - x**2)._eval_nseries(x, 2, None) == sqrt(2)*x + O(x**2) assert polygamma(n, x + 1)._eval_nseries(x, 2, None) == \ polygamma(n, 1) + polygamma(n + 1, 1)*x + O(x**2) raises(PoleError, lambda: sin(1/x)._eval_nseries(x, 2, None)) raises(PoleError, lambda: acos(1 - x)._eval_nseries(x, 2, None)) raises(PoleError, lambda: acos(1 + x)._eval_nseries(x, 2, None)) assert loggamma(1/x)._eval_nseries(x, 0, None) == \ log(x)/2 - log(x)/x - 1/x + O(1, x) assert loggamma(log(1/x)).nseries(x, n=1, logx=y) == loggamma(-y)
def test_roots_cubic(): assert roots_cubic(Poly(2*x**3, x)) == [0, 0, 0] assert roots_cubic(Poly(x**3 - 3*x**2 + 3*x - 1, x)) == [1, 1, 1] assert roots_cubic(Poly(x**3 + 1, x)) == \ [-1, S.Half - I*sqrt(3)/2, S.Half + I*sqrt(3)/2] assert roots_cubic(Poly(2*x**3 - 3*x**2 - 3*x - 1, x))[0] == \ S.Half + 3**Rational(1, 3)/2 + 3**Rational(2, 3)/2 eq = -x**3 + 2*x**2 + 3*x - 2 assert roots(eq, trig=True, multiple=True) == \ roots_cubic(Poly(eq, x), trig=True) == [ S(2)/3 + 2*sqrt(13)*cos(acos(8*sqrt(13)/169)/3)/3, -2*sqrt(13)*sin(-acos(8*sqrt(13)/169)/3 + pi/6)/3 + S(2)/3, -2*sqrt(13)*cos(-acos(8*sqrt(13)/169)/3 + pi/3)/3 + S(2)/3, ]
def test_conv7(): x = Symbol("x") y = Symbol("y") assert sin(x/3) == sin(sympy.Symbol("x") / 3) assert cos(x/3) == cos(sympy.Symbol("x") / 3) assert tan(x/3) == tan(sympy.Symbol("x") / 3) assert cot(x/3) == cot(sympy.Symbol("x") / 3) assert csc(x/3) == csc(sympy.Symbol("x") / 3) assert sec(x/3) == sec(sympy.Symbol("x") / 3) assert asin(x/3) == asin(sympy.Symbol("x") / 3) assert acos(x/3) == acos(sympy.Symbol("x") / 3) assert atan(x/3) == atan(sympy.Symbol("x") / 3) assert acot(x/3) == acot(sympy.Symbol("x") / 3) assert acsc(x/3) == acsc(sympy.Symbol("x") / 3) assert asec(x/3) == asec(sympy.Symbol("x") / 3) assert sin(x/3)._sympy_() == sympy.sin(sympy.Symbol("x") / 3) assert sin(x/3)._sympy_() != sympy.cos(sympy.Symbol("x") / 3) assert cos(x/3)._sympy_() == sympy.cos(sympy.Symbol("x") / 3) assert tan(x/3)._sympy_() == sympy.tan(sympy.Symbol("x") / 3) assert cot(x/3)._sympy_() == sympy.cot(sympy.Symbol("x") / 3) assert csc(x/3)._sympy_() == sympy.csc(sympy.Symbol("x") / 3) assert sec(x/3)._sympy_() == sympy.sec(sympy.Symbol("x") / 3) assert asin(x/3)._sympy_() == sympy.asin(sympy.Symbol("x") / 3) assert acos(x/3)._sympy_() == sympy.acos(sympy.Symbol("x") / 3) assert atan(x/3)._sympy_() == sympy.atan(sympy.Symbol("x") / 3) assert acot(x/3)._sympy_() == sympy.acot(sympy.Symbol("x") / 3) assert acsc(x/3)._sympy_() == sympy.acsc(sympy.Symbol("x") / 3) assert asec(x/3)._sympy_() == sympy.asec(sympy.Symbol("x") / 3)
def _set_inv_trans_equations(self, curv_coord_name): """ Store information about some default, pre-defined inverse transformation equations. Parameters ========== curv_coord_name : str The type of the new coordinate system. """ equations_mapping = { 'cartesian': (self.x, self.y, self.z), 'spherical': (sqrt(self.x**2 + self.y**2 + self.z**2), acos((self.z) / sqrt(self.x**2 + self.y**2 + self.z**2)), atan2(self.y, self.x)), 'cylindrical': (sqrt(self.x**2 + self.y**2), atan2(self.y, self.x), self.z) } if curv_coord_name not in equations_mapping: raise ValueError('Wrong set of parameters.' 'Type of coordinate system is defined') self._inv_transformation_eqs = equations_mapping[curv_coord_name]
def _set_inv_trans_equations(curv_coord_name): """ Store information about inverse transformation equations for pre-defined coordinate systems. Parameters ========== curv_coord_name : str Name of coordinate system """ if curv_coord_name == 'cartesian': return lambda x, y, z: (x, y, z) if curv_coord_name == 'spherical': return lambda x, y, z: ( sqrt(x**2 + y**2 + z**2), acos(z/sqrt(x**2 + y**2 + z**2)), atan2(y, x) ) if curv_coord_name == 'cylindrical': return lambda x, y, z: ( sqrt(x**2 + y**2), atan2(y, x), z ) raise ValueError('Wrong set of parameters.' 'Type of coordinate system is defined')
def angle_between_vectors(a, b): """Return the minimum angle between two vectors. The angle returned for vectors a and -a is 0. """ angle = (acos(dot(a, b)/(a.magnitude() * b.magnitude())) * 180 / pi).evalf() return min(angle, 180 - angle)
def test_trigo(): # Vérifie que arcsin est correctement implémenté (appel à math, numpy ou # sympy suivant le type d'objet). assertAlmostEqual(asin(.2), math.asin(.2)) a, b, c = asin([.2, .3, .4]) d, e, f = numpy.arcsin([.2, .3, .4]) assertAlmostEqual(a, d) assertAlmostEqual(b, e) assertAlmostEqual(c, f) assertEqual(asin(x + 1), sympy.asin(x + 1)) # Vérifie que arccos est correctement implémenté (appel à math, numpy ou # sympy suivant le type d'objet). assertAlmostEqual(acos(.2), math.acos(.2)) a, b, c = acos([.2, .3, .4]) d, e, f = numpy.arccos([.2, .3, .4]) assertAlmostEqual(a, d) assertAlmostEqual(b, e) assertAlmostEqual(c, f) assertEqual(acos(x + 1), sympy.acos(x + 1)) # Vérifie que arctan est correctement implémenté (appel à math, numpy ou # sympy suivant le type d'objet). assertAlmostEqual(atan(.2), math.atan(.2)) a, b, c = atan([.2, .3, .4]) d, e, f = numpy.arctan([.2, .3, .4]) assertAlmostEqual(a, d) assertAlmostEqual(b, e) assertAlmostEqual(c, f) assertEqual(atan(x + 1), sympy.atan(x + 1))
def test_ansi_math1_codegen(): # not included: log10 from sympy import acos, asin, atan, ceiling, cos, cosh, floor, log, ln, \ sin, sinh, sqrt, tan, tanh, N x = symbols('x') name_expr = [ ("test_fabs", abs(x)), ("test_acos", acos(x)), ("test_asin", asin(x)), ("test_atan", atan(x)), ("test_ceil", ceiling(x)), ("test_cos", cos(x)), ("test_cosh", cosh(x)), ("test_floor", floor(x)), ("test_log", log(x)), ("test_ln", ln(x)), ("test_sin", sin(x)), ("test_sinh", sinh(x)), ("test_sqrt", sqrt(x)), ("test_tan", tan(x)), ("test_tanh", tanh(x)), ] numerical_tests = [] for name, expr in name_expr: for xval in 0.2, 0.5, 0.8: expected = N(expr.subs(x, xval)) numerical_tests.append((name, (xval,), expected, 1e-14)) run_cc_test("ansi_math1", name_expr, numerical_tests)
def quat2angle_axis(quat): ''' Convert quaternion to rotation of angle around axis ''' w, x, y, z = quat vec = [x, y, z] n = sqrt(x*x + y*y + z*z) return np.array([2 * acos(w), (np.array(vec) / n)[:]])
def log(T): (R,p) = breakTrans(T) if np.array_equiv(R, np.eye(3)): w = np.zeros((3,1)) theta = 1 u = p else: tr = R.trace() if tr == -1: theta = -math.pi w = np.array([[ sqrt((R[i][i]+1)/2) for i in range(3)]]).T W = bra(w) else: theta = acos((tr-1)/2) W = (1/(2*sin(theta)))*(R-R.T) w = ibra(W) W2 = np.dot(W,W) G1 = 1./theta*np.eye(3) G2 = 0.5*W G3 = (1./theta-cot(theta/2)/2)*W2 G = G1+G2+G3 # This corrects the bug!!!!! G = G.T u = np.dot(G,p) h = np.dot(w.T,u) return (w,u,theta,h)
def eval_trigsubstitution(theta, func, rewritten, substep, restriction, integrand, symbol): func = func.subs(sympy.sec(theta), 1/sympy.cos(theta)) trig_function = list(func.find(TrigonometricFunction)) assert len(trig_function) == 1 trig_function = trig_function[0] relation = sympy.solve(symbol - func, trig_function) assert len(relation) == 1 numer, denom = sympy.fraction(relation[0]) if isinstance(trig_function, sympy.sin): opposite = numer hypotenuse = denom adjacent = sympy.sqrt(denom**2 - numer**2) inverse = sympy.asin(relation[0]) elif isinstance(trig_function, sympy.cos): adjacent = numer hypotenuse = denom opposite = sympy.sqrt(denom**2 - numer**2) inverse = sympy.acos(relation[0]) elif isinstance(trig_function, sympy.tan): opposite = numer adjacent = denom hypotenuse = sympy.sqrt(denom**2 + numer**2) inverse = sympy.atan(relation[0]) substitution = [ (sympy.sin(theta), opposite/hypotenuse), (sympy.cos(theta), adjacent/hypotenuse), (sympy.tan(theta), opposite/adjacent), (theta, inverse) ] return sympy.Piecewise( (_manualintegrate(substep).subs(substitution).trigsimp(), restriction) )
def test_atan_rewrite(): assert atan(x).rewrite(log) == I*log((1 - I*x)/(1 + I*x))/2 assert atan(x).rewrite(asin) == (-asin(1/sqrt(x**2 + 1)) + pi/2)*sqrt(x**2)/x assert atan(x).rewrite(acos) == sqrt(x**2)*acos(1/sqrt(x**2 + 1))/x assert atan(x).rewrite(acot) == acot(1/x) assert atan(x).rewrite(asec) == sqrt(x**2)*asec(sqrt(x**2 + 1))/x assert atan(x).rewrite(acsc) == (-acsc(sqrt(x**2 + 1)) + pi/2)*sqrt(x**2)/x
def test_acot_rewrite(): assert acot(x).rewrite(log) == I*log((x - I)/(x + I))/2 assert acot(x).rewrite(asin) == x*(-asin(sqrt(-x**2)/sqrt(-x**2 - 1)) + pi/2)*sqrt(x**(-2)) assert acot(x).rewrite(acos) == x*sqrt(x**(-2))*acos(sqrt(-x**2)/sqrt(-x**2 - 1)) assert acot(x).rewrite(atan) == atan(1/x) assert acot(x).rewrite(asec) == x*sqrt(x**(-2))*asec(sqrt((x**2 + 1)/x**2)) assert acot(x).rewrite(acsc) == x*(-acsc(sqrt((x**2 + 1)/x**2)) + pi/2)*sqrt(x**(-2))
def jsify_expr(expr): clamp = Function("clamp") bottom_clamp = Function("bottom") x = Wild("x") # Prevent NaNs on inverse trig functions expr = expr.replace(asin, lambda x: asin(clamp(x, -1, 1))) expr = expr.replace(acos, lambda x: acos(clamp(x, -1, 1))) # Prevent NaNs on sqrts expr = expr.replace(sqrt(x + 1), sqrt(bottom_clamp(x + 1, 0))) js_expr = jscode(expr, user_functions = { "clamp": "THREE.Math.clamp", "bottom": "THREE.Math.clampBottom" }) # Convert all matrix references for compatibility with # three.js atoms = expr.atoms(Symbol) matrices = set([]) for atom in atoms: matrix_name = re.findall("([a-zA-Z]+)_\d,\d", atom.name) if len(matrix_name) > 0: matrices.add(matrix_name[0]) for matrix in matrices: js_expr = subs_matrix_elements(js_expr, matrix) return js_expr
def test_intrinsic_math1_codegen(): # not included: log10 from sympy import acos, asin, atan, ceiling, cos, cosh, floor, log, ln, \ sin, sinh, sqrt, tan, tanh, N x = symbols('x') name_expr = [ ("test_fabs", abs(x)), ("test_acos", acos(x)), ("test_asin", asin(x)), ("test_atan", atan(x)), ("test_cos", cos(x)), ("test_cosh", cosh(x)), ("test_log", log(x)), ("test_ln", ln(x)), ("test_sin", sin(x)), ("test_sinh", sinh(x)), ("test_sqrt", sqrt(x)), ("test_tan", tan(x)), ("test_tanh", tanh(x)), ] numerical_tests = [] for name, expr in name_expr: for xval in 0.2, 0.5, 0.8: expected = N(expr.subs(x, xval)) numerical_tests.append((name, (xval,), expected, 1e-14)) for lang, commands in valid_lang_commands: if lang == "C": name_expr_C = [("test_floor", floor(x)), ("test_ceil", ceiling(x))] else: name_expr_C = [] run_test("intrinsic_math1", name_expr + name_expr_C, numerical_tests, lang, commands)
def test_asin_rewrite(): assert asin(x).rewrite(log) == -I*log(I*x + sqrt(1 - x**2)) assert asin(x).rewrite(atan) == 2*atan(x/(1 + sqrt(1 - x**2))) assert asin(x).rewrite(acos) == S.Pi/2 - acos(x) assert asin(x).rewrite(acot) == 2*acot((sqrt(-x**2 + 1) + 1)/x) assert asin(x).rewrite(asec) == -asec(1/x) + pi/2 assert asin(x).rewrite(acsc) == acsc(1/x)
def test_issue_17141(): # Check that there is no RecursionError assert simplify(x**(1 / acos(I))) == x**(2 / (pi - 2 * I * log(1 + sqrt(2)))) assert simplify(acos(-I)**2*acos(I)**2) == \ log(1 + sqrt(2))**4 + pi**2*log(1 + sqrt(2))**2/2 + pi**4/16 assert simplify(2**acos(I)**2) == 2**((pi - 2 * I * log(1 + sqrt(2)))**2 / 4) p = 2**acos(I + 1)**2 assert simplify(p) == p # However, for a complex number it still happens if PY3: raises(RecursionError, lambda: simplify( (2**acos(I + 1)**2).rewrite('log'))) else: raises(RuntimeError, lambda: simplify( (2**acos(I + 1)**2).rewrite('log')))
def compute_internal_angles(self, theta_0, theta_1): """ Return the internal angles of the robot leg from the current motor angles """ D = sqrt(l_base**2 + l1**2 - 2 * l1 * l_base * cos(math.pi - theta_0)) Beta = asin((l1 / D) * sin(math.pi - theta_0)) Q1 = theta_1 - Beta A = 2 * l2 * (l1 * cos(Q1) - D) B = 2 * l1 * l2 * sin(Q1) C = 2 * D * l1 * cos(Q1) - (l1**2) - (D**2) Q2 = (atan(B / A) - acos(C / sqrt(A * A + B * B))) + math.pi # +or- alpha_1 = Q2 + Beta alpha_0 = math.pi - asin( (l1 * sin(theta_1) - l1 * sin(theta_0) + l2 * sin(alpha_1)) / l2) return (alpha_0, alpha_1)
def test_manualintegrate_trig_substitution(): assert manualintegrate(sqrt(16 * x ** 2 - 9) / x, x) == Piecewise( ( sqrt(16 * x ** 2 - 9) - 3 * acos(3 / (4 * x)), And(x < Rational(3, 4), x > Rational(-3, 4)), ) ) assert manualintegrate(1 / (x ** 4 * sqrt(25 - x ** 2)), x) == Piecewise( ( -sqrt(-(x ** 2) / 25 + 1) / (125 * x) - (-(x ** 2) / 25 + 1) ** (3 * S.Half) / (15 * x ** 3), And(x < 5, x > -5), ) ) assert manualintegrate(x ** 7 / (49 * x ** 2 + 1) ** (3 * S.Half), x) == ( (49 * x ** 2 + 1) ** (5 * S.Half) / 28824005 - (49 * x ** 2 + 1) ** (3 * S.Half) / 5764801 + 3 * sqrt(49 * x ** 2 + 1) / 5764801 + 1 / (5764801 * sqrt(49 * x ** 2 + 1)) )
def __init__(self): x, y, z, r, theta, theta_v, theta_a = symbols( "x,y,z,r,theta,theta_v,theta_a") m = 0.03 x_tag0 = (r + m) * sympy.cos(theta) + x y_tag0 = (r + m) * sympy.sin(theta) + y angle_delta = sympy.acos( (2 * r**2 - m * r) / (2 * r * sympy.sqrt(r**2 + m**2 - m * r))) d = sympy.sqrt(r**2 + m**2 - m * r) x_tag1 = d * sympy.cos(theta - angle_delta) + x y_tag1 = d * sympy.sin(theta - angle_delta) + y x_tag2 = d * sympy.cos(theta + angle_delta) + x y_tag2 = d * sympy.cos(theta + angle_delta) + y distance_tag0 = sympy.sqrt(x_tag0**2 + y_tag0**2 + z**2) distance_tag1 = sympy.sqrt(x_tag1**2 + y_tag1**2 + z**2) distance_tag2 = sympy.sqrt(x_tag2**2 + y_tag2**2 + z**2) fxu = Matrix([[distance_tag0], [distance_tag1], [distance_tag2]]) self.F_J = fxu.jacobian(Matrix([x, y, z, r, theta, theta_v, theta_a])) self.x, self.y, self.z, self.r, self.theta, self.theta_v, self.theta_a = x, y, z, r, theta, theta_v, theta_a self.subs = {x: 0, y: 0, z: 0, r: 0, theta: 0, theta_v: 0, theta_a: 0} pass
def test_quaternion_conversions(): q1 = Quaternion(1, 2, 3, 4) assert q1.to_axis_angle() == ((2 * sqrt(29)/29, 3 * sqrt(29)/29, 4 * sqrt(29)/29), 2 * acos(sqrt(30)/30)) assert q1.to_rotation_matrix() == Matrix([[-S(2)/3, S(2)/15, S(11)/15], [S(2)/3, -S(1)/3, S(14)/15], [S(1)/3, S(14)/15, S(2)/15]]) assert q1.to_rotation_matrix((1, 1, 1)) == Matrix([[-S(2)/3, S(2)/15, S(11)/15, S(4)/5], [S(2)/3, -S(1)/3, S(14)/15, -S(4)/15], [S(1)/3, S(14)/15, S(2)/15, -S(2)/5], [S(0), S(0), S(0), S(1)]]) theta = symbols("theta", real=True) q2 = Quaternion(cos(theta/2), 0, 0, sin(theta/2)) assert trigsimp(q2.to_rotation_matrix()) == Matrix( [[cos(theta), -sin(theta), 0], [sin(theta), cos(theta), 0], [0, 0, 1]])
def liu_vinokur_12(): lmbda = frac(4, 27) * (4 * sqrt(79) * cos( (acos(67 * sqrt(79) / 24964) + 2 * numpy.pi) / 3) + 71) alpha1 = (+sqrt(9 * lmbda**2 - 248 * lmbda + 1680) + 28 - 3 * lmbda) / (112 - 10 * lmbda) alpha2 = (-sqrt(9 * lmbda**2 - 248 * lmbda + 1680) + 28 - 3 * lmbda) / (112 - 10 * lmbda) w1 = ((21 - lmbda) * alpha2 - 7) / (420 * alpha1**2 * (alpha2 - alpha1)) w2 = ((21 - lmbda) * alpha1 - 7) / (420 * alpha2**2 * (alpha1 - alpha2)) weights = numpy.concatenate( [numpy.full(4, w1), numpy.full(4, w2), numpy.full(6, lmbda**2 / 840)]) points = numpy.concatenate( [_r_alpha(alpha1), _r_alpha(alpha2), _r_beta(1 / sqrt(lmbda))]) degree = 5 return TetrahedronScheme("Liu-Vinokur 12", weights, points, degree, citation)
def print_values(self, theta, Energy): print "wavelength (A): ",12398./Energy, " Energy (eV): ", Energy print "Bragg reflection: " for layer in self.Layers: print layer.Miller print "Surface: ", self.substrate.v_perp phi=np.degrees(float(sp.acos(self.substrate.H.normalized().dot(self.substrate.w3)).subs(self.substrate.structure.subs))) print "Bragg plane angle to surface (degrees): ", phi thetaBragg=self.substrate.thetaBragg thetaBraggdegree=np.degrees(thetaBragg) print "Bragg angle (degrees): ", thetaBraggdegree inc_angle=np.degrees(-np.arcsin(float(self.substrate.k_in_unit(thetaBragg)[2]))) print "Incident angle (degrees): ", inc_angle ex_angle=np.degrees(np.arcsin(float(self.substrate.k_sc_unit(thetaBragg)[2]))) print "Exit angle (degrees): ", ex_angle b=self.substrate.g0/self.substrate.gH print "Asymmetry factor: ", b if self.substrate.w1.dot(self.substrate.H)==0: print "Symmetric" if (self.substrate.w1.cross(self.substrate.w3)).dot(self.substrate.H.normalized())==0: print "Coplanar"
def to_axis_angle(self): """Returns the axis and angle of rotation of a quaternion Returns ======= tuple Tuple of (axis, angle) Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(1, 1, 1, 1) >>> (axis, angle) = q.to_axis_angle() >>> axis (sqrt(3)/3, sqrt(3)/3, sqrt(3)/3) >>> angle 2*pi/3 """ q = self if q.a.is_negative: q = q * -1 q = q.normalize() angle = trigsimp(2 * acos(q.a)) # Since quaternion is normalised, q.a is less than 1. s = sqrt(1 - q.a * q.a) x = trigsimp(q.b / s) y = trigsimp(q.c / s) z = trigsimp(q.d / s) v = (x, y, z) t = (v, angle) return t
def test_quaternion_functions(): q = Quaternion(x, y, z, w) q1 = Quaternion(1, 2, 3, 4) q0 = Quaternion(0, 0, 0, 0) assert conjugate(q) == Quaternion(x, -y, -z, -w) assert q.norm() == sqrt(w**2 + x**2 + y**2 + z**2) assert q.normalize() == Quaternion(x, y, z, w) / sqrt(w**2 + x**2 + y**2 + z**2) assert q.inverse() == Quaternion(x, -y, -z, -w) / (w**2 + x**2 + y**2 + z**2) raises(ValueError, lambda: q0.inverse()) assert q.pow(2) == Quaternion(-w**2 + x**2 - y**2 - z**2, 2 * x * y, 2 * x * z, 2 * w * x) assert q1.pow(-2) == Quaternion(-S(7) / 225, -S(1) / 225, -S(1) / 150, -S(2) / 225) assert q1.pow(-0.5) == NotImplemented assert q1.exp() == \ Quaternion(E * cos(sqrt(29)), 2 * sqrt(29) * E * sin(sqrt(29)) / 29, 3 * sqrt(29) * E * sin(sqrt(29)) / 29, 4 * sqrt(29) * E * sin(sqrt(29)) / 29) assert q1._ln() == \ Quaternion(log(sqrt(30)), 2 * sqrt(29) * acos(sqrt(30)/30) / 29, 3 * sqrt(29) * acos(sqrt(30)/30) / 29, 4 * sqrt(29) * acos(sqrt(30)/30) / 29) assert q1.pow_cos_sin(2) == \ Quaternion(30 * cos(2 * acos(sqrt(30)/30)), 60 * sqrt(29) * sin(2 * acos(sqrt(30)/30)) / 29, 90 * sqrt(29) * sin(2 * acos(sqrt(30)/30)) / 29, 120 * sqrt(29) * sin(2 * acos(sqrt(30)/30)) / 29) assert diff(Quaternion(x, x, x, x), x) == Quaternion(1, 1, 1, 1) assert integrate(Quaternion(x, x, x, x), x) == \ Quaternion(x**2 / 2, x**2 / 2, x**2 / 2, x**2 / 2) assert Quaternion.rotate_point((1, 1, 1), q1) == (1 / 5, 1, 7 / 5)
def to_axis_angle(self): """Returns the axis and angle of rotation of a quaternion Example ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(1, 1, 1, 1) >>> (axis, angle) = q.to_axis_angle() >>> axis (sqrt(3)/3, sqrt(3)/3, sqrt(3)/3) >>> angle 2*pi/3 """ q = self try: # Skips it if it doesn't know whether q.a is negative if q.a < 0: # avoid error with acos # axis and angle of rotation of q and q*-1 will be the same q = q * -1 except BaseException: pass q = q.normalize() angle = trigsimp(2 * acos(q.a)) # Since quaternion is normalised, q.a is less than 1. s = sqrt(1 - q.a * q.a) x = trigsimp(q.b / s) y = trigsimp(q.c / s) z = trigsimp(q.d / s) v = (x, y, z) t = (v, angle) return t
def test_bng_printer(): # Constants assert _bng_print(sympy.pi) == '_pi' assert _bng_print(sympy.E) == '_e' x, y = sympy.symbols('x y') # Binary functions assert _bng_print(sympy.sympify('x & y')) == 'x && y' assert _bng_print(sympy.sympify('x | y')) == 'x || y' # Trig functions assert _bng_print(sympy.sin(x)) == 'sin(x)' assert _bng_print(sympy.cos(x)) == 'cos(x)' assert _bng_print(sympy.tan(x)) == 'tan(x)' assert _bng_print(sympy.asin(x)) == 'asin(x)' assert _bng_print(sympy.acos(x)) == 'acos(x)' assert _bng_print(sympy.atan(x)) == 'atan(x)' assert _bng_print(sympy.sinh(x)) == 'sinh(x)' assert _bng_print(sympy.cosh(x)) == 'cosh(x)' assert _bng_print(sympy.tanh(x)) == 'tanh(x)' assert _bng_print(sympy.asinh(x)) == 'asinh(x)' assert _bng_print(sympy.acosh(x)) == 'acosh(x)' assert _bng_print(sympy.atanh(x)) == 'atanh(x)' # Logs and powers assert _bng_print(sympy.log(x)) == 'ln(x)' assert _bng_print(sympy.exp(x)) == 'exp(x)' assert _bng_print(sympy.sqrt(x)) == 'sqrt(x)' # Rounding assert _bng_print(sympy.Abs(x)) == 'abs(x)' assert _bng_print(sympy.floor(x)) == 'rint(x - 0.5)' assert _bng_print(sympy.ceiling(x)) == '(rint(x + 1) - 1)' # Min/max assert _bng_print(sympy.Min(x, y)) == 'min(x, y)' assert _bng_print(sympy.Max(x, y)) == 'max(x, y)'
def _set_inv_trans_equations(curv_coord_name): """ Store information about inverse transformation equations for pre-defined coordinate systems. Parameters ========== curv_coord_name : str Name of coordinate system """ if curv_coord_name == 'cartesian': return lambda x, y, z: (x, y, z) if curv_coord_name == 'spherical': return lambda x, y, z: (sqrt(x**2 + y**2 + z**2), acos(z / sqrt(x**2 + y**2 + z**2)), atan2(y, x)) if curv_coord_name == 'cylindrical': return lambda x, y, z: (sqrt(x**2 + y**2), atan2(y, x), z) raise ValueError('Wrong set of parameters.' 'Type of coordinate system is defined')
def theta_err(xval, yval, zval, x0val, y0val, z0val, dx, dx0, dy, dy0, dz, dz0): '''Finding error on the calculated value of theta''' x, y, z, x0, y0, z0 = sympy.symbols('x y z x0 y0 z0') f = sympy.Function('f') f = acos((z - z0) / sympy.sqrt((x - x0)**2 + (y - y0)**2 + (z - z0)**2)) subs = {x: xval, x0: x0val, y: yval, y0: y0val, z: zval, z0: z0val} div_x = sympy.diff(f, x) div_y = sympy.diff(f, y) div_z = sympy.diff(f, z) div_x0 = sympy.diff(f, x0) div_y0 = sympy.diff(f, y0) div_z0 = sympy.diff(f, z0) dee_x = div_x.evalf(subs=subs) dee_y = div_y.evalf(subs=subs) dee_z = div_z.evalf(subs=subs) dee_x0 = div_x0.evalf(subs=subs) dee_y0 = div_y0.evalf(subs=subs) dee_z0 = div_z0.evalf(subs=subs) f_error = math.sqrt((dee_x * dx)**2 + (dee_y * dy)**2 + (dee_z * dz)**2 + (dee_x0 * dx0)**2 + (dee_y0 * dy0)**2 + (dee_z0 * dz0)**2) return f_error
def compute_internal_angles(self, theta_0, theta_1): """ Return the internal angles of the robot leg from the current motor angles """ l1 = 7 # NEED TO UPDATE units of cm l2 = 14 # NEED TO UPDATE units of cm l_base = 7 # NEED TO UPDATE units of cm BE = (l_base**2 + l1**2 - 2 * l_base * l1 * sympy.cos(math.pi - theta_0))**0.5 ABE_angle = asin(l1 * sympy.sin(math.pi - theta_0) / BE) AEB_angle = theta_0 - ABE_angle CBE_angle = theta_1 - ABE_angle CE = (2 * l1**2 + l_base**2 - 2 * l_base * l1 * sympy.cos(math.pi - theta_0) - 2 * l1 * BE * sympy.cos(CBE_angle))**0.5 BCE_angle = asin(BE * sympy.sin(CBE_angle) / CE) BEC_angle = math.pi - BCE_angle - CBE_angle ECD_angle = acos((CE / 2) / l2) alpha_1 = BCE_angle + ECD_angle - (math.pi - theta_1) alpha_0 = 2 * math.pi - (math.pi - theta_0) - AEB_angle - BEC_angle - ECD_angle #Wrong Approach T-T #alpha_0, alpha_1, A, B, C, D, Beta, Q1, Q2 = symbols('alpha_0 alpha_1 A B C D Beta Q1 Q2', real = True) #D = sympy.sqrt(l_base**2 + l1**2 -2*l1*l_base*cos(math.pi - theta_0)) #Beta = sympy.simplify(asin((l1/D)*sin(math.pi-theta_0))) #Q1 = sympy.simplify(theta_1 - Beta) #A = sympy.simplify(2*l2*(l1*cos(Q1)-D)) #B = sympy.simplify(2*l1*l2*sin(Q1)) #C = sympy.simplify(2*D*l1*cos(Q1)-(l1**2)-(D**2)) #Q2 = sympy.simplify((atan(B/A)-acos(C/sympy.sqrt(A*A+B*B))) + math.pi) #alpha_1 = sympy.simplify(Q2 + Beta) #alpha_0 = sympy.simplify(math.pi - asin((l1*sin(theta_1) - l1*sin(theta_0) + l2*sin(alpha_1))/l2)) return (alpha_0, alpha_1)
def test_presentation_mathml_trig(): mml = mpp._print(sin(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'sin' mml = mpp._print(cos(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'cos' mml = mpp._print(tan(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'tan' mml = mpp._print(asin(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arcsin' mml = mpp._print(acos(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arccos' mml = mpp._print(atan(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arctan' mml = mpp._print(sinh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'sinh' mml = mpp._print(cosh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'cosh' mml = mpp._print(tanh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'tanh' mml = mpp._print(asinh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arcsinh' mml = mpp._print(atanh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arctanh' mml = mpp._print(acosh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arccosh'
def test_mathml_trig(): mml = mp._print(sin(x)) assert mml.childNodes[0].nodeName == 'sin' mml = mp._print(cos(x)) assert mml.childNodes[0].nodeName == 'cos' mml = mp._print(tan(x)) assert mml.childNodes[0].nodeName == 'tan' mml = mp._print(asin(x)) assert mml.childNodes[0].nodeName == 'arcsin' mml = mp._print(acos(x)) assert mml.childNodes[0].nodeName == 'arccos' mml = mp._print(atan(x)) assert mml.childNodes[0].nodeName == 'arctan' mml = mp._print(sinh(x)) assert mml.childNodes[0].nodeName == 'sinh' mml = mp._print(cosh(x)) assert mml.childNodes[0].nodeName == 'cosh' mml = mp._print(tanh(x)) assert mml.childNodes[0].nodeName == 'tanh' mml = mp._print(asinh(x)) assert mml.childNodes[0].nodeName == 'arcsinh' mml = mp._print(atanh(x)) assert mml.childNodes[0].nodeName == 'arctanh' mml = mp._print(acosh(x)) assert mml.childNodes[0].nodeName == 'arccosh'
def init_scalene_normal(base, a, b, c): C = acos((a**2 + b**2 - c**2)/(2*a*b)) rx = (a - b + c)/2 ry = (c - a + b)/2 r0 = abs((c - a - b)/2) if a*sin(C) <= rx or b*sin(C) <= ry: raise ValueError("The side lengths a, b, and c produce extra points") base.points = [ (cos(C)*(b + ry), sin(C)*(b + ry)), (cos(C)*b, sin(C)*b), (cos(C)*r0, sin(C)*r0), (0, 0), (-cos(C)*r0, -sin(C)*r0), (-r0, 0), (r0, 0), (a, 0), (a + rx, 0), (a - (a + r0)*rx/c, sin(C)*b*rx/c)] base.lines = [(0, 0, cos(C), sin(C)), (0, 0, 1, 0)] base.circles = [(0, 0, r0), (a, 0, rx), (cos(C)*b, sin(C)*b, ry)] for i, (x, y) in enumerate(base.points): base.points[i] = simplify(x), simplify(y) for i, (x, y, dx, dy) in enumerate(base.lines): base.lines[i] = simplify(x), simplify(y), simplify(dx), simplify(dy) for i, (x, y, r) in enumerate(base.circles): base.circles[i] = simplify(x), simplify(y), simplify(r) r = 1/(1/r0 + 1/rx + 1/ry + 2*sqrt(1/(r0*rx) + 1/(rx*ry) + 1/(ry*r0))) z = r*(a/rx + b*exp(I*C)/ry + 2*sqrt(a*b*exp(I*C)/(rx*ry))) base.goal = simplify(re(z)), simplify(im(z)), simplify(r)
def test_tsolve(): x = Symbol('x') y = Symbol('y') z = Symbol('z') assert solve(exp(x)-3, x) == [log(3)] assert solve(cos(x)-y, x) == [acos(y)] assert solve(2*cos(x)-y,x)== [acos(y/2)] # 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 tsolve(exp(x)-3, x) == [log(3)] assert tsolve(Eq(exp(x), 3), x) == [log(3)] assert tsolve(log(x)-3, x) == [exp(3)] assert tsolve(sqrt(3*x)-4, x) == [Rational(16,3)] assert tsolve(3**(x+2), x) == [-oo] assert tsolve(3**(2-x), x) == [oo] assert tsolve(4*3**(5*x+2)-7, x) == [(log(Rational(7,4))-2*log(3))/(5*log(3))] assert tsolve(x+2**x, x) == [-LambertW(log(2))/log(2)] assert tsolve(3*x+5+2**(-5*x+3), x) == \ [-Rational(5,3) + LambertW(-10240*2**Rational(1,3)*log(2)/3)/(5*log(2))] assert tsolve(5*x-1+3*exp(2-7*x), x) == \ [Rational(1,5) + LambertW(-21*exp(Rational(3,5))/5)/7] assert tsolve(2*x+5+log(3*x-2), x) == \ [Rational(2,3) + LambertW(2*exp(-Rational(19,3))/3)/2] assert tsolve(3*x+log(4*x), x) == [LambertW(Rational(3,4))/3] assert tsolve((2*x+8)*(8+exp(x)), x) == [-4] assert tsolve(2*exp(3*x+4)-3, x) == [-Rational(4,3)+log(Rational(3,2))/3] assert tsolve(2*log(3*x+4)-3, x) == [(exp(Rational(3,2))-4)/3] assert tsolve(exp(x)+1, x) == [pi*I] assert tsolve(x**2 - 2**x, x) == [2] assert tsolve(x**3 - 3**x, x) == [-3/log(3)*LambertW(-log(3)/3)] assert tsolve(2*(3*x+4)**5 - 6*7**(3*x+9), x) == \ [Rational(-4,3) - 5/log(7)/3*LambertW(-7*2**Rational(4,5)*6**Rational(1,5)*log(7)/10)] assert tsolve(z*cos(x)-y, x) == [acos(y/z)] assert tsolve(z*cos(2*x)-y, x) == [acos(y/z)/2] assert tsolve(z*cos(sin(x))-y, x) == [asin(acos(y/z))] assert tsolve(z*cos(x), x) == [acos(0)] assert tsolve(exp(x)+exp(-x)-y, x)== [log(y/2 + Rational(1,2)*(-4 + y**2)**Rational(1,2)), log(y/2 - Rational(1,2)*(-4 + y**2)**Rational(1,2))]
def test_quaternion_functions(): q = Quaternion(x, y, z, w) q1 = Quaternion(1, 2, 3, 4) assert conjugate(q) == Quaternion(x, -y, -z, -w) assert q.norm() == sqrt(w**2 + x**2 + y**2 + z**2) assert q.normalize() == Quaternion(x, y, z, w) / sqrt(w**2 + x**2 + y**2 + z**2) assert q.inverse() == Quaternion(x, -y, -z, -w) / (w**2 + x**2 + y**2 + z**2) assert q.pow(2) == Quaternion(-w**2 + x**2 - y**2 - z**2, 2 * x * y, 2 * x * z, 2 * w * x) assert q1.exp() == \ Quaternion(E * cos(sqrt(29)), 2 * sqrt(29) * E * sin(sqrt(29)) / 29, 3 * sqrt(29) * E * sin(sqrt(29)) / 29, 4 * sqrt(29) * E * sin(sqrt(29)) / 29) assert q1._ln() == \ Quaternion(log(sqrt(30)), 2 * sqrt(29) * acos(sqrt(30)/30) / 29, 3 * sqrt(29) * acos(sqrt(30)/30) / 29, 4 * sqrt(29) * acos(sqrt(30)/30) / 29) assert q1.pow_cos_sin(2) == \ Quaternion(30 * cos(2 * acos(sqrt(30)/30)), 60 * sqrt(29) * sin(2 * acos(sqrt(30)/30)) / 29, 90 * sqrt(29) * sin(2 * acos(sqrt(30)/30)) / 29, 120 * sqrt(29) * sin(2 * acos(sqrt(30)/30)) / 29) assert diff(Quaternion(x, x, x, x), x) == Quaternion(1, 1, 1, 1) assert integrate(Quaternion(x, x, x, x), x) == \ Quaternion(x**2 / 2, x**2 / 2, x**2 / 2, x**2 / 2) assert Quaternion.rotate_point((1, 1, 1), q1) == (1 / 5, 1, 7 / 5)
def test_bicycle(): if ON_TRAVIS: skip("Too slow for travis.") # Code to get equations of motion for a bicycle modeled as in: # J.P Meijaard, Jim M Papadopoulos, Andy Ruina and A.L Schwab. Linearized # dynamics equations for the balance and steer of a bicycle: a benchmark # and review. Proceedings of The Royal Society (2007) 463, 1955-1982 # doi: 10.1098/rspa.2007.1857 # Note that this code has been crudely ported from Autolev, which is the # reason for some of the unusual naming conventions. It was purposefully as # similar as possible in order to aide debugging. # Declare Coordinates & Speeds # Simple definitions for qdots - qd = u # Speeds are: yaw frame ang. rate, roll frame ang. rate, rear wheel frame # ang. rate (spinning motion), frame ang. rate (pitching motion), steering # frame ang. rate, and front wheel ang. rate (spinning motion). # Wheel positions are ignorable coordinates, so they are not introduced. q1, q2, q4, q5 = dynamicsymbols('q1 q2 q4 q5') q1d, q2d, q4d, q5d = dynamicsymbols('q1 q2 q4 q5', 1) u1, u2, u3, u4, u5, u6 = dynamicsymbols('u1 u2 u3 u4 u5 u6') u1d, u2d, u3d, u4d, u5d, u6d = dynamicsymbols('u1 u2 u3 u4 u5 u6', 1) # Declare System's Parameters WFrad, WRrad, htangle, forkoffset = symbols( 'WFrad WRrad htangle forkoffset') forklength, framelength, forkcg1 = symbols( 'forklength framelength forkcg1') forkcg3, framecg1, framecg3, Iwr11 = symbols( 'forkcg3 framecg1 framecg3 Iwr11') Iwr22, Iwf11, Iwf22, Iframe11 = symbols('Iwr22 Iwf11 Iwf22 Iframe11') Iframe22, Iframe33, Iframe31, Ifork11 = symbols( 'Iframe22 Iframe33 Iframe31 Ifork11') Ifork22, Ifork33, Ifork31, g = symbols('Ifork22 Ifork33 Ifork31 g') mframe, mfork, mwf, mwr = symbols('mframe mfork mwf mwr') # Set up reference frames for the system # N - inertial # Y - yaw # R - roll # WR - rear wheel, rotation angle is ignorable coordinate so not oriented # Frame - bicycle frame # TempFrame - statically rotated frame for easier reference inertia definition # Fork - bicycle fork # TempFork - statically rotated frame for easier reference inertia definition # WF - front wheel, again posses a ignorable coordinate N = ReferenceFrame('N') Y = N.orientnew('Y', 'Axis', [q1, N.z]) R = Y.orientnew('R', 'Axis', [q2, Y.x]) Frame = R.orientnew('Frame', 'Axis', [q4 + htangle, R.y]) WR = ReferenceFrame('WR') TempFrame = Frame.orientnew('TempFrame', 'Axis', [-htangle, Frame.y]) Fork = Frame.orientnew('Fork', 'Axis', [q5, Frame.x]) TempFork = Fork.orientnew('TempFork', 'Axis', [-htangle, Fork.y]) WF = ReferenceFrame('WF') # Kinematics of the Bicycle First block of code is forming the positions of # the relevant points # rear wheel contact -> rear wheel mass center -> frame mass center + # frame/fork connection -> fork mass center + front wheel mass center -> # front wheel contact point WR_cont = Point('WR_cont') WR_mc = WR_cont.locatenew('WR_mc', WRrad * R.z) Steer = WR_mc.locatenew('Steer', framelength * Frame.z) Frame_mc = WR_mc.locatenew('Frame_mc', -framecg1 * Frame.x + framecg3 * Frame.z) Fork_mc = Steer.locatenew('Fork_mc', -forkcg1 * Fork.x + forkcg3 * Fork.z) WF_mc = Steer.locatenew('WF_mc', forklength * Fork.x + forkoffset * Fork.z) WF_cont = WF_mc.locatenew( 'WF_cont', WFrad * (dot(Fork.y, Y.z) * Fork.y - Y.z).normalize()) # Set the angular velocity of each frame. # Angular accelerations end up being calculated automatically by # differentiating the angular velocities when first needed. # u1 is yaw rate # u2 is roll rate # u3 is rear wheel rate # u4 is frame pitch rate # u5 is fork steer rate # u6 is front wheel rate Y.set_ang_vel(N, u1 * Y.z) R.set_ang_vel(Y, u2 * R.x) WR.set_ang_vel(Frame, u3 * Frame.y) Frame.set_ang_vel(R, u4 * Frame.y) Fork.set_ang_vel(Frame, u5 * Fork.x) WF.set_ang_vel(Fork, u6 * Fork.y) # Form the velocities of the previously defined points, using the 2 - point # theorem (written out by hand here). Accelerations again are calculated # automatically when first needed. WR_cont.set_vel(N, 0) WR_mc.v2pt_theory(WR_cont, N, WR) Steer.v2pt_theory(WR_mc, N, Frame) Frame_mc.v2pt_theory(WR_mc, N, Frame) Fork_mc.v2pt_theory(Steer, N, Fork) WF_mc.v2pt_theory(Steer, N, Fork) WF_cont.v2pt_theory(WF_mc, N, WF) # Sets the inertias of each body. Uses the inertia frame to construct the # inertia dyadics. Wheel inertias are only defined by principle moments of # inertia, and are in fact constant in the frame and fork reference frames; # it is for this reason that the orientations of the wheels does not need # to be defined. The frame and fork inertias are defined in the 'Temp' # frames which are fixed to the appropriate body frames; this is to allow # easier input of the reference values of the benchmark paper. Note that # due to slightly different orientations, the products of inertia need to # have their signs flipped; this is done later when entering the numerical # value. Frame_I = (inertia(TempFrame, Iframe11, Iframe22, Iframe33, 0, 0, Iframe31), Frame_mc) Fork_I = (inertia(TempFork, Ifork11, Ifork22, Ifork33, 0, 0, Ifork31), Fork_mc) WR_I = (inertia(Frame, Iwr11, Iwr22, Iwr11), WR_mc) WF_I = (inertia(Fork, Iwf11, Iwf22, Iwf11), WF_mc) # Declaration of the RigidBody containers. :: BodyFrame = RigidBody('BodyFrame', Frame_mc, Frame, mframe, Frame_I) BodyFork = RigidBody('BodyFork', Fork_mc, Fork, mfork, Fork_I) BodyWR = RigidBody('BodyWR', WR_mc, WR, mwr, WR_I) BodyWF = RigidBody('BodyWF', WF_mc, WF, mwf, WF_I) # The kinematic differential equations; they are defined quite simply. Each # entry in this list is equal to zero. kd = [q1d - u1, q2d - u2, q4d - u4, q5d - u5] # The nonholonomic constraints are the velocity of the front wheel contact # point dotted into the X, Y, and Z directions; the yaw frame is used as it # is "closer" to the front wheel (1 less DCM connecting them). These # constraints force the velocity of the front wheel contact point to be 0 # in the inertial frame; the X and Y direction constraints enforce a # "no-slip" condition, and the Z direction constraint forces the front # wheel contact point to not move away from the ground frame, essentially # replicating the holonomic constraint which does not allow the frame pitch # to change in an invalid fashion. conlist_speed = [ WF_cont.vel(N) & Y.x, WF_cont.vel(N) & Y.y, WF_cont.vel(N) & Y.z ] # The holonomic constraint is that the position from the rear wheel contact # point to the front wheel contact point when dotted into the # normal-to-ground plane direction must be zero; effectively that the front # and rear wheel contact points are always touching the ground plane. This # is actually not part of the dynamic equations, but instead is necessary # for the lineraization process. conlist_coord = [WF_cont.pos_from(WR_cont) & Y.z] # The force list; each body has the appropriate gravitational force applied # at its mass center. FL = [(Frame_mc, -mframe * g * Y.z), (Fork_mc, -mfork * g * Y.z), (WF_mc, -mwf * g * Y.z), (WR_mc, -mwr * g * Y.z)] BL = [BodyFrame, BodyFork, BodyWR, BodyWF] # The N frame is the inertial frame, coordinates are supplied in the order # of independent, dependent coordinates, as are the speeds. The kinematic # differential equation are also entered here. Here the dependent speeds # are specified, in the same order they were provided in earlier, along # with the non-holonomic constraints. The dependent coordinate is also # provided, with the holonomic constraint. Again, this is only provided # for the linearization process. KM = KanesMethod(N, q_ind=[q1, q2, q5], q_dependent=[q4], configuration_constraints=conlist_coord, u_ind=[u2, u3, u5], u_dependent=[u1, u4, u6], velocity_constraints=conlist_speed, kd_eqs=kd) (fr, frstar) = KM.kanes_equations(FL, BL) # This is the start of entering in the numerical values from the benchmark # paper to validate the eigen values of the linearized equations from this # model to the reference eigen values. Look at the aforementioned paper for # more information. Some of these are intermediate values, used to # transform values from the paper into the coordinate systems used in this # model. PaperRadRear = 0.3 PaperRadFront = 0.35 HTA = evalf.N(pi / 2 - pi / 10) TrailPaper = 0.08 rake = evalf.N(-(TrailPaper * sin(HTA) - (PaperRadFront * cos(HTA)))) PaperWb = 1.02 PaperFrameCgX = 0.3 PaperFrameCgZ = 0.9 PaperForkCgX = 0.9 PaperForkCgZ = 0.7 FrameLength = evalf.N(PaperWb * sin(HTA) - (rake - (PaperRadFront - PaperRadRear) * cos(HTA))) FrameCGNorm = evalf.N((PaperFrameCgZ - PaperRadRear - (PaperFrameCgX / sin(HTA)) * cos(HTA)) * sin(HTA)) FrameCGPar = evalf.N( (PaperFrameCgX / sin(HTA) + (PaperFrameCgZ - PaperRadRear - PaperFrameCgX / sin(HTA) * cos(HTA)) * cos(HTA))) tempa = evalf.N((PaperForkCgZ - PaperRadFront)) tempb = evalf.N((PaperWb - PaperForkCgX)) tempc = evalf.N(sqrt(tempa**2 + tempb**2)) PaperForkL = evalf.N( (PaperWb * cos(HTA) - (PaperRadFront - PaperRadRear) * sin(HTA))) ForkCGNorm = evalf.N(rake + (tempc * sin(pi / 2 - HTA - acos(tempa / tempc)))) ForkCGPar = evalf.N(tempc * cos((pi / 2 - HTA) - acos(tempa / tempc)) - PaperForkL) # Here is the final assembly of the numerical values. The symbol 'v' is the # forward speed of the bicycle (a concept which only makes sense in the # upright, static equilibrium case?). These are in a dictionary which will # later be substituted in. Again the sign on the *product* of inertia # values is flipped here, due to different orientations of coordinate # systems. v = symbols('v') val_dict = { WFrad: PaperRadFront, WRrad: PaperRadRear, htangle: HTA, forkoffset: rake, forklength: PaperForkL, framelength: FrameLength, forkcg1: ForkCGPar, forkcg3: ForkCGNorm, framecg1: FrameCGNorm, framecg3: FrameCGPar, Iwr11: 0.0603, Iwr22: 0.12, Iwf11: 0.1405, Iwf22: 0.28, Ifork11: 0.05892, Ifork22: 0.06, Ifork33: 0.00708, Ifork31: 0.00756, Iframe11: 9.2, Iframe22: 11, Iframe33: 2.8, Iframe31: -2.4, mfork: 4, mframe: 85, mwf: 3, mwr: 2, g: 9.81, q1: 0, q2: 0, q4: 0, q5: 0, u1: 0, u2: 0, u3: v / PaperRadRear, u4: 0, u5: 0, u6: v / PaperRadFront } # Linearizes the forcing vector; the equations are set up as MM udot = # forcing, where MM is the mass matrix, udot is the vector representing the # time derivatives of the generalized speeds, and forcing is a vector which # contains both external forcing terms and internal forcing terms, such as # centripital or coriolis forces. This actually returns a matrix with as # many rows as *total* coordinates and speeds, but only as many columns as # independent coordinates and speeds. with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=SymPyDeprecationWarning) forcing_lin = KM.linearize()[0] # As mentioned above, the size of the linearized forcing terms is expanded # to include both q's and u's, so the mass matrix must have this done as # well. This will likely be changed to be part of the linearized process, # for future reference. MM_full = KM.mass_matrix_full MM_full_s = MM_full.subs(val_dict) forcing_lin_s = forcing_lin.subs(KM.kindiffdict()).subs(val_dict) MM_full_s = MM_full_s.evalf() forcing_lin_s = forcing_lin_s.evalf() # Finally, we construct an "A" matrix for the form xdot = A x (x being the # state vector, although in this case, the sizes are a little off). The # following line extracts only the minimum entries required for eigenvalue # analysis, which correspond to rows and columns for lean, steer, lean # rate, and steer rate. Amat = MM_full_s.inv() * forcing_lin_s A = Amat.extract([1, 2, 4, 6], [1, 2, 3, 5]) # Precomputed for comparison Res = Matrix([[0, 0, 1.0, 0], [0, 0, 0, 1.0], [ 9.48977444677355, -0.891197738059089 * v**2 - 0.571523173729245, -0.105522449805691 * v, -0.330515398992311 * v ], [ 11.7194768719633, -1.97171508499972 * v**2 + 30.9087533932407, 3.67680523332152 * v, -3.08486552743311 * v ]]) # Actual eigenvalue comparison eps = 1.e-12 for i in xrange(6): error = Res.subs(v, i) - A.subs(v, i) assert all(abs(x) < eps for x in error)
def test_Abs(): raises(TypeError, lambda: Abs(Interval(2, 3))) # issue 8717 x, y = symbols('x,y') assert sign(sign(x)) == sign(x) assert sign(x*y).func is sign assert Abs(0) == 0 assert Abs(1) == 1 assert Abs(-1) == 1 assert Abs(I) == 1 assert Abs(-I) == 1 assert Abs(nan) is nan assert Abs(zoo) is oo assert Abs(I * pi) == pi assert Abs(-I * pi) == pi assert Abs(I * x) == Abs(x) assert Abs(-I * x) == Abs(x) assert Abs(-2*x) == 2*Abs(x) assert Abs(-2.0*x) == 2.0*Abs(x) assert Abs(2*pi*x*y) == 2*pi*Abs(x*y) assert Abs(conjugate(x)) == Abs(x) assert conjugate(Abs(x)) == Abs(x) assert Abs(x).expand(complex=True) == sqrt(re(x)**2 + im(x)**2) a = Symbol('a', positive=True) assert Abs(2*pi*x*a) == 2*pi*a*Abs(x) assert Abs(2*pi*I*x*a) == 2*pi*a*Abs(x) x = Symbol('x', real=True) n = Symbol('n', integer=True) assert Abs((-1)**n) == 1 assert x**(2*n) == Abs(x)**(2*n) assert Abs(x).diff(x) == sign(x) assert abs(x) == Abs(x) # Python built-in assert Abs(x)**3 == x**2*Abs(x) assert Abs(x)**4 == x**4 assert ( Abs(x)**(3*n)).args == (Abs(x), 3*n) # leave symbolic odd unchanged assert (1/Abs(x)).args == (Abs(x), -1) assert 1/Abs(x)**3 == 1/(x**2*Abs(x)) assert Abs(x)**-3 == Abs(x)/(x**4) assert Abs(x**3) == x**2*Abs(x) assert Abs(I**I) == exp(-pi/2) assert Abs((4 + 5*I)**(6 + 7*I)) == 68921*exp(-7*atan(Rational(5, 4))) y = Symbol('y', real=True) assert Abs(I**y) == 1 y = Symbol('y') assert Abs(I**y) == exp(-pi*im(y)/2) x = Symbol('x', imaginary=True) assert Abs(x).diff(x) == -sign(x) eq = -sqrt(10 + 6*sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3)) # if there is a fast way to know when you can and when you cannot prove an # expression like this is zero then the equality to zero is ok assert abs(eq).func is Abs or abs(eq) == 0 # but sometimes it's hard to do this so it's better not to load # abs down with tests that will be very slow q = 1 + sqrt(2) - 2*sqrt(3) + 1331*sqrt(6) p = expand(q**3)**Rational(1, 3) d = p - q assert abs(d).func is Abs or abs(d) == 0 assert Abs(4*exp(pi*I/4)) == 4 assert Abs(3**(2 + I)) == 9 assert Abs((-3)**(1 - I)) == 3*exp(pi) assert Abs(oo) is oo assert Abs(-oo) is oo assert Abs(oo + I) is oo assert Abs(oo + I*oo) is oo a = Symbol('a', algebraic=True) t = Symbol('t', transcendental=True) x = Symbol('x') assert re(a).is_algebraic assert re(x).is_algebraic is None assert re(t).is_algebraic is False assert Abs(x).fdiff() == sign(x) raises(ArgumentIndexError, lambda: Abs(x).fdiff(2)) # doesn't have recursion error arg = sqrt(acos(1 - I)*acos(1 + I)) assert abs(arg) == arg # special handling to put Abs in denom assert abs(1/x) == 1/Abs(x) e = abs(2/x**2) assert e.is_Mul and e == 2/Abs(x**2) assert unchanged(Abs, y/x) assert unchanged(Abs, x/(x + 1)) assert unchanged(Abs, x*y) p = Symbol('p', positive=True) assert abs(x/p) == abs(x)/p # coverage assert unchanged(Abs, Symbol('x', real=True)**y)
def test_issue_4052(): f = S(1) / 2 * asin(x) + x * sqrt(1 - x**2) / 2 assert integrate(cos(asin(x)), x) == f assert integrate(sin(acos(x)), x) == f
of refractive index "index" $n=1$ ''' # %% theta = sp.symbols('theta') index, gamma = sp.symbols('n gamma', positive=True) N_t = sp.sign(theta) / gamma * ( 1 - index - sp.cos(theta) + sp.sqrt(index**2 - sp.sin(theta)**2)) # %% N = sp.symbols('N') theta_t = sp.sign(N) * sp.acos(index**2 - 1 - (gamma * sp.Abs(N) + index - 1)**2)/(2*(gamma*sp.Abs(N)+index-1)) # %% N_t theta_t # %% #sp.series(theta_t, x=N, x0=1, n=3) print(sp.latex(sp.series(N_t, x=theta, x0=0, n=5))) # %%
import sympy.physics.mechanics as _me import sympy as _sm import math as m import numpy as _np x, y = _me.dynamicsymbols('x y') x_d, y_d = _me.dynamicsymbols('x_ y_', 1) e = _sm.cos(x)+_sm.sin(x)+_sm.tan(x)+_sm.cosh(x)+_sm.sinh(x)+_sm.tanh(x)+_sm.acos(x)+_sm.asin(x)+_sm.atan(x)+_sm.log(x)+_sm.exp(x)+_sm.sqrt(x)+_sm.factorial(x)+_sm.ceiling(x)+_sm.floor(x)+_sm.sign(x) e = (x)**2+_sm.log(x, 10) a = _sm.Abs(-1*1)+int(1.5)+round(1.9) e1 = 2*x+3*y e2 = x+y am = _sm.Matrix([e1.expand().coeff(x), e1.expand().coeff(y), e2.expand().coeff(x), e2.expand().coeff(y)]).reshape(2, 2) b = (e1).expand().coeff(x) c = (e2).expand().coeff(y) d1 = (e1).collect(x).coeff(x,0) d2 = (e1).collect(x).coeff(x,1) fm = _sm.Matrix([i.collect(x)for i in _sm.Matrix([e1,e2]).reshape(1, 2)]).reshape((_sm.Matrix([e1,e2]).reshape(1, 2)).shape[0], (_sm.Matrix([e1,e2]).reshape(1, 2)).shape[1]) f = (e1).collect(y) g = (e1).subs({x:2*x}) gm = _sm.Matrix([i.subs({x:3}) for i in _sm.Matrix([e1,e2]).reshape(2, 1)]).reshape((_sm.Matrix([e1,e2]).reshape(2, 1)).shape[0], (_sm.Matrix([e1,e2]).reshape(2, 1)).shape[1]) frame_a = _me.ReferenceFrame('a') frame_b = _me.ReferenceFrame('b') theta = _me.dynamicsymbols('theta') frame_b.orient(frame_a, 'Axis', [theta, frame_a.z]) v1 = 2*frame_a.x-3*frame_a.y+frame_a.z v2 = frame_b.x+frame_b.y+frame_b.z a = _me.dot(v1, v2) bm = _sm.Matrix([_me.dot(v1, v2),_me.dot(v1, 2*v2)]).reshape(2, 1) c = _me.cross(v1, v2) d = 2*v1.magnitude()+3*v1.magnitude()
def test_issue_17141_slow(): # Should not give RecursionError assert simplify((2**acos(I + 1)**2).rewrite('log')) == 2**( (pi + 2 * I * log(-1 + sqrt(1 - 2 * I) + I))**2 / 4)
def test_transformation_equations(): x, y, z = symbols("x y z") # Str a = CoordSys3D("a", transformation="spherical", variable_names=["r", "theta", "phi"]) r, theta, phi = a.base_scalars() assert r == a.r assert theta == a.theta assert phi == a.phi raises(AttributeError, lambda: a.x) raises(AttributeError, lambda: a.y) raises(AttributeError, lambda: a.z) assert a.transformation_to_parent() == ( r * sin(theta) * cos(phi), r * sin(theta) * sin(phi), r * cos(theta), ) assert a.lame_coefficients() == (1, r, r * sin(theta)) assert a.transformation_from_parent_function()(x, y, z) == ( sqrt(x**2 + y**2 + z**2), acos((z) / sqrt(x**2 + y**2 + z**2)), atan2(y, x), ) a = CoordSys3D("a", transformation="cylindrical", variable_names=["r", "theta", "z"]) r, theta, z = a.base_scalars() assert a.transformation_to_parent() == (r * cos(theta), r * sin(theta), z) assert a.lame_coefficients() == (1, a.r, 1) assert a.transformation_from_parent_function()(x, y, z) == ( sqrt(x**2 + y**2), atan2(y, x), z, ) a = CoordSys3D("a", "cartesian") assert a.transformation_to_parent() == (a.x, a.y, a.z) assert a.lame_coefficients() == (1, 1, 1) assert a.transformation_from_parent_function()(x, y, z) == (x, y, z) # Variables and expressions # Cartesian with equation tuple: x, y, z = symbols("x y z") a = CoordSys3D("a", ((x, y, z), (x, y, z))) a._calculate_inv_trans_equations() assert a.transformation_to_parent() == (a.x1, a.x2, a.x3) assert a.lame_coefficients() == (1, 1, 1) assert a.transformation_from_parent_function()(x, y, z) == (x, y, z) r, theta, z = symbols("r theta z") # Cylindrical with equation tuple: a = CoordSys3D( "a", [(r, theta, z), (r * cos(theta), r * sin(theta), z)], variable_names=["r", "theta", "z"], ) r, theta, z = a.base_scalars() assert a.transformation_to_parent() == (r * cos(theta), r * sin(theta), z) assert a.lame_coefficients() == ( sqrt(sin(theta)**2 + cos(theta)**2), sqrt(r**2 * sin(theta)**2 + r**2 * cos(theta)**2), 1, ) # ==> this should simplify to (1, r, 1), tests are too slow with `simplify`. # Definitions with `lambda`: # Cartesian with `lambda` a = CoordSys3D("a", lambda x, y, z: (x, y, z)) assert a.transformation_to_parent() == (a.x1, a.x2, a.x3) assert a.lame_coefficients() == (1, 1, 1) a._calculate_inv_trans_equations() assert a.transformation_from_parent_function()(x, y, z) == (x, y, z) # Spherical with `lambda` a = CoordSys3D( "a", lambda r, theta, phi: ( r * sin(theta) * cos(phi), r * sin(theta) * sin(phi), r * cos(theta), ), variable_names=["r", "theta", "phi"], ) r, theta, phi = a.base_scalars() assert a.transformation_to_parent() == ( r * sin(theta) * cos(phi), r * sin(phi) * sin(theta), r * cos(theta), ) assert a.lame_coefficients() == ( sqrt( sin(phi)**2 * sin(theta)**2 + sin(theta)**2 * cos(phi)**2 + cos(theta)**2), sqrt(r**2 * sin(phi)**2 * cos(theta)**2 + r**2 * sin(theta)**2 + r**2 * cos(phi)**2 * cos(theta)**2), sqrt(r**2 * sin(phi)**2 * sin(theta)**2 + r**2 * sin(theta)**2 * cos(phi)**2), ) # ==> this should simplify to (1, r, sin(theta)*r), `simplify` is too slow. # Cylindrical with `lambda` a = CoordSys3D( "a", lambda r, theta, z: (r * cos(theta), r * sin(theta), z), variable_names=["r", "theta", "z"], ) r, theta, z = a.base_scalars() assert a.transformation_to_parent() == (r * cos(theta), r * sin(theta), z) assert a.lame_coefficients() == ( sqrt(sin(theta)**2 + cos(theta)**2), sqrt(r**2 * sin(theta)**2 + r**2 * cos(theta)**2), 1, ) # ==> this should simplify to (1, a.x, 1) raises( TypeError, lambda: CoordSys3D( "a", transformation={ x: x * sin(y) * cos(z), y: x * sin(y) * sin(z), z: x * cos(y), }, ), )
print('Z') print(eqnZ) #For Paper thisIsOne = sp.simplify( ((eqnX / eqnr)**2 + (eqnY / eqnr)**2 + (eqnZ / eqnr)**2)) thetaEquation = sp.simplify(eqnY / eqnX) FORPAPER_eqnS_eqnr = sp.simplify(sp.sqrt((eqnX / eqnr)**2. + (eqnY / eqnr)**2.)) #s eqnS = sp.sqrt(eqnX**2. + eqnY**2.) eqnSAlpha = a * sp.sin(alpha * np.pi / 180.) #alpha in deg eqnAlpha1 = sp.acos( eqnZ / sp.sqrt(eqnX**2. + eqnY**2. + eqnZ**2.)) * 180. / np.pi eqnAlpha2 = sp.asin( eqnS / sp.sqrt(eqnX**2. + eqnY**2. + eqnZ**2.)) * 180. / np.pi print('Alpha') print(eqnAlpha1) #dmag eqnDmagInside = p * (R / a)**2. * Phi eqnDmag = -2.5 * sp.log(eqnDmagInside, 10) #### PHASE FUNCTIONS ############## #LAMBERT eqnLAMBERT = ( sp.sin(alpha * np.pi / 180.) + (np.pi - alpha * np.pi / 180.) * sp.cos(alpha * np.pi / 180.)) / np.pi
def test_solve_lambert(): assert solveset_real(x * exp(x) - 1, x) == FiniteSet(LambertW(1)) assert solveset_real(x + 2**x, x) == \ FiniteSet(-LambertW(log(2))/log(2)) # issue 4739 assert solveset_real(exp(log(5) * x) - 2**x, x) == FiniteSet(0) ans = solveset_real(3 * x + 5 + 2**(-5 * x + 3), x) assert ans == FiniteSet(-Rational(5, 3) + LambertW(-10240 * 2**(S(1) / 3) * log(2) / 3) / (5 * log(2))) eq = 2 * (3 * x + 4)**5 - 6 * 7**(3 * x + 9) result = solveset_real(eq, x) ans = FiniteSet( (log(2401) + 5 * LambertW(-log(7**(7 * 3**Rational(1, 5) / 5)))) / (3 * log(7)) / -1) assert result == ans assert solveset_real(eq.expand(), x) == result assert solveset_real(5*x - 1 + 3*exp(2 - 7*x), x) == \ FiniteSet(Rational(1, 5) + LambertW(-21*exp(Rational(3, 5))/5)/7) assert solveset_real(2*x + 5 + log(3*x - 2), x) == \ FiniteSet(Rational(2, 3) + LambertW(2*exp(-Rational(19, 3))/3)/2) assert solveset_real(3*x + log(4*x), x) == \ FiniteSet(LambertW(Rational(3, 4))/3) assert solveset_complex(x**z*y**z - 2, z) == \ FiniteSet(log(2)/(log(x) + log(y))) assert solveset_real(x**x - 2) == FiniteSet(exp(LambertW(log(2)))) a = Symbol('a') assert solveset_real(-a * x + 2 * x * log(x), x) == FiniteSet(exp(a / 2)) a = Symbol('a', real=True) assert solveset_real(a/x + exp(x/2), x) == \ FiniteSet(2*LambertW(-a/2)) assert solveset_real((a/x + exp(x/2)).diff(x), x) == \ FiniteSet(4*LambertW(sqrt(2)*sqrt(a)/4)) assert solveset_real(1 / (1 / x - y + exp(y)), x) == EmptySet() # coverage test p = Symbol('p', positive=True) w = Symbol('w') assert solveset_real((1 / p + 1)**(p + 1), p) == EmptySet() assert solveset_real(tanh(x + 3) * tanh(x - 3) - 1, x) == EmptySet() assert solveset_real(2*x**w - 4*y**w, w) == \ solveset_real((x/y)**w - 2, w) assert solveset_real((x**2 - 2*x + 1).subs(x, log(x) + 3*x), x) == \ FiniteSet(LambertW(3*S.Exp1)/3) assert solveset_real((x**2 - 2*x + 1).subs(x, (log(x) + 3*x)**2 - 1), x) == \ FiniteSet(LambertW(3*exp(-sqrt(2)))/3, LambertW(3*exp(sqrt(2)))/3) assert solveset_real((x**2 - 2*x - 2).subs(x, log(x) + 3*x), x) == \ FiniteSet(LambertW(3*exp(1 + sqrt(3)))/3, LambertW(3*exp(-sqrt(3) + 1))/3) assert solveset_real(x*log(x) + 3*x + 1, x) == \ FiniteSet(exp(-3 + LambertW(-exp(3)))) eq = (x * exp(x) - 3).subs(x, x * exp(x)) assert solveset_real(eq, x) == \ FiniteSet(LambertW(3*exp(-LambertW(3)))) assert solveset_real(3*log(a**(3*x + 5)) + a**(3*x + 5), x) == \ FiniteSet(-((log(a**5) + LambertW(S(1)/3))/(3*log(a)))) p = symbols('p', positive=True) assert solveset_real(3*log(p**(3*x + 5)) + p**(3*x + 5), x) == \ FiniteSet( log((-3**(S(1)/3) - 3**(S(5)/6)*I)*LambertW(S(1)/3)**(S(1)/3)/(2*p**(S(5)/3)))/log(p), log((-3**(S(1)/3) + 3**(S(5)/6)*I)*LambertW(S(1)/3)**(S(1)/3)/(2*p**(S(5)/3)))/log(p), log((3*LambertW(S(1)/3)/p**5)**(1/(3*log(p)))),) # checked numerically # check collection b = Symbol('b') eq = 3 * log(a**(3 * x + 5)) + b * log(a**(3 * x + 5)) + a**(3 * x + 5) assert solveset_real( eq, x) == FiniteSet(-((log(a**5) + LambertW(1 / (b + 3))) / (3 * log(a)))) # issue 4271 assert solveset_real((a / x + exp(x / 2)).diff(x, 2), x) == FiniteSet(6 * LambertW( (-1)**(S(1) / 3) * a**(S(1) / 3) / 3)) assert solveset_real(x**3 - 3**x, x) == \ FiniteSet(-3/log(3)*LambertW(-log(3)/3)) assert solveset_real(x**2 - 2**x, x) == FiniteSet(2) assert solveset_real(-x**2 + 2**x, x) == FiniteSet(2) assert solveset_real(3**cos(x) - cos(x)**3) == FiniteSet( acos(-3 * LambertW(-log(3) / 3) / log(3))) assert solveset_real(4**(x / 2) - 2**(x / 3), x) == FiniteSet(0) assert solveset_real(5**(x / 2) - 2**(x / 3), x) == FiniteSet(0) b = sqrt(6) * sqrt(log(2)) / sqrt(log(5)) assert solveset_real(5**(x / 2) - 2**(3 / x), x) == FiniteSet(-b, b)
def test_invert_real(): x = Symbol('x', real=True) y = Symbol('y') n = Symbol('n') def ireal(x, s=S.Reals): return Intersection(s, x) minus_n = Intersection(Interval(-oo, 0), FiniteSet(-n)) plus_n = Intersection(Interval(0, oo), FiniteSet(n)) assert solveset(abs(x) - n, x, S.Reals) == Union(minus_n, plus_n) assert invert_real(exp(x), y, x) == (x, ireal(FiniteSet(log(y)))) y = Symbol('y', positive=True) n = Symbol('n', real=True) assert invert_real(x + 3, y, x) == (x, FiniteSet(y - 3)) assert invert_real(x * 3, y, x) == (x, FiniteSet(y / 3)) assert invert_real(exp(x), y, x) == (x, FiniteSet(log(y))) assert invert_real(exp(3 * x), y, x) == (x, FiniteSet(log(y) / 3)) assert invert_real(exp(x + 3), y, x) == (x, FiniteSet(log(y) - 3)) assert invert_real(exp(x) + 3, y, x) == (x, ireal(FiniteSet(log(y - 3)))) assert invert_real(exp(x) * 3, y, x) == (x, FiniteSet(log(y / 3))) assert invert_real(log(x), y, x) == (x, FiniteSet(exp(y))) assert invert_real(log(3 * x), y, x) == (x, FiniteSet(exp(y) / 3)) assert invert_real(log(x + 3), y, x) == (x, FiniteSet(exp(y) - 3)) minus_y = Intersection(Interval(-oo, 0), FiniteSet(-y)) plus_y = Intersection(Interval(0, oo), FiniteSet(y)) assert invert_real(Abs(x), y, x) == (x, Union(minus_y, plus_y)) assert invert_real(2**x, y, x) == (x, FiniteSet(log(y) / log(2))) assert invert_real(2**exp(x), y, x) == (x, ireal(FiniteSet(log(log(y) / log(2))))) assert invert_real(x**2, y, x) == (x, FiniteSet(sqrt(y), -sqrt(y))) assert invert_real(x**Rational(1, 2), y, x) == (x, FiniteSet(y**2)) raises(ValueError, lambda: invert_real(x, x, x)) raises(ValueError, lambda: invert_real(x**pi, y, x)) raises(ValueError, lambda: invert_real(S.One, y, x)) assert invert_real(x**31 + x, y, x) == (x**31 + x, FiniteSet(y)) y_1 = Intersection(Interval(-1, oo), FiniteSet(y - 1)) y_2 = Intersection(Interval(-oo, -1), FiniteSet(-y - 1)) assert invert_real(Abs(x**31 + x + 1), y, x) == (x**31 + x, Union(y_1, y_2)) assert invert_real(sin(x), y, x) == \ (x, imageset(Lambda(n, n*pi + (-1)**n*asin(y)), S.Integers)) assert invert_real(sin(exp(x)), y, x) == \ (x, imageset(Lambda(n, log((-1)**n*asin(y) + n*pi)), S.Integers)) assert invert_real(csc(x), y, x) == \ (x, imageset(Lambda(n, n*pi + (-1)**n*acsc(y)), S.Integers)) assert invert_real(csc(exp(x)), y, x) == \ (x, imageset(Lambda(n, log((-1)**n*acsc(y) + n*pi)), S.Integers)) assert invert_real(cos(x), y, x) == \ (x, Union(imageset(Lambda(n, 2*n*pi + acos(y)), S.Integers), \ imageset(Lambda(n, 2*n*pi - acos(y)), S.Integers))) assert invert_real(cos(exp(x)), y, x) == \ (x, Union(imageset(Lambda(n, log(2*n*pi + acos(y))), S.Integers), \ imageset(Lambda(n, log(2*n*pi - acos(y))), S.Integers))) assert invert_real(sec(x), y, x) == \ (x, Union(imageset(Lambda(n, 2*n*pi + asec(y)), S.Integers), \ imageset(Lambda(n, 2*n*pi - asec(y)), S.Integers))) assert invert_real(sec(exp(x)), y, x) == \ (x, Union(imageset(Lambda(n, log(2*n*pi + asec(y))), S.Integers), \ imageset(Lambda(n, log(2*n*pi - asec(y))), S.Integers))) assert invert_real(tan(x), y, x) == \ (x, imageset(Lambda(n, n*pi + atan(y)), S.Integers)) assert invert_real(tan(exp(x)), y, x) == \ (x, imageset(Lambda(n, log(n*pi + atan(y))), S.Integers)) assert invert_real(cot(x), y, x) == \ (x, imageset(Lambda(n, n*pi + acot(y)), S.Integers)) assert invert_real(cot(exp(x)), y, x) == \ (x, imageset(Lambda(n, log(n*pi + acot(y))), S.Integers)) assert invert_real(tan(tan(x)), y, x) == \ (tan(x), imageset(Lambda(n, n*pi + atan(y)), S.Integers)) x = Symbol('x', positive=True) assert invert_real(x**pi, y, x) == (x, FiniteSet(y**(1 / pi))) # Test for ``set_h`` containing information about the domain n = Dummy('n') x = Symbol('x') h1 = Intersection(Interval(-oo, -3), FiniteSet(-a + b - 3), imageset(Lambda(n, n - a - 3), Interval(0, oo))) h2 = Intersection(Interval(-3, oo), FiniteSet(a - b - 3), imageset(Lambda(n, -n + a - 3), Interval(0, oo))) assert invert_real(Abs(Abs(x + 3) - a) - b, 0, x) == (x, Union(h1, h2))
def test_tsolve(): assert solve(exp(x) - 3, x) == [log(3)] assert set(solve((a * x + b) * (exp(x) - 3), x)) == set([-b / a, log(3)]) assert solve(cos(x) - y, x) == [acos(y)] assert solve(2 * cos(x) - y, x) == [acos(y / 2)] assert set(solve(Eq(cos(x), sin(x)), x)) == set([-3 * pi / 4, pi / 4]) assert set(solve(exp(x) + exp(-x) - y, x)) in [ set([ log(y / 2 - sqrt(y**2 - 4) / 2), log(y / 2 + sqrt(y**2 - 4) / 2), ]), set([ log(y - sqrt(y**2 - 4)) - log(2), log(y + sqrt(y**2 - 4)) - log(2) ]), set([ log(y / 2 - sqrt((y - 2) * (y + 2)) / 2), log(y / 2 + sqrt((y - 2) * (y + 2)) / 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) == [] assert solve(3**(2 - x), x) == [] assert solve(x + 2**x, x) == [-LambertW(log(2)) / log(2)] ans = solve(3 * x + 5 + 2**(-5 * x + 3), x) assert len(ans) == 1 and ans[0].expand() == \ -Rational(5, 3) + LambertW(-10240*2**(S(1)/3)*log(2)/3)/(5*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 set(solve((2 * x + 8) * (8 + exp(x)), x)) == set([S(-4), log(8) + pi * I]) eq = 2 * exp(3 * x + 4) - 3 ans = solve(eq, x) # this generated a failure in flatten assert len(ans) == 3 and all(eq.subs(x, a).n(chop=True) == 0 for a in ans) 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 * LambertW(-log(3) / 3) / log(3)] A = -7 * 2**Rational(4, 5) * 6**Rational(1, 5) * log(7) / 10 B = -7 * 3**Rational(1, 5) * log(7) / 5 result = solve(2 * (3 * x + 4)**5 - 6 * 7**(3 * x + 9), x) assert len(result) == 1 and expand(result[0]) in [ Rational(-4, 3) - 5 / log(7) / 3 * LambertW(A), Rational(-4, 3) - 5 / log(7) / 3 * LambertW(B), ] 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)] # issue #1409 assert solve(y - b * x / (a + x), x) in [[-a * y / (y - b)], [a * y / (b - y)]] assert solve(y - b * exp(a / x), x) == [a / log(y / b)] # issue #1408 assert solve(y - b / (1 + a * x), x) in [[(b - y) / (a * y)], [-((y - b) / (a * y))]] # issue #1407 assert solve(y - a * x**b, x) == [(y / 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)] # issue #3645 assert solve(x * y) == [{x: 0}, {y: 0}] assert solve([x * y]) == [{x: 0}, {y: 0}] assert solve(x**y - 1) == [{x: 1}, {y: 0}] assert solve([x**y - 1]) == [{x: 1}, {y: 0}] assert solve(x * y * (x**2 - y**2)) == [{x: 0}, {x: -y}, {x: y}, {y: 0}] assert solve([x * y * (x**2 - y**2)]) == [{x: 0}, {x: -y}, {x: y}, {y: 0}] #issue #1640 assert solve(exp(log(5) * x) - 2**x, x) == [0]