防止舍入错误
我刚刚读到有关 C++ 中的舍入错误的内容。因此,如果我正在制作一个数学密集型程序(或任何重要的计算),我是否应该将浮点数全部放在一起并仅使用双精度数,还是有更简单的方法来防止舍入错误?
I was just reading about rounding errors in C++. So, if I'm making a math intense program (or any important calculations) should I just drop floats all together and use only doubles or is there an easier way to prevent rounding errors?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
必修讲座:每个程序员都应该了解浮点运算。
另外,请尝试阅读IEEE 浮点标准。
你总是会遇到舍入错误。除非您使用
无限任意精度库,例如gmplib。您必须决定您的应用程序是否真的需要这种努力。或者,您可以使用整数算术,仅在需要时转换为浮点数。这仍然很难做到,你必须决定是否值得。
最后,您可以使用
float
或double
,注意不要在表示精度的限制下对值进行假设。我希望 这个 Valgrind 插件 能够实现(grep for float)...Obligatory lecture: What Every Programmer Should Know About Floating-Point Arithmetic.
Also, try reading IEEE Floating Point standard.
You'll always get rounding errors. Unless you use an
infinitearbitrary precision library, like gmplib. You have to decide if your application really needs this kind of effort.Or, you could use integer arithmetic, converting to floats only when needed. This is still hard to do, you have to decide if it's worth it.
Lastly, you can use
float
ordouble
taking care not to make assumption about values at the limit of representation's precision. I'd wish this Valgrind plugin was implemented (grep for float)...即使使用浮点数,舍入误差通常也非常微不足道。像游戏这样的数学密集型程序会进行大量浮点计算,通常仍然使用单精度。
The rounding errors are normally very insignificant, even using floats. Mathematically-intense programs like games, which do very large numbers of floating-point computations, often still use single-precision.
如果您的最大数字小于 100 亿并且您使用的是 C++ 双精度,这可能会起作用。
这应该至少允许最后一位数字偏离 +/- 9。我假设除以 1000 总是只会移动一位小数。如果没有,那么也许可以用二进制来完成。
您必须在每个非 +、-、* 或比较之外的操作之后应用它。例如,您不能在同一个公式中进行两次除法,因为您必须将其应用于每个除法。
如果这不起作用,您可以通过按比例放大数字来处理整数,并始终使用整数除法。如果您需要高级函数,也许有一个包可以执行确定性整数数学。在许多金融环境中都需要整数除法,因为舍入误差会像电影“办公室”中那样受到利用。
This might work if your highest number is less than 10 billion and you're using C++ double precision.
This should allow at least the last digit to be off +/- 9. I'm assuming dividing by 1000 will always just move a decimal place. If not, then maybe it could be done in binary.
You would have to apply it after every operation that is not +, -, *, or a comparison. For example, you can't do two divisions in the same formula because you'd have to apply it to each division.
If that doesn't work, you could work in integers by scaling the numbers up and always use integer division. If you need advanced functions maybe there is a package that does deterministic integer math. Integer division is required in a lot of financial settings because of round off error being subject to exploit like in the movie "The Office".