While Loop for Percent Error Not Ending
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Hello! This is the first time i am posting a question so i apologize if i format it incorrectly.
I am trying to create a while loop that will determine how many iterations are needed for the percent error between the taylor series for sin and the matlab sin() function to be below 2%. The code i currently have just continues to run without an end in sight. Here's what i have:
x=sym('x')
x=input('Enter a scalar value for x.')
n=0:100000;
e=100000;
k=0;
while e>2
for i=1:length(n)
y(i)=((-1).^n(i))*((x.^(2*n(i))+1)/factorial((2*n(i))+1));
k=k+n(i);
u=sin(x);
e=((abs(u-k)/abs(k))*100);
%i=n(i);
end
end
fprintf('Percent Error:%d',e)
For reference i am using the generalized version of the Taylor series that is attached.
Thank you in advance!
0 Commenti
Risposta accettata
Mischa Kim
il 5 Ago 2016
Madi, how about
x = input('Enter a scalar value for x: ');
n = 0;
e = 3;
k = 0;
while e>2
dk = (-1)^n*x^(2*n + 1)/factorial(2*n + 1);
k = k + dk;
u = sin(x);
e = ((abs(u-k)/abs(k))*100);
n = n + 1;
fprintf('Terms: %d, percent error: %3.2d\n', n, e)
end
No need for the sym command. The entire computation is done numerically.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!