-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnewton-revisit.scm
69 lines (58 loc) · 1.24 KB
/
newton-revisit.scm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
; fixed-point procedure
(define (fixed-point f start)
(define tol 1e-5)
(define (close-enough? v1 v2)
(< (abs (- v1 v2)) tol))
(define (try guess)
(let ((next (f guess)))
(if (close-enough? guess next)
next
(try next))))
(try start))
; calculate derivatives
(define (deriv f)
(define dx 1e-5)
(lambda (x)
(/ (- (f (+ x dx))
(f x))
dx)))
; test deriv
(define (cube x) (* x x x))
((deriv cube) 5)
;; find a root <==> find a fixed-point of a transform
(define (newton-transform g)
(lambda (x)
(- x (/ (g x)
((deriv g) x)))))
; find the root of g
(define (newton-method g guess)
(fixed-point (newton-transform g) guess))
;; test
(define (sqrt x)
(newton-method
(lambda (y)
(- x (square y)))
1.0))
(sqrt 2)
;; one more abstraction
(define (fixed-point-of-transform g tranform guess)
(fixed-point (tranform g) guess))
; half-interval method
(define (sqrt x)
(fixed-point-of-transform
(lambda (y) (/ x y))
average-damp
1.0))
(define (average-damp f)
(lambda (x)
(/ (+ x (f x))
2.0)))
; or newton-method
(define (sqrt x)
(fixed-point-of-transform
(lambda (y)
(- x (square y)))
newton-transform
1.0))
;; test
(sqrt 2)