用java编写的快速开平方根的精准算法
发布一个本人原创的求平方根的算法。
本算法不是穷举法,而是非常高效的一种算法。
具体思路是从第一位小数开始验证,找出最合适大小的数字;
然后找第二位小数,再第三位。。。每找一位就验证10次(从0-9)。
效率比较:穷举法在计算小数点后6位的平方根时,至少要进行一百万次循环。
本算法理论上只需10x6次循环即可得出较精确的结果。
下面是代码:
文件MS.java内容:
public class MS {
public MS() {
// TODO Auto-generated constructor stub
//测试和验证
System.out.println("2的平方根(精确到小数点后6位):" + mySqr(2d,6));
System.out.println("2的平方根(jdk系统自带的方法):" + Math.pow(2d, 0.5d));
}
public double cifang(double d,int cf){
double total=1d;
for(int j=0;j<cf;j++){
total=d*total;
}
return total;
}
public int getIntPart(double d){
int myIntPart=(int)d;
if(myIntPart==1){
return 1;
}
int miniSqr=0;
for(int i=0;i<myIntPart;i++){
if(i*i>myIntPart){
break;
}else{
miniSqr=i;
}
}
return miniSqr;
}
public double getSmallDAccuracy(double d,int myint,double result,int accuracy){
double small_d_accuracy=0d;
double differ_old=(double)myint*myint;
for(int j=0;j<10;j++){
double small_d=((double)j)/cifang(10d,accuracy);
double temp=result+small_d;
double differ=Math.abs(d-cifang(temp,2));
if(differ<differ_old){
differ_old=differ;
small_d_accuracy=small_d;
}
}
return small_d_accuracy;
}
public double getCloser(double d,double result,double small_d1,double small_d2,double small_d3){
double temp1=result + small_d1;
double temp2=result + small_d2;
double temp3=result + small_d3;
double differ1=Math.abs(d - cifang(temp1,2));
double differ2=Math.abs(d - cifang(temp2,2));
double differ3=Math.abs(d - cifang(temp3,2));
if(differ1<=differ2 && differ1<=differ3){
return small_d1;
}else if(differ2<=differ1 && differ2<=differ3){
return small_d2;
}else{
return small_d3;
}
}
public double mySqr(double d,int accuracy){
int myint=getIntPart(d);
if(accuracy==0){
return myint;
}
double result=(double)myint;
for(int i=1;i<=accuracy;i++){
double small_dd=0d;
if(accuracy>=2){
//微调,前一位小数加一减一,得出两个结果
double small_d1=getSmallDAccuracy(d,myint,(result + 1d/cifang(10d,accuracy-1)),i);
double small_d2=getSmallDAccuracy(d,myint,(result - 1d/cifang(10d,accuracy-1)),i);
//结束微调
//不微调的结果
double small_d3=getSmallDAccuracy(d,myint,result,i);
//比较微调之后的三个结果,获取离结果最近的一个
small_dd=getCloser(d,result,small_d1,small_d2,small_d3);
}else{
small_dd=getSmallDAccuracy(d,myint,result,i);
}
result+=small_dd;
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new MS();
}
}运行结果:
2的平方根(精确到小数点后6位):1.4142139999999999
2的平方根(jdk系统自带的方法):1.4142135623730951
对此程序略作修改,可以求3次方根、4次方根、多次方根等等。
















