Info

This question is closed. Reopen it to edit or answer.

Need help with an if loop

1 view (last 30 days)
Nathan Berg
Nathan Berg on 24 Oct 2019
Closed: MATLAB Answer Bot on 20 Aug 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

Answers (1)

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

Community Treasure Hunt

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

Start Hunting!