Info
Diese Frage ist geschlossen. Öffnen Sie sie erneut, um sie zu bearbeiten oder zu beantworten.
Need help with an if loop
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
I need help generating an 'if' loop to calculate the approximate f(x)=exp(5) in matlab
I don't understand how to do these loops and would appreciate some assitance in learning them
Thank you in advance
0 Kommentare
Antworten (1)
Shubham Gupta
am 25 Okt. 2019
First, exp(x) has an expansion as follows:
Now, how to define infinity?
When , . So, we check if this term is close to zero? Depending on that we can say that our estimation has converged. Now, to code this
function y = exp_mm(x)
y = 1; % initial estimation
n = 1; % initial n
while 1
add_term = (x^n)/factorial(n); % additional term x^n/(n!)
if abs(add_term)<1e-6 % check if it's close to zero?
break; % break if it's close to zero
else
y = y + add_term; % else we continue adding the term
n = n+1; % and increase the n
end
end
Here are some comarison:
y = exp(5)
% Outputs:
y =
148.4132
y1 =exp_mm(5)
% Outputs:
y1 =
148.4132
Pretty close to what we wanted. We can calculate error now,
error = y-y1
% Output:
error =
1.1981e-07
So, our value is correct at least of the 1e-6.
I hope this help! Let me know if you have doubts.
0 Kommentare
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!