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

前端 未结 4 1733
长情又很酷
长情又很酷 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-25 00:15

    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)
    

提交回复
热议问题