EECS 110: Lec 6: Fractals and Trutles

Slides:



Advertisements
Similar presentations
ECS 15 if and random. Topic  Testing user input using if statements  Truth and falsehood in Python  Getting random numbers.
Advertisements

1 Many people debate basic questions of chance in games such as lotteries. The Monty Hall problem is a fun brain teaser that Marilyn vos Savant addressed.
Main task -write me a program
EECS 110: Lec 6: Fractals and Trutles Aleksandar Kuzmanovic Northwestern University
Cyriak: conceptually disruptive recursion… Baaa. Welcome to IST338… Be sure to watch your head!
CS 5 Today CS 5 alien on strike! Claremont residents report droplets of water falling down-ward from the sky: unexplained meteorological phenomenon causes.
Welcome to CS 5! Be sure to watch your head…. A recursive spiral …
IS 313 Tomorrow… IS 313 last week ? 9/20/09 - today: beyond recursion! 9/27/09 - next wk: web technologies, pt 2 Assignment reminders... Which door to.
General Programming Introduction to Computing Science and Programming I.
The not-so-subtle art of singling out the best (and worst) of anything… Computing with language Computing to the max You know this would make me hungry…
Programming Training kiddo Main Points: - Python Statements - Problems with selections.
B.A. (Mahayana Studies) Introduction to Computer Science November March Logo (Part 2) More complex procedures using parameters,
1 CSC 221: Computer Programming I Fall 2011 Fun with turtle graphics  turtle module  relative motion (setup, reset, left, right, forward, backward) 
Class 2 Introduction to turtle graphics
A new human-computer interface?
EECS 110: Lec 5: List Comprehensions Aleksandar Kuzmanovic Northwestern University
The building blocks of functional computing data, sequences conditionals recursion CS 121 today List Comprehensions map and applications.
EECS 110: Lec 6: Fractals and Trutles Aleksandar Kuzmanovic Northwestern University
EECS 110: Lec 12: Mutable Data Aleksandar Kuzmanovic Northwestern University
IS 313: Putting loops to work for you What's next? [ 1, 11, 21, 1211, , ? ] [ -35, -24, -13, -2, 9, 20, 31, ? ] [ 2, 22, 222, ? ] [ 26250, 5250,
EECS 110: Lec 4: Functions and Recursion Aleksandar Kuzmanovic Northwestern University
CS 121 Today Fractals and Turtles! The Koch Curve how random…
IS 313 Tomorrow… IS 313 Today? 9/16/09 - today: recursion and beyond! 9/23/09 - next wk: no meeting (DC) 9/30/09 - following wk: for & while Homework functions.
EECS 110 Recitation #3 Ning Xia Northwestern University.
1 Computer Science of Graphics and Games MONT 105S, Spring 2009 Session 4 Conditionals Turtles.
Loops ! We've seen variables change in-place before: [ x*6 for x in range(8) ] [ 0, 6, 12, 18, 24, 30, 36, 42 ] remember range ?
EECS 110: Lec 10: Definite Loops and User Input Aleksandar Kuzmanovic Northwestern University
Code Compression the benefits of looping... Today in CS 5 HW 4 - (3 problems) M/T sections W/Th sections due Sunday, 9/26 at midnight due Monday, 9/27.
EECS 110: Lec 7: Program Planning Aleksandar Kuzmanovic Northwestern University
EECS 110: Lec 9: Review for the Midterm Exam Aleksandar Kuzmanovic Northwestern University
Programming Training kiddo Main Points: - Python Statements - Problems with selections.
EECS 110: Lec 12: Mutable Data Aleksandar Kuzmanovic Northwestern University
EECS 110: Lec 7: Program Planning Aleksandar Kuzmanovic Northwestern University
CS 121 Today Fractals and Turtles! The Koch Curve how random…
Cyriak: conceptually disruptive recursion…
EECS 110: Lec 10: Definite Loops and User Input
Introduction to Computing Science and Programming I
EECS 110: Lec 12: Mutable Data
CS 5 Today hw2 due Monday… Lots of tutoring… Fractals and Turtles
EECS 110: Lec 9: Review for the Midterm Exam
Expressions.
EECS 110: Lec 5: List Comprehensions
Formatting Output.
Module 2: Investigation 1
EECS 110: Lec 5: List Comprehensions
General Form for a Conditional
EECS 110: Lec 7: Program Planning
CSc 110, Autumn 2016 Lecture 13: Random Numbers
We are removing the 4th part of hw2pr2 for now.
EECS 110: Lec 4: Functions and Recursion
Writing Functions( ) (Part 5)
The CS 5 Times “Zach and Geoff to be Replaced by
EECS 110: Lec 10: Definite Loops and User Input
Random numbers What does it mean for a number to be random?
Random numbers What does it mean for a number to be random?
Probability And Expected Value ————————————
Exercise (1) What does function chai draw? def chai(size):
Truth tables: Ways to organize results of Boolean expressions.
CISC101 Reminders Quiz 2 this week.
EECS 110: Lec 14: Classes and Objects
Truth tables: Ways to organize results of Boolean expressions.
EECS 110: Lec 4: Functions and Recursion
Probability, Games & Sentiment Analysis
A look at Python Programming Language 2018.
Probability And Expected Value ————————————
Marty the Robot.
Chapter 9 Using Decisions to
EECS 110: Lec 12: Mutable Data
Background for lab: the ord() function
Random numbers What does it mean for a number to be random?
Presentation transcript:

