cos(x) 的泰勒级数展开不起作用

问题描述 投票:0回答:2
#include <stdio.h>
#include <math.h>
#define PI 3.1416
double fact(n){
  double x = 1;
  for(int i = 1 ; i <= n ; i++){
    x = x*i;
  }
  return x;
}
int main(void) {
  int deg,term,n=1,sign=1;
  float radian,result=0;
  printf("Enter the Angle (in degree) : ");
  scanf("%d",&deg);
  printf("Enter the number of terms : ");
  scanf("%d",&term);
  radian = deg*(PI/180.0);

  for(int count = 0 ;n<=term ; count+=2){
    result = result + sign *(double)(pow(radian,count)/fact(count));
    n++;
    sign = sign * (-1) ;
  }
  
  printf("user defined cos(%d) = %f\n",deg,result);
  printf("inbuilt cos(%d) = %f\n",deg,cos(deg));
  return 0;
}

我尝试了使用 sin 函数和不同的 count 值的类似代码,但它不适用于 cos。如果有人知道为什么它打印错误的答案...请回复

c math trigonometry logic-error
2个回答
3
投票

你的代码是正确的,你的测试是错误的:

而不是

cos(deg)
,应该是
cos(radian)

此外,您可以使用

PI
中给出的定义,而不是定义
math.h
:
M_PI
:

#define _USE_MATH_DEFINES
#include <math.h>

// from here, you can use M_PI 


您还可以改进您的代码

  1. 由于余弦函数是周期性的,并且泰勒级数在 0 附近更好,因此您应该将输入数字限制在 [-180, 180] 范围内

  2. 阶乘函数可以计算得更快:如果您存储 4!,则必须计算 2!、4!、6!...例如,6!可以只用 2 次乘法来计算,或者从头开始重新计算(就像你对

    sign
    所做的那样,而不是调用
    pow(-1, n)

  3. 同样适用于

    x^(2n)


-1
投票

你的代码效率低下。你一遍又一遍地调用阶乘而不记住它。

这里有更好的 Python 示例。无需调用阶乘函数。您应该能够移植它们。

def cosine(t, n):
    result = 0.0
    term = 1.0
    sign = 1.0
    for i in range(0, n):
        result += sign*term
        sign *= -1.0
        term *= t*t/(2*i+1)/(2*i+2)
    return result

def sine(t, n):
    result = 0.0
    term = t
    sign = 1.0
    for i in range(1, n):
        result += sign*term
        sign *= -1.0
        term *= t*t/(2*i)/(2*i+1)
    return result
© www.soinside.com 2019 - 2024. All rights reserved.