Question about Taylor series

3 visualizzazioni (ultimi 30 giorni)
Qiuyi Wei
Qiuyi Wei il 2 Apr 2019
Risposto: Torsten il 2 Apr 2019
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 Commenti
Qiuyi Wei
Qiuyi Wei il 2 Apr 2019
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 il 2 Apr 2019
Here is my code

Accedi per commentare.

Risposte (1)

Torsten
Torsten il 2 Apr 2019
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!.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti


Release

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by