$$\cos x=1-{\frac {x^{2}}{2!}}+{\frac {x^{4}}{4!}}-{\frac {x^{6}}{6!}}+\cdots =\sum _{n=0}^{\infty }{\frac {(-1)^{n}x^{2n}}{(2n)!}}$$
A typical example of partial summation. The process will be terminated when the absolute value of the next term is less than \(10^{-6}\).
TIPS:
参考:
NEVER calculate the next term in this way:
1, calculate \(x^{2n}\);
2, calculate \((2n)!\);
3, calculate the division: \(x^{2n} / (2n)!\).
This will lead to OVERFLOW!
Note: n-th term is
$$t_n=(-1)^n\frac{x^{2n}}{2n!}$$
and (n+1)-th term is
$$t_{n+1}=(-1)^{n+1}\frac{x^{2(n+1)}}{(2(n+1))!}$$
So, we could compute \(t_{n+1}\) in turns of \(t_n\) in the following way:
$$t_{n+1}=-t_n \times\frac{x^2}{(2n+1)(2n+2)}$$
/*
Description: Solving problem by using sub-problem's solution
calculte cos x
Author: Liutong Xu
Date: 2016/11/01
*/
#include<stdio.h>
#include<math.h>
int main()
{
int i;
double x, nextterm;
double cosx;
printf("Please input a value for x\n");
scanf("%lf",&x);
//because cos x == cos (x + 2pi)
while (x > 6.2831852) x = x - 6.2831852;
while (x < 0) x = x + 6.2831852;
//initialization
cosx = 0.0;
nextterm = 1.0;
i = 1;
while(fabs(nextterm)>=1e-6) //if the next term is still significant
{
cosx = cosx + nextterm;
nextterm = -nextterm*x*x/i/(i+1);
i = i + 2;
}
printf("cos(x) = %lf\n", cosx);
return 0;
}