Getting Started with Math.NET and F# Programming

This is the first blog in a series to help F# programmers keep up-to-date with different ways of doing numerically-oriented programming with F#.

The first posts in this series will focus on the open source Math.NET Numerics library.

Math.NET Numerics is an opensource numerical library for F# and C# on .NET and Mono, including implementations of .NET supporting .NET portable code (Metro and Silverlight). Math.NET Numerics is the numerical foundation of the Math.NET project, aiming to provide methods and algorithms for numerical computations in science, engineering and every day use. Covered topics include special functions, linear algebra, probability models, random numbers, interpolation, integral transforms (FFT) and more.

In this post, we look at the basics of getting started with Math.NET. To install Math.NET Numerics, you do one of the following:


  • or, if using Visual Studio 2012, add it as a NuGET package to anF# project by right-clicking on a project node, choosing "Manage NuGet packages...", choose the "Online" tab, and search for "mathnet", "numerics" or a similar search term. Install the package "Math.NET Numerics", and, if desired "Math.NET Numerics F# Modules". The DLLs will be installed as a dependency in your project.  If necessary, create an empty project in a working directory like "projects".




Now create an F# Script.

  • Create a .fsx file using your favourite editor.
  • If using Visual Studio, use "File --> New --> File --> Script --> F# Script". 

Add the following references to the top of the script. If necessary, adjust the paths to those where you unzipped the Math.NET libraries:

#r @"c:\projects\TestProject\packages\MathNet.Numerics.2.1.2\lib\Net40\MathNet.Numerics.dll"
#r @"c:\projects\TestProject\packages\MathNet.Numerics.FSharp.2.1.2\lib\Net40\MathNet.Numerics.FSharp.dll"
#r @"c:\projects\TestProject\packages\\lib\"

(If you used NuGET, determine where the packages have been installed by expading the "References" tab, right-clicking on a reference, and choose "Properties". The path to the DLL will be shown in the "Full Path" property for the reference.)

Once you have your references in your script, highlight them and execute them in F# Interactive in the usual way. In Visual Studio, use Alt-Enter or right-click and "Send to Interactive". 

You can now test that your setup is working correctly by using some of the statistical functions that are available with the library. For example, to take the standard deviation of a sequence of 10 million random numbers, use the following:

open MathNet.Numerics.Statistics

let rnd = System.Random()

let rand() = rnd.NextDouble()

let data = seq { for i in 0 .. 10000000 -> rand() }

Statistics.StandardDeviation data

 The answer will be:

val rnd : System.Random
val rand : unit -> float
val data : seq<float>
val it : float = 0.2887244193