我正在尝试用 C++ 实现 Matlab 的 eps(x)
函数
例如,在 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
似乎出于某种原因,即使单精度和 double 的 eps 值是正确的,使用 nextafter
函数的输出也只输出 double 值。我对 epsxf
的值应该是 6.1035e-05,因为它在 Matlab 中。
有什么想法吗?
最佳答案
包括<cmath>
并调用std::nextafter
,如果您有 C++11 编译器,您的代码就可以运行。
包括<math.h>
并调用 ::nextafter
调用函数的 C 版本。 nextafter
的 C 实现显然不支持重载,所以 C 提供了一个 nextafterf
对于单精度结果,以及 nextafterl
对于四精度。 (简单地用 nextafter
调用 double float
失败,因为参数被转换为 double
。)如果你没有 C++11 编译器,你可以通过调用 ::nextafterf
来修复你的代码。 .
关于c++ - 用C++实现Matlab的eps(x)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20169049/