当共域维度大于域维度时,Julia NLsolve 会给出 DimensionMismatch-Error

问题描述 投票:0回答:2
using NLsolve


function g!(G,x)
    G .= [x[1]^2-x[2] for i in 1:3]
end

nlsolve(g!,[0.1, 0.1])

此代码给出了

DimensionMismatch("array could not be broadcast to match destination")

当我使用

G .= [x[1]^2-x[2] for i in 1:2]
时,我没有收到错误。 NLsolve 似乎希望输入的大小与输出的大小相同。这是一个错误还是我做错了什么?

julia equation-solving
2个回答
0
投票

在新的 Julia 会话中,这不是一个

NLsolve
问题:

julia> function g!(G,x)
           G .= [x[1]^2-x[2] for i in 1:3]
       end
g! (generic function with 1 method)

julia> g!([0.0, 0.0], [1.0, 1.0])
ERROR: DimensionMismatch("array could not be broadcast to match destination")

这里我传递长度为 2 的

G
,然后在右侧创建一个长度为 3 的数组。然后,
.=
尝试将右侧创建的值逐个元素写入左侧数组,但数组的大小不兼容。更短地说,你本质上是在做:

julia> [0, 0] .= [1, 2, 3]
ERROR: DimensionMismatch("array could not be broadcast to match destination")

0
投票

请注意,您要解决的问题是非线性最小二乘问题,而不是非线性方程。它们之间的主要区别是,前者允许有欠定或超定系统,这使得获取输出向量的大小变得棘手。我建议查看 https://docs.sciml.ai/NonlinearSolve/stable/tutorials/getting_started/,其中描述了主要差异以及如何解决它们。

现在,来解决您的具体问题。

using NonlinearSolve

function g!(G, x, p)  # Note that we need to pass a parameter p for NonlinearSolve.jl
    G[1] = x[1]^2 - x[2]
    G[2] = x[1]^2 - x[2]
    G[3] = x[1]^2 - x[2]
    return nothing
end

现在我们将创建将

resid_prototype
作为 Zeros(3) 传递的函数,它告诉 NonlinearSolve.jl 残差向量的长度为 3

nlf = NonlinearFunction(g!; resid_prototype=zeros(3))
prob = NonlinearLeastSquaresProblem(nlf, [0.1, 0.1])

终于解决了。

solve
默认情况下将选择一个强大的多元算法,否则您也可以从 https://docs.sciml.ai/NonlinearSolve/stable/solvers/nonlinear_least_squares_solvers/

传入您选择的求解器
solve(prob)
© www.soinside.com 2019 - 2024. All rights reserved.