【发布时间】:2021-05-19 19:13:36
【问题描述】:
我尝试使用下面的程序用一个简单的 C 程序估计机器 epsilon
#include <stdio.h>
#include <limits.h>
#include <float.h>
int main(){
float f = 1.0f;
float prev_f = 1.0f;
while( 1 + f != 1 ){
prev_f = f;
f /= 2;
}
prev_f *= 2;
printf("Calculated epsilon for float is %.10g", prev_f);
printf("The actual value is %.10f", FLT_EPSILON);
return 0;
}
我的输出在哪里
Calculated epsilon for float is 2.802596929e-45
The actual value is 0.0000001192
谁能向我解释这种偏差?它是特定于架构的吗?编译器依赖?我是不是做错了什么?
编辑: 问题似乎是由于我在 gcc 中使用 -Ofast 优化造成的。改用 -O 可以解决问题。
【问题讨论】:
-
您计算了
float的精度(24 位 ~= 7.2 个十进制数字),而不是 epsilon。 -
如果我取出不应该存在的
prev_f *= 2;行,我会得到相同的值。但是在您的输出中,我不知道您如何获得第一个输出 - 可能是某些编译器设置,例如-ffast-math,这会导致结果不准确.. -
这很奇怪 - 我得到
2.384185791e-07这是实际值 * 2。您使用的是什么编译器?你在什么架构上?您使用什么编译器选项? -
计算出的正确结果示例:godbolt.org/z/Ghf1TP
-
还有一种替代方法:stackoverflow.com/a/24915880/6865932