c# MathNet.Numerics 二次函数拟合使用案例

下载地址
https://www.nuget.org/packages/MathNet.Numerics/4.15.0#supportedframeworks-body-tab

案例

using MathNet.Numerics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MathNetTest
{
    class Program
    {
        static void Main(string[] args)
        {
            double a = 800;//y=ax²+bx+c
            double b = 900;
            double c = 100;
            double[] y = new double[1000];
            double[] x = new double[1000];
            Random random = new Random();
            int index = 0;
            for (int i = -300; i < 1000 - 300; i++)
            {//生成随机偏移点
                x[index] = i;
                y[index] = a * Math.Pow(i, 2) + b * i + c + random.NextDouble();
                index++;
            }
            double[] res = Fit.Polynomial(x, y, 2);//拟合
            double aFit = res[2];
            double bFit = res[1];
            double cFit = res[0];
            double[] yFit = new double[1000];
            index = 0;
            for (int i = -300; i < 1000 - 300; i++)
            {//计算拟合后点
                yFit[index] = aFit * Math.Pow(i, 2) + bFit * i + cFit;
                index++;
            }
            double RSquared = GoodnessOfFit.RSquared(y, yFit);//拟合度
            double peakX = -bFit / (2 * aFit);//计算顶点
            double peaky = (4 * aFit * cFit - bFit * bFit) / (4 * aFit);
        }
    }
}

你可能感兴趣的:(算法,c#,算法)