[erlang-bugs] Sum small floats and get erroneous result in R12B-2

Badlop badlop@REDACTED
Sun Jun 1 13:58:49 CEST 2008


Thanks to Hans Bolinder and Matthew Dempsky.

The rest of this email is just a summary for reference.

> [Badlop:]
>> 2> 20.15 + 2.01.
>> 22.159999999999997

On Thu, May 29, 2008 at 9:06 AM, Hans Bolinder
<hans.bolinder@REDACTED> wrote:
> The floats representing 20.15 and 2.01 are not exactly equal to 20.15
> and 2.01 respectively. The sum is some other float than the one
> representing 22.16.
>
> Floats are printed accurately as the shortest, correctly rounded
> string. This is a new feature in R12B-2;

Ah. That explains why R11B-5 and R12B-2 provide different values:
>    OTP-7084  The functions io_lib:write/1,2 and io_lib:print/1,4 have been
>             changed when it comes to writing floating point numbers. This
>             change affects the control sequences p, P, w, and W of the
>             io_lib module. (Thanks to Bob Ippolito for code
>             contribution.)
http://www.erlang.org/download/otp_src_R12B-2.readme


In Erlang/OTP R11B-5 and older, this is obtained:
1> 2.01+0.01.
2.02000
2> 1.123456789.
1.12346


The result 1> is correct just by coincidence:
in reality the sum returns 2.0199999999999996,
but this value is rounded internally using io_lib
before being printed in the shell.
As a result 2.02000 is printed.

Similar results are obtained with:
CLISP 2.44, Awk 3.1.5, Octave 3.0.1, R 2.7.0, Yorick 2.1.05,
Maxima 5.13.0, ARIBAS 1.63, Google online calculator.


In Erlang R12B-2 this is obtained:
1> 2.01 + 0.01.
2.0199999999999996
2> 1.23546789123456789123.
1.2354678912345678

Similar results are obtained with:
Python 2.4.4, GHCi 6.8.2, OCaml 3.10.2.

So, this is not a bug in OTP, but a limitation in how most programs
represent floats:
IEEE Standard for Binary Floating-Point Arithmetic (IEEE 754)


It is more precise to calculate 2.01 + 0.01 with pencil and paper.
Or use special programs like 'bc':

$ bc
bc 1.06.94 - An arbitrary precision calculator language
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.

2.01 + 0.01
2.02

20.15 + 2.01
22.16

0.111111111111111111111111111111111111111111111111111111111111112 + 0.1
.211111111111111111111111111111111111111111111111111111111111112

---



More information about the erlang-bugs mailing list