[Tutor] cube root

Alan Gauld alan.gauld at btinternet.com
Mon Jan 19 10:00:13 CET 2009


"Brett Wilkins" <lupin at orcon.net.nz> wrote

> What you're running into here is the limited accuracy of floating 
> point
> values... You'll likely find this happens a lot in python.. CPython, 
> at least.

In fact it happens with virtually every programming language 
available.
The problem traces back to the way that computers represent floating
point numbers in hardware. The integrated circuits cannot hold 
infinitely
long numbers so they need to use a condensed representation and
that inherently introduces small inaccuracies. (Think of 1/3 in
decimal - an infinite series of 1.3333..., the same is true in binary,
some numbers just cannot be represented accurately)

In the specific case being discussed you can disguise the problem
quite easily by displaying the result with a smaller number of decimal
places using round() or string formatting:

>>> 64**(1.0/3)
3.9999999999999996
>>> print 64**(1.0/3)
4.0
>>> round(64**(1.0/3))
4.0
>>> "%5.3f" % 64**(1.0/3)
'4.000'
>>>

When you need to compare floating point numbers you also
need to be careful since:

>>> 4.0 == 64**(1.0/3)     ## is false!

You need to introduce an error range, typically:

>>> e = 0.00000001
>>> 4.0-e < 64**(1.0/3) < 4.0+e     #  is true

You can also use the decimal module for exact decimal
arithmetic but it introduces some other complications.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list