Using the randomnumber class
Introduction
The randomnumber class provides methods for generating and scaling random numbers.
Superfluous background:
There is no such thing as true randomness. Many random number generators just return values from a highly divergent series. Others collect "entropy" from system hardware returning numbers that are actually associated with system activity but in an indiscernible way. In most cases, entropy-based systems are just used to seed systems that return values from a highly divergnet series.
If there is only one running process generating random numbers using a highly divergent series, successive calls to generateNumber() will never return the same value until all numbers between 0 and the number returned by getRandMax() (usually 2^31-1 but could be 2^32-1 or 2^15-1 on some systems) have been returned. At that point, the entire sequence will repeat.
Calls to the methods that generate scaled numbers may return the same value before all numbers in the range have been returned because they just scale down unique numbers returned from a larger range.
Generating a Few Numbers
The randomnumber class provides several static methods that are useful if you need to generate a few numbers here and there.
#include <rudiments/randomnumber.h> #include <rudiments/stdio.h> int main(int argc, const char **argv) { stdoutput.printf("random number between 0 and %d: %d\n", randomnumber::getRandMax(), randomnumber::generate(randomnumber::getSeed())); stdoutput.printf("random number between 1 and 10: %d\n", randomnumber::generate(randomnumber::getSeed(),1,10)); }
Generating Lots of Numbers
If you need to generate lots of numbers though, you should create an instance, seed it, and use it over and over to generate numbers.
#include <rudiments/randomnumber.h> #include <rudiments/stdio.h> int main(int argc, const char **argv) { // create an instance and seed it randomnumber rn; rn.setSeed(randomnumber::getSeed()); // generate some unscaled numbers stdoutput.write("generating some random numbers:\n"); for (uint16_t i=0; i<20; i++) { uint32_t unscalednum; rn.generate(&unscalednum); stdoutput.printf("%d, ",unscalednum); } stdoutput.write("\n\n"); // generate some scaled numbers stdoutput.write("generating some scaled random numbers:\n"); for (uint16_t j=0; j<20; j++) { int32_t scalednum; rn.generate(&scalednum,1,10); stdoutput.printf("%d, ",scalednum); } stdoutput.write("\n\n"); }