Is there a method to limit/clamp a number?
Ruby 2.4.0 introduces Comparable#clamp: 523.clamp(0, 100) #=> 100
Ruby 2.4.0 introduces Comparable#clamp: 523.clamp(0, 100) #=> 100
Numpy’s clip function will do this. >>> import numpy >>> numpy.clip(10,0,3) 3 >>> numpy.clip(-4,0,3) 0 >>> numpy.clip(2,0,3) 2
This is pretty clear, actually. Many folks learn it quickly. You can use a comment to help them. new_index = max(0, min(new_index, len(mylist)-1))
Both GCC and clang generate beautiful assembly for the following simple, straightforward, portable code: double clamp(double d, double min, double max) { const double t = d < min ? min : d; return t > max ? max : t; } > gcc -O3 -march=native -Wall -Wextra -Wc++-compat -S -fverbose-asm clamp_ternary_operator.c GCC-generated assembly: maxsd … Read more
OP asks for this implementation in a standard library: int ensureRange(int value, int min, int max) { return Math.min(Math.max(value, min), max); } boolean inRange(int value, int min, int max) { return (value>= min) && (value<= max); } A pity the standard Math library lacks these
Is there any built in function for clamping to a range? No.
Looking at the examples for Uint8ClampedArray and Uint8Array, it looks like the difference is how values are treated when assigned. If you are trying to set one element to a clamped array to any value outside of the range 0-255, it will simply default to 0 or 255 (depending on whether the value is smaller … Read more
Swift 4/5 Extension of Comparable/Strideable similar to ClosedRange.clamped(to:_) -> ClosedRange from standard Swift library. extension Comparable { func clamped(to limits: ClosedRange<Self>) -> Self { return min(max(self, limits.lowerBound), limits.upperBound) } } #if swift(<5.1) extension Strideable where Stride: SignedInteger { func clamped(to limits: CountableClosedRange<Self>) -> Self { return min(max(self, limits.lowerBound), limits.upperBound) } } #endif Usage: 15.clamped(to: 0…10) … Read more
You could write an extension method: public static T Clamp<T>(this T val, T min, T max) where T : IComparable<T> { if (val.CompareTo(min) < 0) return min; else if(val.CompareTo(max) > 0) return max; else return val; } Extension methods go in static classes – since this is quite a low-level function, it should probably go … Read more
This is pretty clear, actually. Many folks learn it quickly. You can use a comment to help them. new_index = max(0, min(new_index, len(mylist)-1))