matlap二分法求根函数文件

f(x)=x^3+1.1*x^2+0.9*x-1.4
区间【0,1】求近似解,不超过10^(-5)
编写程序需要nargin语句判断输入参变量个数是否正确。

function x = approximate_solution(varargin)

if nargin ~= 1 
    error('Please enter the function f(x).');
end 

f=@(x) varargin{1}(1)*x.^3 + varargin{1}(2)*x.^2 + varargin{1}(3)*x + varargin{1}(4);

a=0;
b=1;
tolerance = 1e-5;

while (b-a) > tolerance
    c = (a+b)/2;
    if f(a)*f(c) < 0
        b=c;
    else
        a=c;
    end
end

x = (a+b)/2;

end

function root = bisection(f,a,b,tol)
% bisection function to solve for roots using the bisection method
% input: 
% f - function handle for the function to find roots for
% a, b - interval to search for roots in 
% tol - tolerance for the approximate solution (default is 10^-5)
% output:
% root - approximate solution for the root of the function

% check for correct number of input arguments
if nargin < 3
    error('Not enough input arguments.')
elseif nargin == 3
    tol = 10^-5; % set default tolerance
elseif nargin > 4
    error('Too many input arguments.')
end

% check if function is continuous on the interval
if sign(f(a)) == sign(f(b))
    error('Function is not continuous on the interval.')
end

% initialize variables
c = (a+b)/2;
i = 0;

% iterate until approximate solution is within tolerance
while abs(f(c)) > tol
    if sign(f(c)) == sign(f(a))
        a = c;
    else
        b = c;
    end
    c = (a+b)/2;
    i = i+1; % keep track of iterations for debugging purposes
end

root = c;
disp(['Approximate root: ',num2str(root)]);
disp(['Number of iterations: ',num2str(i)]);

end

使用示例:

>> f = @(x) x.^3 + 1.1.*x.^2 + 0.9.*x - 1.4;
>> bisection(f,0,1)

Approximate root: 0.55042
Number of iterations: 15