I have a sequence.
a1 = 1 - cos(x);
ai = a1 + (-1)^(i-1) * x^(2*i-2) / (2*i-2)!
I need to write this with and without recursion. But it has a different results.
Here is my code: http://codepaste.net/q213q6
I have a sequence.
a1 = 1 - cos(x);
ai = a1 + (-1)^(i-1) * x^(2*i-2) / (2*i-2)!
I need to write this with and without recursion. But it has a different results.
Here is my code: http://codepaste.net/q213q6
I'm going to operate under the assumption that this is homework, if I'm wrong I'll come back and edit this post or repost.
Firstly, you should try to write your factorial function in a tail recursive manner. Though it probably won't make much difference in C, it's good practice.
int helper( int x, int acc ) {
if( x == 0 ) {
return acc;
}
else {
return helper( x - 1, acc * x );
}
}
int factorial( x ) {
helper( x, 1 );
}
Next, you don't generally want to put a loop inside of your recursive functions, that somewhat defeats the point. Think of a recursive call as one iteration with a test and either return or recall.
Since you are performing floating point arithmetic. Different ways of implementation can produce different results. In your case i can think of one place where losses are incurred
currC = pow(x, 2*i-2);
is not equal to
47: currC = currC * x * x;
For more information, http://en.wikipedia.org/wiki/Floating_point#Multiplication