Search code examples
ctrigonometrytaylor-series

Using a Taylor series to find sin(x) in C


I have an assignment where my professor wants us to calculate sin(x) using a taylor series. He wants us to stop the iterations when the difference between two consecutive fractions is less than 10^-6.

I ended up approaching the problem by saying that for example x^5/5! is the same as (x^3/3!) * (x^2/4*5) and that this is true for all the fractions. So I can just keep the previous fraction I calculated and use it on the next iteration. Problem is the number I end up with is a bit off from its actual sin and I can't figure out why.Thanks in advance. Here is my code:

#include <stdio.h>
#include <Math.h>
#define pi 3.14159265358979323846

int main(int argc, int **argv){
    
    int sign = -1, pwr = 3;
    double previous, current, rad,sum, degr;
    printf("Calculating sin using Taylor Series\n\n");
    printf("Give degrees: ");
    scanf("%lf", &degr);
    
    // translate to rads
    rad = degr*(pi/180);
    
    sum = rad;
    previous = rad;
    do{
        current = (previous * pow(rad, 2))/(pwr* pwr-1);
        
        sum += sign*current;
        pwr += 2;
        sign *= -1;
    }
    while(abs(current - previous) > pow(10, -6));
    
    printf("The sin of %lf degrees is ", degr);
    printf("%.6f\n", sum);
    printf("%.6f", sin(rad));
    return 0;   
}

Solution

  • You're using the abs function, which expects an int and returns an int. This results in the loop existing if the difference between the current and prior term is less than 1 as it will set diff to 0.

    Instead, you want fabs which expects and returns a double.