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
Probably there are much more efficient ways(I am not familiar with that library) but I tried to do with regex
. If e-
exist in a part of the equation it replaces it to 0(you can remove directly if you want). But to be able to do this, I had to remove to spaces between +-
operators inside the parentheses, so I could make a list by splitting from the other +-
operators.
import re
result='''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)'''
too_small='e-'
mylist=re.split(r"\s+", result)
for i in range(len(mylist)):
if too_small in mylist[i]:
mylist[i]='0'
new_result=''.join(mylist)
print(new_result)
And this is the output:
1.0*a1*cos(q1)-0+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)
As I said, there are probably much better ways than this.