How can I use the Bisection method to converge on an arbitrary value?
11 次查看(过去 30 天)
显示 更早的评论
I am working on coding a function to solve for the water level inside a water tank. The volume of the tank is described by:
V = pi * x^2 *((3*R-x)/3)
I have R = 4 m and I need to find the height (x) where V = 100 m^3. I chose to use the Bisection Method to find this height and use a while loop that should end when the height that gives out Volume equal to 100 m^3. Though I am having a hard time getting the loop to run more than just once and I don't know what could be going wrong. I'm new to Matlab so I might be missing something very obvious but any help would be appreciated.
Here is the code that I have managed to come up with so far:
% Define function
R = 4;
v = @(x) pi.*x.^2.*((3.*R-x)./3);
% Define variables
xL = 0;
xH = 2.*R;
vL = v(xL);
vH = v(xH);
% Define xr
xr = .5.*(xL+xH); % Bisection method
vR = v(xr);
% Define the loop's target value
tar = 100;
while v(xr) == tar
xr = .5.*(xL+xH);
% Update xH and xL
if vH>vR
xH = xr;
else
xL = xr;
end
end
root = xr;
Once again thanks for any help it is very appreciated
0 个评论
采纳的回答
Voss
2022-1-28
In fact your loop runs 0 times (because v(xr) is not equal to 100).
% Define function
R = 4;
v = @(x) pi.*x.^2.*((3.*R-x)./3);
% Define variables
xL = 0;
xH = 2.*R;
vL = v(xL);
vH = v(xH);
% Define xr
xr = .5.*(xL+xH); % Bisection method
vR = v(xr);
% Define the loop's target value
tar = 100;
disp(v(xr));
while v(xr) == tar
disp('looping');
xr = .5.*(xL+xH);
% Update xH and xL
if vH>vR
xH = xr;
else
xL = xr;
end
end
root = xr;
It should loop until v(xr) == tar, so: while v(xr) ~= tar, and in fact it probably should not be with exact (in)equality but using some small error, e.g., while abs(v(xr) - tar) > max_error. And you need to update your volumes as you go and use tar to tell which of xH or xL need to be updated each time.
% Define function
R = 4;
v = @(x) pi.*x.^2.*((3.*R-x)./3);
% Define variables
xL = 0;
xH = 2.*R;
vL = v(xL);
vH = v(xH);
% Define xr
xr = .5.*(xL+xH); % Bisection method
vR = v(xr);
% Define the loop's target value
tar = 100;
max_error = 1e-6;
while abs(v(xr) - tar) > max_error
xr = .5.*(xL+xH);
vR = v(xr); % update vR too
fprintf(1,'looping: xr = %12.8f, vR = %12.8f\n',xr,vR);
% Update xH and xL
if tar < vR % use tar to determine which side of the target you're on
xH = xr;
vH = v(xH); % update vH too
else
xL = xr;
vL = v(xL); % update vL too
end
end
format long;
root = xr
v(root)
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!