Matlab中的Newton Raphsons方法? [英] Newton Raphsons method in Matlab?
问题描述
Newtons-Raphsons方法在Mathematica中易于实现,但在Matlab中似乎有点困难.我不知道是否可以将函数传递给函数,以及如何将导数用作函数.
Newtons-Raphsons method is easy to implement in Mathematica but in Matlab it seems a bit difficult. I don't get if I can pass a function to a function and how to use the derivative as a function.
newtonRaphson[f_, n_, guess_] :=
If[n == 0, guess, newtonRaphson[f, n - 1, guess - f[guess]/f'[guess]]]
newtonRaphsonOptimize[f_, n_, guess_] :=
If[n == 0, guess,
newtonRaphsonOptimize[f, n - 1, guess - f'[guess]/f''[guess]]]
似乎无法导出文件中定义的函数句柄或函数,但我可能是错的.
It doesn't seem like you can derive neither function-handles nor functions defined in a file but I might be wrong.
推荐答案
您可以使用以下实现:
function x = newton(f,dfdx,x0,tolerance)
err = Inf;
x = x0;
while abs(err) > tolerance
xPrev = x;
x = xPrev - f(xPrev)./dfdx(xPrev);
% stop criterion: (f(x) - 0) < tolerance
err = f(x); %
% stop criterion: change of x < tolerance
% err = x - xPrev;
end
并将函数及其派生函数的函数句柄传递给它.可以通过一些不同的方法来获取此导数:手动微分,符号微分或自动微分.您还可以通过数字方式执行微分,但这既慢,又需要使用修改后的实现.因此,我假设您已经以任何合适的方式计算了导数.然后,您可以调用代码:
And pass it function handles of both the function and its derivative. This derivative is possible to acquire by some different methods: manual differentiation, symbolic differentiation or automatic differentiation. You can also perform the differentiation numerically, but this is both slow and requires you to use a modified implementation. So I will assume you have calculated the derivative in any suitable way. Then you can call the code:
f = @(x)((x-4).^2-4);
dfdx = @(x)(2.*(x-4));
x0 = 1;
xRoot = newton(@f,@dfdx,x0,1e-10);
这篇关于Matlab中的Newton Raphsons方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!