首页 > 解决方案 > 如何在 C++ 中实现 Fortran 间距()函数?

问题描述

我从 Fortran 转换为 C++ 的代码包含该spacing(x)函数。根据描述,spacing(x)返回

给定类型的两个数字之间的最小距离

确定参数 X 和最近的相同类型的相邻数字之间的距离。

是否有 C++ 等效函数,或者,如果没有,我如何在 C++ 中实现该函数?

标签: c++floating-point

解决方案


使用SPACINGas确定参数 X 和最近的相同类型的相邻数字之间的距离,使用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()


推荐阅读