Random float number generation

c++, floating-point, random

Solution

`rand()` can be used to generate pseudo-random numbers in C++. In combination with `RAND_MAX` and a little math, you can generate random numbers in any arbitrary interval you choose. This is sufficient for learning purposes and toy programs. If you need truly random numbers with normal distribution, you'll need to employ a more advanced method.

This will generate a number from 0.0 to 1.0, inclusive.

float r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);

This will generate a number from 0.0 to some arbitrary `float`, `X`:

float r2 = static_cast <float> (rand()) / (static_cast <float> (RAND_MAX/X));

This will generate a number from some arbitrary `LO` to some arbitrary `HI`:

float r3 = LO + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(HI-LO)));

Note that the `rand()` function will often not be sufficient if you need truly random numbers.

Before calling `rand()`, you must first "seed" the random number generator by calling `srand()`. This should be done once during your program's run -- not once every time you call `rand()`. This is often done like this:

srand (static_cast <unsigned> (time(0)));

In order to call `rand` or `srand` you must `#include <cstdlib>`.

In order to call `time`, you must `#include <ctime>`.

Problem

How do I generate random floats in C++? I thought I could take the integer rand and divide it by something, would that be adequate enough?

Original source

Related problems