Matlab中的牛顿拉夫森法?
Newtons-Raphsons 方法在 Mathematica 中很容易实现,但在 Matlab 中似乎有点困难。我不知道是否可以将函数传递给函数以及如何将导数用作函数。
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]]]
似乎您既无法派生函数句柄,也无法派生文件中定义的函数,但我可能是错的。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用这样的实现:
并将函数及其派生函数的函数句柄传递给它。该导数可以通过一些不同的方法获得:手动微分、符号微分或自动微分。您还可以以数字方式执行微分,但这既慢又需要您使用修改后的实现。所以我假设您已经以任何合适的方式计算了导数。然后就可以调用代码了:
You could use an implementation like this:
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:
没有办法以代数方式获取函数句柄或 m 文件中定义的函数的导数。您必须通过在多个点评估函数并逼近导数来以数值方式来完成此操作。
您可能想要做的是符号方程的微分 ,并且您需要符号数学工具箱。下面是使用 Newton-Raphson 方法 查找根的示例:
您可以看到经过几次迭代后,
xRoot
的值就接近真根的值(2)。您还可以将函数求值放在 while 循环中,并设置一个条件来检查每个新猜测与前一个猜测之间有多大差异,当差异足够小时停止(即已找到根):There's no way to algebraically take derivatives of function handles or functions defined in m-files. You would have to do this numerically by evaluating the function at a number of points and approximating the derivative.
What you're probably wanting to do is differentiation of symbolic equations, and you need the Symbolic Math Toolbox for that. Here's an example of finding a root using the Newton-Raphson method:
You can see that the value of
xRoot
comes close to the value of the true root (which is 2) after just a couple of iterations. You could also place the function evaluation in a while loop with a condition that checks how big a difference there is between each new guess and the previous guess, stopping when that difference is sufficiently small (i.e. the root has been found):