如何使sin(pi)和cos(pi / 2)为零?

时间:2018-07-19 14:50:55

标签: python matrix sympy

我了解在Python sin(pi)cos(pi/2)中不会产生0,但是我正在使用矩阵进行计算,因此需要使用这些值。

我正在使用SymPy,起初sin(pi)cos(pi/2)的值有点令人讨厌。经过一些乘法后,它们开始妨碍您。有没有办法使这些值在整个模块中等于0? 如何在表达式中间更改它?

我将使用此矩阵作为示例:

A = Matrix([
[(-sin(theta1)*sin(theta2)*cos(alpha2) + cos(theta1)*cos(theta2))*cos(theta3) + (-sin(theta1)*cos(alpha2)*cos(theta2) - sin(theta2)*cos(theta1))*sin(theta3)*cos(alpha3) + sin(alpha2)*sin(alpha3)*sin(theta1)*sin(theta3), -(-sin(theta1)*sin(theta2)*cos(alpha2) + cos(theta1)*cos(theta2))*sin(theta3) + (-sin(theta1)*cos(alpha2)*cos(theta2) - sin(theta2)*cos(theta1))*cos(alpha3)*cos(theta3) + sin(alpha2)*sin(alpha3)*sin(theta1)*cos(theta3), -(-sin(theta1)*cos(alpha2)*cos(theta2) - sin(theta2)*cos(theta1))*sin(alpha3) + sin(alpha2)*sin(theta1)*cos(alpha3), a3*(-sin(theta1)*sin(theta2)*cos(alpha2) + cos(theta1)*cos(theta2)) + d2*sin(alpha2)*sin(theta1) - d3*(-sin(theta1)*cos(alpha2)*cos(theta2) - sin(theta2)*cos(theta1))*sin(alpha3) + d3*sin(alpha2)*sin(theta1)*cos(alpha3)],
[(-sin(theta1)*sin(theta2) + cos(alpha2)*cos(theta1)*cos(theta2))*sin(theta3)*cos(alpha3) + (sin(theta1)*cos(theta2) + sin(theta2)*cos(alpha2)*cos(theta1))*cos(theta3) - sin(alpha2)*sin(alpha3)*sin(theta3)*cos(theta1),   (-sin(theta1)*sin(theta2) + cos(alpha2)*cos(theta1)*cos(theta2))*cos(alpha3)*cos(theta3) - (sin(theta1)*cos(theta2) + sin(theta2)*cos(alpha2)*cos(theta1))*sin(theta3) - sin(alpha2)*sin(alpha3)*cos(theta1)*cos(theta3), -(-sin(theta1)*sin(theta2) + cos(alpha2)*cos(theta1)*cos(theta2))*sin(alpha3) - sin(alpha2)*cos(alpha3)*cos(theta1),  a3*(sin(theta1)*cos(theta2) + sin(theta2)*cos(alpha2)*cos(theta1)) - d2*sin(alpha2)*cos(theta1) - d3*(-sin(theta1)*sin(theta2) + cos(alpha2)*cos(theta1)*cos(theta2))*sin(alpha3) - d3*sin(alpha2)*cos(alpha3)*cos(theta1)],
[sin(alpha2)*sin(theta2)*cos(theta3) + sin(alpha2)*sin(theta3)*cos(alpha3)*cos(theta2) + sin(alpha3)*sin(theta3)*cos(alpha2), -sin(alpha2)*sin(theta2)*sin(theta3) + sin(alpha2)*cos(alpha3)*cos(theta2)*cos(theta3) + sin(alpha3)*cos(alpha2)*cos(theta3), -sin(alpha2)*sin(alpha3)*cos(theta2) + cos(alpha2)*cos(alpha3),a3*sin(alpha2)*sin(theta2) + d2*cos(alpha2) - d3*sin(alpha2)*sin(alpha3)*cos(theta2) + d3*cos(alpha2)*cos(alpha3)],
[0,0,0,1]])

使用SymPy,我将替换为值

substitution = A.subs(alpha2, (-pi/2))

其中会有很多6.12323399573677e-17

3 个答案:

答案 0 :(得分:4)

使用SymPy中的符号pi,而不是math或NumPy模块中的数字pi。这可能是您正在做的事情:

from sympy import sin, cos
from math import pi
print([sin(pi), cos(pi/2)])   # [1.22464679914735e-16, 6.12323399573677e-17]

这是您应该做的:

from sympy import sin, cos, pi
print([sin(pi), cos(pi/2)])  #  [0, 0]

答案 1 :(得分:0)

您总是可以创建函数!

from math import sin as oldsin

def sin(x):
    if x % pi == 0: 
        #if x is an integer mult of pi, like pi, 2pi, -7pi, etc.
        return 0
    else:
        return oldsin(x)

答案 2 :(得分:-1)

这是比您想要的答案更通用的答案,但是您可以尝试将这些值四舍五入为零。在Numpy中,您可以轻松完成此操作:下面的示例将数组中小于1e-14的所有值四舍五入为零。

threshold = 1e-14
array[array < threshold] = 0

希望这会有所帮助。