Random Numbers Until now, all programs have behaved deterministically - completely predictable and repeatable based on input values Some applications.

Slides:



Advertisements
Similar presentations
Modular Programming With Functions
Advertisements

1 Chapter Eight Designing Libraries. 2 Programming Complexity As long as we continue to solve problems of ever-increasing sophistication, the process.
Random variables 1. Note  there is no chapter in the textbook that corresponds to this topic 2.
Exercise 4 1. Write a program that simulates coin tossing. For each toss of the coin the program should print Heads or Tails. Let the program toss the.
1 Random number generation Using srand(), rand() & time(0) Searching and Sorting Demo Making searching & sorting more generic Overloading the functions.
A Java API Package java.security  The Java Security Package contains classes and interfaces that are required by many Java programs.  This package is.
The Princeton Egg The Global Consciousness Project (video)The Global Consciousness Project (video) Princeton Egg Website Our Egg: PrincetonEgg.cppPrincetonEgg.cpp.
 Monday, 10/28/02, Slide #1 CS106 Introduction to CS1 Monday, 10/28/02  QUESTIONS on HW 03??  Today: Generating random numbers  Reading & exercises:
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 12 – Craps Game Application: Introducing Random.
1 Random numbers Random  completely unpredictable. No way to determine in advance what value will be chosen from a set of equally probable elements. Impossible.
Random Number Generator. Using Software We can generate random number by: 1- table 2- hardware 3-- software Function to generate RN by SW is: 1-rand 2-
 2008 Pearson Education, Inc. All rights reserved Case Study: Random Number Generation C++ Standard Library function rand – Introduces the element.
