Fastest way to clamp a real (fixed/floating point) value?

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

Standard way to “clamp” a number between two values in Swift

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

Where can I find the “clamp” function in .NET?

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

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)