[erlang-questions] Maths Problem -> 2452.45*100. = 245244.99999999997

Richard A. O'Keefe <>
Wed Nov 27 04:28:36 CET 2013


On 27/11/2013, at 3:01 PM, Sanath Prasanna wrote:

> I accepted your comment. But generally we expected full value. I did same in another scripting language like php. It is given correct result.

Wrong.  It *calculated* the same number as Erlang did,
but then it *displayed* a different number, a rounded version.

m% cat >foo.php
<?php
$a = 2452.45*100;
echo $a; echo "\n";
$a = $a - 245245.0;
echo $a; echo "\n";
exit;
?>
<EOF>
m% php foo.php
245245
-2.9103830456734E-11

We see from this that while the number *displays as*
245245, it is not *equal to* 245245.

As I said, PHP computed *exactly* the same answer as Erlang.
Who is this "we" who "expect full value"?
This is floating-point arithmetic, not rational arithmetic.

(Our 2nd year students are taught this stuff, but it doesn't
really take.  In 3rd year they have an exercise they have to
do where they start to really understand that floating point
arithmetic is *not* arithmetic on the mathematical real
numbers, but a different mathematical system which sort of
approximates the algebra of the reals.  They learn that
adding up an array of numbers from left to right generally
gives you a different answer from adding up from right to
left, for example.)

Numbers in IEEE floating point arithmetic are precise,
but are bounded in their precision, and arithmetic operations
on them (including conversion between decimal and binary)
have to round their answers to something that is representable.
There's a rounding in the conversion of 2452.45 to binary,
and then the multiplication incurs another rounding.



More information about the erlang-questions mailing list