Hi there.
I’ve come upon a situation where I need to filter a numeric value (of any type) so it falls into a predetermined set of output values.
For example, let’s say we have an integer whose range is 0-200:
final int MIN = 0;
final int MAX = 200;
And we want to, given an input in said range, filter it out so we get one of three values:
final int HIGH = 200;
final int MED = 100;
final int LOW = 0;
So, we would have a filter method doing something like this:
int filter(int input) { ... }
filter(10); // Output: 0
filter(30); // Output: 0
filter(110); // Output: 100
filter(180); // Output: 200
In other words:
int filter(int input)
{
if(input < MAX/3) return LOW;
if(input < 2*(MAX/3)) return MED;
return HIGH;
}
So, my question would be… What is the most efficient way to do this type of operation? This code is meant to be executed many (as in once per pixel at least) times per frame. Is there some bit-shifting trickery that could be used? Some arithmetic magic?
Currently, my generalized (using doubles as the value type) implementation is as follows:
public static double filterValue(double value, int slices, double MIN, double MAX)
{
if(value <= MIN) return MIN;
if(value >= MAX) return MAX;
double increment = MAX / slices;
for(int i = 1; i < slices; i++)
{
if(value - (i*increment) < MIN)
{
return (i*increment);
}
}
return MAX;
}
To me, it looks like there are way too many ifs, multiplications and divisions in there. :persecutioncomplex:
Comments like “don’t use doubles you dolt, do it with byte-shifted integers!” are the type of ideas I am looking for.