EECS 110: Lec 6: Fractals and Trutles Aleksandar Kuzmanovic Northwestern University http://networks.cs.northwestern.edu/EECS110-s17/

Midterm and Final Midterm: Final: Wednesday 4/26/2017 9:30am – 11:30am Pancoe Life Science Pavilion (PLSAUD) Final: Wednesday 5/31/2017

EECS 110 Today hw2 due Sunday evening… Fractals and Turtles! The Koch Curve

Quiz Write each of these functions concisely using list comprehensions… Name(s): Write input: e, any element L, any list or string Remember True == 1 and False == 0 def count(e,L): output: the # of times L contains e example: count('f', 'fluff') == 3 W are the winning numbers Write input: Y and W, two lists of lottery numbers (ints) Y are your numbers def lotto(Y,W): output: the # of matches between Y & W example: lotto([5,7,42,44],[3,5,7,44]) == 3 Extra! Write input: N, an int >= 2 output: the number of positive divisors of N def divs(N): example: divs(12) == 6 (1,2,3,4,6,12)

Quiz

Quiz count(e,L) LC = [x==e for x in L] return sum( LC )

Quiz lotto(Y,W) LC = [c in Y for c in W] return sum( LC )

Quiz divs(N) LC = [ N%c==0 for c in range(1,N+1)] return sum( LC )

Quiz count(e,L) lotto(Y,W) divs(N) LC = [x==e for x in L] return sum( LC ) lotto(Y,W) LC = [c in Y for c in W] return sum( LC ) divs(N) LC = [ N%c==0 for c in range(1,N+1)] return sum( LC )

return to recursion Composing functions into specific applications what applications? Creating general functions that will be useful everywhere (or almost…)

Numerical Integration 1 def recip(x): return 1.0/x 0.5 y = 1 x area 1 2 3 4 5 6 7 8 9 10 Numerical Integration Lab 2: Tuesday (yesterday) steps(low,hi,N) fsteps(recip,low,hi,N) finteg(f,low,hi,N)

N == 9 == total number of steps (rectangles) 1 def recip(x): return 1.0/x 0.5 y = 1 x area 1 2 3 4 5 6 7 8 9 10 1 0.5 1 2 3 4 5 6 7 8 9 10 low = 1.0 hi = 10.0 N == 9 == total number of steps (rectangles) steps(low,hi,N) fsteps(recip,low,hi,N) finteg(f,low,hi,N)

Numerical Integration def fracSteps(N): return [ x/float(N) for x in range(N) ] 1 41 fractional steps 42 42 42 def steps(low,hi,N): return [ low + (hi-low)*x for x in fracSteps(N) ] x values 1 6 10 10 15 7 7 7 def fsteps(f,low,hi,N): return [ f(x) for x in steps(low,hi,N) ] y values 10 16 def finteg(f,low,hi,N): return sum(fsteps(f,low,hi,N))*(hi-low)/float(N) 10 16 integral: heights width

