Browse Source

examples: added Andriy's examples and bug fixes

la-knuth
Marcus Cuda 16 years ago
parent
commit
d0e926f1d9
  1. 109
      src/Examples/ConsoleHelper.cs
  2. 165
      src/Examples/ContinuousDistributions/BetaDistribution.cs
  3. 108
      src/Examples/ContinuousDistributions/CauchyDistribution.cs
  4. 151
      src/Examples/ContinuousDistributions/ChiDistribution.cs
  5. 154
      src/Examples/ContinuousDistributions/ChiSquareDistribution.cs
  6. 144
      src/Examples/ContinuousDistributions/ContinuousUniformDistribution.cs
  7. 152
      src/Examples/ContinuousDistributions/ErlangDistribution.cs
  8. 154
      src/Examples/ContinuousDistributions/ExponentialDistribution.cs
  9. 150
      src/Examples/ContinuousDistributions/FisherSnedecorDistribution.cs
  10. 141
      src/Examples/ContinuousDistributions/GammaDistribution.cs
  11. 151
      src/Examples/ContinuousDistributions/InverseGammaDistribution.cs
  12. 155
      src/Examples/ContinuousDistributions/LaplaceDistribution.cs
  13. 155
      src/Examples/ContinuousDistributions/LogNormalDistribution.cs
  14. 144
      src/Examples/ContinuousDistributions/NormalDistribution.cs
  15. 155
      src/Examples/ContinuousDistributions/ParetoDistribution.cs
  16. 154
      src/Examples/ContinuousDistributions/RayleighDistribution.cs
  17. 154
      src/Examples/ContinuousDistributions/StableDistribution.cs
  18. 149
      src/Examples/ContinuousDistributions/StudentTDistribution.cs
  19. 154
      src/Examples/ContinuousDistributions/WeibullDistribution.cs
  20. 151
      src/Examples/DiscreteDistributions/BernoulliDistribution.cs
  21. 155
      src/Examples/DiscreteDistributions/BinomialDistribution.cs
  22. 135
      src/Examples/DiscreteDistributions/CategoricalDistribution.cs
  23. 139
      src/Examples/DiscreteDistributions/ConwayMaxwellPoissonDistribution.cs
  24. 156
      src/Examples/DiscreteDistributions/DiscreteUniformDistribution.cs
  25. 154
      src/Examples/DiscreteDistributions/GeometricDistribution.cs
  26. 139
      src/Examples/DiscreteDistributions/HypergeometricDistribution.cs
  27. 149
      src/Examples/DiscreteDistributions/NegativeBinomialDistribution.cs
  28. 154
      src/Examples/DiscreteDistributions/PoissonDistribution.cs
  29. 152
      src/Examples/DiscreteDistributions/ZipfDistribution.cs
  30. 52
      src/Examples/Examples.csproj
  31. 105
      src/Examples/Integration.cs
  32. 119
      src/Examples/Interpolation/AkimaSpline.cs
  33. 118
      src/Examples/Interpolation/LinearBetweenPoints.cs
  34. 109
      src/Examples/Interpolation/RationalWithPoles.cs
  35. 111
      src/Examples/Interpolation/RationalWithoutPoles.cs
  36. 141
      src/Examples/LinearAlgebra/IterativeSolvers/BiCgStabSolver.cs
  37. 208
      src/Examples/LinearAlgebra/IterativeSolvers/CompositeSolverExample.cs
  38. 139
      src/Examples/LinearAlgebra/IterativeSolvers/GpBiCgSolver.cs
  39. 140
      src/Examples/LinearAlgebra/IterativeSolvers/MlkBiCgStabSolver.cs
  40. 140
      src/Examples/LinearAlgebra/IterativeSolvers/TFQMRSolver.cs
  41. 117
      src/Examples/NumberTheory.cs
  42. 191
      src/Examples/RandomNumberGeneration.cs
  43. 96
      src/Examples/Sampling/Chebyshev.cs
  44. 127
      src/Examples/Sampling/Equidistant.cs
  45. 131
      src/Examples/Sampling/Random.cs
  46. 96
      src/Examples/SpecialFunctions/Beta.cs
  47. 101
      src/Examples/SpecialFunctions/Common.cs
  48. 129
      src/Examples/SpecialFunctions/ErrorFunction.cs
  49. 95
      src/Examples/SpecialFunctions/Factorial.cs
  50. 116
      src/Examples/SpecialFunctions/Gamma.cs
  51. 80
      src/Examples/SpecialFunctions/Stability.cs
  52. 133
      src/Examples/Statistics.cs
  53. 2
      src/Numerics/Distributions/Continuous/Chi.cs
  54. 2
      src/Numerics/Distributions/Continuous/ChiSquare.cs
  55. 3
      src/Numerics/Distributions/Discrete/Hypergeometric.cs
  56. 2
      src/Numerics/Interpolation/Algorithms/BulirschStoerRationalInterpolation.cs
  57. 4
      src/Numerics/LinearAlgebra/Complex/Solvers/Iterative/CompositeSolver.cs
  58. 4
      src/Numerics/LinearAlgebra/Complex32/Solvers/Iterative/CompositeSolver.cs
  59. 4
      src/Numerics/LinearAlgebra/Double/Solvers/Iterative/CompositeSolver.cs
  60. 4
      src/Numerics/LinearAlgebra/Single/Solvers/Iterative/CompositeSolver.cs
  61. 4
      src/Numerics/NumberTheory/IntegerTheory.cs

109
src/Examples/ConsoleHelper.cs

@ -0,0 +1,109 @@
// <copyright file="ConsoleHelper.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples
{
using System;
using MathNet.Numerics.Statistics;
/// <summary>
/// Helper fucntions to output into Console window
/// </summary>
public static class ConsoleHelper
{
/// <summary>
/// Disoplay histogram from the array
/// </summary>
/// <param name="data">Source array</param>
public static void DisplayHistogram(double[] data)
{
var blockSymbol = Convert.ToChar(9608);
var rowMaxLength = Console.WindowWidth - 1;
rowMaxLength = (rowMaxLength / 10) * 10;
var rowCount = rowMaxLength / 3;
var histogram = new Histogram(data, rowMaxLength);
// Find the absolute peak
var maxBucketCount = 0.0;
for (var i = 0; i < histogram.BucketCount; i++)
{
if (histogram[i].Count > maxBucketCount)
{
maxBucketCount = histogram[i].Count;
}
}
// Number of bucket counts between rows
var rowStep = maxBucketCount / rowCount;
// Draw histogram line-by-line
Console.WriteLine();
for (var row = 0; row < rowCount; row++)
{
for (var col = 0; col < histogram.BucketCount; col++)
{
if (histogram[col].Count >= maxBucketCount)
{
Console.Write(blockSymbol);
}
else
{
Console.Write(@" ");
}
}
Console.SetCursorPosition(0, Console.CursorTop + 1);
maxBucketCount -= rowStep;
}
// Calculate distanse between label in X axis
var axisStep = histogram.BucketCount / 2;
var leftLabel = histogram.LowerBound.ToString("N");
var middleLabel = ((histogram.UpperBound + histogram.LowerBound) / 2.0).ToString("N");
var rightLabel = histogram.UpperBound.ToString("N");
Console.Write(leftLabel);
for (var j = 0; j < axisStep - leftLabel.Length; j++)
{
Console.Write(@" ");
}
Console.Write(middleLabel);
for (var j = 0; j < axisStep - middleLabel.Length; j++)
{
Console.Write(@" ");
}
Console.Write(rightLabel);
Console.WriteLine();
}
}
}

165
src/Examples/ContinuousDistributions/BetaDistribution.cs

