pythonsympycoefficients

Sympy: drop terms with small coefficients


Is it possible to drop terms with coefficients below a given, small number (say 1e-5) in a Sympy expression? I.e., such that

0.25 + 8.5*exp(-2.6*u) - 2.7e-17*exp(-2.4*u) + 1.2*exp(-0.1*u)

becomes

0.25 + 8.5*exp(-2.6*u) + 1.2*exp(-0.1*u)

for instance.


Solution

  • You can use a combination of coeffs, subs and Poly:

    u = Symbol('u')
    poly = Poly(0.25 + 8.5*exp(-2.6*u) - 2.7e-17*exp(-2.4*u) + 1.2*exp(-0.1*u))
    threshold = 1e-5
    
    to_remove = [abs(i) for i in poly.coeffs() if abs(i) < threshold]
    for i in to_remove:
        poly = poly.subs(i, 0)
    

    poly no yields the following:

    0.25 + 8.5*exp(-2.6*u) + 1.2*exp(-0.1*u)