I'm doing a practice question in which I have the answer to(below), but I'm having a hard time understanding how to solve the question. Can someone explain how they knew to write the code properly? Is it some kind of proof that I do not know? I don't understand how they knew to multiply things like this "sum+=pow(−1, i ) ∗ ( i +1)∗pow ( x , i ) ;"
It is known that (1 + x)−2 = 1 − 2x + 3x^2 − 4x^3 + 5x^4 − 6x^5 + ... for x^2 <
We would like a function to compute this series for n terms where n and x can be specified bythe client. If x is outside its specified range the function should return 0. Write a function, ingood C++ code, that returns the n
th order approximation of (1 + x)−2 using this method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
double series ( int n , double x ){
double sum=0;
int i =0;
if (pow (x,2)>=1){
return 0;
}
else
{
while ( i<n ){
sum+=pow(−1, i ) ∗ ( i +1)∗pow ( x , i ) ;
i ++;
}
}
return sum ;
}
Would it be correct to do it like this with for loops? Also, what am I looking to output? It asks for nth order of approximation, does that just mean the nth term in the series, or the sum of the series until the nth term?
Would you call -12*0.5^11 (=~ -0.0059) a good approximation for 1.5^(-2) (i.e. 0.444)? No.
Series like this are approximations. Each additional term brings it a step closer to the real thing. Hence the sum. However, you don't calculate infinite number of terms, becase (1) it is too expensive, and (2) floating point numbers have finite presicion.