Presentation is loading. Please wait.

Presentation is loading. Please wait.

 Monday, 10/28/02, Slide #1 CS106 Introduction to CS1 Monday, 10/28/02  QUESTIONS on HW 03??  Today: Generating random numbers  Reading & exercises:

Similar presentations


Presentation on theme: " Monday, 10/28/02, Slide #1 CS106 Introduction to CS1 Monday, 10/28/02  QUESTIONS on HW 03??  Today: Generating random numbers  Reading & exercises:"— Presentation transcript:

1  Monday, 10/28/02, Slide #1 CS106 Introduction to CS1 Monday, 10/28/02  QUESTIONS on HW 03??  Today: Generating random numbers  Reading & exercises: None  New files/handouts: Random1.cpp to Random4.cpp

2  Monday, 10/28/02, Slide #2 Functions for generating random numbers (well, pseudo-random)  The library contains the function rand(), which returns a random integer in the range 0 to RAND_MAX (a system-determined constant, 32,767 on our system)  See the program Random1.cpp  How do the random values generated compare if we run the program more than once?

3  Monday, 10/28/02, Slide #3 Generating different numbers on each run: srand(), time(0)  Function rand() essentially uses a list of numbers that are randomly distributed: 41, 18467, 6334,...  First call to rand() always returns 41, 2nd call 18467, etc.  Function srand(int n) changes the starting point  Use srand(n) just once before using rand(): n =1 is default; other n’s give other starting points  Function time(0) returns # seconds elapsed since 1/1/70!  Use to get an arbitrary starting point for srand():  srand(time(0)) ; Use this once before rand() for “random” starting point  See Random2.cpp

4  Monday, 10/28/02, Slide #4 Changing the range of random numbers with mod operator %  If Q is a positive integer, then rand() % Q is a number from 0 to Q -1  E.g. if Q = 6, then rand() % 6 = 0,1,2,3,4 or 5  rand() % Q always produces one of Q consecutive integers, starting with 0  To change the starting value from 0 to another integer S, use rand() % Q + S  E.g. if Q = 6 and S = 1, then rand() % 6 +1= 1,2,3,4, 5 or 6: essentially the toss of a die!  To get a value from loVal to (and including) hiVal:  rand() % (hiVal - loVal + 1) + loVal  See Random3.cpp

5  Monday, 10/28/02, Slide #5 Some random exercises...  Write a code segment that tosses a coin (randomly outputs “heads” or “tails”)  Modify it so it cheats -- heads are twice as likely as tails  How would we generate a random probability -- a fraction between 0 and 1?  Modify code to generate heads with desired probability p between 0 and 1  See Random4.cpp


Download ppt " Monday, 10/28/02, Slide #1 CS106 Introduction to CS1 Monday, 10/28/02  QUESTIONS on HW 03??  Today: Generating random numbers  Reading & exercises:"

Similar presentations


Ads by Google