How to use a loop to find a maximum value

3 views (last 30 days)
The equation 1+x+((x^2)/2)+((x^3)/6) is often used to approximate e^x. Find to two decimal places the largest value of x before the error exceeds 1 percent. The calculation for error is: e^x-(1+x+((x^2)/2)+((x^3)/6))/e^x.
I know i need to use a loop to find this. However, I am not sure how to format this one or whether to use a for or while loop.
Any suggestions?
  2 Comments
lvn
lvn on 19 Apr 2014
I would first make a plot of both e^x and the approximation, so you get an idea where that largest x will be.
Then I would simply do a for loop to find the first x (e.g from x=-10 to 10 in steps of 0.01 (two decimal places) - and put a break a soon as your error exceeds 1%).
PS. For the error, do not forget to take the absolute value.
Matthew Quinones
Matthew Quinones on 21 Apr 2014
Ok so i put the e^x formula to begin. Then I have
for x=-10:.01:10
x=((ex)-(1+x+((x^2)/2)+((x^3)/6))/ex
if x<=.01
end
After this, what do I do?

Sign in to comment.

Answers (2)

Image Analyst
Image Analyst on 19 Apr 2014
You don't need to use a loop. You can simply do
x = 0: 0.01 : 1;
theErrorPercentage = exp(x)-(1+x+((x.^2)/2)+((x.^3)/6)) ./ exp(x);
plot(x, theErrorPercentage);
xlabel('x');
ylabel('Percent Error');
grid on;
% Find where it's closest to 1
[theDifference, indexAtMin] = min(abs(theErrorPercentage - 1));
xAt1Percent = x(indexAtMin)
At least that's one way. Do you want to use a loop?
  2 Comments
Matthew Quinones
Matthew Quinones on 21 Apr 2014
I think I am supposed to use a loop with a break in it. However I am not sure how to format it
Matthew Quinones
Matthew Quinones on 22 Apr 2014
Ok so far i have:
x=0;
for k=0:.01:10
x=1+x+((x^2)/2)+((x^3)/6);
y=(x-(1+x+((x^2)/2)+((x^3)/6))/x);
if y<=0.01
break
end
end
x
The output I get x=1 and y=-1.6667
not sure if that sounds right? Can't there be another value that would be closer to 0.01% error?

Sign in to comment.


Rohan Sanjay Patel
Rohan Sanjay Patel on 10 Jun 2021
Edited: Rohan Sanjay Patel on 10 Jun 2021
error = 0;
x = 0;
while error < 1
x = x + 0.01;
approx = 1 + x + x^2/2 + x^3/6;
error = 100*(exp(x) - approx)/exp(x);
end
disp(x)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!