Reputation: 255
I am trying to create a recursive method to compute a series in java 1/i.
Here is my code:
public static double computeSeries(int n) {
if (n == 1)
return 1;
else
return (1/n) + computeSeries(n - 1);
}
where 'n' is passed through the main method. However it doesn't exactly work correctly. FE when I type in 3, it returns 2.0, where I calculated it to be 1.8, and if I use 2, it gives me 1.0
Upvotes: 2
Views: 92
Reputation: 1232
As most others have said, you need to convert the values to double
before performing operations. Also, and this may just be personal preference, you may not want to have n
calls of computeSeries
running before they can all be completed.
Edit: After thinking more, using the for loop as I did below, there is no need for an extra method to calculate each term in the series. You can simply do the following
public static double computeSeries(int n) {
double sum = 0.0;
for(int i=1; i<=n; i++){
sum += (1.0/(double)i);
}
return sum;
}
Upvotes: 0
Reputation: 21975
While you're going to work with decimals, you might at least want to have a double
as input
public static double computeSeries(double n)
However, if you only want the method to have an int
as input, you might want to change 1/n
to 1.0/n
this will result to an operation of type double
instead of int
This is called Promotion
If either operand is of type double, the other is converted to double.
Upvotes: 4
Reputation: 14255
Your first division will be 0
in most of the cases, since you're calculating with integers.
Instead use one of
return (1.0 / n) + computeSeries(n - 1);
return (1 / (double) n) + computeSeries(n - 1);
public static double computeSeries(double n) {
Bonus: You should take care of n = 0
to prevent a java.lang.ArithmeticException
.
Upvotes: 0
Reputation: 3075
First part of your result (1/n) is truncated to an int:
return (1/n) + computeSeries(n - 1);
Force calculations to be done in a double type by changing 1 to 1.0 (then it's a double):
return (1.0/n) + computeSeries(n - 1);
Upvotes: 3
Reputation: 86774
1/n
You are calculating in integers. This is always ZERO unless n == 1
Upvotes: 0