#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)
{
double num1;
int num2;
Console.WriteLine("请输入要开方的值:");
num1 = float.Parse(Console.ReadLine());
Console.WriteLine("请输入精度");
num2 = Int32.Parse(Console.ReadLine());
num1 = sqrt(num1,num2);
Console.WriteLine(num1);
Console.ReadLine();
}
static double sqrt(double num,int num1)
{
double precision = Math.Pow(0.1, num1);//定义精度
double result = 1;//定义结果
while (Math.Abs( Math.Pow((num / result + result)/2, 2) - num) > precision)//
{
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)