【问题标题】:Implementing Multivariate Newton's Method in Julia在 Julia 中实现多元牛顿法
【发布时间】:2019-09-08 13:34:34
【问题描述】:

我正在尝试在 Julia 中实现多元牛顿法,但遇到了“无方法匹配”错误。下面是我的实现和我用来调用它的代码。

function newton(f::Vector, J::Matrix, x::Vector)
   h = Inf64
   tolerance = 10^(-10)
   while (norm(h) > tolerance)
      h = J(x)\f(x)
      x = x - h
   end
   return x
end

调用尝试 1

f(x::Vector) = [(93-x[1])^2 + (63-x[2])^2 - 55.1^2, 
         (6-x[1])^2 + (16-x[2])^2 - 46.2^2]
J(x::Vector) = [-2*(93-x[1]) -2*(63-x[2]); -2*(6-x[1]) -2*(16-x[2])]
x = [35, 50]
newton(f, J, x)

运行上述代码时,会抛出以下错误:

ERROR: LoadError: MethodError: no method matching newton(::typeof(f), ::typeof(J), ::Array{Int64,1})
Closest candidates are:
  newton(::Array{T,1} where T, ::Array{T,2} where T, ::Array{Int64,1})
  newton(::Array{T,1} where T, ::Array{T,2} where T, ::Array{T,1} where T)
  newton(::Array{T,1} where T, ::Array{T,2} where T, ::Array)

调用尝试 2

f(x::Vector) = [(93-x[1])^2 + (63-x[2])^2 - 55.1^2, 
         (6-x[1])^2 + (16-x[2])^2 - 46.2^2]
J(x::Vector) = [-2*(93-x[1]) -2*(63-x[2]); -2*(6-x[1]) -2*(16-x[2])]
x = [35, 50]
newton(f(x), J(x), x) # passing x into f and J

在尝试调用方法 2 时,我没有遇到任何错误,但进程永远不会终止。作为参考,我在 MATLB 中编写的多元牛顿法的相应实现在大约 10 秒内解决了示例中的方程组。

如何在 Julia 中正确实现和调用多元牛顿法?

【问题讨论】:

    标签: julia newtons-method


    【解决方案1】:

    虽然它们可能返回Vector 或Matrix,但f 和J 都是函数。将newtons 签名更改为

    function newton(f::Function, J::Function, x)
    

    将使您的实施工作。

    附带说明,除非必要,否则您可能希望避免指定类型,并使用动态类型和 Julia 类型系统的强大功能。代码应尽可能通用。例如,您的 newton 函数将无法与 x 一起使用,因为它们的类型不是 <: Vector 中的 SArray 或其他包中的其他数组类型。但是,如果您省略类型,您的函数将适用于其他类型。请注意,一旦函数编译完成,您不会损失任何性能。

    请参阅 Julia 文档 Style Guide 中的相关讨论。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-11
      • 1970-01-01
      • 2013-10-17
      • 2017-05-05
      • 1970-01-01
      相关资源
      最近更新 更多