blob: 079a8b58ca0867d268c1ba63623827ac1590b098 (
plain) (
blame)
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
|
;;; Note: all versions work only for quadratics with real roots
;;; Straightforward but slow way:
(define (roots a b c)
(se (/ (+ (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a))
(/ (- (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a)) ))
;;; Using a subprocedure to eliminate the repeated computation:
(define (roots a b c)
(define (roots1 d)
(se (/ (+ (- b) d) (* 2 a))
(/ (- (- b) d) (* 2 a)) ))
(roots1 (sqrt (- (* b b) (* 4 a c)))) )
;;; Using lambda to avoid naming the subprocedure:
(define (roots a b c)
((lambda (d)
(se (/ (+ (- b) d) (* 2 a))
(/ (- (- b) d) (* 2 a)) ))
(sqrt (- (* b b) (* 4 a c))) ))
;;; Using let to rearrange the above:
(define (roots a b c)
(let ((d (sqrt (- (* b b) (* 4 a c)))))
(se (/ (+ (- b) d) (* 2 a))
(/ (- (- b) d) (* 2 a)) )))
;;; More optimization:
(define (roots a b c)
(let ((d (sqrt (- (* b b) (* 4 a c))))
(-b (- b))
(2a (* 2 a)))
(se (/ (+ -b d) 2a)
(/ (- -b d) 2a) )))
|