我从 Fortran 转换为 C++ 的代码包含 spacing(x)
功能。从描述来看,spacing(x)
返回
Smallest distance between two numbers of a given type
和
Determines the distance between the argument X and the nearest adjacent number of the same type.
是否有 C++ 等效函数,或者如果没有,我如何在 C++ 中实现该函数?
最佳答案
使用 SPACING
如 Determines the distance between the argument X and the nearest adjacent number of the same type , 使用 nexttoward()
.
upper = nexttoward(x, INFINITY) - x;
lower = x - nexttoward(x, -INFINITY);
spacing = fmin(upper, lower);
upper != lower
在特定情况下:例如x
是 2 的幂。可能需要一些工作来处理缺乏真正 INFINITY 的实现。
或
if (x > 0) {
spacing = x - nexttoward(x, 0);
} else {
// 1.0 used here instead of 0 to handle x==0
spacing = nexttoward(x, 1.0) - x;
}
或 // Subtract next smaller-in-magnitude value. With 0, use next toward 1.
spacing = fabs(x - nexttoward(x, !x));
我怀疑
nextafter()
效果与 nexttoward()
一样好,甚至更好.
关于c++ - 如何在 C++ 中实现 Fortran 间距()函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69683869/