Categories
Java Low Latency Technology

Floating Point Numbers in Low Latency Applications

            Clearly there are lots of issues with using <a href="http://www.ibm.com/developerworks/library/j-jtp0114/">float and double</a> and using BigDecimal is not going to cut it an low latency financial world unless you are not really that low latency.  So what is the answer. As usual it depends, but here are some suggestions.
  • Look after the pennies rather than the pounds. That is use cents rather than dollars, or what ever is the lowest precision in your world.
  • Ensure intermediate calculations are as exact as possible so that rounding errors are not accumulated.
  • Build or borrow a maths library to compare floating point numbers for instance (i.e float and double) with an epsilon value, i.e. a nearly equals method so that you can hide all the gory details in a library. Also add rounding and precision to the laundry list. Slightly surprised Java’s core libraries don’t cover this better.
  • Use string representations on the wire rounded to appropriate levels of precision. Sure there is an overhead in conversion but at least its accurate.
  • A reminder of sizes:-
    • Integer = 32 bits, 4 bytes = 2^31 =+- 2147483648 = 2.14748E+9
    • Long = 64 bits, 8 byes = 2^63 = +-9.22337E+18
    • Float = 32 bits, 4 bytes = +-3.5E+38 and +-1.4E-45, about 7 digits
    • Double = 64 bits, 8 bytes = +-1.7E+308 and +-4.9E-324, about 15 digits
    • String = words, 2 bytes, short

References

Java theory and practice: Where’s your point?
Java’s new math, Part 2: Floating-point numbers
Java float / double comparison