patternMinor
Square root calculation in Scheme (SICP Exercise 1.7)
Viewed 0 times
schemecalculationsquareexerciserootsicp
Problem
I have done exercise 1.7 in SICP (calculate square root precision when change in guesses is under a certain value), but I am calling the change-in-precision function twice in each iteration, which disturbs me. I wonder if there is a better way to implement this.
(define (average . ns) (/ (apply + ns) (length ns)))
(define (change-in-precision guess x)
( - (- guess (average guess (/ x guess)))))
(define (sqrt guess x)
(if (< (abs (change-in-precision guess x)) (/ 0.00000001 guess))
(+ guess (change-in-precision guess x))
(sqrt (+ guess (change-in-precision guess x)) x)))Solution
In
In
To eliminate the repeated call to
The two branches of the
change-in-precision, you can avoid the negation by swapping the operands for the subtraction.In
sqrt, if the guess is already close enough, why not just return guess? To eliminate the repeated call to
change-in-precision, use a let to define a variable delta.The two branches of the
if should be indented.Context
StackExchange Code Review Q#120625, answer score: 2
Revisions (0)
No revisions yet.