I'm new to programming. My uni course has a programming module included (C) and i need some help figuring what has happened to my code.
For sin(x) I have:
#include <stdio.h>
#include <math.h>
/*Taylor series expansion of sin(x)*/
int main(void)
{
float x, ans;
int i, fac, n, sign;
printf("Value for x: ");
scanf("%f", &x);
printf("Value for n: ");
scanf("%d", &n);
for (i=1, fac=1, ans=x, sign=-1; i<=n; i++)
{
fac*=(2*i+1)*2*i;
ans+=sign*pow(x,2*i+1)/fac;
sign*=-1;
}
printf("Answer is %f.\n", ans); /*Taylor expansion completed*/
return 0;
}
I've now (with help) fixed expansion for sin(x). But for the full question I am having difficulty getting right.
So far my expansion for f(x)=sin(x)+cos(x) looks like this:
#include <stdio.h>
#include <math.h>
int main(void)
{
int x, sin, cos;
float i, j, fac1, fac2, n, sign, ans;
printf("Value for x: ");
scanf("%f", &x);
printf("Value for n: ");
scanf("%d", &n);
for (i=1, fac1=1, fac2=1, sin=x, cos=1, ans=1+x, sign; i<=n; i++)
{
fac1*=(2*i+1)*2*i; /*factorial expansion for sin(x)*/
fac2*=2*i*(2*i-1); /*factorial expansion for cos(x)*/
sin+=sign*pow(x,2*i+1)/fac1; /*Series expansion of sin(x)*/
cos+=sign*pow(x,2*i)/fac2; /*Series expansion of cos(x)*/
sign*=-1;
ans=sin+cos; /*Final step*/
}
printf("Answer is %f.\n", ans); /*Taylor expansion completed*/
return 0;
}
I assumed this would work, but for example plugging in 1 an 10 gives 1065353216 (basically grossly wrong). Any suggestions with this one?