Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ std::nextbefore function?

Tags:

c++

precision

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

like image 818
bradgonesurfing Avatar asked Jul 22 '26 13:07

bradgonesurfing


1 Answers

It's a kludge, but what about:

std::nextafter(a, (b > a) ? 
    -std::numeric_limits<double>::infinity() : 
    std::numeric_limits<double>::infinity())
like image 113
Adam Kotwasinski Avatar answered Jul 24 '26 02:07

Adam Kotwasinski