Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Diagnostics;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using MathNet.Numerics.LinearAlgebra;
- using MathNet.Numerics.LinearAlgebra.Double;
- using MathNet.Numerics.LinearAlgebra.Factorization;
- using MathNet.Numerics.LinearRegression;
- namespace GaussAprox
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- var xs = new double[ ] { 1, 1, 8, 22,30,32,35 };
- var ys = new double[] { 2, 10, 22, 33, 37,44,50 };
- var res = Polyfit(xs, ys, 4);//.Select(ee => Math.Round(ee, 10).ToString("N0")).ToList();
- var eq = String.Format("x=1, y= ({0})x^4 + ({1})x^3 + ({2})x^2 +({3})x +({4})", res[4], res[3], res[2], res[1], res[0]);
- Clipboard.SetText(eq);
- Process.Start("https://www.wolframalpha.com/input/?i=" + Uri.EscapeDataString(eq));
- }
- public static double[] Polynomial(double[] x, double[] y, int order)
- {
- var design = Matrix<double>.Build.Dense(x.Length, order + 1, (i, j) => Math.Pow(x[i], j));
- return MultipleRegression.QR(design, Vector<double>.Build.Dense(y)).ToArray();
- }
- public static double[] Polyfit(double[] x, double[] y, int degree)
- {
- // Vandermonde matrix
- var v = new DenseMatrix(x.Length, degree + 1);
- for (int i = 0; i < v.RowCount; i++)
- for (int j = 0; j <= degree; j++) v[i, j] = Math.Pow(x[i], j);
- var yv = new DenseVector(y).ToColumnMatrix();
- QR<double> qr = v.QR();
- // Math.Net doesn't have an "economy" QR, so:
- // cut R short to square upper triangle, then recompute Q
- var r = qr.R.SubMatrix(0, degree + 1, 0, degree + 1);
- var q = v.Multiply(r.Inverse());
- var p = r.Inverse().Multiply(q.TransposeThisAndMultiply(yv));
- return p.Column(0).ToArray();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement