sqrt.java

publicclass Sqrt {
publicstaticvoidmain(String[] args){

// read in the command-line argument
double c = Double.parseDouble(args[0]);
double epsilon =1e-15;// relative error tolerance
double t = c;// estimate of the square root of c

// repeatedly apply Newton update step until desired precision is achieved
while(Math.abs(t - c/t)> epsilon*t){
            t =(c/t + t)/2.0;
}

// print out the estimate of the square root of c
        System.out.println(t);
}

}
intput :c = 16
step1:t = 8.5
8.5 - 16/8.5 > 1e-15*8.5
step1: t = (16/8.5+8.5)/2.0=5.2
...
...
当t - c/t的值小于相对误差时则输出t;

posted on 2013-04-30 23:29  chateldon  阅读(248)  评论(0)    收藏  举报

导航