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?
c++floating-pointrandom
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?
Best Answer
rand()
can be used to generate pseudo-random numbers in C++. In combination withRAND_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.
This will generate a number from 0.0 to some arbitrary
float
,X
:This will generate a number from some arbitrary
LO
to some arbitraryHI
: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 callingsrand()
. This should be done once during your program's run -- not once every time you callrand()
. This is often done like this:In order to call
rand
orsrand
you must#include <cstdlib>
.In order to call
time
, you must#include <ctime>
.