Info

La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.

Need help with an if loop

6 visualizaciones (últimos 30 días)
Nathan Berg
Nathan Berg el 24 de Oct. de 2019
Cerrada: MATLAB Answer Bot el 20 de Ag. de 2021
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

Respuestas (1)

Shubham Gupta
Shubham Gupta el 25 de Oct. de 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.

La pregunta está cerrada.

Community Treasure Hunt

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

Start Hunting!

Translated by