YouTip LogoYouTip

Ref Math Dist

## Python math.dist() Method The `math.dist()` method is a built-in function in Python's standard `math` module. It calculates and returns the Euclidean distance between two points, $p$ and $q$, which are represented as sequences (or iterables) of coordinates. The two points must have the same number of dimensions (i.e., the same length). --- ### Introduction to Euclidean Distance The Euclidean distance is the straight-line distance between two points in Euclidean space. * For 1D space: $$\text{dist}(p, q) = |p_0 - q_0|$$ * For 2D space: $$\text{dist}(p, q) = \sqrt{(p_0 - q_0)^2 + (p_1 - q_1)^2}$$ * For $N$-dimensional space: $$\text{dist}(p, q) = \sqrt{\sum_{i=0}^{n-1} (p_i - q_i)^2}$$ > **Note:** This method was introduced in **Python 3.8**. --- ### Syntax ```python import math math.dist(p, q) ``` #### Parameters | Parameter | Type | Description | | :--- | :--- | :--- | | **p** | *Iterable (list, tuple, etc.)* | **Required.** The coordinates of the first point. | | **q** | *Iterable (list, tuple, etc.)* | **Required.** The coordinates of the second point. | #### Return Value * **Type:** `float` * **Description:** Returns the Euclidean distance between points `p` and `q`. --- ### Code Examples The following example demonstrates how to calculate the Euclidean distance in both 1-dimensional and 2-dimensional spaces. ```python import math # --- Example 1: 1D Space --- p1 = q1 = # Calculate Euclidean distance in 1D: |3 - 1| = 2.0 distance_1d = math.dist(p1, q1) print("1D Distance:", distance_1d) # --- Example 2: 2D Space --- p2 = [3, 3] q2 = [6, 12] # Calculate Euclidean distance in 2D: sqrt((6-3)^2 + (12-3)^2) = sqrt(9 + 81) = sqrt(90) distance_2d = math.dist(p2, q2) print("2D Distance:", distance_2d) ``` #### Output ```text 1D Distance: 2.0 2D Distance: 9.486832980505138 ``` --- ### Important Considerations 1. **Dimension Matching:** The two points `p` and `q` must have the same number of dimensions. If their lengths do not match, Python will raise a `ValueError`. ```python import math # This will raise a ValueError: math.dist() x and y must have the same length math.dist([1, 2], [3, 4, 5]) ``` 2. **Supported Types:** The coordinates can be specified using any iterable type, such as `list`, `tuple`, or even custom generator expressions, as long as they contain numeric values (integers or floats). 3. **Equivalence to `math.hypot`:** `math.dist(p, q)` is functionally equivalent to `math.hypot(*(px - qx for px, qx in zip(p, q)))`. However, `math.dist()` is optimized in C, making it faster and less prone to cumulative rounding errors.
← Ref Math ErfcRef Math Comb β†’