{"record":{"id":"5649a51fe32acd36","repo":"TheAlgorithms/C-Sharp","slug":"variance-of-x-must-not-be-zero","errorCode":null,"errorMessage":"Variance of X must not be zero.","messagePattern":"Variance of X must not be zero\\.","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Algorithms/MachineLearning/LinearRegression.cs","lineNumber":61,"sourceCode":"        }\n\n        // Calculate means\n        double xMean = x.Average();\n        double yMean = y.Average();\n\n        // Calculate slope (b) and intercept (a)\n        double numerator = 0.0;\n        double denominator = 0.0;\n        for (int i = 0; i < x.Count; i++)\n        {\n            numerator += (x[i] - xMean) * (y[i] - yMean);\n            denominator += (x[i] - xMean) * (x[i] - xMean);\n        }\n\n        const double epsilon = 1e-12;\n        if (Math.Abs(denominator) < epsilon)\n        {\n            throw new ArgumentException(\"Variance of X must not be zero.\");\n        }\n\n        Slope = numerator / denominator;\n        Intercept = yMean - Slope * xMean;\n        IsFitted = true;\n    }\n\n    /// <summary>\n    /// Predicts the output value for a given input using the fitted model.\n    /// </summary>\n    /// <param name=\"x\">Input value.</param>\n    /// <returns>Predicted output value.</returns>\n    /// <exception cref=\"InvalidOperationException\">Thrown if the model is not fitted.</exception>\n    public double Predict(double x)\n    {\n        if (!IsFitted)\n        {\n            throw new InvalidOperationException(\"Model must be fitted before prediction.\");","sourceCodeStart":43,"sourceCodeEnd":79,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/MachineLearning/LinearRegression.cs#L43-L79","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Provide x data with at least two distinct values.","Check the distinct count of x before fitting: if x.Distinct().Count() < 2, don't call Fit.","Remove or replace the constant feature column; a constant x carries no predictive information."],"exampleFix":"// before\nregression.Fit(new List<double> { 5, 5, 5 }, ys); // zero variance\n// after\nif (xs.Distinct().Count() < 2)\n    throw new InvalidOperationException(\"X must contain distinct values.\");\nregression.Fit(xs, ys);","handlingStrategy":"validation","validationCode":"if (xs.Distinct().Count() < 2)\n    throw new InvalidOperationException(\"X must have at least two distinct values to fit a slope.\");\nregression.Fit(xs, ys);","typeGuard":null,"tryCatchPattern":"try\n{\n    regression.Fit(xs, ys);\n}\ncatch (ArgumentException ex) when (ex.Message.Contains(\"Variance\"))\n{\n    // constant x column — switch feature or report bad dataset\n    logger.LogError(ex, \"X has zero variance\");\n}","preventionTips":["Check Distinct().Count() >= 2 on x during data profiling before fitting.","Watch for constant/default-valued columns in exports and single-row datasets.","Add a dataset-quality check step (cardinality of each feature) in the pipeline."],"tags":["csharp","zero-variance","machine-learning","linear-regression","math"],"backgroundTag":"invalid-argument-value","analyzedSha":"96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c","analyzedAt":"2026-09-13T17:04:01.438Z","contentChangedAt":"2026-09-13T17:04:01.438Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}