How to use a loop to find a maximum value
1 view (last 30 days)
Show older comments
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
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.
Answers (2)
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
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)
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!