@ -0,0 +1,165 @@
// <copyright file="BetaDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.ContinuousDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// Beta distribution example
/// </summary>
public class BetaDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/BetaDistribution.html"/>
public string Name
{
get
{
return "Beta distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Beta distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Beta_distribution">Beta distribution</a>
public void Run()
{
// 1. Initialize the new instance of the Beta distribution class with parameters a = 5 and b = 1.
var beta = new Beta(5, 1);
Console.WriteLine(@"1. Initialize the new instance of the Beta distribution class with parameters a = {0} and b = {1}", beta.A, beta.B);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", beta);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", beta.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability density at location '0.3'", beta.Density(0.3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability density at location '0.3'", beta.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", beta.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", beta.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", beta.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", beta.Mean.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", beta.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", beta.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", beta.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", beta.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the Beta distribution
Console.WriteLine(@"3. Generate 10 samples of the Beta distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(beta.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the Beta(5, 1) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the Beta(5, 1) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = beta.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the Beta(2, 5) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the Beta(2, 5) distribution and display histogram");
beta.A = 2;
beta.B = 5;
for (var i = 0; i < data.Length; i++)
{
data[i] = beta.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 6. Generate 100000 samples of the Beta distribution and display histogram
Console.WriteLine(@"6. Generate 100000 samples of the Beta(0.5, 0.5) distribution and display histogram");
beta.A = 0.5;
beta.B = 0.5;
for (var i = 0; i < data.Length; i++)
{
data[i] = beta.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 7. Generate 100000 samples of the Beta distribution and display histogram
Console.WriteLine(@"7. Generate 100000 samples of the Beta(2, 2) distribution and display histogram");
beta.A = 2;
beta.B = 2;
for (var i = 0; i < data.Length; i++)
{
data[i] = beta.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

108
src/Examples/ContinuousDistributions/CauchyDistribution.cs

@ -0,0 +1,108 @@
// <copyright file="CauchyDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.ContinuousDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// Cauchy distribution example
/// </summary>
public class CauchyDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/CauchyDistribution.html"/>
public string Name
{
get
{
return "Cauchy distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Cauchy distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Cauchy_distribution">Cauchy distribution</a>
public void Run()
{
// 1. Initialize the new instance of the Cauchy distribution class with parameters Location = 1 and Scale = 2.
var cauchy = new Cauchy(1, 2);
Console.WriteLine(@"1. Initialize the new instance of the Cauchy distribution class with parameters Location = {0} and Scale = {1}", cauchy.Location, cauchy.Scale);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", cauchy);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", cauchy.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability density at location '0.3'", cauchy.Density(0.3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability density at location '0.3'", cauchy.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", cauchy.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", cauchy.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", cauchy.Minimum.ToString(" #0.00000;-#0.00000"));
// Median
Console.WriteLine(@"{0} - Median", cauchy.Median.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", cauchy.Mode.ToString(" #0.00000;-#0.00000"));
// 3. Generate 10 samples of the Cauchy distribution
Console.WriteLine(@"3. Generate 10 samples of the Cauchy distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(cauchy.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
}
}
}

151
src/Examples/ContinuousDistributions/ChiDistribution.cs

@ -0,0 +1,151 @@
// <copyright file="ChiDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.ContinuousDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// Chi distribution example
/// </summary>
public class ChiDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/ChiDistribution.html"/>
public string Name
{
get
{
return "Chi distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Chi distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Chi_distribution">Chi distribution</a>
public void Run()
{
// 1. Initialize the new instance of the Chi distribution class with parameter dof = 1.
var chi = new Chi(1);
Console.WriteLine(@"1. Initialize the new instance of the Chi distribution class with parameter DegreesOfFreedom = {0}", chi.DegreesOfFreedom);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", chi);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", chi.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability density at location '0.3'", chi.Density(0.3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability density at location '0.3'", chi.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", chi.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", chi.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", chi.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", chi.Mean.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", chi.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", chi.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", chi.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", chi.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the Chi distribution
Console.WriteLine(@"3. Generate 10 samples of the Chi distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(chi.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the Chi(1) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the Chi(1) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = chi.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the Chi(2) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the Chi(2) distribution and display histogram");
chi.DegreesOfFreedom = 2;
for (var i = 0; i < data.Length; i++)
{
data[i] = chi.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 6. Generate 100000 samples of the Chi(5) distribution and display histogram
Console.WriteLine(@"6. Generate 100000 samples of the Chi(5) distribution and display histogram");
chi.DegreesOfFreedom = 5;
for (var i = 0; i < data.Length; i++)
{
data[i] = chi.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

154
src/Examples/ContinuousDistributions/ChiSquareDistribution.cs

@ -0,0 +1,154 @@
// <copyright file="ChiSquareDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.ContinuousDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// ChiSquare distribution example
/// </summary>
public class ChiSquareDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/ChiSquareDistribution.html"/>
public string Name
{
get
{
return "ChiSquare distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "ChiSquare distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Chi-square_distribution">ChiSquare distribution</a>
public void Run()
{
// 1. Initialize the new instance of the ChiSquare distribution class with parameter dof = 1.
var chiSquare = new ChiSquare(1);
Console.WriteLine(@"1. Initialize the new instance of the ChiSquare distribution class with parameter DegreesOfFreedom = {0}", chiSquare.DegreesOfFreedom);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", chiSquare);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", chiSquare.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability density at location '0.3'", chiSquare.Density(0.3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability density at location '0.3'", chiSquare.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", chiSquare.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", chiSquare.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", chiSquare.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", chiSquare.Mean.ToString(" #0.00000;-#0.00000"));
// Median
Console.WriteLine(@"{0} - Median", chiSquare.Median.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", chiSquare.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", chiSquare.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", chiSquare.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", chiSquare.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the ChiSquare distribution
Console.WriteLine(@"3. Generate 10 samples of the ChiSquare distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(chiSquare.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the ChiSquare(1) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the ChiSquare(1) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = chiSquare.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the ChiSquare(4) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the ChiSquare(4) distribution and display histogram");
chiSquare.DegreesOfFreedom = 4;
for (var i = 0; i < data.Length; i++)
{
data[i] = chiSquare.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 6. Generate 100000 samples of the ChiSquare(8) distribution and display histogram
Console.WriteLine(@"6. Generate 100000 samples of the ChiSquare(8) distribution and display histogram");
chiSquare.DegreesOfFreedom = 8;
for (var i = 0; i < data.Length; i++)
{
data[i] = chiSquare.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

144
src/Examples/ContinuousDistributions/ContinuousUniformDistribution.cs

@ -0,0 +1,144 @@
// <copyright file="ContinuousUniformDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.ContinuousDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// ContinuousUniform distribution example
/// </summary>
public class ContinuousUniformDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/UniformDistribution.html"/>
public string Name
{
get
{
return "ContinuousUniform distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "ContinuousUniform distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Uniform_distribution_%28continuous%29">ContinuousUniform distribution</a>
public void Run()
{
// 1. Initialize the new instance of the ContinuousUniform distribution class with default parameters.
var continuousUniform = new ContinuousUniform();
Console.WriteLine(@"1. Initialize the new instance of the ContinuousUniform distribution class with parameters Lower = {0}, Upper = {1}", continuousUniform.Lower, continuousUniform.Upper);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", continuousUniform);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", continuousUniform.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability density at location '0.3'", continuousUniform.Density(0.3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability density at location '0.3'", continuousUniform.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", continuousUniform.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", continuousUniform.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", continuousUniform.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", continuousUniform.Mean.ToString(" #0.00000;-#0.00000"));
// Median
Console.WriteLine(@"{0} - Median", continuousUniform.Median.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", continuousUniform.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", continuousUniform.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", continuousUniform.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", continuousUniform.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the ContinuousUniform distribution
Console.WriteLine(@"3. Generate 10 samples of the ContinuousUniform distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(continuousUniform.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the ContinuousUniform(0, 1) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the ContinuousUniform(0, 1) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = continuousUniform.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the ContinuousUniform(2, 10) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the ContinuousUniform(2, 10) distribution and display histogram");
continuousUniform.Upper = 10;
continuousUniform.Lower = 2;
for (var i = 0; i < data.Length; i++)
{
data[i] = continuousUniform.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

152
src/Examples/ContinuousDistributions/ErlangDistribution.cs

@ -0,0 +1,152 @@
// <copyright file="ErlangDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.ContinuousDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// Erlang distribution example
/// </summary>
public class ErlangDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/ErlangDistribution.html"/>
public string Name
{
get
{
return "Erlang distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Erlang distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Erlang_distribution">Erlang distribution</a>
public void Run()
{
// 1. Initialize the new instance of the Erlang distribution class with parameters Shape = 1, Scale = 2.
var erlang = new Erlang(1, 2.0);
Console.WriteLine(@"1. Initialize the new instance of the Erlang distribution class with parameters Shape = {0}, Scale = {1}", erlang.Shape, erlang.Scale);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", erlang);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", erlang.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability density at location '0.3'", erlang.Density(0.3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability density at location '0.3'", erlang.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", erlang.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", erlang.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", erlang.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", erlang.Mean.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", erlang.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", erlang.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", erlang.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", erlang.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the Erlang distribution
Console.WriteLine(@"3. Generate 10 samples of the Erlang distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(erlang.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the Erlang(1, 2.0) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the Erlang(1, 2.0) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = erlang.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the Erlang(3, 2.0) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the Erlang(3, 2.0) distribution and display histogram");
erlang.Shape = 3;
for (var i = 0; i < data.Length; i++)
{
data[i] = erlang.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 6. Generate 100000 samples of the Erlang(9, 0.5) distribution and display histogram
Console.WriteLine(@"6. Generate 100000 samples of the Erlang(9, 0.5) distribution and display histogram");
erlang.Shape = 9;
erlang.Scale = 0.5;
for (var i = 0; i < data.Length; i++)
{
data[i] = erlang.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

154
src/Examples/ContinuousDistributions/ExponentialDistribution.cs

@ -0,0 +1,154 @@
// <copyright file="ExponentialDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.ContinuousDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// Exponential distribution example
/// </summary>
public class ExponentialDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/ExponentialDistribution.html"/>
public string Name
{
get
{
return "Exponential distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Exponential distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Exponential_distribution">Exponential distribution</a>
public void Run()
{
// 1. Initialize the new instance of the Exponential distribution class with parameter Lambda = 1.
var exponential = new Exponential(1);
Console.WriteLine(@"1. Initialize the new instance of the Exponential distribution class with parameter Lambda = {0}", exponential.Lambda);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", exponential);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", exponential.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability density at location '0.3'", exponential.Density(0.3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability density at location '0.3'", exponential.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", exponential.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", exponential.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", exponential.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", exponential.Mean.ToString(" #0.00000;-#0.00000"));
// Median
Console.WriteLine(@"{0} - Median", exponential.Median.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", exponential.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", exponential.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", exponential.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", exponential.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the Exponential distribution
Console.WriteLine(@"3. Generate 10 samples of the Exponential distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(exponential.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the Exponential(1) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the Exponential(1) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = exponential.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the Exponential(9) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the Exponential(9) distribution and display histogram");
exponential.Lambda = 9;
for (var i = 0; i < data.Length; i++)
{
data[i] = exponential.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 6. Generate 100000 samples of the Exponential(0.01) distribution and display histogram
Console.WriteLine(@"6. Generate 100000 samples of the Exponential(0.01) distribution and display histogram");
exponential.Lambda = 0.01;
for (var i = 0; i < data.Length; i++)
{
data[i] = exponential.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

150
src/Examples/ContinuousDistributions/FisherSnedecorDistribution.cs

@ -0,0 +1,150 @@
// <copyright file="FisherSnedecorDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.ContinuousDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// FisherSnedecor distribution example
/// </summary>
public class FisherSnedecorDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/FisherZDistribution.html"/>
public string Name
{
get
{
return "FisherSnedecor distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "FisherSnedecor distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/F-distribution">FisherSnedecor distribution</a>
public void Run()
{
// 1. Initialize the new instance of the FisherSnedecor distribution class with parameter DegreeOfFreedom1 = 50, DegreeOfFreedom2 = 20.
var fisherSnedecor = new FisherSnedecor(50, 20);
Console.WriteLine(@"1. Initialize the new instance of the FisherSnedecor distribution class with parameters DegreeOfFreedom1 = {0}, DegreeOfFreedom2 = {1}", fisherSnedecor.DegreeOfFreedom1, fisherSnedecor.DegreeOfFreedom2);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", fisherSnedecor);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", fisherSnedecor.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability density at location '0.3'", fisherSnedecor.Density(0.3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability density at location '0.3'", fisherSnedecor.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", fisherSnedecor.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", fisherSnedecor.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", fisherSnedecor.Mean.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", fisherSnedecor.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", fisherSnedecor.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", fisherSnedecor.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", fisherSnedecor.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the FisherSnedecor distribution
Console.WriteLine(@"3. Generate 10 samples of the FisherSnedecor distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(fisherSnedecor.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the FisherSnedecor(50, 20) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the FisherSnedecor(50, 20) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = fisherSnedecor.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the FisherSnedecor(20, 10) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the FisherSnedecor(20, 10) distribution and display histogram");
fisherSnedecor.DegreeOfFreedom1 = 20;
fisherSnedecor.DegreeOfFreedom2 = 10;
for (var i = 0; i < data.Length; i++)
{
data[i] = fisherSnedecor.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 6. Generate 100000 samples of the FisherSnedecor(100, 100) distribution and display histogram
Console.WriteLine(@"6. Generate 100000 samples of the FisherSnedecor(100, 100) distribution and display histogram");
fisherSnedecor.DegreeOfFreedom1 = 100;
fisherSnedecor.DegreeOfFreedom2 = 100;
for (var i = 0; i < data.Length; i++)
{
data[i] = fisherSnedecor.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

141
src/Examples/ContinuousDistributions/GammaDistribution.cs

@ -0,0 +1,141 @@
// <copyright file="GammaDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.ContinuousDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// Gamma distribution example
/// </summary>
public class GammaDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/GammaDistribution.html"/>
public string Name
{
get
{
return "Gamma distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Gamma distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Gamma_distribution">Gamma distribution</a>
public void Run()
{
// 1. Initialize the new instance of the Gamma distribution class with parameter Shape = 1, Scale = 0.5.
var gamma = new Gamma(1, 2.0);
Console.WriteLine(@"1. Initialize the new instance of the Gamma distribution class with parameters Shape = {0}, Scale = {1}", gamma.Shape, gamma.Scale);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", gamma);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", gamma.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability density at location '0.3'", gamma.Density(0.3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability density at location '0.3'", gamma.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", gamma.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", gamma.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", gamma.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", gamma.Mean.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", gamma.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", gamma.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", gamma.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", gamma.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the Gamma distribution
Console.WriteLine(@"3. Generate 10 samples of the Gamma distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(gamma.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the Gamma(1, 2) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the Gamma(1, 2) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = gamma.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the Gamma(8) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the Gamma(5, 1) distribution and display histogram");
gamma.Shape = 5;
gamma.Scale = 1;
for (var i = 0; i < data.Length; i++)
{
data[i] = gamma.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

151
src/Examples/ContinuousDistributions/InverseGammaDistribution.cs

@ -0,0 +1,151 @@
// <copyright file="InverseGammaDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.ContinuousDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// InverseGamma distribution example
/// </summary>
public class InverseGammaDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/InverseGammaDistribution.html"/>
public string Name
{
get
{
return "InverseGamma distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "InverseGamma distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Inverse-gamma_distribution">InverseGamma distribution</a>
public void Run()
{
// 1. Initialize the new instance of the InverseGamma distribution class with parameters shape = 4, scale = 0.5
var inverseGamma = new InverseGamma(4, 0.5);
Console.WriteLine(@"1. Initialize the new instance of the InverseGamma distribution class with parameters Shape = {0}, Scale = {1}", inverseGamma.Shape, inverseGamma.Scale);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", inverseGamma);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", inverseGamma.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability density at location '0.3'", inverseGamma.Density(0.3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability density at location '0.3'", inverseGamma.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", inverseGamma.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", inverseGamma.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", inverseGamma.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", inverseGamma.Mean.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", inverseGamma.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", inverseGamma.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", inverseGamma.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", inverseGamma.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the InverseGamma distribution
Console.WriteLine(@"3. Generate 10 samples of the InverseGamma distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(inverseGamma.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the InverseGamma(4, 0.5) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the InverseGamma(4, 0.5) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = inverseGamma.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the InverseGamma(8, 0.5) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the InverseGamma(8, 0.5) distribution and display histogram");
inverseGamma.Shape = 8;
for (var i = 0; i < data.Length; i++)
{
data[i] = inverseGamma.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 6. Generate 100000 samples of the InverseGamma(2, 1) distribution and display histogram
Console.WriteLine(@"6. Generate 100000 samples of the InverseGamma(8, 2) distribution and display histogram");
inverseGamma.Scale = 2;
for (var i = 0; i < data.Length; i++)
{
data[i] = inverseGamma.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

155
src/Examples/ContinuousDistributions/LaplaceDistribution.cs

@ -0,0 +1,155 @@
// <copyright file="LaplaceDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.ContinuousDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// Laplace distribution example
/// </summary>
public class LaplaceDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/LaplaceDistribution.html"/>
public string Name
{
get
{
return "Laplace distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Laplace distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Laplace_distribution">Laplace distribution</a>
public void Run()
{
// 1. Initialize the new instance of the Laplace distribution class with parameters Location = {0}, Scale = {1}
var laplace = new Laplace(0, 1);
Console.WriteLine(@"1. Initialize the new instance of the Laplace distribution class with parameters Location = {0}, Scale = {1}", laplace.Location, laplace.Scale);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", laplace);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", laplace.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability density at location '0.3'", laplace.Density(0.3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability density at location '0.3'", laplace.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", laplace.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", laplace.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", laplace.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", laplace.Mean.ToString(" #0.00000;-#0.00000"));
// Median
Console.WriteLine(@"{0} - Median", laplace.Median.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", laplace.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", laplace.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", laplace.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", laplace.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the Laplace distribution
Console.WriteLine(@"3. Generate 10 samples of the Laplace distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(laplace.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the Laplace(0, 1) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the Laplace(0, 1) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = laplace.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the Laplace(0, 4) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the Laplace(0, 4) distribution and display histogram");
data = new double[100000];
laplace.Scale = 4;
for (var i = 0; i < data.Length; i++)
{
data[i] = laplace.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 6. Generate 100000 samples of the Laplace(-10, 4) distribution and display histogram
Console.WriteLine(@"6. Generate 100000 samples of the Laplace(-10 4) distribution and display histogram");
laplace.Location = -10;
for (var i = 0; i < data.Length; i++)
{
data[i] = laplace.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

155
src/Examples/ContinuousDistributions/LogNormalDistribution.cs

@ -0,0 +1,155 @@
// <copyright file="LogNormalDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.ContinuousDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// LogNormal distribution example
/// </summary>
public class LogNormalDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/LogNormalDistribution.html"/>
public string Name
{
get
{
return "LogNormal distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "LogNormal distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Log-normal_distribution">LogNormal distribution</a>
public void Run()
{
// 1. Initialize the new instance of the LogNormal distribution class with parameters Mu = 0, Sigma = 1
var logNormal = new LogNormal(0, 1);
Console.WriteLine(@"1. Initialize the new instance of the LogNormal distribution class with parameters Mu = {0}, Sigma = {1}", logNormal.Mu, logNormal.Sigma);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", logNormal);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", logNormal.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability density at location '0.3'", logNormal.Density(0.3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability density at location '0.3'", logNormal.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", logNormal.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", logNormal.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", logNormal.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", logNormal.Mean.ToString(" #0.00000;-#0.00000"));
// Median
Console.WriteLine(@"{0} - Median", logNormal.Median.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", logNormal.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", logNormal.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", logNormal.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", logNormal.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples
Console.WriteLine(@"3. Generate 10 samples");
for (var i = 0; i < 10; i++)
{
Console.Write(logNormal.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the LogNormal(0, 1) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the LogNormal(0, 1) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = logNormal.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the LogNormal(0, 0.5) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the LogNormal(0, 0.5) distribution and display histogram");
logNormal.Sigma = 0.5;
for (var i = 0; i < data.Length; i++)
{
data[i] = logNormal.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 6. Generate 100000 samples of the LogNormal(5, 0.25) distribution and display histogram
Console.WriteLine(@"6. Generate 100000 samples of the LogNormal(5, 0.25) distribution and display histogram");
logNormal.Mu = 5;
logNormal.Sigma = 0.25;
for (var i = 0; i < data.Length; i++)
{
data[i] = logNormal.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

144
src/Examples/ContinuousDistributions/NormalDistribution.cs

@ -0,0 +1,144 @@
// <copyright file="NormalDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.ContinuousDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// Normal distribution example
/// </summary>
public class NormalDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/NormalDistribution.html"/>
public string Name
{
get
{
return "Normal distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Normal distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Normal_distribution">Normal distribution</a>
public void Run()
{
// 1. Initialize the new instance of the Normal distribution class with parameters Mean = 0, StdDev = 1
var normal = new Normal(0, 1);
Console.WriteLine(@"1. Initialize the new instance of the Normal distribution class with parameters Mean = {0}, StdDev = {1}", normal.Mean, normal.StdDev);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", normal);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", normal.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability density at location '0.3'", normal.Density(0.3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability density at location '0.3'", normal.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", normal.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", normal.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", normal.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", normal.Mean.ToString(" #0.00000;-#0.00000"));
// Median
Console.WriteLine(@"{0} - Median", normal.Median.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", normal.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", normal.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", normal.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", normal.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples
Console.WriteLine(@"3. Generate 10 samples");
for (var i = 0; i < 10; i++)
{
Console.Write(normal.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the Normal(0, 1) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the Normal(0, 1) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = normal.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the Normal(-10, 0.2) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the Normal(-10, 0.01) distribution and display histogram");
normal.Mean = -10;
normal.StdDev = 0.01;
for (var i = 0; i < data.Length; i++)
{
data[i] = normal.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

155
src/Examples/ContinuousDistributions/ParetoDistribution.cs

@ -0,0 +1,155 @@
// <copyright file="ParetoDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.ContinuousDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// Pareto distribution example
/// </summary>
public class ParetoDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/ParetoDistribution.html"/>
public string Name
{
get
{
return "Pareto distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Pareto distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Pareto_distribution">Pareto distribution</a>
public void Run()
{
// 1. Initialize the new instance of the Pareto distribution class with parameters Shape = 3, Scale = 1
var pareto = new Pareto(1, 3);
Console.WriteLine(@"1. Initialize the new instance of the Pareto distribution class with parameters Shape = {0}, Scale = {1}", pareto.Shape, pareto.Scale);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", pareto);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", pareto.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability density at location '0.3'", pareto.Density(0.3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability density at location '0.3'", pareto.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", pareto.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", pareto.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", pareto.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", pareto.Mean.ToString(" #0.00000;-#0.00000"));
// Median
Console.WriteLine(@"{0} - Median", pareto.Median.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", pareto.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", pareto.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", pareto.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", pareto.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the Pareto distribution
Console.WriteLine(@"3. Generate 10 samples of the Pareto distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(pareto.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the Pareto(1, 3) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the Pareto(1, 3) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = pareto.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the Pareto(1, 1) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the Pareto(1, 1) distribution and display histogram");
pareto.Shape = 1;
for (var i = 0; i < data.Length; i++)
{
data[i] = pareto.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 6. Generate 100000 samples of the Pareto(10, 5) distribution and display histogram
Console.WriteLine(@"6. Generate 100000 samples of the Pareto(10, 50) distribution and display histogram");
pareto.Shape = 50;
pareto.Scale = 10;
for (var i = 0; i < data.Length; i++)
{
data[i] = pareto.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

154
src/Examples/ContinuousDistributions/RayleighDistribution.cs

@ -0,0 +1,154 @@
// <copyright file="RayleighDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.ContinuousDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// Rayleigh distribution example
/// </summary>
public class RayleighDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/RayleighDistribution.html"/>
public string Name
{
get
{
return "Rayleigh distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Rayleigh distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Rayleigh_distribution">Rayleigh distribution</a>
public void Run()
{
// 1. Initialize the new instance of the Rayleigh distribution class with parameter Scale = 1.
var rayleigh = new Rayleigh(1);
Console.WriteLine(@"1. Initialize the new instance of the Rayleigh distribution class with parameter Scale = {0}", rayleigh.Scale);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", rayleigh);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", rayleigh.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability density at location '0.3'", rayleigh.Density(0.3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability density at location '0.3'", rayleigh.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", rayleigh.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", rayleigh.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", rayleigh.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", rayleigh.Mean.ToString(" #0.00000;-#0.00000"));
// Median
Console.WriteLine(@"{0} - Median", rayleigh.Median.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", rayleigh.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", rayleigh.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", rayleigh.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", rayleigh.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the Rayleigh distribution
Console.WriteLine(@"3. Generate 10 samples of the Rayleigh distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(rayleigh.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the Rayleigh(1) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the Rayleigh(1) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = rayleigh.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the Rayleigh(4) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the Rayleigh(4) distribution and display histogram");
rayleigh.Scale = 4;
for (var i = 0; i < data.Length; i++)
{
data[i] = rayleigh.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 6. Generate 100000 samples of the Rayleigh(0.5) distribution and display histogram
Console.WriteLine(@"6. Generate 100000 samples of the Rayleigh(0.5) distribution and display histogram");
rayleigh.Scale = 0.5;
for (var i = 0; i < data.Length; i++)
{
data[i] = rayleigh.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

154
src/Examples/ContinuousDistributions/StableDistribution.cs

@ -0,0 +1,154 @@
// <copyright file="StableDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.ContinuousDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// Stable distribution example
/// </summary>
public class StableDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/StableDistribution.html"/>
public string Name
{
get
{
return "Stable distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Stable distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Stable_distribution">Stable distribution</a>
public void Run()
{
// 1. Initialize the new instance of the Stable distribution class with parameters Alpha = 2.0, Beta = 0, Scale = 1, Location = 0.
var stable = new Stable(2.0, 0, 1, 0);
Console.WriteLine(@"1. Initialize the new instance of the Stable distribution class with parameters Alpha = {0}, Beta = {1}, Scale = {2}, Location = {3}", stable.Alpha, stable.Beta, stable.Scale, stable.Location);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", stable);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", stable.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability density at location '0.3'", stable.Density(0.3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability density at location '0.3'", stable.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", stable.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", stable.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", stable.Mean.ToString(" #0.00000;-#0.00000"));
// Median
Console.WriteLine(@"{0} - Median", stable.Median.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", stable.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", stable.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", stable.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", stable.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the Stable distribution
Console.WriteLine(@"3. Generate 10 samples of the Stable distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(stable.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the Stable(1) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the Stable(2, 0, 1, 0) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = stable.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the Stable(1, 0, 1, 0) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the Stable(1, 0, 1, 0) distribution and display histogram");
stable.Alpha = 1;
for (var i = 0; i < data.Length; i++)
{
data[i] = stable.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 6. Generate 100000 samples of the Stable(1.5, 1, 1, 5) distribution and display histogram
Console.WriteLine(@"6. Generate 100000 samples of the Stable(1.5, 1, 1, 5) distribution and display histogram");
stable.Alpha = 1.5;
stable.Beta = 1;
stable.Location = 5;
stable.Scale = 5;
for (var i = 0; i < data.Length; i++)
{
data[i] = stable.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

149
src/Examples/ContinuousDistributions/StudentTDistribution.cs

@ -0,0 +1,149 @@
// <copyright file="StudentTDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.ContinuousDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// StudentT distribution example
/// </summary>
public class StudentTDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/StudentTDistribution.html"/>
public string Name
{
get
{
return "StudentT distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "StudentT distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/StudentT_distribution">StudentT distribution</a>
public void Run()
{
// 1. Initialize the new instance of the StudentT distribution class with parameters Location = 0, Scale = 1, DegreesOfFreedom = 1
var studentT = new StudentT();
Console.WriteLine(@"1. Initialize the new instance of the StudentT distribution class with parameters Location = {0}, Scale = {1}, DegreesOfFreedom = {2}", studentT.Location, studentT.Scale, studentT.DegreesOfFreedom);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", studentT);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", studentT.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability density at location '0.3'", studentT.Density(0.3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability density at location '0.3'", studentT.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", studentT.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", studentT.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", studentT.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", studentT.Mean.ToString(" #0.00000;-#0.00000"));
// Median
Console.WriteLine(@"{0} - Median", studentT.Median.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", studentT.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", studentT.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", studentT.StdDev.ToString(" #0.00000;-#0.00000"));
// 3. Generate 10 samples of the StudentT distribution
Console.WriteLine(@"3. Generate 10 samples of the StudentT distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(studentT.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the StudentT(0, 1, 1) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the StudentT(0, 1, 1) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = studentT.Sample();
}
ConsoleHelper.DisplayHistogram(data);
// 5. Generate 100000 samples of the StudentT(0, 1, 5) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the StudentT(0, 1, 5) distribution and display histogram");
studentT.DegreesOfFreedom = 5;
for (var i = 0; i < data.Length; i++)
{
data[i] = studentT.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 6. Generate 100000 samples of the StudentT(0, 1, 10) distribution and display histogram
Console.WriteLine(@"6. Generate 100000 samples of the StudentT(0, 1, 10) distribution and display histogram");
studentT.DegreesOfFreedom = 10;
for (var i = 0; i < data.Length; i++)
{
data[i] = studentT.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

154
src/Examples/ContinuousDistributions/WeibullDistribution.cs

@ -0,0 +1,154 @@
// <copyright file="WeibullDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.ContinuousDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// Weibull distribution example
/// </summary>
public class WeibullDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/WeibullDistribution.html"/>
public string Name
{
get
{
return "Weibull distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Weibull distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Weibull_distribution">Weibull distribution</a>
public void Run()
{
// 1. Initialize the new instance of the Weibull distribution class with parameters Scale = 1, Shape = 0.5
var weibull = new Weibull(0.5, 1);
Console.WriteLine(@"1. Initialize the new instance of the Weibull distribution class with parameterы Scale = {0}, Shape = {1}", weibull.Scale, weibull.Shape);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", weibull);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", weibull.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability density at location '0.3'", weibull.Density(0.3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability density at location '0.3'", weibull.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", weibull.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", weibull.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", weibull.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", weibull.Mean.ToString(" #0.00000;-#0.00000"));
// Median
Console.WriteLine(@"{0} - Median", weibull.Median.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", weibull.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", weibull.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", weibull.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", weibull.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the Weibull distribution
Console.WriteLine(@"3. Generate 10 samples of the Weibull distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(weibull.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the Weibull(0.5, 1) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the Weibull(0.5, 1) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = weibull.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the Weibull(1.5, 1) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the Weibull(1.5, 1) distribution and display histogram");
weibull.Shape = 1.5;
for (var i = 0; i < data.Length; i++)
{
data[i] = weibull.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 6. Generate 100000 samples of the Weibull(5, 1) distribution and display histogram
Console.WriteLine(@"6. Generate 100000 samples of the Weibull(5, 1) distribution and display histogram");
weibull.Shape = 5;
for (var i = 0; i < data.Length; i++)
{
data[i] = weibull.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

151
src/Examples/DiscreteDistributions/BernoulliDistribution.cs

@ -0,0 +1,151 @@
// <copyright file="BernoulliDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.DiscreteDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// Bernoulli distribution example
/// </summary>
public class BernoulliDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/BernoulliDistribution.html"/>
public string Name
{
get
{
return "Bernoulli distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Bernoulli distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Bernoulli_distribution">Bernoulli distribution</a>
public void Run()
{
// 1. Initialize the new instance of the Bernoulli distribution class with parameter P = 0.2
var bernoulli = new Bernoulli(0.2);
Console.WriteLine(@"1. Initialize the new instance of the Bernoulli distribution class with parameter P = {0}", bernoulli.P);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", bernoulli);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '3'", bernoulli.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability mass at location '3'", bernoulli.Probability(3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability mass at location '3'", bernoulli.ProbabilityLn(3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", bernoulli.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", bernoulli.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", bernoulli.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", bernoulli.Mean.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", bernoulli.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", bernoulli.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", bernoulli.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", bernoulli.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the Bernoulli distribution
Console.WriteLine(@"3. Generate 10 samples of the Bernoulli distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(bernoulli.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the Bernoulli(0.2) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the Bernoulli(0.2) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = bernoulli.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the Bernoulli(4) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the Bernoulli(0.9) distribution and display histogram");
bernoulli.P = 0.9;
for (var i = 0; i < data.Length; i++)
{
data[i] = bernoulli.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 6. Generate 100000 samples of the Bernoulli(8) distribution and display histogram
Console.WriteLine(@"6. Generate 100000 samples of the Bernoulli(0.5) distribution and display histogram");
bernoulli.P = 0.5;
for (var i = 0; i < data.Length; i++)
{
data[i] = bernoulli.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

155
src/Examples/DiscreteDistributions/BinomialDistribution.cs

@ -0,0 +1,155 @@
// <copyright file="BinomialDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.DiscreteDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// Binomial distribution example
/// </summary>
public class BinomialDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/BinomialDistribution.html"/>
public string Name
{
get
{
return "Binomial distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Binomial distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Binomial_distribution">Binomial distribution</a>
public void Run()
{
// 1. Initialize the new instance of the Binomial distribution class with parameters P = 0.2, N = 20
var binomial = new Binomial(0.2, 20);
Console.WriteLine(@"1. Initialize the new instance of the Binomial distribution class with parameters P = {0}, N = {1}", binomial.P, binomial.N);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", binomial);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '3'", binomial.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability mass at location '3'", binomial.Probability(3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability mass at location '3'", binomial.ProbabilityLn(3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", binomial.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", binomial.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", binomial.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", binomial.Mean.ToString(" #0.00000;-#0.00000"));
// Median
Console.WriteLine(@"{0} - Median", binomial.Median.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", binomial.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", binomial.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", binomial.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", binomial.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the Binomial distribution
Console.WriteLine(@"3. Generate 10 samples of the Binomial distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(binomial.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the Binomial(0.2, 20) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the Binomial(0.2, 20) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = binomial.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the Binomial(0.7, 20) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the Binomial(0.7, 20) distribution and display histogram");
binomial.P = 0.7;
for (var i = 0; i < data.Length; i++)
{
data[i] = binomial.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 6. Generate 100000 samples of the Binomial(0.5, 40) distribution and display histogram
Console.WriteLine(@"6. Generate 100000 samples of the Binomial(0.5, 40) distribution and display histogram");
binomial.P = 0.5;
binomial.N = 40;
for (var i = 0; i < data.Length; i++)
{
data[i] = binomial.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

135
src/Examples/DiscreteDistributions/CategoricalDistribution.cs

@ -0,0 +1,135 @@
// <copyright file="CategoricalDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.DiscreteDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// Categorical distribution example
/// </summary>
public class CategoricalDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Categorical distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Categorical distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Categorical_distribution">Categorical distribution</a>
public void Run()
{
// 1. Initialize the new instance of the Categorical distribution class with parameters P = (0.1, 0.2, 0.25, 0.45)
var binomial = new Categorical(new[] { 0.1, 0.2, 0.25, 0.45 });
Console.WriteLine(@"1. Initialize the new instance of the Categorical distribution class with parameters P = (0.1, 0.2, 0.25, 0.45)");
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", binomial);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '3'", binomial.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability mass at location '3'", binomial.Probability(3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability mass at location '3'", binomial.ProbabilityLn(3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", binomial.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", binomial.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", binomial.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", binomial.Mean.ToString(" #0.00000;-#0.00000"));
// Median
Console.WriteLine(@"{0} - Median", binomial.Median.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", binomial.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", binomial.StdDev.ToString(" #0.00000;-#0.00000"));
// 3. Generate 10 samples of the Categorical distribution
Console.WriteLine(@"3. Generate 10 samples of the Categorical distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(binomial.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the Categorical(new []{ 0.1, 0.2, 0.25, 0.45 }) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the Categorical(0.2, 20) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = binomial.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the Categorical(new []{ 0.6, 0.2, 0.1, 0.1 }) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the Categorical(0.7, 20) distribution and display histogram");
binomial.P = new[] { 0.6, 0.2, 0.1, 0.1 };
for (var i = 0; i < data.Length; i++)
{
data[i] = binomial.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

139
src/Examples/DiscreteDistributions/ConwayMaxwellPoissonDistribution.cs

@ -0,0 +1,139 @@
// <copyright file="ConwayMaxwellPoissonDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.DiscreteDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// ConwayMaxwellPoisson distribution example
/// </summary>
public class ConwayMaxwellPoissonDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "ConwayMaxwellPoisson distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "ConwayMaxwellPoisson distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Conway%E2%80%93Maxwell%E2%80%93Poisson_distribution">ConwayMaxwellPoisson distribution</a>
public void Run()
{
// 1. Initialize the new instance of the ConwayMaxwellPoisson distribution class with parameters Lambda = 2, Nu = 1
var binomial = new ConwayMaxwellPoisson(2, 1);
Console.WriteLine(@"1. Initialize the new instance of the ConwayMaxwellPoisson distribution class with parameters Lambda = {0}, Nu = {1}", binomial.Lambda, binomial.Nu);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", binomial);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '3'", binomial.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability mass at location '3'", binomial.Probability(3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability mass at location '3'", binomial.ProbabilityLn(3).ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", binomial.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", binomial.Mean.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", binomial.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", binomial.StdDev.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the ConwayMaxwellPoisson distribution
Console.WriteLine(@"3. Generate 10 samples of the ConwayMaxwellPoisson distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(binomial.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the ConwayMaxwellPoisson(4, 1) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the ConwayMaxwellPoisson(4, 1) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = binomial.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the ConwayMaxwellPoisson(2, 1) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the ConwayMaxwellPoisson(2, 1) distribution and display histogram");
binomial.Lambda = 2;
for (var i = 0; i < data.Length; i++)
{
data[i] = binomial.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 6. Generate 100000 samples of the ConwayMaxwellPoisson(5, 2) distribution and display histogram
Console.WriteLine(@"6. Generate 100000 samples of the ConwayMaxwellPoisson(5, 2) distribution and display histogram");
binomial.Lambda = 5;
binomial.Nu = 2;
for (var i = 0; i < data.Length; i++)
{
data[i] = binomial.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

156
src/Examples/DiscreteDistributions/DiscreteUniformDistribution.cs

@ -0,0 +1,156 @@
// <copyright file="DiscreteUniformDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.DiscreteDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// DiscreteUniform distribution example
/// </summary>
public class DiscreteUniformDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/DiscreteUniformDistribution.html"/>
public string Name
{
get
{
return "DiscreteUniform distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "DiscreteUniform distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Discrete_uniform">DiscreteUniform distribution</a>
public void Run()
{
// 1. Initialize the new instance of the DiscreteUniform distribution class with parameters LowerBound = 2, UpperBound = 10
var discreteUniform = new DiscreteUniform(2, 10);
Console.WriteLine(@"1. Initialize the new instance of the DiscreteUniform distribution class with parameters LowerBound = {0}, UpperBound = {1}", discreteUniform.LowerBound, discreteUniform.UpperBound);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", discreteUniform);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '3'", discreteUniform.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability mass at location '3'", discreteUniform.Probability(3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability mass at location '3'", discreteUniform.ProbabilityLn(3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", discreteUniform.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", discreteUniform.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", discreteUniform.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", discreteUniform.Mean.ToString(" #0.00000;-#0.00000"));
// Median
Console.WriteLine(@"{0} - Median", discreteUniform.Median.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", discreteUniform.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", discreteUniform.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", discreteUniform.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", discreteUniform.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the DiscreteUniform distribution
Console.WriteLine(@"3. Generate 10 samples of the DiscreteUniform distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(discreteUniform.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the DiscreteUniform(2, 10) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the DiscreteUniform(2, 10) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = discreteUniform.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the DiscreteUniform(-10, 10) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the DiscreteUniform(-10, 10) distribution and display histogram");
discreteUniform.LowerBound = -10;
discreteUniform.UpperBound = 10;
for (var i = 0; i < data.Length; i++)
{
data[i] = discreteUniform.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 6. Generate 100000 samples of the DiscreteUniform(0, 40) distribution and display histogram
Console.WriteLine(@"6. Generate 100000 samples of the DiscreteUniform(0, 40) distribution and display histogram");
discreteUniform.LowerBound = 0;
discreteUniform.UpperBound = 40;
for (var i = 0; i < data.Length; i++)
{
data[i] = discreteUniform.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

154
src/Examples/DiscreteDistributions/GeometricDistribution.cs

@ -0,0 +1,154 @@
// <copyright file="GeometricDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.DiscreteDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// Geometric distribution example
/// </summary>
public class GeometricDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/GeometricDistribution.html"/>
public string Name
{
get
{
return "Geometric distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Geometric distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Geometric_distribution">Geometric distribution</a>
public void Run()
{
// 1. Initialize the new instance of the Geometric distribution class with parameter P = 0.2
var geometric = new Geometric(0.2);
Console.WriteLine(@"1. Initialize the new instance of the Geometric distribution class with parameter P = {0}", geometric.P);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", geometric);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '3'", geometric.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability mass at location '3'", geometric.Probability(3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability mass at location '3'", geometric.ProbabilityLn(3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", geometric.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", geometric.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", geometric.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", geometric.Mean.ToString(" #0.00000;-#0.00000"));
// Median
Console.WriteLine(@"{0} - Median", geometric.Median.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", geometric.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", geometric.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", geometric.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", geometric.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the Geometric distribution
Console.WriteLine(@"3. Generate 10 samples of the Geometric distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(geometric.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the Geometric(0.2, 20) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the Geometric(0.2, 20) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = geometric.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the Geometric(0.5) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the Geometric(0.5) distribution and display histogram");
geometric.P = 0.5;
for (var i = 0; i < data.Length; i++)
{
data[i] = geometric.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 6. Generate 100000 samples of the Geometric(0.8) distribution and display histogram
Console.WriteLine(@"6. Generate 100000 samples of the Geometric(0.8) distribution and display histogram");
geometric.P = 0.8;
for (var i = 0; i < data.Length; i++)
{
data[i] = geometric.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

139
src/Examples/DiscreteDistributions/HypergeometricDistribution.cs

@ -0,0 +1,139 @@
// <copyright file="HypergeometricDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.DiscreteDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// Hypergeometric distribution example
/// </summary>
public class HypergeometricDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/HypergeometricDistribution.html"/>
public string Name
{
get
{
return "Hypergeometric distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Hypergeometric distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Hypergeometric_distribution">Hypergeometric distribution</a>
public void Run()
{
// 1. Initialize the new instance of the Hypergeometric distribution class with parameters PopulationSize = 10, M = 2, N = 8
var hypergeometric = new Hypergeometric(30, 15, 10);
Console.WriteLine(@"1. Initialize the new instance of the Hypergeometric distribution class with parameters PopulationSize = {0}, M = {1}, N = {2}", hypergeometric.PopulationSize, hypergeometric.M, hypergeometric.N);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", hypergeometric);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '3'", hypergeometric.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability mass at location '3'", hypergeometric.Probability(3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability mass at location '3'", hypergeometric.ProbabilityLn(3).ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", hypergeometric.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", hypergeometric.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", hypergeometric.Mean.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", hypergeometric.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", hypergeometric.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", hypergeometric.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", hypergeometric.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the Hypergeometric distribution
Console.WriteLine(@"3. Generate 10 samples of the Hypergeometric distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(hypergeometric.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the Hypergeometric(30, 15, 10) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the Hypergeometric(30, 15, 10) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = hypergeometric.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the Hypergeometric(52, 13, 5) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the Hypergeometric(52, 13, 5) distribution and display histogram");
hypergeometric.PopulationSize = 52;
hypergeometric.M = 13;
hypergeometric.N = 5;
for (var i = 0; i < data.Length; i++)
{
data[i] = hypergeometric.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

149
src/Examples/DiscreteDistributions/NegativeBinomialDistribution.cs

@ -0,0 +1,149 @@
// <copyright file="NegativeBinomialDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.DiscreteDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// NegativeBinomial distribution example
/// </summary>
public class NegativeBinomialDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/NegativeBinomialDistribution.html"/>
public string Name
{
get
{
return "NegativeBinomial distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "NegativeBinomial distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Negative_binomial">NegativeBinomial distribution</a>
public void Run()
{
// 1. Initialize the new instance of the NegativeBinomial distribution class with parameters P = 0.2, R = 20
var negativeBinomial = new NegativeBinomial(20, 0.2);
Console.WriteLine(@"1. Initialize the new instance of the NegativeBinomial distribution class with parameters P = {0}, N = {1}", negativeBinomial.P, negativeBinomial.R);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", negativeBinomial);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '3'", negativeBinomial.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability mass at location '3'", negativeBinomial.Probability(3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability mass at location '3'", negativeBinomial.ProbabilityLn(3).ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", negativeBinomial.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", negativeBinomial.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", negativeBinomial.Mean.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", negativeBinomial.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", negativeBinomial.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", negativeBinomial.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", negativeBinomial.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the NegativeBinomial distribution
Console.WriteLine(@"3. Generate 10 samples of the NegativeBinomial distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(negativeBinomial.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the NegativeBinomial(0.2, 20) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the NegativeBinomial(0.2, 20) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = negativeBinomial.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the NegativeBinomial(0.7, 20) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the NegativeBinomial(0.7, 20) distribution and display histogram");
negativeBinomial.P = 0.7;
for (var i = 0; i < data.Length; i++)
{
data[i] = negativeBinomial.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 6. Generate 100000 samples of the NegativeBinomial(0.5, 1) distribution and display histogram
Console.WriteLine(@"6. Generate 100000 samples of the NegativeBinomial(0.5, 1) distribution and display histogram");
negativeBinomial.P = 0.5;
negativeBinomial.R = 1;
for (var i = 0; i < data.Length; i++)
{
data[i] = negativeBinomial.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

154
src/Examples/DiscreteDistributions/PoissonDistribution.cs

@ -0,0 +1,154 @@
// <copyright file="PoissonDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.DiscreteDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// Poisson distribution example
/// </summary>
public class PoissonDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/PoissonDistribution.html"/>
public string Name
{
get
{
return "Poisson distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Poisson distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Poisson_distribution">Poisson distribution</a>
public void Run()
{
// 1. Initialize the new instance of the Poisson distribution class with parameter Lambda = 1
var poisson = new Poisson(1);
Console.WriteLine(@"1. Initialize the new instance of the Poisson distribution class with parameter Lambda = {0}", poisson.Lambda);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", poisson);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '3'", poisson.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability mass at location '3'", poisson.Probability(3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability mass at location '3'", poisson.ProbabilityLn(3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", poisson.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", poisson.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", poisson.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", poisson.Mean.ToString(" #0.00000;-#0.00000"));
// Median
Console.WriteLine(@"{0} - Median", poisson.Median.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", poisson.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", poisson.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", poisson.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", poisson.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the Poisson distribution
Console.WriteLine(@"3. Generate 10 samples of the Poisson distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(poisson.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the Poisson(1) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the Poisson(1) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = poisson.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the Poisson(4) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the Poisson(4) distribution and display histogram");
poisson.Lambda = 4;
for (var i = 0; i < data.Length; i++)
{
data[i] = poisson.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 6. Generate 100000 samples of the Poisson(10) distribution and display histogram
Console.WriteLine(@"6. Generate 100000 samples of the Poisson(10) distribution and display histogram");
poisson.Lambda = 10;
for (var i = 0; i < data.Length; i++)
{
data[i] = poisson.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

152
src/Examples/DiscreteDistributions/ZipfDistribution.cs

@ -0,0 +1,152 @@
// <copyright file="ZipfDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.DiscreteDistributions
{
using System;
using MathNet.Numerics.Distributions;
/// <summary>
/// Zipf distribution example
/// </summary>
public class ZipfDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/ZipfDistribution.html"/>
public string Name
{
get
{
return "Zipf distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Zipf distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Zipf_distribution">Zipf distribution</a>
public void Run()
{
// 1. Initialize the new instance of the Zipf distribution class with parameters S = 5, N = 10
var zipf = new Zipf(5, 10);
Console.WriteLine(@"1. Initialize the new instance of the Zipf distribution class with parameters S = {0}, N = {1}", zipf.S, zipf.N);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", zipf);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '3'", zipf.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability mass at location '3'", zipf.Probability(3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability mass at location '3'", zipf.ProbabilityLn(3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", zipf.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", zipf.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", zipf.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", zipf.Mean.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", zipf.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", zipf.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", zipf.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", zipf.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the Zipf distribution
Console.WriteLine(@"3. Generate 10 samples of the Zipf distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(zipf.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the Zipf(5, 10) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the Zipf(5, 10) distribution and display histogram");
var data = new double[100000];
for (var i = 0; i < data.Length; i++)
{
data[i] = zipf.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the Zipf(2, 10) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the Zipf(2, 10) distribution and display histogram");
zipf.S = 2;
for (var i = 0; i < data.Length; i++)
{
data[i] = zipf.Sample();
}
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 6. Generate 100000 samples of the Zipf(5, 20) distribution and display histogram
Console.WriteLine(@"6. Generate 100000 samples of the Zipf(1, 20) distribution and display histogram");
zipf.S = 1;
zipf.N = 20;
for (var i = 0; i < data.Length; i++)
{
data[i] = zipf.Sample();
}
ConsoleHelper.DisplayHistogram(data);
}
}
}

52
src/Examples/Examples.csproj

@ -68,11 +68,51 @@
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="ConsoleHelper.cs" />
<Compile Include="ContinuousDistributions\CauchyDistribution.cs" />
<Compile Include="ContinuousDistributions\ChiDistribution.cs" />
<Compile Include="ContinuousDistributions\ChiSquareDistribution.cs" />
<Compile Include="ContinuousDistributions\ContinuousUniformDistribution.cs" />
<Compile Include="ContinuousDistributions\WeibullDistribution.cs" />
<Compile Include="ContinuousDistributions\StudentTDistribution.cs" />
<Compile Include="ContinuousDistributions\StableDistribution.cs" />
<Compile Include="ContinuousDistributions\RayleighDistribution.cs" />
<Compile Include="ContinuousDistributions\ParetoDistribution.cs" />
<Compile Include="ContinuousDistributions\NormalDistribution.cs" />
<Compile Include="ContinuousDistributions\LogNormalDistribution.cs" />
<Compile Include="ContinuousDistributions\LaplaceDistribution.cs" />
<Compile Include="ContinuousDistributions\InverseGammaDistribution.cs" />
<Compile Include="ContinuousDistributions\GammaDistribution.cs" />
<Compile Include="ContinuousDistributions\FisherSnedecorDistribution.cs" />
<Compile Include="ContinuousDistributions\ExponentialDistribution.cs" />
<Compile Include="ContinuousDistributions\ErlangDistribution.cs" />
<Compile Include="Statistics.cs" />
<Compile Include="NumberTheory.cs" />
<Compile Include="Interpolation\AkimaSpline.cs" />
<Compile Include="Interpolation\RationalWithPoles.cs" />
<Compile Include="Interpolation\LinearBetweenPoints.cs" />
<Compile Include="Interpolation\RationalWithoutPoles.cs" />
<Compile Include="DiscreteDistributions\BernoulliDistribution.cs" />
<Compile Include="DiscreteDistributions\BinomialDistribution.cs" />
<Compile Include="DiscreteDistributions\CategoricalDistribution.cs" />
<Compile Include="DiscreteDistributions\ConwayMaxwellPoissonDistribution.cs" />
<Compile Include="DiscreteDistributions\ZipfDistribution.cs" />
<Compile Include="DiscreteDistributions\PoissonDistribution.cs" />
<Compile Include="DiscreteDistributions\NegativeBinomialDistribution.cs" />
<Compile Include="DiscreteDistributions\HypergeometricDistribution.cs" />
<Compile Include="DiscreteDistributions\GeometricDistribution.cs" />
<Compile Include="DiscreteDistributions\DiscreteUniformDistribution.cs" />
<Compile Include="IExample.cs" /> <Compile Include="IExample.cs" />
<Compile Include="ContinuousDistributions\BetaDistribution.cs" />
<Compile Include="LinearAlgebra\DirectSolvers.cs" /> <Compile Include="LinearAlgebra\DirectSolvers.cs" />
<Compile Include="LinearAlgebra\Factorization\Cholesky.cs" /> <Compile Include="LinearAlgebra\Factorization\Cholesky.cs" />
<Compile Include="LinearAlgebra\Factorization\Evd.cs" /> <Compile Include="LinearAlgebra\Factorization\Evd.cs" />
<Compile Include="LinearAlgebra\Factorization\LU.cs" /> <Compile Include="LinearAlgebra\Factorization\LU.cs" />
<Compile Include="LinearAlgebra\IterativeSolvers\BiCgStabSolver.cs" />
<Compile Include="LinearAlgebra\IterativeSolvers\CompositeSolverExample.cs" />
<Compile Include="LinearAlgebra\IterativeSolvers\GpBiCgSolver.cs" />
<Compile Include="LinearAlgebra\IterativeSolvers\MlkBiCgStabSolver.cs" />
<Compile Include="LinearAlgebra\IterativeSolvers\TFQMRSolver.cs" />
<Compile Include="LinearAlgebra\MatrixNorms.cs" /> <Compile Include="LinearAlgebra\MatrixNorms.cs" />
<Compile Include="LinearAlgebra\Factorization\QR.cs" /> <Compile Include="LinearAlgebra\Factorization\QR.cs" />
<Compile Include="LinearAlgebra\Factorization\Svd.cs" /> <Compile Include="LinearAlgebra\Factorization\Svd.cs" />
@ -87,6 +127,17 @@
<Compile Include="LinearAlgebra\VectorDataAccessor.cs" /> <Compile Include="LinearAlgebra\VectorDataAccessor.cs" />
<Compile Include="LinearAlgebra\VectorInitialization.cs" /> <Compile Include="LinearAlgebra\VectorInitialization.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RandomNumberGeneration.cs" />
<Compile Include="Integration.cs" />
<Compile Include="Sampling\Chebyshev.cs" />
<Compile Include="Sampling\Random.cs" />
<Compile Include="Sampling\Equidistant.cs" />
<Compile Include="SpecialFunctions\Common.cs" />
<Compile Include="SpecialFunctions\Beta.cs" />
<Compile Include="SpecialFunctions\ErrorFunction.cs" />
<Compile Include="SpecialFunctions\Stability.cs" />
<Compile Include="SpecialFunctions\Factorial.cs" />
<Compile Include="SpecialFunctions\Gamma.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5"> <BootstrapperPackage Include="Microsoft.Net.Client.3.5">
@ -111,6 +162,7 @@
<Name>Numerics</Name> <Name>Numerics</Name>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets. Other similar extension points exist, see Microsoft.Common.targets.

105
src/Examples/Integration.cs

@ -0,0 +1,105 @@
// <copyright file="Integration.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples
{
using System;
using MathNet.Numerics.Integration;
/// <summary>
/// Numeric Integration (Quadrature)
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/Integrate.html"/>
public class Integration : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Numeric Integration";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Analytic integration of smooth functions with no discontinuitie or derivative discontinuities and no poles inside the interval";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Trapezoidal_rule">Trapezoidal rule</seealso>
public void Run()
{
// 1. Integrate x*x on interval [0, 10]
Console.WriteLine(@"1. Integrate x*x on interval [0, 10]");
var result = Integrate.OnClosedInterval(x => x * x, 0, 10);
Console.WriteLine(result);
Console.WriteLine();
// 2. Integrate 1/(x^3 + 1) on interval [0, 1]
Console.WriteLine(@"2. Integrate 1/(x^3 + 1) on interval [0, 1]");
result = Integrate.OnClosedInterval(x => 1 / (Math.Pow(x, 3) + 1), 0, 1);
Console.WriteLine(result);
Console.WriteLine();
// 3. Integrate f(x) = exp(-x/5) (2 + sin(2 * x)) on [0, 10]
Console.WriteLine(@"3. Integrate f(x) = exp(-x/5) (2 + sin(2 * x)) on [0, 10]");
result = Integrate.OnClosedInterval(x => Math.Exp(-x / 5) * (2 + Math.Sin(2 * x)), 0, 100);
Console.WriteLine(result);
Console.WriteLine();
// 4. Integrate target function with absolute error = 1E-4
Console.WriteLine(@"4. Integrate target function with absolute error = 1E-4 on [0, 10]");
Console.WriteLine(@"public static double TargetFunctionA(double x)
{
return Math.Exp(-x / 5) * (2 + Math.Sin(2 * x));
}");
result = Integrate.OnClosedInterval(TargetFunctionA, 0, 100, 1e-4);
Console.WriteLine(result);
Console.WriteLine();
}
/// <summary>
/// Test Function: f(x) = exp(-x/5) (2 + sin(2 * x))
/// </summary>
/// <param name="x">X parameter value</param>
/// <returns>Calculation result</returns>
public static double TargetFunctionA(double x)
{
return Math.Exp(-x / 5) * (2 + Math.Sin(2 * x));
}
}
}

119
src/Examples/Interpolation/AkimaSpline.cs

@ -0,0 +1,119 @@
// <copyright file="AkimaSpline.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.Interpolation
{
using System;
using MathNet.Numerics.Interpolation;
using MathNet.Numerics.Interpolation.Algorithms;
using MathNet.Numerics.Random;
using MathNet.Numerics.Sampling;
/// <summary>
/// Interpolation example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/Interpolation.html"/>
public class AkimaSpline : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Interpolation - Akima Spline";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Akima Spline Interpolation Algorithm";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Spline_interpolation">Spline interpolation</seealso>
public void Run()
{
// 1. Generate 10 samples of the function x*x-2*x on interval [0, 10]
Console.WriteLine(@"1. Generate 10 samples of the function x*x-2*x on interval [0, 10]");
double[] points;
var values = Sample.EquidistantInterval(TargetFunction, 0, 10, 10, out points);
Console.WriteLine();
// 2. Create akima spline interpolation
var method = new AkimaSplineInterpolation(points, values);
Console.WriteLine(@"2. Create akima spline interpolation based on arbitrary points");
Console.WriteLine();
// 3. Check if interpolation support integration
Console.WriteLine(@"3. Support integration = {0}", ((IInterpolation)method).SupportsIntegration);
Console.WriteLine();
// 4. Check if interpolation support differentiation
Console.WriteLine(@"4. Support differentiation = {0}", ((IInterpolation)method).SupportsDifferentiation);
Console.WriteLine();
// 5. Differentiate at point 5.2
Console.WriteLine(@"5. Differentiate at point 5.2 = {0}", method.Differentiate(5.2));
Console.WriteLine();
// 6. Integrate at point 5.2
Console.WriteLine(@"6. Integrate at point 5.2 = {0}", method.Integrate(5.2));
Console.WriteLine();
// 7. Interpolate ten random points and compare to function results
Console.WriteLine(@"7. 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, 10]
var point = rng.NextDouble() * 10;
Console.WriteLine(@"Interpolate at {0} = {1}. Function({0}) = {2}", point.ToString("N05"), method.Interpolate(point).ToString("N05"), TargetFunction(point).ToString("N05"));
}
Console.WriteLine();
}
/// <summary>
/// Test Function: f(x) = x * x - 2 * x
/// </summary>
/// <param name="x">X parameter value</param>
/// <returns>Calculation result</returns>
public static double TargetFunction(double x)
{
return (x * x) - (2 * x);
}
}
}

118
src/Examples/Interpolation/LinearBetweenPoints.cs

@ -0,0 +1,118 @@
// <copyright file="LinearBetweenPoints.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.Interpolation
{
using System;
using MathNet.Numerics.Interpolation;
using MathNet.Numerics.Random;
using MathNet.Numerics.Sampling;
/// <summary>
/// Interpolation example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/Interpolation.html"/>
public class LinearBetweenPoints : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Interpolation - Linear Between Points";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Linear Spline Interpolation Algorithm";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Spline_interpolation">Spline interpolation</seealso>
public void Run()
{
// 1. Generate 20 samples of the function x*x-2*x on interval [0, 10]
Console.WriteLine(@"1. Generate 20 samples of the function x*x-2*x on interval [0, 10]");
double[] points;
var values = Sample.EquidistantInterval(TargetFunction, 0, 10, 20, out points);
Console.WriteLine();
// 2. Create a linear spline interpolation based on arbitrary points
var method = Interpolate.LinearBetweenPoints(points, values);
Console.WriteLine(@"2. Create a linear spline interpolation based on arbitrary points");
Console.WriteLine();
// 3. Check if interpolation support integration
Console.WriteLine(@"3. Support integration = {0}", method.SupportsIntegration);
Console.WriteLine();
// 4. Check if interpolation support differentiation
Console.WriteLine(@"4. Support differentiation = {0}", method.SupportsDifferentiation);
Console.WriteLine();
// 5. Differentiate at point 5.2
Console.WriteLine(@"5. Differentiate at point 5.2 = {0}", method.Differentiate(5.2));
Console.WriteLine();
// 6. Integrate at point 5.2
Console.WriteLine(@"6. Integrate at point 5.2 = {0}", method.Integrate(5.2));
Console.WriteLine();
// 7. Interpolate ten random points and compare to function results
Console.WriteLine(@"7. 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, 10]
var point = rng.NextDouble() * 10;
Console.WriteLine(@"Interpolate at {0} = {1}. Function({0}) = {2}", point.ToString("N05"), method.Interpolate(point).ToString("N05"), TargetFunction(point).ToString("N05"));
}
Console.WriteLine();
}
/// <summary>
/// Test Function: f(x) = x * x - 2 * x
/// </summary>
/// <param name="x">X parameter value</param>
/// <returns>Calculation result</returns>
public static double TargetFunction(double x)
{
return (x * x) - (2 * x);
}
}
}

109
src/Examples/Interpolation/RationalWithPoles.cs

@ -0,0 +1,109 @@
// <copyright file="RationalWithPoles.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.Interpolation
{
using System;
using MathNet.Numerics.Interpolation;
using MathNet.Numerics.Random;
using MathNet.Numerics.Sampling;
/// <summary>
/// Interpolation example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/Interpolation.html"/>
public class RationalWithPoles : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Interpolation - Rational With Poles";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Rational Interpolation (with poles) using Roland Bulirsch and Josef Stoer's Algorithm";
}
}
/// <summary>
/// Run example
/// </summary>
public void Run()
{
// 1. Generate 20 samples of the function f(x) = x on interval [-5, 5]
Console.WriteLine(@"1. Generate 20 samples of the function f(x) = x on interval [-5, 5]");
double[] points;
var values = Sample.EquidistantInterval(TargetFunction, -5, 5, 20, out points);
Console.WriteLine();
// 2. Create a burlish stoer rational interpolation based on arbitrary points
var method = Interpolate.RationalWithPoles(points, values);
Console.WriteLine(@"2. Create a burlish stoer rational interpolation based on arbitrary points");
Console.WriteLine();
// 3. Check if interpolation support integration
Console.WriteLine(@"3. Support integration = {0}", method.SupportsIntegration);
Console.WriteLine();
// 4. Check if interpolation support differentiation
Console.WriteLine(@"4. Support differentiation = {0}", method.SupportsDifferentiation);
Console.WriteLine();
// 5. Interpolate ten random points and compare to function results
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.Next(0, 5);
Console.WriteLine(@"Interpolate at {0} = {1}. Function({0}) = {2}", point.ToString("N05"), method.Interpolate(point).ToString("N05"), TargetFunction(point).ToString("N05"));
}
Console.WriteLine();
}
/// <summary>
/// Test Function: f(x) = x * x + 10
/// </summary>
/// <param name="x">X parameter value</param>
/// <returns>Calculation result</returns>
public static double TargetFunction(double x)
{
return x;
}
}
}

111
src/Examples/Interpolation/RationalWithoutPoles.cs

@ -0,0 +1,111 @@
// <copyright file="RationalWithoutPoles.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.Interpolation
{
using System;
using MathNet.Numerics.Interpolation;
using MathNet.Numerics.Random;
using MathNet.Numerics.Sampling;
/// <summary>
/// Interpolation example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/Interpolation.html"/>
public class RationalWithoutPoles : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Interpolation - Rational Without Poles";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Barycentric Rational Interpolation without poles, using Mike Floater and Kai Hormann's Algorithm";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Interpolation">Interpolation</seealso>
public void Run()
{
// 1. Generate 10 samples of the function 1/(1+x*x) on interval [-5, 5]
Console.WriteLine(@"1. Generate 10 samples of the function 1/(1+x*x) on interval [-5, 5]");
double[] points;
var values = Sample.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. Check if interpolation support integration
Console.WriteLine(@"3. Support integration = {0}", method.SupportsIntegration);
Console.WriteLine();
// 4. Check if interpolation support differentiation
Console.WriteLine(@"4. Support differentiation = {0}", method.SupportsDifferentiation);
Console.WriteLine();
// 5. Interpolate ten random points and compare to function results
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.WriteLine();
}
/// <summary>
/// Test Function: f(x) = 1 / (1 + (x * x))
/// </summary>
/// <param name="x">X parameter value</param>
/// <returns>Calculation result</returns>
public static double TargetFunction(double x)
{
return 1 / (1 + (x * x));
}
}
}

141
src/Examples/LinearAlgebra/IterativeSolvers/BiCgStabSolver.cs

@ -0,0 +1,141 @@
// <copyright file="BiCgStabSolver.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.LinearAlgebra.IterativeSolvers
{
using System;
using System.Globalization;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Double.Solvers;
using MathNet.Numerics.LinearAlgebra.Double.Solvers.Iterative;
using MathNet.Numerics.LinearAlgebra.Double.Solvers.StopCriterium;
using MathNet.Numerics.LinearAlgebra.Generic.Solvers.StopCriterium;
/// <summary>
/// BiCGStab Iterative solver
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Biconjugate_gradient_stabilized_method"/>
public class BiCgStabSolver : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Bi-Conjugate Gradient Stabilized iterative solver";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Solve linear equation using Bi-Conjugate Gradient Stabilized (BiCGStab) solver";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Biconjugate_gradient_stabilized_method">Biconjugate gradient stabilized method</seealso>
public void Run()
{
// Format matrix output to console
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
// Solve next system of linear equations (Ax=b):
// 5*x + 2*y - 4*z = -7
// 3*x - 7*y + 6*z = 38
// 4*x + 1*y + 5*z = 43
// Create matrix "A" with coefficients
var matrixA = new DenseMatrix(new[,] { { 5.00, 2.00, -4.00 }, { 3.00, -7.00, 6.00 }, { 4.00, 1.00, 5.00 } });
Console.WriteLine(@"Matrix 'A' with coefficients");
Console.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Create vector "b" with the constant terms.
var vectorB = new DenseVector(new[] { -7.0, 38.0, 43.0 });
Console.WriteLine(@"Vector 'b' with the constant terms");
Console.WriteLine(vectorB.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Create stop criteriums to monitor an iterative calculation. There are next available stop criteriums:
// - DivergenceStopCriterium: monitors an iterative calculation for signs of divergence;
// - FailureStopCriterium: monitors residuals for NaN's;
// - IterationCountStopCriterium: monitors the numbers of iteration steps;
// - ResidualStopCriterium: monitors residuals if calculation is considered converged;
// Stop calculation if 1000 iterations reached during calculation
var iterationCountStopCriterium = new IterationCountStopCriterium(1000);
// Stop calculation if residuals are below 1E-10 --> the calculation is considered converged
var residualStopCriterium = new ResidualStopCriterium(1e-10);
// Create monitor with defined stop criteriums
var monitor = new Iterator(new IIterationStopCriterium<double>[] { iterationCountStopCriterium, residualStopCriterium });
// Create Bi-Conjugate Gradient Stabilized solver
var solver = new BiCgStab(monitor);
// 1. Solve the matrix equation
var resultX = solver.Solve(matrixA, vectorB);
Console.WriteLine(@"1. Solve the matrix equation");
Console.WriteLine();
// 2. Check solver status of the iterations.
// Solver has property IterationResult which contains the status of the iteration once the calculation is finished.
// Possible values are:
// - CalculationCancelled: calculation was cancelled by the user;
// - CalculationConverged: calculation has converged to the desired convergence levels;
// - CalculationDiverged: calculation diverged;
// - CalculationFailure: calculation has failed for some reason;
// - CalculationIndetermined: calculation is indetermined, not started or stopped;
// - CalculationRunning: calculation is running and no results are yet known;
// - CalculationStoppedWithoutConvergence: calculation has been stopped due to reaching the stopping limits, but that convergence was not achieved;
Console.WriteLine(@"2. Solver status of the iterations");
Console.WriteLine(solver.IterationResult);
Console.WriteLine();
// 3. Solution result vector of the matrix equation
Console.WriteLine(@"3. Solution result vector of the matrix equation");
Console.WriteLine(resultX.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 4. Verify result. Multiply coefficient matrix "A" by result vector "x"
var reconstructVecorB = matrixA * resultX;
Console.WriteLine(@"4. Multiply coefficient matrix 'A' by result vector 'x'");
Console.WriteLine(reconstructVecorB.ToString("#0.00\t", formatProvider));
Console.WriteLine();
}
}
}

208
src/Examples/LinearAlgebra/IterativeSolvers/CompositeSolverExample.cs

@ -0,0 +1,208 @@
// <copyright file="CompositeSolverExample.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.LinearAlgebra.IterativeSolvers
{
using System;
using System.Globalization;
using System.Reflection;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Double.Solvers;
using MathNet.Numerics.LinearAlgebra.Double.Solvers.Iterative;
using MathNet.Numerics.LinearAlgebra.Double.Solvers.StopCriterium;
using MathNet.Numerics.LinearAlgebra.Generic.Solvers;
using MathNet.Numerics.LinearAlgebra.Generic.Solvers.StopCriterium;
/// <summary>
/// Сomposite matrix solver
/// </summary>
public class CompositeSolverExample : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Composite matrix solver";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Solve linear equation using composite matrix solver. The actual solver is made by a sequence of matrix solvers";
}
}
/// <summary>
/// Run example
/// </summary>
public void Run()
{
// Format matrix output to console
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
// Solve next system of linear equations (Ax=b):
// 5*x + 2*y - 4*z = -7
// 3*x - 7*y + 6*z = 38
// 4*x + 1*y + 5*z = 43
// Create matrix "A" with coefficients
var matrixA = new DenseMatrix(new[,] { { 5.00, 2.00, -4.00 }, { 3.00, -7.00, 6.00 }, { 4.00, 1.00, 5.00 } });
Console.WriteLine(@"Matrix 'A' with coefficients");
Console.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Create vector "b" with the constant terms.
var vectorB = new DenseVector(new[] { -7.0, 38.0, 43.0 });
Console.WriteLine(@"Vector 'b' with the constant terms");
Console.WriteLine(vectorB.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Create stop criteriums to monitor an iterative calculation. There are next available stop criteriums:
// - DivergenceStopCriterium: monitors an iterative calculation for signs of divergence;
// - FailureStopCriterium: monitors residuals for NaN's;
// - IterationCountStopCriterium: monitors the numbers of iteration steps;
// - ResidualStopCriterium: monitors residuals if calculation is considered converged;
// Stop calculation if 1000 iterations reached during calculation
var iterationCountStopCriterium = new IterationCountStopCriterium(1000);
// Stop calculation if residuals are below 1E-10 --> the calculation is considered converged
var residualStopCriterium = new ResidualStopCriterium(1e-10);
// Create monitor with defined stop criteriums
var monitor = new Iterator(new IIterationStopCriterium<double>[] { iterationCountStopCriterium, residualStopCriterium });
// Load all suitable solvers from current assembly. Below in this example, there is user-defined solver
// "class UserBiCgStab : IIterativeSolverSetup<double>" which uses regular BiCgStab solver. But user may create any other solver
// and solver setup classes which implement IIterativeSolverSetup<T> and pass assembly to next function:
CompositeSolver.LoadSolverInformationFromAssembly(Assembly.GetExecutingAssembly());
// Create composite solver
var solver = new CompositeSolver(monitor);
// 1. Solve the matrix equation
var resultX = solver.Solve(matrixA, vectorB);
Console.WriteLine(@"1. Solve the matrix equation");
Console.WriteLine();
// 2. Check solver status of the iterations.
// Solver has property IterationResult which contains the status of the iteration once the calculation is finished.
// Possible values are:
// - CalculationCancelled: calculation was cancelled by the user;
// - CalculationConverged: calculation has converged to the desired convergence levels;
// - CalculationDiverged: calculation diverged;
// - CalculationFailure: calculation has failed for some reason;
// - CalculationIndetermined: calculation is indetermined, not started or stopped;
// - CalculationRunning: calculation is running and no results are yet known;
// - CalculationStoppedWithoutConvergence: calculation has been stopped due to reaching the stopping limits, but that convergence was not achieved;
Console.WriteLine(@"2. Solver status of the iterations");
Console.WriteLine(solver.IterationResult);
Console.WriteLine();
// 3. Solution result vector of the matrix equation
Console.WriteLine(@"3. Solution result vector of the matrix equation");
Console.WriteLine(resultX.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 4. Verify result. Multiply coefficient matrix "A" by result vector "x"
var reconstructVecorB = matrixA * resultX;
Console.WriteLine(@"4. Multiply coefficient matrix 'A' by result vector 'x'");
Console.WriteLine(reconstructVecorB.ToString("#0.00\t", formatProvider));
Console.WriteLine();
}
}
/// <summary>
/// Sample of user-defined solver setup
/// </summary>
public class UserBiCgStab : IIterativeSolverSetup<double>
{
/// <summary>
/// Gets the type of the solver that will be created by this setup object.
/// </summary>
public Type SolverType
{
get
{
return null;
}
}
/// <summary>
/// Gets type of preconditioner, if any, that will be created by this setup object.
/// </summary>
public Type PreconditionerType
{
get
{
return null;
}
}
/// <summary>
/// Creates a fully functional iterative solver with the default settings
/// given by this setup.
/// </summary>
/// <returns>A new <see cref="IIterativeSolver{T}"/>.</returns>
public IIterativeSolver<double> CreateNew()
{
return new BiCgStab();
}
/// <summary>
/// Gets the relative speed of the solver.
/// </summary>
/// <value>Returns a value between 0 and 1, inclusive.</value>
public double SolutionSpeed
{
get
{
return 0.99;
}
}
/// <summary>
/// Gets the relative reliability of the solver.
/// </summary>
/// <value>Returns a value between 0 and 1 inclusive.</value>
public double Reliability
{
get
{
return 0.99;
}
}
}
}

139
src/Examples/LinearAlgebra/IterativeSolvers/GpBiCgSolver.cs

@ -0,0 +1,139 @@
// <copyright file="GpBiCgSolver.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.LinearAlgebra.IterativeSolvers
{
using System;
using System.Globalization;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Double.Solvers;
using MathNet.Numerics.LinearAlgebra.Double.Solvers.Iterative;
using MathNet.Numerics.LinearAlgebra.Double.Solvers.StopCriterium;
using MathNet.Numerics.LinearAlgebra.Generic.Solvers.StopCriterium;
/// <summary>
/// GpBiCg Iterative solver
/// </summary>
public class GpBiCgSolver : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Generalized Product Bi-Conjugate Gradient iterative solver";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Solve linear equation using Generalized Product Bi-Conjugate Gradient (GPBiCG) solver";
}
}
/// <summary>
/// Run example
/// </summary>
public void Run()
{
// Format matrix output to console
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
// Solve next system of linear equations (Ax=b):
// 5*x + 2*y - 4*z = -7
// 3*x - 7*y + 6*z = 38
// 4*x + 1*y + 5*z = 43
// Create matrix "A" with coefficients
var matrixA = new DenseMatrix(new[,] { { 5.00, 2.00, -4.00 }, { 3.00, -7.00, 6.00 }, { 4.00, 1.00, 5.00 } });
Console.WriteLine(@"Matrix 'A' with coefficients");
Console.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Create vector "b" with the constant terms.
var vectorB = new DenseVector(new[] { -7.0, 38.0, 43.0 });
Console.WriteLine(@"Vector 'b' with the constant terms");
Console.WriteLine(vectorB.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Create stop criteriums to monitor an iterative calculation. There are next available stop criteriums:
// - DivergenceStopCriterium: monitors an iterative calculation for signs of divergence;
// - FailureStopCriterium: monitors residuals for NaN's;
// - IterationCountStopCriterium: monitors the numbers of iteration steps;
// - ResidualStopCriterium: monitors residuals if calculation is considered converged;
// Stop calculation if 1000 iterations reached during calculation
var iterationCountStopCriterium = new IterationCountStopCriterium(1000);
// Stop calculation if residuals are below 1E-10 --> the calculation is considered converged
var residualStopCriterium = new ResidualStopCriterium(1e-10);
// Create monitor with defined stop criteriums
var monitor = new Iterator(new IIterationStopCriterium<double>[] { iterationCountStopCriterium, residualStopCriterium });
// Create Generalized Product Bi-Conjugate Gradient solver
var solver = new GpBiCg(monitor);
// 1. Solve the matrix equation
var resultX = solver.Solve(matrixA, vectorB);
Console.WriteLine(@"1. Solve the matrix equation");
Console.WriteLine();
// 2. Check solver status of the iterations.
// Solver has property IterationResult which contains the status of the iteration once the calculation is finished.
// Possible values are:
// - CalculationCancelled: calculation was cancelled by the user;
// - CalculationConverged: calculation has converged to the desired convergence levels;
// - CalculationDiverged: calculation diverged;
// - CalculationFailure: calculation has failed for some reason;
// - CalculationIndetermined: calculation is indetermined, not started or stopped;
// - CalculationRunning: calculation is running and no results are yet known;
// - CalculationStoppedWithoutConvergence: calculation has been stopped due to reaching the stopping limits, but that convergence was not achieved;
Console.WriteLine(@"2. Solver status of the iterations");
Console.WriteLine(solver.IterationResult);
Console.WriteLine();
// 3. Solution result vector of the matrix equation
Console.WriteLine(@"3. Solution result vector of the matrix equation");
Console.WriteLine(resultX.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 4. Verify result. Multiply coefficient matrix "A" by result vector "x"
var reconstructVecorB = matrixA * resultX;
Console.WriteLine(@"4. Multiply coefficient matrix 'A' by result vector 'x'");
Console.WriteLine(reconstructVecorB.ToString("#0.00\t", formatProvider));
Console.WriteLine();
}
}
}

140
src/Examples/LinearAlgebra/IterativeSolvers/MlkBiCgStabSolver.cs

@ -0,0 +1,140 @@
// <copyright file="MlkBiCgStabSolver.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.LinearAlgebra.IterativeSolvers
{
using System;
using System.Globalization;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Double.Solvers;
using MathNet.Numerics.LinearAlgebra.Double.Solvers.Iterative;
using MathNet.Numerics.LinearAlgebra.Double.Solvers.StopCriterium;
using MathNet.Numerics.LinearAlgebra.Generic.Solvers.StopCriterium;
/// <summary>
/// Multiple-Lanczos Bi-Conjugate Gradient stabilized Iterative solver
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Derivation_of_the_conjugate_gradient_method#Derivation_from_the_Arnoldi.2FLanczos_iteration"/>
public class MlkBiCgStabSolver : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Multiple-Lanczos Bi-Conjugate Gradient Stabilized iterative solver";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Solve linear equation using Multiple-Lanczos Bi-Conjugate Gradient stabilized (ML(k)-BiCGStab) solver";
}
}
/// <summary>
/// Run example
/// </summary>
public void Run()
{
// Format matrix output to console
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
// Solve next system of linear equations (Ax=b):
// 5*x + 2*y - 4*z = -7
// 3*x - 7*y + 6*z = 38
// 4*x + 1*y + 5*z = 43
// Create matrix "A" with coefficients
var matrixA = new DenseMatrix(new[,] { { 5.00, 2.00, -4.00 }, { 3.00, -7.00, 6.00 }, { 4.00, 1.00, 5.00 } });
Console.WriteLine(@"Matrix 'A' with coefficients");
Console.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Create vector "b" with the constant terms.
var vectorB = new DenseVector(new[] { -7.0, 38.0, 43.0 });
Console.WriteLine(@"Vector 'b' with the constant terms");
Console.WriteLine(vectorB.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Create stop criteriums to monitor an iterative calculation. There are next available stop criteriums:
// - DivergenceStopCriterium: monitors an iterative calculation for signs of divergence;
// - FailureStopCriterium: monitors residuals for NaN's;
// - IterationCountStopCriterium: monitors the numbers of iteration steps;
// - ResidualStopCriterium: monitors residuals if calculation is considered converged;
// Stop calculation if 1000 iterations reached during calculation
var iterationCountStopCriterium = new IterationCountStopCriterium(1000);
// Stop calculation if residuals are below 1E-10 --> the calculation is considered converged
var residualStopCriterium = new ResidualStopCriterium(1e-10);
// Create monitor with defined stop criteriums
var monitor = new Iterator(new IIterationStopCriterium<double>[] { iterationCountStopCriterium, residualStopCriterium });
// Create Multiple-Lanczos Bi-Conjugate Gradient Stabilized solver
var solver = new MlkBiCgStab(monitor);
// 1. Solve the matrix equation
var resultX = solver.Solve(matrixA, vectorB);
Console.WriteLine(@"1. Solve the matrix equation");
Console.WriteLine();
// 2. Check solver status of the iterations.
// Solver has property IterationResult which contains the status of the iteration once the calculation is finished.
// Possible values are:
// - CalculationCancelled: calculation was cancelled by the user;
// - CalculationConverged: calculation has converged to the desired convergence levels;
// - CalculationDiverged: calculation diverged;
// - CalculationFailure: calculation has failed for some reason;
// - CalculationIndetermined: calculation is indetermined, not started or stopped;
// - CalculationRunning: calculation is running and no results are yet known;
// - CalculationStoppedWithoutConvergence: calculation has been stopped due to reaching the stopping limits, but that convergence was not achieved;
Console.WriteLine(@"2. Solver status of the iterations");
Console.WriteLine(solver.IterationResult);
Console.WriteLine();
// 3. Solution result vector of the matrix equation
Console.WriteLine(@"3. Solution result vector of the matrix equation");
Console.WriteLine(resultX.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 4. Verify result. Multiply coefficient matrix "A" by result vector "x"
var reconstructVecorB = matrixA * resultX;
Console.WriteLine(@"4. Multiply coefficient matrix 'A' by result vector 'x'");
Console.WriteLine(reconstructVecorB.ToString("#0.00\t", formatProvider));
Console.WriteLine();
}
}
}

140
src/Examples/LinearAlgebra/IterativeSolvers/TFQMRSolver.cs

@ -0,0 +1,140 @@
// <copyright file="TFQMRSolver.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.LinearAlgebra.IterativeSolvers
{
using System;
using System.Globalization;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Double.Solvers;
using MathNet.Numerics.LinearAlgebra.Double.Solvers.Iterative;
using MathNet.Numerics.LinearAlgebra.Double.Solvers.StopCriterium;
using MathNet.Numerics.LinearAlgebra.Generic.Solvers.StopCriterium;
/// <summary>
/// Transpose Free Quasi-Minimal Residual iterative solver
/// </summary>
/// <seealso cref="http://es.wikipedia.org/wiki/Algoritmo_TFQMR"/>
public class TFQMRSolver : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Transpose Free Quasi-Minimal Residual iterative solver";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Solve linear equation using Transpose Free Quasi-Minimal Residual (TFQMR) iterative solver";
}
}
/// <summary>
/// Run example
/// </summary>
public void Run()
{
// Format matrix output to console
var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
formatProvider.TextInfo.ListSeparator = " ";
// Solve next system of linear equations (Ax=b):
// 5*x + 2*y - 4*z = -7
// 3*x - 7*y + 6*z = 38
// 4*x + 1*y + 5*z = 43
// Create matrix "A" with coefficients
var matrixA = new DenseMatrix(new[,] { { 5.00, 2.00, -4.00 }, { 3.00, -7.00, 6.00 }, { 4.00, 1.00, 5.00 } });
Console.WriteLine(@"Matrix 'A' with coefficients");
Console.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Create vector "b" with the constant terms.
var vectorB = new DenseVector(new[] { -7.0, 38.0, 43.0 });
Console.WriteLine(@"Vector 'b' with the constant terms");
Console.WriteLine(vectorB.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// Create stop criteriums to monitor an iterative calculation. There are next available stop criteriums:
// - DivergenceStopCriterium: monitors an iterative calculation for signs of divergence;
// - FailureStopCriterium: monitors residuals for NaN's;
// - IterationCountStopCriterium: monitors the numbers of iteration steps;
// - ResidualStopCriterium: monitors residuals if calculation is considered converged;
// Stop calculation if 1000 iterations reached during calculation
var iterationCountStopCriterium = new IterationCountStopCriterium(1000);
// Stop calculation if residuals are below 1E-10 --> the calculation is considered converged
var residualStopCriterium = new ResidualStopCriterium(1e-10);
// Create monitor with defined stop criteriums
var monitor = new Iterator(new IIterationStopCriterium<double>[] { iterationCountStopCriterium, residualStopCriterium });
// Create Transpose Free Quasi-Minimal Residual solver
var solver = new TFQMR(monitor);
// 1. Solve the matrix equation
var resultX = solver.Solve(matrixA, vectorB);
Console.WriteLine(@"1. Solve the matrix equation");
Console.WriteLine();
// 2. Check solver status of the iterations.
// Solver has property IterationResult which contains the status of the iteration once the calculation is finished.
// Possible values are:
// - CalculationCancelled: calculation was cancelled by the user;
// - CalculationConverged: calculation has converged to the desired convergence levels;
// - CalculationDiverged: calculation diverged;
// - CalculationFailure: calculation has failed for some reason;
// - CalculationIndetermined: calculation is indetermined, not started or stopped;
// - CalculationRunning: calculation is running and no results are yet known;
// - CalculationStoppedWithoutConvergence: calculation has been stopped due to reaching the stopping limits, but that convergence was not achieved;
Console.WriteLine(@"2. Solver status of the iterations");
Console.WriteLine(solver.IterationResult);
Console.WriteLine();
// 3. Solution result vector of the matrix equation
Console.WriteLine(@"3. Solution result vector of the matrix equation");
Console.WriteLine(resultX.ToString("#0.00\t", formatProvider));
Console.WriteLine();
// 4. Verify result. Multiply coefficient matrix "A" by result vector "x"
var reconstructVecorB = matrixA * resultX;
Console.WriteLine(@"4. Multiply coefficient matrix 'A' by result vector 'x'");
Console.WriteLine(reconstructVecorB.ToString("#0.00\t", formatProvider));
Console.WriteLine();
}
}
}

117
src/Examples/NumberTheory.cs

@ -0,0 +1,117 @@
// <copyright file="NumberTheory.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples
{
using System;
using MathNet.Numerics.NumberTheory;
/// <summary>
/// Number theory utility functions
/// </summary>
public class NumberTheory : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Number theory utility functions";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Usage of the number theory utility functions and extention methods";
}
}
/// <summary>
/// Run example
/// </summary>
public void Run()
{
// 1. Find out whether the provided number is an even number
Console.WriteLine(@"1. Find out whether the provided number is an even number");
Console.WriteLine(@"{0} is even = {1}. {2} is even = {3}", 1, IntegerTheory.IsEven(1), 2, 2.IsEven());
Console.WriteLine();
// 2. Find out whether the provided number is an odd number
Console.WriteLine(@"2. Find out whether the provided number is an odd number");
Console.WriteLine(@"{0} is odd = {1}. {2} is odd = {3}", 1, 1.IsOdd(), 2, IntegerTheory.IsOdd(2));
Console.WriteLine();
// 3. Find out whether the provided number is a perfect power of two
Console.WriteLine(@"2. Find out whether the provided number is a perfect power of two");
Console.WriteLine(@"{0} is power of two = {1}. {2} is power of two = {3}", 5, 5.IsPowerOfTwo(), 16, IntegerTheory.IsPowerOfTwo(16));
Console.WriteLine();
// 4. Find the closest perfect power of two that is larger or equal to 97
Console.WriteLine(@"4. Find the closest perfect power of two that is larger or equal to 97");
Console.WriteLine(97.CeilingToPowerOfTwo());
Console.WriteLine();
// 5. Raise 2 to the 16
Console.WriteLine(@"5. Raise 2 to the 16");
Console.WriteLine(16.PowerOfTwo());
Console.WriteLine();
// 6. Find out whether the number is a perfect square
Console.WriteLine(@"6. Find out whether the number is a perfect square");
Console.WriteLine(@"{0} is perfect square = {1}. {2} is perfect square = {3}", 37, 37.IsPerfectSquare(), 81, IntegerTheory.IsPerfectSquare(81));
Console.WriteLine();
// 7. Compute the greatest common divisor of 32 and 36
Console.WriteLine(@"7. Returns the greatest common divisor of 32 and 36");
Console.WriteLine(IntegerTheory.GreatestCommonDivisor(32, 36));
Console.WriteLine();
// 8. Compute the greatest common divisor of 492, -984, 123, 246
Console.WriteLine(@"8. Returns the greatest common divisor of 492, -984, 123, 246");
Console.WriteLine(IntegerTheory.GreatestCommonDivisor(492, -984, 123, 246));
Console.WriteLine();
// 9. Compute the extended greatest common divisor "z", such that 45*x + 18*y = z
Console.WriteLine(@"9. Compute the extended greatest common divisor Z, such that 45*x + 18*y = Z");
long x, y;
var z = IntegerTheory.ExtendedGreatestCommonDivisor(45, 18, out x, out y);
Console.WriteLine(@"z = {0}, x = {1}, y = {2}. 45*{1} + 18*{2} = {0}", z, x, y);
Console.WriteLine();
// 10. Compute the least common multiple of 16 and 12
Console.WriteLine(@"10. Compute the least common multiple of 16 and 12");
Console.WriteLine(IntegerTheory.LeastCommonMultiple(16, 12));
Console.WriteLine();
}
}
}

191
src/Examples/RandomNumberGeneration.cs

@ -0,0 +1,191 @@
// <copyright file="RandomNumberGeneration.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples
{
using System;
using MathNet.Numerics.Random;
/// <summary>
/// Random number generation
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/tutorial/RandomNumberGeneration.html">Random number generation</seealso>
public class RandomNumberGeneration : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Random number generation";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Usage examples of random number generators (RNG)";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Random_number_generation">Random number generation</seealso>
/// <seealso cref="http://en.wikipedia.org/wiki/Linear_congruential_generator">Linear congruential generator</seealso>
/// <seealso cref="http://en.wikipedia.org/wiki/Mersenne_twister">Mersenne twister</seealso>
/// <seealso cref="http://en.wikipedia.org/wiki/Lagged_Fibonacci_generator">Lagged Fibonacci generator</seealso>
/// <seealso cref="http://en.wikipedia.org/wiki/Xorshift">Xorshift</seealso>
public void Run()
{
// All RNG classes in MathNet have next counstructors:
// - RNG(int seed, bool threadSafe): initializes a new instance with specific seed value and thread safe property
// - RNG(int seed): iуууnitializes a new instance with specific seed value. Thread safe property is set to Control.ThreadSafeRandomNumberGenerators
// - RNG(bool threadSafe) : initializes a new instance with the seed value set to DateTime.Now.Ticks and specific thread safe property
// - RNG(bool threadSafe) : initializes a new instance with the seed value set to DateTime.Now.Ticks and thread safe property set to Control.ThreadSafeRandomNumberGenerators
// All RNG classes in MathNet have next methods to produce random values:
// - double[] NextDouble(int n): returns an "n"-size array of uniformly distributed random doubles in the interval [0.0,1.0];
// - int Next(): returns a nonnegative random number;
// - int Next(int maxValue): returns a random number less then a specified maximum;
// - int Next(int minValue, int maxValue): returns a random number within a specified range;
// - void NextBytes(byte[] buffer): fills the elements of a specified array of bytes with random numbers;
// All RNG classes in MathNet have next extension methods to produce random values:
// - long NextInt64(): returns a nonnegative random number less than "Int64.MaxValue";
// - int NextFullRangeInt32(): returns a random number of the full Int32 range;
// - long NextFullRangeInt64(): returns a random number of the full Int64 range;
// - decimal NextDecimal(): returns a nonnegative decimal floating point random number less than 1.0;
// 1. Multiplicative congruential generator using a modulus of 2^31-1 and a multiplier of 1132489760
var mcg31M1 = new Mcg31m1(1);
Console.WriteLine(@"1. Generate 10 random double values using Multiplicative congruential generator with a modulus of 2^31-1 and a multiplier of 1132489760");
var randomValues = mcg31M1.NextDouble(10);
for (var i = 0; i < randomValues.Length; i++)
{
Console.Write(randomValues[i].ToString("N") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 2. Multiplicative congruential generator using a modulus of 2^59 and a multiplier of 13^13
var mcg59 = new Mcg59(1);
Console.WriteLine(@"2. Generate 10 random integer values using Multiplicative congruential generator with a modulus of 2^59 and a multiplier of 13^13");
for (var i = 0; i < 10; i++)
{
Console.Write(mcg59.Next() + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 3. Random number generator using Mersenne Twister 19937 algorithm
var mersenneTwister = new MersenneTwister(1);
Console.WriteLine(@"3. Generate 10 random integer values less then 100 using Mersenne Twister 19937 algorithm");
for (var i = 0; i < 10; i++)
{
Console.Write(mersenneTwister.Next(100) + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Multiple recursive generator with 2 components of order 3
var mrg32K3A = new Mrg32k3a(1);
Console.WriteLine(@"4. Generate 10 random integer values in range [50;100] using multiple recursive generator with 2 components of order 3");
for (var i = 0; i < 10; i++)
{
Console.Write(mrg32K3A.Next(50, 100) + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 5. Parallel Additive Lagged Fibonacci pseudo-random number generator
var palf = new Palf(1);
Console.WriteLine(@"5. Generate 10 random bytes using Parallel Additive Lagged Fibonacci pseudo-random number generator");
var bytes = new byte[10];
palf.NextBytes(bytes);
for (var i = 0; i < bytes.Length; i++)
{
Console.Write(bytes[i] + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 6. A random number generator based on the "System.Security.Cryptography.RandomNumberGenerator" class in the .NET library
var systemCryptoRandomNumberGenerator = new SystemCryptoRandomNumberGenerator();
Console.WriteLine(@"6. Generate 10 random decimal values using RNG based on the 'System.Security.Cryptography.RandomNumberGenerator'");
for (var i = 0; i < 10; i++)
{
Console.Write(systemCryptoRandomNumberGenerator.NextDecimal().ToString("N") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 7. Wichmann-Hill’s 1982 combined multiplicative congruential generator
var rngWh1982 = new WH1982();
Console.WriteLine(@"7. Generate 10 random full Int32 range values using Wichmann-Hill’s 1982 combined multiplicative congruential generator");
for (var i = 0; i < 10; i++)
{
Console.Write(rngWh1982.NextFullRangeInt32() + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 8. Wichmann-Hill’s 2006 combined multiplicative congruential generator.
var rngWh2006 = new WH2006();
Console.WriteLine(@"8. Generate 10 random full Int64 range values using Wichmann-Hill’s 2006 combined multiplicative congruential generator");
for (var i = 0; i < 10; i++)
{
Console.Write(rngWh2006.NextFullRangeInt32() + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 9. Multiply-with-carry Xorshift pseudo random number generator
var xorshift = new Xorshift();
Console.WriteLine(@"9. Generate 10 random nonnegative values less than Int64.MaxValue using Multiply-with-carry Xorshift pseudo random number generator");
for (var i = 0; i < 10; i++)
{
Console.Write(xorshift.NextInt64() + @" ");
}
Console.WriteLine();
}
}
}

96
src/Examples/Sampling/Chebyshev.cs

@ -0,0 +1,96 @@
// <copyright file="Chebyshev.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.Sampling
{
using System;
using MathNet.Numerics.Sampling;
/// <summary>
/// Example of generic function sampling and quantization provider
/// </summary>
public class Chebyshev : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Sampling - Chebyshev";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Samples a function at the roots of the Chebyshev polynomial";
}
}
/// <summary>
/// Run example
/// </summary>
public void Run()
{
// 1. Get 20 samples of f(x) = (x * x) / 2 at the roots of the Chebyshev polynomial of the first kind within interval [0, 10]
var result = Sample.ChebyshevNodesFirstKind(Function, 0, 10, 20);
Console.WriteLine(@"1. Get 20 samples of f(x) = (x * x) / 2 at the roots of the Chebyshev polynomial of the first kind within interval [0, 10]");
for (var i = 0; i < result.Length; i++)
{
Console.Write(result[i].ToString("N") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 2. Get 20 samples of f(x) = (x * x) / 2 at the roots of the Chebyshev polynomial of the second kind within interval [0, 10]
result = Sample.ChebyshevNodesSecondKind(Function, 0, 10, 20);
Console.WriteLine(@"2. Get 20 samples of f(x) = (x * x) / 2 at the roots of the Chebyshev polynomial of the second kind within interval [0, 10]");
for (var i = 0; i < result.Length; i++)
{
Console.Write(result[i].ToString("N") + @" ");
}
Console.WriteLine();
}
/// <summary>
/// Fucntion f(x) = (x * x) / 2
/// </summary>
/// <param name="x">Input value</param>
/// <returns>Calculation result</returns>
public double Function(double x)
{
return Math.Pow(x, 2) / 2;
}
}
}

127
src/Examples/Sampling/Equidistant.cs

@ -0,0 +1,127 @@
// <copyright file="Equidistant.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.Sampling
{
using System;
using MathNet.Numerics.Sampling;
/// <summary>
/// Example of generic function sampling and quantization provider
/// </summary>
public class Equidistant : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Sampling - Equidistant";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Samples a function equidistant";
}
}
/// <summary>
/// Run example
/// </summary>
public void Run()
{
// 1. Get 11 samples of f(x) = (x * x) / 2 equidistant within interval [-5, 5]
var result = Sample.EquidistantInterval(Function, -5, 5, 11);
Console.WriteLine(@"1. Get 11 samples of f(x) = (x * x) / 2 equidistant within interval [-5, 5]");
for (var i = 0; i < result.Length; i++)
{
Console.Write(result[i].ToString("N") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 2. Get 10 samples of f(x) = (x * x) / 2 equidistant starting at x=1 with step = 0.5 and retrieve sample points
double[] samplePoints;
result = Sample.EquidistantStartingAt(Function, 1, 0.5, 10, out samplePoints);
Console.WriteLine(@"2. Get 10 samples of f(x) = (x * x) / 2 equidistant starting at x=1 with step = 0.5 and retrieve sample points");
Console.Write(@"Points: ");
for (var i = 0; i < samplePoints.Length; i++)
{
Console.Write(samplePoints[i].ToString("N") + @" ");
}
Console.WriteLine();
Console.Write(@"Values: ");
for (var i = 0; i < result.Length; i++)
{
Console.Write(result[i].ToString("N") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 3. Get 10 samples of f(x) = (x * x) / 2 equidistant within period = 10 and period offset = 5
result = Sample.EquidistantPeriodic(Function, 10, 5, 10);
Console.WriteLine(@"3. Get 10 samples of f(x) = (x * x) / 2 equidistant within period = 10 and period offset = 5");
for (var i = 0; i < result.Length; i++)
{
Console.Write(result[i].ToString("N") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Sample f(x) = (x * x) / 2 equidistant to an integer-domain function starting at x = 0 and step = 2
var equidistant = Sample.EquidistantToFunction(Function, 0, 2);
Console.WriteLine(@" 4. Sample f(x) = (x * x) / 2 equidistant to an integer-domain function starting at x = 0 and step = 2");
for (var i = 0; i < 10; i++)
{
Console.Write(equidistant(i).ToString("N") + @" ");
}
Console.WriteLine();
}
/// <summary>
/// Fucntion f(x) = (x * x) / 2
/// </summary>
/// <param name="x">Input value</param>
/// <returns>Calculation result</returns>
public double Function(double x)
{
return Math.Pow(x, 2) / 2;
}
}
}

131
src/Examples/Sampling/Random.cs

@ -0,0 +1,131 @@
// <copyright file="Random.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.Sampling
{
using System;
using MathNet.Numerics.Distributions;
using MathNet.Numerics.Sampling;
/// <summary>
/// Example of generic function sampling and quantization provider
/// </summary>
public class Random : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Sampling - Random";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Samples a function randomly with the provided distribution";
}
}
/// <summary>
/// Run example
/// </summary>
public void Run()
{
// 1. Get 10 random samples of f(x) = (x * x) / 2 using continuous uniform distribution on [-10, 10]
var uniform = new ContinuousUniform(-10, 10);
var result = Sample.Random(Function, uniform, 10);
Console.WriteLine(@" 1. Get 10 random samples of f(x) = (x * x) / 2 using continuous uniform distribution on [-10, 10]");
for (var i = 0; i < result.Length; i++)
{
Console.Write(result[i].ToString("N") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 2. Get 10 random samples of f(x) = (x * x) / 2 using Exponential(1) distribution and retrieve sample points
var exponential = new Exponential(1);
double[] samplePoints;
result = Sample.Random(Function, exponential, 10, out samplePoints);
Console.WriteLine(@"2. Get 10 random samples of f(x) = (x * x) / 2 using Exponential(1) distribution and retrieve sample points");
Console.Write(@"Points: ");
for (var i = 0; i < samplePoints.Length; i++)
{
Console.Write(samplePoints[i].ToString("N") + @" ");
}
Console.WriteLine();
Console.Write(@"Values: ");
for (var i = 0; i < result.Length; i++)
{
Console.Write(result[i].ToString("N") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 3. Get 10 random samples of f(x, y) = (x * y) / 2 using ChiSquare(10) distribution
var chiSquare = new ChiSquare(10);
result = Sample.Random(TwoDomainFunction, chiSquare, 10);
Console.WriteLine(@" 3. Get 10 random samples of f(x, y) = (x * y) / 2 using ChiSquare(10) distribution");
for (var i = 0; i < result.Length; i++)
{
Console.Write(result[i].ToString("N") + @" ");
}
Console.WriteLine();
}
/// <summary>
/// Fucntion f(x, y) = (x * y) / 2
/// </summary>
/// <param name="x">Input value</param>
/// <returns>Calculation result</returns>
public double Function(double x)
{
return Math.Pow(x, 2) / 2;
}
/// <summary>
/// Fucntion f(x,y) = (x * y) / 2
/// </summary>
/// <param name="x">X input value</param>
/// <param name="y">Y input value</param>
/// <returns>Calculation result</returns>
public double TwoDomainFunction(double x, double y)
{
return (x * y) / 2;
}
}
}

96
src/Examples/SpecialFunctions/Beta.cs

@ -0,0 +1,96 @@
// <copyright file="Beta.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.SpecialFunctions
{
using System;
using MathNet.Numerics;
/// <summary>
/// Special Functions: Beta
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/Beta.html"/>
public class Beta : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Special Functions: Beta";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Beta, incomplete Beta, regularized Beta";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Beta_function">Beta function</seealso>
public void Run()
{
// 1. Compute the Beta function at z = 1.0, w = 3.0
Console.WriteLine(@"1. Compute the Beta function at z = 1.0, w = 3.0");
Console.WriteLine(SpecialFunctions.Beta(1.0, 3.0));
Console.WriteLine();
// 2. Compute the logarithm of the Beta function at z = 1.0, w = 3.0
Console.WriteLine(@"2. Compute the logarithm of the Beta function at z = 1.0, w = 3.0");
Console.WriteLine(SpecialFunctions.BetaLn(1.0, 3.0));
Console.WriteLine();
// 3. Compute the Beta incomplete function at z = 1.0, w = 3.0, x = 0.7
Console.WriteLine(@"3. Compute the Beta incomplete function at z = 1.0, w = 3.0, x = 0.7");
Console.WriteLine(SpecialFunctions.BetaIncomplete(1.0, 3.0, 0.7));
Console.WriteLine();
// 4. Compute the Beta incomplete function at z = 1.0, w = 3.0, x = 1.0
Console.WriteLine(@"4. Compute the Beta incomplete function at z = 1.0, w = 3.0, x = 1.0");
Console.WriteLine(SpecialFunctions.BetaIncomplete(1.0, 3.0, 1.0));
Console.WriteLine();
// 5. Compute the Beta regularized function at z = 1.0, w = 3.0, x = 0.7
Console.WriteLine(@"5. Compute the Beta regularized function at z = 1.0, w = 3.0, x = 0.7");
Console.WriteLine(SpecialFunctions.BetaRegularized(1.0, 3.0, 0.7));
Console.WriteLine();
// 6. Compute the Beta regularized function at z = 1.0, w = 3.0, x = 1.0
Console.WriteLine(@"6. Compute the Beta regularized function at z = 1.0, w = 3.0, x = 1.0");
Console.WriteLine(SpecialFunctions.BetaRegularized(1.0, 3.0, 1.0));
Console.WriteLine();
}
}
}

101
src/Examples/SpecialFunctions/Common.cs

@ -0,0 +1,101 @@
// <copyright file="Common.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.SpecialFunctions
{
using System;
using MathNet.Numerics;
/// <summary>
/// Special Functions
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/PolyGamma.html"/>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/HarmonicNumber.html"/>
public class Common : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Special Functions";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Harmonic, DiGamma, Logit, Logistic";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Digamma_function">Digamma function</seealso>
/// <seealso cref="http://en.wikipedia.org/wiki/Harmonic_number">Harmonic number</seealso>
/// <seealso cref="http://en.wikipedia.org/wiki/Harmonic_number#Generalized_harmonic_numbers">Generalized harmonic numbers</seealso>
/// <seealso cref="http://en.wikipedia.org/wiki/Logistic_function">Logistic function</seealso>
/// <seealso cref="http://en.wikipedia.org/wiki/Logit">Logit function</seealso>
public void Run()
{
// 1. Calculate the Digamma function at point 5.0
Console.WriteLine(@"1. Calculate the Digamma function at point 5.0");
Console.WriteLine(SpecialFunctions.DiGamma(5.0));
Console.WriteLine();
// 2. Calculate the inverse Digamma function at point 1.5
Console.WriteLine(@"2. Calculate the inverse Digamma function at point 1.5");
Console.WriteLine(SpecialFunctions.DiGammaInv(1.5));
Console.WriteLine();
// 3. Calculate the 10'th Harmonic number
Console.WriteLine(@"3. Calculate the 10'th Harmonic number");
Console.WriteLine(SpecialFunctions.Harmonic(10));
Console.WriteLine();
// 4. Calculate the generalized harmonic number of order 10 of 3.0.
Console.WriteLine(@"4. Calculate the generalized harmonic number of order 10 of 3.0");
Console.WriteLine(SpecialFunctions.GeneralHarmonic(10, 3.0));
Console.WriteLine();
// 5. Calculate the logistic function of 3.0
Console.WriteLine(@"5. Calculate the logistic function of 3.0");
Console.WriteLine(SpecialFunctions.Logistic(3.0));
Console.WriteLine();
// 6. Calculate the logit function of 0.3
Console.WriteLine(@"6. Calculate the logit function of 0.3");
Console.WriteLine(SpecialFunctions.Logit(0.3));
Console.WriteLine();
}
}
}

129
src/Examples/SpecialFunctions/ErrorFunction.cs

@ -0,0 +1,129 @@
// <copyright file="ErrorFunction.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.SpecialFunctions
{
using System;
using MathNet.Numerics;
using MathNet.Numerics.Sampling;
/// <summary>
/// Special Functions: error functions
/// </summary>
public class ErrorFunction : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Special Functions: error functions";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Error function (Gauss error function or probability integral)";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Error_function">Error function</seealso>
public void Run()
{
// 1. Calculate the error function at point 2
Console.WriteLine(@"1. Calculate the error function at point 2");
Console.WriteLine(SpecialFunctions.Erf(2));
Console.WriteLine();
// 2. Sample 10 values of the error function in [-1.0; 1.0]
Console.WriteLine(@"2. Sample 10 values of the error function in [-1.0; 1.0]");
var data = Sample.EquidistantInterval(SpecialFunctions.Erf, -1.0, 1.0, 10);
for (var i = 0; i < data.Length; i++)
{
Console.Write(data[i].ToString("N") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 3. Calculate the complementary error function at point 2
Console.WriteLine(@"3. Calculate the complementary error function at point 2");
Console.WriteLine(SpecialFunctions.Erfc(2));
Console.WriteLine();
// 4. Sample 10 values of the complementary error function in [-1.0; 1.0]
Console.WriteLine(@"4. Sample 10 values of the complementary error function in [-1.0; 1.0]");
data = Sample.EquidistantInterval(SpecialFunctions.Erfc, -1.0, 1.0, 10);
for (var i = 0; i < data.Length; i++)
{
Console.Write(data[i].ToString("N") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 5. Calculate the inverse error function at point z=0.5
Console.WriteLine(@"5. Calculate the inverse error function at point z=0.5");
Console.WriteLine(SpecialFunctions.ErfInv(0.5));
Console.WriteLine();
// 6. Sample 10 values of the inverse error function in [-1.0; 1.0]
Console.WriteLine(@"6. Sample 10 values of the inverse error function in [-1.0; 1.0]");
data = Sample.EquidistantInterval(SpecialFunctions.ErfInv, -1.0, 1.0, 10);
for (var i = 0; i < data.Length; i++)
{
Console.Write(data[i].ToString("N") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 7. Calculate the complementary inverse error function at point z=0.5
Console.WriteLine(@"7. Calculate the complementary inverse error function at point z=0.5");
Console.WriteLine(SpecialFunctions.ErfcInv(0.5));
Console.WriteLine();
// 8. Sample 10 values of the complementary inverse error function in [-1.0; 1.0]
Console.WriteLine(@"8. Sample 10 values of the complementary inverse error function in [-1.0; 1.0]");
data = Sample.EquidistantInterval(SpecialFunctions.ErfcInv, -1.0, 1.0, 10);
for (var i = 0; i < data.Length; i++)
{
Console.Write(data[i].ToString("N") + @" ");
}
Console.WriteLine();
}
}
}

95
src/Examples/SpecialFunctions/Factorial.cs

@ -0,0 +1,95 @@
// <copyright file="Factorial.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.SpecialFunctions
{
using System;
using MathNet.Numerics;
/// <summary>
/// Special Functions: Factorial
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/Factorial.html"/>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/Binomial.html"/>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/Multinomial.html"/>
public class Factorial : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Special Functions: Factorial";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Factorial, Binomial, Multinomial";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Factorial">Factorial</seealso>
/// <seealso cref="http://en.wikipedia.org/wiki/Binomial_coefficient">Binomial coefficient</seealso>
/// <seealso cref="http://en.wikipedia.org/wiki/Multinomial_theorem#Multinomial_coefficients">Multinomial coefficients</seealso>
public void Run()
{
// 1. Compute the factorial of 5
Console.WriteLine(@"1. Compute the factorial of 5");
Console.WriteLine(SpecialFunctions.Factorial(5).ToString("N"));
Console.WriteLine();
// 2. Compute the logarithm of the factorial of 5
Console.WriteLine(@"2. Compute the logarithm of the factorial of 5");
Console.WriteLine(SpecialFunctions.FactorialLn(5).ToString("N"));
Console.WriteLine();
// 3. Compute the binomial coefficient: 10 choose 8
Console.WriteLine(@"3. Compute the binomial coefficient: 10 choose 8");
Console.WriteLine(SpecialFunctions.Binomial(10, 8).ToString("N"));
Console.WriteLine();
// 4. Compute the logarithm of the binomial coefficient: 10 choose 8
Console.WriteLine(@"4. Compute the logarithm of the binomial coefficient: 10 choose 8");
Console.WriteLine(SpecialFunctions.BinomialLn(10, 8).ToString("N"));
Console.WriteLine();
// 5. Compute the multinomial coefficient: 10 choose 2, 3, 5
Console.WriteLine(@"5. Compute the multinomial coefficient: 10 choose 2, 3, 5");
Console.WriteLine(SpecialFunctions.Multinomial(10, new[] { 2, 3, 5 }).ToString("N"));
Console.WriteLine();
}
}
}

116
src/Examples/SpecialFunctions/Gamma.cs

@ -0,0 +1,116 @@
// <copyright file="Gamma.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.SpecialFunctions
{
using System;
using MathNet.Numerics;
/// <summary>
/// Special Functions: Gamma
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/Gamma.html"/>
public class Gamma : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Special Functions: Gamma";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Gamma, incomplete Gamma, regularized Gamma";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Gamma_function">Gamma function</seealso>
public void Run()
{
// 1. Compute the Gamma function of 10
Console.WriteLine(@"1. Compute the Gamma function of 10");
Console.WriteLine(SpecialFunctions.Gamma(10).ToString("N"));
Console.WriteLine();
// 2. Compute the logarithm of the Gamma function of 10
Console.WriteLine(@"2. Compute the logarithm of the Gamma function of 10");
Console.WriteLine(SpecialFunctions.GammaLn(10).ToString("N"));
Console.WriteLine();
// 3. Compute the lower incomplete gamma(a, x) function at a = 10, x = 14
Console.WriteLine(@"3. Compute the lower incomplete gamma(a, x) function at a = 10, x = 14");
Console.WriteLine(SpecialFunctions.GammaLowerIncomplete(10, 14).ToString("N"));
Console.WriteLine();
// 4. Compute the lower incomplete gamma(a, x) function at a = 10, x = 100
Console.WriteLine(@"4. Compute the lower incomplete gamma(a, x) function at a = 10, x = 100");
Console.WriteLine(SpecialFunctions.GammaLowerIncomplete(10, 100).ToString("N"));
Console.WriteLine();
// 5. Compute the upper incomplete gamma(a, x) function at a = 10, x = 0
Console.WriteLine(@"5. Compute the upper incomplete gamma(a, x) function at a = 10, x = 0");
Console.WriteLine(SpecialFunctions.GammaUpperIncomplete(10, 0).ToString("N"));
Console.WriteLine();
// 6. Compute the upper incomplete gamma(a, x) function at a = 10, x = 10
Console.WriteLine(@"6. Compute the upper incomplete gamma(a, x) function at a = 10, x = 100");
Console.WriteLine(SpecialFunctions.GammaLowerIncomplete(10, 10).ToString("N"));
Console.WriteLine();
// 7. Compute the lower regularized gamma(a, x) function at a = 10, x = 14
Console.WriteLine(@"7. Compute the lower regularized gamma(a, x) function at a = 10, x = 14");
Console.WriteLine(SpecialFunctions.GammaLowerRegularized(10, 14).ToString("N"));
Console.WriteLine();
// 8. Compute the lower regularized gamma(a, x) function at a = 10, x = 100
Console.WriteLine(@"8. Compute the lower regularized gamma(a, x) function at a = 10, x = 100");
Console.WriteLine(SpecialFunctions.GammaLowerRegularized(10, 100).ToString("N"));
Console.WriteLine();
// 9. Compute the upper regularized gamma(a, x) function at a = 10, x = 0
Console.WriteLine(@"9. Compute the upper regularized gamma(a, x) function at a = 10, x = 0");
Console.WriteLine(SpecialFunctions.GammaUpperRegularized(10, 0).ToString("N"));
Console.WriteLine();
// 10. Compute the upper regularized gamma(a, x) function at a = 10, x = 10
Console.WriteLine(@"10. Compute the upper regularized gamma(a, x) function at a = 10, x = 100");
Console.WriteLine(SpecialFunctions.GammaUpperRegularized(10, 10).ToString("N"));
Console.WriteLine();
}
}
}

80
src/Examples/SpecialFunctions/Stability.cs

@ -0,0 +1,80 @@
// <copyright file="Stability.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples.SpecialFunctions
{
using System;
using MathNet.Numerics;
/// <summary>
/// Special Functions: Stability
/// </summary>
public class Stability : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Special Functions: Stability";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Exponential, Hypotenuse, Series";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Hypotenuse">Hypotenuse</seealso>
public void Run()
{
// 1. Compute numerically stable exponential of 10 minus one
Console.WriteLine(@"1. Compute numerically stable exponential of 4.2876 minus one");
Console.WriteLine(SpecialFunctions.ExponentialMinusOne(4.2876));
Console.WriteLine();
// 2. Compute regular System.Math exponential of 15.28 minus one
Console.WriteLine(@"2. Compute regular System.Math exponential of 4.2876 minus one ");
Console.WriteLine(Math.Exp(4.2876) - 1);
Console.WriteLine();
// 3. Compute numerically stable hypotenuse of a right angle triangle with a = 5, b = 3
Console.WriteLine(@"3. Compute numerically stable hypotenuse of a right angle triangle with a = 5, b = 3");
Console.WriteLine(SpecialFunctions.Hypotenuse(5, 3));
Console.WriteLine();
}
}
}

133
src/Examples/Statistics.cs

@ -0,0 +1,133 @@
// <copyright file="Statistics.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
namespace Examples
{
using System;
using MathNet.Numerics.Distributions;
using MathNet.Numerics.Sampling;
using MathNet.Numerics.Statistics;
/// <summary>
/// Statistics on set of data
/// </summary>
public class Statistics : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
public string Name
{
get
{
return "Statistics";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Basic statistics on set of data, correlation";
}
}
/// <summary>
/// Run example
/// </summary>
/// <seealso cref="http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient">Pearson product-moment correlation coefficient</seealso>
public void Run()
{
// 1. Initialize the new instance of the ChiSquare distribution class with parameter dof = 5.
var chiSquare = new ChiSquare(5);
Console.WriteLine(@"1. Initialize the new instance of the ChiSquare distribution class with parameter DegreesOfFreedom = {0}", chiSquare.DegreesOfFreedom);
Console.WriteLine(@"{0} distributuion properties:", chiSquare);
Console.WriteLine(@"{0} - Largest element", chiSquare.Maximum.ToString(" #0.00000;-#0.00000"));
Console.WriteLine(@"{0} - Smallest element", chiSquare.Minimum.ToString(" #0.00000;-#0.00000"));
Console.WriteLine(@"{0} - Mean", chiSquare.Mean.ToString(" #0.00000;-#0.00000"));
Console.WriteLine(@"{0} - Median", chiSquare.Median.ToString(" #0.00000;-#0.00000"));
Console.WriteLine(@"{0} - Mode", chiSquare.Mode.ToString(" #0.00000;-#0.00000"));
Console.WriteLine(@"{0} - Variance", chiSquare.Variance.ToString(" #0.00000;-#0.00000"));
Console.WriteLine(@"{0} - Standard deviation", chiSquare.StdDev.ToString(" #0.00000;-#0.00000"));
Console.WriteLine(@"{0} - Skewness", chiSquare.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 2. Generate 1000 samples of the ChiSquare(5) distribution
Console.WriteLine(@"2. Generate 1000 samples of the ChiSquare(5) distribution");
var data = new double[1000];
for (var i = 0; i < data.Length; i++)
{
data[i] = chiSquare.Sample();
}
// 3. Get basic statistics on set of generated data using extention methods
Console.WriteLine(@"3. Get basic statistics on set of generated data using extention methods");
Console.WriteLine(@"{0} - Largest element", data.Maximum().ToString(" #0.00000;-#0.00000"));
Console.WriteLine(@"{0} - Smallest element", data.Minimum().ToString(" #0.00000;-#0.00000"));
Console.WriteLine(@"{0} - Mean", data.Mean().ToString(" #0.00000;-#0.00000"));
Console.WriteLine(@"{0} - Median", data.Median().ToString(" #0.00000;-#0.00000"));
Console.WriteLine(@"{0} - Biased population variance", data.PopulationVariance().ToString(" #0.00000;-#0.00000"));
Console.WriteLine(@"{0} - Variance", data.Variance().ToString(" #0.00000;-#0.00000"));
Console.WriteLine(@"{0} - Standard deviation", data.StandardDeviation().ToString(" #0.00000;-#0.00000"));
Console.WriteLine(@"{0} - Biased sample standard deviation", data.PopulationStandardDeviation().ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 4. Compute the basic statistics of data set using DescriptiveStatistics class
Console.WriteLine(@"4. Compute the basic statistics of data set using DescriptiveStatistics class");
var descriptiveStatistics = new DescriptiveStatistics(data);
Console.WriteLine(@"{0} - Kurtosis", descriptiveStatistics.Kurtosis.ToString(" #0.00000;-#0.00000"));
Console.WriteLine(@"{0} - Largest element", descriptiveStatistics.Maximum.ToString(" #0.00000;-#0.00000"));
Console.WriteLine(@"{0} - Smallest element", descriptiveStatistics.Minimum.ToString(" #0.00000;-#0.00000"));
Console.WriteLine(@"{0} - Mean", descriptiveStatistics.Mean.ToString(" #0.00000;-#0.00000"));
Console.WriteLine(@"{0} - Median", descriptiveStatistics.Median.ToString(" #0.00000;-#0.00000"));
Console.WriteLine(@"{0} - Variance", descriptiveStatistics.Variance.ToString(" #0.00000;-#0.00000"));
Console.WriteLine(@"{0} - Standard deviation", descriptiveStatistics.StandardDeviation.ToString(" #0.00000;-#0.00000"));
Console.WriteLine(@"{0} - Skewness", descriptiveStatistics.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// Generate 1000 samples of the ChiSquare(2.5) distribution
var chiSquareB = new ChiSquare(2);
var dataB = new double[1000];
for (var i = 0; i < data.Length; i++)
{
dataB[i] = chiSquareB.Sample();
}
// 5. Correlation coefficient between 1000 samples of ChiSquare(5) and ChiSquare(2.5)
Console.WriteLine(@"5. Correlation coefficient between 1000 samples of ChiSquare(5) and ChiSquare(2.5) is {0}", Correlation.Pearson(data, dataB).ToString("N04"));
Console.WriteLine();
// 6. Correlation coefficient between 1000 samples of f(x) = x * 2 and f(x) = x * x
data = Sample.EquidistantInterval(x => x * 2, 0, 100, 1000);
dataB = Sample.EquidistantInterval(x => x * x, 0, 100, 1000);
Console.WriteLine(@"6. Correlation coefficient between 1000 samples of f(x) = x * 2 and f(x) = x * x is {0}", Correlation.Pearson(data, dataB).ToString("N04"));
Console.WriteLine();
}
}
}

2
src/Numerics/Distributions/Continuous/Chi.cs

@ -317,7 +317,7 @@ namespace MathNet.Numerics.Distributions
var n = (int)_dof; var n = (int)_dof;
for (var i = 0; i < n; i++) for (var i = 0; i < n; i++)
{ {
sum += Normal.Sample(rnd, 0.0, 1.0); sum += Math.Pow(Normal.Sample(rnd, 0.0, 1.0), 2);
} }
return Math.Sqrt(sum); return Math.Sqrt(sum);

2
src/Numerics/Distributions/Continuous/ChiSquare.cs

@ -278,7 +278,7 @@ namespace MathNet.Numerics.Distributions
var n = (int)dof; var n = (int)dof;
for (var i = 0; i < n; i++) for (var i = 0; i < n; i++)
{ {
sum += Normal.Sample(rnd, 0.0, 1.0); sum += Math.Pow(Normal.Sample(rnd, 0.0, 1.0), 2);
} }
return sum; return sum;

3
src/Numerics/Distributions/Discrete/Hypergeometric.cs

@ -366,8 +366,9 @@ namespace MathNet.Numerics.Distributions
} }
size--; size--;
n--;
} }
while (1 < n); while (0 < n);
return x; return x;
} }

2
src/Numerics/Interpolation/Algorithms/BulirschStoerRationalInterpolation.cs

@ -168,7 +168,7 @@ namespace MathNet.Numerics.Interpolation.Algorithms
double ho = (_points[i] - t) * d[i] / hp; double ho = (_points[i] - t) * d[i] / hp;
double den = ho - c[i + 1]; double den = ho - c[i + 1];
if (den == 0.0) if (den.AlmostEqual(0.0))
{ {
return double.NaN; // zero-div, singularity return double.NaN; // zero-div, singularity
} }

4
src/Numerics/LinearAlgebra/Complex/Solvers/Iterative/CompositeSolver.cs

@ -264,6 +264,7 @@ namespace MathNet.Numerics.LinearAlgebra.Complex.Solvers.Iterative
var interfaceTypes = new List<Type>(); var interfaceTypes = new List<Type>();
foreach (var type in assembly.GetTypes().Where(type => (!type.IsAbstract && !type.IsEnum && !type.IsInterface && type.IsVisible))) foreach (var type in assembly.GetTypes().Where(type => (!type.IsAbstract && !type.IsEnum && !type.IsInterface && type.IsVisible)))
{ {
interfaceTypes.Clear();
interfaceTypes.AddRange(type.GetInterfaces()); interfaceTypes.AddRange(type.GetInterfaces());
if (!interfaceTypes.Any(match => typeof(IIterativeSolverSetup<Complex>).IsAssignableFrom(match))) if (!interfaceTypes.Any(match => typeof(IIterativeSolverSetup<Complex>).IsAssignableFrom(match)))
{ {
@ -512,6 +513,7 @@ namespace MathNet.Numerics.LinearAlgebra.Complex.Solvers.Iterative
if (_iterator.Status is CalculationConverged) if (_iterator.Status is CalculationConverged)
{ {
// We're done // We're done
internalResult.CopyTo(result);
break; break;
} }
@ -522,7 +524,7 @@ namespace MathNet.Numerics.LinearAlgebra.Complex.Solvers.Iterative
{ {
// Copy the internal result to the result vector and // Copy the internal result to the result vector and
// continue with the calculation. // continue with the calculation.
internalInput.CopyTo(input); internalResult.CopyTo(result);
} }
else else
{ {

4
src/Numerics/LinearAlgebra/Complex32/Solvers/Iterative/CompositeSolver.cs

@ -264,6 +264,7 @@ namespace MathNet.Numerics.LinearAlgebra.Complex32.Solvers.Iterative
var interfaceTypes = new List<Type>(); var interfaceTypes = new List<Type>();
foreach (var type in assembly.GetTypes().Where(type => (!type.IsAbstract && !type.IsEnum && !type.IsInterface && type.IsVisible))) foreach (var type in assembly.GetTypes().Where(type => (!type.IsAbstract && !type.IsEnum && !type.IsInterface && type.IsVisible)))
{ {
interfaceTypes.Clear();
interfaceTypes.AddRange(type.GetInterfaces()); interfaceTypes.AddRange(type.GetInterfaces());
if (!interfaceTypes.Any(match => typeof(IIterativeSolverSetup<Complex32>).IsAssignableFrom(match))) if (!interfaceTypes.Any(match => typeof(IIterativeSolverSetup<Complex32>).IsAssignableFrom(match)))
{ {
@ -512,6 +513,7 @@ namespace MathNet.Numerics.LinearAlgebra.Complex32.Solvers.Iterative
if (_iterator.Status is CalculationConverged) if (_iterator.Status is CalculationConverged)
{ {
// We're done // We're done
internalResult.CopyTo(result);
break; break;
} }
@ -522,7 +524,7 @@ namespace MathNet.Numerics.LinearAlgebra.Complex32.Solvers.Iterative
{ {
// Copy the internal result to the result vector and // Copy the internal result to the result vector and
// continue with the calculation. // continue with the calculation.
internalInput.CopyTo(input); internalResult.CopyTo(result);
} }
else else
{ {

4
src/Numerics/LinearAlgebra/Double/Solvers/Iterative/CompositeSolver.cs

@ -263,6 +263,7 @@ namespace MathNet.Numerics.LinearAlgebra.Double.Solvers.Iterative
var interfaceTypes = new List<Type>(); var interfaceTypes = new List<Type>();
foreach (var type in assembly.GetTypes().Where(type => (!type.IsAbstract && !type.IsEnum && !type.IsInterface && type.IsVisible))) foreach (var type in assembly.GetTypes().Where(type => (!type.IsAbstract && !type.IsEnum && !type.IsInterface && type.IsVisible)))
{ {
interfaceTypes.Clear();
interfaceTypes.AddRange(type.GetInterfaces()); interfaceTypes.AddRange(type.GetInterfaces());
if (!interfaceTypes.Any(match => typeof(IIterativeSolverSetup<double>).IsAssignableFrom(match))) if (!interfaceTypes.Any(match => typeof(IIterativeSolverSetup<double>).IsAssignableFrom(match)))
{ {
@ -511,6 +512,7 @@ namespace MathNet.Numerics.LinearAlgebra.Double.Solvers.Iterative
if (_iterator.Status is CalculationConverged) if (_iterator.Status is CalculationConverged)
{ {
// We're done // We're done
internalResult.CopyTo(result);
break; break;
} }
@ -521,7 +523,7 @@ namespace MathNet.Numerics.LinearAlgebra.Double.Solvers.Iterative
{ {
// Copy the internal result to the result vector and // Copy the internal result to the result vector and
// continue with the calculation. // continue with the calculation.
internalInput.CopyTo(input); internalResult.CopyTo(result);
} }
else else
{ {

4
src/Numerics/LinearAlgebra/Single/Solvers/Iterative/CompositeSolver.cs

@ -263,6 +263,7 @@ namespace MathNet.Numerics.LinearAlgebra.Single.Solvers.Iterative
var interfaceTypes = new List<Type>(); var interfaceTypes = new List<Type>();
foreach (var type in assembly.GetTypes().Where(type => (!type.IsAbstract && !type.IsEnum && !type.IsInterface && type.IsVisible))) foreach (var type in assembly.GetTypes().Where(type => (!type.IsAbstract && !type.IsEnum && !type.IsInterface && type.IsVisible)))
{ {
interfaceTypes.Clear();
interfaceTypes.AddRange(type.GetInterfaces()); interfaceTypes.AddRange(type.GetInterfaces());
if (!interfaceTypes.Any(match => typeof(IIterativeSolverSetup<double>).IsAssignableFrom(match))) if (!interfaceTypes.Any(match => typeof(IIterativeSolverSetup<double>).IsAssignableFrom(match)))
{ {
@ -511,6 +512,7 @@ namespace MathNet.Numerics.LinearAlgebra.Single.Solvers.Iterative
if (_iterator.Status is CalculationConverged) if (_iterator.Status is CalculationConverged)
{ {
// We're done // We're done
internalResult.CopyTo(result);
break; break;
} }
@ -521,7 +523,7 @@ namespace MathNet.Numerics.LinearAlgebra.Single.Solvers.Iterative
{ {
// Copy the internal result to the result vector and // Copy the internal result to the result vector and
// continue with the calculation. // continue with the calculation.
internalInput.CopyTo(input); internalResult.CopyTo(result);
} }
else else
{ {

4
src/Numerics/NumberTheory/IntegerTheory.cs

@ -193,7 +193,7 @@ namespace MathNet.Numerics.NumberTheory
/// </summary> /// </summary>
/// <param name="number">The number to very whether it's a perfect square.</param> /// <param name="number">The number to very whether it's a perfect square.</param>
/// <returns>True if and only if it is a perfect square.</returns> /// <returns>True if and only if it is a perfect square.</returns>
public static bool IsPerfectSquare(int number) public static bool IsPerfectSquare(this int number)
{ {
if (number < 0) if (number < 0)
{ {
@ -220,7 +220,7 @@ namespace MathNet.Numerics.NumberTheory
/// </summary> /// </summary>
/// <param name="number">The number to very whether it's a perfect square.</param> /// <param name="number">The number to very whether it's a perfect square.</param>
/// <returns>True if and only if it is a perfect square.</returns> /// <returns>True if and only if it is a perfect square.</returns>
public static bool IsPerfectSquare(long number) public static bool IsPerfectSquare(this long number)
{ {
if (number < 0) if (number < 0)
{ {

Loading…
Cancel
Save