SlideShare a Scribd company logo
1 of 36
Class 17:
Golden
Sneezewort



             cs1120 Fall 2011
             David Evans
             30 September 2011
Plan
Generalizing Loops

Introducing Cost
  Book: Chapter 7 and 8
     (okay to read after Exam 1)
  Not covered on Exam 1



                                   2
Recap/Wake-up: A General Loop
(define (loop index result test update proc)




                                               3
General Loop with Result

(define (loop index result test update proc)
 (if (test index)
     (loop (update index)
            (proc index result)
            test update proc)
     result))


                                               4
Using Loop
                           (define (loop index result test update proc)
                            (if (test index)
                                (loop (update index)
                                    (proc index result)
                                    test update proc)
                                result))

(define (gauss-sum n)
  (loop 1 0 (lambda (i) (<= i n))
            (lambda (i) (+ i 1))
            (lambda (i res) (+ res i))))



                                                                          5
(define (loop index result test update proc)
                         (if (test index)
                             (loop (update index)
                                 (proc index result)
                                 test update proc)
                             result))

(define (factorial n)




                                                                       6
(define (loop index result test update proc)
                           (if (test index)
                               (loop (update index)
                                   (proc index result)
                                   test update proc)
                               result))



(define (list-length p)




                                                                         7
(define (loop index result test update proc)
                                  (if (test index)
                                      (loop (update index)
                                          (proc index result)
                                          test update proc)
                                      result))

(define (list-accumulate f base p)
  (if (null? p) base
      (f (car p) (list-accumulate f base (cdr p))))




                                                                                8
(define (loop index result test update proc)
                                  (if (test index)
                                      (loop (update index)
                                          (proc index result)
                                          test update proc)
                                      result))

(define (list-accumulate f base p)
  (if (null? p) base
      (f (car p) (list-accumulate f base (cdr p))))


(define (list-accumulate f base p)
 (loop p base not-null? cdr (lambda (p res) (f (car p) res))))




                                                                                9
Challenge Problem

Define an efficient edit-distance
procedure (as defined in PS2) using
loop (without using memoization).




                                      10
Sneezewort!




              11
Sneezewort Growth




First Time Unit   Second Time Unit         Offshoot
                               Could we model Sneezewort with PS3 code?

                                                                          12
Sneezewort Numbers
      13

           8?

           5
           3

           2


           1


           1




                     13
Page from
Liber abbaci,
Leonardo da Pisa
(1202)




                   14
Fibonacci’s Problem
Suppose a newly-born pair of rabbits, one
male, one female, are put in a field.
Rabbits mate at the age of one month so
that at the end of its second month a
female can produce another pair of
rabbits.

Suppose that our rabbits never die and
that the female always produces one new
pair (one male, one female) every month
from the second month on.

How many pairs will there be in one year?       Filius Bonacci, 1202 (Pisa)
                                            Liber Abaci (“Book of Calculation”)

                                                                       15
Rabbits




From http://www.mcs.surrey.ac.uk/Personal/R.Knott/Fibonacci/fibnat.html

                                                                          16
Fibonacci Numbers
GEB p. 136:
 These numbers are best defined
 recursively by the pair of formulas
    FIBO (n) = FIBO (n – 1) + FIBO (n – 2)
                              for n > 2
    FIBO (1) = FIBO (2) = 1
              Can we turn this into a Scheme procedure?


                                                          17
Defining FIBO
         These numbers defined
         recursively by:
         FIBO (n) =
           FIBO (n – 1)
           + FIBO (n – 2)
               for n > 1
         FIBO (1) = 1
         FIBO (0) = 0




                                 18
Defining fibo
(define (fibo n)                 > (fibo 1)
                                 1
 (if (= n 0) 0
                                 > (fibo 2)
     (if (= n 1) 1               2
         (+ (fibo (- n 1))       > (fibo 3)
                                 3
            (fibo (- n 2))))))   > (fibo 10)
                                 55



                                               19
Defining fibo with loop?
               (define (loop index result test update proc)
                (if (test index)
                    (loop (update index)
                        (proc index result)
                        test update proc)
                    result))




                                                          20
(define (fibo-loop n) ; doesn't work for n=0
 (cdr
  (loop 1
      (cons 0 1)
      (lambda (i) (< i n))
      inc
      (lambda (i v) (cons (cdr v) (+ (car v) (cdr v)))))))




                                                             21
Which is better?
 (define (fibo-rec n)
  (if (= n 0) 0
      (if (= n 1) 1
          (+ (fibo-rec (- n 1)) (fibo-rec (- n 2))))))

(define (fibo-loop n) ; doesn't work for n=0
 (cdr
  (loop 1 (cons 0 1) (lambda (i) (< i n)) inc
        (lambda (i v) (cons (cdr v) (+ (car v) (cdr v)))))))


                                                               22
Fibo Results
> (fibo-rec 2)
1
> (fibo-rec 3)
2
> (fibo-rec 4)
3
> (fibo-rec 10)
55
> (fibo-rec 60)
Still working…


                                 23
Tracing Fibo
> (require racket/trace)
> (trace fibo-rec)
> (fibo-rec 3)         > (fibo-loop 3)
|(fibo-rec 3)          >(fibo-loop 3)
|      (fibo-rec 2)    > (loop 1 '(0 . 1)   #<procedure> #<procedure:inc> #<procedure>   )
|      1               > (loop 2 '(1 . 1)   #<procedure> #<procedure:inc> #<procedure>   )
|      (fibo-rec 1)    > (loop 3 '(1 . 2)   #<procedure> #<procedure:inc> #<procedure>   )
|      1               < '(1 . 2)
|2                     <2
2                      2


                                                                                             24
> (fibo-rec 4)
>(fibo-rec 4)
> (fibo-rec 3)
> >(fibo-rec 2)
> > (fibo-rec 1)
<<1                To compute (fibo 4) we calculated:
> > (fibo-rec 0)
<<0                (fibo 3)      1 times
< <1               (fibo 2)      2 times
> >(fibo-rec 1)    (fibo 1)      3 times
< <1
<2                 (fibo 0)      3 times
> (fibo-rec 2)                  = 3+6 calls to fibo
> >(fibo-rec 1)
< <1               How many calls to calculate (fibo 60)?
> >(fibo-rec 0)
< <0
<1
<3
3


                                                            25
> (fibo-rec 5)
>(fibo-rec 5)
> (fibo-rec 4)
> >(fibo-rec 3)
> > (fibo-rec 2)
> > >(fibo-rec 1)    To calculate (fibo 5) we calculated:
< < <1
> > >(fibo-rec 0)    (fibo 4)        1 time
< < <0
<<1                  (fibo 3)        2 times
> > (fibo-rec 1)
<<1                  (fibo 2)        3 times
< <2
> >(fibo-rec 2)      (fibo 1/0)      8 times
> > (fibo-rec 1)
<<1
> > (fibo-rec 0)
<<0
< <1
<3
> (fibo-rec 3)      How many calls to calculate (fibo 60)?
> >(fibo-rec 2)
> > (fibo-rec 1)
<<1
> > (fibo-rec 0)
<<0
< <1
> >(fibo-rec 1)
< <1
<2
<5
5



                                                             26
Fast-Fibo Results

 > (time (fibo-loop 61))
 cpu time: 0 real time: 0 gc time: 0
 2504730781961
2.5 Trillion applications
2.5 GHz computer does 2.5 Billion simple operations per second,
so 2.5 Trillion applications operations take ~1000 seconds.
Each application of fibo involves hundreds of simple operations…




                                                                   27
;;; The Earth's mass is 6.0 x 10^24 kg
> (define mass-of-earth (* 6 (expt 10 24)))
  ;;; A typical rabbit's mass is 2.5 kilograms
> (define mass-of-rabbit 2.5)
> (/ (* mass-of-rabbit (fibo-loop 60)) mass-of-earth)
6.450036483e-013
> (/ (* mass-of-rabbit (fibo-loop 120)) mass-of-earth)
2.2326496895795693

According to Bonacci’s model, after less than 10 years, rabbits
would out-weigh the Earth!

         Beware the Bunnies!!
     Beware the Sneezewort!!
                                                                  28
The Verge of Survival
 by Filip and Colton

                        29
Evaluation Cost
Actual running times         How does time
vary according to:
– How fast a processor        scale with the
  you have                    size of the input?
– How much memory you
  have                        If the input size increases by
– Where data is located in    one, how much longer will it
                              take?
  memory
– How hot it is               If the input size doubles, how
– What else is running        much longer will it take?
– etc...
Running Time of fibo-rec
Fibonacci (n) = Fibonacci(n-2) + Fibonacci(n-1)
            = X Fibonacci(n-1)
            = Xn

  What is X?
         > (exact->inexact (/ (fibo-loop 2) (fibo-loop 1)))
         1.0
         > (exact->inexact (/ (fibo-loop 3) (fibo-loop 2)))
         2.0
         > (exact->inexact (/ (fibo-loop 4) (fibo-loop 3)))
         1.5
> (for 1 50
       (lambda (i) (printf "~a~n" (exact->inexact (/ (fibo-loop (+ i 1)) (fibo-loop i))))))
1.0
2.0
1.5
1.6666666666666667
1.6
1.625
1.6153846153846154
1.619047619047619
1.6176470588235294
1.6181818181818182
1.6179775280898876
1.6180555555555556
1.6180257510729614
1.6180371352785146
1.618032786885246
1.618034447821682
1.6180338134001253
…
1.618033988749895
Running Time of fibo-rec

     Fibonacci (n) = Fibonacci(n-2) + Fibonacci(n-1)
                   = ? Fibonacci(n-1)
                   = Φn

Φ = (/ (+ 1 (sqrt 5)) 2)
“The Golden Ratio” 1.618033988749895...

> (exact->inexact (/ (fibo-loop 41) (fibo-loop 40)))
1.618033988749895
“Golden” Rotunda?
The Golden Ratio
                                                      Euclid: “extreme and
                                                      mean ratio”




                  Parthenon
http://www.mathsisfun.com/numbers/golden-ratio.html




                                                          Nautilus Shell

                                                                             35
Charge
PS4 due Monday 3 October
Exam 1: out October 7, due October 12
  Covers:
      Problem Sets 1-4 including PS Comments
      Course Book Chapters 1-6
      Classes 1-18
Reading:
  no reading assignment until after Exam 1, but I will
  start covering things in Chapter 7-8 soon and
  encourage you to read The Information, Chapters 5-7

                                                         36

More Related Content

What's hot

Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Leonardo Borges
 
Emo-Exploitation
Emo-ExploitationEmo-Exploitation
Emo-Exploitationw0nd
 
The Ring programming language version 1.5.2 book - Part 13 of 181
The Ring programming language version 1.5.2 book - Part 13 of 181The Ring programming language version 1.5.2 book - Part 13 of 181
The Ring programming language version 1.5.2 book - Part 13 of 181Mahmoud Samir Fayed
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Leonardo Borges
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscexjeffz
 
Class 28: Entropy
Class 28: EntropyClass 28: Entropy
Class 28: EntropyDavid Evans
 
Macroprocessor
MacroprocessorMacroprocessor
Macroprocessorksanthosh
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)jeffz
 
Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++Sergey Platonov
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptjeffz
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架jeffz
 
Extend R with Rcpp!!!
Extend R with Rcpp!!!Extend R with Rcpp!!!
Extend R with Rcpp!!!mickey24
 
MeCC: Memory Comparison-based Code Clone Detector
MeCC: Memory Comparison-based Code Clone DetectorMeCC: Memory Comparison-based Code Clone Detector
MeCC: Memory Comparison-based Code Clone Detector영범 정
 
Runtime Code Generation and Data Management for Heterogeneous Computing in Java
Runtime Code Generation and Data Management for Heterogeneous Computing in JavaRuntime Code Generation and Data Management for Heterogeneous Computing in Java
Runtime Code Generation and Data Management for Heterogeneous Computing in JavaJuan Fumero
 
Preparation for mit ose lab4
Preparation for mit ose lab4Preparation for mit ose lab4
Preparation for mit ose lab4Benux Wei
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)jeffz
 
The Ring programming language version 1.3 book - Part 84 of 88
The Ring programming language version 1.3 book - Part 84 of 88The Ring programming language version 1.3 book - Part 84 of 88
The Ring programming language version 1.3 book - Part 84 of 88Mahmoud Samir Fayed
 
12X1 T01 03 integrating derivative on function
12X1 T01 03 integrating derivative on function12X1 T01 03 integrating derivative on function
12X1 T01 03 integrating derivative on functionNigel Simmons
 

What's hot (18)

Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012
 
Emo-Exploitation
Emo-ExploitationEmo-Exploitation
Emo-Exploitation
 
The Ring programming language version 1.5.2 book - Part 13 of 181
The Ring programming language version 1.5.2 book - Part 13 of 181The Ring programming language version 1.5.2 book - Part 13 of 181
The Ring programming language version 1.5.2 book - Part 13 of 181
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscex
 
Class 28: Entropy
Class 28: EntropyClass 28: Entropy
Class 28: Entropy
 
Macroprocessor
MacroprocessorMacroprocessor
Macroprocessor
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)
 
Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScript
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架
 
Extend R with Rcpp!!!
Extend R with Rcpp!!!Extend R with Rcpp!!!
Extend R with Rcpp!!!
 
MeCC: Memory Comparison-based Code Clone Detector
MeCC: Memory Comparison-based Code Clone DetectorMeCC: Memory Comparison-based Code Clone Detector
MeCC: Memory Comparison-based Code Clone Detector
 
Runtime Code Generation and Data Management for Heterogeneous Computing in Java
Runtime Code Generation and Data Management for Heterogeneous Computing in JavaRuntime Code Generation and Data Management for Heterogeneous Computing in Java
Runtime Code Generation and Data Management for Heterogeneous Computing in Java
 
Preparation for mit ose lab4
Preparation for mit ose lab4Preparation for mit ose lab4
Preparation for mit ose lab4
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)
 
The Ring programming language version 1.3 book - Part 84 of 88
The Ring programming language version 1.3 book - Part 84 of 88The Ring programming language version 1.3 book - Part 84 of 88
The Ring programming language version 1.3 book - Part 84 of 88
 
12X1 T01 03 integrating derivative on function
12X1 T01 03 integrating derivative on function12X1 T01 03 integrating derivative on function
12X1 T01 03 integrating derivative on function
 

Viewers also liked

Class 30: Sex, Religion, and Politics
Class 30: Sex, Religion, and PoliticsClass 30: Sex, Religion, and Politics
Class 30: Sex, Religion, and PoliticsDavid Evans
 
Class 31: Deanonymizing
Class 31: DeanonymizingClass 31: Deanonymizing
Class 31: DeanonymizingDavid Evans
 
Lecture 1: Introduction
Lecture 1: IntroductionLecture 1: Introduction
Lecture 1: IntroductionDavid Evans
 
Class 39: ...and the World Wide Web
Class 39: ...and the World Wide WebClass 39: ...and the World Wide Web
Class 39: ...and the World Wide WebDavid Evans
 
Class 11: Deeper List Procedures
Class 11: Deeper List ProceduresClass 11: Deeper List Procedures
Class 11: Deeper List ProceduresDavid Evans
 
Class 34: Proving Unprovability
Class 34: Proving UnprovabilityClass 34: Proving Unprovability
Class 34: Proving UnprovabilityDavid Evans
 
Class 12: Computing Machines
Class 12: Computing MachinesClass 12: Computing Machines
Class 12: Computing MachinesDavid Evans
 
Web Server Scheduling
Web Server SchedulingWeb Server Scheduling
Web Server SchedulingDavid Evans
 
Multi-Tasking Map (MapReduce, Tasks in Rust)
Multi-Tasking Map (MapReduce, Tasks in Rust)Multi-Tasking Map (MapReduce, Tasks in Rust)
Multi-Tasking Map (MapReduce, Tasks in Rust)David Evans
 
How to Live in Paradise
How to Live in ParadiseHow to Live in Paradise
How to Live in ParadiseDavid Evans
 
Class 24: Imperative Programming
Class 24: Imperative ProgrammingClass 24: Imperative Programming
Class 24: Imperative ProgrammingDavid Evans
 
The First Billion Android Activations
The First Billion Android ActivationsThe First Billion Android Activations
The First Billion Android ActivationsDavid Evans
 
Cryptographic Future
Cryptographic FutureCryptographic Future
Cryptographic FutureDavid Evans
 
Bakers and Philosophers
Bakers and PhilosophersBakers and Philosophers
Bakers and PhilosophersDavid Evans
 
Engineering Cryptographic Applications: Symmetric Encryption
Engineering Cryptographic Applications: Symmetric EncryptionEngineering Cryptographic Applications: Symmetric Encryption
Engineering Cryptographic Applications: Symmetric EncryptionDavid Evans
 
Scheduling in Linux and Web Servers
Scheduling in Linux and Web ServersScheduling in Linux and Web Servers
Scheduling in Linux and Web ServersDavid Evans
 
Class 1: Introduction - What is an Operating System?
Class 1: Introduction - What is an Operating System?Class 1: Introduction - What is an Operating System?
Class 1: Introduction - What is an Operating System?David Evans
 

Viewers also liked (19)

Class 30: Sex, Religion, and Politics
Class 30: Sex, Religion, and PoliticsClass 30: Sex, Religion, and Politics
Class 30: Sex, Religion, and Politics
 
Storage Systems
Storage SystemsStorage Systems
Storage Systems
 
Class 31: Deanonymizing
Class 31: DeanonymizingClass 31: Deanonymizing
Class 31: Deanonymizing
 
Lecture 1: Introduction
Lecture 1: IntroductionLecture 1: Introduction
Lecture 1: Introduction
 
Class 39: ...and the World Wide Web
Class 39: ...and the World Wide WebClass 39: ...and the World Wide Web
Class 39: ...and the World Wide Web
 
Class 11: Deeper List Procedures
Class 11: Deeper List ProceduresClass 11: Deeper List Procedures
Class 11: Deeper List Procedures
 
Class 34: Proving Unprovability
Class 34: Proving UnprovabilityClass 34: Proving Unprovability
Class 34: Proving Unprovability
 
Class 12: Computing Machines
Class 12: Computing MachinesClass 12: Computing Machines
Class 12: Computing Machines
 
Lecture20
Lecture20Lecture20
Lecture20
 
Web Server Scheduling
Web Server SchedulingWeb Server Scheduling
Web Server Scheduling
 
Multi-Tasking Map (MapReduce, Tasks in Rust)
Multi-Tasking Map (MapReduce, Tasks in Rust)Multi-Tasking Map (MapReduce, Tasks in Rust)
Multi-Tasking Map (MapReduce, Tasks in Rust)
 
How to Live in Paradise
How to Live in ParadiseHow to Live in Paradise
How to Live in Paradise
 
Class 24: Imperative Programming
Class 24: Imperative ProgrammingClass 24: Imperative Programming
Class 24: Imperative Programming
 
The First Billion Android Activations
The First Billion Android ActivationsThe First Billion Android Activations
The First Billion Android Activations
 
Cryptographic Future
Cryptographic FutureCryptographic Future
Cryptographic Future
 
Bakers and Philosophers
Bakers and PhilosophersBakers and Philosophers
Bakers and Philosophers
 
Engineering Cryptographic Applications: Symmetric Encryption
Engineering Cryptographic Applications: Symmetric EncryptionEngineering Cryptographic Applications: Symmetric Encryption
Engineering Cryptographic Applications: Symmetric Encryption
 
Scheduling in Linux and Web Servers
Scheduling in Linux and Web ServersScheduling in Linux and Web Servers
Scheduling in Linux and Web Servers
 
Class 1: Introduction - What is an Operating System?
Class 1: Introduction - What is an Operating System?Class 1: Introduction - What is an Operating System?
Class 1: Introduction - What is an Operating System?
 

Similar to Class 17: Golden Sneezewort

On Resolution Proofs for Combinational Equivalence
On Resolution Proofs for Combinational EquivalenceOn Resolution Proofs for Combinational Equivalence
On Resolution Proofs for Combinational Equivalencesatrajit
 
State equations model based on modulo 2 arithmetic and its applciation on rec...
State equations model based on modulo 2 arithmetic and its applciation on rec...State equations model based on modulo 2 arithmetic and its applciation on rec...
State equations model based on modulo 2 arithmetic and its applciation on rec...Anax Fotopoulos
 
State Equations Model Based On Modulo 2 Arithmetic And Its Applciation On Rec...
State Equations Model Based On Modulo 2 Arithmetic And Its Applciation On Rec...State Equations Model Based On Modulo 2 Arithmetic And Its Applciation On Rec...
State Equations Model Based On Modulo 2 Arithmetic And Its Applciation On Rec...Anax_Fotopoulos
 
R package 'bayesImageS': a case study in Bayesian computation using Rcpp and ...
R package 'bayesImageS': a case study in Bayesian computation using Rcpp and ...R package 'bayesImageS': a case study in Bayesian computation using Rcpp and ...
R package 'bayesImageS': a case study in Bayesian computation using Rcpp and ...Matt Moores
 
Use PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language ParserUse PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language ParserYodalee
 
Metaheuristic Tuning of Type-II Fuzzy Inference System for Data Mining
Metaheuristic Tuning of Type-II Fuzzy Inference System for Data MiningMetaheuristic Tuning of Type-II Fuzzy Inference System for Data Mining
Metaheuristic Tuning of Type-II Fuzzy Inference System for Data MiningVarun Ojha
 
Pointcuts and Analysis
Pointcuts and AnalysisPointcuts and Analysis
Pointcuts and AnalysisWiwat Ruengmee
 
Class 16: Making Loops
Class 16: Making LoopsClass 16: Making Loops
Class 16: Making LoopsDavid Evans
 
Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議dico_leque
 
Locks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael BarkerLocks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael BarkerJAX London
 
Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Michael Barker
 
The Ring programming language version 1.9 book - Part 33 of 210
The Ring programming language version 1.9 book - Part 33 of 210The Ring programming language version 1.9 book - Part 33 of 210
The Ring programming language version 1.9 book - Part 33 of 210Mahmoud Samir Fayed
 
Low-level Shader Optimization for Next-Gen and DX11 by Emil Persson
Low-level Shader Optimization for Next-Gen and DX11 by Emil PerssonLow-level Shader Optimization for Next-Gen and DX11 by Emil Persson
Low-level Shader Optimization for Next-Gen and DX11 by Emil PerssonAMD Developer Central
 
The Ring programming language version 1.5.4 book - Part 26 of 185
The Ring programming language version 1.5.4 book - Part 26 of 185The Ring programming language version 1.5.4 book - Part 26 of 185
The Ring programming language version 1.5.4 book - Part 26 of 185Mahmoud Samir Fayed
 
Introduction to Julia
Introduction to JuliaIntroduction to Julia
Introduction to Julia岳華 杜
 

Similar to Class 17: Golden Sneezewort (20)

On Resolution Proofs for Combinational Equivalence
On Resolution Proofs for Combinational EquivalenceOn Resolution Proofs for Combinational Equivalence
On Resolution Proofs for Combinational Equivalence
 
State equations model based on modulo 2 arithmetic and its applciation on rec...
State equations model based on modulo 2 arithmetic and its applciation on rec...State equations model based on modulo 2 arithmetic and its applciation on rec...
State equations model based on modulo 2 arithmetic and its applciation on rec...
 
State Equations Model Based On Modulo 2 Arithmetic And Its Applciation On Rec...
State Equations Model Based On Modulo 2 Arithmetic And Its Applciation On Rec...State Equations Model Based On Modulo 2 Arithmetic And Its Applciation On Rec...
State Equations Model Based On Modulo 2 Arithmetic And Its Applciation On Rec...
 
numdoc
numdocnumdoc
numdoc
 
R Language Introduction
R Language IntroductionR Language Introduction
R Language Introduction
 
R package 'bayesImageS': a case study in Bayesian computation using Rcpp and ...
R package 'bayesImageS': a case study in Bayesian computation using Rcpp and ...R package 'bayesImageS': a case study in Bayesian computation using Rcpp and ...
R package 'bayesImageS': a case study in Bayesian computation using Rcpp and ...
 
Use PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language ParserUse PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language Parser
 
Metaheuristic Tuning of Type-II Fuzzy Inference System for Data Mining
Metaheuristic Tuning of Type-II Fuzzy Inference System for Data MiningMetaheuristic Tuning of Type-II Fuzzy Inference System for Data Mining
Metaheuristic Tuning of Type-II Fuzzy Inference System for Data Mining
 
Pointcuts and Analysis
Pointcuts and AnalysisPointcuts and Analysis
Pointcuts and Analysis
 
Class 16: Making Loops
Class 16: Making LoopsClass 16: Making Loops
Class 16: Making Loops
 
Term Rewriting
Term RewritingTerm Rewriting
Term Rewriting
 
Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議
 
Locks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael BarkerLocks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael Barker
 
Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!
 
The Ring programming language version 1.9 book - Part 33 of 210
The Ring programming language version 1.9 book - Part 33 of 210The Ring programming language version 1.9 book - Part 33 of 210
The Ring programming language version 1.9 book - Part 33 of 210
 
Pas oct12
Pas oct12Pas oct12
Pas oct12
 
PAS 2012
PAS 2012PAS 2012
PAS 2012
 
Low-level Shader Optimization for Next-Gen and DX11 by Emil Persson
Low-level Shader Optimization for Next-Gen and DX11 by Emil PerssonLow-level Shader Optimization for Next-Gen and DX11 by Emil Persson
Low-level Shader Optimization for Next-Gen and DX11 by Emil Persson
 
The Ring programming language version 1.5.4 book - Part 26 of 185
The Ring programming language version 1.5.4 book - Part 26 of 185The Ring programming language version 1.5.4 book - Part 26 of 185
The Ring programming language version 1.5.4 book - Part 26 of 185
 
Introduction to Julia
Introduction to JuliaIntroduction to Julia
Introduction to Julia
 

More from David Evans

Cryptocurrency Jeopardy!
Cryptocurrency Jeopardy!Cryptocurrency Jeopardy!
Cryptocurrency Jeopardy!David Evans
 
Trick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for Cypherpunks
Trick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for CypherpunksTrick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for Cypherpunks
Trick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for CypherpunksDavid Evans
 
Hidden Services, Zero Knowledge
Hidden Services, Zero KnowledgeHidden Services, Zero Knowledge
Hidden Services, Zero KnowledgeDavid Evans
 
Anonymity in Bitcoin
Anonymity in BitcoinAnonymity in Bitcoin
Anonymity in BitcoinDavid Evans
 
Midterm Confirmations
Midterm ConfirmationsMidterm Confirmations
Midterm ConfirmationsDavid Evans
 
Scripting Transactions
Scripting TransactionsScripting Transactions
Scripting TransactionsDavid Evans
 
How to Live in Paradise
How to Live in ParadiseHow to Live in Paradise
How to Live in ParadiseDavid Evans
 
Mining Economics
Mining EconomicsMining Economics
Mining EconomicsDavid Evans
 
Becoming More Paranoid
Becoming More ParanoidBecoming More Paranoid
Becoming More ParanoidDavid Evans
 
Asymmetric Key Signatures
Asymmetric Key SignaturesAsymmetric Key Signatures
Asymmetric Key SignaturesDavid Evans
 
Introduction to Cryptography
Introduction to CryptographyIntroduction to Cryptography
Introduction to CryptographyDavid Evans
 
Class 1: What is Money?
Class 1: What is Money?Class 1: What is Money?
Class 1: What is Money?David Evans
 
Multi-Party Computation for the Masses
Multi-Party Computation for the MassesMulti-Party Computation for the Masses
Multi-Party Computation for the MassesDavid Evans
 
Proof of Reserve
Proof of ReserveProof of Reserve
Proof of ReserveDavid Evans
 
Blooming Sidechains!
Blooming Sidechains!Blooming Sidechains!
Blooming Sidechains!David Evans
 
Useful Proofs of Work, Permacoin
Useful Proofs of Work, PermacoinUseful Proofs of Work, Permacoin
Useful Proofs of Work, PermacoinDavid Evans
 

More from David Evans (20)

Cryptocurrency Jeopardy!
Cryptocurrency Jeopardy!Cryptocurrency Jeopardy!
Cryptocurrency Jeopardy!
 
Trick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for Cypherpunks
Trick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for CypherpunksTrick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for Cypherpunks
Trick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for Cypherpunks
 
Hidden Services, Zero Knowledge
Hidden Services, Zero KnowledgeHidden Services, Zero Knowledge
Hidden Services, Zero Knowledge
 
Anonymity in Bitcoin
Anonymity in BitcoinAnonymity in Bitcoin
Anonymity in Bitcoin
 
Midterm Confirmations
Midterm ConfirmationsMidterm Confirmations
Midterm Confirmations
 
Scripting Transactions
Scripting TransactionsScripting Transactions
Scripting Transactions
 
How to Live in Paradise
How to Live in ParadiseHow to Live in Paradise
How to Live in Paradise
 
Bitcoin Script
Bitcoin ScriptBitcoin Script
Bitcoin Script
 
Mining Economics
Mining EconomicsMining Economics
Mining Economics
 
Mining
MiningMining
Mining
 
The Blockchain
The BlockchainThe Blockchain
The Blockchain
 
Becoming More Paranoid
Becoming More ParanoidBecoming More Paranoid
Becoming More Paranoid
 
Asymmetric Key Signatures
Asymmetric Key SignaturesAsymmetric Key Signatures
Asymmetric Key Signatures
 
Introduction to Cryptography
Introduction to CryptographyIntroduction to Cryptography
Introduction to Cryptography
 
Class 1: What is Money?
Class 1: What is Money?Class 1: What is Money?
Class 1: What is Money?
 
Multi-Party Computation for the Masses
Multi-Party Computation for the MassesMulti-Party Computation for the Masses
Multi-Party Computation for the Masses
 
Proof of Reserve
Proof of ReserveProof of Reserve
Proof of Reserve
 
Silk Road
Silk RoadSilk Road
Silk Road
 
Blooming Sidechains!
Blooming Sidechains!Blooming Sidechains!
Blooming Sidechains!
 
Useful Proofs of Work, Permacoin
Useful Proofs of Work, PermacoinUseful Proofs of Work, Permacoin
Useful Proofs of Work, Permacoin
 

Recently uploaded

Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...lizamodels9
 
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCRashishs7044
 
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...lizamodels9
 
Digital Transformation in the PLM domain - distrib.pdf
Digital Transformation in the PLM domain - distrib.pdfDigital Transformation in the PLM domain - distrib.pdf
Digital Transformation in the PLM domain - distrib.pdfJos Voskuil
 
Pitch Deck Teardown: NOQX's $200k Pre-seed deck
Pitch Deck Teardown: NOQX's $200k Pre-seed deckPitch Deck Teardown: NOQX's $200k Pre-seed deck
Pitch Deck Teardown: NOQX's $200k Pre-seed deckHajeJanKamps
 
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptxContemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptxMarkAnthonyAurellano
 
The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024christinemoorman
 
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCRashishs7044
 
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City GurgaonCall Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaoncallgirls2057
 
Flow Your Strategy at Flight Levels Day 2024
Flow Your Strategy at Flight Levels Day 2024Flow Your Strategy at Flight Levels Day 2024
Flow Your Strategy at Flight Levels Day 2024Kirill Klimov
 
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCRashishs7044
 
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,noida100girls
 
Annual General Meeting Presentation Slides
Annual General Meeting Presentation SlidesAnnual General Meeting Presentation Slides
Annual General Meeting Presentation SlidesKeppelCorporation
 
8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCRashishs7044
 
Call Girls Miyapur 7001305949 all area service COD available Any Time
Call Girls Miyapur 7001305949 all area service COD available Any TimeCall Girls Miyapur 7001305949 all area service COD available Any Time
Call Girls Miyapur 7001305949 all area service COD available Any Timedelhimodelshub1
 
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / NcrCall Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncrdollysharma2066
 
RE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman LeechRE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman LeechNewman George Leech
 
Sales & Marketing Alignment: How to Synergize for Success
Sales & Marketing Alignment: How to Synergize for SuccessSales & Marketing Alignment: How to Synergize for Success
Sales & Marketing Alignment: How to Synergize for SuccessAggregage
 
8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCR8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCRashishs7044
 
Progress Report - Oracle Database Analyst Summit
Progress  Report - Oracle Database Analyst SummitProgress  Report - Oracle Database Analyst Summit
Progress Report - Oracle Database Analyst SummitHolger Mueller
 

Recently uploaded (20)

Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
 
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
 
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
 
Digital Transformation in the PLM domain - distrib.pdf
Digital Transformation in the PLM domain - distrib.pdfDigital Transformation in the PLM domain - distrib.pdf
Digital Transformation in the PLM domain - distrib.pdf
 
Pitch Deck Teardown: NOQX's $200k Pre-seed deck
Pitch Deck Teardown: NOQX's $200k Pre-seed deckPitch Deck Teardown: NOQX's $200k Pre-seed deck
Pitch Deck Teardown: NOQX's $200k Pre-seed deck
 
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptxContemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
 
The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024
 
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
 
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City GurgaonCall Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
 
Flow Your Strategy at Flight Levels Day 2024
Flow Your Strategy at Flight Levels Day 2024Flow Your Strategy at Flight Levels Day 2024
Flow Your Strategy at Flight Levels Day 2024
 
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
 
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
 
Annual General Meeting Presentation Slides
Annual General Meeting Presentation SlidesAnnual General Meeting Presentation Slides
Annual General Meeting Presentation Slides
 
8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR
 
Call Girls Miyapur 7001305949 all area service COD available Any Time
Call Girls Miyapur 7001305949 all area service COD available Any TimeCall Girls Miyapur 7001305949 all area service COD available Any Time
Call Girls Miyapur 7001305949 all area service COD available Any Time
 
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / NcrCall Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
 
RE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman LeechRE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman Leech
 
Sales & Marketing Alignment: How to Synergize for Success
Sales & Marketing Alignment: How to Synergize for SuccessSales & Marketing Alignment: How to Synergize for Success
Sales & Marketing Alignment: How to Synergize for Success
 
8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCR8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCR
 
Progress Report - Oracle Database Analyst Summit
Progress  Report - Oracle Database Analyst SummitProgress  Report - Oracle Database Analyst Summit
Progress Report - Oracle Database Analyst Summit
 

Class 17: Golden Sneezewort

  • 1. Class 17: Golden Sneezewort cs1120 Fall 2011 David Evans 30 September 2011
  • 2. Plan Generalizing Loops Introducing Cost Book: Chapter 7 and 8 (okay to read after Exam 1) Not covered on Exam 1 2
  • 3. Recap/Wake-up: A General Loop (define (loop index result test update proc) 3
  • 4. General Loop with Result (define (loop index result test update proc) (if (test index) (loop (update index) (proc index result) test update proc) result)) 4
  • 5. Using Loop (define (loop index result test update proc) (if (test index) (loop (update index) (proc index result) test update proc) result)) (define (gauss-sum n) (loop 1 0 (lambda (i) (<= i n)) (lambda (i) (+ i 1)) (lambda (i res) (+ res i)))) 5
  • 6. (define (loop index result test update proc) (if (test index) (loop (update index) (proc index result) test update proc) result)) (define (factorial n) 6
  • 7. (define (loop index result test update proc) (if (test index) (loop (update index) (proc index result) test update proc) result)) (define (list-length p) 7
  • 8. (define (loop index result test update proc) (if (test index) (loop (update index) (proc index result) test update proc) result)) (define (list-accumulate f base p) (if (null? p) base (f (car p) (list-accumulate f base (cdr p)))) 8
  • 9. (define (loop index result test update proc) (if (test index) (loop (update index) (proc index result) test update proc) result)) (define (list-accumulate f base p) (if (null? p) base (f (car p) (list-accumulate f base (cdr p)))) (define (list-accumulate f base p) (loop p base not-null? cdr (lambda (p res) (f (car p) res)))) 9
  • 10. Challenge Problem Define an efficient edit-distance procedure (as defined in PS2) using loop (without using memoization). 10
  • 12. Sneezewort Growth First Time Unit Second Time Unit Offshoot Could we model Sneezewort with PS3 code? 12
  • 13. Sneezewort Numbers 13 8? 5 3 2 1 1 13
  • 14. Page from Liber abbaci, Leonardo da Pisa (1202) 14
  • 15. Fibonacci’s Problem Suppose a newly-born pair of rabbits, one male, one female, are put in a field. Rabbits mate at the age of one month so that at the end of its second month a female can produce another pair of rabbits. Suppose that our rabbits never die and that the female always produces one new pair (one male, one female) every month from the second month on. How many pairs will there be in one year? Filius Bonacci, 1202 (Pisa) Liber Abaci (“Book of Calculation”) 15
  • 17. Fibonacci Numbers GEB p. 136: These numbers are best defined recursively by the pair of formulas FIBO (n) = FIBO (n – 1) + FIBO (n – 2) for n > 2 FIBO (1) = FIBO (2) = 1 Can we turn this into a Scheme procedure? 17
  • 18. Defining FIBO These numbers defined recursively by: FIBO (n) = FIBO (n – 1) + FIBO (n – 2) for n > 1 FIBO (1) = 1 FIBO (0) = 0 18
  • 19. Defining fibo (define (fibo n) > (fibo 1) 1 (if (= n 0) 0 > (fibo 2) (if (= n 1) 1 2 (+ (fibo (- n 1)) > (fibo 3) 3 (fibo (- n 2)))))) > (fibo 10) 55 19
  • 20. Defining fibo with loop? (define (loop index result test update proc) (if (test index) (loop (update index) (proc index result) test update proc) result)) 20
  • 21. (define (fibo-loop n) ; doesn't work for n=0 (cdr (loop 1 (cons 0 1) (lambda (i) (< i n)) inc (lambda (i v) (cons (cdr v) (+ (car v) (cdr v))))))) 21
  • 22. Which is better? (define (fibo-rec n) (if (= n 0) 0 (if (= n 1) 1 (+ (fibo-rec (- n 1)) (fibo-rec (- n 2)))))) (define (fibo-loop n) ; doesn't work for n=0 (cdr (loop 1 (cons 0 1) (lambda (i) (< i n)) inc (lambda (i v) (cons (cdr v) (+ (car v) (cdr v))))))) 22
  • 23. Fibo Results > (fibo-rec 2) 1 > (fibo-rec 3) 2 > (fibo-rec 4) 3 > (fibo-rec 10) 55 > (fibo-rec 60) Still working… 23
  • 24. Tracing Fibo > (require racket/trace) > (trace fibo-rec) > (fibo-rec 3) > (fibo-loop 3) |(fibo-rec 3) >(fibo-loop 3) | (fibo-rec 2) > (loop 1 '(0 . 1) #<procedure> #<procedure:inc> #<procedure> ) | 1 > (loop 2 '(1 . 1) #<procedure> #<procedure:inc> #<procedure> ) | (fibo-rec 1) > (loop 3 '(1 . 2) #<procedure> #<procedure:inc> #<procedure> ) | 1 < '(1 . 2) |2 <2 2 2 24
  • 25. > (fibo-rec 4) >(fibo-rec 4) > (fibo-rec 3) > >(fibo-rec 2) > > (fibo-rec 1) <<1 To compute (fibo 4) we calculated: > > (fibo-rec 0) <<0 (fibo 3) 1 times < <1 (fibo 2) 2 times > >(fibo-rec 1) (fibo 1) 3 times < <1 <2 (fibo 0) 3 times > (fibo-rec 2) = 3+6 calls to fibo > >(fibo-rec 1) < <1 How many calls to calculate (fibo 60)? > >(fibo-rec 0) < <0 <1 <3 3 25
  • 26. > (fibo-rec 5) >(fibo-rec 5) > (fibo-rec 4) > >(fibo-rec 3) > > (fibo-rec 2) > > >(fibo-rec 1) To calculate (fibo 5) we calculated: < < <1 > > >(fibo-rec 0) (fibo 4) 1 time < < <0 <<1 (fibo 3) 2 times > > (fibo-rec 1) <<1 (fibo 2) 3 times < <2 > >(fibo-rec 2) (fibo 1/0) 8 times > > (fibo-rec 1) <<1 > > (fibo-rec 0) <<0 < <1 <3 > (fibo-rec 3) How many calls to calculate (fibo 60)? > >(fibo-rec 2) > > (fibo-rec 1) <<1 > > (fibo-rec 0) <<0 < <1 > >(fibo-rec 1) < <1 <2 <5 5 26
  • 27. Fast-Fibo Results > (time (fibo-loop 61)) cpu time: 0 real time: 0 gc time: 0 2504730781961 2.5 Trillion applications 2.5 GHz computer does 2.5 Billion simple operations per second, so 2.5 Trillion applications operations take ~1000 seconds. Each application of fibo involves hundreds of simple operations… 27
  • 28. ;;; The Earth's mass is 6.0 x 10^24 kg > (define mass-of-earth (* 6 (expt 10 24))) ;;; A typical rabbit's mass is 2.5 kilograms > (define mass-of-rabbit 2.5) > (/ (* mass-of-rabbit (fibo-loop 60)) mass-of-earth) 6.450036483e-013 > (/ (* mass-of-rabbit (fibo-loop 120)) mass-of-earth) 2.2326496895795693 According to Bonacci’s model, after less than 10 years, rabbits would out-weigh the Earth! Beware the Bunnies!! Beware the Sneezewort!! 28
  • 29. The Verge of Survival by Filip and Colton 29
  • 30. Evaluation Cost Actual running times How does time vary according to: – How fast a processor scale with the you have size of the input? – How much memory you have If the input size increases by – Where data is located in one, how much longer will it take? memory – How hot it is If the input size doubles, how – What else is running much longer will it take? – etc...
  • 31. Running Time of fibo-rec Fibonacci (n) = Fibonacci(n-2) + Fibonacci(n-1) = X Fibonacci(n-1) = Xn What is X? > (exact->inexact (/ (fibo-loop 2) (fibo-loop 1))) 1.0 > (exact->inexact (/ (fibo-loop 3) (fibo-loop 2))) 2.0 > (exact->inexact (/ (fibo-loop 4) (fibo-loop 3))) 1.5
  • 32. > (for 1 50 (lambda (i) (printf "~a~n" (exact->inexact (/ (fibo-loop (+ i 1)) (fibo-loop i)))))) 1.0 2.0 1.5 1.6666666666666667 1.6 1.625 1.6153846153846154 1.619047619047619 1.6176470588235294 1.6181818181818182 1.6179775280898876 1.6180555555555556 1.6180257510729614 1.6180371352785146 1.618032786885246 1.618034447821682 1.6180338134001253 … 1.618033988749895
  • 33. Running Time of fibo-rec Fibonacci (n) = Fibonacci(n-2) + Fibonacci(n-1) = ? Fibonacci(n-1) = Φn Φ = (/ (+ 1 (sqrt 5)) 2) “The Golden Ratio” 1.618033988749895... > (exact->inexact (/ (fibo-loop 41) (fibo-loop 40))) 1.618033988749895
  • 35. The Golden Ratio Euclid: “extreme and mean ratio” Parthenon http://www.mathsisfun.com/numbers/golden-ratio.html Nautilus Shell 35
  • 36. Charge PS4 due Monday 3 October Exam 1: out October 7, due October 12 Covers: Problem Sets 1-4 including PS Comments Course Book Chapters 1-6 Classes 1-18 Reading: no reading assignment until after Exam 1, but I will start covering things in Chapter 7-8 soon and encourage you to read The Information, Chapters 5-7 36