Question about Taylor series

1 回表示 (過去 30 日間)
Qiuyi Wei
Qiuyi Wei 2019 年 4 月 2 日
回答済み: Torsten 2019 年 4 月 2 日
I am trying to write a code that output a scalor apporximation for function "sin(x)" that have an error less than 0,05. I try to write Taylor series myself(I cannot use "taylor" code) but my error keep getting larger and larger( the wrror supposed to be smaller and smaller). My math is really bad and I don't know why I keep getting wrong answer. Can anyone help me figure out what's wrong for my code and how can I fix it?
Thanks
  2 件のコメント
Qiuyi Wei
Qiuyi Wei 2019 年 4 月 2 日
x=randi([-20 20]);
a=x+randi([2 20]);
k = sin(x); % true value
y = zeros(1,201); % approximation
y(1) = sin(a);
d = zeros(1,200) % derivative
for n = 1:200
e = mod(n,4);
if e==1;
d(n) = sin(a);
elseif e==2;
d(n) = cos(a);
elseif e==3;
d(n) = -sin(a);
elseif e==0;
d(n) = -cos(a);
end
y(n+1) = y(n)+d(n).*(x-a).^(n)./factorial(n);
end
error = abs((y-k)./k);
check = error<=0.05
t = find(check==1);
w = y(t);
est = k(1);
Qiuyi Wei
Qiuyi Wei 2019 年 4 月 2 日
Here is my code

サインインしてコメントする。

回答 (1 件)

Torsten
Torsten 2019 年 4 月 2 日
d(1) = cos(a), d(2) = -sin(a), d(3) = -cos(a), d(4) = sin(a)
So your if-statement to determine f^(n)(a) is wrong.
Further, "error" must be defined as
error = abs((y(end)-k)/k)
Further, you should not always explicitly calculate (x-a)^n/n!. Note that
(x-a)^(n+1)/(n+1)! = (x-a)^n/n! * (x-a)/(n+1).
So you can use a recursion to determine (x-a)^(n+1)/(n+1)! from (x-a)^n/n!.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by