75 lines
1.4 KiB
Scheme
75 lines
1.4 KiB
Scheme
|
|
(define (sqrt-iter guess x)
|
|
(if (good-enough? guess x)
|
|
guess
|
|
(sqrt-iter (improve guess x)
|
|
x
|
|
)
|
|
)
|
|
)
|
|
|
|
(define (improve guess x)
|
|
(average guess (/ x guess))
|
|
)
|
|
|
|
(define (average x y)
|
|
(/ (+ x y) 2)
|
|
)
|
|
|
|
(define (square x) (* x x))
|
|
|
|
(define (good-enough? guess x)
|
|
(< (abs (- (square guess) x)) 0.001)
|
|
)
|
|
|
|
(define (sqrt x)
|
|
(sqrt-iter 1.0 x)
|
|
)
|
|
|
|
(define (new-if predicate then-clause else-clause)
|
|
(cond (predicate then-clause)
|
|
(else else-clause)
|
|
)
|
|
)
|
|
|
|
(define (new-sqrt-iter guess x)
|
|
"gre v neskoncni loop"
|
|
(new-if (good-enough? guess x)
|
|
guess
|
|
(new-sqrt-iter (improve guess x)
|
|
x
|
|
)
|
|
)
|
|
)
|
|
|
|
(define (abs x)
|
|
(if (> 0 x) (- x) x)
|
|
)
|
|
|
|
(define (better-enough? g1 g2)
|
|
"Sledimo spremembam priblizkov. Ustavimo, ko je sprememba majhen delez priblizka."
|
|
(< (/ (- g1 g2) g1) 0.0001)
|
|
)
|
|
|
|
(define (better-sqrt-iter guess x)
|
|
"Better sqrt. Naloga 1.8."
|
|
(let ((g2 (improve guess x)))
|
|
(if (better-enough? g2 guess)
|
|
g2
|
|
(better-sqrt-iter g2 x)
|
|
)
|
|
)
|
|
)
|
|
|
|
(define (improve-cube-root guess x)
|
|
(/ (+ (* 2 guess) (/ x (* guess guess))) 3)
|
|
)
|
|
|
|
(define (cube-root-iter guess x)
|
|
"Tretji koren"
|
|
(if (good-enough? guess x)
|
|
guess
|
|
(cube-root-iter (improve-cube-root guess x) x)
|
|
)
|
|
)
|