I have a float array representing distance bins from 1.5 to 23.5 at 0.5 increments. I am trying to find the nearest float using a binary search so that if, for example, i have a distance of 18.76 the search returns the index of the array containing value 18.5.

Here is what i have so far but this seems to skip counts at the mid-point distances:

int nearest(float array[], const int nbins, const float value, const float binwidth)

{

float dx;

int mid;

int lowest = 0;

int highest = nbins - 1;

while (lowest <= highest)

{

mid = (lowest + highest) / 2;

dx = value - array[mid];

// if the midpoint value is the closest

if ( (dx < binwidth) && (dx >= 0.0) )

return mid;

if (dx < 0.0)

highest = mid - 1;

else

lowest = mid + 1;

}

cout << "Failed finding: " << value << endl;

return -1;

}

Any ideas?

index=floor((value-l)/r+.5

if(index>=nbins) index=nbins-1;

or, if you want to round down (instead of round to the nearest):

index=floor((value-l)/r);

if(index>=nbins) index=nbins-1;