Question about Taylor series

3 vues (au cours des 30 derniers jours)
Qiuyi Wei
Qiuyi Wei le 2 Avr 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 commentaires
Qiuyi Wei
Qiuyi Wei le 2 Avr 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 le 2 Avr 2019
Here is my code

Connectez-vous pour commenter.

Réponses (1)

Torsten
Torsten le 2 Avr 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!.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by