Thursday, March 31, 2011

Floating Point errors in Colt Java matrix libraries

How do I avoid floating point errors in financial calculations performed with Colt matrix libraries?

From stackoverflow
  • Some essential reading about the nastiness of floating point types: What Every Computer Scientist Should Know About Floating Point Arithmetic

    And something more Java flavoured: How Java’s Floating-Point Hurts Everyone Everywhere

  • One common technique is to use integers and keep track of the decimals yourself. For example you can decide that all you currency amount will be represented with 3 decimal points accuracy. So instead of writing:

    double dollars = 10.05d;
    

    you write

    int dollars = 10050;
    

    and when you want to print the amount:

    System.out.println( dollars/100d );
    
  • For financials it's more common to use BigDecimal and related classes. float and doubles are in any case very susceptible to rounding errors.

    You may want to look at Apache Commons Math if you decide to give BigDecimal a try.

0 comments:

Post a Comment