求平方根
SUCCESSIVE AVERAGING DUE TO HERON OF ALEXANDRIA
** TO FIND AN APPROXIMATION TO SQRT(X) **
- MAKR A GUESS G
- IMPROVE THE GUESS BY AVERAGING G AND X/G
- KEEP IMPROVING THE GUESS UNTILE IT IS GOOD ENOUGH
USE 1 AS AN INITIAL GUESS
算法思想
(define (try guess x) (if (good-enough? guess x) guess (try (improve guess x) x))) (define (sqrt x) (try 1 x))
参考代码
注:此代码来自https://blog.csdn.net/jazz_charles/article/details/48974029
(define (square x) (* x x)) //定义求平方 (define (average x y) (/ (+ x y) 2)) //定义求平均值 (define (sqrt x) //定义求平方根 (define (accurate guess) //定义判断精确度 (< (abs (- (square guess) x)) 0.001)) (define (improve guess) //定义改进近似值 (average x (/ x guess))) (define (sqrt-iter guess) //定义主体迭代求解 (if (accurate guess) guess (sqrt-iter (improve guess)))) (sqrt-iter 1.0))