patterncppCritical
Random float number generation
Viewed 0 times
randomgenerationfloatnumber
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?
I thought I could take the integer rand and divide it by something, would that be adequate enough?
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 (rand()) / static_cast (RAND_MAX);This will generate a number from 0.0 to some arbitrary
float, X:float r2 = static_cast (rand()) / (static_cast (RAND_MAX/X));This will generate a number from some arbitrary
LO to some arbitrary HI:float r3 = LO + static_cast (rand()) /( static_cast (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 (time(0)));In order to call
rand or srand you must #include .In order to call
time, you must #include .Code Snippets
float r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);float r2 = static_cast <float> (rand()) / (static_cast <float> (RAND_MAX/X));float r3 = LO + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(HI-LO)));srand (static_cast <unsigned> (time(0)));Context
Stack Overflow Q#686353, score: 455
Revisions (0)
No revisions yet.