Compute the Cosine Function of an angle x using the infinite series expansion. - C Data Type

C examples for Data Type:float

Introduction

The formula of the infinite series expansion is given here:

cos x = 1 - x2/2! + x4/4! - x6/6! +...

Here, x is in radians, and it takes values in the range -1 <= x <= 1.

Demo Code

#include <stdio.h>

int main(){//from   w  w w.  j  a v  a  2  s.c  o m
        double cosine, x = 0.7, z;
        int j, q, flag, factorial, sign;
        char ch;

        cosine = 0;
        sign = -1;
        
        for (int i = 2; i <= 10; i += 2)
        {
            z = 1;
            factorial = 1;

            for (j = 1; j <= i; j++)
               z = z * x;
            factorial = factorial * j;
            cosine += sign * z / factorial;
            sign =  - 1 * sign;
        }
        cosine = 1 + cosine;

        printf("Cosine of %lf is %lf\n", x, cosine);

        return(0);
}

Result


Related Tutorials