c++ std::nextbefore function?

Viewed 104

There exists std::nextafter function however no nextbefore. Naively I would do

double a = 1.0;
double b = 2.0;

std::cout.precision(std::numeric_limits<double>::max_digits10);
std::cout << std::nextafter(a,b) << std::endl;
std::cout << std::nextafter(a,2*a-b) << std::endl;

to get

1.0000000000000002
0.99999999999999989

But using 2a-b seems sketchy in the general case. Is there a more robust way to achieve nextbefore. ie: the next floating point number from a in the opposite direction from a to b?

Demo https://godbolt.org/z/sKsK49oa3

1 Answers

It's a kludge, but what about:

std::nextafter(a, (b > a) ? 
    -std::numeric_limits<double>::infinity() : 
    std::numeric_limits<double>::infinity())
Related