C++ Programming Lecture 10 Functions – Part II
Loops Wrap Up 10/21/13. Topics *Sentinel Loops *Nested Loops *Random Numbers.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions (Header files and Library Functions) Outline.
CS221 Random Numbers. Random numbers are often very important in programming Suppose you are writing a program to play the game of roulette The numbers.
Random numbers in C++ Nobody knows what’s next....
A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I.
CSci 162 Lecture 7 Martin van Bommel. Random Numbers Until now, all programs have behaved deterministically - completely predictable and repeatable based.
CSE202: Lecture 13The Ohio State University1 Function Scope.
Section The Idea of Probability AP Statistics
Functions and Libraries. Reference parameters void setToZero(int var) { var = 0; } int main() { int var = 0; setToZero(var); cout
1 Generating Random Numbers Textbook ch.6, pg
MR. CRONE Generating Random Numbers. Random Numbers Many programs require the computer to generate random numbers Random numbers are used in many applications.
Switch Case, Enums, and Random Numbers CS 242 Tarik Booker California State University, Los Angeles.
L131 Assignment Operators Topics Increment and Decrement Operators Assignment Operators Debugging Tips rand( ) math library functions Reading Sections.
Adding Probabilities 12-5
Chapter 9: Value-Returning Functions
Monte Carlo Methods Some example applications in C++
Probability 100% 50% 0% ½ Will happen Won’t happen
Probability Predictions Ch. 1, Act. 5.
Approximate computations
Why they aren't really random
Predefined Functions Revisited
TMF1414 Introduction to Programming
© 2016 Pearson Education, Ltd. All rights reserved.
Functions, Part 2 of 2 Topics Functions That Return a Value
Number guessing game Pick a random number between 1 and 10
Iterative Constructs Review
CMPT 201 Functions.
Conditional Probability
CSC113: Computer Programming (Theory = 03, Lab = 01)
Deitel- C:How to Program (5ed)
CS1010 Programming Methodology
Approximate computations
Random numbers Taken from notes by Dr. Neil Moore
The Random Class and its Methods
Chapter 5 - Functions Outline 5.1 Introduction
توابع در C++ قسمت اول اصول كامپيوتر 1.
Random Number Generation
Pseudo-random numbers
Expected Value.
Now it’s time to look at…
Iterative Constructs Review
Assignment Operators Topics Increment and Decrement Operators
Assignment Operators Topics Increment and Decrement Operators
A First Book of ANSI C Fourth Edition
CS150 Introduction to Computer Science 1
Now it’s time to look at…
Section 6.1 The Idea of Probability
Applied Discrete Mathematics Week 12: Discrete Probability
Predefined Functions Revisited
CS 144 Advanced C++ Programming January 31 Class Meeting
Expected Value.
6 Functions.
Review Lab assignments Homework #3
Programming Fundamental
Assignment Operators Topics Increment and Decrement Operators
Functions that return a value
Functions in C Math Library Functions Functions Function Definitions
Presentation transcript:

Random Numbers Until now, all programs have behaved deterministically - completely predictable and repeatable based on input values Some applications (e.g. games) require unpredictable behavior - nondeterministic One method for nondeterminism die toss where one of several outcomes possible

Random Numbers Number is random if there is no way to determine in advance what value it will have among a set of equally probable possibilites E.g. on a standard unloaded die random number between 1 and 6 equally possible Cannot generate number randomly on computer uses deterministic behavior

Pseudo-random Numbers Use a deterministic procedure to generate “random” numbers Numbers must appear random behave like random numbers statistically be sufficiently difficult to predict in advance Random numbers generated by an algorithmic process by a computer are called pseudo-random numbers

Pseudo-random number in C++ <cstdlib> includes function rand and constant RAND_MAX prototype int rand(); generates pseudo-random number between 0 and RAND_MAX, inclusive Value of RAND_MAX depends on system Ours uses 32 767 but your program should not rely on a given value but on the symbolic constant

Using “rand” to flip a coin Want to use the result of rand that is a number between 0 and RAND_MAX to generate Heads or Tails Use if (rand() <= RAND_MAX / 2) cout << ”Heads”; else cout << ”Tails”;

Wrong Method to flip a coin Why not use: if (rand() % 2 == 0) cout << ”Heads”; etc. No guarantee of distribution of even and odd numbers, only even distribution along the range 0 to RAND_MAX

Using “rand” to Roll a Die int RollDie(void) { if (rand() < RAND_MAX / 6) return 1; if (rand() < RAND_MAX*2/6) return 2; if (rand() < RAND_MAX*3/6) return 3; if (rand() < RAND_MAX*4/6) return 4; if (rand() < RAND_MAX*5/6) return 5; return 6; } Unfortunately uses new value of “rand” in each “if”, thus losing original.

Using “rand” to Roll a Die (2) int RollDie() { int r = rand(); if (r < RAND_MAX / 6) return 1; if (r < RAND_MAX*2/6) return 2; if (r < RAND_MAX*3/6) return 3; if (r < RAND_MAX*4/6) return 4; if (r < RAND_MAX*5/6) return 5; return 6; } Unfortunately RAND_MAX*2/6 gives strange value due to integer arithmetic Better to use RAND_MAX/6.0*2.0

Generalize the Problem Want a function to choose random number between two values, inclusive int RandomInteger(int low, int high); Four-step process 1. Normalize rand to number d where 0 <= d < 1 2. Scale d by multiplying by size of desired range 3. Truncate number back to an integer 4. Translate integer so range begins at lower bound

RandomInteger int RandomInteger(int low, int high) { int k; double d; d = rand() / ((double) RAND_MAX + 1.0); k = (int) (d * (high - low + 1)); return (low + k); }

Random Problem? Running randtest twice gives same values Why? rand function always returns same sequence of values on every execution Why? So program behavior is repeatable for debugging But - want non-deterministic behavior Can modify behavior

Seeding Random Numbers Initial value for random number generator same each time program is run Next value depends on previous Change initial value, change behavior Function srand in stdlib allows seed Using time from time.h allows “random” seed srand( (int) time(NULL)); Provide operation in interface

Header files and implementation files Example Random Two steps: Create an interface - random.h Write implementation - random.cpp

Interface Contents Documentation on use Function prototypes Constant definitions Type definitions (later) Three lines at top: #ifndef _name_h #define _name_h at end: #endif

Preliminary random.h #ifndef _random_h #define _random_h /* Function: RandomInteger * Usage: n = RandomInteger(low,high); * ----------------------------------- * This function returns a random integer * in the range low to high, inclusive. */ int RandomInteger(int low, int high); #endif

Preliminary random.cpp #include <stdlib> #include ”random.h” int RandomInteger(int low, int high) { int k; double d; d = rand() / ((double) RAND_MAX + 1); k = (int) (d * (high - low + 1)); return (low + k); }

Preliminary Client /* Filename: randtest.cpp */ #include <iostream> #include ”random.h” int main(void) { int i; for (i = 0; i < 10; i++) cout << RandomInteger(1,6) << endl; return (0); }