Can someone help me fix my bisection function?
古いコメントを表示
The function is just adding up the upper and lower bound and then dividing by 2, it goes into the function but produces an incorrect root with the maximum iterations.
function [Root] = BisectionFunc25(func,Xu,Xl,RelE,MaxIt)
% Input:
% Func = the function
% Xmin and Xmax = the lower and upper bounds
% RelE = the desired relative absolute error- defaulted to
% 0.0001 percent
% MaxIt = the maximum number of iterations - defaulted to 50
% Output:
% Root = the root
% Funcroot = the function value at the root
% AssE = the associated relative percent error
% Steps = the number of iterations
MaxIt = 50;
% Set format long to show an adequate number of digits in the results.
format long
% Check the number of inputs. Need at least the first three, the last two
% default to select values.
switch nargin
case 0
error ('Need Func, upper and lower limits; Defaults: desired relative abs error and max number of iterations')
RelE = 0.0001
MaxIt = 50
disp('Defaults: desired relative abs error and max number of iterations')
case 1
error ('Need upper and lower limits')
RelE = 0.0001
MaxIt = 50
disp('Defaults: desired relative abs error and max number of iterations')
case 2
RelE = 0.0001;
MaxIt = 50;
Xu = 4;
Xl = -4;
fprintf('upper limit is %4d, lower limit is %4d', Xu, Xl)
end
% Use the Bisection method to find the root to find func that will result in
% a pipe velocity of 5 m/s.
Mid2 = (Xu + Xl)/2;
NumIt = 0;
% Initialize the number of iterations and set up the for loop for the
% method.
for i = 1:MaxIt
NumIt = NumIt + 1
if func(Xu) * func(Mid2) < 0
Mid1 = Mid2
Mid2 = (Xu + Xl)./2
E = abs((Mid1 - Mid2)./Mid1) * 100
if (E <= RelE || NumIt >= MaxIt)
fprintf('Root found is %10.7f at %4.7f iterations', Mid2,NumIt)
elseif func(Xu) * func(Mid2) > 0
Mid1 = Mid2
Mid2 = (Xu + Xl)./2
E = abs((Mid2 - Mid1)./Mid2) * 100
% Check if the new value of x is zero, then check if the error limit or the iteration limit has been reached
elseif Mid2 == 0
E = abs((Mid2 - Mid1)./Mid2) * 100
fprintf('Root found %10.7f')
break
end
end
end
採用された回答
その他の回答 (0 件)
カテゴリ
ヘルプ センター および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!