Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

normalizing a list of doubles to range -1 to 1 or 0 - 255

I have a list of doubles in the range of anywhere between -1.396655 to 1.74707 could even be higher or lower, either way I would know what the Min and Max value is before normalizing. My question is How can I normalize these values between -1 to 1 or even better yet convert them from double values to char values of 0 to 255

Any help would be appreciated.

double range = (double)(max - min);
value = 255 * (value - min)/range
like image 520
Elgoog Avatar asked Apr 29 '12 22:04

Elgoog


3 Answers

You need a mapping of the form y = mx + c, and you need to find an m and a c. You have two fixed data-points, i.e.:

 1 = m * max + c
-1 = m * min + c

From there, it's simple algebra.

like image 68
Oliver Charlesworth Avatar answered Oct 07 '22 22:10

Oliver Charlesworth


The easiest thing is to first shift all the values so that min is 0, by subtracting Min from each number. Then multiply by 255/(Max-Min), so that the shifted Max will get mapped to 255, and everything else will scale linearly. So I believe your equation would look like this:

newval = (unsigned char) ((oldval - Min)*(255/(Max-Min)))

You may want to round a bit more carefully before casting to char.

like image 44
happydave Avatar answered Oct 07 '22 22:10

happydave


There are two changes to be made.

First, use 256 as the limit.

Second, make sure your range is scaled back slightly to avoid getting 256.

    public int GetRangedValue(double value, double min, double max)
    {
        int outputLimit = 256;

        double range = (max - min) - double.Epsilon; // Here we shorten the range slightly

        // Then we build a range such that value >= 0 and value < 1
        double rangedValue = (value - min) / range;

        return min + (int)(outputLimit * rangedValue);
    }

With these two changes, you will get the correct distribution in your output.

like image 44
Sean Vikoren Avatar answered Oct 07 '22 22:10

Sean Vikoren