Random Walks and Defining Functions FEB 9 AND 11, 2015

Similar documents
Random Walks and Defining Functions FEB 16TH

Basics of Programming with Python

How to Think...- Chapter 3

(Python) Chapter 3: Repetition

Chapter 5 Functions (Part 2) Hong Sun COSC 1436 Fall, 2017 Oct 18, 2017

Chapter 5 Functions. Dr. Zhang COSC 1436 Summer, 2018 June 19, 2018

The Hong Kong Polytechnic University

Week 3. Sun Jun with slides from Hans Petter Langtangen

Last Time: Rolling a Weighted Die

Name: Partner: Python Activity 9: Looping Structures: FOR Loops

UNIT 9A Randomness in Computa5on: Random Number Generators. Randomness in Compu5ng

Computer and Programming: Lab 1

CMSC 201 Spring 2018

Common Loop Algorithms 9/21/16 42

def saylotsostuff(): print("lots Of") print("stuff") Output Lots Of Stuff Lots Of Stuff

Chapter 6: Files and Exceptions. COSC 1436, Spring 2017 Hong Sun 3/6/2017

A453 Task 1: Analysis: Problem: Solution:

More Functions. CS 1111 Introduction to Programming. Spring 2019

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

Computer Science 217

Problem Statement. B1: average speed

Outline. Announcements. Homework 2. Boolean expressions 10/12/2007. Announcements Homework 2 questions. Boolean expression

Most of the class will focus on if/else statements and the logical statements ("conditionals") that are used to build them. Then I'll go over a few

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

Invent Your Own Computer Games with Python

Intro. to Computing. Lecture 7 Page1

Condition Controlled Loops. Introduction to Programming - Python

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

CSc 110, Spring 2018 Lecture 9: Parameters, Graphics and Random. Adapted from slides by Marty Stepp and Stuart Reges

Downloaded from Chapter 2. Functions

The while Loop 4/6/16 4

Vectorization. We ve seen vectorized code already: Vectorized code and methods can be a great tool for simplifying code. 1 A(:,1) = x; 2 A = B.

Write Python statement(s)/expression(s) to solve each of the problems below. Consider the list lista below used to illustrate each problem.

Chapter 5 C Functions

Part 1 (80 points) Multiple Choice Questions (20 questions * 4 points per question = 80 points)

Introduction to Programming

A 10 cm. The diagram represents a large cone of height 30 cm and base diameter 15 cm.

CIS192 Python Programming

COMP 110 Programming Exercise: Simulation of the Game of Craps

PYTHON. Varun Jain & Senior Software Engineer. Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT. CenturyLink Technologies India PVT LTD

Experiment 1 Yahtzee or Validating the t-table

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

LOOPS. Repetition using the while statement

CS1110 Lab 6 (Mar 17-18, 2015)

CS 105 Lab As a review of what we did last week a. What are two ways in which the Python shell is useful to us?

Coordinate Graphing Quadrants and Reading Ordered Pairs. TeacherTwins 2015

Simulations How To for Fathom

Introduction to Programming

cs1114 REVIEW of details test closed laptop period

Lesson 9: An Application of Linear Equations

PURPLE COMET MATH MEET April 2011 HIGH SCHOOL - PROBLEMS. The ratio of 3 to the positive number n is the same as the ratio of n to 192. Find n.

Emil Sekerinski, McMaster University, Winter Term 16/17 COMP SCI 1MD3 Introduction to Programming

Impera've Programming

The Big Python Guide

Introduction to Programming

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

CPSC 427: Object-Oriented Programming

12/22/11. } Rolling a Six-Sided Die. } Fig 6.7: Rolling a Six-Sided Die 6,000,000 Times

Gold Hw8 Problem 3: TT Securities, Incorporated

CS Lecture 18: Card Tricks. Announcements. Slides by D. Gries, L. Lee, S. Marschner, W. White

Algorithms and Data Structures, Academic Year 2010/2011

Professor: Sana Odeh Functions. Math Functions (generating random functions) Reading:

Born in Tulsa in 1914 and passed away in Norman in 2010.

Lab 4 Fruitful Functions

Python Activity 7: Looping Structures WHILE Loops

Lesson 5: Graphs of Functions and Equations

Lab 2: Modules This lab accompanies Chapter 3 of Starting Out with Programming Logic & Design.

RANDOM NUMBER GAME PROJECT

Problem Dice program

