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

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