Question about Taylor series

3 次查看(过去 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);

请先登录,再进行评论。

回答(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 CenterFile Exchange 中查找有关 Loops 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