gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:24:08 26 4
gpt4 key购买 nike

我从 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com