% FOC_VFI_PREC.m is a routine for computing capital satisfying the FOC; see 
% "How to Solve Dynamic Stochastic Models Computing Expectations Just Once" 
% by Kenneth L. Judd, Lilia Maliar, Serguei Maliar and Inna Tsener, (2016),
% Quantitative Economics, forthcoming, (henceforth, JMMT, 2016).
%
% -------------------------------------------------------------------------
% Inputs:    "k1" is next-period capital;
%            "k0" is current capital;
%            "z0" is current productivity;
%            "A" is the normalizing constant in production;
%            "alpha" is the share of capital in production;
%            "gam" is the utility-function parameter;
%            "delta" is the depreciation rate;
%            "beta" is the discount factor; 
%            "vcv" is the variance of the shock
%            "rho" is the autocorrelation coefficient in the process for
%                shock;
%            "vf" is the vector of polynomial coefficients in the approximated 
%               value function;  
%            "D" is the degree of polynomial approximation
%
% Output:    "dif_FOC" is the difference between the right and left hand 
%            sides of the FOC 
% -------------------------------------------------------------------------
% Copyright © 2016 by Lilia Maliar, Serguei Maliar and Inna Tsener. All 
% rights reserved. The code may be used, modified and redistributed under 
% the terms provided in the file "License_Agreement.txt".
% -------------------------------------------------------------------------


function [diff_FOC] = FOC_VFI_PREC(k1,k0,z0,A,alpha,gam,delta,beta,vcv,rho,vf,D)


% Precomputation of integrals for derivative of the value function
%-----------------------------------------------------------------
intV = Integrals_PREC_2d(D,vcv)'; % Precomputed integrals for constructing 
                                  % expectation functions
vf1 = vf.*intV;                   % A new vector of coefficients
                                  % with precomputed integrals
X1der = Polynomial_deriv_2d([k1 z0.^rho],D);  
                            % Construct the derivatives of basis functions 
                            % of polynomial approximating value function 
EVder = X1der*vf1;          % Evaluate derivative of value function
diff_FOC = beta*EVder-((1-delta)*k0+A*z0*k0^alpha-k1)^(-gam); 
                            % Evaluate the difference between left and right
                            % sides of the FOC 
