Precision?

Ron Adam rrr at ronadam.com
Sun May 15 22:39:07 EDT 2005


Ron Adam wrote:

> tiissa wrote:
> 
>>Steffen Glückselig wrote:
>>
>>
>>>>>>1.0 + 3.0 + 4.6
>>>
>>>8.5999999999999996
>>>
>>>Ehm, how could I get the intuitively 'correct' result of - say - 8.6?
>>>;-)
>>
>>
>>You may find annex B of the python tutorial an interesting read:
>>http://docs.python.org/tut/node16.html
> 
> 
> In addition to what you find in the above link, the round function can 
> be used.
> 
> p = 1	#digits of precision after decimal
> a, b, c = 1.0, 3.05, 4.6
> print round(a+b+c,p)
> 
> -> 8.6
> 
> You also have the option to use the print statements '%' operator to 
> format the output.
> 
> 
> a, b, c = 1.0, 3.05, 4.6
> print "%.1f"%(a+b+c)
> 
> -> 8.6
> 
> 
> _Ron

Just to clarify this, It was pointed out to me that round() doesn't 
resolve the problem of floating points, and I agree. (Thanks Fredrik)

 >>>round(1.0+3.05+4.6,1)
8.5999999999999996

The print statement displays it as 8.6.

The only way to avoid the problem completely is by using an alternative 
numeric system such as decimal.

What rounding and print formatting do is give you some control within 
the specifications of your requirements.  Print for display purposes, 
and round to minimize errors to within the needed precision.

 >>> for y in range(1000000):
...     x += 1.6
...
 >>> x
1600001.6000213262

Eventually this could be significant.

 >>> for y in range(1000000):
...    x = round(x+1.6,1)
...
 >>> x
3200001.6000000001

Here the error has been kept to a minimum.  In most cases, it isn't a 
problem, but it is something to be aware of.  It does matter in banking 
and I beleive there are standard ways of dealing with it.

Cheers,
_Ron





More information about the Python-list mailing list