Quantcast
Channel: Math.NET Numerics
Viewing all 971 articles
Browse latest View live

Released: Math.NET Numerics v2.3.0 (Nov 25, 2012)

$
0
0
Portable Library Build:
  • Adds support for WP8 (.Net 4.0 and higher, SL5, WP8 and .NET for Windows Store apps)
  • New: portable build also for F# extensions (.Net 4.5, SL5 and .NET for Windows Store apps)
  • NuGet: portable builds are now included in the main packages, no more need for special portable packages
Linear Algebra:
  • Continued major storage rework, in this release focusing on vectors (previous release was on matrices)
  • Thin QR decomposition (in addition to existing full QR)
  • Static CreateRandom for all dense matrix and vector types
  • F#: slicing support for matrices and vectors
Random and Probability Distributions:
  • Consistent static Sample methods for all continuous and discrete distributions (was previously missing on a few)
  • F#: better usability for random numbers and distributions.
Misc:
  • F# extensions are now using F# 3.0
  • Updated Intel MKL references for our native linear algebra providers
  • Various bug, performance and usability fixes

Also available as NuGet packages:
PM> Install-Package MathNet.Numerics
PM> Install-Package MathNet.Numerics.FSharp

Note: The portable package MathNet.Numerics.Portable has been dropped, as NuGet 2.1 properly supports portable builds in the main package.

If you absolutely require a signed library with a strong name:
PM> Install-Package MathNet.Numerics.Signed

Updated Release: Math.NET Numerics v2.3.0 (Nov 25, 2012)

$
0
0
Portable Library Build:
  • Adds support for WP8 (.Net 4.0 and higher, SL5, WP8 and .NET for Windows Store apps)
  • New: portable build also for F# extensions (.Net 4.5, SL5 and .NET for Windows Store apps)
  • NuGet: portable builds are now included in the main packages, no more need for special portable packages
Linear Algebra:
  • Continued major storage rework, in this release focusing on vectors (previous release was on matrices)
  • Thin QR decomposition (in addition to existing full QR)
  • Static CreateRandom for all dense matrix and vector types
  • F#: slicing support for matrices and vectors
Random and Probability Distributions:
  • Consistent static Sample methods for all continuous and discrete distributions (was previously missing on a few)
  • F#: better usability for random numbers and distributions.
Misc:
  • F# extensions are now using F# 3.0
  • Updated Intel MKL references for our native linear algebra providers
  • Various bug, performance and usability fixes

Also available as NuGet packages:
PM> Install-Package MathNet.Numerics
PM> Install-Package MathNet.Numerics.FSharp

Note: The portable package MathNet.Numerics.Portable has been dropped, as NuGet 2.1 properly supports portable builds in the main package.

If you absolutely require a signed library with a strong name:
PM> Install-Package MathNet.Numerics.Signed

New Post: How to load data into matrix

$
0
0

New to matrices ... coming from relational database background ...

I've got a database table that has: rowkey, columnkey, cellvalue which is read in from SQL to a reader

and the keys are in a hashtable which allows lookup based on key to get row and col IDs. (same set of keys can be in either row or column)

Problem is that it's taking about 4 hours to load ~2M datapoints into a 10500x10500 SparseMatrix A in memory for calculation by looping over the following C# stmt:

                 A [ (int)idHash [reader[0].ToString()], (int)idHash [reader[1].ToString()] ] = reader.GetDouble(2);

I was looking for a "bulk load" function and see SetColumn and SetRow but just not sure, since it's sparse data, whether it's worth it to prepare by columns or ? ... 

Any ideas on how to speed this process up?

Thanks!

New Post: How to load data into matrix

$
0
0

Hi,

Uh. Sparse matrices are much slower than dense ones by design, but 4h is unacceptable. Some ideas:

A) If possible, always initialize a sparse matrices row by row, in ascending order.

Quick Example (in F#, but would be equivalent in C#), initializing a matrix (110M fields) with 2M values:

let good = new SparseMatrix(10500,10500)
for row in 0..999 do
    for col in 0..999 do
        good.At(10*row, 10*col, float32 (Math.Atan2(float row, float col)))
        good.At(2+10*row, 3+10*col, float32 (row+col))

This needs roughly 1 minute on my machine. Still slow, but much better than your 4h.

let bad = new DenseMatrix(10500,10500)
for col in 0..999 do
    for row in 0..999 do
        bad.At(10*row, 10*col, float32 (Math.Atan2(float row, float col)))
        bad.At(2+10*row, 3+10*col, float32 (row+col))

This second version is not row by row, and needs almost 20 times the time of the first example (lot of copying involved).

Hence, if you can, sort your fields by rows and then cols, ascending, before insertion. Thinking about it, we could provide some sort of sparse matrix initialization helper to support such scenarios. They could avoid almost if not all copying if the list of non-zero cells is available in memory at the beginning, speeding it up significantly.

B) Minor: Use At(r,c,v) instead of the [r,c] indexer if you don't need range checking (slightly faster)

Although in this case it probably doesn't make much of a difference

C) Directly populate the underlying storage

Create an instance of the SparseCompressedRowMatrixStorage class and populate the RowPointer/ColumnIndex/Values arrays directly. Then create the matrix usingnew SparseMatrix(storage). This is clearly the most performant approach (as long as we do not provide an initializer as mentioned above), but requires knowledge of the chosen storage layout.

