Suppose I have a value
, I usually do this to "clamp" it to a range, here the range [0..1]
. That is if it is below the range start, increase it to the range start, it above the range end, reduce it to the range end.
clampedValue = Math.max(0, Math.min(1, value));
Is there any built in function for clamping to a range?
A clamp is a fastening device used to hold or secure objects tightly together to prevent movement or separation through the application of inward pressure.
Python – PyTorch clamp() method clamp() method clamps all the input elements into the range [ min, max ] and return a resulting tensor. Syntax: torch.clamp(inp, min, max, out=None) Arguments. inp: This is input tensor. min: This is a number and specifies the lower-bound of the range to which input to be clamped.
Clamps the given value between a range defined by the given minimum integer and maximum integer values. Returns the given value if it is within min and max. Returns the min value if the given value is less than the min value.
Is there any built in function for clamping to a range?
No.
Having looked at the generic clamp method offered up in another answer, it is worth noting that this has boxing/unboxing considerations for primitive types.
public static <T extends Comparable<T>> T clamp(T val, T min, T max) {...} float clampedValue = clamp(value, 0f, 1f);
This will use the Float
wrapper class, resulting in 3 box operations, one for each parameter, and 1 unbox operation for the returned type.
To avoid this, I would just stick to writing it long hand or use a non-generic function for the type you want:
public static float clamp(float val, float min, float max) { return Math.max(min, Math.min(max, val)); }
Then just overload with identical methods for every primitive type you require.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With