Python math.dist() Method



The Python math.dist() method is used to calculate the Euclidean distance between two points in n-dimensional space. Mathematically, the Euclidean distance between two points P and Q with coordinates (x1, y1, z1,..., xn, yn, zn) and (x2, y2, z2,..., xn, yn, zn) respectively is given by the formula −

dist (P, Q) = √ (x2 - x1)2 + (y2 - y1)2 + (z2 - z1)2 + ... + (xn - x1)2 + (yn - y1)2 + (zn - z1)2

In simpler terms, it calculates the straight-line distance between two points in n-dimensional space, where each dimension represents a different attribute.

Syntax

Following is the basic syntax of the Python math.dist() method −

math.dist(p, q)

Parameters

This method accepts the following parameters −

  • p − This is a tuple or a list representing the coordinates of the first point.

  • q − This is a tuple or a list representing the coordinates of the second point.

Both p and q should have the same length, representing points in the same n-dimensional space.

Return Value

The method returns a float, which represents the Euclidean distance between the points p and q. It is calculated as the square root of the sum of squared differences of corresponding coordinates.

Example 1

In the following example, we are calculating the Euclidean distance between the points (1, 2) and (4, 6) in a 2-dimensional space using the math.dist() method −

import math
point1 = (1, 2)
point2 = (4, 6)
distance = math.dist(point1, point2)
print("The Euclidean distance obtained is:",distance) 

Output

The output obtained is as follows −

The Euclidean distance obtained is: 5.0

Example 2

Here, we are calculating the Euclidean distance between the points (1, 2, 3) and (4, 5, 6) in a 3-dimensional space using the math.dist() method −

import math
point1 = (1, 2, 3)
point2 = (4, 5, 6)
distance = math.dist(point1, point2)
print("The Euclidean distance obtained is:",distance) 

Output

Following is the output of the above code −

The Euclidean distance obtained is: 5.196152422706632

Example 3

In this example, we calculate the Euclidean distance between the point (3, 4) and the origin (0, 0) in a 2-dimensional space. This is equivalent to finding the length of the hypotenuse of a right triangle with legs of length 3 and 4 −

import math
point = (3, 4)
distance = math.dist(point, (0, 0))
print("The Euclidean distance obtained is:",distance) 

Output

We get the output as shown below −

The Euclidean distance obtained is: 5.0

Example 4

This example demonstrates how math.dist() handles floating-point numbers. We calculate the Euclidean distance between the points (0.1, 0.2) and (0.4, 0.5) −

import math
point1 = (0.1, 0.2)
point2 = (0.4, 0.5)
distance = math.dist(point1, point2)
print("The Euclidean distance obtained is:",distance)  

Output

The result produced is as shown below −

The Euclidean distance obtained is: 0.42426406871192857
python_maths.htm
Advertisements