# Python math is off by .000000000000045

Chris Rebert clp2 at rebertia.com
Wed Feb 22 13:43:06 EST 2012

```On Wed, Feb 22, 2012 at 10:13 AM, Alec Taylor <alec.taylor6 at gmail.com> wrote:
> Simple mathematical problem, + and - only:
>
>>>> 1800.00-1041.00-555.74+530.74-794.95
> -60.950000000000045
>
> That's wrong.

Welcome to the world of finite-precision binary floating-point
arithmetic then! Reality bites.

> Proof
> http://www.wolframalpha.com/input/?i=1800.00-1041.00-555.74%2B530.74-794.95
> -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.

and http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

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:
http://docs.python.org/library/decimal.html
These aren't the default for both historical and performance reasons.

Cheers,
Chris

```
{"ft_lang_label":"__label__en","ft_lang_prob":0.81408435,"math_prob":0.71279454,"size":1594,"snap":"2019-51-2020-05","text_gpt3_token_len":429,"char_repetition_ratio":0.10377359,"word_repetition_ratio":0.0,"special_character_ratio":0.30112922,"punctuation_ratio":0.196875,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.98594767,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2019-12-14T05:24:30Z\",\"WARC-Record-ID\":\"<urn:uuid:3c36fe9b-234c-4e30-9a53-0f67d2de49f6>\",\"Content-Length\":\"4447\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:909cc25b-87ef-411b-a39f-63ddbcec6837>\",\"WARC-Concurrent-To\":\"<urn:uuid:d61af7dc-a7c2-4609-9c95-a97839add7a1>\",\"WARC-IP-Address\":\"188.166.95.178\",\"WARC-Target-URI\":\"https://mail.python.org/pipermail/python-list/2012-February/620223.html\",\"WARC-Payload-Digest\":\"sha1:2FNKCL2ZAPMC5TL6RYFONOCB3CCCWD2L\",\"WARC-Block-Digest\":\"sha1:GXCBRP65MOWE2EUPZQ7E7JJ6XLJVKKQU\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2019/CC-MAIN-2019-51/CC-MAIN-2019-51_segments_1575540584491.89_warc_CC-MAIN-20191214042241-20191214070241-00081.warc.gz\"}"}