4115 4112 4107 IST 338 Rules lems b
4/1/15!
4/1/12!
4/1/07!
IST 338 Rules ! lems b o r p o w T each two rules z=z 2+c John Conway Simple rules can yield complex results! HW 9 (lab + 1 problem) due Fri. 4/10 Rule #1: Don't follow this rule. Final projects: a look ahead… Three-in-a-row? Aliens rule at this…
(1 a) Lists are handled "by reference" "Reference" "Pointer" id 42, 000, 042 L L = [5, 42, 'hi'] 5 42 L[0] L[1] In CS, rules rule! s = 'hi' L[2] (1 b) Numbers and strings are handled "by value" 'hi' s
Reference vs. Value Python's two methods for handling data "Reference" "Pointer" id 42, 000, 042 L L = [5, 42, 'hi'] 5 42 L[0] L[1] 'hi' L[2] Lists are handled by reference: L really holds a memory address s = 'hi' x = 7 'hi' s 7 x Numeric data and strings are handled by value: imagine they hold the data
(1 a) Lists are handled "by reference" "Reference" "Pointer" id 42, 000, 042 L L = [5, 42, 'hi'] 5 42 L[0] L[1] In CS, rules rule! s = 'hi' s L[2] (1 b) Numbers and strings are handled "by value" (2) Inputs pass to functions "by copy" in main: fav = 7 f(fav) 7 fav 7 x The contents of the variable's "box" in memory are copied. def f(x): x is a copy of fav
Python functions: pass by copy def conform(fav) fav = 42 return fav def main() print " Welcome! " fav = 7 fav = conform(fav) print " My favorite # is", fav 7 fav
Python functions: pass by copy def conform(fav) 7 fav = 42 return fav copy of fav def main() print " Welcome! " "pass by copy" means the contents of fav are copied to fav = 7 fav = conform(fav) print " My favorite # is", fav But what if the underlined part were absent… ? 7 fav
Try it! Rules rule!? Just thought experim ents: Don't hand this in… Trace each f'n. What will main 1, main 2, and main 3 print? def conform 1(fav) fav = 42 return fav def conform 2(L) L = [42, 42] return L fav 7 fav L L L def main 1() fav = 7 conform 1(fav) print fav def conform 3(L) L[0] = 42 L[1] = 42 7 L[0] def main 2() L = [7, 11] conform 2(L) print L 11 L[1] L 7 L[0] def main 3() L = [7, 11] conform 3(L) print L Notice that there are NO assignment statements after these function calls! The return values aren't being used… 11 L[1]
Lists are Mutable You can change the contents of lists in functions that take those lists as input. - Lists are MUTABLE objects Those changes will be visible everywhere. Numbers, strings, etc. are IMMUTABLE – they can't be changed, only reassigned.
Differing approaches to rules … Engineers Physicists Mathematicians CS? diffe ews i v d l r o rent w …
"the rules" Engineers believe equations approximate reality; Safety margins! Grand Canyon Skywalk
Engineers believe equations approximate reality; Physicists believe reality approximates equations… Image forensics' verdict: Fake! http: //www. youtube. com/watch? feature=player_embedded&v=Wba. H 52 JI 3 So http: //www. fourandsix. com/blog/2011/8/29/seriously-amazing-beer-pong-shots. html Not a parabola, so not a real shot!
Engineers believe equations approximate reality; Physicists believe reality approximates equations… Mathematicians don't care either way! A solid sphere can be split into 5 parts and rigidly reassembled into two spheres the same size as the original Banach-Tarski paradox Banach-Tarski XKCD the parts are "mist"
Engineers believe equations approximate reality; Physicists believe reality approximates equations… Mathematicians don't care either way! In CS? Don't like reality? Build a new one! why settle for gears, when you could have fractal gears?
Engineers believe equations approximate reality; Physicists believe reality approximates equations… Mathematics reasons about structural rules… … and CS reasons about procedural ones. Axioms Data Definitions proofs for lists while Data variables arithmetic operations if/else programs Insights, tools, mathematical truths Insights, tools, algorithms math worldview CS worldview
2 D data!
Lists ~ 2 D data A = [ 42, 75, 70 ] 42 list A int 75 int 70 int 1 D lists are familiar – but lists can hold ANY kind of data – including lists!
Lists ~ 2 D data A = [ [1, 2, 3, 4], [5, 6], [7, 8, 9, 10, 11] ] list A[0] list A[1] list A[2] Where's 3? 1 A[0][0] 5 A[1][0] 7 A[2][0] len(A[0]) 2 4 3 A[0][1] A[0][3] ? 6 A[1][1] 8 A[2][1] 9 A[2][2] len(A) 10 A[2][3] 11 A[2][4] Replace 10 with 42.
Rectangular 2 D data A = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 1, 2] ] list A[0] list A[1] list A[2] 1 2 3 4 5 6 7 8 9 0 1 2 A[0][0] A[2][3] To try… What is A[1][2]? What does each component of A[1][2] mean ? Using len, how many rows does A have, in general ? Using len, how many columns does A have, in general ?
Try it… def mystery(A): """ what happens to A ? """ NROWS = len(A) NCOLS = len(A[0]) for r in range( 0, NROWS ): for c in range( 0, NCOLS ): if A[r][c] == 4: A[r][c] = 1 else: A[r][c] += 1 A = [ [4, 2, 2, 2], [2, 2, 4, 4], [2, 4, 4, 2] ] A row 0 row 1 row 2 Before 4 2 2 4 2 4 2 col 0 col 1 col 2 col 3 Starting with the 2 d array A shown above, write the values in A after running the code? Write in the resulting values in A: A After – with the code as written…
hw 9 pr 2 def inarow_2 east(A): """ what happens to A ? """ NROWS = len(A) NCOLS = len(A[0]) for r in range( 0, NROWS ): for c in range( 0, NCOLS ): A = [ [4, 2, 2, 2], [2, 2, 4, 4], [2, 4, 4, 2] ] A row 0 row 1 row 2 Challenge: How would you change the code above to produce a True where the original value is equal to its neighbor to the right? ! (False, if no neighbor or a different neighbor. ) Before 4 2 2 4 2 4 2 col 0 col 1 col 2 col 3 F T F T T T F F
First, try it by eye… … then, on hw 9 pr 2, by Python! col 0 col 1 col 2 col 3 col 4 A = [ [' ', 'X', 'O', 'O'], ['X', 'O'], [' ', 'X', 'O'], ['X', 'O', 'X'] ] row 0 row 1 row 2 row 3 doesn't the data und ro wrap a checker start row start col Lo. L inarow_3 east('X', 1, 0, A)
First, try it by eye… … then, on hw 9 pr 2, by Python! col 0 col 1 col 2 col 3 col 4 A = [ [' ', 'X', 'O', 'O'], ['X', 'O'], [' ', 'X', 'O'], ['X', 'O', 'X'] ] row 0 row 1 row 2 row 3 doesn't the data und ro wrap a checker start row start col Lo. L inarow_3 east('X', 1, 0, A) inarow_3 south('O', 0, 4, A) inarow_3 southeast('X', 2, 3, A) inarow_3 northeast('X', 3, 1, A) True
hw 9 pr 1 (lab): Conway's Game of Life Geometer @ Princeton 1995 ? 20˚ John Conway 10˚ 60˚ 70˚ Solution: www. cs. yale. edu/homes/toyama/tri/sol. html simple rules ~ surprising behavior 1970 (no trig)
Lab Problem: Conway's Game of Life Grid World Evolutionary rules red cells are "alive" • Everything depends on a cell's eight neighbors • Exactly 3 neighbors give birth to a new, live cell. s e • Exactly 2 or 3 neighbors l u r 3 y l keep an existing Oncell alive. white cells are empty • Any other # of neighbors and the central cell dies…
Lab Problem: Conway's Game of Life Grid World Evolutionary rules red cells are "alive" • Everything depends on a cell's eight neighbors • Exactly 3 neighbors give birth to a new, live cell. • Exactly 2 or 3 neighbors keep an existing cell alive. white cells are empty • Any other # of neighbors and the central cell dies…
Lab Problem: Conway's Game of Life Grid World Evolutionary rules red cells are "alive" • Everything depends on a cell's eight neighbors • Exactly 3 neighbors give birth to a new, live cell. • Exactly 2 or 3 neighbors keep an existing cell alive. white cells are empty • Any other # of neighbors and the central cell dies…
Lab Problem: Conway's Game of Life Grid World Evolutionary rules red cells are alive • Everything depends on a cell's eight neighbors • Exactly 3 neighbors give birth to a new, live cell. xt? • Exactly 2 or s 3 n neighbors e ' t a h keep an Wexisting cell alive. white cells are empty • Any other # of neighbors and the central cell dies…
Lab Problem: Creating life next_life_generation( A ) For each cell… • 3 live neighbors – life! • 2 live neighbors – same ? • 0, 1, 4, 5, 6, 7, or 8 live neighbors – death • computed all at once, not cellby-cell, so the ? at left does NOT come to life! http: //www. math. com/students/wonders/life. html
Lab Problem: Creating life next_life_generation( A ) old generation is the input, A 0 1 2 3 4 returns the next generation 0 5 0 0 1 1 2 2 3 3 4 4 5 5 1 2 3 4 5 ?
Lab Problem: Creating life Stable configurations: "rocks" Periodic "plants" period 2 period 3 Self-propagating "animals" glider
Lab Problem: Creating life Many life configurations expand forever… "Gosper glider gun" "glider" What is the largest amount of the life universe that can be filled with cells? How sophisticated can Life-structures get? www. ibiblio. org/lifepatterns/
Ex Cr: the Mandelbrot Set Consider an update rule for all complex numbers c z 0 = 0 zn+1 = zn 2 + c
Python's complex #s Nothing's too complex for Python! >>> c = 3 + 4 j >>> 3. 0 c. real >>> 4. 0 c. imag >>> 5. 0 abs(c)
Mandelbrot Definition z 0 = 0 Consider an update rule for all complex numbers c zn+1 = zn 2 + c Small values of c keep the sequence near the origin, 0+0 j. z 3 c z 1 z 0 z 2 z 4 z 5 some "stick around": oscillate or converge Imaginary axis Real axis
Mandelbrot Definition z 0 = 0 Consider an update rule for all complex numbers c Small values of c keep the sequence near the origin, 0+0 j. zn+1 = zn 2 + c c's h c i h W d? n u o r a Benoit B. stick c Mandelbrot 1924 – 2010 Real axis c Imaginary axis Other values of c make the sequence head to infinity.
hw 9 pr 3: the Mandelbrot Set Consider an update rule for all complex numbers c z 0 = 0 zn+1 = zn 2 + c s ' c e m so d n u o r a k c i t s
hw 9 pr 3: the Mandelbrot Set Consider an update rule for all complex numbers c z 0 = 0 zn+1 = zn 2 + c s ' c r e oth e g r e div
hw 9 pr 3 Mandelbrot Set ~ points that stick around mid 7 0 resolu 's tion The shaded area are points that do not diverge for z = z**2 + c
Higher-resolution M. Set -2 + 1 j connected 1 + 1 j finite area perimeter! -2 - 1 j 1 - 1 j The black pixels are points that do not diverge for z = z**2 + c
Chaos? Complex things always consisted of simple parts…
Before the M. Set, complex things were made of simple parts: Chaos! This was a "naturally occurring" object where zooming uncovers more detail, not less: not self-similar but quasi-self-similar http: //www. youtube. com/watch? v=0 j. Gaio 87 u 3 A
The black pixels are points that do not diverge for z = z**2 + c What are these colors?
The black pixels are points that do not diverge for z = z**2 + c What are these colors? escape velocities
Atlas of the M. Set
In the Seahorse Valley….
Happy Mandelbrotting! www. cs. hmc. edu/~jgrasel/projects http: //www. youtube. com/watch? v=0 j. Gaio 87 u 3 A
Tis the season for final projects… Today is about the our final projects + it's a sales pitch for the three possible options: I've got my eyes on some of these projects! v. Pool Text. ID Picobot Eye'll bet !
Final projects open-ended Final CS assignment comprehensive same projects for black/gold three choices… Eye, eye! Working solo or in a pair is OK Pairs need to work together - in the same place - and they need to share the work equally. . .
VPool n ho t y P V … Project options… Desi gn-y o (by 4 ur ow /17… n ) Text. ID v rko a M … See the IST 338 Final Projects page… Picobot! r u o F …C
VPool Pre-planned possibilities n ho t y P V … Text. ID v rko a M … Picobot! at least to think about… r u o F …C
The Picobot project Big ideas: (1) Implement Picobot in Python (2) Train Python to write successful Picobot programs! talk about going full circle. . .
Picobot returns! es r u t c u r a st t a d t a l in Wh u f p l e h e b t h g i ot? b m o c i P ng i t n e m imple
Picobot's classes class Program: What in Python could most usefully hold all of these rules? on h t y P ry a n o i What type should dict self. rules be? key self. rules[ (1, "NExx") ] 0 0 0 0 0 1 1 1 1 1 xxxx Nxxx Nx. Wx xx. WS xxx. S x. Exx NExx -> -> -> -> -> value = ("W", 0) N W S S E E N N W W S W 0 0 0 0 1 1 1 1 1 0
Picobot's classes class World: What in Python could most usefully hold the environment? What type should self. room be? +++++++++++++ +ooooo. Pooooooooo+ +o o o+ +o o o+ +o o+ +o o+ +o o+ +oooooooooooo+ +++++++++++++ Wall: Visited: Picobot: + o P
Picobot's classes class World: What in Python could most usefully hold the environment? What type should self. room be? ve ' e w t as eek! s u j a t w a s d i d h t 2 ng i s u been +++++++++++++ +ooooo. Pooooooooo+ +o o o+ +o o o+ +o o+ +o o+ +o o+ +oooooooooooo+ +++++++++++++ Wall: Visited: Picobot: + o P
The Picobot project Current State: 1 Current Rule: 1 N*W* -> X 2 +++++ +o++o+o+++ +oooooo ++ ++++o++ + +oooo+++++o + +oooo+++ + ++++o+++++ +Pooo + +++++ Picobot started here… and is now here… First build an ASCII simulation
Program evolution An example of genetic algorithms, used for optimizing hard-to-describe functions. program p 1 program p 2 Start with a population of, say, ~200 random Picobot programs…
Program evolution An example of genetic algorithms, used for optimizing hard-to-describe functions. program p 1 fitness = 0. 03 program p 2 fitness = 0. 05 Then, evaluate the fitness of all of those programs Evaluate? How? ?
program p 1 fitness = 0. 03 program p 2 fitness = 0. 05 mate + mutate the fittest rulesets to create a new generation of ~200 programs… program c 1 fitness = 0. 19
Repeat this "survival of the fittest" process for many generations… … and by the end, your Python code should have evolved a much more capable Picobot program! fitness = 0. 90
Project options. . . VPool Text. ID Picobot!
the Text. ID project Though Robin Ellacott’s twenty-five years of life had seen their moments of drama and incident, she had never before woken up in the certain knowledge that she would remember the coming day for as long as she lived. First paragraph of The Cuckoo's Calling by R. Galbraith
kottke. org/13/08/how-jk-rowling-was-found-to-be-robert-galbraith
the Text. ID project Big ideas: (1) Build lexical models of bodies of text… (2) Create a similarity score that defines Rowlingness vs. Shakepearity NYTimes-iness WSJournalicity vs. Big Bang Theory? vs. Arrested Development your own choice of two comparisons…
Text. ID model word-frequencies class Text. Model WS: { "love": 50, "spell": 8, … } JKR: { "love": 11, "spell": 277, … } stem-frequencies WS: { "lov": 612, "spell": 9, … } word-length-freq. 's / sentence-length-freq. 's WS: { 4: 7042, 5: 6203, … } JKR: { "lov": 98, "spell": 306, … } JKR: { 4: 980, 5: 42005, … } all will be Python dictionaries…
Processing steps: one idea Split the text into words… This looks familiar. . . Clean the words … Remove all non-alphabetic characters Find sentence lengths using punctuation Create dictionaries of the words and their lengths Stem the words Create a dictionary of word stems You're ready to match against another model!
Stemming stem( "party" ) "parti" stem( "parties" ) "parti" An algorithm that outputs the root of the input word. stem( "love" ) "lov" stem( "loving" ) "lov" Or tries to output the root! these don't have to be words, just stems…
Stemming stem( "party" ) "parti" stem( "parties" ) "parti" g n i m m e t S r e t r o P e h An algorithm that outputs the t e Us root of the input word. ! m h t i r o g Al stem( "love" ) "lov" stem( "loving" ) "lov" Or tries to output the root! these don't have to be words, just stems…
Model matching Suppose we have two dictionaries: WS: { "love": 50, "spell": 8, "thou": 42 } "potter" is not here. JKR: { "love": 25, "spell": 275, "potter": 700 } New: { "love": 3, "thou": 1, "potter": 2, "spam": 4 } How could we give a match score for this New dictionary against each one above? "thou" is not here.
's multiply each word ey probability as if th ent were all independ Naïve Bayes classification WS: { "love": 50, "spell": 8, "thou": 42 } "potter" is not here. JKR: { "love": 25, "spell": 275, "potter": 700 } score vs. WS "thou" is not here. score vs. JKR 50 100 42 100 love tho u 0 100 25 1000 ter pot love score = 0 New: { "love": 3, "thou": 1, "potter": 2, "spam": 4 } 25 0 700 1000 love u tho ter pot score = 0 s? problem s? solution
's multiply each word ey probability as if th ent were all independ Naïve Bayes classification WS: { "love": 50, "spell": 8, "thou": 42 } "potter" is not here. t i w s score vs. WS o r e z e c a l p Re 50 100 42 100 love tho u JKR: { "love": 25, "spell": 275, "potter": 700 } … s e u l a v l l a m s h score vs. JKR 1 100 25 1000 ter pot love score = 0. 0525 "thou" is not here. 25 1 700 1000 love u tho ter pot score = 0. 000011 New: { "love": 3, "thou": 1, "potter": 2, "spam": 4 } s? problem s? solution
Naïve Bayes classification done!
Naïve Bayes classification as Don' ul m r o f e s e h t e t tak ly… s u o i r too se done!
Project options. . . VPool Text. ID Picobot!
3 d graphics-based game using VPython v. Pool I'll take your cue. . . Let's play! not really very constrained at all! A few constraints • physically interacting "pool balls" • must detect some collisions and model their results on the motion • allow the user to direct 1+ objects • needs a game goal + be winnable!
The v. Pool project VPython was designed to make 3 d physics simulations simpler to program Funky Physics is OK… ! Collisions with walls should be handled. . . Collisions with other pool balls should be handled. . . You need pockets – or some other game objective A few examples to get you thinking… So far, VPython has eventually worked for everyone. . .
VPool n … ho t y P V Project options… Desi gn-y o (by 4 ur ow /17… n ) Text. ID v rko a M … Picobot! r u o F …C
Project details…
Enjoy the projects! An unusual variation on VPool … we certainly do!
Extra: Text Clouds text cloud Summary of the words in a body of text, sized according to their frequency. this doesn't look nearly colorful enough… demos… ?
Text-cloud history http: //chir. ag/phernalia/preztags/
Collisions and velocities ball. vel = vector(1, 0, 1) +z x = 10 while True: ball. pos += dt*ball. vel if ball. pos. x > 10: ball. vel. x ball. pos. x At least some of the game is about detecting collisions and changing velocities +x What's the black line doing? How to bounce? What else to do?
"Spherical" collisions Zeroth approximation: Stop q. Make r. vel = q. vel. r q q. vel
"Spherical" collisions Zeroth approximation: Stop q. Make r. vel = q. vel. d r First approximation: q Stop q. vel Compute d = r. pos – q. pos Make r. vel = d
"Spherical" collisions Zeroth approximation: Stop q. d Make r. vel = q. vel. d r First approximation: q Stop q. vel Compute d = r. pos – q. pos Make r. vel = d Second approximation: Same as first, but Make q. vel = d , at 90 from d
v. Pool – physics? http: //en. wikipedia. org/wiki/Elastic_collision
v. Pool – physics? equations below. . . http: //en. wikipedia. org/wiki/Elastic_collision
other VPython examples tictac. py – a 3 d game of tic-tac-toe material_test. py – lots of materials texture_and _lighting. py – fancier textures, opacity and a pendulum example boxlighttest. py – very short + simple rotation and lighting example
What's due? Wed. 5/7 Wed. 5/14 • The "milestone" • The "final" • project-specific progress ~ really to ensure everyone's gotten started! • A zip file with everything to run your final project + a. txt file describing how! Nice milestone! It’s actually a kilometer stone.
Stemming getting to the root of the problem… Try some of these!!! def stem( w ): if w[-3: ] == 'ies': return w[: -2] elif w[-3: ] == 'ing' and w[-4: -3] == w[-5: -4]: return w[: -4] elif This works for parties -> parti it fails for What's this doing? What's an example where it works? What's an example where it fails? Write a rule to handle plurals. . . (1) What is a case where it will fail? (2) How could you fix that case? Choose any other stemming rule and implement it here!
Stemming getting to the root of the problem… Name(s): __________ def stem( w ): if w[-3: ] == 'ies': return w[: -2] elif w[-3: ] == 'ing' and w[-4: -3] == w[-5: -4]: return w[: -4] elif This works for parties -> parti it fails for What's this doing? What's an example where it works? What's an example where it fails? Write a rule to handle plurals. . . (1) What is a case where it will fail? (2) How could you fix that case? Choose any other stemming rule and implement it here!
Quiz Rules rule!? Try this on the back page first… Trace each f'n. What will main 1, main 2, and main 3 print? def conform 1(fav) fav = 42 return fav def conform 2(L) L = [42, 42] return L def conform 3(L) L[0] = 42 L[1] = 42 L 7 fav L def main 1() fav = 7 conform 1(fav) print fav L 7 L[0] def main 2() L = [7, 11] conform 2(L) print L 11 L[1] L 7 L[0] def main 3() L = [7, 11] conform 3(L) print L Notice that there are NO assignment statements after these function calls! The return values aren't being used… 11 L[1]
Part 2 A before Write a method that adds five times the values in row #1 into row #2. row 0 row 1 row 2 The values in row 1 should not change row 0 row 1 Only row 2's values change. row 2 0. 00 3. 00 10. 00 1. 00 0. 50 20. 00 0. 50 30. 00 1. 00 3. 00 27. 00 0. 00 3. 00 25. 00 1. 00 0. 50 22. 50 0. 00 0. 50 32. 50 1. 00 3. 00 42. 00 A after def add 5 of. Row 1 Into. Row 2( A ): for ____ in range( ): += You need only one line in the loop! What if 5, 1, and 2 were the variables: m, s, and d?
hw 9 pr 2: 2 D data Menu (1) Enter the size and values of an array (2) Print the array (3) Multiply an array row by a constant (4) Add one row into another (5) Add a multiple of one row to another (6) Solve! Functions print. Menu enter. Values print mult. Row add. Row. SInto. Row. D (9) Quit add. Mof. Row. SInto. Row. D Which choice would you like? solve S ~ source row index D ~ destination row index M ~ a multiplier
2. 00 -3. 00 1. 00 3. 00 -1. 00 -9. 00 -1. 00 2. 00 4. 00 -8. 00 42. 00 56. 00 First: fix A[0][0] What row operation can we perform to make A[0][0], the upper-left entry, equal to 1. 0 ? Solve 1. 00 0. 00 Get 1's on the diagonal Get 0's elsewhere 0. 00 1. 00 5. 00 25. 00 Goal
2. 00 -3. 00 1. 00 3. 00 -1. 00 -9. 00 -1. 00 2. 00 4. 00 -8. 00 42. 00 56. 00 1. 00 -3. 00 1. 50 -1. 00 -9. 00 -0. 50 2. 00 4. 00 -4. 00 42. 00 56. 00 Solve 1. 00 0. 00 First: fix A[0][0] fixed, by … multiplying Row 0 by 0. 5 Get 1's on the diagonal Get 0's elsewhere 0. 00 1. 00 5. 00 25. 00 Goal
Go one column at a time 1. 00 -3. 00 1. 50 -1. 00 -9. 00 -0. 50 2. 00 4. 00 -4. 00 42. 00 56. 00 multiply Row 0 by 0. 5 1. 00 0. 00 1. 50 3. 50 -10. 50 -0. 50 4. 50 -4. 00 30. 00 44. 00 add 3 times Row 0 to Row 1 add -1 times Row 0 to Row 2 1. 00 0. 00 -0. 71 0. 14 6. 00 -16. 85 30. 00 150. 00 multiply Row 1 by 1/3. 5 add a multiple of Row 1 to Row 0 add a multiple of Row 1 to Row 2 1. 00 0. 00 1. 00 5. 00 25. 00 same for other columns as far as possible. . .
Gaussian Elimination Goal: to find x, y, and z: 2 x -3 x 1 x + + + 3 y -1 y -9 y + + + Aargh! -1 z 2 z 4 z = = = -8 42 56
Gaussian Elimination Goal: to find x, y, and z: 2 x -3 x 1 x + + + 3 y -1 y -9 y + + + -1 z 2 z 4 z = = = -8 42 56 but some sets of equations are easier than others! 1 x 0 x 0 x + + + 0 y 1 y 0 y + + + 0 z 0 z 1 z = = = 1 5 25 I like this one!
Gauss's idea Goal: to find x, y, and z: 2 x -3 x 1 x + + + until it looks like: + + + -1 z 2 z 4 z = = = -8 42 56 multiply any row by a constant Use two rules: 1 x 0 x 0 x 3 y -1 y -9 y nonzero add a multiple of any row to another + + + 0 y 1 y 0 y + + + 0 z 0 z 1 z = = = 1 5 25 les u r e Thes hange ! 't c don lutions o the s
hw 9 pr 2: 2 D data Menu (1) Enter the size and values of an array (2) Print the array (3) Multiply an array row by a constant (4) Add one row into another (5) Add a multiple of one row to another (6) Solve! Functions print. Menu enter. Values print mult. Row add. Row. SInto. Row. D (9) Quit add. Mof. Row. SInto. Row. D Which choice would you like? solve S ~ source row index Demo… D ~ destination row index M ~ a multiplier
2 D data! Note that 2 x -3 x 1 x + + + 3 y -1 y -9 y + + + -1 z 2 z 4 z = = = -8 42 56 is really just the 2 D matrix: 2 -3 1 3 -1 -9 -1 2 4 -8 42 56 …the variables aren't needed at all!
The 5 C Hackathon is two weeks away and if possible I'd like to make an announcement in your two intro CS classes at the start of class Tuesday or later next week. In addition to the hackathon, we're holding an informal hack week series of tutorials that is designed to get beginners excited about CS and to introduce them to web programming! Thanks, Joe (jnewbry 14@students. claremontmckenna. edu)
Nathan F. + Nicole A. 42 darts
Watch out! How could we create this rectangular array of 0 s? [[0, 0, 0], [0, 0, 0]] A = 3*[ 5*[0] ] or A = 5*[ 3*[0] ]
Watch out! A = 3*[ 5*[0] ] list A inner = 5*[0] A = 3*[inner] list inner "shallow copy" copies the list reference, not the list data Inner-esting!
A 4 B C 6 5 D 7 E 8 next_life_generation( A ) returns new generation or "array" old generation or "array" 0 1 2 3 4 0 5 0 0 1 1 2 2 3 3 4 4 5 5 1 2 3 4 5 How many will there be?
Lab Problem: Creating life next_life_generation( A ) returns new generation or "array" old generation or "array" 0 0 1 1 2 3 4 0 5 0 42 darts! 1 2 2 3 3 4 4 5 5 1 2 3 4 5
Rectangular arrays list A[0] A[1][2] = 42 A[0][0] list A[1] list A[2][3] What does each component of A[1][2] mean ? How many rows does A have, in general ? How many columns does A have, in general ?
Quiz A = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ] Starting with the 2 d array A shown here, what are the values in A after running this code? def mystery(A): """ what happens to A ? """ NUM_ROWS = len(A) NUM_COLS = len(A[0]) A row 0 row 1 row 2 for row in range( 0, NUM_ROWS ): for col in range( 0, NUM_COLS ): if row == col: A[row][col] = 42 else: A[row][col] += 1 Before 1 5 9 2 6 10 3 7 11 col 0 col 1 col 2 A 4 8 12 col 3 After What are the resulting values in A?
Quiz, part 2 Write a method that adds five times the values in row #1 into the values in row #2. You may assume that A has at least three rows! five of row 1 will be added to row 2 The values in row 1 should not change Only row 2's values change. A row 0 row 1 row 2 before 0. 00 3. 00 10. 00 1. 00 0. 50 20. 00 0. 50 30. 00 1. 00 3. 00 27. 00 0. 00 3. 00 25. 00 1. 00 0. 50 22. 50 0. 00 0. 50 32. 50 1. 00 3. 00 42. 00 A def add 5 of. Row 1 Into. Row 2( A ): for ____ in range( += Extra! How could you make the multipier, the source row number, and the destination row number into inputs to this function – and then use those inputs? ): after
2. 00 -3. 00 1. 00 3. 00 -1. 00 -9. 00 -1. 00 2. 00 4. 00 -8. 00 42. 00 56. 00 1. 00 -3. 00 1. 50 -1. 00 -9. 00 -0. 50 2. 00 4. 00 -4. 00 42. 00 56. 00 GOAL: to get this side to look like the identity matrix. ORIGINAL: fix A[0][0] by … multiplying Row 0 by 0. 5 RESULT: this column will be our solution! Which term should we fix next !? !
Gaussian Elimination 2 p -3 p 1 p Goal: + + + 3 n -1 n -9 n Find p, n, q + + + -1 q 2 q 4 q = = = -8. 00 42. 00 56. 00 • get 1 s along the diagonal • get 0 s elsewhere on the left Wh at ru les c with an w out mea chang e us e ning equ of the atio ns? se
Gaussian Elimination 2 p -3 p 1 p Goal: 1 p 0 p 0 p + + + 3 n -1 n -9 n + + + 0 n 1 n 0 n = = = -8. 00 42. 00 56. 00 • get 1 s along the diagonal • get 0 s elsewhere on the left Find p, n, q + + + -1 q 2 q 4 q + + + 0 q 0 q 1 q = = = 1. 00 5. 00 25. 00 Using only row operations (our methods) ! Just the array is necessary ! We can get rid of the variables. . . where to start?
Gaussian Elimination Goal: to find x, y, and z: 2 x -3 x 1 x Goal: Find + + + 3 y -1 y -9 y p, n, q + + + -1 z 2 z 4 z = = = -8. 00 42. 00 56. 00 • get 1 s along the diagonal • get 0 s elsewhere on the left Wh at ru les c with an w out mea chang e us e ning equ of the atio ns? se
Gaussian Elimination 2 p -3 p 1 p Goal: 1 p 0 p 0 p + + + 3 n -1 n -9 n + + + 0 n 1 n 0 n = = = -8. 00 42. 00 56. 00 • get 1 s along the diagonal • get 0 s elsewhere on the left Find p, n, q + + + -1 q 2 q 4 q + + + 0 q 0 q 1 q = = = 1. 00 5. 00 25. 00 Using only row operations (our methods) ! Just the array is necessary ! We can get rid of the variables. . . where to start?
Lists ~ flexibility Lists can hold ANY type of data A = [ 42, 75, 70 ] 42 list A they don't have to be horizontal It looks vertical to me! int 75 int 70 int
Lists' flexibility Lists can hold ANY type of data A = [ 42, 75, 70 ] 42 list A We can equally well imagine them as vertical structures. int 42 list A int 75 int 70 int or diagonal. . . 75 int 70 int
Lists' flexibility Lists can hold ANY type of data 42. 0 list A double 42 list A int “O” list A String 75. 0 double 7 int “hi” String 70. 0 double -11 int “O! String ”
2 d lists or arrays Lists can hold ANY type of data -- including lists ! A = [ [1, 2, 3, 4], [5, 6], [7, 8, 9, 10, 11] ] list A
2 d arrays Lists can hold ANY type of data -- including lists ! A = [ [1, 2, 3, 4], [5, 6], [7, 8, 9, 10, 11] ] list A[0] list A[1] list A[2]
Jagged arrays Lists can hold ANY type of data -- including lists ! A = [ [1, 2, 3, 4], [5, 6], [7, 8, 9, 10, 11] ] list A[0] list A[1] list A[2] Rows within 2 d arrays need not be the same length…
No "jagged" arrays for us… at least not in hw 9 A = [ [1, 2, 3, 4], [5, 6], [7, 8, 9, 10, 11] ] e b s y a r r a r u o y ! l d l e a n y g i a l a M y r o m me list A[0] list A[1] list A[2] Rows within 2 d arrays need not be the same length…
Rectangular arrays list A[0] list A[1] list A[2] A = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 1, 2] ] 1 2 3 4 5 6 7 8 9 0 1 2 A[0][0] A[2][3] To try… Set A[1][2] = 42 What does each component of A[1][2] mean ? How many rows does A have, in general ? How many columns does A have, in general ?
Quiz Rules rule!? def conform 1(fav) fav = 42 return fav Name(s) _______________ def conform 2(faves) faves = [42, 42] return faves def conform 3(faves) faves[0] = 42 faves[1] = 42 fav faves def main 1() fav = 7 conform 1(fav) print "Fave: ", fav def main 2() faves = [7, 11] conform 2(faves) print "Faves: ", faves def main 3() faves = [7, 11] conform 3(faves) print "Faves: ", faves What will main 1, main 2, and main 3 end up printing?
Sizing up arrays… How could we create this rectangular array of 0 s? ! s rk A = 3*[ 5*[0] ] or HE T I E N o w E sts e li s u eca b A = 5*[ 3*[0] ] N [[0, 0, 0], O R ce ren ! e are d dle n a h ref by [0, 0, 0], [0, 0, 0]]
Safely creating arrays… def create. One. Row( width ): """ does just that """ row = [] # start with nothing for col in range( width ): row = row + [0] # loop and add! return row adding lists with lists! So, how would you create a list of rows!?
Safely creating arrays… def create 2 d. Array( width, height ): """ does just that """ A = [] # start with nothing for row in range( height ): row = create. One. Row( width ) A = A + [row] return A the same approach as before; now, adding lists of rows with lists of rows!
hw 9 pr 2: 2 D data Menu (1) Enter the size and values of an array (2) Print the array (3) Multiply an array row by a constant (4) Add one row into another (5) Add a multiple of one row to another (6) Solve! Functions print. Menu enter. Values print mult. Row add. Row. SInto. Row. D (9) Quit add. Mof. Row. SInto. Row. D Which choice would you like? solve S ~ source row index D ~ destination row index M ~ a multiplier
Engineers believe equations approximate reality; Physicists believe reality approximates equations… Mathematics reasons about structural rules… … and CS reasons about procedural ones. (without using trig) Creating structure from a few simple facts. . . ? Axioms Definitions 20˚ Proof 60˚ 10˚ 70˚ Solution and proof at http: //www. cs. yale. edu/homes/toyama/tri/sol. htmll
A John Conway's Challenge…. D ? E 20˚ 10˚ 60˚ 70˚ C B (without using trig) Solution and proof at cs-www. cs. yale. edu/homes/toyama/tri/sol. html
CS 5 Today Rules: emphasize the elegance of 2 interacting or rules… s s u Ga en? e Carl Gauss s o e o w h o c l • Midterm e Hal • 2 exam rules: data by ref. vs. value: lists vs. yononlyr show Coming up in CS 5: An way fo Con in-class on Thu. ints 11/8 • then, quiz • HW 9 (lab + 1 prob. ) • then, advantage of ref. == lists' flexibility due Monday, 11/12 the at midnight • 2 rules: multiply by non-zero or add a multiple to another • 2 rules: coming to life, staying alive This week's I give you all the credit! credits: John Conway Lecture 17 Today's honorees: mathematicians…
- Slides: 139