Monday, April 17, 2017

Things that go wrong with monetary calculations...

Things that go wrong with monetary calculations...  As a programmer, it's very easy to forget about the error-producing “edge cases” in calculations.  These are all things that can occur in any calculations, including monetary calculations.  For a robust financial application, all of these must be handled in some way.  The big three:
  • Division by zero.  This is probably the classic “gotcha” in financial calculations, probably because there are so many ways for it to happen that programmers somehow fail to foresee.  The standard floating point implementations will return a value of infinity for this operation (either positive or negative).  Some libraries will throw an exception.  Either method works.
  • Invalid operation.  The canonical examples are zero divided by zero, or the square root of a negative number.  There are others, too.  I've had this error crop up in several implementations of bond and stock options models I made.  The standard floating point implementations will return a value of Not A Number (abbreviated as NaN) for these operations.  Other libraries will throw an exception.  Again, either method works.
  • Inexact result.  An inexact result occurs when the result of any calculation cannot be represented exactly because the number representation cannot hold either the number of significant digits or the exponent size, or both.  In either binary or decimal, the result of 1/3 is one example of such a result.  Standard floating point implementations silently round such results, providing no indication that the result is inexact.
For monetary calculations, the ideal situation would an implementation that allowed either special values for all three of the above situations, or would throw exceptions.  It would also be very useful if the rounding mode could be specified (as it can be in Java's BigDecimal class).  To the best of my knowledge, there is presently no Java decimal floating point library that handles all three of these cases...

No comments:

Post a Comment