I am trying to create a method that is tail recursive and finds the sum
of an equation ( i / 2i + 1
) where i
needs to increment 1-10
. I'm having trouble with how to reach the base case and make the recursion cease.
This is what I have so far:
public class SumSeries {
public static void main(String[] args) {
System.out.println(sumSeries());
}
public static double sumSeries(){
int i = 10;
if (i == 0)
return 0;
else
return (i / (2 * i + 1));
}
}
I think that you are looking something like that:
public class SumSeries {
public static void main(String[] args) {
System.out.println(sumSeries(10,0));
}
public static double sumSeries(int i,double result){
if (i == 1)
return result;
else{
double res = result + (i / (double)(2 * i + 1));
return sumSeries(i-1,res);
}
}
}
If you want recursion, your method should look something like this:
public class SumSeries {
public static void main(String[] args) {
System.out.println(sumSeries());
}
// if you want to keep the argument-less method in main but want to calculate
// the sum from 1 - 10 nevertheless.
public static double sumSeries() {
return sumSeries(10);
}
public static double sumSeries(int i){
if (i == 0) {
return 0;
}
else {
// The cast to double is necessary.
// Else you will do an int-division here and get 0.0 as result.
// Note the invocation of sumSeries here inside sumSeries.
return ((double)i / (2 * i + 1)) + sumSeries(i-1);
}
}
}
If you're looking for a way to find this sum :
(1 / 2*1 + 1) + (2 / 2*2 + 1) + (3 / 2*3 + 1) + ... + i/(2i + 1)
You could try this :
public double sumSeries(int i) {
if (i == 1) { // base case is 1 not 0
return 1/3;
} else {
double s = i / (2.0 * i + 1.0);
return s + sumSeries(i - 1);
}
}
Your method is not recursive. A recursive method needs to use 'himself' and at a certain condition it stops. An example:
public static double sumSeries(int x) {
if (x == 0)
return x;
else {
return x + sumSeries(x - 1);
}
for your example, something like this would fit:
public static double sumSeries(double x) {
if (x == 0)
return x;
else
return (x / (2 * x + 1)) + sumSeries(x - 1.0);
}
If I understood your algorithm correctly :) If not, edit the algorithm :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.