clamp
clamp(x, lo, hi)
Return x if lo <= x <= hi. If x < lo, return lo. If x > hi, return hi. Arguments are promoted to a common type. Operates elementwise over x if it is an array.
Examples
-
Clamp a single value within a range:
julia> clamp(8, 10, 20) 10In this example, the value
8is clamped between the range10and20. Since8is less than the lower bound10, it returns the lower bound value10. -
Clamp an array of values within a range:
julia> arr = [5, 15, 25, 35]; julia> clamp.(arr, 10, 30) 4-element Array{Int64,1}: 10 15 25 30The
clampfunction can also operate elementwise over arrays. In this example, each element of the arrayarris clamped between the range10and30. Values less than the lower bound are replaced with the lower bound, and values greater than the upper bound are replaced with the upper bound. - Clamp values of mixed types:
julia> x = 5.5; julia> lo = 5; julia> hi = 10.0; julia> clamp(x, lo, hi) 5.5The
clampfunction promotes the arguments to a common type. Here, the valuexis promoted to a floating-point number to match the type ofhi. The result is still5.5since it falls within the range.
Common mistake example:
julia> clamp(20, 10, 5)
ERROR: ArgumentError: invalid range: 10:5
In this example, the lower bound (10) is greater than the upper bound (5), which results in an invalid range. It's important to ensure that the lower bound is less than or equal to the upper bound to avoid such errors when using the clamp function.
See Also
User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.