您的位置:首页 > 编程语言 > Java开发

Java计算平方根算法

2016-12-23 15:24 330 查看
public class SqrtTest{
public static double mySqrt(double num, double offSet){
if(num <= 0) return 0;
double flag = 10.0;
int counter = 0;
do{
if (Math.abs(flag*flag - num) < offSet) {
System.out.println(flag);
return flag;
}else{
System.out.println(flag);
counter++;
flag = (flag + num/flag)/2;
}
}while(counter<100);
return -1;
}
public static void main(String[] args){
System.out.println(mySqrt(12545, 0.2));
}
}


上述方法是g=(g+x/g)的方法。若不知道该方法,亦可用二分法来逼近。是偶数次开方时,初始下界为0,上初始界为x;奇数次开方时,初始下界为-|x|,上初始界为|x|。后续二分查找直至逼近或者到达搜索次数退出。

public class MySqrt{
public static double doMySqrt(double num, double offSet, int sqrtNum){
double low = 0, high = 0;
if(sqrtNum <= 0){
return 0;
}else if(sqrtNum % 2 == 0){
high = num;
}else{
low = -Math.abs(num);
high = Math.abs(num);
}
int counter = 0;
double flag = (low + high)/2;
do{
if (Math.abs(Math.pow(flag, sqrtNum)-num)<offSet) return flag;
if(Math.pow(flag, sqrtNum)>num){
high = flag;
}else{
low = flag;
}
flag = (low + high)/2;
counter ++;
}while(counter < 100);
return 0;
}
public static void main(String[] args){
System.out.println(doMySqrt(-45, 0.1, 3));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: