Slot a floating point number

Hi All. I know there has got to be a better way to do this than what I am doing. I currently need to slot a floating point number in a bin and then do other things with it. This is not the actual bins, they could be almost any value in a reasonable range for the data. Is there some other way of getting the input value’s bin other than doing a case statement like below:

Select Case ValueToBeSlotted
Case 0.1 to 0.14999999999
’ call another routine
Case 1.5 to 3.999999999
’ call another routine
Case 4.0 to 4.49999999
’ call another routine
Case 4.5 to 5.99999999
’ call another routine
Case a bunch more bins…
’ call another routine
End Select

This works, but there are many bins and it is in a high traffic area so I’d like to optimize this some way if I can. If it were integers I was dealing with I could do other things, but I’m stumped on this example with a floating point input and bins. Thanks for any guidance.

The first thing I would suggest is to take advantage of the fact that the select will only execute the first matching case to eliminate “holes” such as between 3.999999999 and 4.0 and that it can compare against a boolean.

Select case true
case ValueToBeSlotted<1.5
//
case ValueToBeSlotted<4
//
case ValueToBeSlotted<4.5
//
case ValueToBeSlotted<6
end Select

Another idea if the bin values are not predefined, and depending on how your code is structured, would be to pass an array of bin values and delegates. Then the function could loop through the array and call the appropriate function based on the Value passed in.

Thanks, Jim. That’s an idea, I am guessing that searching through an array (or even better, doing a binary search) is a lot faster than using Case Statements?

I haven’t tested, but I would bet a case statement would be faster, but likely not significantly unless you have millions of iterations. The benefit of arrays would be the flexibility of being able to change the bin values (and associated functions) at runtime.

Do you really need to call different routines? I don’t know what you intend to do but I’ve seem weird processing rules in the past like this bellow that could be summarized better in just one function for example:

// Not the best way...

Global val1 As Double = 1.0
Global val2 As Double = 0.0

Select Case val1
Case Is < 1.5
  Call IsLessThan15()
Case Is < 2.0
  Call IsLessThan20()
End Select

Sub IsLessThan15
  var2 = 1.5
End Sub

Sub IsLessThan20
  var2 = 2.0
End Sub
//——— That’s “better”…

Dim val1 As Double = 1.0
Dim val2 As Double = 0.0

val2 = GetProperVal(val1)

Function GetProperVal (v As Double) As Double
  If v < 1.5 Then Return 1.5
  If v < 2.0 Then Return 2.0
  Return 0.0
End Function

No, I just stuck that in there to illustrate the need for Bins. I was much more concerned about how to slot the Floating point number.