Ordering operation to maximize double precision

核能气质少年 提交于 2019-12-06 03:48:43
Vegard

If it is important to get the correct answer, you should use BigDecimal. It is slower than double, but for most cases it is fast enough. I can't think of a lot of cases where you do a lot of calculations with such small numbers where it does not matter if the answer is correct - at least with Java.

If this is a super performance sensitive application, I would consider using a different language.

Thanks to @John for pointing out a very complete article about floating point arithmetics.

It turns out that, when precision is needed, operations should be re-ordered, and formulas adapted to avoid loss of precision, as explained in the Cancellation chapter: when comparing numbers that are very close to each other (which is my case), "catastrophic cancellation" may occur, inducing a huge loss of precision. Often, re-writing the formula, or re-ordering operations according to your à-priori knowledge of the operands values can lead to achieving greater accuracy in calculus.

What I'll remember from this article is:

  • be careful when substracting two nearly-identical quantities
  • try to re-arrange operations to avoid catastrophic cancellation

For the latter case, remember that computing (x - y) * (x + y) gives more accurate results than x * x - y * y.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!