Skip to the content of the web site.

Project AA.2: Discrete uniform distribution

A random variable that chooses a real number from $a$ to $b$, inclusive, with a number appearing in a sub-interval $[c, d]$ with probability $\frac{d - c}{b - a}$ is said to be a continuous uniform distribution on $[a, b]$.

Examples of a uniform distribution include:

  • If a person arrives at a bus-stop without knowing when the bus is coming and the bus arrives once per half hour, then the distribution describing how long that person will wait will be a uniform distribution from $0$ to $30$ minutes.
  • If an incoming voltage has a value between $0$ and $n$ volts, and an analog-to-digital converter turns that voltage into a digital integer from $0$ to $n$, then the error of that conversion will result in a value in $[-0.5, 0.5]$ if rounding is used, or $[0, 1]$ if truncation is used.
  • If you are playing Twister and you spin the spinner with sufficient force that it goes around at least four times, then the angle that the spinner lands at will be a uniform distribution between $0$ and $360$ degrees or $0$ and $2\pi$ radians.

Implement a function that returns a double between $a$ and $b$ with equal likelihood.

Use an assertion to ensure that the argument $a$ is less than or equal to $b$.

The rand(), found in the cstdlib library, returns an integer between 0 and RAND_MAX, inclusive.

#include <cstdlib>
#include <cassert>

// Function declaration
double continuous_uniform( double a, double b );

One observation: you will be converting the integer returned by rand() into a double, but ask yourself, which is more "uniform" on the interval $[0, 1]$:

  • ((double) rand())/MAX_RAND, or
  • (rand() + 0.5)/(MAX_RAND + 1.0).

Justify your answer. You can use as an argument the example of the choosing a random angle on the interval $[0, 2\pi]$. Is there one angle that is twice as likely to be returned as any other?

Class implementation

Implement a class Continuous_uniform_distribution where:

  • The constructor Continuous_uniform_distribution::Continuous_uniform_distribution( double a, double b ); takes arguments $a$ and $b$ and creates an instance that generates random values that follow the discrete uniform distribution.
  • The member function double Continuous_uniform_distribution::operator()() const; returns a value from the interval $[a, b]$ following the uniform distribution described above.