我希望你能够帮助将Matlab的eps(x)
函数实现到C++中。
例如,在Matlab中:
>> eps(587.3888)
ans = 1.1369e-13
>> eps(single(587.3888))
ans = 6.1035e-05
然而,当我尝试在C++中实现此操作时,我无法得到正确的单精度答案。
#include <limits>
#include <iostream>
#include <math.h>
#define DEBUG(x) do { std::cerr << x << std::endl; } while (0)
#define DEBUG2(x) do { std::cerr << #x << ": " << x << std::endl; } while (0)
int main() {
float epsf = std::numeric_limits<float>::epsilon();
DEBUG2(epsf);
double epsd = std::numeric_limits<double>::epsilon();
DEBUG2(epsd);
float espxf = nextafter(float(587.3888), epsf) - float(587.3888);
double espxd = nextafter(double(587.3888), epsd) - double(587.3888);
DEBUG2(espxf);
DEBUG2(espxd);
}
运行程序后我得到以下输出:
$ ./a.out
epsf: 1.19209e-07
epsd: 2.22045e-16
espxf: -1.13687e-13
espxd: -1.13687e-13
似乎由于某种原因,尽管单精度和双精度的eps值是正确的,但使用“nextafter”函数输出的结果只有双精度值。我的“epsxf”值应该是6.1035e-05,就像在Matlab中一样。有什么想法吗?
eps
总是给出正结果。如果x
大于epsf
,上述代码将给出负结果。这里是修复后的代码:double eps(float x) { float xp = std::abs(x); double x1 = std::nextafter(xp, xp + 1.0f); return x1 - xp; }
- legends2k