What is the best way to deal with floating point errors?
So I have a Javascript script which adds small fractions together in a loop and its possible that it will add 0.2 to 0.1. Then that value is fed to another function but the issue is I need 0.3 to be fed exactly and not 0.30000000000000004.
What is the simplest way to ensure the number is corrected and exact. Note that its possible to get 0.25+0.125 etc being added to simply rounding to 1 decimal won't fix the issue.
It is also possible to have 0.2 + 0.10000000000000004 being added although this is very, very unlikely!
There is no simple method of avoiding rounding errors in general-purpose floating-point arithmetic. The number 0.3
does not have an exact binary floating-point representation.
I would suggest reading What Every Computer Scientist Should Know About Floating-Point Arithmetic to familiarize yourself with the trade-offs inherent to floating-point representation of numbers.
To actually solve your issue, you should ask yourself a few questions:
0.30000000000000004
outside your margin for error? Is it acceptable to round your results? BigDecimal
? Ultimately, when it comes to issues with floating-point precision, you'll often have to tailor the solution to the requirements posed by your specific issue.
链接地址: http://www.djcxy.com/p/27502.html上一篇: 在JavaScript中的位浮点数学错误
下一篇: 处理浮点错误的最佳方法是什么?