Using trunc function in Erlang

Richard Cameron camster@REDACTED
Fri Dec 30 19:35:58 CET 2005

On 30 Dec 2005, at 18:15, Erlang Questions wrote:

> Hello everybody, I have one question about Erlang trunc function.
> Why Erlang behaves like this?
> 1> trunc(1.3/0.1).
> 13
> 2> trunc(1.4/0.1).
> 13
> 3> trunc(1.5/0.1).
> 15

Unfortunately, this isn't an Erlang problem at all. Look at the  
output of this little C program on my machine:

wilt:/tmp rcameron$ cat floor.c
#include <math.h>
#include <stdio.h>
main() {
         printf("%f\n", floor(1.4/0.1));
wilt:/tmp rcameron$ gcc -o floor floor.c
wilt:/tmp rcameron$ ./floor

Computers have a nasty habit of doing things you might not  
intuitively expect with floating point operations. You sort of just  
have to accept that float operations are not exact, so the computation:


actually produces a result in the range

14.0000000000000 +/- epsilon

where epsilon is (very) small. Unfortunately, in your case, it's  
every so slightly negative, so

erlang:trunc(14.0000000000000 - Epsilon).

evaluates to 13.

> And which you think is the best way to manage this in order to  
> solve this kind of problems?

It depends very much what you're trying to do. What do these numbers  
represent in your application?


More information about the erlang-questions mailing list