Random numbers in C++
Download
Report
Transcript Random numbers in C++
Random numbers in
C++
Nobody knows what’s next...
Deterministic machines
That means that computers do the same
predictable thing every time you give them
the same instructions
we WANT this – we don't want random
happenings - most of the time
when would you NOT want this?
games
of reality – traffic flows, nuclear
explosions, star formation
Cryptography!
simulations
What is "random"?
A “real” random number is generated by a
real world event like an atom decaying or
not in a certain time
Hard to do that in a computer
Best we can do with a deterministic
machine is make “pseudorandom”
numbers
They are “good enough”
“good enough”?
A “good” random number is one that is
distributed evenly in its range
If you were rolling a die, you want
numbers from 1 to 6 to be equally likely to
show up
This is over the “long run”, not each
individual trial
Lots of research
Lots has been done on random numbers
Trying to get faster algorithms
With larger cycles – all algorithms will
eventually start repeating but the best
ones not before a few million numbers at
least
Very heavy statistics and mathematics in
the latest algorithms
A simple one – “mid square”
Take a number to start with (the “seed”)
Square it
Take the “middle” of it – trim off some
digits at front and end
That’s the random number
Repeat the process by feeding the number
just generated back in as the starting
number next time
An example
12345 squared = 152399025
chop it off and get 23990
23990 squared = 575520100
chop it off and get 55201
55201 squared = 3047150401
chop it off and get 47150
And so on
Properties of an RNG
Give the algorithm a DIFFERENT seed to
start with and what comes out?
Give the algorithm the SAME seed to start
with and what comes out?
Syntax
Include the cstdlib library to get the
functions
Use srand(seed); to set the initial seed
(seed must be an integer)
Use rand() to get the next random number
returns
an integer between 0 and
RAND_MAX
Call srand ONCE per program, call rand
many times
Seeds to start with
srand(23); will always give you the same
sequence of random numbers – good
when testing!
Asking the user for a number and then
using it as the seed - works but is a bit
aggravating to the user
Using the time function is most flexible
(see example on web page)
rand() and RAND_MAX
rand() returns a integer between 0 and
RAND_MAX (a constant defined in cstdlib)
What if you need an integer number
between 1 and 6? rand() % 6 + 1
What if you need a number between 0 and
1 (i.e, a fraction) ? rand() / RAND_MAX
(but watch your TYPE here!)