When good programs go bad… def power(b, p): """ Returns b**p for p >= 0 """ if p == 0: return 1 else: return b*power(b, p)

print: Making programs talk to you! Debugging had to be discovered. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs. - Maurice Wilkes

When good programs go bad… def power(b, p): """ Returns b**p for p >= 0 """ print( "p is", p, "; b is", b ) if p == 0: return 1 else: return b*power(b, p)

Careful! print != return def power(b, p): """ Returns b**p for p >= 0 """ if p == 0: return 1 else: return b*power(b, p-1) def powerPrint(b, p): """ Returns(?) b**p for p >= 0 """ if p == 0: print 1 else: print b*powerPrint(b, p-1) Run this one in python Start with power(2, 4) Then do powerPrint(2, 0) – everything looks OK Now do powerPrint(2, 4) – it will crash, explain why and illustrate with: X = powerPrint(2, 0) It still prints 1, but you can show that x has no value.

for more explanation, try dir(random) or help(random) A random aside… import random for more explanation, try dir(random) or help(random) random.choice( L ) chooses 1 element from the list L random.choice( ['north', 'case', 'west'] ) How would you get a random int from 0 to 9? random.choice(range(10)) random.uniform(low,hi) chooses a random float from low to hi random.uniform(41.9,42.1) How likely is this to return 42 ?

A random function… from random import * def guess( hidden ): """ guesses the user's hidden # """ compguess = choice( range(100) ) if compguess == hidden: # at last! print( 'I got it!’ ) else: guess( hidden )

The final version from random import * import time def guessFinal( hidden ): """ guesses the user's hidden # """ compguess = choice( range(100) ) print( 'I choose', compguess ) time.sleep(0.05) if compguess == hidden: # at last! print( 'I got it!’ ) return 0 else: return 1 + guessFinal( hidden )

The two Monte Carlos Making random numbers work for you! Monte Carlo methods, Math/CS Monte Carlo casino, Monaco

Monte Carlo in action Suppose you roll two dice. What are the chances that you roll doubles? input is the total number of rolls def countDoubles( N ): """ inputs a # of dice rolls outputs the # of doubles """ if N == 0: return 0 # zero rolls, zero doubles… else: d1 = choice( [1,2,3,4,5,6] ) d2 = choice( range(1,7) ) if d1 != d2: return countDoubles( N-1 ) # not doubles return # doubles! 1+countDoubles(N-1) one roll of the dice what should the last line be?

Monte Carlo in action Suppose you roll two dice. What are the chances that you roll doubles? input is the total number of rolls def countDoubles( N ): """ inputs a # of dice rolls outputs the # of doubles """ if N == 0: return 0 # zero rolls, zero doubles… else: d1 = choice( [1,2,3,4,5,6] ) d2 = choice( range(1,7) ) if d1 != d2: return countDoubles( N-1 ) # not doubles return 1 + countDoubles( N-1 ) # doubles! one roll of the dice

Monty Hall Let’s make a deal ’63-’86 http://en.wikipedia.org/wiki/Monty_Hall_problem inspiring the “Monty Hall paradox”

Run it (randomly) 1000 times and see! Monte Carlo Monty Hall Suppose you always switch to the other door... What are the chances that you will win the car ? Run it (randomly) 1000 times and see!

Monte Carlo Monty Hall def MCMH( init, sors, N ): Your initial choice! 'switch' or 'stay' number of times to play def MCMH( init, sors, N ): """ plays the same "Let's make a deal" game, N times returns the number of times you win the car """ if N == 0: return 0 # don't play, can't win carDoor = choice([1,2,3]) # where is the car? if init == carDoor and sors == 'stay': result = 'Car!' elif init == carDoor and sors == 'switch': result = 'Spam.' elif init != carDoor and sors == 'switch': result = 'Car!' else: result = 'Spam.' print( 'You get the', result ) if result == 'Car!': return 1 + MCMH( init, sors, N-1 ) else: return 0 + MCMH( init, sors, N-1 )

