在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
#lang racket (define (square x) (* x x)) (define (sqrt-iter guess x) (if (good-enough? guess x) guess (sqrt-iter (improve guess x) x))) (define (improve guess x) (average guess (/ x guess))) (define (average x y) (/ (+ x y) 2)) (define (good-enough? guess x) (< (abs (- (square guess) x)) 0.001)) (define (sqrt x) (sqrt-iter 1.0 x)) (sqrt 9) 3.000000001396984 > 此为SICP中给出的实现方法,使用常规的过程调用能力实现。 下为我在C#中的实现方法。 static void Main(string[] args) result = (num / result + result) / 2; return result; SICP中用比例法改进的算法 1 #lang racket 2 (define (square x) (* x x)) 3 (define (sqrt-iter guess x) 4 (if (good-enough? guess x) 5 guess 6 (sqrt-iter (improve guess x) 7 x))) 8 (define (improve guess x) 9 (average guess (/ x guess))) 10 11 (define (average x y) 12 (/ (+ x y) 2)) 13 14 (define (good-enough? guess x) 15 (< (abs (- (/ (square guess) x) 1) ) 0.00001)) 16 17 (define (sqrt x) 18 (sqrt-iter 1.0 x)) 19 20 21 (sqrt 0.002)
|
请发表评论