在看 SICP 这本书,做到练习 1.8 的时候,Newton method 实现的代码如下:
(define (cubrt-iter guess x)
(if (good-enough? guess x)
guess
(cubrt-iter (improve guess x)
x)))
(define (improve guess x)
(third guess (/ x guess)))
(define (third x y)
(/ (+ (/ x (* y y))
(* 2 y))
3))
(define (good-enough? guess x)
(< (abs (- (cube guess) x)) 0.001))
(define (cube x) (* x x x))
(define (abs x)
(cond ((> x 0) x)
((= x 0) 0)
((< x 0) (- x)))
)
(define (cubrt x)
(cubrt-iter 1.0 x))
使用牛顿公式做开立方,但是不知道为什么执行的时候没有结果,大家帮我看下原因吧 :(
贴已经解决了,third里面的参数搞反了,正式代码解决如下:
(define (cubrt-iter guess x)
(if (good-enough? guess x)
guess
(cubrt-iter (improve guess x)
x)))
(define (improve guess x)
(/ (+ (/ x (* guess guess))
(* 2 guess))
3))
(define (good-enough? guess x)
(< (abs (- (cube guess) x)) 0.001))
(define (cube x) (* x x x))
(define (abs x)
(cond ((> x 0) x)
((= x 0) 0)
((< x 0) (- x)))
)
(define (cubrt x)
(cubrt-iter 1.0 x))
1
tan90ds 2016-10-24 10:22:53 +08:00
你的 improve 函数和 third 函数有点怪,没仔细看但是感觉不像是正确的牛顿迭代法。
|