How do I avoid floating point errors in financial calculations performed with Colt matrix libraries?
+3
A:
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
Anonymous
2009-02-13 14:31:57
A:
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 );
idrosid
2009-02-13 15:37:32
A:
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.
extraneon
2009-02-13 17:49:56