2

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.

Tamas Ferenci
  • 424
  • 2
  • 10

3 Answers3

1

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)
Marcelo Paco
  • 2,732
  • 4
  • 9
  • 26
1

Another way to do that: extract the numbers from the expression, select the ones with absolute value lower than some threshold, build a substitution dictionary to set them to zero:

expr = 0.25 + 8.5*exp(-2.6*u) - 2.7e-17*exp(-2.4*u) + 1.2*exp(-0.1*u)
small_numbers = set([e for e in expr.atoms(Number) if abs(e) < 1e-05])
d = {s: 0 for s in small_numbers}
expr.subs(d)
# out: 0.25 + 8.5*exp(-2.6*u) + 1.2*exp(-0.1*u)
Davide_sd
  • 10,578
  • 3
  • 18
  • 30
0

Yes you can filter out terms with coefficient smaller than a specified threshold using as_ordered_terms

Here is some code as example:

import sympy as sp

u = sp.Symbol('u')
expr = 0.25 + 8.5*sp.exp(-2.6*u) - 2.7e-17*sp.exp(-2.4*u) + 1.2*sp.exp(-0.1*u)
threshold = 1e-5

terms = expr.as_ordered_terms()
filtered_terms = [term for term in terms if abs(term.as_coefficient(u)) > threshold]
new_expr = sp.Add(*filtered_terms)

print(new_expr)
Saxtheowl
  • 4,136
  • 5
  • 23
  • 32
  • 1
    Thanks for the idea! Unfortunately the `filtered_terms = ...` line gives a `TypeError: Expr.as_coefficient() missing 1 required positional argument: 'expr'` error message when running your code. – Tamas Ferenci Mar 22 '23 at 00:27
  • I modified my code This should now correctly filter out terms – Saxtheowl Mar 22 '23 at 00:50
  • Strange, but it still gives an error at the very same line, but this time it says `TypeError: bad operand type for abs(): 'NoneType'... – Tamas Ferenci Mar 22 '23 at 10:58