How makes all low values in the symbolic calculation become zero?

前端 未结 4 1739
长情又很酷
长情又很酷 2021-01-24 23:47

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         


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-01-24 23:58

    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.

提交回复
热议问题