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.
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])
So simple just use abs((a) - (b)).
will work seamless without any additional care in signs(positive , negative)
def get_distance(p1,p2):
return abs((p1) - (p2))
get_distance(0,2)
2
get_distance(0,2)
2
get_distance(-2,0)
2
get_distance(2,-1)
3
get_distance(-2,-1)
1
Just use abs(x - y). This'll return the net difference between the two as a positive value, regardless of which value is larger.
If you don't need a signed integer, this is an alternative that uses a slightly different approach, is easy to read and doesn't require an import:
def distance(a, b):
if a > 0 and b > 0:
return max(a, b) - min(a, b)
elif a < 0 and b < 0:
return abs(a - b)
elif a == b:
return 0
return abs(a - 0) + abs(b - 0)
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
You can try: a=[0,1,2,3,4,5,6,7,8,9];
[abs(x[1]-x[0]) for x in zip(a[1:],a[:-1])]