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
python类cos()的实例源码
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_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_sqrt_symbolic_denest():
x = Symbol('x')
z = sqrt(((1 + sqrt(sqrt(2 + x) + 3))**2).expand())
assert sqrtdenest(z) == sqrt((1 + sqrt(sqrt(2 + x) + 3))**2)
z = sqrt(((1 + sqrt(sqrt(2 + cos(1)) + 3))**2).expand())
assert sqrtdenest(z) == 1 + sqrt(sqrt(2 + cos(1)) + 3)
z = ((1 + cos(2))**4 + 1).expand()
assert sqrtdenest(z) == z
z = sqrt(((1 + sqrt(sqrt(2 + cos(3*x)) + 3))**2 + 1).expand())
assert sqrtdenest(z) == z
c = cos(3)
c2 = c**2
assert sqrtdenest(sqrt(2*sqrt(1 + r3)*c + c2 + 1 + r3*c2)) == \
-1 - sqrt(1 + r3)*c
ra = sqrt(1 + r3)
z = sqrt(20*ra*sqrt(3 + 3*r3) + 12*r3*ra*sqrt(3 + 3*r3) + 64*r3 + 112)
assert sqrtdenest(z) == z
def equation(self, type='cosine'):
"""
Returns equation of the wave.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.equation('cosine')
A*cos(2*pi*f*t + phi)
"""
if not isinstance(type, str):
raise TypeError("type can only be a string.")
if type == 'cosine':
return self._amplitude*cos(self.angular_velocity*Symbol('t') + self._phase)
def test_twave():
A1, phi1, A2, phi2, f = symbols('A1, phi1, A2, phi2, f')
c = Symbol('c') # Speed of light in vacuum
n = Symbol('n') # Refractive index
t = Symbol('t') # Time
w1 = TWave(A1, f, phi1)
w2 = TWave(A2, f, phi2)
assert w1.amplitude == A1
assert w1.frequency == f
assert w1.phase == phi1
assert w1.wavelength == c/(f*n)
assert w1.time_period == 1/f
w3 = w1 + w2
assert w3.amplitude == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2)
assert w3.frequency == f
assert w3.wavelength == c/(f*n)
assert w3.time_period == 1/f
assert w3.angular_velocity == 2*pi*f
assert w3.equation() == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2)*cos(2*pi*f*t + phi1 + phi2)
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_partial_velocity():
q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1 q2 q3 u1 u2 u3')
u4, u5 = dynamicsymbols('u4, u5')
r = symbols('r')
N = ReferenceFrame('N')
Y = N.orientnew('Y', 'Axis', [q1, N.z])
L = Y.orientnew('L', 'Axis', [q2, Y.x])
R = L.orientnew('R', 'Axis', [q3, L.y])
R.set_ang_vel(N, u1 * L.x + u2 * L.y + u3 * L.z)
C = Point('C')
C.set_vel(N, u4 * L.x + u5 * (Y.z ^ L.x))
Dmc = C.locatenew('Dmc', r * L.z)
Dmc.v2pt_theory(C, N, R)
vel_list = [Dmc.vel(N), C.vel(N), R.ang_vel_in(N)]
u_list = [u1, u2, u3, u4, u5]
assert (partial_velocity(vel_list, u_list, N) ==
[[- r*L.y, r*L.x, 0, L.x, cos(q2)*L.y - sin(q2)*L.z],
[0, 0, 0, L.x, cos(q2)*L.y - sin(q2)*L.z],
[L.x, L.y, L.z, 0, 0]])
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_simplify():
f, n = symbols('f, n')
m = Matrix([[1, x], [x + 1/x, x - 1]])
m = m.row_join(eye(m.cols))
raw = m.rref(simplify=lambda x: x)[0]
assert raw != m.rref(simplify=True)[0]
M = Matrix([[ 1/x + 1/y, (x + x*y) / x ],
[ (f(x) + y*f(x))/f(x), 2 * (1/n - cos(n * pi)/n) / pi ]])
M.simplify()
assert M == Matrix([[ (x + y)/(x * y), 1 + y ],
[ 1 + y, 2*((1 - 1*cos(pi*n))/(pi*n)) ]])
eq = (1 + x)**2
M = Matrix([[eq]])
M.simplify()
assert M == Matrix([[eq]])
M.simplify(ratio=oo) == M
assert M == Matrix([[eq.simplify(ratio=oo)]])
def test_rotation_matrices():
# This tests the rotation matrices by rotating about an axis and back.
theta = pi/3
r3_plus = rot_axis3(theta)
r3_minus = rot_axis3(-theta)
r2_plus = rot_axis2(theta)
r2_minus = rot_axis2(-theta)
r1_plus = rot_axis1(theta)
r1_minus = rot_axis1(-theta)
assert r3_minus*r3_plus*eye(3) == eye(3)
assert r2_minus*r2_plus*eye(3) == eye(3)
assert r1_minus*r1_plus*eye(3) == eye(3)
# Check the correctness of the trace of the rotation matrix
assert r1_plus.trace() == 1 + 2*cos(theta)
assert r2_plus.trace() == 1 + 2*cos(theta)
assert r3_plus.trace() == 1 + 2*cos(theta)
# Check that a rotation with zero angle doesn't change anything.
assert rot_axis1(0) == eye(3)
assert rot_axis2(0) == eye(3)
assert rot_axis3(0) == eye(3)
def test_Znm():
# http://en.wikipedia.org/wiki/Solid_harmonics#List_of_lowest_functions
th, ph = Symbol("theta", real=True), Symbol("phi", real=True)
from sympy.abc import n,m
assert Znm(0, 0, th, ph) == Ynm(0, 0, th, ph)
assert Znm(1, -1, th, ph) == (-sqrt(2)*I*(Ynm(1, 1, th, ph)
- exp(-2*I*ph)*Ynm(1, 1, th, ph))/2)
assert Znm(1, 0, th, ph) == Ynm(1, 0, th, ph)
assert Znm(1, 1, th, ph) == (sqrt(2)*(Ynm(1, 1, th, ph)
+ exp(-2*I*ph)*Ynm(1, 1, th, ph))/2)
assert Znm(0, 0, th, ph).expand(func=True) == 1/(2*sqrt(pi))
assert Znm(1, -1, th, ph).expand(func=True) == (sqrt(3)*I*sqrt(-cos(th)**2 + 1)*exp(I*ph)/(4*sqrt(pi))
- sqrt(3)*I*sqrt(-cos(th)**2 + 1)*exp(-I*ph)/(4*sqrt(pi)))
assert Znm(1, 0, th, ph).expand(func=True) == sqrt(3)*cos(th)/(2*sqrt(pi))
assert Znm(1, 1, th, ph).expand(func=True) == (-sqrt(3)*sqrt(-cos(th)**2 + 1)*exp(I*ph)/(4*sqrt(pi))
- sqrt(3)*sqrt(-cos(th)**2 + 1)*exp(-I*ph)/(4*sqrt(pi)))
assert Znm(2, -1, th, ph).expand(func=True) == (sqrt(15)*I*sqrt(-cos(th)**2 + 1)*exp(I*ph)*cos(th)/(4*sqrt(pi))
- sqrt(15)*I*sqrt(-cos(th)**2 + 1)*exp(-I*ph)*cos(th)/(4*sqrt(pi)))
assert Znm(2, 0, th, ph).expand(func=True) == 3*sqrt(5)*cos(th)**2/(4*sqrt(pi)) - sqrt(5)/(4*sqrt(pi))
assert Znm(2, 1, th, ph).expand(func=True) == (-sqrt(15)*sqrt(-cos(th)**2 + 1)*exp(I*ph)*cos(th)/(4*sqrt(pi))
- sqrt(15)*sqrt(-cos(th)**2 + 1)*exp(-I*ph)*cos(th)/(4*sqrt(pi)))
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 test_piecewise_fold_piecewise_in_cond():
p1 = Piecewise((cos(x), x < 0), (0, True))
p2 = Piecewise((0, Eq(p1, 0)), (p1 / Abs(p1), True))
p3 = piecewise_fold(p2)
assert(p2.subs(x, -pi/2) == 0.0)
assert(p2.subs(x, 1) == 0.0)
assert(p2.subs(x, -pi/4) == 1.0)
p4 = Piecewise((0, Eq(p1, 0)), (1,True))
assert(piecewise_fold(p4) == Piecewise(
(0, Or(And(Eq(cos(x), 0), x < 0), Not(x < 0))), (1, True)))
r1 = 1 < Piecewise((1, x < 1), (3, True))
assert(piecewise_fold(r1) == Not(x < 1))
p5 = Piecewise((1, x < 0), (3, True))
p6 = Piecewise((1, x < 1), (3, True))
p7 = piecewise_fold(Piecewise((1, p5 < p6), (0, True)))
assert(Piecewise((1, And(Not(x < 1), x < 0)), (0, True)))
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 trig_tansec_rule(integral):
integrand, symbol = integral
integrand = integrand.subs({
1 / sympy.cos(symbol): sympy.sec(symbol)
})
if any(integrand.has(f) for f in (sympy.tan, sympy.sec)):
pattern, a, b, m, n = tansec_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({
tansec_tanodd_condition: tansec_tanodd,
tansec_seceven_condition: tansec_seceven,
tan_tansquared_condition: tan_tansquared
})((a, b, m, n, integrand, symbol))
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_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 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 main():
x = sympy.Symbol('x')
y = sympy.Symbol('y')
e = 1/sympy.cos(x)
print()
pprint(e)
print('\n')
pprint(e.subs(sympy.cos(x), y))
print('\n')
pprint(e.subs(sympy.cos(x), y).subs(y, x**2))
e = 1/sympy.log(x)
e = e.subs(x, sympy.Float("2.71828"))
print('\n')
pprint(e)
print('\n')
pprint(e.evalf())
print()
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])