# Why is Nearest not giving me expected result

I have the following list:

numbers={0.,0.6,0.8,1.,1.2,1.4,1.8}


Then I calculate the midpoints:

midpoints=Table[0.5*(numbers[[ii+1]]+numbers[[ii]]),{ii,Length[numbers]-1}]

>>> {0.3,0.7,0.9,1.1,1.3,1.6}


When I plug this into Nearest, I get sometimes two numbers, sometimes the lower and sometimes the upper:

Nearest[numbers,#]&/@midpoints

>>> {{0.,0.6},{0.6},{0.8,1.},{1.2},{1.2},{1.8}}


By the way, this other form for calculating the midpoints is giving me strange results:

(0.5*(numbers[[# + 1]] + numbers[[#]])) & /@ (Range@Length@numbers - 1)

>>> {0.5 (0. +List), 0.6, 1.4, 1.8, 2.2, 2.6, 3.2}


Where is my mistake?

• Regarding the last issue, use Range[1, Length@numbers - 1] instead of Range@Length@numbers - 1.
– kglr
Dec 9, 2014 at 19:45
• I think you have two questions here. Your question on Nearest could be: Why do Nearest[{0.6,0.8},0.7] give one result (0.6), while Nearest[{0.8,1.0},0.9] give two results (0.8 and 1.0)? About your construction of midpoints, I don't see what is wrong with your approach, but another way would be midpoints = ReplaceList[numbers, {___, a_, b_, ___} -> Mean[{a, b}]]. Dec 9, 2014 at 19:46
• From the documentation - If the internal implementation is using Round this could explain your results. Round rounds numbers of the form x.5 toward the nearest even integer. Dec 11, 2014 at 10:51

It's a rounding problem. You can see it from:

numbers = Rationalize@{0., 0.6, 0.8, 1., 1.2, 1.4, 1.8}
midpoints = MovingAverage[numbers, 2]
Nearest[numbers, #] & /@ midpoints

(* {{0, 3/5}, {3/5, 4/5}, {4/5, 1}, {1, 6/5}, {6/5, 7/5}, {7/5, 9/5}} *)


BTW, for long lists and reusable results use Nearest this way:

f = Nearest[numbers];
f /@ midpoints

• Thanks! I didn't know that there were these rounding problems. Is there a logic behind it, to see when it would round up and when down or it just depends on the machine precision or something? Dec 10, 2014 at 13:57
• @Santi I don't know. And that's probably prone to change from one version to the next. Dec 10, 2014 at 14:27