Skip to content

Uniform Distribution

Scalar

template <typename T, typename RNG>
inline T pxart::uniform(RNG&& rng);
This functions advances the state of the given random number generator to get a number and transforms it such that a sequence of returned numbers is uniformly distributed in a default type-dependent range. The default range for floating-point types is \([0,1)\). The default range for integral types is every possible integral number that can be stored by the given type.


template <typename T, typename RNG>
inline T pxart::uniform(RNG&& rng, T a, T b) noexcept;
This functions advances the state of the given random number generator to get a number and transforms it such that a sequence of returned numbers is uniformly distributed in the given range. The range for floating-point types is interpreted as \([a,b)\). The range for integral types is interpreted as \(\{x\in\mathbb{Z} \ | \ a\leq x \leq b\}\).

Include Scheme

#include <pxart/uniform.hpp>

Floating-Point Numbers

The pxart::uniform methods for floating-point types can only be used for float and double.

Notes and Implementation Details

Scheme of the Uniform Distribution Implementation for Floating-Point Numbers

Example

#include <iomanip>
#include <iostream>
#include <random>
//
#include <pxart/mt19937.hpp>
#include <pxart/uniform.hpp>

using namespace std;

int main() {
  // Initialize pxart PRNG.
  pxart::mt19937 rng{random_device{}};
  // Print some pseudorandom numbers.
  for (size_t i = 0; i < 10; ++i) {
    // Generate uniformly distributed single-precision floating-point number
    // in the interval [0, 1).
    const auto random1 = uniform<float>(rng);
    // Generate uniformly distributed double-precision floating-point number
    // in the interval [-1.5, 1.0).
    const auto random2 = uniform(rng, -1.5, 1.0);

    cout << setw(20) << random1 << setw(20) << random2 << '\n';
  }
}

Integral Numbers

Notes and Implementation Details

To be fast, the pxart::uniform methods for integral numbers exhibit a small bias which is caused by round-off errors when truncating the shifted multiplication of two integral numbers.

Example

#include <iomanip>
#include <iostream>
#include <random>
//
#include <pxart/mt19937.hpp>
#include <pxart/uniform.hpp>

using namespace std;

int main() {
  // Initialize pxart PRNG.
  pxart::mt19937 rng{random_device{}};
  // Print some pseudorandom numbers.
  for (size_t i = 0; i < 10; ++i) {
    // Generate uniformly distributed integral numbers of type int
    // in the interval [-12, 25].
    const auto random1 = uniform<int>(rng, -12, 25);
    // Generate uniformly distributed characters
    // in the interval ['A', 'Z'].
    const auto random2 = uniform<char>(rng, 'A', 'Z');

    cout << setw(20) << random1 << setw(20) << random2 << '\n';
  }
}

Last update: January 18, 2021