[Tutor] cube root

Brett Wilkins lupin at orcon.net.nz
Mon Jan 19 12:11:22 CET 2009


The only language I've run into so far (I haven't used many, mind) that
doesn't have this issue is Scheme :)
(Just learning it at the moment.)

Cheers,
--Brett

P.S. Forgive me if this email doesn't sort properly, sending through
webmail, as I don't have a relaying SMTP available to me currently.

Alan Gauld wrote:
>
> "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,
>
>





More information about the Tutor mailing list