简体   繁体   中英

Round all numbers in sympy object

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM