<div dir="ltr">Dear FieldTrippers,<div><br></div><div>I'd like to report a bug in the 'nearest' function. It occurs at line 152, the first line of the following if statement:</div><div><br></div><div><div>indx2 = find(array<=val, 1, 'last');</div><div>indx3 = find(array>=val, 1, 'first');</div></div><div><div>if abs(array(indx2)-val) <= abs(array(indx3)-val)</div><div>    indx = indx2;</div><div>  else</div><div>    indx = indx3;</div><div>  end</div><div>  if ~wassorted</div><div>    indx = xidx(indx);</div><div>  end</div></div><div><br></div><div>In my case, the two values being compared should be considered equal (i.e. val is halfway between array(indx2) and array(indx3)). However due to precision issues, the condition is false and indx is set to indx3.</div><div><br></div><div>Specifically:</div><div>- In short format:</div><div>  val = -17.4930</div><div>  array(indx2) = -17.4940</div><div>  array(indx3) = -17.4920</div><div><br></div><div>- Full precision:</div>  val =  -17.492999999999999<br>  array(indx2) = -17.494000000000000 <div>  array(indx3) = -17.492000000000001</div><div><div><br></div><div>For me this leads to the 'begsampl' variable in line 223 of ft_timelockanalysis to be 2 when it should be 1, which then leads to an undersizing of subsequent variables, and finally an 'index exceeds matrix dimension' error at line 280. </div><div><br></div><div>I gather the precision issue was noted as a general problem a long time ago, and the if statement noted above was implemented as a fix for the 'nearest' function -- interestingly, the fix even notes that the choice of indx2 over indx3 when the condition is true is arbitrary (<a href="http://bugzilla.fcdonders.nl/show_bug.cgi?id=1943">http://bugzilla.fcdonders.nl/show_bug.cgi?id=1943</a>). But it seems that when val *should be* equidistant from its nearest neighbors in array, precision issues could cause an inequality in the differences, and thus cause 'nearest' to randomly select the lesser or greater of the neighbors. I guess it just so happens in my case that I need 'nearest' to arbitrarily select indx2, which it is designed to to do but fails because of the precision issue.</div><div><br></div><div>I did try the old (commented out) fix for precision in 'nearest' and it solved my problem, i.e. it selects the lesser of the two neighbors. The bug report notes this is a slower method, but I will revert to that unless it has been found to cause other problems.</div></div><div><br></div><div>Best,</div><div>Tim</div></div>