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?

Asked By: sqp_125

||

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)
Answered By: smichr
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.