C Program: Sine Series
For an angle $x$ in radians, the sine series is given by
$sin(x) = x - \frac{x^{3}}{3!} + \frac{x^{5}}{5!} - \frac{x^{7}}{7!} + ...$
It can be derived by applying Maclaurin's Series to the sine function. The sine series is convergent for all values of $x$.
We observe the terms of the series and note that the numerators are odd powers of a given radian value $x$, i.e., $x^{2n + 1}$, where $n = 0,1,2,3, ... $, and the corresponding denominators are the factorials of the same odd power $(2n+1)!$ as that of the numerator. We define two functions to compute these powers and factorials — power()
and factorial()
.
The series summation takes place inside the while
loop; even terms are added and odd terms are subtracted.
#include <stdio.h>
unsigned long factorial(unsigned short int);
float power(float, unsigned short int);
int main() {
unsigned short n, i = 0;
float x, sum = 0;
printf("n: ");
scanf("%hu", &n);
printf("x: ");
scanf("%f", &x);
while(i < n) {
if(i%2 == 0)
sum += power(x,2*i+1)/(float) factorial(2*i+1);
else
sum -= power(x,2*i+1)/(float) factorial(2*i+1);
i++;
}
printf("Sum upto %hd terms = %f", n, sum);
return 0;
}
float power(float x, unsigned short n) {
float pow = 1;
while(n > 0) {
pow *= x;
--n;
}
return pow;
}
unsigned long factorial(unsigned short n) {
unsigned long f;
if(n == 0 || n == 1)
return 1;
else
f = n * factorial(n-1);
return f;
}
We will verify the results of our summation upto a considerable number of terms $n$ for some well-known angles/values of $x$ (radians).
When the angle is equal to $0\deg$ ($x = 0$), the series value is $0$ for any value of $n$.
When the angle is equal to $30°$ ($x = 0.523599$ radians), our summation result should give the value close to $\frac{1}{2} = 0.5$, for some term $n$.
And when the angle equals $90°$ ($x = 1.5708$ radians), the sum should come close to 1 for some significant term $n$.