Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clamping floating numbers in Python? [duplicate]

Tags:

python

math

clamp

Is there a built-in function for this in Python 2.6?

Something like:

clamp(myValue, min, max) 
like image 988
Joan Venge Avatar asked Mar 19 '12 18:03

Joan Venge


People also ask

How do you trim a float in Python?

Use the int Function to Truncate a Float in Python The built-in int() function takes a float and converts it to an integer, thereby truncating a float value by removing its decimal places.

How do you clamp an integer in Python?

Python – PyTorch clamp() method inp: This is input tensor. min: This is a number and specifies the lower-bound of the range to which input to be clamped. max: This is a number and specifies the upper-bound of the range to which input to be clamped. out: The output tensor.

How do you clip a value in Python?

clip() function is used to Clip (limit) the values in an array. Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1.


1 Answers

Numpy's clip function will do this.

>>> import numpy >>> numpy.clip(10,0,3) 3 >>> numpy.clip(-4,0,3) 0 >>> numpy.clip(2,0,3) 2 
like image 82
Richard Avatar answered Sep 24 '22 07:09

Richard