The function f(x) and the series need to end up with the same answer This is my attempt on this task, but it gives me different results and I don't fully understand the concept of series in C++
#include <iostream>
#include <math.h>
#include <cstdlib>
using namespace std;
int main()
{
float x, y1, y2, a;
int n;
cout<<"Enter x: ";
cin>>x;
cout<<"Enter n: ";
cin>>n;
if (x == 0) x = 3.0;
y1 = 1.0/(2.0*x+5.0);
a = 1.0/11;
y2 = a;
cout<<"f(x) = "<<y1<<endl;
if(x > -5.0/2.0 && x < 17.0/2.0){
for (int k = 0; k <= n; k++){
a = (a*(-1)*pow(2.0/11.0,k))/pow(11.0,k);
y2 = y2 + a;
}
}
else{
return 1;
}
cout<<"Sum = "<<y2<<endl;
system("pause");
return 0;
}
I used any x from -2,5 to 8,5 and n up to 100 the results are always different... the function and sum of the series are supposed to have very close, if not equal answers, but it's not in my case..
How am I supposed to do it? would be happy for an explanation)
You should probably just use the correct term for your sum:
a = pow(-2.0 / 11.0 * (x - 3), k) / 11.0;
Note that I combined the terms in the power. The division by 11
may also be moved to the end, saving some operations. But then you would need a different initialization. However, this would also allow you to calculate a
incrementally. Something like this:
//Initialization
a = 1.0;
y2 = a;
double factor = -2.0 / 11.0 * (x - 3);
//...
for (int k = 1; k <= n; k++)
{
a *= factor;
y2 += a;
}
//Finally
cout << "Sum = " << y2 / 11.0f << endl;