Beginner c++ math question

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 ;
}
Last edited on
Look at any term in the series (in the math equation). They are all in form
s Nx^M

Where N = M+1
and
s is + if M is even
s is - if M is odd

(-1)^M is +1 if M is even and -1 if M is odd. One could use other methods than pow() there.
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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Example program
#include <iostream>
#include <string>
#include <cmath>
double series(double x, int n);
int main()
{

  std::cout << series(.25,5);
}

double series(double x, int n){
double sumy=0;
if(pow(x,2)>=1){
   return 0;
        }
            else{
                  for(int i=0;i<n;i++){
           sumy += pow(-1,i)*pow(x,i)*(1+i);
        
        }
}
        return sumy;

}
Last edited on
The for and while are equivalent.

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.
Okay, so I need the sum. MY answer for the code above is .64, is that correct? It's not .444

My answer keeps giving me .64 for both codes. Is that correct for x=.25 and n=(I tried everything from 5-100+, nearly the same result.)
Topic archived. No new replies allowed.