Reputation: 1
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);
}
Please someone help me to solve this. I am being tired of doing this for many time.
Upvotes: 0
Views: 115
Reputation: 1
I got my answer myself. Asking for a guess will solve the problem. Do not need to set the guess like the code I have given. However, I do not know the reason but it solved the problem. Thank you.
Upvotes: 0
Reputation: 393946
You never change root
and num
, and you reset guess
in each call to guess= num/(root+1);
, so you get an endless recursion, leading to StackOverflowError
.
I'm not sure what the correct logic should be, but to prevent the endless recursion you must either pass different values of root
or num
to each recursive call, or don't reset guess
at the start of the method.
Upvotes: 3