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");
}
 20 23 23 22 22 25 21 21 23 21 22 19 20 22 21 21 23 24 23 21
 24 18 22 19 20 22 23 21 24 23 21 18 21 18 23 25 25 18 20 23
 21 24 24 24 21 19 19 18 25 25 21 23 25 18 25 20 22 22 23 20
 19 18 20 22 19 25 21 18 18 24 23 21 22 21 19 25 22 21 25 22
 20 21 19 19 21 18 21 25 22 18 19 24 19 21 20 20 21 24 20 21
 22 18 24 18 21 18 18 18 21 25 22 23 20 23 24 23 24 20 22 20
 20 23 18 21 19 21 23 22 19 18 25 23 18 23 23 21 23 23 21 18

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2017-12-10T17:22

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building