[erlang-questions] Any way to correct the round off errors?

Zoltan Lajos Kis kiszl@REDACTED
Sun Sep 20 14:03:45 CEST 2009


Lev Walkin wrote:
> G.S. wrote:
>> Hello everyone,
>>
>> When subtracting in Erlang: 0.92915-0.92945 we should get -0.0003 but 
>> Erlang
>> gives: -2.9999999999996696e-4   (when doing 92915-92945 Erlang gives 
>> -30 so
>> that's ok).
>>
>> Anyway to make make it give -0.0003 ?, and in general make it give more
>> accurate answers?
>
> Your computer hardware cannot represent 0.0003.
>
> [vlm@REDACTED:~]> cc -o c c.c && ./c
> -0.000300
> -0.00029999999999999997
> [vlm@REDACTED:~]> cat c.c
> #include <stdio.h>
>
> int main() {
>     double d = -0.0003;
>     printf("%f\n", d);
>     printf("%.20f\n", d);
> }
> [vlm@REDACTED:~]>
>
>
> So, Erlang does not give you less accurate numbers.
> Erlang just gives you a differently formatted decimal
> representation of a binary number which can't be 0.0003.
>
It's not the computer hardware, but the representation used for floating 
point numbers...
You can come up with your own library of arithmetic functions where you 
represent decimals as you wish. Of course you will have to trade 
performance for the desired accuracy. Java for example has BigDecimals 
for this cause:

 >java Zed
-0.00030

-------------

import java.math.BigDecimal;

class Zed {
  public static void main(String[] args) {
    BigDecimal x = new BigDecimal("0.92915");
    BigDecimal y = new BigDecimal("0.92945");

    System.out.println( x.subtract(y) );
  }
}




More information about the erlang-questions mailing list