Using trunc function in Erlang
Erlang Questions
erlang@REDACTED
Fri Dec 30 20:50:29 CET 2005
I was afraid about that.
Unfortunately, these numbers represent money in my application :o(
Regards, Carlos.-
----- Original Message -----
From: "Richard Cameron" <camster@REDACTED>
To: "Erlang Questions" <erlang@REDACTED>
Cc: "Erlang Questions" <erlang-questions@REDACTED>
Sent: Friday, December 30, 2005 3:35 PM
Subject: Re: Using trunc function in Erlang
>
> 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
> 13.000000
>
> 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:
>
> 1.4/0.1
>
> 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?
>
> Richard.
>
>
More information about the erlang-questions
mailing list