Python math is off by .000000000000045
clp2 at rebertia.com
Wed Feb 22 19:43:06 CET 2012
On Wed, Feb 22, 2012 at 10:13 AM, Alec Taylor <alec.taylor6 at gmail.com> wrote:
> Simple mathematical problem, + and - only:
> That's wrong.
Welcome to the world of finite-precision binary floating-point
arithmetic then! Reality bites.
> -60.95 aka (-(1219/20))
> Is there a reason Python math is only approximated?
Because vanilla floating-point numbers have a finite bit length (and
thus finite precision) but they try to represent a portion of the real
number line, which has infinitely many points. Some approximation
therefore has to occur. It's not a problem specific to Python; it's
inherent to your CPU's floating point numeric types.
Wolfram Alpha is either rounding off its answer to fewer decimal
places (thus merely hiding the imprecision), or using some different,
more computationally expensive arithmetic type(s) in its calculations,
hence why it gives the exact answer.
Alternatives to floats in Python include:
* Fractions: http://docs.python.org/library/fractions.html
* Arbitrary-precision decimal floating point:
These aren't the default for both historical and performance reasons.
More information about the Python-list