Floating Point errors in Colt Java matrix libraries

581 Views Asked by At

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

3

There are 3 best solutions below

0
On

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

0
On

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 );
0
On

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.