SICP 1.3.2-1.3.3
Posted on 2015-02-15 20:13:00 +0900
in SICP
Lisp
1.34
( define ( f g ) ( g 2 ))
( f f )
-->
( f 2 )
-->
( 2 2 )
1.35
( define ( fixed-point f first-guess )
( define ( close-enough? v1 v2 )
( < ( abs ( - v1 v2 )) tolerance ))
( define ( try guess )
( let (( next ( f guess )))
( if ( close-enough? guess next )
next
( try next ))))
( try first-guess ))
( fixed-point ( lambda ( x ) ( + 1 ( / 1 x ))) 1.0 )
1.36
( define ( fixed-point f first-guess )
( define ( close-enough? v1 v2 )
( < ( abs ( - v1 v2 )) tolerance ))
( define ( try guess tried )
( display guess )
( newline )
( let (( next ( f guess )))
( if ( close-enough? guess next )
( begin
( display ( + tried 1 ))
( newline )
next )
( try next ( + tried 1 )))))
( try first-guess 1 ))
( fixed-point ( lambda ( x ) ( / ( log 1000 ) ( log x ))) 2.0 )
( define ( average x y )
( / ( + x y ) 2 ))
( fixed-point ( lambda ( x ) ( average x
( / ( log 1000 ) ( log x )))) 2.0 )
If order to display the iterate numbers, a new parameter tried
is added in.
A new syntax begin
is used in order to run multiple commands sequencely, which will
return the last expression’s value as the result.
The simple version will run 35
times, while the average version will only run 10
times.
1.37
( define ( cont-frac n d k )
( define ( iter x )
( if ( < x k )
( / ( n x )
( + ( d x )
( iter ( + x 1 ))))
( / ( n x )
( d x ))))
( iter 1 ))
( define ( cont-frac-iter n d k )
( define ( iter k result )
( if ( = k 0 )
result
( iter ( - k 1 )
( + ( d k )
( / ( n k )
result )))))
( iter ( - k 1 ) ( / ( n k )
( d k ))))
1.38
The key lies in finding out a math expression for
1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8,...
( define ( d i )
( if ( not ( = 0
( remainder ( + i 1 ) 3 )))
1
( * 2
( / ( + i 1 )
3 ))))
( define euler-e
( + 2 ( cont-frac ( lambda ( x ) 1.0 ) d 10 )))
1.39
( define ( tan-cf x k )
( cont-frac
( lambda ( a ) ( if ( = a 1 )
x
( - ( square x ))))
( lambda ( a ) ( - ( * 2 a ) 1 ))
k ))