TheAlgorithms/C-Sharp · error · ArgumentException

Variance of X must not be zero.

Error message

Variance of X must not be zero.

What it means

If all x values are identical, the denominator of the slope formula (sum of squared deviations from xMean) is 0 and the slope is undefined (division by zero). Fit throws ArgumentException('Variance of X must not be zero.') when |denominator| < 1e-12.

Solutions

  1. Provide x data with at least two distinct values.
  2. Check the distinct count of x before fitting: if x.Distinct().Count() < 2, don't call Fit.
  3. Remove or replace the constant feature column; a constant x carries no predictive information.

Example fix

// before
regression.Fit(new List<double> { 5, 5, 5 }, ys); // zero variance
// after
if (xs.Distinct().Count() < 2)
    throw new InvalidOperationException("X must contain distinct values.");
regression.Fit(xs, ys);
Defensive patterns

Strategy: validation

Validate before calling

if (xs.Distinct().Count() < 2)
    throw new InvalidOperationException("X must have at least two distinct values to fit a slope.");
regression.Fit(xs, ys);

Try / catch

try
{
    regression.Fit(xs, ys);
}
catch (ArgumentException ex) when (ex.Message.Contains("Variance"))
{
    // constant x column — switch feature or report bad dataset
    logger.LogError(ex, "X has zero variance");
}

Prevention

When it happens

Trigger: Calling Fit with every x equal — e.g. all x = 0, a single-element list (count >= 1 passes the empty check but has zero variance), or a feature column that is constant.

Common situations: Fitting on a constant dummy variable or an unpopulated column defaulted to one value; a single data point passed in; unit-scale features truncated so they all round to the same value.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


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

Appendix: source

Thrown at Algorithms/MachineLearning/LinearRegression.cs:61

        }

        // Calculate means
        double xMean = x.Average();
        double yMean = y.Average();

        // Calculate slope (b) and intercept (a)
        double numerator = 0.0;
        double denominator = 0.0;
        for (int i = 0; i < x.Count; i++)
        {
            numerator += (x[i] - xMean) * (y[i] - yMean);
            denominator += (x[i] - xMean) * (x[i] - xMean);
        }

        const double epsilon = 1e-12;
        if (Math.Abs(denominator) < epsilon)
        {
            throw new ArgumentException("Variance of X must not be zero.");
        }

        Slope = numerator / denominator;
        Intercept = yMean - Slope * xMean;
        IsFitted = true;
    }

    /// <summary>
    /// Predicts the output value for a given input using the fitted model.
    /// </summary>
    /// <param name="x">Input value.</param>
    /// <returns>Predicted output value.</returns>
    /// <exception cref="InvalidOperationException">Thrown if the model is not fitted.</exception>
    public double Predict(double x)
    {
        if (!IsFitted)
        {
            throw new InvalidOperationException("Model must be fitted before prediction.");

View on GitHub (pinned to 96e2905cab)