// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using MathNet.Numerics.LinearAlgebra; namespace E { public class Program { private static void Solve(double[] y, out double[] b, double[] x) { Vector one = Vector.Ones(x.Length); Vector x2 = Vector.Create(x); Matrix x3 = Matrix.CreateFromColumns(new List { one, x2 }); Vector y2 = Vector.Create(y); Matrix y3 = Matrix.CreateFromColumns(new List { y2 }); Matrix b3 = x3.Solve(y3); Vector b2 = b3.GetColumnVector(0); b = b2.CopyToArray(); } private static readonly Random rng = new Random(); private static double Eps(double spread) { return (rng.NextDouble() - 0.5) * spread; } public static void Main(string[] args) { double[] x = { 1, 2, 3, 4, 5 }; double[] y = new double[x.Length]; double[] b; for(int i = 0; i < y.Length; i++) { y[i] = 0.456 + 0.123 * x[i] + Eps(0.05); } Solve(y, out b, x); Console.WriteLine("y = " + b[0] + " + " + b[1] + " * x"); } } }