gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
c# 实现一个最小二乘法
- User
c# 实现一个最小二乘法
- Assistant
下面是一个c#例子,展示了一个使用最小二乘法进行线性回归的过程。
using System; using System.Linq; namespace LeastSquares { class Program { static void Main(string[] args) { // 样本数据 double[] x = { 1, 2, 3, 4, 5 }; double[] y = { 1, 3, 2, 5, 4 }; // 拟合 var result = Fit(x, y); // 输出结果 Console.WriteLine($"斜率:{result.Item1}"); Console.WriteLine($"截距:{result.Item2}"); // 预测 double x_pred = 6; double y_pred = result.Item1 * x_pred + result.Item2; Console.WriteLine($"预测值:{y_pred}"); } /// <summary> /// 最小二乘法线性回归 /// </summary> /// <param name="x">自变量</param> /// <param name="y">因变量</param> /// <returns>线性回归方程的斜率和截距</returns> static Tuple<double, double> Fit(double[] x, double[] y) { double x_avg = x.Average(); double y_avg = y.Average(); double sxy = 0; double sxx = 0; for (int i = 0; i < x.Length; i++) { sxy += (x[i] - x_avg) * (y[i] - y_avg); sxx += (x[i] - x_avg) * (x[i] - x_avg); } double slope = sxy / sxx; double intercept = y_avg - slope * x_avg; return Tuple.Create(slope, intercept); } } }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.