D) Consider dense matrices

If I change the above example to use a dense matrix instead (after all such a 100M cell matrix still fits into memory easily):

let dense = new DenseMatrix(10500,10500)
for row in 0..999 do
    for col in 0..999 do
        dense.At(10*row, 10*col, float32 (Math.Atan2(float row, float col)))
        dense.At(2+10*row, 3+10*col, float32 (row+col))

then the example runs in less than a second. However, any operation on that matrix would obviously then be very inefficient, but it depends what you actually want to do with it.

 

Thinking about it, we should really consider to provide some efficient sparse matrix initializer (as mentioned in A), that avoids any expensive copying at the cost of a two-pass process. In your case that may work nicely, since it seems you already know all possible non-zero value indices at the beginning (in your hash table). Let me know what you think.

Thanks,
Christoph 

New Post: How to load data into matrix

$
0
0

Quick note: we currently have a pull request open for an alternative sparse storage scheme (based on Knuth) that might be much more efficient in this scenario, since it seems to avoid almost all copying in this case. Might be worth to give it a trial.

Thanks,
Christoph 

New Post: How to load data into matrix

$
0
0
Thanks a bunch, Christoph.

We'll look at this and let you know what we come up with.

Yvonne


On Tue, Nov 27, 2012 at 6:02 AM, cdrnet <notifications@codeplex.com> wrote:

From: cdrnet

