CS157

CS157: Intro to C, Part II

Spring 2018

Random

See this page as a slide show

Random Numbers

Random numbers—too important to be left to chance!

Random Number Generation

A true random number generator has three important properties:

  1. It is unbiased.
    All values of whatever sample size is collected are equiprobable.
  2. It is unpredictable.
    It is impossible to predict what the next output will be, given all the previous outputs, but not the internal “hidden” state.
  3. It is unreproducible.
    Two of the same generators, given the same starting conditions, will produce different outputs.

Random Number Generation

Other Descriptions:

Very rarely is a random number generator all of: “good”, “cryptographically strong”, and “true”. This isn't necessarily a bad thing, but it's worth remembering when evaluating claims that one random number generator is “better” than another.

Random Number Generation

<stdlib.h> provides us with two random number generator functions:

Random Number Generation

rand()

Why is the number so big? Shouldn’t we randomly get a small number every once in a while?

Seeding the generator

srand()

Random Number Generation

Scaling

Scaling

Example

srand(time(NULL));

for (int row = 0; row < 7; row++) {
    for (int i = 0; i < 20; i++)
        printf(" %d", 18 + rand() % 8);
    printf("\n");
}
 24 24 18 19 19 20 19 21 19 18 19 21 25 22 22 18 25 25 20 24
 19 24 19 22 24 22 24 18 19 18 20 25 25 20 18 18 22 19 21 24
 19 23 19 19 19 23 19 18 23 21 24 24 19 18 20 25 22 19 25 23
 19 19 23 18 21 23 19 25 25 22 23 18 19 25 19 20 22 20 21 19
 23 19 25 24 19 20 23 24 21 22 21 22 23 18 23 18 24 24 18 23
 20 23 23 22 22 25 24 19 19 19 20 25 21 20 23 22 22 21 20 25
 25 24 21 23 24 18 23 22 24 23 19 19 21 25 23 25 24 21 18 25

Modified: 2017-12-10T17:22

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building