16

The function lerp() is a common function in programming languages:

lerp(a, b, t) = a + t * (b - a).

Now for very many situatons I have an inverse function:

fraction(x, a, b) = (x - a) / (b - a).

This function is built so that

lerp(a, b, fraction(x, a, b)) == x

and

fraction(lerp(a, b, t), a, b) == t

However I'm not happy with the name "fraction". Is there a common name for this function?

hippietrail
  • 15,848
  • 18
  • 99
  • 158
Erik Leppen
  • 325
  • 1
  • 2
  • 8
  • In addition to my answer below, I'll also add that I like naming the `t` parameter “ratio” instead of “time” because it's often used as a ratio of one part to another part (so it's technically not the ratio but fraction part of the ratio). So I've been leaning in recent years towards names like `decudeRatio()` or `ratioOf()` or `proportionFrom()` (“proportion“ is another name I like despite not fitting the math definition exactly). This can be really clean in modern languages with named args, resulting in calls like `ratio(of: 3.5, in: 0.0...10.0)` or `(3.5).proportion(within: 0.0...10.0)`. – Slipp D. Thompson Jun 10 '20 at 03:48
  • My library has prel (x, xLo, xHi) returning 0 to 1. Also lerpxlh (yLo, yHi, x, xLo, xHi) returning a y value proportionate as x within xLo to xHi. – dcromley May 10 '21 at 00:32

1 Answers1

14

GLSL

GLSL's built-in functions include:

mix(), which works like your lerp() function.
smoothstep(), which works like your inverse-lerp function combined with hermite smoothing and a x = clamp(x, 0.0, 1.0).

You could consider the name linearstep() for your implementation.

Unity Engine

Unity's API includes:

Lerp()/LerpUnclamped()
InverseLerp(), which does exactly what your inverse-lerp function does.


Note: I wouldn't use the name fraction()— it seems that it would be easily confused with fract()/frac(), which do something completely different.

Slipp D. Thompson
  • 33,165
  • 3
  • 43
  • 43