簡體   English   中英

遞歸算法計算平方根和立方根

[英]Recursive algorithm to calculate the square root and cube root

當我運行我的代碼工作有時但其他我得到這個錯誤:

Exception in thread "main" java.lang.StackOverflowError       
at squareroot.SquareRoot.GetSquareRoot (SquareRoot.java: 9)   
at squareroot.SquareRoot.GetSquareRoot (SquareRoot.java: 13)   
at squareroot.SquareRoot.GetSquareRoot (SquareRoot.java: 13)`

我正在檢查我的代碼並且我沒有進入無限循環,請問我該如何解決這個問題?謝謝。

public static double GetSquareRoot(double n, double low, double high) {
    double sqrt = (low + high) / 2;
    if (sqrt*sqrt > n)
        return GetSquareRoot(n, low, sqrt);
    if (sqrt*sqrt < n)
        return GetSquareRoot(n, sqrt, high);
    return sqrt;
}
public static double Sqrt(double n){
    return GetSquareRoot(n, 0, n);
}

public static double GetCubicRoot(double n, double low, double high) {
    double cbrt = (low + high) / 2;
    if (cbrt*cbrt*cbrt > n)
        return GetCubicRoot(n, low, cbrt);
    if (cbrt*cbrt*cbrt < n)
        return GetCubicRoot(n, cbrt, high);
    return cbrt;
}
public static double Cbrt(double n) {
    return GetCubicRoot(n, 0, n);
}

public static void main(String[] args) {
    Scanner Input = new Scanner(System.in);

    double n = Input.nextDouble();
    double sqrt = Sqrt(n);
    double cbrt = Cbrt(n);

    System.out.println("Raiz cuadrada igual a: "+ sqrt);        
    System.out.println("Raiz cubica igual a: "+ cbrt);  

}

您的結果不可能達到最終條件,因為乘以數字不太可能產生確切的數字,您必須引入誤差幅度,因為平方根通常不精確,浮點算法使用近似值,因為浮點限制。

public static double GetSquareRoot(double n, double low, double high) {
    double errorMargin = 0.001;        
    double sqrt = (low + high) / 2;
    double diff = sqrt*sqrt - n;
    if ( diff > errorMargin)
        return GetSquareRoot(n, low, sqrt);
    if ( -diff > errorMargin)
        return GetSquareRoot(n, sqrt, high);
    return sqrt;
}

您正在停止條件是“if n == num”而n和num是double。 已知Double或Float數字不精確,因此可能永遠不會滿足此條件。 而是使用它

if(Math.abs(sqrt*sqrt - n) < .001)
     return sqrt;

當兩個數字之間的差異變得“足夠小”時,這將停止。

當您使用double時,您應該使用delta double值。 因為您的計算值可能與您預期的不相等。

bool CompareDoubles2 (double A, double B) 
{
   diff = A - B;
   return (diff < EPSILON) && (-diff > EPSILON);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM