Program 7
Develop a program to compute
sin(x)/cos(x) using
Taylor series approximation and compare the result with the
built-in library function. The program implements Taylor series
expansion for both sine and cosine functions and demonstrates numerical analysis techniques.
Algorithm
- Initialize: Define number of terms for Taylor series approximation
- Create Factorial Function: Implement function to calculate n!
- Taylor Sin Function: Compute sin(x) using series: x - x³/3! + x⁵/5! - ...
- Taylor Cos Function: Compute cos(x) using series: 1 - x²/2! + x⁴/4! - ...
- Input Angle: Read angle value in radians from user
- Calculate Approximation: Compute tan(x) = sin(x)/cos(x) using Taylor series
- Library Comparison: Calculate tan(x) using built-in tan() function
- Display Results: Show both results and compute difference for analysis
Flowchart
START
→
Input x
→
Taylor sin(x)
→
Taylor cos(x)
→
tan(x) = sin(x)/cos(x)
→
Library tan(x)
→
Compare & Display
→
STOP
Code
#include <stdio.h>
#include <math.h>
#define TERMS 10 // Number of terms for approximation
// Function to compute factorial
double fact(int n) {
double f = 1;
for (int i = 1; i <= n; i++)
f *= i;
return f;
}
// Function to compute sin(x) using Taylor series
double taylor_sin(double x) {
double sum = 0;
for (int i = 0; i < TERMS; i++) {
int power = 2 * i + 1;
double term = pow(-1, i) * pow(x, power) / fact(power);
sum += term;
}
return sum;
}
// Function to compute cos(x) using Taylor series
double taylor_cos(double x) {
double sum = 0;
for (int i = 0; i < TERMS; i++) {
int power = 2 * i;
double term = pow(-1, i) * pow(x, power) / fact(power);
sum += term;
}
return sum;
}
int main() {
double x;
printf("Enter angle in radians: ");
scanf("%lf", &x);
double sinx = taylor_sin(x);
double cosx = taylor_cos(x);
// Taylor approximation
double approx_tan = sinx / cosx;
// Library function
double builtin_tan = tan(x);
printf("\nUsing Taylor Series:\n");
printf("sin(x) ≈ %.6lf\n", sinx);
printf("cos(x) ≈ %.6lf\n", cosx);
printf("tan(x) ≈ %.6lf\n", approx_tan);
printf("\nUsing Library Function:\n");
printf("tan(x) = %.6lf\n", builtin_tan);
printf("\nInference: Difference = %.6lf\n", fabs(approx_tan - builtin_tan));
return 0;
}
Replay !
Share Your Thoughts