Strange behaviour with numbers in exponential notation

Random832 random832 at fastmail.com
Fri Sep 2 13:29:45 EDT 2016


On Fri, Sep 2, 2016, at 13:02, Marco Sulla wrote:
> On Fri, Sep 2, 2016 at 6:17 PM, Random832 <random832 at fastmail.com> wrote:
> > Trying to add 1 gets it rounded off again, and the value is simply
> > printed as 1e+26 by default because this is the shortest representation
> > that gives the same number, even if "100000000000000004764729344.0"
> > would be more accurate.
> 
> It seems it's not simply a representation. It seems the numbers are just
> equal:

Yes. The number 1e+16 is represented as a floating point number 
equal to 100000000000000004764729344. Then when you add 1 to it, the 
1 gets rounded off and you get a floating point number that is still 
equal to 100000000000000004764729344:

>>> a = float(10**16)
>>> int(a)
100000000000000004764729344
>>> b = a + 1
>>> int(b)
100000000000000004764729344

You switched examples. 10**22 is the largest power of 10 that can be 
represented exactly, but 10**15+1 is te largest "power of 10 plus 
one" that can be represented exactly.

Float can only represent numbers whose binary representation 
contains 53 bits or less from the first to the last "1".

>>> '{:b}'.format(10**15)
'11100011010111111010100100110001101000000000000000'
# 35 bits before the run of zeros
>>> '{:b}'.format(10**16)
'100011100001101111001001101111110000010000000000000000'
# 38 bits, works fine in float
>>> '{:b}'.format(10**15+1)
'11100011010111111010100100110001101000000000000001'
# 50 bits, barely fits in a float
>>> '{:b}'.format(10**16+1)
'100011100001101111001001101111110000010000000000000001'
# 54 bits, too many.

Anything else gets rounded off. It's the same as if you tried to add
a tiny number to 1.

>>> 1+1e-15 == 1
False
>>> 1+1e-16 == 1
True

> This is really weird. I tried to do it just in C:

You should be using double instead of long double; double is the
C equivalent of the Python float type.



More information about the Python-list mailing list