Advertisement
Guest User

Untitled

a guest
Dec 7th, 2016
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.Drawing;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Windows.Forms;
  11. using MathNet.Numerics.LinearAlgebra;
  12. using MathNet.Numerics.LinearAlgebra.Double;
  13. using MathNet.Numerics.LinearAlgebra.Factorization;
  14. using MathNet.Numerics.LinearRegression;
  15.  
  16. namespace GaussAprox
  17. {
  18. public partial class Form1 : Form
  19. {
  20. public Form1()
  21. {
  22. InitializeComponent();
  23. }
  24.  
  25. private void Form1_Load(object sender, EventArgs e)
  26. {
  27. var xs = new double[ ] { 1, 1, 8, 22,30,32,35 };
  28. var ys = new double[] { 2, 10, 22, 33, 37,44,50 };
  29. var res = Polyfit(xs, ys, 4);//.Select(ee => Math.Round(ee, 10).ToString("N0")).ToList();
  30.  
  31. 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]);
  32. Clipboard.SetText(eq);
  33. Process.Start("https://www.wolframalpha.com/input/?i=" + Uri.EscapeDataString(eq));
  34. }
  35.  
  36. public static double[] Polynomial(double[] x, double[] y, int order)
  37. {
  38. var design = Matrix<double>.Build.Dense(x.Length, order + 1, (i, j) => Math.Pow(x[i], j));
  39. return MultipleRegression.QR(design, Vector<double>.Build.Dense(y)).ToArray();
  40. }
  41. public static double[] Polyfit(double[] x, double[] y, int degree)
  42. {
  43. // Vandermonde matrix
  44. var v = new DenseMatrix(x.Length, degree + 1);
  45. for (int i = 0; i < v.RowCount; i++)
  46. for (int j = 0; j <= degree; j++) v[i, j] = Math.Pow(x[i], j);
  47. var yv = new DenseVector(y).ToColumnMatrix();
  48. QR<double> qr = v.QR();
  49. // Math.Net doesn't have an "economy" QR, so:
  50. // cut R short to square upper triangle, then recompute Q
  51. var r = qr.R.SubMatrix(0, degree + 1, 0, degree + 1);
  52. var q = v.Multiply(r.Inverse());
  53. var p = r.Inverse().Multiply(q.TransposeThisAndMultiply(yv));
  54. return p.Column(0).ToArray();
  55. }
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement