C/Cosine Function
Expert: Zlatko - 3/26/2011
QuestionSir,pls help me to get a program to generate the cosine function.I am totally confused,just a beginner in C programming
Hope you will surely find an answer to my question.Thanking you.
AnswerHello Aiswarya
You are asking me how to generate a cosine function which is an unusual question for a beginner. Are you sure your instructor is not asking you to simply use the cos function built into the C math library?
I will assume here that you actually need to generate the cosine function.
Has your instructor suggested a particular formula for calculating the cosine ?
I'll show you the Taylor series expansion method.
cos(x) = 1 - x^2/2! + x^4/4! - x^6/6! + ...
The Taylor series is a series of terms separated by plus and minus. Here x is in radians. If you want to input x in degrees, then your program will need to convert x to radians, before using x in the Taylor series.
You have to decide how many terms you will use to calculate the cosine. As a first attempt, I suggest you make your program as simple as possible, and use no more than 6 terms. This is because each term needs to do a factorial calculation and the factorial gets very large very quickly. 12! is 479001600 and is the most an unsigned four byte integer can hold.
You need a main program with a loop, and a loop counter, which goes from 1 to 6. Lets say your loop counter is i. Notice you have terms like x^2/2!, x^4/4!, or in general x^j/j! where j is two times i. Also notice that the term is subtracted from the result when i is odd, and added to the result if i is even. You can decide if a number is odd or even based on if (number % 2) is zero or not. There are other ways too, but lets just focus on one for now.
Now, I will give you the outline of the program. It is up to you to fill in the rest according to my instructions. Show me your effort, and I will help you more.
Best regards
Zlatko
#include <math.h>
#include <stdio.h>
unsigned int factorial(unsigned int j)
{
/* calculate and return the factorial of j */
}
double calculateTerm(double x, int j)
{
/* Calculate and return a term. A term of the Taylor series for cosine is
x^j/j!
You can use the pow function available from the C library to calculate x^j
and use the factorial function which you will write to calculate j factorial
*/
}
#define PI 3.1415926535897932384
int main(void)
{
double deg;
double rad;
int i;
double result = 1;
printf("Input x in degrees: ");
scanf("%lf", °);
/* convert x from degrees to radians */
rad = deg * PI / 180;
for(i = 1; i <= 6; ++i)
{
int j = 2*i;
double term = calculateTerm(rad, j);
/* add term to result if i is even and subtract term from result if i is odd */
}
printf("cos(%lf degrees) = %lf\n", deg, result);
}