Math.Net入门笔记

          由于项目需要用到很多数据处理,需要寻找一个基于.Net的数学库,下面是我从维基百科上得到的一张清单,我在比较了几种库后选择了Math.net,原因是开源免费,文档较为详细,需要的朋友可以去我的资源下载。

§  Anumer.Lin is simple and affordable .NETlibrary assisting in solving basic linear algebra problems. Code-independent consoleversion is included.

§  Dambach LinearAlgebra Framework is a new general purpose linear algebra frameworkto enable the elegant expression and solution of linear algebra problems andmodels.

§  DotNumerics is a numerical library for .NETwritten in C#. It provides routines for: linear algebra (CSLapack, CSBlas,CSEispack), differential equations and optimization.

§  FinMath is a library for scientific andfinancial computation on the .NETFramework. Its functionality includes vector and matrix algebra, statistics, dataanalysis, advanced functions, signal processing, numerical optimization andmany more. It uses Intel's Math Kernel Library and Intel Integrated PerformancePrimitives to do most of the low-level computations while providing simple andobject oriented interface.

§  ILNumerics.Net high performance, typesafe numericalarray classes and functions for general math, FFT and linear algebra, aims.NET/mono, 32&64 bit, script-like syntax in C#, 2D & 3D plot controls,efficient memory management

§  IMSLNumerical Libraries for .NET is a set of mathematical,statistical, data mining, financial and charting classes written in C#.

§  Machine Learningfor .NET is a library designed to assist in the use of common machinelearning algorithms in conjunction with the .NET platform. It is designed toinclude the most popular supervised and unsupervised learning algorithms whileminimizing the friction involved with creating the predictive models.

§  Math.NET is a mathematical open source(MIT/X11, LGPL & GPL) library written in C#/F#, aiming to provide a self.Math.NET Numerics is the numerical component which was built by merging theMath.NET Iridium library and dnAnalytics.

§  Measurement Studio is an integrated suite UI controlsand class libraries for use in developing test and measurement applications.The analysis class libraries provide various digital signal processing, signalfiltering, signal generation, peak detection, and other general mathematicalfunctionality.

§  Meta.Numerics is a library for scientific andtechnical computation on the .NETFramework. Its functionality includes matrix algebra, statistics and data analysis,advanced functions, and signal processing. The Meta.Numerics library isobject-oriented, performance-optimized, documented, and compatible withboth Mono and Silverlight.

§  The NAGLibrary for .NET is a .NET assembly of numerical routines developedby the Numerical Algorithms Group which have been optimized for usewithin the .NET environment.

§  NLinear is a generic linear algebra toolkit in C#compatible with Silverlight.

§  NMath by CenterSpace Software are numerical component librariesfor the .NET platform. The libraries include high performance signal processing(FFT) classes, an extensive linear algebra (LAPACK & BLAS) framework, and astatistics package including descriptive statistics, distributions, ANOVA, andmultivariate analysis (NMF, k-means, PCA). Most classes scale with the numberof processor cores.[1]

§  SCINET is an object-based high performanceScientific Software Framework for the Microsoft .NET platform. It is purelywritten in C# programming language and fully compliant with the Microsoft's CLIspecification.

§  Sho is a library and interactiveenvironment from Microsoft Research for data analysis and scientific computing,that includes powerful and efficient libraries for linear algebra as well asdata visualization.

         安装方法也很简单,将解压后得到的dll文件添加到项目引用就可以了,解压后得到的dll文件如图0所示。


图0

下面讲述几个简单使用例程。

统计量分析

         若需要计算样本参数的统计量特征分析,可以直接调用Statistics类的扩展方法,也可以将样本传递给DescriptiveStatistics的构造函数一次性计算出全部特性。

代码1是使用DescriptiveStatistics的例程:

using MathNet.Numerics.Statistics;
//ChiSquare创建X~2检验样本,这里的样本值可以换成自己的样本集
var samples = new ChiSquare(5).Samples().Take(1000);
var statistics = new DescriptiveStatistics(samples);

// 最大值,最小值,中位数
var largestElement = statistics.Maximum;
var smallestElement = statistics.Minimum;
var median = statistics.Median;

// 平均数
var mean = statistics.Mean;

// 方差,标准差
var variance = statistics.Variance;
var stdDev = statistics.StandardDeviation;

// 峭度,不对称度
var kurtosis = statistics.Kurtosis;
var skewness = statistics.Skewness;

代码1 

代码2是使用扩展方法的例程:
using MathNet.Numerics.Statistics;

// 扩展方法是基于 IEnumerable定义的
// 所以需要调用ToArray做一下转化
var samples = new ChiSquare(5).Samples().Take(1000).ToArray()
;

