Ask Your Question

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

asked 2020-01-05 10:24:39 -0600

geroyx gravatar image

If I type in

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

I get


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

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2020-01-08 09:26:40 -0600

dsejas gravatar image

updated 2020-01-09 19:07:03 -0600

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

I don't know if Sage has a built-in mechanism for dealing with number of digits after the decimal point, but here is a work-around that should work. (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(0.0123, 10)

That should return the following:


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

I hope this helps!

edit flag offensive delete link 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)
geroyx gravatar imagegeroyx ( 2020-01-09 12:28:26 -0600 )edit

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!

dsejas gravatar imagedsejas ( 2020-01-09 19:05:16 -0600 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2020-01-05 10:24:39 -0600

Seen: 42 times

Last updated: Jan 09