Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does java have a clamp function?

Tags:

java

clamp

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?

like image 323
weston Avatar asked May 20 '13 19:05

weston


People also ask

What is a clamp function?

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.

What is Python clamp?

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.

What is math clamp?

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.


2 Answers

Is there any built in function for clamping to a range?

No.

like image 96
Matt Ball Avatar answered Sep 30 '22 02:09

Matt Ball


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.

like image 24
weston Avatar answered Sep 30 '22 04:09

weston