Thursday, March 9, 2017

Quick notes on double numeric type vs. integers

NOTE: If you're dealing with "money values" you should probably do things quite differently from what I'm talking about here -- but it all depends.

Benefits of using double (primitives) instead of longs (integers) as I see it for my use case i.e. number crunching in finance and statistics:
  • "Everything is the same". No need to constantly convert and cast back and forth between numeric types when doing e.g. division, sqrt and so on.
  • Things like NaN and Infinite (vs. Finite; testable) turns out to be really useful. E.g. NaN and Infinity will flow through your code and all future calculations without causing trouble and in the end your output will be NaN or Infinity. No need to check for and handle special cases all over the place – instead only doing this at the original input end; i.e. in one or just a few places.
  • Dividing by 0.0 does not lead to an exception which will disrupt the flow of my program. I will get Infinite as a normal return value instead.
  • Primitive doubles seem to be fast enough(?) and certainly accurate enough (I'm not dealing with money directly; only statistics which *in turn* will deal with money as integer type). GPUs also seem to have better and better support for the double primitive type so I don't feel I'm painting myself into a corner here.
  • Bonus: things like Double/POSITIVE_INFINITY, Double/NEGATIVE_INFINITY, Double/MAX_VALUE, Double/MIN_VALUE and so on can or might be used to denote special information or flags.
..I'm not sure how much I might be losing with regards to performance by using doubles instead of integers – if anything at all, but for convenience and simplicity it seems very good.

No comments:

Post a Comment