MATLAB牛顿迭代法
- 牛顿迭代法(用于搜索零点):
通过函数 f ( x ) = 0 \ f(x) =0 f(x)=0的泰勒级数展开
f ( x ) = f ( x 0 ) + f ′ ( x 0 ) 1 ! ( x − x 0 ) + f ′ ′ ( x 0 ) 2 ! ( x − x 0 ) 2 + . . . + f ( n ) ( x 0 ) n ! ( x − x 0 ) n \ f(x) =f(x_0) +\frac {f'(x_0)} {1!}(x-x_0)+\frac {f''(x_0)} {2!}(x-x_0)^2+...+\frac {f^{(n)}(x_0)} {n!}(x-x_0)^n f(x)=f(x0)+1!f′(x0)(x−x0)+2!f′′(x0)(x−x0)2+...+n!f(n)(x0)(x−x0)n
取级数展开式的常数项和一次项: f ( x 0 ) + f ′ ( x 0 ) ( x − x 0 ) = 0 \ f(x_0) +f'(x_0)(x-x_0)=0 f(x0)+f′(x0)(x−x0)=0
得到迭代函数: x = x 0 − f ( x 0 ) f ′ ( x 0 ) \ x=x_0 -\frac {f(x_0)} {f'(x_0)} x=x0−f′(x0)f(x0)
这里是一个一元函数的简单代码:
%牛顿迭代法
function [x,n,Xn,Yn] = newiteration(fun,dfun,x0,EPS)
% fun为目标函数,dfun为目标函数的一阶导数,x0为起始点,EPS为精度
a=feval(fun,x0);
b=a+1;
n=0;
%建立画图的点
Xn = zeros(5,1);
Yn = zeros(5,1);
while(abs(a-b) >= EPS)
a = feval(fun,x0) ;
df = feval(dfun,x0);
Xn(n+1,1) = x0;
Yn(n+1,1) = a;
if (feval(dfun,x0) == 0)
break
else
x0 = x0 - a/df;
end
b = feval(fun,x0);
n = n + 1;
end
x = x0;
调用函数:
%% 调用函数
clear all
clc
% syms x
fun=inline('x^2 - 9','x');
dfun = inline('2*x','x');
Xn = zeros(5,1);
Yn = zeros(5,1);
x0 = 1;
EPS = 0.001;
[x,n,Xn,Yn] = newiteration(fun,dfun,x0,EPS)
figure
plot(Xn,Yn,'k-','color','red')
hold on
x = 0:0.1:7;
y = x.^2 - 9;
y2 = zeros(1,71);
plot(x,y,'color','b')
plot(x,y2,'color','black')
运行结果:
x =3.000000001396984
n =5
迭代过程:
如果需要减少计算,可以通过将
f
′
(
x
0
)
\ f'(x_0)
f′(x0)设置为定值,收敛速度会减慢。