简体   繁体   English

奇怪的C ++浮动bug

[英]Weird C++ float bug

#include <iostream>
using namespace std;

int main()
{
    cout.precision(32);

    float val = 268433072;
    float add = 13.5;

    cout << "result =" << (val + add) << endl;
}

I'm compiling the above program with standard g++ main.cc 我正在用标准的g++ main.cc编译上面的程序
and running it with ./a.out 并使用./a.out运行它

The ouput I receive however, is, 然而,我收到的输出是,
result =268433088

Clearly, this is not the correct answer..Why is this happening? 显然,这不是正确答案。为什么会发生这种情况?

EDIT : This does not occur when using double in place of float 编辑 :当使用double代替float时不会发生这种情况

You can reproduce your "float bug" with an even simpler piece of code 您可以使用更简单的代码重现您的“浮动bug”

#include <iostream>
using namespace std;

int main()
{
    cout.precision(32);
    float val = 2684330722;
    cout << "result =" << val << endl;
}

The output 输出

result =2684330752

As you can see the output does not match the value val was initialized with. 如您所见,输出与初始化的值val不匹配。

As it has been stated many times, floating-point types have limited precision. 正如已多次说明的那样,浮点类型的精度有限。 Your code sample simply exceeded that precision, so the result got rounded. 您的代码示例只是超出了该精度,因此结果得到了舍入。 There's no "bug" here. 这里没有“错误”。

Aside from the reference to (1991, PDF) What Every Computer Scientist Should Know About Floating-Point Arithmetic 除了参考(1991,PDF)每个计算机科学家应该知道的关于浮点运算的内容

The short answer is, that because float has limited storage (like the other primitives too) the engineers had to make a choice: which numbers to store with which precision. 简短的回答是,因为浮动 存储有限 (就像其他基元一样),工程师必须做出选择:存储哪些数字具有哪种精度。 For the floating point formats they decided to store numbers of small magnitude precisely (some decimal digits), but numbers of large magnitude very imprecisely, in fact starting with +-16,777,217 the representable numbers are becoming so thin that not even all integers are represented which is the thing you noticed. 对于浮点格式,他们决定精确地存储小幅度的数字(一些十进制数字),但是大幅度的数字非常不精确,事实上从+ -16,777,217开始,可表示的数字变得如此之小,以至于甚至没有表示所有整数是你注意到的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM