# Can't seem to get NLsolve to converge

**URL:** https://discourse.julialang.org/t/cant-seem-to-get-nlsolve-to-converge/40845
**Category:** New to Julia
**Tags:** question
**Created:** [June 6, 2020, 1:15am UTC](https://discourse.julialang.org/t/cant-seem-to-get-nlsolve-to-converge/40845 "2020-06-06T01:15:13Z")
**Posts on this page:** 6
**Page:** 1

<div class="post-metadata">

### Author: ![Mark\_Williams](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mark_williams/32/7668_2.png) [@Mark\_Williams](https://discourse.julialang.org/u/Mark_Williams)
#### Post date: [June 6, 2020, 1:15am UTC](https://discourse.julialang.org/t/cant-seem-to-get-nlsolve-to-converge/40845/1 "2020-06-06T01:15:13Z")

</div>

Please note: I’ve cross posted this question on StackOverflow.  
[here](https://stackoverflow.com/questions/62225913/cant-seem-to-get-nlsolve-to-converge-in-julia-can-you-suggest-any-tips)

I’m trying to solve a life cycle problem in economics using Julia but I’m having trouble with NLsolve. The model boils down to trying to solve two a two equation system to find optimal leisure hours and capital stock each working period. The economic agent after retirement sets leisure = 1 and I only need to solve a single non linear equation for capital. This part works fine. It’s solving the two equation system that seems to break down.

As I’m fairly new to Julia / programming in general so any advice would be very helpful. Also advice / points / recommendations on all aspects of the code will be greatly appreciated. The model is solved backwards from the final time period.

My attempt

```julia
using Parameters
using Roots
using Plots
using NLsolve
using ForwardDiff

Model = @with_kw (α = 0.66,
                  δ = 0.02,
                  τ = 0.015,
                  β = 1/1.01,
                  T = 70,
                  Ret = 40,
                  );

function du_c(c, l, η=2, γ=2)
    if c>0 && l>0
        return (c+1e-6)^(-η) * l^((1-η)*γ)
    else
        return Inf
    end
end

function du_l(c, l, η=2, γ=2)
    if l>0 && c>0
        return γ * (c+1e-6)^(1-η) * l^(γ*(1-η)-1)
    else
        return Inf
    end
end

function create_euler_work(x, y, m, k, l, r, w, t)
    # x = todays capital, y = leisure
    @unpack α, β, τ, δ, T, Ret = m
    c_1 = x*(1+r) + (1-τ)*w*(1-y) - k[t+1]
    c_2 = k[t+1]*(1+r) + (1-τ)*w*(1-l[t+1]) - k[t+2]
    return du_c(c_1,y) - β*(1+r)*du_c(c_2,l[t+1])
end

function create_euler_retire(x, m, k, r, b, t)
    # Holds at time periods Ret onwards 
    @unpack α, β, τ, δ, T, Ret = m
    c_1 = x*(1+r) + b - k[t+1]
    c_2 = k[t+1]*(1+r) + b - k[t+2]
    return du_c(c_1,1) - β*(1+r)*du_c(c_2,1)
end

function create_euler_lyw(x, y, m, k, r, w, b, t)
    # x = todays capital, y = leisure
    @unpack α, β, τ, δ, T, Ret = m
    c_1 = x*(1+r) + (1-τ)*w*(1-y) - k[t+1]
    c_2 = k[t+1]*(1+r) + b - k[t+2]
    return du_c(c_1,y) - β*(1+r)*du_c(c_2,1)
end

function create_foc(x, y, m, k, r, w, t)
    # x = todays capital, l= leisure
    @unpack α, β, τ, δ, T = m
    c = x*(1+r) + (1-τ)*w*(1-y) - k[t+1]
    return du_l(c,y) - (1-τ)*w*du_c(c,y)
end

function life_cycle(m, guess, r, w, b, initial)
    @unpack α, β, τ, δ, T, Ret = m
    k = zeros(T+1);
    l = zeros(T);
    k[T] = guess

    println("Period t = $(T+1) Retirment, k = $(k[T+1]), l.0 = NA")
    println("Period t = $T Retirment, k = $(k[T]), l = 1.0")
    ########################## Retirment ################################

    for t in T-1:-1:Ret+1 
        euler(x) = create_euler_retire(x, m, k, r, b, t)
        k[t] = find_zero(euler, (0,100))
        l[t] = 1
        println("Period t = $t Retirment, k = $(k[t]), l = $(l[t])")
    end 
    ###################### Retirement Year #############################
    for t in Ret:Ret
        euler(x,y) = create_euler_lyw(x, y, m, k, r, w, b, t)
        foc(x,y) = create_foc(x, y, m, k, r, w, t)

        function f!(F, x)
            F[1] = euler(x[1], x[2])
            F[2] = foc(x[1], x[2])
        end

        res = nlsolve(f!, [5; 0.7], autodiff = :forward)
        k[t] = res.zero[1]
        l[t] = res.zero[2]
        println("Period t = $t Working, k = $(k[t]), l = $(l[t])")
    end 
    ############################ Working ###############################
    for t in Ret-1:-1:1
        euler(x,y) = create_euler_work(x, y, m, k, l, r, w, t)
        foc(x,y) = create_foc(x, y, m, k, r, w, t)

        function f!(F, x)
            F[1] = euler(x[1], x[2])
            F[2] = foc(x[1], x[2])
        end

        res = nlsolve(f!, [5; 0.7], autodiff = :forward)
        k[t] = res.zero[1]
        l[t] = res.zero[2]
        println("Period t = $t Working, k = $(k[t]), l = $(l[t])")
    end
    #####################################################################
    return k[1] - initial, k, l
end

m = Model();

residual, k, l = life_cycle(m, 0.3, 0.03, 1.0, 0.0, 0.0)

```

The code seems to break on period 35 with the error “During the resolution of the nonlinear system, the evaluation of following equations resulted in a non-finite number: [1,2]” However the solutions seem to go weird at period 37.

---

<div class="post-metadata">

### Author: ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)
#### Post date: [June 7, 2020, 2:47pm UTC](https://discourse.julialang.org/t/cant-seem-to-get-nlsolve-to-converge/40845/2 "2020-06-07T14:47:37Z")

</div>

I think you are running into non-positive consumption or labor choices, get infinities, which then combine into a `NaN`.

I would recommend reformulating the problem in a way that either avoids or incorporates this, eg using a reparametrization \tilde{l} = \log(l) and \tilde{c} = \log(c) and solving for all periods simultaneously (as a nonlinear system). The infinite-lifetime (dynasty) model or a one-shot version should provide a reasonable initial guess for the solver.

---

<div class="post-metadata">

### Author: ![Mark\_Williams](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mark_williams/32/7668_2.png) [@Mark\_Williams](https://discourse.julialang.org/u/Mark_Williams)
#### Post date: [June 7, 2020, 3:47pm UTC](https://discourse.julialang.org/t/cant-seem-to-get-nlsolve-to-converge/40845/3 "2020-06-07T15:47:52Z")

</div>

Thanks for the reply. Your exactly right! Turns out that instead of declaring c,l\<0 = Inf I can just set it to some arbitrary large number 1e6 or so. However it only converges for a very narrow interval of guesses. Not sure why that is. Cheers.

---

<div class="post-metadata">

### Author: ![Mark\_Williams](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mark_williams/32/7668_2.png) [@Mark\_Williams](https://discourse.julialang.org/u/Mark_Williams)
#### Post date: [June 7, 2020, 3:55pm UTC](https://discourse.julialang.org/t/cant-seem-to-get-nlsolve-to-converge/40845/4 "2020-06-07T15:55:55Z")

</div>

I didn’t want to formulate the problem as a large non linear system. With the way it’s written it exploits the time structure to make it more efficient, well hopefully.

---

<div class="post-metadata">

### Author: ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)
#### Post date: [June 7, 2020, 4:44pm UTC](https://discourse.julialang.org/t/cant-seem-to-get-nlsolve-to-converge/40845/5 "2020-06-07T16:44:46Z")

</div>

> [@Mark\_Williams](#):
>
> With the way it’s written it exploits the time structure to make it more efficient, well hopefully.

I don’t think so; breaking it up to T intertemporal problems should be less efficient IMO because the solver will be constrained on the manifold defined by the Euler equations.

---

<div class="post-metadata">

### Author: ![Mark\_Williams](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mark_williams/32/7668_2.png) [@Mark\_Williams](https://discourse.julialang.org/u/Mark_Williams)
#### Post date: [June 7, 2020, 5:08pm UTC](https://discourse.julialang.org/t/cant-seem-to-get-nlsolve-to-converge/40845/6 "2020-06-07T17:08:30Z")

</div>

I’ll certainly try your suggestion and report the results. Will be an Interesting comparison. I’m relatively new to programming in general so all advice is appreciated. Thanks.
