成功引用mathnet.numerics之后,在资源管理器中双击它可以打开预览一下,看看都包括了些什么内容:
长长的一列看不到头,光从名字上就能看到差分、插值、积分、线性代数、傅里叶变换这些让人肝颤的家伙(大学数学课本在哪里,赶紧翻出来复习一下)。
点开第一个mathnet.numerics看看
复数、微积分什么都出来了,看着就觉得被暴击了。先做个拟合试试。Fit里面点进去,从一堆指数拟合、多项式拟合里面挑个最软的线性拟合看看。
点进去,官方注释这样的:
public static System.Tuple<double, double> Line(double[] x, double[] y)
MathNet.Numerics.Fit 的成员
摘要:
Least-Squares fitting the points (x,y) to a line y : x -> a+b*x, returning its best fitting parameters as [a, b] array, where a is the intercept and b the slope.
准备点数据实验一下,数据集:
x= 13,15,16,21,22,23,25,29,30,31,36,40,42,55,60,62,64,70,72,100,130
y= 11,10,11,12,12,13,13,12,14,16,17,13,14,22,14,21,21,24,17,23,34
预期拟合结果: y = 8.2084 + 0.1795x
代码如下:
static void Main(string[] args)
{
double[] x = {13, 15, 16, 21, 22, 23, 25, 29, 30, 31, 36, 40, 42, 55, 60, 62, 64, 70, 72, 100, 130};
double[] y = {11, 10, 11, 12, 12, 13, 13, 12, 14, 16, 17, 13, 14, 22, 14, 21, 21, 24, 17, 23, 34 };
var result = MathNet.Numerics.Fit.Line(x, y);
Console.WriteLine(result.ToString());
Console.ReadLine();
}
运行结果和预期符合,b= 8.2084, k= 0.1795
========分割线=======
你们以为这就完了么?接下来当然要对算法进行各种测试,简而言之就是:
Fit.Line()返回的是斜率k和截距b,那如果k=tan90°的情况呢?
先把数据改成这样的,x在1的附近浮动
static void Main(string[] args)
{
double[] x = {1, 1.01, 1, 0.999, 1, 1.01, 1, 1, 0.999, 1, 1.01, 1.01, 0.999, 1, 1, 1, 1.01, 0.999, 1, 1, 1.01};
double[] y = {11, 10, 11, 12, 12, 13, 13, 12, 14, 16, 17, 13, 14, 22, 14, 21, 21, 24, 17, 23, 34 };
var result = MathNet.Numerics.Fit.Line(x, y);
Console.WriteLine(result.ToString());
Console.ReadLine();
}
运行结果
噢哟呵,居然还没出错。
那么继续,干脆把x全改成1
static void Main(string[] args)
{
double[] x = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
double[] y = {11, 10, 11, 12, 12, 13, 13, 12, 14, 16, 17, 13, 14, 22, 14, 21, 21, 24, 17, 23, 34 };
var result = MathNet.Numerics.Fit.Line(x, y);
Console.WriteLine(result.ToString());
Console.ReadLine();
}
铛铛!
、
好了,我们现在知道tan90°的拟合结果也是tan90°,手动狗头表情。然后开始下一项作死,把数据弄成正方形四个顶点会如何?
static void Main(string[] args)
{
double[] x = {0, 1, 1, 0};
double[] y = {0, 0, 1, 1};
var result = MathNet.Numerics.Fit.Line(x, y);
Console.WriteLine(result.ToString());
Console.ReadLine();
}
结果是b= 0.5, k= 0
那么继续,把四个点位置旋转45°
static void Main(string[] args)
{
double[] x = {0, 1, 0, -1};
double[] y = {0, 1, 2, 1};
var result = MathNet.Numerics.Fit.Line(x, y);
Console.WriteLine(result.ToString());
Console.ReadLine();
}
结果是b=1, k=0