{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

CS 100 M Lecture 10

# CS 100 M Lecture 10 - 10 More on Functions Header...

This preview shows pages 1–13. Sign up to view the full content.

10. More on Functions Header, Specification, Body Input Parameter List Output Parameter List Built-Ins: randn, imag, real,max, min, ginput

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Eg. 1: “Gap N” Keep tossing a fair coin until | Heads – Tails | == N Score = total # tosses Write a function Gap(N) that returns the score and estimate the average value.
The Packaging… Heads = 0; Tails = 0; nTosses = 0; while abs(Heads-Tails) < N nTosses = nTosses + 1; if rand <.5 Heads = Heads + 1; else Tails = Tails + 1; end end function nTosses = Gap(N)

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
The Header… function nTosses = Gap(N) output parameter list input parameter list
The Body Heads = 0; Tails = 0; nTosses = 0; while abs(Heads-Tails) < N nTosses = nTosses + 1; if rand <.5 Heads = Heads + 1; else Tails = Tails + 1; end end The necessary output value is computed.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Local Variables Heads = 0; Tails = 0; nTosses = 0; while abs( Heads - Tails ) < N nTosses = nTosses + 1; if rand <.5 Heads = Heads + 1; else Tails = Tails + 1; end end
A Helpful Style Heads = 0; Tails = 0; n = 0; while abs(Heads-Tails) < N n = n + 1; if rand <.5 Heads = Heads + 1; else Tails = Tails + 1; end end nTosses = n; Explicitly assign output value at the end.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
The Specification… % Simulates a game where you % keep tossing a fair coin % until |Heads - Tails| == N. % N is a positive integer and % nTosses is the number of % tosses needed. function nTosses = Gap(N)
Estimate Expected Value of Gap(N) Strategy: Play “Gap N” a large number of times. Compute the average “score.” That estimates the expected value.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Solution… N = input('Enter N:'); nGames = 10000; s = 0; for k=1:nGames s = s + Gap(N); end ave = s/nGames; A very common methodology for the estimation of expected value.
Sample Outputs N = 10 Expected Value = 98.67 N = 20 Expected Value = 395.64 N = 30 Expected Value = 889.11

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
N = input('Enter N:'); nGames = 10000;
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 45

CS 100 M Lecture 10 - 10 More on Functions Header...

This preview shows document pages 1 - 13. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online