使用浮点数时避免不稳定的微小数字

发布于 2024-12-20 05:57:07 字数 122 浏览 1 评论 0原文

有时,当我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

把回忆走一遍 2024-12-27 05:57:08

使用整数进行迭代并在使用前乘以浮点增量。

或者找到一个十进制数学包并使用它而不是浮点数。

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.

ぺ禁宫浮华殁 2024-12-27 05:57:08

不要迭代浮点数。

问题是0.1无法用浮点数精确表示。因此,你应该这样做:

for (int i = 0; i < N; i++)
{
    float f = i * 0.1f;

    ...
}

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:

for (int i = 0; i < N; i++)
{
    float f = i * 0.1f;

    ...
}
じ违心 2024-12-27 05:57:08

这是一篇关于使用漂浮。有一个讨论恰好涵盖了您的示例 - 增量为 0.1:

for (double r=0.0; r!=1.0; r+=0.1) printf("*");

它将打印多少颗星星?十?运行它,你会感到惊讶。代码只是继续打印星星,直到我们破坏它。

问题出在哪里?正如我们所知,双打并不是无限精确的。我们在这里遇到的问题如下:在二进制中,0.1 的表示不是有限的(因为它以 10 为底)。十进制 0.1 相当于二进制 0.0(0011),其中括号中的部分将永远重复。当 0.1 存储在双精度变量中时,它会四舍五入到最接近的可表示值。因此,如果我们将其相加 10 倍,结果并不完全等于 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:

for (double r=0.0; r!=1.0; r+=0.1) printf("*");

How many stars is it going to print? Ten? Run it and be surprised. The code just keeps on printing the stars until we break it.

Where's the problem? As we already know, doubles are not infinitely precise. The problem we encountered here is the following: In binary, the representation of 0.1 is not finite (as it is in base 10). Decimal 0.1 is equivalent to binary 0.0(0011), where the part in the parentheses is repeated forever. When 0.1 is stored in a double variable, it gets rounded to the closest representable value. Thus if we add it 10 times the result is not exactly equal to one.

I highly recommend reading the whole article if you work a lot with floating point numbers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文