How can i get a 0-1 range between two numbers?

Title is a bit nonspecific, so i’ll try to specify more here, i’m trying to interpolate a value depending on two numbers, i’ll leave an example below:

I want to lerp a number depending on how far down another number is from 1, with a lower limit of 0.8, but i don’t know how i would go along with converting that 0.2 gap into a range of 0-1, with 1 being 0 and 0.8 being 1, unfortunately i’m not the best with maths so i can’t really do this on my own, so any help works! :slight_smile: thanks in advance, and i will answer as many questions about this (especially because i wrote it like crap)

You’re close, this does relate to interpolating a little.

There’s a mapping function which does exactly this. Map to range.

function mapToRange(t, a, b, c, d)
	return c + ((d-c)/(b-a)) * (t-a)
end

Usage:
t is your number.
a, b are your input range.
c, d are your output range.


If I understand correctly, this is what you want to do? (I hope the explanation was clear enough to do it yourself for future implementations)

function mapToRange(t, a, b, c, d)
	return c + ((d-c)/(b-a)) * (t-a)
end

for i = 0, 1, .1 do
    print(mapToRange(i, 0, 1, 0, .8))
end

Out:

0.0 - 0
0.08 - 1
0.16 - 2
0.24 - 3
0.32 - 4
0.4 - 5
0.48 - 6
0.56 - 7
0.64 - 8
0.72 - 9
0.8 - 10
1 Like

I think you are describing an inverse lerp (linear interpolation)?

local function ilerp(value, minimum, maximum) do
    return (value - minimum) / (maximium - minimum)
end

print(ilerp(0.2, 0.2, 0.8)) -- 0
print(ilerp(0.5, 0.2, 0.8)) -- 0.5
print(ilerp(0.8, 0.2, 0.8)) -- 1
1 Like