Aaron Brock
Aaron Brock

Reputation: 4536

Round Sympy Mul with Units

I'm trying to round the output of a solve evaluation that has units attached to it.

For example:

solve(Eq(x, 22/7 * seconds), x)[0]

Outputs:

3.14285714285714*s

Is there a way to round it to 3.14*s while keeping the s?

Upvotes: 1

Views: 193

Answers (1)

Francesco Bonazzi
Francesco Bonazzi

Reputation: 1957

SymPy expressions have the .evalf() method to approximate numbers. It accepts an optional parameter n, which specifies the number of digits the approximate expression will contain.

Supposing you expression is contained in the expr variable:

In [5]: expr
Out[5]: 3.14285714285714⋅s

In [6]: expr.evalf(n=10)
Out[6]: 3.142857143⋅s

In [7]: expr.evalf(n=2)
Out[7]: 3.1⋅s

In [8]: expr.evalf(n=3)
Out[8]: 3.14⋅s

Upvotes: 1

Related Questions