// Order Statistics
var largestElement = samples.Maximum();
var smallestElement = samples.Minimum();
var median = samples.Median();
var 250thOrderStatistic = samples.OrderStatistic(250);

// Central Tendency
var mean = samples.Mean();

// Dispersion
var variance = samples.Variance();
var biasedPopulationVariance = samples.PopulationVariance();
var stdDev = samples.StandardDeviation();
var biasedPopulationStdDev = samples.
PopulationStandardDeviation();
代码2

其他统计量分析详见帮助文档。

线性代数

         关于线性代数的计算位于命名空间MathNet.Numerics.LinearAlgebra下,该命名空间下有四个子命名空间。

MathNet.Numerics.LinearAlgebra.Double:双精度浮点数计算

MathNet.Numerics.LinearAlgebra.Single:单精度浮点数计算

MathNet.Numerics.LinearAlgebra.Complex:进行复杂的双精度浮点数计算

MathNet.Numerics.LinearAlgebra.Complex32:进行复杂的单精度浮点数计算

之所以分为四个子命名空间的原因是考虑了内存需求,双精度浮点矩阵至少需要4倍同样单精度浮点矩阵的内存。此外,好考虑了矩阵的存储情况,现在Math.net支持三种矩阵的存储:

DenseMatrix任意矩阵

SparseMatrix稀疏矩阵

DiagonalMatrix:对角阵

将矩阵分为这三种也也考虑了对应存储的优化,比如稀疏矩阵在存储时就使用了3数组的稀疏压缩行(Compressed-sparse-row, CSR)格式。

代码3是矩阵乘以向量的例程:

using MathNet.Numerics.LinearAlgebra.Double;
// Create a vector of dimension 5 with 4.0 in every entry.
var x = new DenseVector(5, 4.0);
// Create a 3 by 5 matrix with 2.0 in every entry.
var A = new DenseMatrix(3, 5, 2.0);
// Multiply the matrix and the vector.
var y = A * x;
代码3

特殊函数

l  阶乘:Factorial

l  对数阶乘:FactorialLn

l  伯努利系数:Binomial

l  对数伯努利系数:BinomialLn

l  多项式系数:Multinomial

代码4 阶乘例程:

using MathNet.Numerics;
double x = SpecialFunctions.Factorial(2);
// x will now have the value 2

double y = SpecialFunctions.Factorial(4);
// y will now have the value 24

其他特殊函数如Gamma, Logistic见帮助文档http://mathnetnumerics.codeplex.com/wikipage?title=Special%20Functions&referringTitle=Documentation。

函数插值

         函数插值位于命名空间MathNet.Numerics.Interpolation

Math.net的插值有两种:

1.      为选定算法和样本点创建一个插值结构,你将获得一个实现了IInterpolation接口的类。

2.      使用该插值结构计算任意位置的点。一些插值算法还可以计算偏差和不定积分。

静态类Interpolate提供了工厂方法来创建插值操作:

RationalWithoutPoles创建 Floater-Hormann重心插值

RationalWithPoles创建Bulirsch& Stoer有理插值

LinearBetweenPoints创建样条曲线插值

如果不确定使用哪种插值方法,我们推荐使用Floater-Hormann重心插值。或者,你也可以直接使用别的插值算法,它们都位于子命名空间Algorithms ,下面是一些插值算法:

等间距样本点插值:

Polynomial: 重心算法,多项式插值

任意样本点插值:

·        Rational pole-free:Floater-Hormann重心算法

·        Rational with poles: Bulirsch & Stoer算法

·        Neville Polynomial: Neville算法。注意 Neville算法在处理等间距样本点时非常低效。.如果需要在等间距样本点上进行多项式插值,推荐使用barycentric算法。

·        Linear Spline:样条曲线

·        Cubic Spline 带边界条件的三次样条曲线

·        Natural Cubic Spline普通三次样条曲线

·        Akima Cubic Splineakima三次样条曲线

其他数据插值:

·        Generic Barycentric Interpolation,需要barycentric权重

·        Generic Spline,需要样条系数

·        Generic Cubic Hermite Spline,需要偏差

代码5 插值例程:

using MathNet.Numerics.Signals;
using MathNet.Numerics.Interpolation;
using MathNet.Numerics.Random;


namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        // 1. 利用函数1/(1+x*x) 在区间 [-5, 5]产生10个样本点
//points是x坐标,values是y坐标值
        Console.WriteLine(@"1. Generate 10 samples of the 
        function 1/(1+x*x) on interval [-5, 5]");
        double[] points;
        var values = SignalGenerator.EquidistantInterval(
        TargetFunction, -5, 5, 10, out points);
        Console.WriteLine();

        // 2. Create a floater hormann rational pole-free 
        interpolation based on arbitrary points
        // This method is used by default when create an 
        interpolation using Interpolate.Common method
        var method = Interpolate.RationalWithoutPoles(points,
        values);
        Console.WriteLine(@"2. Create a floater hormann 
        rational pole-free interpolation based on arbitrary 
        points");
        Console.WriteLine();

        // 3. 是否支持积分
        Console.WriteLine(@"3. Support integration = {0}", 
        method.SupportsIntegration);
        Console.WriteLine();

        // 4. 是否支持微分
        Console.WriteLine(@"4. Support differentiation = {0}
        ", method.SupportsDifferentiation);
        Console.WriteLine();

        // 5. 将插值结果和函数计算结果做比较
        Console.WriteLine(@"5. Interpolate ten random points 
        and compare to function results");
        var rng = new MersenneTwister(1);
        for (var i = 0; i < 10; i++)
        {
            // Generate random value from [0, 5]
            var point = rng.NextDouble() * 5;
            Console.WriteLine(@"Interpolate at {0} = {1}. 
            Function({0}) = {2}", point.ToString("N05"), 
            method.Interpolate(point).ToString("N05"), 
            TargetFunction(point).ToString("N05"));
        }
        Console.ReadKey();
    }
    public static double TargetFunction(double x)
    {
        return 1 / (1 + (x * x));
    }
}
}

执行结果如图 1所示。

图1 插值执行结果

线性积分变换

         math.net目前仅支持两种线性积分变换:离线傅立叶变换和离散哈特莱变换。它们都仅能在频域下进行变换,但傅立叶变换支持复杂数值,而哈特莱变换仅支持实数值。它们都支持正变换和反变换,这是靠方法中的options参数来区分的。

傅立叶空间:离散傅立叶变换DFT和快速傅立叶变换FFT

目前支持的算法有:

·        Naive Discrete Fourier Transform (DFT): Out-placetransform for arbitrary vector lengths. Mainly intended for verifying fasteralgorithms: NaiveForwardNaiveInverse

·        Radix-2 Fast Fourier Transform (FFT): In-placefast fourier transform for vectors with a power-of-two length (Radix-2): Radix2ForwardRadix2Inverse

·        Bluestein Fast Fourier Transform (FFT): In-placefast fourier transform for arbitrary vector lengths:BluesteinForwardBluesteinInverse

另外,Transform类提供了静态方法使我们能更容易地使用傅立叶正变换FourierForward和傅立叶反变换FourierInverse。如代码6所示。

// create a complex sample vector of length 96
Complex[] samples = SignalGenerator.EquidistantInterval(
                        t => new Complex(1.0 / (t * t + 1.0),
                        t / (t * t + 1.0)),
-16, 16, 96);

// inplace bluestein FFT with default options
Transform.FourierForward(samples);

代码6

下面是一些傅立叶参数,由于我对傅立叶变换不是很明白,原文没有翻译:

·        Default: Uses a negative exponent sign inforward transformations, and symmetric scaling (that is, sqrt(1/N) for bothforward and inverse transformation). This is the convention used in Maple andis widely accepted in the educational sector (due to the symmetry).

·        AsymmetricScaling: Set this flag to suppress scalingon the forward transformation but scale the inverse transform with 1/N.

·        NoScaling: Set this flag to suppress scaling forboth forward and inverse transformation. Note that in this case if you applyfirst the forward and then inverse transformation you won't get back theoriginal signal (by factor N/2).

·        InverseExponent: Uses the positive instead of thenegative sign in the forward exponent, and the negative (instead of positive)exponent in the inverse transformation.

·        Matlab: Use this flag if you need Matlab compatibility.Equals to setting the AsymmetricScaling flag.This matches the definition used in the wikipedia article.

·        NumericalRecipes: Use this flag if you needNumerical Recipes compatibility. Equal to setting both theInverseExponent and the NoScaling flags.

下面是一些傅立叶变换有用的常识,就是讲变换前后的奇偶性,很容易看懂:

·        h(t) is real valued <=> real part of H(f) is even,imgainary part of H(f) is odd

·        h(t) is imaginary valued <=> real part of H(f) isodd, imaginary part of H(f) is even

·        h(t) is even <=> H(f) is even

·        h(t) is odd <=> H(f) is odd

·        h(t) is real-valued even <=> H(f) is real-valuedeven

·        h(t) is real-valued odd <=> H(f) isimaginary-valued odd

·        h(t) is imaginary-valued even <=> H(f) isimaginary-valued even

·        h(t) is imaginary-valued odd <=> H(f) isreal-valued odd




你可能感兴趣的:(工具库)