我试图在Julia中实现多变量Newton方法,但遇到了“无metehod匹配”错误。下面是我的实现和我用来调用它的代码。
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
Invokation尝试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)
Invokation尝试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中正确实现和调用多变量Newton方法?
虽然他们可能会返回Vector
或Matrix
,但f
和J
都是函数。将newton
s签名更改为
function newton(f::Function, J::Function, x)
将使您的实施工作。
作为旁注,您可能希望避免指定类型,除非有必要,并使用动态类型和Julia的类型系统的强大功能。代码应尽可能通用。例如,你的newton
函数不能用x
作为来自SArray
的StaticArrays
或来自其他包的其他数组类型,因为它们的类型不会是<: Vector
。但如果省略该类型,则您的函数将与其他类型一起使用。请注意,编译函数后,您不会丢失任何性能。
请参阅Julia文档Style Guide中的相关讨论。