Problem with NLSolve: cant find x st f(x) =0

So, I have a code in matlab and I am trying to translate it to Julia.
Im not being able to run this NLSolve in Julia. It returns me a domain error… probably because there is x^eta, where eta = 0.5.

But what makes no sense for me is that it runs in matlab. I have even tried to use ’ fzero ’ in Julia, and it still does not work: returns domain problem (but with different error outcome).

I would not say there is an error in my function (PrivateF) itself because when I run only this function with arbitrary values, both Julia and Matlab returns the same value. For example, if x=10, both matlab and julia results are equal.

Therefore, I think the problem is in the optimization part of NLsolve / fzero (roots package).

The code is just below, both for matlab and Julia. If anyoen could help me, I would be extremaly grateful.


#%% Matlab
function F = PrivateF(x, kappa , zeta , eta , beta , y , b , s_p, rr, tauu)
F = [kappa *x(1)^(1-eta ) /zeta  - (1-beta )*(y -b )/(rr+tauu+s_p+beta *zeta *x(1)^eta )];

#% Solving system in Matlab 
[theta ,fval,exitflag] = fsolve(@(x) PrivateF(x,kappa , zeta , eta , beta , y , b , s_p, r, tauu), x0 ,optimset('Display','off', 'TolFun',1.0e-009));

# end matlab code

### Julia
function PrivateF(x, kappa , zeta , eta , beta , y , b , s_p, rr, tauu)
    F = [kappa *(x[1])^(1-eta ) / zeta  - (1-beta ) * (y -b )/(rr+tauu+s_p+beta *zeta *x[1]^eta )];
    return F

#Solving system
x0 = [10.0]; #starting guess

f_aux = (x -> PrivateF(x, kappa , zeta , eta , beta , y , b , s_p, r, tauu))
theta  = nlsolve(f_aux, x0).zero

#even tried with fzero
theta = fzero(f_aux, x0[1])

Thank you very much!

It looks like your function is only defined for positive x — so maybe mcpsolve() (from NLsolve.jl) is a better method for your case.

Does this work for you?

julia> theta  = nlsolve(x -> f_aux(max.(0.0, x)), x0).zero
1-element Vector{Float64}:

Thank you very much!!! Exactly the same outcome that I had in Matlab.

I didnt know this (max.(0.0,x)) formulation.

The error your original code produces, indicates that your (real) function PrivateF is defined only on the non-negative real axis. max(0, x) insulates PrivateF from any negative x the root-finding algorithm throws at it.