习题5-7 使用函数求余弦函数的近似值
本题要求实现一个函数,用下列公式求cos(x)的近似值,精确到最后一项的绝对值小于e:
cos(x)=x^0/0!-x^2/2!+x^4/4!-x^6/6!+......
函数接口定义:
double funcos( double e, double x )
其中用户传入的参数为误差上限e和自变量x;函数funcos应返回用给定公式计算出来、并且满足误差要求的cos(x)的近似值。输入输出均在双精度范围内
#include <stdio.h>
#include <math.h>
double funcos( double e, double x );
int main()
{
double e, x;
scanf("%lf %lf", &e, &x);
printf("cos(%.2f) = %.6f\n", x, funcos(e, x));
return 0;
}
// 函数实现cos(x)的近似值
double funcos( double e, double x )
{
double tmp1 = 1,tmp2 = 1,tmp3 = 1;
double sum = 1; // 0的阶乘是1,所以sum = 1
int i,j;
j = -1; //等式中第0项是正号,第一项是负号,第二项又是正号......
for(i=2; tmp1>e; i+=2) //tmp>1 这一项是判断精确度
{
tmp2 = tmp2 * x * x; // 每次比前一项都需要多乘x^2
tmp3 = tmp3 * i * (i-1); //每次比前一项都需要多乘i*(i-1)
sum = sum + k*tmp2/tmp3; //sum 就是cos(x)的近似值
tmp1 = tmp2/tmp3; // tmp1是第1、2、3...项的近似值
j = -j;
}
return sum;
}
/*
试数:e = 0.01 x = -3.14
1> i=2; 1>0.01;
tmp2 = x^2;
tmp3 = 2!;
sum = 1+(-1)*(-3.14)^2/2!;
tmp1 = (-3.14)^2/2! = 4.9298;
j = 1;
i = 4;
2> 4.9298 > 0.01;
tmp2 = x^2*x^2 = x^4;
tmp3 = 2!*4*3 = 4!;
sum = 1+(-1)*(-3.14)^2/2!+(1)*(-3.14)^4/4!;
tmp1 = (-3.14)^4/4! = 4.0505;
j = -1;
i = 6;
3> 4.0505>0.01;
tmp2 = x^4*x^2 = x^6;
tmp3 = 4!*6*5 = 6!;
sum = 1+(-1)*(-3.14)^2/2!+(1)*(-3.14)^4/4!+(-1)*(-3.14)^6/6!;
tmp1 = (-3.14)^6/6! = 1.3312;
j = 1;
i = 8;
4> 1.3312>0.01;
tmp2 = x^6*x^2 = x^8;
tmp3 = 6!*8*7 = 8!;
sum = 1+(-1)*(-3.14)^2/2!+(1)*(-3.14)^4/4!+(-1)*(-3.14)^6/6!+(1)*(-3.14)^8/8!;
tmp1 = (-3.14)^8/8! = 0.2344;
j = -1;
i = 10;
5> 0.2344>0.01;
tmp2 = x^8*x^2 = x^10;
tmp3 = 8!*10*9 = 10!;
sum = 1+(-1)*(-3.14)^2/2!+(1)*(-3.14)^4/4!+(-1)*(-3.14)^6/6!+(1)*(-3.14)^8/8!+(-3.14)^10/10!;
tmp1 = (-3.14)^10/10! = 0.0257;
j = 1;
i = 12;
6> 0.0257>0.01;
tmp2 = x^10*x^2 = x^12;
tmp3 = 10!*12*11 = 12!;
sum = 1+(-1)*(-3.14)^2/2!+(1)*(-3.14)^4/4!+(-1)*(-3.14)^6/6!+(1)*(-3.14)^8/8!+(-1)*(-3.14)^10/10!+(1)*(-3.14)^12/12!;
tmp1 = (-3.14)^12/12! = 0.0019;
j = -1;
i = 14;
7> 0.0019>0.01 不成立 循环结束 返回sum = -0.9999(近似运算)
*/