Distance Formula

Imports

I'm just importing some selected objects from the math module. I won't use them all, as I am do doing this for demonstration purposes. In this case I am importing the functions sqrt, gamma, floor, and the float object pi.

In [8]:
#import math
from math import sqrt, gamma, floor, pi

Make a point!

I'm using simultaneous assignment to create two x,y coordinate pairs. The comments below x_1 and y_1 show what it would look like if I didn't use simultaneous assignment.

In [9]:
# Point x_1, y_1
x_1, y_1 = 100, 23
#x_1 = 100
#y_1 = 23

# Point x_2, y_2
x_2, y_2 = 45, 60

Distance Calculation

Now, we calculate the distance between two points, as defined above. We store the calculated result in dist. Notice we are calling sqrt, not math.sqrt. If I had imported math using import math, then the latter form would be needed.

In [10]:
#dist = math.sqrt((x_2 - x_1)**2 + (y_2 - y_1)**2)
dist = sqrt((x_2 - x_1)**2 + (y_2 - y_1)**2)
In [11]:
print(dist)
66.2872536767062
In [12]:
dist
Out[12]:
66.2872536767062
In [7]:
dir(math)
Out[7]:
['__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'acos',
 'acosh',
 'asin',
 'asinh',
 'atan',
 'atan2',
 'atanh',
 'ceil',
 'copysign',
 'cos',
 'cosh',
 'degrees',
 'e',
 'erf',
 'erfc',
 'exp',
 'expm1',
 'fabs',
 'factorial',
 'floor',
 'fmod',
 'frexp',
 'fsum',
 'gamma',
 'gcd',
 'hypot',
 'inf',
 'isclose',
 'isfinite',
 'isinf',
 'isnan',
 'ldexp',
 'lgamma',
 'log',
 'log10',
 'log1p',
 'log2',
 'modf',
 'nan',
 'pi',
 'pow',
 'radians',
 'sin',
 'sinh',
 'sqrt',
 'tan',
 'tanh',
 'tau',
 'trunc']
In [ ]: