使用浮点数时避免不稳定的微小数字
有时,当我在 C++ 中使用浮点数并且仅使用数字作为 for 循环中的增量(例如 0.1)时,循环迭代器的实际数字并不完全是 0.1 的倍数,而是添加了不可预测的其他数字或减去 1^-17 量级的微小数字。我怎样才能避免这种情况?
It some times happen when I use floating point numbers in c++ and only use numbers as multiples of, say 0.1, as an increment in a for loop, the actual number which is the loop iterators is not exactly multiples of 0.1 but has unpredictably other added or subtracted tiny numbers of the order of 1^-17. How can I avoid that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用整数进行迭代并在使用前乘以浮点增量。
或者找到一个十进制数学包并使用它而不是浮点数。
Use integers for the iteration and multiply by the floating-point increment before using.
Alternatively find a decimal math package and use it instead of floating point.
不要迭代浮点数。
问题是0.1无法用浮点数精确表示。因此,你应该这样做:
Don't iterate over floating-point numbers.
The problem is that 0.1 can't be exactly represented in floating-point. So instead, you should do something like:
这是一篇关于使用漂浮。有一个讨论恰好涵盖了您的示例 - 增量为 0.1:
如果您经常使用浮点数,我强烈建议您阅读整篇文章。
Here is an excellent article on the subject of working with floats. There is a discussion covering precisely your example - an increment of 0.1:
I highly recommend reading the whole article if you work a lot with floating point numbers.