TheAlgorithms/C-Sharp · error · ArgumentException

Both points should have the same dimensionality

Error message

Both points should have the same dimensionality

What it means

Euclidean.Distance computes sqrt of the sum of squared coordinate differences, requiring both points to share dimensionality. If point1.Length != point2.Length it throws ArgumentException rather than silently ignoring coordinates via Zip.

Solutions

  1. Assert equal array lengths before invoking Distance
  2. Align feature pipelines so all vectors share the same dimension count
  3. Pad missing features with defaults before comparison
  4. Catch ArgumentException and log/skip the mismatched vector pair

Example fix

// before
Euclidean.Distance(new double[]{0,0}, new double[]{1,1,1}); // throws
// after
var p = new double[]{0,0,0};
var q = new double[]{1,1,1};
Euclidean.Distance(p, q);
Defensive patterns

Strategy: validation

Validate before calling

if (point1.Length != point2.Length) throw new ArgumentException("Dimension mismatch for Euclidean distance");

Type guard

bool SameDimension(double[] a, double[] b) => a.Length == b.Length;

Try / catch

try { d = Euclidean.Distance(a, b); }
catch (ArgumentException) { skipOrLogPair(a, b); }

Prevention

When it happens

Trigger: Calling Euclidean.Distance(double[] point1, double[] point2) with arrays of differing lengths — e.g., comparing a 2D coordinate to a 3D coordinate, or feature vectors of unequal width.

Common situations: KNN/clustering code fed vectors from inconsistent feature extractors; schema changes adding a feature to one dataset only; mixing latitude/longitude pairs with x/y/z points.

Related errors


AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13). Data as JSON: /api/errors/3bb3c7b6d5b93bcd. Report an issue: GitHub.

Appendix: source

Thrown at Algorithms/LinearAlgebra/Distances/Euclidean.cs:18

namespace Algorithms.LinearAlgebra.Distances;

/// <summary>
/// Implementation for Euclidean distance.
/// </summary>
public static class Euclidean
{
    /// <summary>
    /// Calculate Euclidean distance for two N-Dimensional points.
    /// </summary>
    /// <param name="point1">First N-Dimensional point.</param>
    /// <param name="point2">Second N-Dimensional point.</param>
    /// <returns>Calculated Euclidean distance.</returns>
    public static double Distance(double[] point1, double[] point2)
    {
        if (point1.Length != point2.Length)
        {
            throw new ArgumentException("Both points should have the same dimensionality");
        }

        // distance = sqrt((x1-y1)^2 + (x2-y2)^2 + ... + (xn-yn)^2)
        return Math.Sqrt(point1.Zip(point2, (x1, x2) => (x1 - x2) * (x1 - x2)).Sum());
    }
}

View on GitHub (pinned to 96e2905cab)