Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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, digits=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!

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, digits=7):
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!

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

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