Skip to content

[BUG] Incorrect coordinate subtraction in DistanceFormula.euclideanDistance #7746

Open

Description

@spidervirus

Description

In com.thealgorithms.maths.DistanceFormula.java, the method euclideanDistance(double x1, double y1, double x2, double y2) incorrectly subtracts x1 instead of y1 when computing the y-axis delta:

public static double euclideanDistance(double x1, double y1, double x2, double y2) {
    double dX = Math.pow(x2 - x1, 2);
    double dY = Math.pow(y2 - x1, 2); // <--- Bug: x1 used instead of y1
    return Math.sqrt(dX + dY);
}

As a result, it computes $\sqrt{(x_2 - x_1)^2 + (y_2 - x_1)^2}$ instead of the Euclidean distance $\sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}$.

In addition, DistanceFormulaTest.java hardcoded incorrect expected values that were produced by the buggy formula (for example, expecting $\sqrt{50} \approx 7.0710678$ instead of the true Euclidean distance $\sqrt{58} \approx 7.6157731$ for points (1, 3) and (8, 0)).

Steps to reproduce

// Calculating Euclidean distance between (1, 3) and (8, 0)
// dx = 8 - 1 = 7, dy = 0 - 3 = -3
// Expected: sqrt(7^2 + (-3)^2) = sqrt(58) ≈ 7.615773105863909
double distance = DistanceFormula.euclideanDistance(1, 3, 8, 0);
System.out.println(distance); // Prints 7.0710678118654755 (which is sqrt(50))

Expected behavior

DistanceFormula.euclideanDistance(x1, y1, x2, y2) should subtract $y_1$ from $y_2$ (Math.pow(y2 - y1, 2)), correctly yielding $\sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}$.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions