In [6]:
import math
def distance(a, b):
"""The distance between two (x, y) points."""
return math.hypot((a[0] - b[0]), (a[1] - b[1]))
For example:
In [7]:
print(distance((1, 2), (5, 5)))
In [8]:
def distance_squared(a, b):
"""The square of the distance between two (x, y) points."""
return (a[0] - b[0])**2 + (a[1] - b[1])**2
For example:
In [10]:
print(distance_squared((1, 2), (5, 5)))
With this function we can make sure the values of a vector are within a given range. It takes as arguments three vectors: the vector to clip (vector
), a vector containing the lowest values allowed (lowest
) and a vector for the highest values (highest
). All these vectors are of the same length. If a value v1
in vector
is lower than the corresponding value v2
in lowest
, then we set v1
to v2
. Similarly we "clip" the values exceeding the highest
values.
In [5]:
from utils import clip
def vector_clip(vector, lowest, highest):
"""Return vector, except if any element is less than the corresponding
value of lowest or more than the corresponding value of highest, clip to
those values."""
return type(vector)(map(clip, vector, lowest, highest))
For example:
In [6]:
print(vector_clip((-1, 10), (0, 0), (9, 9)))
The vector we wanted to clip was the tuple (-1, 10). The lowest allowed values were (0, 0) and the highest (9, 9). So, the result is the tuple (0,9).