Getting absoulte values in Python with abs()
Python has a built in function called abs()
that is used to find the absolute value from an interget or float value.
Absolute values are values that return a magnitue of a given number. If I put it in more simple tems, magnitue of a number tells us how far they are from zero in the number line.
For negative numbers -
sign is not considered.
Example
>>> x, y = -10.11, -10
>>> abs(x)
>>>10.11
>>>abs(y)
>>>10
Like most of python builtins it also has a dunder method __abs__
>>> y = -10
>>> y.__abs__()
>>> 10
Real World Example
Suppose you are given a chart of temprature that has temprature values and you need to find the value that is closest to 0.
class TempratureReader:
def closest_to_zero(self, readings: List[float]) -> float:
result = readings[0]
for reading in readings:
if abs(reading) < abs(result):
result = reading
elif abs(reading) == abs(result):
result = max(result, reading )
return result
>>> t = TempratureReader()
>>> t.closest_to_zero([10.11,-35.11,22.11, -2.1, -1.1, 1.1])
>>> 1.1
absoulte values of other types
- For complex number,
abs()
returns the maginitudu.
>>> num = complex(3, 10)
>>> num
>>> (3+10j)
>>> abs(num)
>>> 10.44030650891055
- For
Decimal
values it just works likefloat
just returns the postive value.
References