K. *_*son 2 newtons-method julia
我试图在 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
Run Code Online (Sandbox Code Playgroud)
调用尝试 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)
Run Code Online (Sandbox Code Playgroud)
运行上述代码时,抛出以下错误:
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)
Run Code Online (Sandbox Code Playgroud)
调用尝试 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
Run Code Online (Sandbox Code Playgroud)
当尝试像尝试 2 那样调用该方法时,我没有遇到任何错误,但该过程永远不会终止。作为参考,我在 MATLB 中编写的多元牛顿法的相应实现在大约 10 秒内解决了示例中的方程组。
如何在 Julia 中正确实现和调用多元牛顿法?
虽然他们可能会返回一个Vector或一个Matrix,无论是f和J是函数。将newtons 签名更改为
function newton(f::Function, J::Function, x)
Run Code Online (Sandbox Code Playgroud)
将使您的实施工作。
作为旁注,除非必要,否则您可能希望避免指定类型,并使用动态类型和 Julia 类型系统的强大功能。代码应该尽可能通用。例如,您的newton函数不能x作为来自其他包的SArrayfromStaticArrays或其他数组类型使用,因为它们的类型不是<: Vector. 但是如果你省略类型,你的函数将适用于其他类型。请注意,一旦函数被编译,您将不会失去任何性能。
请参阅 Julia 文档样式指南中的相关讨论。
| 归档时间: |
|
| 查看次数: |
417 次 |
| 最近记录: |