我可以这样在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 输入是向量?
无论如何,我如何使用 NLsolve、Optim 或 JuMP 在 Julia 中实现这一点?原始问题有超过 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.
感谢您的建议!
最佳答案
根据 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
谢谢!
关于julia - 在 Julia 中求解非线性方程组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45545275/