1 Chapter Eight Designing Libraries. 2 Programming Complexity As long as we continue to solve problems of ever-increasing sophistication, the process.

Slides:



Advertisements
Similar presentations
Methods Java 5.1 A quick overview of methods
Advertisements

Modular Programming With Functions
BU BU Decision Models Simulation1 Simulation Summer 2013.
Computer Science 111 Fundamentals of Programming I Introduction to Object-Based Programming.
Building Java Programs
Random variables 1. Note  there is no chapter in the textbook that corresponds to this topic 2.
Probability Distributions CSLU 2850.Lo1 Spring 2008 Cameron McInally Fordham University May contain work from the Creative Commons.
Games as Emergent Systems first schema on “rules”.
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.
Overview Reference parameters Documenting functions A game of craps. Design, code, test and document.
Chapter 5 Understanding Randomness
Excursions in Modern Mathematics, 7e: Copyright © 2010 Pearson Education, Inc. 15 Chances, Probabilities, and Odds 15.1Random Experiments and.
Probability theory and average-case complexity. Review of probability theory.
3.6: Probabilities Through Simulations Objective: To simulate probabilities using random number tables and random number generators CHS Statistics.
A Java API Package java.security  The Java Security Package contains classes and interfaces that are required by many Java programs.  This package is.
1 CMSC 132: Object-Oriented Programming II Software Development II Department of Computer Science University of Maryland, College Park.
Discrete Event Simulation How to generate RV according to a specified distribution? geometric Poisson etc. Example of a DEVS: repair problem.
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.
C++ fundamentals.
Fair Games/Expected Value
Chapter 11: understanding randomness (Simulations)
Stevenson and Ozgur First Edition Introduction to Management Science with Spreadsheets McGraw-Hill/Irwin Copyright © 2007 by The McGraw-Hill Companies,
1 Building Java Programs Chapter 5 Lecture 5-2: Random Numbers reading: 5.1, 5.6.
Copyright © 2010 Pearson Education, Inc. Unit 3: Gathering Data Chapter 11 Understanding Randomness.
Chapter 9: Simulation Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
Sullivan – Fundamentals of Statistics – 2 nd Edition – Chapter 5 Section 1 – Slide 1 of 33 Chapter 5 Section 1 Probability Rules.
Slide 11-1 Copyright © 2004 Pearson Education, Inc.
1-1 Copyright © 2015, 2010, 2007 Pearson Education, Inc. Chapter 10, Slide 1 Chapter 10 Understanding Randomness.
Understanding Randomness Chapter 11. Why Be Random? What is it about chance outcomes being random that makes random selection seem fair? Two things: –
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11 Understanding Randomness.
STA Lecture 61 STA 291 Lecture 6 Randomness and Probability.
1.3 Simulations and Experimental Probability (Textbook Section 4.1)
Understanding Randomness
Slide Understanding Randomness.  What is it about chance outcomes being random that makes random selection seem fair? Two things:  Nobody can.
1 FUNCTIONS - I Chapter 5 Functions help us write more complex programs.
Recap of Functions. Functions in Java f x y z f (x, y, z) Input Output Algorithm Allows you to clearly separate the tasks in a program. Enables reuse.
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.
1 CSCD 326 Data Structures I Software Design. 2 The Software Life Cycle 1. Specification 2. Design 3. Risk Analysis 4. Verification 5. Coding 6. Testing.
Probability Evaluation 11/12 th Grade Statistics Fair Games Random Number Generator Probable Outcomes Resources Why Fair Games? Probable Outcome Examples.
5.1 Probability in our Daily Lives.  Which of these list is a “random” list of results when flipping a fair coin 10 times?  A) T H T H T H T H T H 
CS 108 Computing Fundamentals Notes for Tuesday, February 24, 2015.
WOULD YOU PLAY THIS GAME? Roll a dice, and win $1000 dollars if you roll a 6.
Inference: Probabilities and Distributions Feb , 2012.
Binomial Distributions Chapter 5.3 – Probability Distributions and Predictions Mathematics of Data Management (Nelson) MDM 4U.
 2000 Prentice Hall, Inc. All rights reserved. 5.2Program Modules in C Functions –Modules in C –Programs combine user-defined functions with library functions.
CSci 162 Lecture 7 Martin van Bommel. Random Numbers Until now, all programs have behaved deterministically - completely predictable and repeatable based.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Chapter 10 Understanding Randomness. Why Be Random? What is it about chance outcomes being random that makes random selection seem fair? Two things: –
Computer Science I: Understand how to evaluate expressions with DIV and MOD Random Numbers Reading random code Writing random code Odds/evens/…
Chapter 6—Objects and Classes The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Objects and Classes C H A P T E R 6 To beautify.
CSci 162 Lecture 8 Martin van Bommel. Large-scale Programming Up to now we have been writing relatively short programs to solve simple problem Want to.
1 Chapter 11 Understanding Randomness. 2 Why Be Random? What is it about chance outcomes being random that makes random selection seem fair? Two things:
Random Numbers Eric Roberts CS 106A January 22, 2010.
Introduction Imagine the process for testing a new design for a propulsion system on the International Space Station. The project engineers wouldn’t perform.
Functions and Libraries. Reference parameters void setToZero(int var) { var = 0; } int main() { int var = 0; setToZero(var); cout
Statistics 11 Understanding Randomness. Example If you had a coin from someone, that they said ended up heads more often than tails, how would you test.
The normal approximation for probability histograms.
1 Building Java Programs Chapter 5 Lecture 11: Random Numbers reading: 5.1, 5.6.
Fundamentals of Programming I Introduction to Object-Based Programming
Building Java Programs
Building Java Programs
Random Numbers Until now, all programs have behaved deterministically - completely predictable and repeatable based on input values Some applications.
Understanding Randomness
Statistics 1: Elementary Statistics
Dry run Fix Random Numbers
Building Java Programs
Topic 1: Problem Solving
Probability using Simulations
Building Java Programs
Presentation transcript:

1 Chapter Eight Designing Libraries

2 Programming Complexity As long as we continue to solve problems of ever-increasing sophistication, the process of programming will become more sophisticated as well To make programming manageable, we must reduce the complexity of the programming process as much as possible Libraries offer a similar reduction in programming complexity as functions, but at a higher level of detail

3 Criteria for Designing Libraries Unified Simple Sufficient General Stable

4 A Unifying Theme A central feature of a well-designed library is that it presents a unified and consistent abstraction and theme The math library consists of mathematical functions, and the graphics library provides functions for drawing pictures on the screen All the functions in graphics use coordinates in inches and angles in degrees, and all drawings begin at the current position of the pen

5 Simplicity & Information Hiding A library should be as easy to use as possible A library interface acts as a reference guide and contains precisely the information a client needs to know and no more Often, the real value of an interface lies not in the information it reveals but rather in the information it hides

6 Simplicity & Information Hiding It is best to think of an interface not primarily as a communication channel between the client and implementation, but instead as a wall that divides them Ideally, all the complexity involved in the realization of a library lies on the implementation side of the wall

7 Meeting the needs of Clients Everything should be as simple as possible, but no simpler Simplicity is only part of the story. Your interface must provide sufficient functionality to serve the clients’ needs Learning to strike the right balance between simplicity and completeness in interface design is one of the fundamental challenges in programming

8 Advantages of General Tools A good library abstraction serves the needs of many different clients When you design the interface for a library, forget about the application that cause you to design it in the first place and instead design it for the most general possible audience The function drawGrid in graphics library is a good example

9 The Value of Stability People change and forget to tell each other. Too bed—causes so many mistakes Interfaces tend to be stable over long periods of time As long as the interface does not change, both implementers and clients are relatively free to make changes on their own side of the abstraction boundary

10 The Value of Stability Changing an interface in such a way that existing programs will continue to run without modification is called extending the interface If you need to make evolutionary changes over the lifetime of an interface, it is usually best to make those changes by extension

11 Generating Random Numbers Being able to simulate random behavior is necessary in situations that involves flipping a coin or rolling a die A program is deterministic if its actions are completely predictable given any set of input values; otherwise, it is nondeterministic

12 Pseudo Random Numbers From a theoretical perspective, a number is random if there is no way to determine in advance what value it will have among a set of equally probable possibilities Computers in fact use a deterministic procedure to generate what we call random numbers

13 Pseudo Random Numbers In most applications, it does not matter if the numbers are truly random; all that matters is that the numbers appear to be random They should behave like random numbers from a statistical point of view They should be sufficiently difficult to predict in advance that no user would bother

14 rand The function rand in the library stdlib.h produces pseudo random numbers int rand(void) The values returned are integers between 0 and RAND_MAX, inclusive

15 An Example #include main() { int i; printf(“On this computer, RAND_MAX = %d.\n”, RAND_MAX); for (i = 1; i < 10; i++) { printf(“The %dth number = %10d\n”, i, rand()); }

16 An Example On this computer, RAND_MAX = The 1th number = 41 The 2th number = The 3th number = 6334 The 4th number = The 5th number = The 6th number = The 7th number = The 8th number = The 9th number = Press any key to continue

17 Changing the Range Heads Tails Heads Tails Heads Tails 0RAND_MAX 0 HeadsTails

18 Changing the Range #include main() { int i; for (i = 1; i < 10; i++) { if (rand( ) <= RAND_MAX / 2) { printf(“Heads\n”); } else { printf(“Tails\n”); }

19 Pitfalls The only random property that you are allowed to count on when using rand is the position of the result along the number line When converting the result of rand to a more restricted range of integers, do not try to use the remainder operator On many computers, the results of rand alternate between even and odd numbers

20 An Example int rollDie(void) { int r; r = rand(); if (r < RAND_MAX / 6) { return 1; } else if (r < RAND_MAX / 6 * 2) { return 2; } else if (r < RAND_MAX / 6 * 3) { return 3; } else if (r < RAND_MAX / 6 * 4) { return 4; } else if (r < RAND_MAX / 6 * 5) { return 5; } else { return 6; } }

21 A General Function In general, what you need is not a function that chooses a number between 0 and RAND_MAX but one that chooses a random integer between two limits that you supply int randomInt(int low, int high);

22 A General Function Normalize the integer result into a floating point d in the range 0  d < 1 Scale the value d by multiplying it by the size of the desired range high – low + 1 Truncate the number back to an integer k by throwing away any fraction Translate the integer, k + low, so that the range begins at the desired lower bound

23 A General Function int randomInt(int low, int high) { int k; double d; d = (double) rand() / ((double) RAND_MAX + 1); k = (int) (d * (high – low + 1)); return (k + low); }

24 The Contents of an Interface Each definition exported by an interface is called an interface entry An interface entry may be –a function prototype –a constant definition –a type definition

25 The Contents of an Interface #ifndef _name_h #define _name_h any required #include lines interface entries #endif

26 The Interface random.h /* * File: random.h … */ #ifndef _random_h #define _random_h /* * Function: randomInt … */ int randomInt(int low, int high); #endif Comments for clients

27 The Implementation random.c /* File: random.c … */ #include #include “random.h” /* Function: randomInt … */ int randomInt(int low, int high) { int k; double d; d = (double) rand() / ((double) RAND_MAX + 1); k = (int) (d * (high – low + 1)); return (k + low); } Comments for implementers

28 Testing the Library #include #include “random.h” int rollDie(void) { return randomInt(1, 6); } main() { int i; for (i = 1; i < 10; i++) printf(“%d\n”, rollDie()); }

29 Deterministic Sequence The sequence of results of rand is the same for every run of the program This is because rand is a deterministic procedure This deterministic property facilitates the debugging of programs

30 Initializing the Generator Each time rand is called, it uses the last random number to perform a series of calculations to produce the next random number The value that is used to get the entire process started is called a seed for the random number generator

31 Initializing the Generator rand seed41 rand rand

32 Randomizing the Seed The seed of the random number generator can be initialized using the function srand void srand(int seed); The function time in library time.h can be used to randomize the seed void randomize(void) { srand( (int) time(NULL)); }

33 Evaluating the Library Is it unified? Yes! Is it simple? Yes! Is it suffient? Questionable! Is it general? Yes! Is it stable? Yes!

34 Generating Random Real Numbers In some applications, random real numbers are required double randomReal(double low, double high); double randomReal(double low, double high) { double d; d = (double) rand() / ((double) RAND_MAX + 1); return (d * (high – low + 1)) + low; }

35 Simulating a Probabilistic Event In some applications, you need to simulate events that occur with random probability bool randomeChance(double p); bool randomChance(double p) { return (randomReal(0, 1) < p); }

36 Simulating a Probabilistic Event #include main() { int i; for (i = 1; i < 10; i++) { if (randomChance(0.5)) { printf(“Heads\n”); } else { printf(“Tails\n”); }

37 Complete random.h /* File: random.h … */ #ifndef _random_h #define _random_h /* Function: randomInt … */ int randomInt(int low, int high); /* Function: randomize … */ void randomize(void); /* Function: randomReal … */ double randomReal(double low, double high); /* Function: randomChance … */ bool randomChance(double p); #endif

38 Complete random.c /* File: random.c … */ #include #include “random.h” /* Function: randomInt … */ int randomInt(int low, int high) { … } /* Function: randomize … */ void randomize(void) { … } /* Function: randomReal … */ double randomReal(double low, double high) { … } /* Function: randomChance … */ bool randomChance(double p) { … }

39 Play the Craps Game Roll a pair of dice If the total is 2, 3, or 12, you lose If the total is 7 or 11, you win If the total is 4, 5, 6, 8, 9, or 10, this number is your point. You will continue to roll the dice until the total is equal to your point or 7. If the total is 7, you lose. If the total is your point, you win

40 Play the Craps Game #include #include “random.h> main() { randomize(); playCrapsGame(); }

41 Play the Craps Game void playCrapsGame(void) { int total, point; total = rollTwoDice(); if (total == 7 || total == 11) { printf(“You win.\n”); } else if (total == 2 || total == 3 || total == 12) { printf(“You lose.\n”) } else { point = total; playPoint(point); }

42 Play the Craps Game void playPoint(int point) { int total; printf(“Your point is %d.\n”, point); while (TRUE) { total = rollTwoDice(); if (total == point) { printf(“You win.\n”); break; } else if (total == 7) { printf(“You lose.\n”); break; }

43 Play the Craps Game void rollTwoDice(void) { int d1, d2, total; d1 = randomInt(1, 6); d2 = randomInt(1, 6); total = d1 + d2; printf(“You rolled %d + %d = %d.\n”, d1, d2, total); return total; }