如何在C++中实现Fortran的spacing()函数?
C++ 中 Fortran
spacing(x) 函数的等效方案 内置函数说明
C++ 标准库没有提供和spacing(x)完全一致的单参数内置函数,但可以通过现有标准库组件快速实现,无需引入第三方依赖。
Fortran 中
spacing(x)的核心定义:计算给定浮点数x与其同类型下最相邻的可表示数值的距离,该距离会随x的大小变化(x越大,相邻数间距越大),注意不要和固定的epsilon(1附近的最小间距)混淆。
实现代码
#include <cmath> #include <limits> #include <type_traits> template <typename FloatType> FloatType spacing(FloatType x) { // 编译期校验仅允许浮点类型入参 static_assert(std::is_floating_point_v<FloatType>, "spacing函数仅支持float、double、long double等浮点类型"); // 取x向正无穷方向的最近相邻数 const FloatType next_pos = std::nextafter(x, std::numeric_limits<FloatType>::max()); if (next_pos > x) { return next_pos - x; } // 边界处理:x为当前类型最大值时,取向负无穷方向的相邻数差值 const FloatType next_neg = std::nextafter(x, std::numeric_limits<FloatType>::lowest()); return x - next_neg; }
简化场景说明
如果你确认使用场景仅需要计算1.0附近的同类型最小间距,可以直接调用标准库的std::numeric_limits<FloatType>::epsilon(),无需自行实现上述函数。
内容的提问来源于stack exchange,提问作者Epsilon
相关产品推荐
相关产品推荐

