【发布时间】:2016-07-23 14:54:25
【问题描述】:
import java.util.*;
public class NRootx {
public static Double NRmethod (Double num, int root, Double guess){
guess= num/(root+1); //first guess
Double guess_output=1.0;
for (int i=1;i<=root; i++)
{
guess_output *= guess;
}
Double error= guess_output-num;
error = error * 0.001;
guess = guess - error;
if (Math.abs(error)>=0.000001)
return NRmethod(num, root, guess); //Recursion
else
return guess;
//I can't find out the problem now. Java.lang.StackOverFlow error is showing.
}
}
}
// Main function
public static void main(String[] args) {
Double x;
int n;
Scanner sc= new Scanner (System.in);
System.out.println("Enter the value of x: ");
x=sc.nextDouble();
System.out.println("Enter the value of n: ");
n=sc.nextInt();
Double guess=x/(n+1);
Double ans= NRmethod(x,n,guess);
System.out.println("The value of y is ="+ans);
}
请有人帮我解决这个问题。我厌倦了这样做很多次。
【问题讨论】:
-
与
StackOverflowError问题无关,但使用double而不是Double,所以你不需要创建不必要的Double对象。 -
还有:
guess_output = Math.pow(guess, root);,不需要 for 循环。
标签: java recursion newtons-method