3

I've been trying to generate random numbers between 0 - 1 (but less than 1) using a std::uniform_real_distribution with 0.0f & 1.0f as the lower and upper bounds. It's occasionally giving me 1.0f as the result though, but the documentation suggests that this shouldn't happen. Have I misunderstood how this works, or is this likely to be a rounding issue? If so, what's the correct way to generate random numbers strictly less than 1.0f?

I'm using Visual Studio 2015 for this.

My code:

std::mt19937                                mGenerator( static_cast< unsigned int >( std::chrono::system_clock::now().time_since_epoch().count() ) );
std::uniform_real_distribution< float >     mDistribution( 0.0f, 1.0f );

float result = mDistribution( mGenerator );

Thanks.

Mark Lucas
  • 31
  • 1
  • 3
    http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution has a note about this, & a link to an open standard issue. – Mat Dec 29 '15 at 10:32
  • tl; dr? use `std::uniform_real_distribution`. – YSC Dec 29 '15 at 10:47

0 Answers0