(i) d={'head':(1,2,1),'arm':(1,2),'hand':(1,1,2),'leg':(1,1,1),'foot':(1,2,1) sum(d['head'])

2. Explain the difference between read(), readline(), and readlines(). Give an example of when you might use each.

Introduction to Computer Programming for Non-Majors

6.S189 Homework 2. What to turn in. Exercise 3.1 Defining A Function. Exercise 3.2 Math Module.

CE151-4-AU UNIVERSITY OF ESSEX. Sample Examination Questions 2011 INTRODUCTION TO PROGRAMMING

Programming Training kiddo. Main Points: - Python Statements - Problems with selections.

15-110: Principles of Computing, Spring 2018

Data 8 Final Review #1

Zipf's Law. This preliminary discussion gives us our first ideas about what the program we're writing needs to do.

Test 2: Compsci 06. Owen Astrachan. April 13, 2011

1 Lecture 6: Conditionals and Exceptions

Interactive Mode Python Pylab

Chapter Four: Loops II

Dividing Rectangles into Rows and Columns Part 1. 2nd Grade. Slide 1 / 201 Slide 2 / 201. Slide 3 / 201. Slide 4 / 201. Slide 6 / 201.

Python Games. Session 1 By Declan Fox

Functions and Recursion

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

CPTS 111, Fall 2011, Sections 6&7 Exam 3 Review

Python 1: Intro! Max Dougherty Andrew Schmitt

Java Outline (Upto Exam 2)

GWC Lesson 9 Partner Work and Comprehension

Math Day 2 Programming: How to make computers do math for you

lambda forms map(), reduce(), filter(), eval(), and apply() estimating π with list comprehensions

Cambridge International Examinations Cambridge International Advanced Subsidiary and Advanced Level. Published

Scientific Computing: Lecture 3

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Chapter Five: Functions

C Functions. 5.2 Program Modules in C

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.5. for loop and do-while loop

Random Walks & Cellular Automata

Spring Semester 13, Dr. Punch. Exam #1 (2/14), form 1 A

Transcription:

Random Walks and Defining Functions FEB 9 AND 11, 2015

If we take a random walk, will we go places? Problem: Simulate a random walk in which a person starts of at point 0 and at each step randomly picks a direction (left or right) and moves 1 step in that direction. Take as input a positive integer n and terminate the simulation when the walk reaches n or n. Report the average number of steps it took for the walk to terminate. Do this for various n and plot the results to get a sense of how rapidly the walk terminates, as a function of n.

The random module Programs for games and simulation use randomization extensively. In games, you want to add an element of randomness to the obstacles or adversaries. In simulations (e.g., traffic simulation) you want to introduce actors into your simulation according to certain probability distribution.

Some functions in the random module random.randint(a, b): return a random integer N such that a <= N <= b. random.random(): Return the next random floating point number in the range [0.0, 1.0). random.uniform(a, b): Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.

Simple Example Problem Problem: Write a program that takes as input a positive integer n and simulates n rolls of two six-sided dice. The program should report the number of times 7 appears as the sum of the outcomes of the two dice rolls.

Solution # Programmer: Sriram Pemmaraju # Feb 8th, 2015 # This program simulates the roll of two six-sided dice # as many times as specified by the input. Then the program # outputs the number of times 7 shows up as the sum of the two # dice rolls import random n = int(input("enter the number of times you want the dice rolled: ")) counter = 0 # keeps track of the number of rolls numsevens = 0 # keeps track of the number of sevens # while-loop that simulates the roll of two six-sided dice n times while counter < n: # Roll two six-sided dice and compute the sum of the outcomes sumrolls = random.randint(1, 6) + random.randint(1, 6) # if sum is seven then update a counter called numsevens if sumrolls == 7: numsevens = numsevens + 1 counter = counter + 1 print("the number of sevens is", numsevens)

Taking a single random step import random # Version 0. This program starts off a person at 0 and moves # her one step to the left or right, at random. location = 0 step = random.randint(0, 1) # returns 0 or 1, each with prob. 1/2 if step == 0: step = -1 location = location + step print(location)

Simulating the random walk import random # Programmer: Sriram Pemmaraju # Date: Feb 8, 2015 # Version 1: moves the person at random, one step at a time, left or right, # until the person reaches a barrier n or -n. Outputs the number of steps # it took to reach the barrier location = 0 # tracks the person's current location n = 10 # value of the barrier length = 0 # tracks the length of the random walk # This moves the person until she reaches the barrier at n or -n while abs(location) < n: step = random.randint(0, 1) # returns 0 or 1, each with prob. 1/2 # Adjusts the random number to be either -1 or +1 if step == 0: step = -1 location = location + step # updates location length = length + 1 print(length)

What more is there to do? There are two more things we need to do to solve our problem: 1. Find the average length of a walk, for a particular value n of the barrier. We have to decide how many runs to take the average over. 2. Repeat this for various values of n and try to understand the trend. We need a loop around our current code to do (1) and another loop around that code to do (2).

Defining a function Things have become complicated enough that we need to reorganize our code using functions. The plan is to define a function called randomwalk that takes n (the barrier distance) as an argument and returns the length of a simulated random walk. We can then just call this function from the main part of the program.

The function randomwalk # This function takes the barrier distance n as an argument, simulates # the random walk until it hits the barrier (n or -n), and returns the # length of the random walk def randomwalk( n ): location = 0 # tracks the location of the person length = 0 # tracks the length of the random walk # Loop terminates when the location reaches n or -n while abs(location)!= n: step = random.randint(0, 1) #returns 0 or 1, each with prob. 1/2 if step == 0: step = -1 location = location + step length = length + 1 return length

Notes about this function The first line of the function: def randomwalk( n ) Python keyword function name argument list The body of the function is indented. It is as though n is input to the function. A function can have one or more arguments The last line of the function is usually a return: return length

The rest of the program n = input("enter a positive integer: ") print(randomwalk(n)) randomwalk(n) is a call to the function randomwalk providing it the number n that the user as input as an argument. In order to execute the print statement, the function call randomwalk(n) needs to be executed first. This means that control is transferred to the function and we start executing the function starting with its first line. The value that the function returns essentially replaces the function call.

Averaging over 100 simulations n = input("enter a positive integer: ") count = 0 # tracks the number of times the walk is repeated sum = 0 # sum of the lengths of the walk; needed for average while count < 100: sum = sum + randomwalk(n) count = count + 1 print sum/100 Function call. The function is called 100 times.

The organization of the program import random # Programmer: Sriram Pemmaraju # Date: Feb 8, 2015 # Version 2: moves the person at random, one step at a time, left or right, # until the person reaches a barrier n or -n. Outputs the number of steps # it took to reach the barrier # This function takes in the value of the barrier, simulates a random # walk that terminates on reaching the barrier, and returns the length # of the simulated random walk def randomwalk(n): location = 0 # tracks the person's current location length = 0 # tracks the length of the random walk Function definition # This moves the person until she reaches the barrier at n or -n while abs(location)!= n: step = random.randint(0, 1) # returns 0 or 1, each with prob. 1/2 # Adjusts the random number to be either -1 or +1 if step == 0: step = -1 location = location + step # updates location length = length + 1 return length First line of code that is executed is the first line of the main program # This is the main part of the program (i.e., outside the function) n = input("enter the value of the barrier (a positive integer): ") sum = 0 # track the total length of all simulated random walks counter = 0 # The simulation is repeated 100 times while counter < 100: sum = sum + randomwalk(n) counter = counter + 1 print(sum/100) Function call Main program

Notes about programs that contain function definitions The first line of the main program is the first line of code that is executed. The function is only executed when it is called. In this code, the function is called 100 times and is therefore executed 100 times. In general a program will contain many function definitions followed by a main program. Functions may call each other. Typically the function will return a value. The returned value replaces the function call.

Making another function # This function repeats a random walk with barrier n as many times # as specified by the argument numrepititions and returns the length # of the walk, averaged over all the repititions def manyrandomwalks(n, numrepititions): count = 0 # tracks the number of times the walk is repeated sum = 0 # sum of the lengths of the walk; needed for average # Repeats the random walk as many times as specified by numrepititions while count < numrepitions: sum = sum + randomwalk(n) count = count + 1 return sum/numrepititions

The rest of the program n = input("enter a positive integer: ") print(manyrandomwalks(n, 100)) The function call needs to supply arguments in the correct order, i.e., in the order specified in the function definition. Names in the function call have nothing to do with names in the function definition. We could have written m = input("enter a positive integer: ") print manyrandomwalks(m, 100) And the value of m and the value 100 would be used for n and numrepititions in the function.

Trying this out for different barrier values m = 10 # tracks the value of the barrier # m travels through 10, 20,..., 100 in this loop and we compute and print the # average walk length for each m while m <= 100: print manyrandomwalks(m, 100) m = m + 10

Sample output 112.86 376.4 827.6 1628.04 2570.6 3594.2 4616.14 6035.6 8596.58 10948.58 Length of random walk 10948.58 8596.58 6035.6 4616.14 3594.2 2570.6 1628.04 827.6 112.86 376.4 1 2 3 4 5 6 7 8 9 10