[erlang-questions] Float multiplication behaviours

Valentin Nechayev netch@REDACTED
Tue Apr 24 12:34:37 CEST 2012


 Mon, Apr 23, 2012 at 13:46:14, vinoski wrote about "Re: [erlang-questions] Float multiplication behaviours": 

> > (node@REDACTED)49> 10.20*100.
> > 1019.9999999999999
> http://floating-point-gui.de/

The question is more complex if to compare with different language
system behaviors and Erlang behavior difference between output formats.
For example, Python (2.7) shows exactly the same value as Erlang in the
quote, but C with Glibc (glibc-2.14.1-14.27.1.x86_64@REDACTED), Perl
and Ruby's irb shows simply 1020. The latter one shows rounding which
could be unreasonable, because doesn't differ adjacent values:

$ cat tx1.c
#include <stdio.h>
#include <math.h>
main() {
  double a = 10.20;
  a *= 100;
  double ap, an;
  ap = nextafter(a, 1000.0);
  an = nextafter(a, 0.0);
  printf("%g%s%g%s%g\n",
      an, (an == a) ? "==" : "!=",
      a, (a == ap) ? "==" : "!=", ap);
  return 0;
}
$ ./tx1
1020!=1020!=1020

If the thread starter expects the value to be rounded in accustomed way, this
can help in its reading, but can also give confusing results on values which
are looking equal but differs really. Erlang manner to print with full details
with ~p is more debug-oriented than user-oriented:

2> io:fwrite("~p~n", [10.20*100]).
1019.9999999999999
ok
3> io:fwrite("~g~n", [10.20*100]).
1020.00
ok

(Sadly, math module is quite thin and doesn't carry IEEE required
functions, as nextafter().)

For more floating-point details, it's better to go to
<http://randomascii.wordpress.com/2012/04/21/exceptional-floating-point/>
and start reading from the previous topics.


-netch-



More information about the erlang-questions mailing list