package com.heu.wsq.ali;
import java.text.DecimalFormat;
public class MySqrt {
public static double EPSILON = Math.pow(0.1, 10);
public double sqrt2(){
double low = 1.4, high = 1.5;
double mid = (low + high) / 2;
while(high - low > EPSILON){
if(mid * mid > 2){
high = mid;
}else{
low = mid;
}
mid = (low + high) / 2;
}
return mid;
}
public double newton(double x){
if (Math.abs(x * x - 2) > EPSILON){
return newton(x - (x * x - 2) / (2 * x));
}else {
return x;
}
}
public static void main(String[] args) {
MySqrt ms = new MySqrt();
double ans = ms.newton(1.5);
DecimalFormat df = new DecimalFormat("#.0000000000");
System.out.println("2的开方为:" + df.format(ans));
System.out.println("2的开方为:" + ans);
}
}