Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can std::uniform_real_distribution<double>(0,1) return a value greater than 0.99999999999999994?

From the C++11 header , I was wondering if a std::uniform_real_distribution<double> object can spit out a double that's greater than 0.99999999999999994? If so, multiplying this value by 2 would equal 2.

Example:

std::default_random_engine engine;
std::uniform_real_distribution<double> dist(0,1);

double num = dist(engine);

if (num > 0.99999999999999994) 
    num = 0.99999999999999994;

int test1 = (int)(0.99999999999999994 * 2);
int test2 = (int)(0.99999999999999995 * 2);

std::cout << test1 << std::endl; // 1
std::cout << test2 << std::endl; // 2
like image 941
starpax Avatar asked Jan 09 '23 04:01

starpax


1 Answers

The maximum value dist(engine) in your code can return is std::nextafter(1, 0). Assuming IEEE-754 binary64 format for double, this number is

0.99999999999999988897769753748434595763683319091796875

If your compiler rounds floating point literals to the nearest representable value, then this is also the value you actually get when you write 0.99999999999999994 in code (the second nearest representable value is, of course, 1).

like image 139
T.C. Avatar answered Jan 25 '23 23:01

T.C.