Clamp
Clamping guarantees the return value is within the provided range.
Why?
For example, maybe you’re computing a relative value based on some sensor input, assuming that 500 is the maximum. We want a percentage scale from 0..1:
But if sensorValue
rises above 500 unexpectedly, v
will be greater than 1 (ie. more than 100%). Other parts of our code might purposefully be able to handle this, but there are times where exceeding 100% cannot be permitted. Likewise, we might not want v
to be less than 0% because of assumptions made in other parts of our code.
To do this manually, we might write:
Usage
The above example is really all that Numbers.clamp is doing.
It takes an input value and optionally a range to clamp within. By default it uses a minimum of 0, a maximum of 1:
Revisiting an earlier example, we can scale a sensor value which we expect to be on the range of 0..500 and clamp it to be sure we’re always within 0..1:
A custom output range can be used as well:
If you are working with bipolar values (-1..1), use the Module Numbers.Bipolar .