问题描述
作为学校作业的一部分,我试图计算C ++中的double和float的机器epsilon值.我在Windows 7(64位)中使用Cygwin,这是代码:
I am attempting to calculate the machine epsilon value for doubles and floats in C++ as part of a school assignment. I'm using Cygwin in Windows 7, 64 bit, here is the code:
#include <iostream>
int main() {
double epsilon = 1;
while(1 + epsilon > 1)
epsilon = epsilon / 2;
epsilon = 2*epsilon;
std::cout << epsilon << std::endl;
float epsilon_f = 1;
while(1 + epsilon_f > 1)
epsilon_f = epsilon_f / 2;
epsilon_f = 2*epsilon_f;
std::cout << epsilon_f << std::endl;
return 1;
}
运行代码时,两个值都收到1.0842e-019.我查了一下,应该为double获得2.22e-16,为float值获得1.19e-07.当我在Macbook上运行 exact 相同的代码时,该代码将返回正确的值.是什么原因导致Windows计算机上的差异?
When I run the code, I receive 1.0842e-019 for both values. I looked it up and should be getting 2.22e-16 for the double, and 1.19e-07 for the float value. When I run the exact same code on a Macbook, the code returns the correct values. What could be causing the discrepancy on my Windows machine?
推荐答案
CPU的浮点寄存器通常包含80位,看起来Cygwin编译器选择完全在寄存器中执行循环计算(打印结果时只将结果截断为32/64位).
The CPU's floating-point registers typically contain 80 bits, and it looks like the Cygwin compiler chooses to perform the loop calculations entirely in registers (only truncating the result to 32/64 bits when printing the results).
正如@Potatoswatter指出的那样,这对于编译器是完全合法的,并且您的程序实际上表现出未定义的行为,因为它假定存在 个精度限制.由于存在未定义的行为,因此编译器可以选择将程序转换为所需的任何内容(包括删除所有文件的程序,但是幸运的是,这不是常见的解决方案...)
As @Potatoswatter points out, this is entirely legal for the compiler, and your program actually exhibits undefined behavior because it assumes that there is a precision limit. Since there's undefined behavior, the compiler may choose to transform your program into anything it wants (including one that deletes all of your files, but that's fortunately not a common solution...)
P.S.欢迎来到StackOverflow,并且对这个问题(如果您阅读了答案中的概念)感到很敬佩,这可能会让您比课堂上的其他任何人都更多地了解处理器体系结构和编译器!:-)
P.S. Welcome to StackOverflow, and kudos for a question that (if you read up on the concepts in the answers) will probably make you learn more about processor architecture and compilers than anyone else in your class! :-)
这篇关于机器Epsilon精度差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!