为什么我不能使用此代码找到sqrt?

时间:2016-12-06 18:19:03

标签: java sqrt

我试图找到一种方法来获得一个没有内置插件的sqrt并且出现了这个,不幸的是它不能工作,我不知道为什么

    double num=0;
    while ((num*num)!=this.first)
        num=num+0.0001;
    return num;

3 个答案:

答案 0 :(得分:3)

你不会得到完全平等。你可以想象得到真正的平方根的0.0001,但就是这样。但num*num并不完全等于this.first,除非它实际上是0.0001的倍数的平方。

while ((num * num) < this.first)可能更接近你想要的东西。

答案 1 :(得分:1)

使用此:

public class FindSqrt {

public static void main(String[] strings) {

    double num = 3;
    System.out.println(sqrt(num, 0, num));
}


private static double sqrt(double num, double min, double max) {
    if (max-min<=0.0002) min=max;
    double middle = (min + max) / 2;
    double x = middle * middle;
    if ((num>=x&&num-x<=0.02)||(x>=num&&x-num<=0.02)) {
        return middle;
    } else if (x < num) {
        return sqrt(num, middle, max);
    } else {
        return sqrt(num, min, middle);
    }
}
}

如果你需要一个没有递归的解决方案(但是循环没问题,以下工作):

public class FindSqrt {

public static void main(String[] strings) {

    double num = 131072;
    System.out.println(sqrt(num, 0, num));
}


private static double sqrt(double num, double min, double max) {
    boolean done = false;
    double answer = 0;

    while(!done){
        if (max-min<=0.0002) min=max;
        double middle = (min + max) / 2;
        double x = middle * middle;
        if ((num>=x&&num-x<=0.02)||(x>=num&&x-num<=0.02)) {
            done = true;
            answer = middle;
        } else if (x < num) {
            min = middle;
        } else {
            max = middle;
        }
    }
    return answer;



}
}

但是,在任何一种情况下,您都可以使用它来查找数字的平方根&lt; = 131072

答案 2 :(得分:0)

从谷歌宣传:

What is floating point error?
The most common situation is illustrated by the decimal number 0.1.
Although it has a finite decimal representation, in binary it has an
infinite repeating representation. Thus when = 2, the number 0.1 lies
strictly between two floating-point numbers and is exactly representable
by neither of them.

所以,填写你的例子9,你的循环可能看起来像:

num = 0; add 0.0001 -> num is now 0.000099999999
add 0.0001 -> num is now 0.000199999999998
add 0.0001 -> num is now 0.000299999999997
etc...
add 0.0001 -> num is now 2.9999999999953667
add 0.0001 -> num is now 3.000099999994321

因此,您与3的确切比较将无法匹配。