How do I find the difference between two values without knowing which is larger?
Although abs(x - y)
or equivalently abs(y - x)
works, the following one-liners also work:
math.dist((x,), (y,))
(available in Python ≥3.8)math.fabs(x - y)
max(x - y, y - x)
-min(x - y, y - x)
max(x, y) - min(x, y)
(x - y) * math.copysign(1, x - y)
, or equivalently(d := x - y) * math.copysign(1, d)
in Python ≥3.8functools.reduce(operator.sub, sorted([x, y], reverse=True))
All of these return the euclidean distance(x, y).
If you have an array, you can also use numpy.diff
:
import numpy as npa = [1,5,6,8]np.diff(a)Out: array([4, 1, 2])