Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::mt19937 and std::uniform_real_distribution returning boundary value every time

Tags:

c++

random

c++11

OK, so I've got some RNG code that (when all is said and done) boils down to this:

#include <limits>
#include <random>
#include <chrono>
#include <iostream>

double randomValue() {
    // Seed a Mersenne Twister (good RNG) with the current system time
    std::mt19937 generator(std::chrono::system_clock::now().time_since_epoch().count());

    std::uniform_real_distribution<double> dist(
        std::numeric_limits<double>::lowest(),
        std::numeric_limits<double>::max()
    );

    // Problem lives here
    for (unsigned int i = 0; i < 30; i++)
        std::cout << dist(generator) << "\n";
}

The output from this is 30 lines of inf. Why?

Compiling with g++ Debian 4.9.2-10, using -std=c++11 and no other flags. And, before anyone else comments on it, I'm using the built-in Mersenne Twister-based RNG because my application requires high-quality random numbers, and seeding it with the system time (so no, it's not just the same seed over and over again).

like image 520
Sebastian Lenartowicz Avatar asked Jan 06 '23 12:01

Sebastian Lenartowicz


1 Answers

According to C++14 section 26.5.8.2.2 paragraph 2:

Requires: a ≤ b and b − a ≤ numeric_limits<RealType>::max().

In your case, b-a is greater than the allowed range.

like image 69
Vaughn Cato Avatar answered Jan 14 '23 08:01

Vaughn Cato