输入int k,double delta,
求k的正平方根,误差位正负delta,
如k=8,delta=2.3,根号8=2.8284…,输出[2.8-2.3,2.8+2.3]=[0.5,5.1]
//输入
int k=8;
double delta=2.3;
//
double jinduzhi=1;//最小精度
int jindu=0;//小数个数
String str = delta + "";
jindu=str.length() - (str.indexOf(".") + 1);
for (int i = 0; i < jindu; i++) {
jinduzhi/=10;
}
double[] ans=new double[2];
ss(k,0,k,delta,jinduzhi,ans,-1,jindu);
ss(k,0,k,delta,jinduzhi,ans,1,jindu);
System.out.println(Arrays.asList(ans[0],ans[1]));
public void ss(int k,double l,double r,double delta,double jinduzhi,double[] ans,int label,int jindu){
double mid=0;
while(l<=r){
mid=l+((r-l)/2);
double d=dd(mid-delta*label,jindu);
if(d*d>k){
r=mid-jinduzhi;
}else if (d*d<k){
l=mid+jinduzhi;
}
}
if(label==1){
ans[1]=dd(r,jindu);
}else {
ans[0]=dd(r,jindu);
}
}
//去掉精度外的数
public double dd(double d,int jindu){
String s=d+"";
return Double.valueOf(s.substring(0,s.indexOf('.')+jindu+1));
}
输出:
[0.5, 5.1]
另外一例:
//输入
int k=9999;
double delta=10;
输出:
[89.9, 109.9]