Round all numbers in sympy object
Question:
I have a class ‘sympy.core.add.Add’ object which I would like to round all numbers in that object to 2 digits.
Given:
2.96652814643838*sin(x) + 3.11758737898895*sin(2*x)
Desired:
2.97*sin(x) + 3.12*sin(2*x)
Any ideas how to do that?
Answers:
Although nfloat
will convert all numbers to a desired number of significant figures, there is no way to globally round numbers in an expression. But expr.xreplace(Transform(lambda x: x.round(2), lambda x: isinstance(x, Float)))
would work.
>>> expr = 2.96652814643838*sin(x) + 3.11758737898895*sin(2*x)
>>> from sympy.core.rules import Transform
>>> expr.xreplace(Transform(lambda x: x.round(2), lambda x: isinstance(x, Float)))
2.97*sin(x) + 3.12*sin(2*x)
I have a class ‘sympy.core.add.Add’ object which I would like to round all numbers in that object to 2 digits.
Given:
2.96652814643838*sin(x) + 3.11758737898895*sin(2*x)
Desired:
2.97*sin(x) + 3.12*sin(2*x)
Any ideas how to do that?
Although nfloat
will convert all numbers to a desired number of significant figures, there is no way to globally round numbers in an expression. But expr.xreplace(Transform(lambda x: x.round(2), lambda x: isinstance(x, Float)))
would work.
>>> expr = 2.96652814643838*sin(x) + 3.11758737898895*sin(2*x)
>>> from sympy.core.rules import Transform
>>> expr.xreplace(Transform(lambda x: x.round(2), lambda x: isinstance(x, Float)))
2.97*sin(x) + 3.12*sin(2*x)