[英]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.所以我有一个 Javascript 脚本,它在一个循环中将小部分加在一起,它可能会将 0.2 添加到 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.然后将该值馈送到另一个函数,但问题是我需要准确馈送 0.3 而不是 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.请注意,将 0.25+0.125 等添加到简单地四舍五入到小数点后不会解决问题。
It is also possible to have 0.2 + 0.10000000000000004 being added although this is very, very unlikely!也有可能添加 0.2 + 0.10000000000000004,尽管这是非常非常不可能的!
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.数字0.3
没有精确的二进制浮点表示。
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.我建议您阅读What Every Computer Scientist should Know About Floating-Point Arithmetic以熟悉浮点数表示固有的权衡。
To actually solve your issue, you should ask yourself a few questions:要真正解决您的问题,您应该问自己几个问题:
0.30000000000000004
outside your margin for error?为什么0.30000000000000004
超出了您的误差范围? Is it acceptable to round your results?将结果四舍五入是否可以接受?BigDecimal
?如果您无法对整数执行计算,是否可以使用其他数据类型,例如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.最终,当涉及到浮点精度问题时,您通常必须根据您的特定问题提出的要求定制解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.