Newton Raphson method

时间:2015-05-04 19:26:41

标签: matlab

I have the below matlab code for newton raphson method.

a=1;b=4;c=-2;d=0;h=0.5;t=1;
x0 = -0.5+2i;
i = 1;
N = 100;                %maximum number of iterations
tol = 1e-4;         %precision required

syms x
p = @(x) x^2+a*x+b-c*exp(-x*h)-d*exp(-x*t);
f = @(x) a*x+b-lambertw(a*x+b-p*exp(a*x+b)); %function we are solving
df = diff(f);           %differential of f(x)

while i <= N
    numf = subs(f,x,x0); %// Numerator - Substitute f(x) for f(y)
    denf = subs(df,x,x0); 
    x = x0-double(numf)/double(denf);     %Newton-Raphson method 
    if (abs(x - x0)/abs(x))>tol     %stopping criterion 
    fprintf('Solution is %f \n', double(x))
    return
end
i = i + 1;
x0 = x;             %update p0
end
fprintf('Solution did not coverge within %d iterations at a required precision of %d \n', N, error)     %error for non-convergence within N iterations

When I ran it it gives the errors below:

  1. Error using mupadmex Error in MuPAD command: DOUBLE cannot convert the input expression into a double array.
  2. Error using diff Function 'diff' is not supported for class 'function_handle'. Error in line 10 diff = diff(f);
    %differential of f(x)

I don't know how to fix these errors. Help is truly appreciated.

1 个答案:

答案 0 :(得分:0)

在循环初始化x之前。否则你会尝试在没有初步猜测的情况下开始下降。牛顿方法是一种局部方法,因此您需要选择您怀疑要收敛的局部最小值的区域。

然后摆脱双重陈述。由于错误告诉你double(x)是在muPad中定义的函数,这不是matlab,而是这个小子程序。基本上你不能使用这个功能。

使用f(x),因为你已经有了一个函数句柄。对于df,您可以在每次迭代时使用subs(df,x)。这将用你在sub中给出的x替换df中的x,...通过替换自动加倍。

使用提示:

$fso = Get-ChildItem -Recurse -path C:\clntfiles

$fsoBU = Get-ChildItem -Recurse -path C:\clntfilesbkup

$dif = Compare-Object -ReferenceObject $fso -DifferenceObject $fsoBU 

#copy items, sideindicator "<=" indicates object missing in DifferenceObject
$dif | % {if($_.SideIndicator -eq "<="){Copy-Item $_.inputobject.FullName C:\lntfilesbkup}}

#output list to file
$dif.InputObject.FullName | Set-Content dif.txt

值是双倍的,没有明确的声明。