Ask Your Question

Why 5.000000000000000 is not equal to 5

asked 2016-01-12 09:20:28 -0500

danny gravatar image
sage: def f(n):
...        if abs(n-n.integer_part())<1*e-10:
...            return n.integer_part()
...        else:
...            return n
sage: n=5.0000000000000001
sage: f(n)


sage: type(f(n))
<type 'sage.rings.real_mpfr.RealLiteral'>
sage: n.integer_part()
sage: n.integer_part()==5
sage: f(n)==5
edit retag flag offensive close merge delete


Did you mean 1e-10 instead of 1*e-10?

isuruf gravatar imageisuruf ( 2016-01-18 23:16:56 -0500 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2016-01-12 09:52:16 -0500

tmonteil gravatar image

updated 2016-01-15 04:20:17 -0500

The fact that f(n) shows 5.000000000000000 is just a printing artifact, there is no rounding, you can check that f(n) is equal to n and different from 5:

sage: n == f(n)

Even n itself is represented as 5.000000000000000, not 5.0000000000000001:

sage: n=5.0000000000000001
sage: n
sage: n-5

EDIT Here is a way to print more digits of n

sage: n.str(truncate=False)

You might be scary with the two additional 1 at the end. This is because internally, numbers are represented in binary, and you proposed a number which is exact in base 10, but not in base 2, hence some rounding (not only in the printing, but also in the representation of n in the machine).

You can get the exact value of the rounded n as follows:

sage: n.exact_rational()

And even see its internal representation:

sage: n.sign_mantissa_exponent()
(1, 90071992547409922, -54)

And check

sage: 90071992547409922*2^(-54)

You can print the non-truncated expression of n as follows:

edit flag offensive delete link more


I see. Thank you very much.

danny gravatar imagedanny ( 2016-01-12 10:03:45 -0500 )edit

@danny, if this answers your question, please click the check mark to accept it so that others know it's been answered.

kcrisman gravatar imagekcrisman ( 2016-01-12 12:34:02 -0500 )edit

@tmonteil - actually, I think you could expand your answer to mention how to get more digits printed (if not by default) because I think that might be part of the question the OP has.

kcrisman gravatar imagekcrisman ( 2016-01-12 12:34:35 -0500 )edit

@kcrisman : i edited my answer to explain a bit more.

tmonteil gravatar imagetmonteil ( 2016-01-15 04:20:42 -0500 )edit

That is awesome - there are a few places this shows up in Sage documentation but it needs more visibility.

kcrisman gravatar imagekcrisman ( 2016-01-16 15:13:29 -0500 )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: 2016-01-12 09:20:28 -0500

Seen: 216 times

Last updated: Jan 15 '16