C正弦(x)近似误差

时间:2017-10-07 00:33:45

标签: c series

我正在尝试使用泰勒系列计算Sin(x)的值,即:x-x ^ 3/3!+ x ^ 5/5! 我尝试的是这段代码,但它有点给我错误!

int n;
int factorial;
float sum=0;
float angle;
int sign=1;
int i,j;

printf("Please Enter angle in degrees:\n");
scanf("%f",&angle);
angle=angle*3.14/180;

printf("Please Enter Number of terms:\n");
scanf("%d",&n);
for (i=1;i<=n;i++){
    factorial=1;
    for (j=1;j<=(2*i-1);j++)
    factorial=factorial*j;
sum=sum+sign*(pow(angle,j)/factorial);
sign*=-1;
}
printf("Sum up to %d terms is %f",n,sum);

1 个答案:

答案 0 :(得分:1)

关闭1

j太棒了

// sum=sum+sign*(pow(angle,j)/factorial);
sum=sum+sign*(pow(angle,j-1)/factorial);

建议更好地近似pi

#define MY_PI 3.1415926535897932384626433832795
// angle=angle*3.14/180;
angle *= MY_PI/180;

使用float时没有实际价值考虑double。如果代码希望与float保持一致,请使用float之类的powf(angle,j)函数 - 请注意f

提示:不是每次从1开始重新计算术语的阶乘,而是从上一个术语继续。

//psuedo code
term = -x*x/(2i)/(2i+1)*previous_term
  double sum = 0.0;
  double x2 = x_radians * x_radians;
  double term = x_radians;
  for (unsigned i = 1; i <= terms; i++) {
    sum += term;
    term *= -x2 / ((2 * i) * (2 * i + 1));
  }