Quick note: we currently have a [url:pull request|https://github.com/mathnet/mathnet-numerics/pull/58] open for an alternative sparse storage scheme (based on Knuth) that might be much more efficient in this scenario, since it seems to avoid almost all copying in this case. Might be worth to give it a trial.

Thanks,
Christoph

Read the full discussion online.

To add a post to this discussion, reply to this email (mathnetnumerics@discussions.codeplex.com)

To start a new discussion for this project, email mathnetnumerics@discussions.codeplex.com

You are receiving this email because you subscribed to this discussion on CodePlex. You can unsubscribe on CodePlex.com.

Please note: Images and attachments will be removed from emails. Any posts to this discussion will also be available online at CodePlex.com




--
--
Yvonne Burgess
Chief Systems Architect
Climate Earth, Inc.
415.391.2725 (office)
415.816.2674 (mobile)
www.climateearth.com

New Post: How to load data into matrix

$
0
0
Christoph,

re: your comment:

"D) Consider dense matrices

If I change the above example to use a dense matrix instead (after all such a 100M cell matrix still fits into memory easily):

let dense = new DenseMatrix(10500,10500)
for row in 0..999 do
    for col in 0..999 do
        dense.At(10*row, 10*col, float32 (Math.Atan2(float row, float col)))
        dense.At(2+10*row, 3+10*col, float32 (row+col))

then the example runs in less than a second. However, any operation on that matrix would obviously then be very inefficient, but it depends what you actually want to do with it."


Our next operation on this bad boy is:

D = (SparseMatrix)(I - A).Inverse();

where I is the identity matrix also (10500, 10500). If you have suggestions on improving this code, we welcome your comment.


When we went from working with 800x800 matrices to the dim 10500, we hit out of memory problems just initializing the I matrix. So we pulled in the latest Math.Net libraries and switched most of the matrices to Sparse except for those over 50% non-zero ... but maybe we should try setting them back to Matrix or as DenseMatrix.

When you say "(after all such a 100M cell matrix still fits into memory easily)" - do you have guideline for selecting use of sparse vs. dense? I (simpleton) just computed number of non-zero datapoints as a percentage to determine whether the thing was sparse or not. Do you have a smarter guideline we should be using?

Thanks for all your help!

Yvonne




On Tue, Nov 27, 2012 at 8:20 AM, Yvonne Burgess <yvonne@climateearth.com> wrote:
Thanks a bunch, Christoph.

We'll look at this and let you know what we come up with.

Yvonne


On Tue, Nov 27, 2012 at 6:02 AM, cdrnet <notifications@codeplex.com> wrote:

From: cdrnet

Quick note: we currently have a [url:pull request|https://github.com/mathnet/mathnet-numerics/pull/58] open for an alternative sparse storage scheme (based on Knuth) that might be much more efficient in this scenario, since it seems to avoid almost all copying in this case. Might be worth to give it a trial.

Thanks,
Christoph

Read the full discussion online.

To add a post to this discussion, reply to this email (mathnetnumerics@discussions.codeplex.com)

To start a new discussion for this project, email mathnetnumerics@discussions.codeplex.com

You are receiving this email because you subscribed to this discussion on CodePlex. You can unsubscribe on CodePlex.com.

Please note: Images and attachments will be removed from emails. Any posts to this discussion will also be available online at CodePlex.com




--
--
Yvonne Burgess
Chief Systems Architect
Climate Earth, Inc.
415.391.2725 (office)
415.816.2674 (mobile)
www.climateearth.com




--
--
Yvonne Burgess
Chief Systems Architect
Climate Earth, Inc.
415.391.2725 (office)
415.816.2674 (mobile)
www.climateearth.com

New Post: test


New Post: Solving Ax=B in visual basic

$
0
0

Hi cuda, thanks for your help!

I followed your example (programming in VB ofc), although when using this LU decomposition, I run into a series of NaN (not a number) results. I've been debugging this project (all the "pre-system-solving" code) using an old example I had programmed in Fortran. Both the A matrix and the B vector are similar to the ones of the so called example, although LaPack's DGESV seems to be capable of solving it, but this one does not. Any thoughts ?

Thank you in advance, once again. 

New Post: Solving Ax=B in visual basic

$
0
0

Could you post your A matrix and B vector here so I could test a couple things? or e-mail them to me at marcus@cuda.org.

Thanks,
Marcus 

Updated Wiki: Random Numbers

$
0
0

Random Number Generation

The .Net Framwork comes with two (pseudo) random number sources: System.Random and System.Security.Cryptography.RNGCryptoServiceProvider. The former is commonly used throughout the .Net space for general purpose random number generation, the latter in selected cases where random data is needed for cryptoghraphic applications and more "randomness" is required, at the cost of being slower. If you're not sure which one to choose, where randomness is not critical we suggest to simply use System.Random, or MersenneTwister if it turns out to be too slow.

Math.NET Numerics provides a whole set of alternative pseudo random number generators (RNG). Yet, in order to stay fully compatible with other code expecting a traditional System.Random instance, all our providers derive from System.Random (via our AbstractRandomNumberGenerator class) and can thus be used directly in place of System.Random.

Random Number Generators

  • MersenneTwister: Mersenne Twister 19937 generator
  • Xorshift: Multiply-with-carry XOR-shift generator
  • Mcg31m1: Multiplicative congruental generator using a modulus of 2^31-1 and a multiplier of 1132489760
  • Mcg59: Multiplicative congruental generator using a modulus of 2^59 and a multiplier of 13^13
  • WH1982: Wichmann-Hill's 1982 combined multiplicative congruental generator
  • WH2006: Wichmann-Hill's 2006 combined multiplicative congruental generator
  • Mrg32k3a: 32-bit combined multiple recursive generator with 2 components of order 3
  • Palf: Parallel Additive Lagged Fibonacci generator
  • SystemCryptoRandomNumberGenerator: Generator using the RNGCryptoServiceProvider of the .Net framework

Non-Standard Ranges

Often you don't need a random number between 0 and 1 but in a different range, or e.g. a random integer of the full integer type range. Generating such random numbers correctly is non-trivial if the distribution should remain uniform (including at 0, min, max etc.). That's why we also provide a set of extension methods (in addition to Next and NextDouble) defined directly on System.Random, so the can be used not only on our custom RNGs but even with System.Random instances:
  • NextInt64: Returns a 64-bit signed integer greater than or equal to 0 and less than Int64.MaxValue. This is therefore the equivalent of the Next method but for 64-bit integers instead of 32-bit integers. Distributed uniformly.
  • NextFullRangeInt32: Returns a 32-bit signed integer of the full range, including 0, negative numbers, Int32.MinValue and Int32.MaxValue. Distributed uniformly.
  • NextFullRangeInt64: Returns a 64-bit signed integer of the full range, including 0, negative numbers, Int64.MinValue and Int64.MaxValue. Distributed uniformly.
  • NextDecimal: Returns a decimal floating point number greater than or equal to 0.0 and less than 1.0. Distributed uniformly.

Non-Uniform Random Numbers

If you need to generate non-uniform random numbers, you can combine any of these generators with our probability distributions, see Probability Distributions.

Updated Wiki: Random Numbers

$
0
0

Random Number Generation

The .Net Framwork comes with two (pseudo) random number sources: System.Random and System.Security.Cryptography.RNGCryptoServiceProvider. The former is commonly used throughout the .Net space for general purpose random number generation, the latter in selected cases where random data is needed for cryptoghraphic applications and more "randomness" is required, at the cost of being slower. If you're not sure which one to choose, where randomness is not critical we suggest to simply use System.Random, or MersenneTwister if it turns out to be too slow.

Random Number Generators

Math.NET Numerics provides a whole set of alternative pseudo random number generators (RNG). Yet, in order to stay fully compatible with other code expecting a traditional System.Random instance, all our providers derive from System.Random (via our AbstractRandomNumberGenerator class) and can thus be used directly in place of System.Random.
  • MersenneTwister: Mersenne Twister 19937 generator
  • Xorshift: Multiply-with-carry XOR-shift generator
  • Mcg31m1: Multiplicative congruental generator using a modulus of 2^31-1 and a multiplier of 1132489760
  • Mcg59: Multiplicative congruental generator using a modulus of 2^59 and a multiplier of 13^13
  • WH1982: Wichmann-Hill's 1982 combined multiplicative congruental generator
  • WH2006: Wichmann-Hill's 2006 combined multiplicative congruental generator
  • Mrg32k3a: 32-bit combined multiple recursive generator with 2 components of order 3
  • Palf: Parallel Additive Lagged Fibonacci generator
  • SystemCryptoRandomNumberGenerator: Generator using the RNGCryptoServiceProvider of the .Net framework

Non-Standard Ranges

Often you don't need a random number between 0 and 1 but in a different range, or e.g. a random integer of the full integer type range. Generating such random numbers correctly is non-trivial if the distribution should remain uniform (including at 0, min, max etc.). That's why we also provide a set of extension methods (in addition to Next and NextDouble) defined directly on System.Random, so the can be used not only on our custom RNGs but even with System.Random instances:
  • NextInt64: Returns a 64-bit signed integer greater than or equal to 0 and less than Int64.MaxValue. This is therefore the equivalent of the Next method but for 64-bit integers instead of 32-bit integers. Distributed uniformly.
  • NextFullRangeInt32: Returns a 32-bit signed integer of the full range, including 0, negative numbers, Int32.MinValue and Int32.MaxValue. Distributed uniformly.
  • NextFullRangeInt64: Returns a 64-bit signed integer of the full range, including 0, negative numbers, Int64.MinValue and Int64.MaxValue. Distributed uniformly.
  • NextDecimal: Returns a decimal floating point number greater than or equal to 0.0 and less than 1.0. Distributed uniformly.

Non-Uniform Random Numbers

If you need to generate non-uniform random numbers, you can combine any of these generators with our probability distributions, see Probability Distributions.

Updated Wiki: Random Numbers

$
0
0

Random Number Generation

The .Net Framwork comes with two (pseudo) random number sources: System.Random and System.Security.Cryptography.RNGCryptoServiceProvider. The former is commonly used throughout the .Net space for general purpose random number generation, the latter in selected cases where random data is needed for cryptoghraphic applications and more "randomness" is required, at the cost of being slower. If you're not sure which one to choose, where randomness is not critical we suggest to simply use System.Random, or MersenneTwister if it turns out to be too slow.

Math.NET Numerics provides a whole set of alternative pseudo random number generators (RNG). Yet, in order to stay fully compatible with other code expecting a traditional System.Random instance, all our providers derive from System.Random (via our AbstractRandomNumberGenerator class) and can thus be used directly in place of System.Random.

Random Number Generators

Namespace: MathNet.Numerics.Random
  • MersenneTwister: Mersenne Twister 19937 generator
  • Xorshift: Multiply-with-carry XOR-shift generator
  • Mcg31m1: Multiplicative congruental generator using a modulus of 2^31-1 and a multiplier of 1132489760
  • Mcg59: Multiplicative congruental generator using a modulus of 2^59 and a multiplier of 13^13
  • WH1982: Wichmann-Hill's 1982 combined multiplicative congruental generator
  • WH2006: Wichmann-Hill's 2006 combined multiplicative congruental generator
  • Mrg32k3a: 32-bit combined multiple recursive generator with 2 components of order 3
  • Palf: Parallel Additive Lagged Fibonacci generator
  • SystemCryptoRandomNumberGenerator: Generator using the RNGCryptoServiceProvider of the .Net framework. Note: Not available in portable builds

Seeding and thread safety

All generator constructors optionally accept two parameters: an integer for seeding and a boolean to enable thread-safety if needed. An exception is the crypto generator, where a custom seed would defeat its purpose.

If you create two instances of the same generator and seed, they will generate exactly the same number sequence. If no seed is provided, most generator fall back to a time-based seed, which is dangerous when creating multiple generators in quick succession (since time resolution is limited, some can end up with the same seed). It is therefore essential to reuse generators instead of creating new ones every time a random number is needed, or at least to have a single random source to generate random seeds for each.

For performance and design reasons, generators are not thread-safe out of the box. However, since sharing generators is recommended, thread-safe number generation can optionally be enabled with the second, boolean constructor parameter.

Non-Standard Ranges

Often you don't need a random number between 0 and 1 but in a different range, or e.g. a random integer of the full integer type range. Generating such random numbers correctly is non-trivial if the distribution should remain uniform (including at 0, min, max etc.). That's why we also provide a set of extension methods (in addition to Next and NextDouble) defined directly on System.Random, so the can be used not only on our custom RNGs but even with System.Random instances:
  • NextInt64: Returns a 64-bit signed integer greater than or equal to 0 and less than Int64.MaxValue. This is therefore the equivalent of the Next method but for 64-bit integers instead of 32-bit integers. Distributed uniformly.
  • NextFullRangeInt32: Returns a 32-bit signed integer of the full range, including 0, negative numbers, Int32.MinValue and Int32.MaxValue. Distributed uniformly.
  • NextFullRangeInt64: Returns a 64-bit signed integer of the full range, including 0, negative numbers, Int64.MinValue and Int64.MaxValue. Distributed uniformly.
  • NextDecimal: Returns a decimal floating point number greater than or equal to 0.0 and less than 1.0. Distributed uniformly.

Non-Uniform Random Numbers

If you need to generate non-uniform random numbers, you can combine any of these generators with our probability distributions, see Probability Distributions.

Updated Wiki: Random Numbers

$
0
0

Random Number Generation

The .Net Framwork comes with two (pseudo) random number sources: System.Random and System.Security.Cryptography.RNGCryptoServiceProvider. The former is commonly used throughout the .Net space for general purpose random number generation, the latter in selected cases where random data is needed for cryptoghraphic applications and more "randomness" is required, at the cost of being slower. If you're not sure which one to choose, where randomness is not critical we suggest to simply use System.Random, or MersenneTwister if it turns out to be too slow.

Math.NET Numerics provides a whole set of alternative pseudo random number generators (RNG). Yet, in order to stay fully compatible with other code expecting a traditional System.Random instance, all our providers derive from System.Random (via our AbstractRandomNumberGenerator class) and can thus be used directly in place of System.Random.

Random Number Generators

Namespace: MathNet.Numerics.Random
  • MersenneTwister: Mersenne Twister 19937 generator
  • Xorshift: Multiply-with-carry XOR-shift generator
  • Mcg31m1: Multiplicative congruental generator using a modulus of 2^31-1 and a multiplier of 1132489760
  • Mcg59: Multiplicative congruental generator using a modulus of 2^59 and a multiplier of 13^13
  • WH1982: Wichmann-Hill's 1982 combined multiplicative congruental generator
  • WH2006: Wichmann-Hill's 2006 combined multiplicative congruental generator
  • Mrg32k3a: 32-bit combined multiple recursive generator with 2 components of order 3
  • Palf: Parallel Additive Lagged Fibonacci generator
  • SystemCryptoRandomNumberGenerator: Generator using the RNGCryptoServiceProvider of the .Net framework. Note: Not available in portable builds

Seeding and thread safety

All generator constructors optionally accept two parameters: an integer for seeding and a boolean to enable thread-safety if needed. An exception is the crypto generator, where a custom seed would defeat its purpose.

If you create two instances of the same generator and seed, they will generate exactly the same number sequence. If no seed is provided, most generator fall back to a time-based seed, which is dangerous when creating multiple generators in quick succession (since time resolution is limited, some can end up with the same seed). It is therefore essential to reuse generators instead of creating new ones every time a random number is needed, or at least to have a single random source to generate random seeds for each.

For performance and design reasons, generators are not thread-safe out of the box. However, since sharing generators is recommended, thread-safe number generation can optionally be enabled with the second, boolean constructor parameter.

Non-Standard Ranges

Often you don't need a random number between 0 and 1 but in a different range, or e.g. a random integer of the full integer type range. Generating such random numbers correctly is non-trivial if the distribution should remain uniform (including at 0, min, max etc.). That's why we also provide a set of extension methods (in addition to Next and NextDouble) defined directly on System.Random, so the can be used not only on our custom RNGs but even with System.Random instances:
  • NextInt64: Returns a 64-bit signed integer greater than or equal to 0 and less than Int64.MaxValue. This is therefore the equivalent of the Next method but for 64-bit integers instead of 32-bit integers. Distributed uniformly.
  • NextFullRangeInt32: Returns a 32-bit signed integer of the full range, including 0, negative numbers, Int32.MinValue and Int32.MaxValue. Distributed uniformly.
  • NextFullRangeInt64: Returns a 64-bit signed integer of the full range, including 0, negative numbers, Int64.MinValue and Int64.MaxValue. Distributed uniformly.
  • NextDecimal: Returns a decimal floating point number greater than or equal to 0.0 and less than 1.0. Distributed uniformly.

Non-Uniform Random Numbers

If you need to generate non-uniform random numbers, you can combine any of these generators with our probability distributions, see Probability Distributions.

Random Numbers in F#

The F# extensions provide a Random module in the MathNet.Numerics.Random namespace that tries to make using our random number generators in F# a bit simpler and more idiomatic.
  • Random.seed (): generates a GUID based seed
  • Random.timeSeed (): generates a time-based seed
  • Random.system(), Random.systemWith seed
  • Random.crypto(), Random.cryptoWith threadSafe
  • Random.mersenneTwister(), Random.mersenneTwisterWith seed threadSafe
  • Random.xorshift(), Random.xorshiftWith seed threadSafe
  • Random.wh1982(), Random.wh1982With seed threadSafe
  • Random.wh2006(), Random.wh2006With seed threadSafe
  • Random.palf(), Random.palfWith seed threadSafe
  • Random.mcg59(), Random.mcg59With seed threadSafe
  • Random.mcg31m1(), Random.mcg31m1With seed threadSafe
  • Random.mrg32k3a(), Random.mrg32k3aWith seed threadSafe

Updated Wiki: Documentation

$
0
0

Math.NET Numerics Documentation

Math.NET Numerics is an opensource numerical library for .Net, Silverlight, Metro and Mono. This topic lists documentation that will help you use the toolkit in your own application. In addition to the user guide, there's also a condensed API Reference available, or if you prefer examples the sample code project may give you some ideas.

User Guide

Advanced Topics


Updated Wiki: Random Numbers

$
0
0

Random Number Generation

The .Net Framwork comes with two (pseudo) random number sources: System.Random and System.Security.Cryptography.RNGCryptoServiceProvider. The former is commonly used throughout the .Net space for general purpose uniform random number generation, the latter in selected cases where random data is needed for cryptoghraphic applications and more "randomness" is required, at the cost of being slower. If you're not sure which one to choose, where randomness is not critical we suggest to simply use System.Random, or MersenneTwister if it turns out to be too slow.

Math.NET Numerics provides a whole set of alternative pseudo random number generators (RNG). Yet, in order to stay fully compatible with other code expecting a traditional System.Random instance, all our providers derive from System.Random (via our AbstractRandomNumberGenerator class) and can thus be used directly in place of System.Random.

using MathNet.Numerics.Random;
var mersenneTwister = new MersenneTwister(42);
double a = mersenneTwister.NextDouble();
decimal b = mersenneTwister.NextDecimal();
long c = mersenneTwiser.NextFullRangeInt64();

Random Number Generators

Namespace: MathNet.Numerics.Random
  • MersenneTwister: Mersenne Twister 19937 generator
  • Xorshift: Multiply-with-carry XOR-shift generator
  • Mcg31m1: Multiplicative congruental generator using a modulus of 2^31-1 and a multiplier of 1132489760
  • Mcg59: Multiplicative congruental generator using a modulus of 2^59 and a multiplier of 13^13
  • WH1982: Wichmann-Hill's 1982 combined multiplicative congruental generator
  • WH2006: Wichmann-Hill's 2006 combined multiplicative congruental generator
  • Mrg32k3a: 32-bit combined multiple recursive generator with 2 components of order 3
  • Palf: Parallel Additive Lagged Fibonacci generator
  • SystemCryptoRandomNumberGenerator: Generator using the RNGCryptoServiceProvider of the .Net framework. Note: Not available in portable builds

Seeding and thread safety

All generator constructors optionally accept two parameters: an integer for seeding and a boolean to enable thread-safety if needed. An exception is the crypto generator, where a custom seed would defeat its purpose.

If you create two instances of the same generator and seed, they will generate exactly the same number sequence. If no seed is provided, most generator fall back to a time-based seed, which is dangerous when creating multiple generators in quick succession (since time resolution is limited, some can end up with the same seed). It is therefore essential to reuse generators instead of creating new ones every time a random number is needed, or at least to have a single random source to generate random seeds for each.

For performance and design reasons, generators are not thread-safe out of the box. However, since sharing generators is recommended, thread-safe number generation can optionally be enabled with the second, boolean constructor parameter.

Non-Standard Ranges

Often you don't need a random number between 0 and 1 but in a different range, or e.g. a random integer of the full integer type range. Generating such random numbers correctly is non-trivial if the distribution should remain uniform (including at 0, min, max etc.). That's why we also provide a set of extension methods (in addition to Next and NextDouble) defined directly on System.Random, so the can be used not only on our custom RNGs but even with System.Random instances:
  • NextInt64: Returns a 64-bit signed integer greater than or equal to 0 and less than Int64.MaxValue. This is therefore the equivalent of the Next method but for 64-bit integers instead of 32-bit integers. Distributed uniformly.
  • NextFullRangeInt32: Returns a 32-bit signed integer of the full range, including 0, negative numbers, Int32.MinValue and Int32.MaxValue. Distributed uniformly.
  • NextFullRangeInt64: Returns a 64-bit signed integer of the full range, including 0, negative numbers, Int64.MinValue and Int64.MaxValue. Distributed uniformly.
  • NextDecimal: Returns a decimal floating point number greater than or equal to 0.0 and less than 1.0. Distributed uniformly.

Non-Uniform Random Numbers

If you need to generate non-uniform random numbers, you can combine any of these generators with our probability distributions, see Probability Distributions.

Random Numbers in F#

The F# extensions provide a Random module in the MathNet.Numerics.Random namespace that tries to make using our random number generators in F# a bit simpler and more idiomatic.
  • Random.seed (): generates a GUID based seed
  • Random.timeSeed (): generates a time-based seed
  • Random.system(), Random.systemWith seed
  • Random.crypto(), Random.cryptoWith threadSafe
  • Random.mersenneTwister(), Random.mersenneTwisterWith seed threadSafe
  • Random.xorshift(), Random.xorshiftWith seed threadSafe
  • Random.wh1982(), Random.wh1982With seed threadSafe
  • Random.wh2006(), Random.wh2006With seed threadSafe
  • Random.palf(), Random.palfWith seed threadSafe
  • Random.mcg59(), Random.mcg59With seed threadSafe
  • Random.mcg31m1(), Random.mcg31m1With seed threadSafe
  • Random.mrg32k3a(), Random.mrg32k3aWith seed threadSafe

Updated Wiki: Probability Distributions

$
0
0

Probability Distributions

In MathNet.Numerics.Distributions we provide a wide range of probability distributions. Once parametrized, they can be used to sample non-uniform random numbers or investigate their statistical properties.

All the distributions implement a basic set of operations such as computing the mean, standard deviation, density, etc. Because it is often numerically more stable and faster to compute quantities in the log domain, we also provide a selection of them, including Density, in the logarithmic domain with the "Ln" suffix, .e.g. DensityLn.

Random Number Sampling

Each distribution provides methods to generate random numbers from that distribution. These random variate generators work by accessing the distribution's member RandomSource (which is a subclass of System.Random, see Random Numbers for details) to provide uniform random numbers. By default, this member is an instance of System.Random but one can easily replace this with more sophisticated random number generators from MathNet.Numerics.Random. Each distribution class has two static and two class methods: for each pair (static and class), one of them generates a single sample, the other will generate an IEnumerable<T> of samples. The static methods allow random number generation without instantiating the actual class.

Parametrizing the Distributions

There are many ways to parameterize a distribution in the literature. When using the default constructor, study carefully which parameters it requires. If they do not suite your needs, there will likely be static method which can construct the distribution for you with the parameters of your choice. For example, to construct a normal distribution with mean 0.0 and standard deviation 2.0 you can use var n = new Normal(0.0, 2.0); . However, if you'd rather parameterize the normal distribution using a mean and precision, one can use the following code instead: var n = Normal.WithMeanPrecision(0.0,0.5);

Discrete Distributions

All discrete distributions implement the IDiscreteDistribution and IDistribution intefaces.

Continuous Distributions

All continuous distributions implement the IContinuousDistribution and IDistribution intefaces.

Multivariate Distributions

There is no shared interface for the multivariate distributions: as their domains can be quite different it would be hard to come up with a simple and clean but still useful unifying interface.

Updated Wiki: Probability Distributions

$
0
0

Probability Distributions

In MathNet.Numerics.Distributions we provide a wide range of probability distributions. Once parametrized, they can be used to sample non-uniform random numbers or investigate their statistical properties.

All the distributions implement a basic set of operations such as computing the mean, standard deviation, density, etc. Because it is often numerically more stable and faster to compute quantities in the log domain, we also provide a selection of them, including Density, in the logarithmic domain with the "Ln" suffix, .e.g. DensityLn.

using MathNet.Numerics.Random;
using MathNet.Numerics.Distributions;
var gamma = new Gamma(2.0, 1.5);
var mean = gamma.Mean;
var variance = gamma.Variance;
var entropy = gamma.Entropy;
// ...var a = gamma.Density(2.3); // pdfvar b = gamma.DensityLn(2.3); // ln(pdf)var c = gamma.CumulativeDistribution(0.7); // cdf

Random Number Sampling

Each distribution provides methods to generate random numbers from that distribution. These random variate generators work by accessing the distribution's member RandomSource (which is a subclass of System.Random, see Random Numbers for details) to provide uniform random numbers. By default, this member is an instance of System.Random but one can easily replace this with more sophisticated random number generators from MathNet.Numerics.Random. Each distribution class has two static and two class methods: for each pair (static and class), one of them generates a single sample, the other will generate an IEnumerable<T> of samples. The static methods allow random number generation without instantiating the actual class.

using MathNet.Numerics.Random;
using MathNet.Numerics.Distributions;
var gamma = new Gamma(2.0, 1.5);
gamma.RandomSource = new MersenneTwister();
double a = gamma.Sample();
double[] b = gamma.Samples().Take(100).ToArray();
Alternative using static methods (note that no intermediate value caching is possible this way and parameters must be validated on each call):

var rnd = new MersenneTwister();
double a = Gamma.Sample(rnd, 2.0, 1.5);
double[] b = Gamma.Samples(rnd, 2.0, 1.5).Take(10).ToArray();

Parametrizing the Distributions

There are many ways to parameterize a distribution in the literature. When using the default constructor, study carefully which parameters it requires. If they do not suite your needs, there will likely be static method which can construct the distribution for you with the parameters of your choice. For example, to construct a normal distribution with mean 0.0 and standard deviation 2.0 you can use var n = new Normal(0.0, 2.0); . However, if you'd rather parameterize the normal distribution using a mean and precision, one can use the following code instead: var n = Normal.WithMeanPrecision(0.0,0.5);

var gamma = Gamma.WithShapeScale(2.0, 0.75);

Discrete Distributions

All discrete distributions implement the IDiscreteDistribution and IDistribution intefaces.

Continuous Distributions

All continuous distributions implement the IContinuousDistribution and IDistribution intefaces.

Multivariate Distributions

There is no shared interface for the multivariate distributions: as their domains can be quite different it would be hard to come up with a simple and clean but still useful unifying interface.

Updated Wiki: Probability Distributions

$
0
0

Probability Distributions

In MathNet.Numerics.Distributions we provide a wide range of probability distributions. Once parametrized, they can be used to sample non-uniform random numbers or investigate their statistical properties.

All the distributions implement a basic set of operations such as computing the mean, standard deviation, density, etc. Because it is often numerically more stable and faster to compute quantities in the log domain, we also provide a selection of them, including Density, in the logarithmic domain with the "Ln" suffix, .e.g. DensityLn.

using MathNet.Numerics.Random;
using MathNet.Numerics.Distributions;
var gamma = new Gamma(2.0, 1.5);
var mean = gamma.Mean;
var variance = gamma.Variance;
var entropy = gamma.Entropy;
// ...var a = gamma.Density(2.3); // pdfvar b = gamma.DensityLn(2.3); // ln(pdf)var c = gamma.CumulativeDistribution(0.7); // cdf

Random Number Sampling

Each distribution provides methods to generate random numbers from that distribution. These random variate generators work by accessing the distribution's member RandomSource (which is a subclass of System.Random, see Random Numbers for details) to provide uniform random numbers. By default, this member is an instance of System.Random but one can easily replace this with more sophisticated random number generators from MathNet.Numerics.Random. Each distribution class has two static and two class methods: for each pair (static and class), one of them generates a single sample, the other will generate an IEnumerable<T> of samples. The static methods allow random number generation without instantiating the actual class.

using MathNet.Numerics.Random;
using MathNet.Numerics.Distributions;
var gamma = new Gamma(2.0, 1.5);
gamma.RandomSource = new MersenneTwister();
double a = gamma.Sample();
double[] b = gamma.Samples().Take(100).ToArray();
Alternative using static methods (note that no intermediate value caching is possible this way and parameters must be validated on each call):

var rnd = new MersenneTwister();
double a = Gamma.Sample(rnd, 2.0, 1.5);
double[] b = Gamma.Samples(rnd, 2.0, 1.5).Take(10).ToArray();

Parametrizing the Distributions

There are many ways to parameterize a distribution in the literature. When using the default constructor, study carefully which parameters it requires. If they do not suite your needs, there will likely be static method which can construct the distribution for you with the parameters of your choice. For example, to construct a normal distribution with mean 0.0 and standard deviation 2.0 you can use var n = new Normal(0.0, 2.0); . However, if you'd rather parameterize the normal distribution using a mean and precision, one can use the following code instead: var n = Normal.WithMeanPrecision(0.0,0.5);

var gamma = Gamma.WithShapeScale(2.0, 0.75);

Probability Distributions in F#

The F# extensions provide a few simple helper functions in the MathNet.Numerics.Distributions namespace to assign a specific random source to a distribution: withRandom, withSystemRandom, withCryptoRandom and withMersenneTwister:

let rnd = Random.xorshift ()
let normal = Normal.WithMeanVariance(3.0, 1.5) |> withRandom rnd
let gamma = new Gamma(2.0, 1.5) |> withMersenneTwister
let cauchy = new Cauchy() |> withRandom (Random.mrg32k3aWith 10 false)

let samples = cauchy.Samples() |> Seq.take 100 |> List.ofSeq
let samples2 = Cauchy.Samples(rnd, 1.0, 3.0) |> Seq.take 20 |> List.ofSeq

Discrete Distributions

All discrete distributions implement the IDiscreteDistribution and IDistribution intefaces.

Continuous Distributions

All continuous distributions implement the IContinuousDistribution and IDistribution intefaces.

Multivariate Distributions

There is no shared interface for the multivariate distributions: as their domains can be quite different it would be hard to come up with a simple and clean but still useful unifying interface.

Updated Wiki: Probability Distributions

$
0
0

Probability Distributions

In MathNet.Numerics.Distributions we provide a wide range of probability distributions. Once parametrized, they can be used to sample non-uniform random numbers or investigate their statistical properties.

All the distributions implement a basic set of operations such as computing the mean, standard deviation, density, etc. Because it is often numerically more stable and faster to compute quantities in the log domain, we also provide a selection of them, including Density, in the logarithmic domain with the "Ln" suffix, .e.g. DensityLn.

using MathNet.Numerics.Random;
using MathNet.Numerics.Distributions;
var gamma = new Gamma(2.0, 1.5);
var mean = gamma.Mean;
var variance = gamma.Variance;
var entropy = gamma.Entropy;
// ...var a = gamma.Density(2.3); // pdfvar b = gamma.DensityLn(2.3); // ln(pdf)var c = gamma.CumulativeDistribution(0.7); // cdf

Random Number Sampling

Each distribution provides methods to generate random numbers from that distribution. These random variate generators work by accessing the distribution's member RandomSource (which is a subclass of System.Random, see Random Numbers for details) to provide uniform random numbers. By default, this member is an instance of System.Random but one can easily replace this with more sophisticated random number generators from MathNet.Numerics.Random. Each distribution class has two static and two class methods: for each pair (static and class), one of them generates a single sample, the other will generate an IEnumerable<T> of samples. The static methods allow random number generation without instantiating the actual class.

using MathNet.Numerics.Random;
using MathNet.Numerics.Distributions;
var gamma = new Gamma(2.0, 1.5);
gamma.RandomSource = new MersenneTwister();
double a = gamma.Sample();
double[] b = gamma.Samples().Take(100).ToArray();
Alternative using static methods (note that no intermediate value caching is possible this way and parameters must be validated on each call):

var rnd = new MersenneTwister();
double a = Gamma.Sample(rnd, 2.0, 1.5);
double[] b = Gamma.Samples(rnd, 2.0, 1.5).Take(10).ToArray();

Parametrizing the Distributions

There are many ways to parameterize a distribution in the literature. When using the default constructor, study carefully which parameters it requires. If they do not suite your needs, there will likely be static method which can construct the distribution for you with the parameters of your choice. For example, to construct a normal distribution with mean 0.0 and standard deviation 2.0 you can use var n = new Normal(0.0, 2.0); . However, if you'd rather parameterize the normal distribution using a mean and precision, one can use the following code instead: var n = Normal.WithMeanPrecision(0.0,0.5);

var gamma = Gamma.WithShapeScale(2.0, 0.75);

Probability Distributions in F#

The F# extensions provide a few simple helper functions in the MathNet.Numerics.Distributions namespace to assign a specific random source to a distribution: withRandom, withSystemRandom, withCryptoRandom and withMersenneTwister:

let rnd = Random.xorshift ()
let normal = Normal.WithMeanVariance(3.0, 1.5) |> withRandom rnd
let gamma = new Gamma(2.0, 1.5) |> withMersenneTwister
let cauchy = new Cauchy() |> withRandom (Random.mrg32k3aWith 10 false)

let samples = cauchy.Samples() |> Seq.take 100 |> List.ofSeq
let samples2 = Cauchy.Samples(rnd, 1.0, 3.0) |> Seq.take 20 |> List.ofSeq

Discrete Distributions

All discrete distributions implement the IDiscreteDistribution and IDistribution intefaces.

Continuous Distributions

All continuous distributions implement the IContinuousDistribution and IDistribution intefaces.

Multivariate Distributions

There is no shared interface for the multivariate distributions: as their domains can be quite different it would be hard to come up with a simple and clean but still useful unifying interface.
Viewing all 971 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>