An example closer to home Hw2 Pr2 Platt ... ... Dorms Michigan Lake S (W) 22 23 24 25 26 27 28 50 (E) An overworked NU student (S) leaves a pub after a “late-night” breakfast and, each moment, randomly stumbles toward Dorms (W) or toward Michigan Lake (E) Once the student arrives at the dorms or the Michigan Lake, the trip is complete. The program should then print the total number of steps taken. Write a program to model and analyze! this scenario...

An example closer to home Hw2 Pr2 Platt ... ... Dorm Michigan Lake S (W) 22 23 24 25 26 27 28 50 (E) An overworked NU student (S) leaves a pub after a “late-night” breakfast and, each moment, randomly stumbles toward Dorms (W) or toward Michigan Lake (E) Once the student arrives at the dorm or the Michigan Lake, the trip is complete. The program should then print the total number of steps taken. Write a program to model and analyze! this scenario... rs() rwPos(s, nsteps) rwSteps(s, low, hi) take a random step of +1 or -1 take nsteps random steps starting at s take random steps starting at s until you reach either low or hi

one of many applications for random walks… Gel electrophoresis one of many applications for random walks… uses a basic random-walk model with unequal step probabilities Used to separate proteins and nucleic acids (DNA) from a biological sample. Molecules with different properties travel different distances.

Monte Carlo Applications folding @ home (a) start configuration (b) end (c) 3d-model text on MC approaches to protein folding

A new human-computer interface? Python's Etch-a-Sketch from turtle import * reset() left(90) forward(50) right(90) backward(50) down() or up() color('green') width(5) done() and lots more! degrees! states if the pen draws or not A new human-computer interface? http://networks.cs.northwestern.edu/EECS110-s17/misc/TurtleDirections.htm for turtle help

Etch-a-Sketch ? No way this is real… except that it is ! www.gvetchedintime.com No way this is real… except that it is !

Recursive Graphics (1) Could we tri this with recursion? def tri(): there is no tri … (1) Could we tri this with recursion? def tri(): """ draws a polygon """ forward(100) left(120)

Recursive Graphics def tri(N): """ Plots a triangle """ if N == 0: there is no tri … (1) Could we tri this with recursion? def tri(): """ draws a polygon """ forward(100) left(120) def tri(N): """ Plots a triangle """ if N == 0: return else: forward(100) left(120) tri(N-1)

one possible result of rw(20) "Quiz" Name(s): Turtle Graphics (1) What does chai draw? Finish rwalk to draw a "stock-market-type" random path of nsteps steps. Use recursion! (2) from random import * def rw(nsteps): """ moving for nsteps steps, randomly 45 deg. left/up or right/down """ if nsteps == 0: return if choice(['left','right']) == 'left': else: # 'right' def chai(size): """ mystery! """ forward(size) left(90) forward(size/2.0) right(90) backward(size) one possible result of rw(20)

(1) What does chai draw? def chai(size): """ mystery! """ forward(size) left(90) forward(size/2.0) right(90) backward(size) Why are there two identical commands in a row?

one possible result of rw(20) (2) Finish rwalk to draw a "stock-market-type" random path of nsteps steps. from random import * def rw(nsteps): """ moving for nsteps steps, randomly 45 deg. left/up or right/down """ if nsteps == 0: return if choice(['left','right']) == 'left': left(45) forward(20) right(45) else: # 'right‘ return rw(nsteps-1) one possible result of rw(20) What if we didn't go back to the starting pose?

close-up of innermost part of the spiral… hw2pr3 spiral 81 72.9 90 close-up of innermost part of the spiral… spiral( 100, 90, 0.9 ) 100 spiral( initLength, angle, multiplier )

svTree( trunkLength, levels ) hw2pr3 svTree svTree( 100, 4 ) svTree( trunkLength, levels ) and more! (if you want)

Help! My turtle window froze! Your turtle window becomes unresponsive after your program runs. Type: >>> done() to unlock it (but then you have to close it)

The Koch curve snowflake( 100, 0 ) snowflake( 100, 1 )

Have fun! fill(1) color("blue") http://cs.northwestern.edu/~akuzma/classes/EECS110-s09/misc/TurtleDirections.htm fill(1) color("blue")

Have a great weekend! good luck with hw2…