Simulation-6

Simulation-6 - The rand Function Random Numbers In many...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
1 Random Numbers In many applications, want to be able to generate random numbers, permutations, etc. Since computers are deterministic, true randomness does not exist Settle for pseudo-randomness : sequence of numbers that looks random, but is deterministically generated Most random number generators use a “linear congruential generator” (LCG): o Start with a seed number X 0 o Next “random” number given by: X n+1 = ( a X n + c ) mod m o Effectiveness is very sensitive to choice of a , c , and m o Note: the sequence of random numbers must eventually cycle The rand() Function In C/C++, there exists a function for generating pseudo-random numbers: int rand(void) Part of <stdlib.h> library Returns integer between 0 and RAND_MAX , inclusive o Values supposed to be “uniformly” distributed in range o RAND_MAX guaranteed to be at least 32767 (often larger) In most implementations, uses LCG Seeded using: void srand(unsigned int seed) o Often set to current system time: srand(time(NULL)); For our purposes, we accept approximation: (rand()/((double)RAND_MAX + 1)) ~ Uni[0, 1) Shuffling Deck of Cards Want to generate a random permutation of set E.g., completely shuffle a deck of cards Want all permutations to be equally likely void shuffle(int arr[], int n) { for(int i = n - 1; i > 0; i--) { double u = uniformRand(0, 1); // u in [0, 1) // pick one of "remaining" i positions int pos = (int)((i + 1) * u); swap(arr[i], arr[pos]); } } Bad, But Common, Shuffle Common mistake in creating random permutation void badShuffle(int arr[], int n) { for(int i = 0; i < n; i++) { double u = uniformRand(0, 1); // u in [0, 1) // pick any position int pos = (int)(n * u); swap(arr[i], arr[pos]); } } Has n n execution paths, but only n! permutations
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.
  • Spring '09
  • Probability distribution, Randomness, Cumulative distribution function, Discrete probability distribution, Discrete Inverse Transform

{[ snackBarMessage ]}

Page1 / 3

Simulation-6 - The rand Function Random Numbers In many...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online