Thursday Week 9


Random Numbers1/15

Random numbers are useful


... Random Numbers2/15

But how can a computer pick a number at random?

Software can only produce pseudo random numbers.


A Random Number Generator3/15

The most widely-used technique is called the Linear Congruential Generator (LCG)


... A Random Number Generator4/15

LCG is not good for applications that need extremely high-quality random numbers


... A Random Number Generator5/15

Trivial example:


... A Random Number Generator6/15

Another trivial example:


... A Random Number Generator7/15

It is a complex task to pick good numbers. A bit of history:

Lewis, Goodman and Miller (1969) suggested

gcc uses a LCG-based algorithm that's slightly more involved; for details, including a short C program that produces the exact same pseudo-random numbers for any given seed value, see here


... A Random Number Generator8/15


Exercise: Random Numbers9/15

Write a program randolf.c that


... Exercise: Random Numbers10/15

To convert to a number between 0 .. RANGE

Using the remainder to compute a random number is not the best way:


Seeding11/15

There is one significant problem with randolf.c:

To vary the output, can give the random seeder a starting point that varies with time


Exercise: Seeding12/15

Modify randolf.c by

Note: this function is provided by the time.h library


Exercise: Coin Tossing13/15

  • A common application of random numbers is simulation
  • Another common application is generating 'average' data to perform as testcases

    Write a program that

    Measure its performance using the UNIX time command (for a million toin cosses, 10 million, 100 million, ...)


    ... Exercise: Coin Tossing14/15

    What you can observe:


    Tips for Next Week's Lab15/15


    BSTs, Files, Random Numbers

    1. A (recursive) function to delete all leaves in a binary search tree
      • think about the base case first:
        What is it, what should happen, what should the function return?
      • then think about recursive cases

    2. Merge 3 files, line by line
      • keep going after reaching EOF in one file if there are still lines left in the other(s)
      • stop once all 3 files are EOF

    3. Generate random words
      • choose each letter randomly between 'a'..'z'
      • for the second part, design algorithm to reverse a linked list in-place (that is, without using a second list)


    Produced: 5 Oct 2016