[erlang-questions] In Erlang , {1.1*1.1.} show me the answer is 1.2100000000000002, why?

Richard A. O'Keefe ok@REDACTED
Mon Oct 27 23:03:44 CET 2014


On 26/10/2014, at 8:24 PM, 张栋 wrote:
> When I try some multiplication, I got the some unexpected answer about the following expression.

But WHY did you not expect what you got?
If you do not understand floating point arithmetic,
what is your excuse for using it?

> 23> [1.1*1.1,1.1*1.2,1.1*1.3,1.1*1.4,1.1*1.5].
> [1.2100000000000002,1.32,1.4300000000000002,1.54,
>  1.6500000000000001]

Using Gambit Scheme:
> (list (* 1.1 1.1) (* 1.1 1.2) (* 1.1 1.3) (* 1.1 1.4) (* 1.1 1.5))
(1.2100000000000002 1.32 1.4300000000000002 1.54 1.6500000000000001)

We see that Erlang is giving *EXACTLY* the answers that
it ought to.

> 24> [1.2*1.2,1.2*1.3,1.2*1.4,1.2*1.5,1.2*1.6].
> [1.44,1.56,1.68,1.7999999999999998,1.92]

> (list (* 1.2 1.2) (* 1.2 1.3) (* 1.2 1.4) (* 1.2 1.5) (* 1.2 1.6))
(1.44 1.56 1.68 1.7999999999999998 1.92)

Again, Erlang is giving EXACTLY the BEST POSSIBLE ANSWERS.

Read "What every Computer Scientist should know about
Floating-Point arithmetic".  Here's a link to a copy:
https://www.stat.auckland.ac.nz/~stat782/downloads/floating-point-arithmetic.pdf

To cut a long story short, computers use BINARY (base 2)
floating point arithmetic, which means that numbers like 1.1
CANNOT be represented exactly.  When you compute
"1.1*1.1" you are *REALLY* computing round(round(1.1) * round(1.1)).

To make the story somewhat longer, there _have_ been computers
with decimal floating point arithmetic, there is a recent
standard for decimal floating point arithmetic complete with a
C interface to it, and IBM make machines that support it -- in
addition to IEEE binary arithmetic.  This will completely
solve your problem with 1.1 and 1.2, but it will leave people
confused about 1.0/3.0.  




More information about the erlang-questions mailing list