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

why can't I find sqrt using this code?

我试图找到一种方法来获得没有内置函数的 sqrt 并想到了这个,不幸的是它行不通而且我不知道为什么

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

你不会得到完全相等的。您可能会在真平方根的 0.0001 以内,但仅此而已。但是 num*num 不会完全等于 this.first 除非它实际上是 0.0001.

的倍数的平方

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

从 Google 中提取:

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 的精确比较将不匹配。

使用这个:

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);
    }
}
}

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

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;



}
}

但是,在任何一种情况下,您都可以使用它来求数字的平方根<=131072