求解Julia方程的非线性方程组

Solving a nonlinear system of equations in Julia

我可以用这种方式在Matlab中编写函数:

1
2
3
4
5
6
function res=resid(theta,alpha,beta);
RHS=[];
LHS=[];
RHS= theta-alpha;
LHS= theta*beta;
res = (LHS-RHS);

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

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

这将返回[6.0; 6.0]。 选项"[]"是否表示输入是矢量?

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

我可以在Julia中实现这个功能:

1
2
3
4
5
6
7
8
h! =function (theta)
RHS=[];
LHS=[];
RHS= theta-alpha;
LHS= theta*beta;
res= (LHS-RHS);
return res;
end

但只需使用NLsolve:

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

返回:

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

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

1
2
using Optim
optimize(h!, a01)

返回:

1
2
3
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.

谢谢你的建议!


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

1
2
3
4
5
6
7
8
h =function (theta)
RHS=[];
LHS=[];
RHS= theta-alpha;
LHS= theta*beta;
res= (LHS-RHS);
return res;
end

并使用not_in_place:

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

返回解决方案:

1
2
3
4
5
6
7
8
9
10
11
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

谢谢!