求平方根
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))
求两数之和
迭代
(define (+ x y)
(if (= x 0)
y
(+ (-1+ x) (1+ y))))
斐波那契数列
(define (fib n)
(if (< n 2)
n
(+ (fib (- n 1))
(fib (- n 2)))))
求和算法
等差数列求和
[sum _{i=a}^{b}i
]
(define (sum-int a b)
(if (> a b)
0
(+ a
(sum-int (1+ a) b))))
莱布尼茨公式求π/8
[sum_{i=a}^{b}frac{i}{i(i+2)}
]
(define (pi-sum a b)
(if (> a b)
0
(+ (/ 1 (* a (+ a 2))))
(pi-sum (+ a 4) b))))