c++ - 如何在 C++ 中实现 Fortran 间距()函数?

标签 c++ floating-point

我从 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++ 中实现该函数?

最佳答案

使用 SPACINGDetermines 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/

相关文章:

c++ - 理解静态转换

c - float 据类型不确定

SQL将float转换为带小数的逗号varchar

Python Cassandra float 精度损失

c++ - 调用模板化成员的成员函数

c++ - 是否有 C++ 方法来实现/等效于 R 中的 which() 函数?

java - java中如何将Integer的某些操作的结果存储到不同的数据类型中

java - 在Java中匹配Excel的 float

c++ - Boost::Spirit 后跟默认值时字符加倍

c++ - 如何在 LLVM Bitvectors 上操作?