# Correct way to get an exact number of decimal digits (after the point)

If I type in

a = numerical_approx(1/14, digits=7)
print a
b=1/14
print b.n(digits=7)


I get

0.07142857
0.07142857


I count 8 digits after the point.
I wonder: How to get 7 digits as declared?

edit retag close merge delete

Sort by » oldest newest most voted

Hello, @geroyx! The problem you have is that the digits parameter of the N() function actually means number of significant figures.

Updated answer: Sage has a round function, which does exactly what you want. For example,

a = round(1/14, ndigits=7)
print(a)


You will get

0.0714286


Old answer: At the time of posting my answer, I din't know if Sage had a built-in mechanism for dealing with number of digits after the decimal point, but here is a work-around that I posted. I keep it next for historical purposes. (I didn't have the time to mathematically check if this is correct, so maybe you should do it or ask somebody to verify it.)

def N2(x, n=7):
d = floor(log(abs(x), 10)) + 1
return N(x, digits=n+d)


You can check this works fine with:

N2(-100.25)
N2(1/14)
N2(0.0123, 10)


That should return the following:

-100.2500000
0.0714286
0.0123000000


(the exact number of digits after the decimal point.)

I hope this helps!

more

@dsejas OK, I understand. Seems your code has a little mistake. Suggestion:

def NumPrint(x, n):
d = floor(log(abs(x), 10)) + 1
return N(x, digits=n+d)#, d

print NumPrint(-100.25,2)
print NumPrint(1/14,7)
print NumPrint(0.0123, 4)


Oops! Sorry, @geroyx. You're right. I mixed a couple one previous version of my code with the final one. I am editing my answer right now. Thank you!