I was wondering if there was a function built into Python that can determine the distance between two rational numbers but without me telling it which number is larger. e.g.
>>>distance(6,3)
3
>>>distance(3,6)
3
Obviously I could write a simple definition to calculate which is larger and then just do a simple subtraction:
def distance(x, y):
if x >= y:
result = x - y
else:
result = y - x
return result
but I'd rather not have to call a custom function like this. From my limited experience I've often found Python has a built in function or a module that does exactly what you want and quicker than your code does it. Hopefully someone can tell me there is a built in function that can do this.
Find the difference between two values using the subtraction operation.
How to Find the Difference between Two Numbers. To find the difference between two numbers, subtract the number with the smallest value from the number with the largest value. The product of this sum is the difference between the two numbers.
if we are told to find the difference between 3 and 5, then we usually subtract 3 from 5 ,5-3=2 and thus, we say that the difference is 2.
abs(x-y)
will do exactly what you're looking for:
In [1]: abs(1-2)
Out[1]: 1
In [2]: abs(2-1)
Out[2]: 1
Although abs(x - y)
and equivalently abs(y - x)
work, 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.8
functools.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 np
a = [1,5,6,8]
np.diff(a)
Out: array([4, 1, 2])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With