Easier way to calculate an adjusted proportion?

Sorry if this has been answered before, but I have no clue what to actually call this, so all I have to go off is a description.

If I input a float Na that exists within range A, I want to output float Nb that is the same proportion within range B.

Say I have a float A with range (2,4).
Then I have float B with range (15,23).
If I input 3 (halfway between 2 and 4), it should output 19 (halfway between 15 and 23).

Here’s what I’ve written for doing the calculations:

float AdjustedProportion(float input)
    {
        //Convert to percent of first range
        float percent = (maxA - input) / (maxA - minA);

        //Convert back to number within second range
        return (maxB - (percent * (maxB - minB)));
    }

This works fine, but I was wondering if there is a better way to write this or if Unity has a built in Mathf function specifically for this.

You will find many posts if you search for converting values from one range to another, such as:
https://stackoverflow.com/questions/929103/convert-a-number-range-to-another-range-maintaining-ratio

You may find a few slightly shorter versions or tips on handling special cases there.
I dont think unity has a Mathf function for this. Might be wrong. But if what you have works, why change it?

Here’s a thread on that: I feel like I'm forced into using InverseLerp whenever I use Lerp.

The first post is from someone using inverselerp (to get the percent – your first line) followed by lerp (your second line). Then there are several people playing with custom rescale function (which is just what you write, as a function). Basically, the thread beats to death that you can make it look different, but there’s no obvious better way.

Your code is great!

My only quibble is that you’re doing everything with an inverted percent.

The math works out obviously, but to me a percent should be 0.0 at min and 1.0 at max

Yours is exactly the opposite. If you doubt me, print out the value of percent and see.

Personally, I would write it as:

    float AdjustedProportion(float input)
    {
        //Convert to percent of first range
        float percent = (input - minA) / (maxA - minA);

        //Convert back to number within second range
        return minB + percent * (maxB - minB);
    }

That way if you ever have to debug it the numbers aren’t 1.0f - percent, they’re “just” percent.

1 Like