簡體   English   中英

嘗試使用泰勒級數計算余弦非常不精確

[英]Attempt to calculate cosine using Taylor Series is very imprecise

因此,我嘗試在 C 中編寫一個程序,它將使用泰勒級數逼近余弦:

#include <stdio.h>
#include <math.h>

int main() {
  printf("degrees\tTaylor\tcos(degrees)\n");
  for (double i=0; i<=90; i++) {
  double factorial=1;
  double x,xn=1;
  x=i/(180/M_PI);
  double y=1;
  for (int i=1; i<30; i++) {
    factorial*=i;
    xn*=x;
    y+=((i%3==0)?(1):(i%3==1)?(0):(-1))*xn/factorial;
  }
  printf("%lf\t%lf\t%lf\n",i,y,cos(x));
  }
}

然而,90 度的誤差超過 1/3:

錯誤增長非常快

我以為錯誤是由於 C double類型導致的數值不穩定。 然而,當我將程序重寫為 Python 時,我得到了幾乎相同的結果:

import math
print("degrees\tTaylor\tcos(degrees)\tdeviance")
for degrees in range(0,90+1):
  factorial=1
  x=degrees/(180/math.pi)
  xn=1
  y=1
  for i in range(1,50):
    factorial=factorial*i
    xn=xn*x
    multiplicator=0
    if i % 3 == 0:
      multiplicator=1
    elif i % 3 == 1:
      multiplicator=0
    else:
      multiplicator=-1
    y=y+multiplicator*xn/factorial
  print(str(degrees)+"\t"+str(y)+"\t"+str(math.cos(x))+"\t"+str(abs(y-math.cos(x))))

你知道這里發生了什么嗎? 通過使用泰勒級數的前 50 項,它應該與實數余弦 function 幾乎沒有區別。但事實並非如此。

你的錯誤是i % 3 余弦的術語 go 1, 0, -1, 0, 1, 0, -1, 0....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM