将浮点数除以 10

发布于 2024-12-22 15:22:56 字数 720 浏览 5 评论 0原文

可能的重复:
为什么十进制数不能用二进制精确表示?

我正在开发一个非常简单的算法,用于在 C++ 下使用数学。

我有一个名为“step”的浮点变量,每次完成 while 循环时,我都需要将 step 除以 10。

所以我的代码有点像这样,

float step = 1;
while ( ... ){
      //the codes
      step /= 10;
}

在我愚蠢的简单逻辑中,结果很好。步骤将除以 10,从 1 到 0.1,从 0.1 到 0.01。

但事实并非如此,而是出现了类似 0.100000000001 的内容。我当时就想“到底是什么”

有人能帮我解决这个问题吗?这可能是我不完全理解的数据类型本身的问题。因此,如果有人可以进一步解释,我们将不胜感激。

Possible Duplicate:
Why can't decimal numbers be represented exactly in binary?

I am developing a pretty simple algorithm for mathematics use under C++.

And I have a floating point variable named "step", each time I finish a while loop, I need step to be divided by 10.

So my code is kind of like this,

float step = 1;
while ( ... ){
      //the codes
      step /= 10;
}

In my stupid simple logic, that ends of well. step will be divided by 10, from 1 to 0.1, from 0.1 to 0.01.

But it didn't, instead something like 0.100000000001 appears. And I was like "What The Hell"

Can someone please help me with this. It's probably something about the data type itself that I don't fully understand. So if someone could explain further, it'll be appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

与风相奔跑 2024-12-29 15:22:56

这是一个数字问题。问题是 1/10 是一个无限长的二进制数,连续除以 10 会导致每一步的误差相加。为了获得更稳定的版本,您应该乘以除数。但请注意:结果也不准确!您可能需要将浮点型替换为双精度型以最小化错误。

unsigned int div = 1;
while(...)
{
    double step = 1.0 / (double)div;
    ....
    div *= 10;
}

It is a numerical issue. The Problem is that 1/10 is a endless long number in binary and the successive apply of a division by 10 ends up with summing the error in each step. To get a more stable version you should multiply the divisor. But take care: the result is also not exact! You may want to replace the float with a double to minimize the error.

unsigned int div = 1;
while(...)
{
    double step = 1.0 / (double)div;
    ....
    div *= 10;
}
撞了怀 2024-12-29 15:22:56

对于二进制浮点算术来说,除以 1 不能精确,因此您看到的结果与您的预期有点不同。

二进制浮点表示为整数比,其中分母是 2 的幂。由于不存在完全等于十分之一的二进制分数,因此您将看到最接近的可表示数字,而不是您期望的数字。

The division by ten cannot be exact for binary floating point arithmetic, so you see results that will look a little bit off from what you expect.

Binary floating are represented as an integer ratio where the denominator is a power of two. Since there in no binary fraction exactly equal to one-tenth, you'll see the nearest representable number instead of the one you expected.

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