替代 C++11 的 std::nextafter 和 std::nexttowards for C++03?

Alternative to C++11's std::nextafter and std::nexttoward for C++03?

本文关键字:std for C++03 nexttowards nextafter C++11 替代      更新时间:2023-10-16

正如标题所说,我所追求的功能是由c++ 11的数学库提供的,用于查找特定值的下一个浮点值。

除了从std库中提取代码(我可能不得不诉诸于此)之外,还有其他方法可以使用c++ 03(使用GCC 4.4.6)来完成此操作吗?

与平台相关,假设IEEE754,并且端序模,您可以将浮点数的数据存储在整数中,递增1,并检索结果:

float input = 3.15;
uint32_t tmp;
unsigned char * p = reinterpret_cast<unsigned char *>(&tmp);
unsigned char * q = reinterpret_cast<unsigned char *>(&input);
p[0] = q[0]; p[1] = q[1]; p[2] = q[2]; p[3] = q[3];  // endianness?!
++tmp;
q[0] = p[0]; q[1] = p[1]; q[2] = p[2]; q[3] = p[3];
return input;

当然要小心零、nan和无穷大。

我意识到这个答案很晚了,但是当我需要非常类似的解决方案时,我偶然发现了这个解决方案,因此为了完整性,我认为应该在这里包括它。在c++ 11中,上述api位于'std'命名空间中。在此之前,只需从math.h:

中删除'std'命名空间限定符
     double nextafter  (double x     , double y);
      float nextafterf (float x      , float y);
long double nextafterl (long double x, long double y);

虽然我没有GCC4.4.6来验证,但这确实适用于我在一个不支持c++ 11的旧编译器上。