Is there a method to limit/clamp a number?
Ruby 2.4.0 introduces Comparable#clamp
:
523.clamp(0, 100) #=> 100
What's the most elegant way to cap a number to a segment?
The way you do it is pretty standard. You can define a utility clamp
function:
/**
* Returns a number whose value is limited to the given range.
*
* Example: limit the output of this computation to between 0 and 255
* (x * 255).clamp(0, 255)
*
* @param {Number} min The lower boundary of the output range
* @param {Number} max The upper boundary of the output range
* @returns A number in the range [min, max]
* @type Number
*/
Number.prototype.clamp = function(min, max) {
return Math.min(Math.max(this, min), max);
};
(Although extending language built-ins is generally frowned upon)
how to limit(clamp) struct values in C
These are some macros that I been using since forever, for min, max and clamp.
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))
#define CLAMP(x, lower, upper) (MIN((upper), MAX((x), (lower))))
So, for your january example:
months.January = CLAMP(months.January, 1, 31);
How to clamp an integer to some range?
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))
How do I clamp values in Java?
Clamping means that you limit your value to a certain range.
You can either manually check if your value exceeds the upper or lower limit and set that limit as new value or you simply use min and max.
int minimum = 5;
int maximum = 10;
int value = 29;
if (value < minimum){
value = minimum;
}
else if (value > maximum){
value = maximum;
}
Or you simply do something like this:
value = Math.min(maximum, Math.max(minimum, value));
How can I safely add and clamp a signed integer in C?
You're right to worry about overflow. The obvious techniques for checking for overflow detect it after it's happened, which is of course too late, if there's any undefined behavior involved.
The standard technique is to rearrange the test. Rather than saying:
if(X + Delta > MAX) { whoops! it overflowed; }
subtract Delta
from both sides so you have
if(X > MAX - Delta) { whoops! it overflowed; }
Of course you also have to consider the possibility that Delta
is negative. So in your case I believe something like this will do it:
#define MAX (1<<30)
void UpdateX(signed int Delta) {
if(Delta >= 0) X = (X <= MAX - Delta) ? X + Delta : MAX;
else X = (X >= -MAX - Delta) ? X + Delta : -MAX;
}
See also How to check for signed integer overflow in C without undefined behaviour?
See also Question 20.6b in the C FAQ list.
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) // returns 10
3.0.clamped(to: 0.0...10.0) // returns 3.0
"a".clamped(to: "g"..."y") // returns "g"
// this also works (thanks to Strideable extension)
let range: CountableClosedRange<Int> = 0...10
15.clamped(to: range) // returns 10
Fastest Way To Clamp an Integer
As easy as
var normalized = Math.Min(50, Math.Max(0, value));
As of performance:
public static int Max(int val1, int val2) {
return (val1>=val2)?val1:val2;
}
That's how it's implemented in .NET, so it's unlikely you can implement it even better.
Most efficient/elegant way to clip a number?
What about boring, old, readable, and shortest yet:
float clip(float n, float lower, float upper) {
return std::max(lower, std::min(n, upper));
}
?
This expression could also be 'genericized' like so:
template <typename T>
T clip(const T& n, const T& lower, const T& upper) {
return std::max(lower, std::min(n, upper));
}
Update
Billy ONeal added:
Note that on windows you might have to define NOMINMAX because they define min and max macros which conflict
How to limit a number to be within a specified range? (Python)
def clamp(n, minn, maxn):
return max(min(maxn, n), minn)
or functionally equivalent:
clamp = lambda n, minn, maxn: max(min(maxn, n), minn)
now, you use:
n = clamp(n, 7, 42)
or make it perfectly clear:
n = minn if n < minn else maxn if n > maxn else n
even clearer:
def clamp(n, minn, maxn):
if n < minn:
return minn
elif n > maxn:
return maxn
else:
return n
Related Topics
Regex to Validate String Having Only Characters (Not Special Characters), Blank Spaces and Numbers
Using Activemodel::Serializer in Rails - JSON Data Differs Between JSON and Index Response
Run a Command Line with Custom Environment
Need Help Maximizing 3 Factors in Multiple, Similar Objects and Ordering Appropriately
Better Way to Write "Matching Balanced Parenthesis" Program in Ruby
Is There a Solution to Bypass 'Can't Add a New Key into Hash During Iteration (Runtimeerror)'
How to Quickly Reorder a Ruby Array Given an Order
How to Increment/Decrement a Character in Ruby for All Possible Values
Ruby - Extracting the Unique Values Per Key from an Array of Hashes
Uploading a File to a Website with Ruby/Rails
Write Array of Radix-2 Numeric Strings to Binary File in Ruby
Paperclip File Not Found Error
Telling Bundler to Exclude Certain Gems from a Particular Gem's Installation
Configuration in Allure to Cucumber in Ruby
Creating Spectral Heat Maps or Intensity Maps from Cdip Data Using Ruby