pp11
pp11

Reputation: 309

Julia updates variable in a loop

I have a code that programs a value function iteration. The code is translate from Matlab. The first iteration rolls nicely, but in the second, the old value function gets updated at some point wrongly, though the second iteration still produces the equivalent result from matlab.

First, I declare the variables here:

sigma = 1.5;
delta = 0.1;
beta  = 0.95;
alpha = 0.30;
ks    = 1.0;
csy   = 0.2;
kmin  = 0.1*ks;
kmax  = 1.1*ks;
nbk   = 20;
devk  = (kmax-kmin)/(nbk-1);
k     = linspace(kmin,kmax,nbk)';
v0    = zeros(nbk,1);
v0    = (csy*k.^alpha).^(1-sigma);
v0    = v0';
v     = zeros(nbk,1);
ik1   = zeros(nbk,1);
iter  = 1;
crit  = 1;
tol   = 1e-6;

second, I execute this (it is a while loop), but I prefer executing it one iteration after the other):

 for i=1:nbk
      imin =  max(ceil(((1-delta)*k[i]-kmin)/devk)+1.0,1);
      imax =  min(floor((k[i]^alpha+(1-delta)*k[i]-kmin)/devk)+1.0,nbk);

      imin=trunc(Int, imin);
      imax=trunc(Int, imax);
      c = k[i]^alpha+(1-delta)*k[i]-k[imin:imax];
      u = (c.^(1-sigma)-1)/(1-sigma);
      (v[i],itmp)= findmax(u+beta*v0[imin:imax]);
      ik1[i] = imin-1+itmp;
   end;

  v0  = v;

Running this second part the first time prints correctly v and the error:

[-9.41322; -6.19362; -4.35414; -3.01282; -1.95198; -1.07545; -0.330322; 0.316098; 0.885574; 1.39337; 1.85067; 2.29198; 2.69438; 3.06364; 3.40432; 3.72013; 4.0141; 4.28875; 4.54618; 4.79853]
error:5.124021319754114

Running it a second time, leads to an error because now v0 becomes I don't know why equal to v (though v is still produced correctly, like in Matlab):

[-7.06807; -4.7177; -3.24724; -2.16729; -1.30218; -0.578569; 0.0429673; 0.586699; 1.09022; 1.54641; 1.98317; 2.37955; 2.7416; 3.07412; 3.38098; 3.66532; 3.92974; 4.18466; 4.42981; 4.66936]
error:0.0

So the error is zero, which should not be the case after two iterations. Any ideas?

Upvotes: 2

Views: 951

Answers (1)

tim
tim

Reputation: 2096

When you set v0 = v, both variables refer to the same area in memory, i.e, when you try to modify one, you actually modify both at the same time.

Use copy!(v0, v) to copy the content of v into v0. Then the arrays can be modified independently.

Upvotes: 6

Related Questions