我试图在eps(x)中实现Matlab的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中一样。
有什么想法吗?
发布于 2013-11-23 23:13:17
包括<cmath>和调用std::nextafter,只要您有C++11编译器,您的代码就能工作。
包括<math.h>和调用::nextafter调用函数的C版本。nextafter的C实现显然不支持过载,因此C为单精度结果提供了nextafterf,为四精度提供了nextafterl。(简单地用float调用双精度float失败,因为参数被转换为double。)如果没有C++11编译器,则可以通过调用::nextafterf来修复代码。
发布于 2013-11-23 23:16:11
使用图书馆。在其他语言中,Matlab的eps函数称为ULP,作为最后的单元。根据维基百科关于ULP的文章,boost C++库的以下函数可用于计算两个双a和b之间的浮点距离
boost::math::float_distance(a, b)float_distance的文档是这里。
https://stackoverflow.com/questions/20169049
复制相似问题