概括 Julia 中 nlsolve 函数的输入

问题描述 投票:0回答:1

这个问题已经在其他平台问过了,但我还没有得到答案。

https://discourse.julialang.org/t/generalizing-the-inputs-of-the-nlsolve-function-in-julia/

使用 Julia 中的 SymPy 进行大量处理后,我生成了一个非线性方程组。我的系统分配在 NxS 矩阵中。像这样的东西(NN = 2,S = 2)。

我想调整系统以使用 NLsolve 软件包。对于 NN=1 和 S =1 的情况,我做了一些无用功。 system_equations2 函数给出了非线性系统,如图所示

using SymPy
using Plots
using NLsolve

res =  system_equations2() 

为了模拟输出,我这样做:

NN = 1
S = 1
p= [Sym("p$i$j") for i in 1:NN,j in 1:S]
res = [ Eq( -331.330122303069*p[i,j]^(1.0) + p[i,j]^(2.81818181818182) -  1895.10478893046/(p[i,j]^(-1.0))^(2.0),0 ) for i in 1:NN,j in 1:S]
resf = convert( Function,  lhs( res[1,1] ) )
plot(resf, 0 ,10731)

现在

resf = convert( Function,  lhs( res[1,1] ) )

# This for the argument in the nlsolve function
function resf2(p)
    p = Tuple(p)[1]
    r = resf(p)
    return r
end

现在,我找到了零

function K(F,p)
F[1] = resf2(p[1])
end

nlsolve(K , [7500.8])

我想将此价格推广到任何 NN 和任何 S。我相信有一种更简单的方法可以做到这一点。

julia nonlinear-functions
1个回答
0
投票

这里的解决方案涉及两个因素。一是 NonlinearSolve.jl 对参数有显式支持,因此您只需传入

NN
S
等参数即可。但现在,如果您想以符号方式构建方程,NonlinearSolve.jl 可以连接到 ModelingToolkit.jl,以便以简单的方式生成数值问题。这是这样做的一个例子:

using ModelingToolkit, NonlinearSolve

@variables x y z
@parameters σ ρ β

# Define a nonlinear system
eqs = [0 ~ σ * (y - x),
    0 ~ x * (ρ - z) - y,
    0 ~ x * y - β * z]
@named ns = NonlinearSystem(eqs, [x, y, z], [σ, ρ, β])

guess = [x => 1.0,
    y => 0.0,
    z => 0.0]

ps = [σ => 10.0
    ρ => 26.0
    β => 8 / 3]

prob = NonlinearProblem(ns, guess, ps)
sol = solve(prob, NewtonRaphson())

因此,要利用这一点,您可以简单地从 SymPy 更改为 Symbolics 表达式,并使用 MTK NonlinearSystem 从符号表达式构造数值问题。在你的问题上,这看起来像:

using ModelingToolkit, NonlinearSolve
NN = 1
S = 1
@variables p[1:NN,1:S]
i = 1
j = 1
-331.330122303069*p[i,j]^(1.0) + p[i,j]^(2.81818181818182) -  1895.10478893046/(p[i,j]^(-1.0))^(2.0)

eqs = (@. 0 ~ -331.330122303069*p^(1.0) + p^(2.81818181818182) -  1895.10478893046/(p^(-1.0))^(2.0)) |> collect |> vec
@named sys = NonlinearSystem(eqs, vec(p), [])
prob = NonlinearProblem(sys, [p[1,1] => 1.0])
solve(prob)

#=

retcode: Success
u: 1-element Vector{Float64}:
 9.947428729753849e-23
 
=#

请注意,我们不推荐 NLsolve,并且在 SciML 的所有数值工具中已将其弃用于 NonlinearSolve.jl。

© www.soinside.com 2019 - 2024. All rights reserved.