您的位置:首页 > 编程语言 > MATLAB

matlab实现牛顿迭代法求解非线性方程组

2013-11-21 11:13 405 查看
已知非线性方程组如下

3*x1-cos(x2*x3)-1/2=0

x1^2-81*(x2+0.1)^2+sin(x3)+1.06=0

exp(-x1*x2)+20*x3+(10*pi-3)/3=0

求解要求精度达到0.00001

---------------------------------------------------------分--割--线---------------------------------------------------------

首先建立函数fun

储存方程组编程如下将fun.m保存到工作路径中:

function f=fun(x);

%定义非线性方程组如下

%变量x1 x2 x3

%函数f1 f2 f3

syms x1 x2 x3

f1=3*x1-cos(x2*x3)-1/2;

f2=x1^2-81*(x2+0.1)^2+sin(x3)+1.06;

f3=exp(-x1*x2)+20*x3+(10*pi-3)/3;

f=[f1 f2 f3];

---------------------------------------------------------分--割--线---------------------------------------------------------

建立函数dfun

用来求方程组的雅克比矩阵将dfun.m保存到工作路径中:

function df=dfun(x);

%用来求解方程组的雅克比矩阵储存在dfun中

f=fun(x);

df=[diff(f,'x1');diff(f,'x2');diff(f,'x3')];

df=conj(df');

---------------------------------------------------------分--割--线---------------------------------------------------------

编程牛顿法求解非线性方程组将newton.m保存到工作路径中:

function x=newton(x0,eps,N);

con=0;

%其中x0为迭代初值eps为精度要求N为最大迭代步数con用来记录结果是否收敛

for i=1:N;

    f=subs(fun(x0),{'x1' 'x2' 'x3'},{x0(1) x0(2) x0(3)});

    df=subs(dfun(x0),{'x1' 'x2' 'x3'},{x0(1) x0(2) x0(3)});

    x=x0-f/df;

    for j=1:length(x0);

        il(i,j)=x(j);

    end

    if norm(x-x0)<eps

        con=1;

        break;

    end

    x0=x;

end

 

%以下是将迭代过程写入txt文档文件名为iteration.txt

fid=fopen('iteration.txt','w');

fprintf(fid,'iteration');

for j=1:length(x0)

    fprintf(fid,'         x%d',j);

end

for j=1:i

    fprintf(fid,'\n%6d     ',j);

    for k=1:length(x0)

        fprintf(fid,' %10.6f',il(j,k));

    end

end

if con==1

    fprintf(fid,'\n计算结果收敛!');

end

if con==0

    fprintf(fid,'\n迭代步数过多可能不收敛!');

end

fclose(fid);

---------------------------------------------------------分--割--线---------------------------------------------------------

运行程序

在matlab中输入以下内容

newton([0.1 0.1 -0.1],0.00001,20)

---------------------------------------------------------分--割--线---------------------------------------------------------

输出结果

ans =

 

    0.5000    0.0000   -0.5236

 

---------------------------------------------------------分--割--线---------------------------------------------------------

在iteration中查看迭代过程

 

iteration         x1         x2         x3

     1        0.490718   0.031238  -0.519661

     2        0.509011   0.003498  -0.521634

     3        0.500928   0.000756  -0.523391

     4        0.500227   0.000076  -0.523550

     5        0.500019   0.000018  -0.523594

     6        0.500005   0.000002  -0.523598

     7        0.500000   0.000000  -0.523599

计算结果收敛!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: