Reputation: 1
I have to write program which calculates value cos(x) with use Taylor Series. for a= -7 to 7 program work. problem is when i use value a>7 and the same a<-7.
#include <iostream>
#include <cmath>
using namespace std;
unsigned long long silnia(int n)
{
unsigned long long a = 1;
while(n)
a *= n--;
return a;
}
void taylor(int x)
{
long double suma=0;
for (int n=0; n<=10; n++)
{
suma+=pow(-1,n)*(pow(x,2*n)/silnia(2*n));
cout << pow(-1,n) << " * " << pow(x,2*n) <<" / " << silnia(2*n) << " = " << pow(-1,n)*(pow(x,2*n)/silnia(2*n))<<endl;
}
cout << "taylor: "<<suma<< endl;
}
int main() {
int a=5;
taylor(a);
cout << "cos: " << cos(a);
}
output onli taylor and cos for a=5:
taylor: 0.283664
cos: 0.283662
output for a = 9
1 * 1 / 1 = 1
-1 * 81 / 2 = -40.5
1 * 6561 / 24 = 273.375
-1 * 531441 / 720 = -738.112
1 * 4.30467e+007 / 40320 = 1067.63
-1 * 3.48678e+009 / 3628800 = -960.864
1 * 2.8243e+011 / 479001600 = 589.621
-1 * 2.28768e+013 / 87178291200 = -262.414
1 * 1.85302e+015 / 20922789888000 = 88.5647
-1 * 1.50095e+017 / 6402373705728000 = -23.4436
1 * 1.21577e+019 / 2432902008176640000 = 4.99719
taylor: -0.149111
cos: -0.91113
sorry for my bad english and thanks for help!
Upvotes: 0
Views: 397
Reputation: 571
Taylor series are mean to approximate a function around a specific pivot (most commonly 0). But, as you go further from that pivot, the approximation becomes more and more wrong.
Here is a plot, generated by Wolfram alpha, which shows cos(x)
and Tailor Series approximation that function at varying degrees(=highest exponent of derivative):
As you can see, the best approximation(10th degree) is only close for values up to ~±6. If you want values that are closer to the true values, you will have to increase your steps or change your pivot!
To learn more about Tailor Series you can do some more research or watch this intuitive video by 3b1b.
Upvotes: 1