如何在 C++ 中实现 Fortran spacing() 函数?
How to implement the Fortran spacing() function in C++?
我从 Fortran 转换为 C++ 的代码包含 spacing(x)
函数。从描述来看,spacing(x)
returns
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, use nexttoward()
。
upper = nexttoward(x, INFINITY) - x;
lower = x - nexttoward(x, -INFINITY);
spacing = fmin(upper, lower);
upper != lower
在 select 个案例中:例如x
是 2 的幂。
可能需要一些工作来处理缺少真正无限的实现。
或
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()
更好。
我从 Fortran 转换为 C++ 的代码包含 spacing(x)
函数。从描述来看,spacing(x)
returns
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, use nexttoward()
。
upper = nexttoward(x, INFINITY) - x;
lower = x - nexttoward(x, -INFINITY);
spacing = fmin(upper, lower);
upper != lower
在 select 个案例中:例如x
是 2 的幂。
可能需要一些工作来处理缺少真正无限的实现。
或
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()
更好。