4

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
starpax
  • 130
  • 5
  • 1
    No, `std::uniform_real_distribution(0, 1)` cannot produce the value of `0.99999999999999995`, because `0.99999999999999995==1` ( http://rextester.com/BRWD20868 ) – Igor Tandetnik Jun 11 '15 at 01:46

2 Answers2

8

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).

T.C.
  • 133,968
  • 17
  • 288
  • 421
1

std::uniform_real_distribution<double>(0, 1) must return a value that is strictly less than 1.0.

However, what you do with that value is subject to all the many complexities of floating point operations, including rounding errors in calculations and output.

Michael Burr
  • 333,147
  • 50
  • 533
  • 760
  • 1
    True. But if `x < 1`, then `2*x < 2`, because multiplying a float by 2 is exact. (Exact unless `x` is so big that `2*x` overflows, in which case you'd get infinity. But that's obviously not the case here.) As you say, that doesn't stop 2*x from being printed as `2.0` if you don't specify enough precision in the print format. – rici Jun 11 '15 at 02:03
  • @rici: I'm just pointing out that in general floating point is more complicated than it may seem at first glance. I didn't get into specifics - mainly because there are many, and the one that bit the OP in his question is probably among the simplest to understand and avoid. Also, I have found that whenever I try to explain details of floating point, I end up getting them wrong myself. – Michael Burr Jun 11 '15 at 05:26