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

会有一股神秘感。 提交于 2020-01-02 07:10:11

问题


As the title says, the functionality I'm after is provided by C++11's math libraries to find the next floating point value towards a particular value.

Aside from pulling the code out of the std library (which I may have to resort to), any alternatives to do this with C++03 (using GCC 4.4.6)?


回答1:


Platform dependently, assuming IEEE754, and modulo endianness, you can store the data of the floating point number in an integer, increment by one, and retrieve the result:

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;

Beware of zeros, NaNs and infinities, of course.



来源:https://stackoverflow.com/questions/16335992/alternative-to-c11s-stdnextafter-and-stdnexttoward-for-c03

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!