diff --git a/optimize.cc b/optimize.cc index daf015a..63681af 100644 --- a/optimize.cc +++ b/optimize.cc @@ -124,14 +124,17 @@ return (r*r)/2; } -//central difference (f(x+h e_i) - f(x-h e_i))/(2h); xs is a working copy of x, restored on return +//central difference (f(x+h e_i) - f(x-h e_i))/(2h); xs is a working copy of x (unshared on entry), restored on return +//the user's funcgrad may keep a shallow copy of xs, hence copyonwrite() after each call before writing again template static T central_difference(const OptProblem *p, NRVec &xs, const NRVec &x, const int i, const T h) { xs[i]=x[i]+h; T d=p->funcgrad(xs,NULL); +xs.copyonwrite(); xs[i]=x[i]-h; d-=p->funcgrad(xs,NULL); +xs.copyonwrite(); xs[i]=x[i]; return d/(2*h); } @@ -163,9 +166,11 @@ for(int i=0; ip->funcgrad(xs,NULL)/(4*R*sn*sn); } + xs.copyonwrite(); xs[i]=x[i]; (*grad)[i]=w*d; }