Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

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?

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?

18.76 * 2 = 37.52 ---> 37 /2 = 18.5 this will return the Largest increment value that is SMALLER than the Test value.

AW

AW

while (lowest <= highest) {

mid = (lowest + highest) / 2;

if(value>array[mid]) lowest=mid+1;

else highest=mid-1;

}

//now we have highest=lowest-1 and we just choose either one

if(highest<0) return lowest;

else if(lowest>=nbins) return highest;

else return (value-array[highest]>arra

This works with arbitrary float values for distance bins. If you already know that you have all values from 1.5 to 23.5 at .5 increment you can just do:

index=floor((value-array[0

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

with no need for binary search.

Thanks very much for these solutions.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.

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;