I want to generically interpolate between a range of input values (say, between A and B) and get a range of output values (say, between C and D). Sometimes I want to clamp the value (so that B+10000 still outputs D) and sometimes I don't. How do I do it?
For example, given input speeds between 20 mph and 80 mph, I want to adjust the zoom level of my map between 17 and 15:
Without Clamping
| \
| \
17 | \
| \
| \
| \
| \
15 | \
| \
+----------\-
20 80 \
With Clamping
|
17 |----
| \
| \
| \
| \
15 | ----
|
+------------
20 80
I found this utility function, but (a) it does not support clamping by itself, requiring a second function call, and (b) it only supports input between 0 and 1.
The general (unclamped) equation you want is:
For clamping, you can either clamp the output after you calculate the result:
Or you can clamp the input before you use it:
If the slope of the line does not change, and your clamping desires do not change, you can improve performance by pre-calculating it once and generating a function tailored to your input and needs:
In action: