While Loop for Percent Error Not Ending
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Madi Macias
am 5 Aug. 2016
Kommentiert: Madi Macias
am 5 Aug. 2016
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 Kommentare
Akzeptierte Antwort
Mischa Kim
am 5 Aug. 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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!