implementing taylor series with loop

I want to implement taylor series for sinx with loop.
So , :
angle=input('Insert angle in degrees\n');
x=angle*2*pi/360; %convert to radians because the equation is in radians
eps=0.000001;%accuracy
sumation=0;
err=1;%error
n=0;
while err>eps
term=((((-1)^n)/factorial(2*n+1))*(x^2*n +1));
sumation=sumation+term;
err=abs((sumation-term)/term);
n=n+1;
end
result=sumation
I think the problem is in computing the error.The error = ((sum(n)-sum(n-1))/sum(n-1)). I tried it also with sumation as a vector but still with no success.
Thanks!

 Réponse acceptée

Image Analyst
Image Analyst le 18 Fév 2013

0 votes

Is this homework? Don't compare the small latest term you are adding on (say 0.003) to the whole sum (say .707 for 45 degrees). Those are the wrong things to compare. Either compare the sum to the true value (sind(angle)) or compare your latest term to the prior term, which means you'd have to make term an array.

4 commentaires

It's not homework.For the error you mean
term(n+1)=((((-1)^n)/factorial(2*n+1))*(x^2*n +1));
sumation=sumation+term(n+1);
But I can't figure how to write the error because n starts from 0.
You could keep track of them separately.
x=angle*2*pi/360; %convert to radians because the equation is in radians
myEps=0.000001;%accuracy
summation=0;
err=1;%error
n = 0;
index = 1;
% Calculate first term.
term(index) = ((((-1)^n)/factorial(2*n+1))*(x^2*n +1));
% Calculate additional terms.
n=n+1;
index = index + 1;
while err > myEps
term(index) = ((((-1)^n)/factorial(2*n+1))*(x^2*n +1));
summation=summation+term(index);
err=abs((term(index) - term(index-1))/term(index));
n=n+1;
index = index + 1;
end
result=summation
trueResult = sind(angle)
but I don't know if your formula is correct.
George
George le 19 Fév 2013
Ok, thanks now I understand!
George
George le 19 Fév 2013
Modifié(e) : George le 19 Fév 2013
I had one mistake : term(index) = ((((-1)^n)/factorial(2*n+1))*(x^(2*n +1))); The "x^(2*n+1)".I corrected this and also added "result=sind(sumation)" but I still don't get right results.... The formula is : http://www.wolframalpha.com/input/?i=taylor+series+sin+x...

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Programming dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by