Hey everyone,
I have a small numerical problem here. The main idea is that I try to approximate a univariate function, that needs to satisfy some constraint, with a polynomial. I had this already working with an older version of NLsolve and I run this code under Julia 0.6.4 using the package CompEcon. However, after letting the code rest for a while and updating packages, I stopped finding a solution to my problem. Here is the code:
using CompEcon
# Parameters
global γ = 2; # Risk aversion
global α = 0.4; # Capital share
global β = 0.9; # Discount factor
# First, create a grid using the QuantEcon toolbox
# Set the endpoints of approximation interval:
a = 2.0 # left endpoint
b = 3.0 # right endpoint
# Note: They have to be both integer or real. Important in Julia.
# Choose an approximation scheme. In this case, let us use an order 10
n = 3 # order of approximation
fspace = fundefn(:cheb, n, a, b) # define fspace
nodes = funnode(fspace)[1] # safe grid/nodes
Phi = funbase(fspace,nodes) # derive basis matrix Φ
using NLsolve
function f!(res, c_guess, fspace, nodes) # we want to find roots for f
global γ,α,β
K = nodes
con = funeval(c_guess,fspace,K)[1]
K_next = K.^α - con
con_next = funeval(c_guess,fspace,K_next)[1]
res = con.^(-γ) - β*con_next.^(-γ).*α.*K_next.^(α-1)
end
g!(res, c_guess) = f!(res, c_guess, fspace, nodes)
c_guess = Phi\nodes.^0.3 # some initial guess for parameters c
result = nlsolve(g!,c_guess)
I have put equivalent code in MATLAB, where it works and delivers a sensible solution. What may be the reason for this not to work in Julia and what can I do about it?
The Matlab code is the following (before running this code, you need to install the CompEcon Toolbox).
function [res] = ExampleProblem(c_guess,fspace,nodes)
gamma = 2;
alpha = 0.4;
beta = 0.9;
% Unscreened Investment
K = nodes;
con = funeval(c_guess,fspace,K);
K_next = K.^alpha - con;
con_next = funeval(c_guess,fspace,K_next);
% Save the residual
res = con.^(-gamma) - beta*con_next.^(-gamma).*alpha.*K_next.^(alpha-1);
end
n = 3;
a = 2;
b = 3;
fspace = fundefn('cheb', n, a, b);
nodes = funnode(fspace);
Phi = funbas(fspace,nodes);
c_guess = Phi\nodes.^0.3;
options = optimset('display','iter');
y = fsolve(@(x)ExampleProblem(x,fspace,nodes),c_guess,options);