用C++实现Matlab的eps(x)函数

kyl*_*yle 6 c++ matlab epsilon

我正在尝试eps(x)用C++ 实现Matlab的功能

例如,在Matlab中:

>> eps(587.3888)
ans = 1.1369e-13
>> eps(single(587.3888))
ans = 6.1035e-05
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试在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);

}
Run Code Online (Sandbox Code Playgroud)

运行程序我得到以下输出:

$ ./a.out 
epsf: 1.19209e-07
epsd: 2.22045e-16
espxf: -1.13687e-13
espxd: -1.13687e-13
Run Code Online (Sandbox Code Playgroud)

似乎由于某种原因,即使单精度和双精度的eps值是正确的,使用nextafter函数的输出仅输出双精度值.我的值epsxf应该是6.1035e-05,就像在Matlab中一样.

有什么想法吗?

use*_*342 6

包含<cmath>并调用std::nextafter,只要您有C++ 11编译器,您的代码就可以运行.

包含<math.h>和调用::nextafter调用函数的C版本.C实现nextafter显然不支持重载,因此C提供nextafterf单精度结果以及nextafterl四精度结果.(简单地调用双精度nextafterfloat因为争论被转化为失败double).如果你没有一个C++编译器11,您可以通过调用解决您的代码::nextafterf.