Last active
October 10, 2023 03:46
-
-
Save PhDP/5289449 to your computer and use it in GitHub Desktop.
A simple tutorial on C++11's random number generators.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Compile with: | |
// $ clang++ -O3 -std=C++11 main.cc -o main | |
#include <iostream> | |
#include <random> // The header for the generators. | |
#include <ctime> // To seed the generator. | |
using namespace std; | |
int main() { | |
// Seed with time and print the seed: | |
const unsigned int seed = time(0); | |
cout << "Seed = " << seed << endl; // cout is a way to print in C++, endl ends the line. | |
// Generating random numbers with C++11's random requires an engine and a distribution. | |
// This is an engine based on the Mersenne Twister 19937 (64 bits): | |
mt19937_64 rng(seed); | |
// Then we create a distribution. We'll start with a uniform distribution in the | |
// default [0, 1) range: | |
uniform_real_distribution<double> unif; | |
cout << "\nUniform floats [0, 1): "; | |
for (int i = 0; i < 20; i++) { // Sample 20 numbers. | |
// To get a random number, send the engine (rng) as argument to the distribution object: | |
cout << unif(rng) << ' '; | |
} | |
cout << endl; | |
// Now we create another uniform distribution for integers in the [42, 512) range: | |
uniform_int_distribution<int> unii(42, 512); | |
cout << "\nUniform integers [42, 512): "; | |
for (int i = 0; i < 20; i++) { | |
// Again we send the generator as argument to the distribution to get numbers: | |
cout << unii(rng) << ' '; | |
} | |
cout << endl; | |
// C++11 supports all kind of distributions (Normal, Binomial, Gamma, Weibull...). | |
// See this page for more info: en.cppreference.com/w/cpp/numeric/random | |
// A last example: normal distribution with mean 5 and std 2: | |
normal_distribution<double> norm(5, 2); | |
cout << "\nNormal with mean 5, std 2: "; | |
for (int i = 0; i < 20; i++) { | |
cout << norm(rng) << ' '; | |
} | |
cout << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Congrats, a Google search for "mt19937_64 example" shows your gist as the #4 result!
One nit, though: uniform_int_distribution uses closed intervals, unlike uniform_real_distribution.
Here's a fix: https://gist.github.com/jorgbrown/252e6070d905e358ab1ee9be62f5f07e/revisions
Sad that gists don't allow pull requests...