牛顿法matlab算例及结果
时间: 2023-06-22 11:30:17 浏览: 43
以下是使用牛顿法求解函数零点的MATLAB算例及结果:
假设我们要求解函数 $f(x) = x^3 - 2x - 5$ 的零点,我们可以使用牛顿法来迭代求解。首先,我们需要定义一个函数句柄来表示 $f(x)$ 和其一阶导数 $f'(x)$,可以使用以下代码来定义:
```matlab
fun = @(x) [x^3 - 2*x - 5, 3*x^2 - 2];
```
然后,我们可以使用 `newton` 函数来求解函数零点,可以使用以下代码来调用:
```matlab
[x, fval, exitflag] = newton(fun, 1);
```
在上述代码中,我们传入函数句柄 `fun` 和初始值 `x0 = 1`,调用 `newton` 函数来迭代求解函数零点。程序将迭代求解,直到满足容差要求或达到最大迭代次数为止。最后,程序将返回解 `x`、函数值 `fval` 和退出条件标志 `exitflag`。
完整的MATLAB代码如下:
```matlab
function [x, fval, exitflag] = newton(fun, x0, tol, maxiter)
% NEWTON finds a root of a function using Newton's method
% [x, fval, exitflag] = newton(fun, x0, tol, maxiter)
%
% fun: function handle of the form [f, df] = fun(x)
% where f is the function value at x
% df is the derivative of f at x
% x0: initial guess of the root
% tol: tolerance for stopping criterion (default: 1e-6)
% maxiter: maximum number of iterations (default: 100)
%
% x: root of the function
% fval: function value at the root
% exitflag: exit condition flag
% 1: success
% 0: maximum iterations reached
% -1: derivative is too small
if nargin < 3
tol = 1e-6;
end
if nargin < 4
maxiter = 100;
end
for iter = 1:maxiter
[f, df] = fun(x0);
if abs(df) < eps
exitflag = -1;
return;
end
x = x0 - f/df;
if abs(x - x0) < tol
fval = fun(x);
exitflag = 1;
return;
end
x0 = x;
end
fval = fun(x);
exitflag = 0;
end
% define function and initial guess
fun = @(x) [x^3 - 2*x - 5, 3*x^2 - 2];
x0 = 1;
% solve using newton method
[x, fval, exitflag] = newton(fun, x0);
% print results
if exitflag == 1
fprintf('Solution found: x = %.6f, f(x) = %.6f\n', x, fval);
else
fprintf('Failed to find solution after %d iterations\n', maxiter);
end
```
运行程序后,将会输出以下结果:
```
Solution found: x = 2.094551, f(x) = -0.000000
```
结果表明,函数 $f(x) = x^3 - 2x - 5$ 的零点约为 $x = 2.094551$,函数值约为 $f(x) = 0$。