Hi,
Note: I have cross-posted this to stackexchange: optimization - Julia: NLsolve providing different solution each run and sometimes returns NaN? - Stack Overflow
I am trying to replicate some matlab code as a part of my master thesis from the paper Zhu, H. (2014). Do dark pools harm price discovery?
I have a system of two equations which i solve using the “NLsolve” package in Julia. The issue is that NLsolve returns a different solution for f[1] each time i run the code and sometimes it returns a “NaN”.
I am not sure what is causing this?
Here is a code excerpt:
using NLsolve;
function G(x)
min(1,x/C)
end;
function Ginv(x)
min(C,x*C)
end;
function F(x)
1-exp(-x/2)
end;
μᵤ = 60;
σᵤ = sqrt(μᵤ);
a = [0 0];
b = [3*μᵤ 3*μᵤ];
r_bar = 0.91;
μ_bar = 20;
C = 2;
x₀ = [μ_bar, 1.0];
function f_temp!(x,f)
f[1] = μ_bar*F((1-G(1))*μᵤ*x[2]/(x[1]+(1-G(1))μᵤ))-x[1]
f[2] = 1-x[1]/(x[1]+(1-G(1))μᵤ)-r_bar
end;
x = nlsolve(f_temp!, x₀)
μ_hat₀ = x.zero[1];
σ₀ = x.zero[2];
In the second part of my code i think the same issue with “NLsolve” persists and causes the error “During the resolution of the non-linear system, the evaluation of the following equation(s) resulted in a non-finite number: [1]”
σ = exp.([LinRange(log(0.02),log(σ₀),30)
LinRange(log(σ₀*1.1),log(70),20)]);
K = length(σ);
α₀ = fill(NaN,(K,2));
αₑ = fill(NaN,(K,2);
μᵢ = fill(NaN,(K,2));
function func!(x,f)
f[1] = x[2]/(x[2]+x[1]*μᵤ)-Ginv(1-x[1])
f[2] = μ_bar*F(x[1]*μᵤ*σₙ/(x[2]+x[1]*μᵤ))-x[2]
end;
for n=1:K
global σₙ
σₙ = σ[n]
if n==1
x = nlsolve(func!,[1-G(1), μ_bar])
else
x = nlsolve(func!,[real(αₑ[n-1,1]), μ_bar])
end
αₑ[n,1] = x.zero[1]
α₀[n,1] = 1-αₑ[n,1]
μᵢ[n,1] = x.zero[2]
end;
All help appreciated.
Best regards,
Rasmus