How can I make all low values in a SymPy expression zero? For example, my result is:
1.0*a1*cos(q1) - 6.12e-17*(a2*sin(q2) + a3*sin(q2 + q3) + a4*sin(q2 + q3 + q
SymPy’s nsimplify
function with the rational=True
argument converts floats within an expression to rational numbers (within a given tolerance). Something like 6.12e-17
will be converted to 0 if below the threshold. So, in your case:
from sympy import sin, cos, symbols, nsimplify
a1, a2, a3, a4 = symbols("a1, a2, a3, a4")
q1, q2, q3, q4 = symbols("q1, q2, q3, q4")
expr = (
1.0*a1*cos(q1)
- 6.12e-17*(a2*sin(q2) + a3*sin(q2 + q3) + a4*sin(q2 + q3 + q4))*sin(q1)
+ 1.0*(a2*cos(q2) + a3*cos(q2 + q3) + a4*cos(q2 + q3 + q4))*cos(q1)
)
nsimplify(expr,tolerance=1e-10,rational=True)
# a1*cos(q1) + (a2*cos(q2) + a3*cos(q2 + q3) + a4*cos(q2 + q3 + q4))*cos(q1)