Python -- floating point arithmetic

bart.c bartc at freeuk.com
Wed Jul 7 11:02:38 EDT 2010


david mainzer wrote:

>>>> sum = 0.0
>>>> for i in range(10):
> ...     sum += 0.1
> ...
>>>> sum
> 0.99999999999999989
>>>>
>
> But thats looks a little bit wrong for me ... i must be a number
> greater
> then 1.0 because 0.1 =
> 0.100000000000000005551115123125782702118158340454101562500000000000
> in python ... if i print it.
>
> So i create an example program:
>
> sum = 0.0
> n = 10
> d = 1.0 / n
> print "%.60f" % ( d )
> for i in range(n):
>    print "%.60f" % ( sum )
>    sum += d
>
> print sum
> print "%.60f" % ( sum )
>
>
> - -------- RESULTs ------
> 0.100000000000000005551115123125782702118158340454101562500000
> 0.000000000000000000000000000000000000000000000000000000000000
> 0.100000000000000005551115123125782702118158340454101562500000
> 0.200000000000000011102230246251565404236316680908203125000000
> 0.300000000000000044408920985006261616945266723632812500000000
> 0.400000000000000022204460492503130808472633361816406250000000
> 0.500000000000000000000000000000000000000000000000000000000000
> 0.599999999999999977795539507496869191527366638183593750000000
> 0.699999999999999955591079014993738383054733276367187500000000
> 0.799999999999999933386618522490607574582099914550781250000000
> 0.899999999999999911182158029987476766109466552734375000000000
> 1.0
> 0.999999999999999888977697537484345957636833190917968750000000
>
> and the jump from 0.50000000000000*** to 0.59999999* looks wrong
> for me ... do i a mistake or is there something wrong in the
> representation of the floating points in python?

I think the main problem is, as sum gets bigger, the less significant bits 
of the 0.1 representation fall off the end (enough to make it effectively 
just under 0.1 you're adding instead of just over).

> can anybody tell me how python internal represent a float number??

Try "google ieee floating point". The problems aren't specific to Python.

-- 
Bartc 




More information about the Python-list mailing list