Clamp number

Python, Math · Nov 2, 2020

Clamps num within the inclusive range specified by the boundary values.

  • If num falls within the range (a, b), return num.
  • Otherwise, return the nearest number in the range.
def clamp_number(num, a, b):
  return max(min(num, max(a, b)), min(a, b))
clamp_number(2, 3, 5) # 3
clamp_number(1, -1, -5) # -1

More like this

  • Geometric progression

    Initializes a list containing the numbers in the specified geometric progression range.

    Python, Math · Nov 2, 2020

  • Number in range

    Checks if the given number falls within the given range.

    Python, Math · Sep 15, 2020

  • Sum of powers

    Returns the sum of the powers of all the numbers from start to end (both inclusive).

    Python, Math · Nov 2, 2020