Printing The Output Rounded To 3 Decimals In Sympy
I got a SymPy matrix M In [1]: from sympy import * In [2]: M = 1/10**6 * Matrix(([1, 10, 100], [1000, 10000, 100000])) In [3]: M Out[3]: Matrix([ [1.0e-6, 1.0e-5, 0.0001], [ 0.001
Solution 1:
A little bit old, but I used some time to find this today and needed some adjustment. My solution to the exact same question is as a previous answer (user6655984) but with evalf():
def printM(expr, num_digits):
return expr.xreplace({n.evalf() : round(n, num_digits) for n in expr.atoms(Number)})
Then e.g. sqrt(13) is still sqrt(13) and not a numeric value. (Otherwise it is converted to a numeric value after the round and thus having more digits than num_digits. At least in Sympy 1.3 at Python 3.7.1)
Solution 2:
I needed to improve these 2 solutions (Space47 already improved the accepted solution) because my numbers were very big, and Sympy just send "123456789.123 x"
def printM(expr, num_digits):
return expr.xreplace({n.evalf() : n if type(n)==int else Float(n, num_digits) for n in expr.atoms(Number)})
so "123456789.123 x" will be displayed 1.23 * 10^8 and the function does NOT change representation of integers (previously, "1" was replaced by "1.0")
Post a Comment for "Printing The Output Rounded To 3 Decimals In Sympy"