Value Remapping

Viewed 54588

Processing has a great function I use all the time:

map(value, low1, high1, low2, high2)

http://processing.org/reference/map_.html

It remaps value (that has an expected range of low1 to high1) into a target range of low2 to high2).

I want to understand the math behind it so I can use it in other languages. Anyone want to throw me a bone and help me reverse engineer it? I understand that it's a lerp that's been re-scaled and re-offset... feeling brain dead this morning.

5 Answers

Anyone wondering if there's a float-less version that keeps as much precision as possible, I made this:

int remap(int value, int input_min, int input_max, int output_min, int output_max)
{
    const long long factor = 1000000000;

    long long output_spread = output_max - output_min;
    long long input_spread = input_max - input_min;

    long long l_value = value;

    long long zero_value = value - input_min;
    zero_value *= factor;
    long long percentage = zero_value / input_spread;

    long long zero_output = percentage * output_spread / factor;

    long long result = output_min + zero_output;

    return (int)result;
}

Seems to work for me, not extensively tested (e.g. max is smaller than min is not tested).

The idea behind is it to enlarge the original value by using a bigger type so that divisions yield bigger numbers - which results in more precision.

In my case I used an expression (var * amount)-shift where var is value amount is amount of blendshapes and shift is value based on the index of the blendshape (shift by 1 and you get 0 if the value is 1 so the next blendshape starts of)

Related