matlab 牛顿法程序的问题

matlab 牛顿法程序的问题,第1张

function kk=newton(f,df,x0,tol,N)%改了这里

%root是系统保留字。不推荐使用。可以用exist('root')命令测试

% Newton Method

% The first parameter f is a external function with respect to viable x.

% The second parameter df is the first order diffential function of fx.

% x0 is initial iteration point.

% tol is the tolerance of the loop.

% N is the maximum number of iterations.

x=x0

f0=eval(f)df0=eval(df)

n=0

disp(' [ nxn xn+1 fn+1 ]')

while n<=N

x1=x0-f0/df0

x=x1

f1=eval(f)

X=[n,x0,x1,f1]

disp(X)

if abs(x0-x1)<tol

fprintf('The procedure was successful.\n')%改了这里

kk=X%改了这里

return

else

n=n+1

x0=x1f0=f1

end

end

if n==N+1

fprintf('the method failed after N iterations. '),

kk=0%改了这里

end

采用第一个。

首先你的两个代码的计算过程和方法以及步骤是一致的。

只不过第二个将k==N放在循环内部判断是没有必要的。

放在while外面,可以节省点计算量。

如果你要求结果精度高一些的话,你调用:

x=nanewton1(fname,dfname,x0,e,N)

时e要小一些,比如说取1e-6这样。

另外:

if nargin<4

e=1e-4 %这个值也下调几个量级,作为缺省的精度。

end

#include<stdio.h>

#include<math.h>

int main()

{

float x1,x,f1,f2static int count=0

x1=1.5//定义初始值

do

{

x=x1

f1=x*(2*x*x-4*x+3)-6

f2=6*x*x-8*x+3//对函数f1求导

x1=x-f1/f2 count++

}while(fabs(x1-x)<=1e-5)

printf("%8.7f\n",x1)printf("%d\n",count)

return 0

}

//2x3-4x2+3x-6//根据我改了初始值,查看结果,表明:改变初始值得到的结果并不一样,但是迭代的次数并没有改变!!


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/10987326.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-12
下一篇 2023-05-12

发表评论

登录后才能评论

评论列表(0条)

保存