math.nroot [was Re: A brief question.]

George Sakkis gsakkis at rutgers.edu
Sun Jul 3 16:50:09 CEST 2005


"Steven D'Aprano" <steve at REMOVETHIScyber.com.au> wrote:

> Unfortunately, floating point maths is a bit of a black art. Try this
> simple calculation:
>
> py> 4.0/3 - 5.0/6
> 0.49999999999999989
>
> Should be 0.5 exactly.
>
> Many numbers which you can write exactly in decimal cannot be
> stored exactly in floating point. Even something as simple as one tenth
> 0.1 doesn't have an exact representation in binary:
>
> py> 1.0/10
> 0.10000000000000001

Given that 0.5 *can* be represented exactly in binary (try 0.3/0.6),
your first example illustrates something worse about floating point
arithmetic: not only many decimal numbers cannot be represented exactly
as binary floating point, but that the kind and the order of operations
in arithmetic expressions affects the accuracy of the result. *Even
worse* than that, errors can be accumulated over a sequence of
operations, so that even if each individual error is typically very
small, the overall error might be non-trivial. There's a whole area
studying the analysis and control of error in floating point arithmetic
so it's not quite black art for everyone; e.g. see
http://docs.sun.com/source/806-3568/ncg_goldberg.html,
http://http.cs.berkeley.edu/~demmel/cs267/lecture21/lecture21.html for
more.

George




More information about the Python-list mailing list