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)))
-
\$\begingroup\$ Your edit was rolled back. Please see What should I do when someone answers my question? \$\endgroup\$Phrancis– Phrancis2016年02月25日 21:16:58 +00:00Commented Feb 25, 2016 at 21:16
1 Answer 1
In 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.
-
\$\begingroup\$
(/ 0.00000001 guess)
is not the same as(/ guess 100000000)
; in the former,guess
is in the denominator, whereas in the latter,guess
is in the numerator. But(/ 1 guess 100000000)
could work. Not sure if it's "more readable" at that stage, though. \$\endgroup\$C. K. Young– C. K. Young2016年02月20日 18:04:51 +00:00Commented Feb 20, 2016 at 18:04 -
\$\begingroup\$ @200_success Thank you for points 1,2 and 4. For point 3, I wanted to try and avoid a variable as we haven't done that in the book yet. \$\endgroup\$leancz– leancz2016年02月21日 09:37:03 +00:00Commented Feb 21, 2016 at 9:37
-
\$\begingroup\$ @ChrisJester-Young Yes my way of doing it looks strange, but it helps me to think about what the precision implies. \$\endgroup\$leancz– leancz2016年02月21日 09:39:23 +00:00Commented Feb 21, 2016 at 9:39