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) 10
In this example, the value
8
is clamped between the range10
and20
. Since8
is 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 30
The
clamp
function can also operate elementwise over arrays. In this example, each element of the arrayarr
is clamped between the range10
and30
. 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.5
The
clamp
function promotes the arguments to a common type. Here, the valuex
is promoted to a floating-point number to match the type ofhi
. The result is still5.5
since 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.