Math errors in python
Dan Bishop
danb_83 at yahoo.com
Mon Sep 20 00:07:55 EDT 2004
Paul Rubin <http://phr.cx@NOSPAM.invalid> wrote in message news:<7xfz5ein0h.fsf at ruckus.brouhaha.com>...
> Gary Herron <gherron at islandtraining.com> writes:
> > Any representation of the infinity of numbers on a finite computer
> > *must* necessarily be unable to represent some (actually infinity
> > many) of those numbers. The inaccuracies stem from that fact.
>
> Well, finite computers can't even represent all the integers, but
> we can reasonably think of Python as capable of doing exact integer
> arithmetic.
>
> The issue here is that Python's behavior confuses the hell out of some
> new users. There is a separate area of confusion, that
>
> a = 2 / 3
>
> sets a to 0,
That may confusing for non-C programmers, but it's easy to explain.
The real flaw of old-style division is that code like
def mean(seq):
return sum(seq) / len(seq)
subtly fails when seq happens to contain all integers, and you can't
even correctly use:
def mean(seq):
return 1.0 * sum(seq) / len(seq)
because it could lose accuracy if seq's elements were of a custom
high-precision numeric type that is closed under integer division but
gets coerced to float when multiplied by a float.
> That doesn't solve the also very
> common confusion that (1.0/3.0)*3.0 = 0.99999999.
What problem?
>>> (1.0 / 3.0) * 3.0
1.0
The rounding error of multiplying 1/3 by 3 happens to exactly cancel
out that of dividing 1 by 3. It's an accident, but you can use it as
a quick argument against the "decimal arithmetic is always more
acurate" crowd.
> Rational arithmetic can solve that.
Yes, it can, and imho it would be a good idea to use rational
arithmetic as the default for integer division (but _not_ as a general
replacement for float).
More information about the Python-list
mailing list