-
Notifications
You must be signed in to change notification settings - Fork 1
/
Exercise 1.40 cubic.rkt
executable file
·75 lines (58 loc) · 1.43 KB
/
Exercise 1.40 cubic.rkt
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
70
71
72
73
74
75
#lang racket
; Exercise 1.40. Define a procedure cubic that can be used together with the newtons-method
; procedure in expressions of the form
; (newtons-method (cubic a b c) 1)
; to approximate zeros of the cubic x^3 + ax^2 + bx + c.
; SOLUTION
(define (cubic a b c)
(lambda (w) (+ (cube w) (* a (square w)) (* b w) c))
)
(define (cube x)
(* x x x)
)
(define (square x)
(* x x)
)
(define (newtons-method g guess)
(fixed-point (newton-transform g) guess)
)
(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)
)
(define tolerance 0.00001)
(define (newton-transform g)
(lambda (x) (- x (/ (g x) ((deriv g) x))))
)
(define (deriv g)
(lambda (x)
(/ (- (g (+ x dx)) (g x)) dx)
)
)
(define dx 0.00001)
; Tests
> (newtons-method (cubic 0 0 0) 1000)
2.5555229328341865e-006
> (newtons-method (cubic 0 0 0) 10000)
2.617517159109334e-006
> (newtons-method (cubic 0 0 0) 10000000)
2.62097439104511e-006
> (newtons-method (cubic 2 3 8) 10000000)
-2.2482978222845467
> ((cubic 2 3 8) (newtons-method (cubic 2 3 8) 10000000))
1.7763568394002505e-015
> (newtons-method (cubic 1 1 1) 1)
-0.9999999999997796
> ((cubic 1 1 1) (newtons-method (cubic 1 1 1) 10000000))
2.191580250610059e-013
>