is there a way to round the numbers in sympy expression

Viewed 34

Hi I'm using sympy to solve some equations and it gives me output like this.

{P1: 30.0000000000000, P2: 60.0000000000000}

1.40765765765766e-18*x**4 - 5.63063063063063e-15*x**3 + 1.40765765765766e-11*x**2 - 5.63063063063063e-9*x - 1.87687687687688e-7

I need it to use zero decimal points if the number was allready an Integer so it become like

{P1: 30, P2: 60} and if the numbers was none Integer It get round to two decimal points

1.4e-18*x**4 - 5.63e-15*x**3 + 1.4e-11*x**2 - 5.63e-9*x - 1.87e-7

2 Answers

The specifics for sympi I don't know, but for numbers, if you use Python's float representation:

   number = 3.128312563
   
   if number.is_integer():
       number = int(number)
   else:
       number = float(f"{number:.2e}")

this will round up the numbers. How it specifically works to display them in sympy, you can read the manual here.

You can create a replacement dictionary to use with xreplace:

>>> d = Dict({P1: 30,0, P2: 60})
>>> eq = 1.40765765765766e-18*x**4
>>> ir = lambda e: {i: int(i) if int(i) == i else i.round(2)
...     for i in e.atoms(Float)}
>>> touch = lambda e: e.xreplace(ir(e))
>>> touch(d)
{P1: 30, P2: 60}
>>> touch(eq)
0.0
Related