# NumPy: Calculate the distance between a Point and a Line

Last updated: Apr 12, 2024
2 min

## #NumPy: Calculate the distance between a Point and a Line

The example assumes that you have a line drawn between `P1` and `P2` and need to calculate the distance from `P3` to the line.

You can use the `numpy.cross()` method to get the cross-product of the arrays of vectors and divide the result by the norm of the matrix of vectors.

main.py
```Copied!```import numpy as np

p1 = np.array([0, 0])
p2 = np.array([20, 20])
p3 = np.array([10, 14])

distance = np.cross(p2 - p1, p3 - p1) / np.linalg.norm(p2 - p1)

print(distance)  # ๐๏ธ 2.82842712474619
``````

Make sure the values you pass to `numpy.cross()` and `numpy.linalg.norm()` and NumPy arrays.

You can use the `numpy.array()` method if you need to convert a list or a tuple to an array.

main.py
```Copied!```tup = (0, 0)

print(type(tup)) # <class 'tuple'>

arr = np.array(tup)

print(type(arr)) # <class 'numpy.ndarray'>
``````

The numpy.cross() method returns the cross product of two arrays of vectors.

The only arguments we passed to `numpy.cross()` are `a` and `b`:

• `a` - components of the first vector(s).
• `b` components of the second vector(s).
main.py
```Copied!```distance = np.cross(p2 - p1, p3 - p1) / np.linalg.norm(p2 - p1)

print(distance)  # ๐๏ธ 2.82842712474619
``````

The cross product of `a` and `b` is a vector perpendicular to both `a` and `b`.

The `numpy.cross()` method returns the vector cross product(s).

main.py
```Copied!```import numpy as np

p1 = np.array([0, 0])
p2 = np.array([20, 20])
p3 = np.array([10, 14])

print(np.cross(p2 - p1, p3 - p1)) # ๐๏ธ 80
``````

The numpy.linalg.norm() method returns the norm of the matrix or vectors.

main.py
```Copied!```import numpy as np

p1 = np.array([0, 0])
p2 = np.array([20, 20])
p3 = np.array([10, 14])

# ๐๏ธ 28.284271247461902
print(np.linalg.norm(p2 - p1))
``````

The last step is to divide the result of calling `numpy.cross()` by the result of calling `numpy.linalg.norm()`.

main.py
```Copied!```import numpy as np

p1 = np.array([0, 0])
p2 = np.array([20, 20])
p3 = np.array([10, 14])

distance = np.cross(p2 - p1, p3 - p1) / np.linalg.norm(p2 - p1)

print(distance)  # ๐๏ธ 2.82842712474619
``````

If you want to calculate the distance and get the absolute (non-negative) value, use the numpy.absolute() method.

main.py
```Copied!```import numpy as np

p1 = np.array([0, 0])
p2 = np.array([20, 20])
p3 = np.array([10, 14])

distance = np.abs(np.cross(p2 - p1, p1 - p3)) / np.linalg.norm(p2 - p1)

print(distance)  # ๐๏ธ 2.82842712474619
``````

For example, the absolute value of 10 is 10, and the absolute value of `-10` is also `10`.