Random header in C++

#include <random>

This header adds random number generation facilities and can produce random numbers using generators and distributions.

Generators: Objects that produces a sequence of pseudo-random values uniformly distributed numbers within a specified range of an engine.
Distributions: Objects that transform sequences of numbers generated by a generator into sequences of numbers that follow a specific random variable distribution, such as Uniform, Normal or Binomial.

Random number enginesPredefined generators
linear_congruential_engine minstd_rand0
minstd_rand
mersenne_twister_engine mt19937
mt19937_64
implements a subtract-with-carry ranlux24
ranlux48

Example: Seed sequence with enough random data to fill the entire mt19937 state

#include <iostream>
#include <random>
#include <array>
#include <algorithm>
#include <functional>
using namespace std;

int main() {
  std::array<int, 624> seed;
  std::random_device rd;
  std::generate_n(seed.data(), seed.size(), std::ref(rd));
  std::seed_seq seq(std::begin(seed), std::end(seed));

  std::mt19937 gen(seq);
  std::uniform_int_distribution<> distr(100, 200);  // define the range
  cout << distr(gen);
}

Example: Generate random numbers that are within += “range” of “value

#include <iostream>
#include <random>
using namespace std;

// generate random numbers within +- "range" of "value"
// Note: The output will vary in every run
double generate(double value, double range) {
  std::random_device rd;   // obtain a random number from hardware
  std::mt19937 gen(rd());  // seed the generator
  double low = (1 - range) * value;  // calculate low range
  double high = (1 + range) * value;  // calculate high range
  std::uniform_int_distribution<> distr(low, high);  // define the range
  return distr(gen);
}
int main() {
  // generate random number whose value lies between += 30% of 100
  for (int i = 0; i < 10; i++) cout << generate(100, 0.3) << " ";

  return 0;
}
99 85 107 82 109 101 129 80 123 115