From b3a9d07a76d7f3b74cf1fc1c57f80bcd82f74d37 Mon Sep 17 00:00:00 2001 From: Martin Bauer <martin.bauer@fau.de> Date: Tue, 7 Aug 2018 13:53:21 +0200 Subject: [PATCH] Additional utility function: remove sp.Float smaller than a threshold --- sympyextensions.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/sympyextensions.py b/sympyextensions.py index 8320a752d..71fc975a8 100644 --- a/sympyextensions.py +++ b/sympyextensions.py @@ -18,6 +18,20 @@ def prod(seq: Iterable[T]) -> T: return reduce(operator.mul, seq, 1) +def remove_small_floats(expr, threshold): + """Removes all sp.Float objects whose absolute value is smaller than threshold + + >>> expr = sp.sympify("x + 1e-15 * y") + >>> remove_small_floats(expr, 1e-14) + x + """ + if isinstance(expr, sp.Float) and sp.Abs(expr) < threshold: + return 0 + else: + new_args = [remove_small_floats(c, threshold) for c in expr.args] + return expr.func(*new_args) if new_args else expr + + def is_integer_sequence(sequence: Iterable) -> bool: """Checks if all elements of the passed sequence can be cast to integers""" try: -- GitLab