【问题标题】:Solving a nonlinear system of equations in Julia在 Julia 中求解非线性方程组
【发布时间】:2018-01-14 15:55:10
【问题描述】:

我可以这样在Matlab中写函数:

function res=resid(theta,alpha,beta); 
RHS=[];
LHS=[];
RHS= theta-alpha;
LHS= theta*beta;
res = (LHS-RHS);

我们设置参数,调用函数:

alpha=0.3;beta=0.95;
a01=[1.0;1.0];
th=fsolve('resid',a01,[],alpha,beta)

这将返回 [6.0;6.0]。选项“[]”是否表示 fsolve 输入是一个向量?

无论如何,我如何在 Julia 中使用 NLsolve、Optim 或 JuMP 来实现这一点?原始问题有超过 10 个变量,所以我更喜欢向量方法。

我可以在 Julia 中实现该功能:

h! =function (theta) 
RHS=[];
LHS=[];
RHS= theta-alpha;
LHS= theta*beta;
res= (LHS-RHS); 
return res;
end

但只是使用 NLsolve:

a01 = [1.0;1.0];
res = nlsolve(h!,a01)

返回:

MethodError: no method matching (::##17#18)(::Array{Float64,1}, ::Array{Float64,1})
Closest candidates are:
  #17(::Any) at In[23]:3

如果我选择使用 Optim,我会得到:

using Optim
optimize(h!, a01)

返回:

MethodError: Cannot `convert` an object of type Array{Float64,1} to an object of type Float64
This may have arisen from a call to the constructor Float64(...),
since type constructors fall back to convert methods.

感谢您的建议!

【问题讨论】:

  • 你能说明哪些部分,例如您查看过的 NLsolve 文档,特别是什么导致了您的问题?
  • 有更新!
  • 您查看过 NLsolve.jl 文档吗?这不是你定义函数的方式。如果您的功能没有到位,请使用nlsolve(not_in_place(f), initial_x)。但是为什么不直接使用文档中的就地版本呢? function f!(x, fvec)第一个向量是输入第二个是输出?
  • 谢谢! not_in_place(f) 会这样做。我只需要保留函数的奇怪定义!

标签: julia


【解决方案1】:

根据 Chris Rackauckas 的建议,解决方案是保留 h 的定义:

h =function (theta) 
RHS=[];
LHS=[];
RHS= theta-alpha;
LHS= theta*beta;
res= (LHS-RHS); 
return res;
end

并使用 not_in_place:

a01 = [1.0;1.0];
solve = nlsolve(not_in_place(h),a01)

返回解决方案:

Results of Nonlinear Solver Algorithm
 * Algorithm: Trust-region with dogleg and autoscaling
 * Starting Point: [1.0,1.0]
 * Zero: [6.0,6.0]
 * Inf-norm of residuals: 0.000000
 * Iterations: 3
 * Convergence: true
   * |x - x'| < 0.0e+00: false
   * |f(x)| < 1.0e-08: true
 * Function Calls (f): 4
 * Jacobian Calls (df/dx): 4

谢谢!

【讨论】:

  • 按照惯例,如果函数h! 不是变异函数,则不应调用它。见this page in the docs。此外,您应该将此标记为解决方案,以便其他 SO 用户可以看到它已解决。
  • 好的!但由于我自己写了一个答案,我将能够在 48 小时内标记它。但我会做到的……
猜你喜欢
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多