Reputation: 43
The user is meant to give the value of "x" and "n" in order to calculate cos x using taylors series approximation ( you can check out its formula here: http://campusdematematicas.com/wp-content/uploads/2012/05/serie-taylor-funcion-coseno.gif) where the "k" value is the "i" in the code below.
The thing is that i dont know what i have done wrong, because it doesn't give me the proper value of cos x.
The input i just tried was x=3.14, and n=6. And the result it was supposed to give me was cosx = -1.00 Instead, it gave me: 1.14
By the way, it does not work for 0, as it should give cos (x) = 1.00, and it gives 0.000000 instead
#include <stdio.h>
int main(){
double x, n, m;
int i = 0, j, l, k = -1;
double g = 0.0;
unsigned long long p = 1;
printf("Introduce the value of x (real): ");
scanf("%lf%*c", &x);
m = x;
printf("\nIIntroduce the value of n (natural): ");
scanf("%lf%*c", &n);
while (i <=n){
for (l=1; l < (i*2); l++){
m *= x;
}
for (j=1; j <= (2*i); j++){
p *=j;
}
if (i%2 == 0){
k = 1;
}
g += (double) (m/p)*(k);
p = 1;
k = -1;
m = x;
i++;
}
printf("\ncos(%.2lf) = %lf\n", x, g);
}
Upvotes: 2
Views: 389
Reputation: 153303
Wrong initialization for m
. Code is summing odd powers of x
, rather than the even ones.
// m = x;
m = 1.0;
Output
cos(0.00) = 1.000000
cos(1.05) = 0.500460 // cos(60 degrees) --> 0.5
cos(1.57) = 0.000796 // cos(90 degrees) --> 0.0
cos(3.14) = -0.999899
Upvotes: 1