Taylor expansion of function, f(x)=sin(x)+cos(x) in C programming has an output error. Any suggestions?

1.3k views Asked by At

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?

2

There are 2 answers

12
BLUEPIXY On
#include <stdio.h>
#include <math.h>

int main(void){
    float x, a, f;
    int i, n, sign;

    printf("Value for x: ");
    scanf("%f", &x);

    printf("Value for n: ");
    scanf("%d", &n);

    for (i=1, f=1.0, a=x, sign=-1; i<=n; i++){
        f *= (2*i+1)*2*i;
        a += sign * pow(x, 2.0*i+1) / f;
        sign *= -1;
    }

    printf("Answer is %f.\n", a); /*Taylor expansion completed*/

    return 0;
}
12
ryanpattison On

The expansion should have (-1)i in the numerator. And you should use an int i as it is a loop variable and would go against conventions otherwise.

a = a + (pow(-1,i) * pow(x, (2 * i) + 1)) / f; /* Expansion sum */

or replace pow(-1, i) with (i & 1 ? -1 : 1) where i is an int.