diff --git a/src/Examples/ConsoleHelper.cs b/src/Examples/ConsoleHelper.cs new file mode 100644 index 00000000..031d6747 --- /dev/null +++ b/src/Examples/ConsoleHelper.cs @@ -0,0 +1,109 @@ +// +// 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. +// + +namespace Examples +{ + using System; + using MathNet.Numerics.Statistics; + + /// + /// Helper fucntions to output into Console window + /// + public static class ConsoleHelper + { + /// + /// Disoplay histogram from the array + /// + /// Source array + 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(); + } + } +} diff --git a/src/Examples/ContinuousDistributions/BetaDistribution.cs b/src/Examples/ContinuousDistributions/BetaDistribution.cs new file mode 100644 index 00000000..bc2f3a3d --- /dev/null +++ b/src/Examples/ContinuousDistributions/BetaDistribution.cs @@ -0,0 +1,165 @@ +// +// 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. +// + +namespace Examples.ContinuousDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// Beta distribution example + /// + public class BetaDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "Beta distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Beta distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// Beta distribution + 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); + } + } +} diff --git a/src/Examples/ContinuousDistributions/CauchyDistribution.cs b/src/Examples/ContinuousDistributions/CauchyDistribution.cs new file mode 100644 index 00000000..ece8ca49 --- /dev/null +++ b/src/Examples/ContinuousDistributions/CauchyDistribution.cs @@ -0,0 +1,108 @@ +// +// 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. +// + +namespace Examples.ContinuousDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// Cauchy distribution example + /// + public class CauchyDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "Cauchy distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Cauchy distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// Cauchy distribution + 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(); + } + } +} diff --git a/src/Examples/ContinuousDistributions/ChiDistribution.cs b/src/Examples/ContinuousDistributions/ChiDistribution.cs new file mode 100644 index 00000000..e863ae08 --- /dev/null +++ b/src/Examples/ContinuousDistributions/ChiDistribution.cs @@ -0,0 +1,151 @@ +// +// 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. +// + +namespace Examples.ContinuousDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// Chi distribution example + /// + public class ChiDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "Chi distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Chi distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// Chi distribution + 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); + } + } +} diff --git a/src/Examples/ContinuousDistributions/ChiSquareDistribution.cs b/src/Examples/ContinuousDistributions/ChiSquareDistribution.cs new file mode 100644 index 00000000..f7379654 --- /dev/null +++ b/src/Examples/ContinuousDistributions/ChiSquareDistribution.cs @@ -0,0 +1,154 @@ +// +// 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. +// + +namespace Examples.ContinuousDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// ChiSquare distribution example + /// + public class ChiSquareDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "ChiSquare distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "ChiSquare distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// ChiSquare distribution + 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); + } + } +} diff --git a/src/Examples/ContinuousDistributions/ContinuousUniformDistribution.cs b/src/Examples/ContinuousDistributions/ContinuousUniformDistribution.cs new file mode 100644 index 00000000..1ab3c1e1 --- /dev/null +++ b/src/Examples/ContinuousDistributions/ContinuousUniformDistribution.cs @@ -0,0 +1,144 @@ +// +// 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. +// + +namespace Examples.ContinuousDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// ContinuousUniform distribution example + /// + public class ContinuousUniformDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "ContinuousUniform distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "ContinuousUniform distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// ContinuousUniform distribution + 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); + } + } +} diff --git a/src/Examples/ContinuousDistributions/ErlangDistribution.cs b/src/Examples/ContinuousDistributions/ErlangDistribution.cs new file mode 100644 index 00000000..a15110a5 --- /dev/null +++ b/src/Examples/ContinuousDistributions/ErlangDistribution.cs @@ -0,0 +1,152 @@ +// +// 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. +// + +namespace Examples.ContinuousDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// Erlang distribution example + /// + public class ErlangDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "Erlang distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Erlang distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// Erlang distribution + 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); + } + } +} diff --git a/src/Examples/ContinuousDistributions/ExponentialDistribution.cs b/src/Examples/ContinuousDistributions/ExponentialDistribution.cs new file mode 100644 index 00000000..c46964cf --- /dev/null +++ b/src/Examples/ContinuousDistributions/ExponentialDistribution.cs @@ -0,0 +1,154 @@ +// +// 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. +// + +namespace Examples.ContinuousDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// Exponential distribution example + /// + public class ExponentialDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "Exponential distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Exponential distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// Exponential distribution + 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); + } + } +} diff --git a/src/Examples/ContinuousDistributions/FisherSnedecorDistribution.cs b/src/Examples/ContinuousDistributions/FisherSnedecorDistribution.cs new file mode 100644 index 00000000..74fe5ba9 --- /dev/null +++ b/src/Examples/ContinuousDistributions/FisherSnedecorDistribution.cs @@ -0,0 +1,150 @@ +// +// 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. +// + +namespace Examples.ContinuousDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// FisherSnedecor distribution example + /// + public class FisherSnedecorDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "FisherSnedecor distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "FisherSnedecor distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// FisherSnedecor distribution + 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); + } + } +} diff --git a/src/Examples/ContinuousDistributions/GammaDistribution.cs b/src/Examples/ContinuousDistributions/GammaDistribution.cs new file mode 100644 index 00000000..29c4375d --- /dev/null +++ b/src/Examples/ContinuousDistributions/GammaDistribution.cs @@ -0,0 +1,141 @@ +// +// 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. +// + +namespace Examples.ContinuousDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// Gamma distribution example + /// + public class GammaDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "Gamma distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Gamma distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// Gamma distribution + 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); + } + } +} diff --git a/src/Examples/ContinuousDistributions/InverseGammaDistribution.cs b/src/Examples/ContinuousDistributions/InverseGammaDistribution.cs new file mode 100644 index 00000000..cdf3c2db --- /dev/null +++ b/src/Examples/ContinuousDistributions/InverseGammaDistribution.cs @@ -0,0 +1,151 @@ +// +// 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. +// + +namespace Examples.ContinuousDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// InverseGamma distribution example + /// + public class InverseGammaDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "InverseGamma distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "InverseGamma distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// InverseGamma distribution + 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); + } + } +} diff --git a/src/Examples/ContinuousDistributions/LaplaceDistribution.cs b/src/Examples/ContinuousDistributions/LaplaceDistribution.cs new file mode 100644 index 00000000..481e234a --- /dev/null +++ b/src/Examples/ContinuousDistributions/LaplaceDistribution.cs @@ -0,0 +1,155 @@ +// +// 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. +// + +namespace Examples.ContinuousDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// Laplace distribution example + /// + public class LaplaceDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "Laplace distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Laplace distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// Laplace distribution + 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); + } + } +} diff --git a/src/Examples/ContinuousDistributions/LogNormalDistribution.cs b/src/Examples/ContinuousDistributions/LogNormalDistribution.cs new file mode 100644 index 00000000..d2a60bae --- /dev/null +++ b/src/Examples/ContinuousDistributions/LogNormalDistribution.cs @@ -0,0 +1,155 @@ +// +// 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. +// + +namespace Examples.ContinuousDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// LogNormal distribution example + /// + public class LogNormalDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "LogNormal distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "LogNormal distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// LogNormal distribution + 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); + } + } +} diff --git a/src/Examples/ContinuousDistributions/NormalDistribution.cs b/src/Examples/ContinuousDistributions/NormalDistribution.cs new file mode 100644 index 00000000..ea9394fe --- /dev/null +++ b/src/Examples/ContinuousDistributions/NormalDistribution.cs @@ -0,0 +1,144 @@ +// +// 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. +// + +namespace Examples.ContinuousDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// Normal distribution example + /// + public class NormalDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "Normal distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Normal distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// Normal distribution + 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); + } + } +} diff --git a/src/Examples/ContinuousDistributions/ParetoDistribution.cs b/src/Examples/ContinuousDistributions/ParetoDistribution.cs new file mode 100644 index 00000000..9132898f --- /dev/null +++ b/src/Examples/ContinuousDistributions/ParetoDistribution.cs @@ -0,0 +1,155 @@ +// +// 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. +// + +namespace Examples.ContinuousDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// Pareto distribution example + /// + public class ParetoDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "Pareto distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Pareto distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// Pareto distribution + 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); + } + } +} diff --git a/src/Examples/ContinuousDistributions/RayleighDistribution.cs b/src/Examples/ContinuousDistributions/RayleighDistribution.cs new file mode 100644 index 00000000..d7cf55ef --- /dev/null +++ b/src/Examples/ContinuousDistributions/RayleighDistribution.cs @@ -0,0 +1,154 @@ +// +// 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. +// + +namespace Examples.ContinuousDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// Rayleigh distribution example + /// + public class RayleighDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "Rayleigh distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Rayleigh distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// Rayleigh distribution + 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); + } + } +} diff --git a/src/Examples/ContinuousDistributions/StableDistribution.cs b/src/Examples/ContinuousDistributions/StableDistribution.cs new file mode 100644 index 00000000..2edf5b84 --- /dev/null +++ b/src/Examples/ContinuousDistributions/StableDistribution.cs @@ -0,0 +1,154 @@ +// +// 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. +// + +namespace Examples.ContinuousDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// Stable distribution example + /// + public class StableDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "Stable distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Stable distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// Stable distribution + 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); + } + } +} diff --git a/src/Examples/ContinuousDistributions/StudentTDistribution.cs b/src/Examples/ContinuousDistributions/StudentTDistribution.cs new file mode 100644 index 00000000..0d425ae3 --- /dev/null +++ b/src/Examples/ContinuousDistributions/StudentTDistribution.cs @@ -0,0 +1,149 @@ +// +// 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. +// + +namespace Examples.ContinuousDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// StudentT distribution example + /// + public class StudentTDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "StudentT distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "StudentT distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// StudentT distribution + 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); + } + } +} diff --git a/src/Examples/ContinuousDistributions/WeibullDistribution.cs b/src/Examples/ContinuousDistributions/WeibullDistribution.cs new file mode 100644 index 00000000..96083286 --- /dev/null +++ b/src/Examples/ContinuousDistributions/WeibullDistribution.cs @@ -0,0 +1,154 @@ +// +// 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. +// + +namespace Examples.ContinuousDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// Weibull distribution example + /// + public class WeibullDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "Weibull distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Weibull distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// Weibull distribution + 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); + } + } +} diff --git a/src/Examples/DiscreteDistributions/BernoulliDistribution.cs b/src/Examples/DiscreteDistributions/BernoulliDistribution.cs new file mode 100644 index 00000000..a4b99a71 --- /dev/null +++ b/src/Examples/DiscreteDistributions/BernoulliDistribution.cs @@ -0,0 +1,151 @@ +// +// 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. +// + +namespace Examples.DiscreteDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// Bernoulli distribution example + /// + public class BernoulliDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "Bernoulli distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Bernoulli distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// Bernoulli distribution + 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); + } + } +} diff --git a/src/Examples/DiscreteDistributions/BinomialDistribution.cs b/src/Examples/DiscreteDistributions/BinomialDistribution.cs new file mode 100644 index 00000000..127e4b41 --- /dev/null +++ b/src/Examples/DiscreteDistributions/BinomialDistribution.cs @@ -0,0 +1,155 @@ +// +// 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. +// + +namespace Examples.DiscreteDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// Binomial distribution example + /// + public class BinomialDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "Binomial distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Binomial distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// Binomial distribution + 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); + } + } +} diff --git a/src/Examples/DiscreteDistributions/CategoricalDistribution.cs b/src/Examples/DiscreteDistributions/CategoricalDistribution.cs new file mode 100644 index 00000000..266bdfe1 --- /dev/null +++ b/src/Examples/DiscreteDistributions/CategoricalDistribution.cs @@ -0,0 +1,135 @@ +// +// 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. +// + +namespace Examples.DiscreteDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// Categorical distribution example + /// + public class CategoricalDistribution : IExample + { + /// + /// Gets the name of this example + /// + public string Name + { + get + { + return "Categorical distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Categorical distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// Categorical distribution + 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); + } + } +} diff --git a/src/Examples/DiscreteDistributions/ConwayMaxwellPoissonDistribution.cs b/src/Examples/DiscreteDistributions/ConwayMaxwellPoissonDistribution.cs new file mode 100644 index 00000000..60d38c1a --- /dev/null +++ b/src/Examples/DiscreteDistributions/ConwayMaxwellPoissonDistribution.cs @@ -0,0 +1,139 @@ +// +// 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. +// + +namespace Examples.DiscreteDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// ConwayMaxwellPoisson distribution example + /// + public class ConwayMaxwellPoissonDistribution : IExample + { + /// + /// Gets the name of this example + /// + public string Name + { + get + { + return "ConwayMaxwellPoisson distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "ConwayMaxwellPoisson distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// ConwayMaxwellPoisson distribution + 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); + } + } +} diff --git a/src/Examples/DiscreteDistributions/DiscreteUniformDistribution.cs b/src/Examples/DiscreteDistributions/DiscreteUniformDistribution.cs new file mode 100644 index 00000000..81011f7d --- /dev/null +++ b/src/Examples/DiscreteDistributions/DiscreteUniformDistribution.cs @@ -0,0 +1,156 @@ +// +// 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. +// + +namespace Examples.DiscreteDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// DiscreteUniform distribution example + /// + public class DiscreteUniformDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "DiscreteUniform distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "DiscreteUniform distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// DiscreteUniform distribution + 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); + } + } +} diff --git a/src/Examples/DiscreteDistributions/GeometricDistribution.cs b/src/Examples/DiscreteDistributions/GeometricDistribution.cs new file mode 100644 index 00000000..3422b3b9 --- /dev/null +++ b/src/Examples/DiscreteDistributions/GeometricDistribution.cs @@ -0,0 +1,154 @@ +// +// 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. +// + +namespace Examples.DiscreteDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// Geometric distribution example + /// + public class GeometricDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "Geometric distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Geometric distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// Geometric distribution + 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); + } + } +} diff --git a/src/Examples/DiscreteDistributions/HypergeometricDistribution.cs b/src/Examples/DiscreteDistributions/HypergeometricDistribution.cs new file mode 100644 index 00000000..53fbf4f9 --- /dev/null +++ b/src/Examples/DiscreteDistributions/HypergeometricDistribution.cs @@ -0,0 +1,139 @@ +// +// 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. +// + +namespace Examples.DiscreteDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// Hypergeometric distribution example + /// + public class HypergeometricDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "Hypergeometric distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Hypergeometric distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// Hypergeometric distribution + 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); + } + } +} diff --git a/src/Examples/DiscreteDistributions/NegativeBinomialDistribution.cs b/src/Examples/DiscreteDistributions/NegativeBinomialDistribution.cs new file mode 100644 index 00000000..9c141086 --- /dev/null +++ b/src/Examples/DiscreteDistributions/NegativeBinomialDistribution.cs @@ -0,0 +1,149 @@ +// +// 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. +// + +namespace Examples.DiscreteDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// NegativeBinomial distribution example + /// + public class NegativeBinomialDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "NegativeBinomial distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "NegativeBinomial distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// NegativeBinomial distribution + 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); + } + } +} diff --git a/src/Examples/DiscreteDistributions/PoissonDistribution.cs b/src/Examples/DiscreteDistributions/PoissonDistribution.cs new file mode 100644 index 00000000..de5c81d7 --- /dev/null +++ b/src/Examples/DiscreteDistributions/PoissonDistribution.cs @@ -0,0 +1,154 @@ +// +// 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. +// + +namespace Examples.DiscreteDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// Poisson distribution example + /// + public class PoissonDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "Poisson distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Poisson distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// Poisson distribution + 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); + } + } +} diff --git a/src/Examples/DiscreteDistributions/ZipfDistribution.cs b/src/Examples/DiscreteDistributions/ZipfDistribution.cs new file mode 100644 index 00000000..0147d73b --- /dev/null +++ b/src/Examples/DiscreteDistributions/ZipfDistribution.cs @@ -0,0 +1,152 @@ +// +// 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. +// + +namespace Examples.DiscreteDistributions +{ + using System; + using MathNet.Numerics.Distributions; + + /// + /// Zipf distribution example + /// + public class ZipfDistribution : IExample + { + /// + /// Gets the name of this example + /// + /// + public string Name + { + get + { + return "Zipf distribution"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Zipf distribution properties and samples generating examples"; + } + } + + /// + /// Run example + /// + /// Zipf distribution + 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); + } + } +} diff --git a/src/Examples/Examples.csproj b/src/Examples/Examples.csproj index af531ba3..08dd0b3e 100644 --- a/src/Examples/Examples.csproj +++ b/src/Examples/Examples.csproj @@ -68,11 +68,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -87,6 +127,17 @@ + + + + + + + + + + + @@ -111,6 +162,7 @@ Numerics + the calculation is considered converged + var residualStopCriterium = new ResidualStopCriterium(1e-10); + + // Create monitor with defined stop criteriums + var monitor = new Iterator(new IIterationStopCriterium[] { 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(); + } + } +} diff --git a/src/Examples/LinearAlgebra/IterativeSolvers/CompositeSolverExample.cs b/src/Examples/LinearAlgebra/IterativeSolvers/CompositeSolverExample.cs new file mode 100644 index 00000000..4864de07 --- /dev/null +++ b/src/Examples/LinearAlgebra/IterativeSolvers/CompositeSolverExample.cs @@ -0,0 +1,208 @@ +// +// 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. +// + +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; + + /// + /// Сomposite matrix solver + /// + public class CompositeSolverExample : IExample + { + /// + /// Gets the name of this example + /// + public string Name + { + get + { + return "Composite matrix solver"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Solve linear equation using composite matrix solver. The actual solver is made by a sequence of matrix solvers"; + } + } + + /// + /// Run example + /// + 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[] { iterationCountStopCriterium, residualStopCriterium }); + + // Load all suitable solvers from current assembly. Below in this example, there is user-defined solver + // "class UserBiCgStab : IIterativeSolverSetup" which uses regular BiCgStab solver. But user may create any other solver + // and solver setup classes which implement IIterativeSolverSetup 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(); + } + } + + /// + /// Sample of user-defined solver setup + /// + public class UserBiCgStab : IIterativeSolverSetup + { + /// + /// Gets the type of the solver that will be created by this setup object. + /// + public Type SolverType + { + get + { + return null; + } + } + + /// + /// Gets type of preconditioner, if any, that will be created by this setup object. + /// + public Type PreconditionerType + { + get + { + return null; + } + } + + /// + /// Creates a fully functional iterative solver with the default settings + /// given by this setup. + /// + /// A new . + public IIterativeSolver CreateNew() + { + return new BiCgStab(); + } + + /// + /// Gets the relative speed of the solver. + /// + /// Returns a value between 0 and 1, inclusive. + public double SolutionSpeed + { + get + { + return 0.99; + } + } + + /// + /// Gets the relative reliability of the solver. + /// + /// Returns a value between 0 and 1 inclusive. + public double Reliability + { + get + { + return 0.99; + } + } + } +} diff --git a/src/Examples/LinearAlgebra/IterativeSolvers/GpBiCgSolver.cs b/src/Examples/LinearAlgebra/IterativeSolvers/GpBiCgSolver.cs new file mode 100644 index 00000000..675b6a8f --- /dev/null +++ b/src/Examples/LinearAlgebra/IterativeSolvers/GpBiCgSolver.cs @@ -0,0 +1,139 @@ +// +// 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. +// + +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; + + /// + /// GpBiCg Iterative solver + /// + public class GpBiCgSolver : IExample + { + /// + /// Gets the name of this example + /// + public string Name + { + get + { + return "Generalized Product Bi-Conjugate Gradient iterative solver"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Solve linear equation using Generalized Product Bi-Conjugate Gradient (GPBiCG) solver"; + } + } + + /// + /// Run example + /// + 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[] { 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(); + } + } +} diff --git a/src/Examples/LinearAlgebra/IterativeSolvers/MlkBiCgStabSolver.cs b/src/Examples/LinearAlgebra/IterativeSolvers/MlkBiCgStabSolver.cs new file mode 100644 index 00000000..8a56f3bf --- /dev/null +++ b/src/Examples/LinearAlgebra/IterativeSolvers/MlkBiCgStabSolver.cs @@ -0,0 +1,140 @@ +// +// 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. +// + +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; + + /// + /// Multiple-Lanczos Bi-Conjugate Gradient stabilized Iterative solver + /// + /// + public class MlkBiCgStabSolver : IExample + { + /// + /// Gets the name of this example + /// + public string Name + { + get + { + return "Multiple-Lanczos Bi-Conjugate Gradient Stabilized iterative solver"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Solve linear equation using Multiple-Lanczos Bi-Conjugate Gradient stabilized (ML(k)-BiCGStab) solver"; + } + } + + /// + /// Run example + /// + 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[] { 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(); + } + } +} diff --git a/src/Examples/LinearAlgebra/IterativeSolvers/TFQMRSolver.cs b/src/Examples/LinearAlgebra/IterativeSolvers/TFQMRSolver.cs new file mode 100644 index 00000000..4938acb8 --- /dev/null +++ b/src/Examples/LinearAlgebra/IterativeSolvers/TFQMRSolver.cs @@ -0,0 +1,140 @@ +// +// 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. +// + +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; + + /// + /// Transpose Free Quasi-Minimal Residual iterative solver + /// + /// + public class TFQMRSolver : IExample + { + /// + /// Gets the name of this example + /// + public string Name + { + get + { + return "Transpose Free Quasi-Minimal Residual iterative solver"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Solve linear equation using Transpose Free Quasi-Minimal Residual (TFQMR) iterative solver"; + } + } + + /// + /// Run example + /// + 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[] { 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(); + } + } +} diff --git a/src/Examples/NumberTheory.cs b/src/Examples/NumberTheory.cs new file mode 100644 index 00000000..357c0fce --- /dev/null +++ b/src/Examples/NumberTheory.cs @@ -0,0 +1,117 @@ +// +// 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. +// + +namespace Examples +{ + using System; + using MathNet.Numerics.NumberTheory; + + /// + /// Number theory utility functions + /// + public class NumberTheory : IExample + { + /// + /// Gets the name of this example + /// + public string Name + { + get + { + return "Number theory utility functions"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Usage of the number theory utility functions and extention methods"; + } + } + + /// + /// Run example + /// + 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(); + } + } +} diff --git a/src/Examples/RandomNumberGeneration.cs b/src/Examples/RandomNumberGeneration.cs new file mode 100644 index 00000000..1e4e08ef --- /dev/null +++ b/src/Examples/RandomNumberGeneration.cs @@ -0,0 +1,191 @@ +// +// 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. +// + +namespace Examples +{ + using System; + using MathNet.Numerics.Random; + + /// + /// Random number generation + /// + /// Random number generation + public class RandomNumberGeneration : IExample + { + /// + /// Gets the name of this example + /// + public string Name + { + get + { + return "Random number generation"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Usage examples of random number generators (RNG)"; + } + } + + /// + /// Run example + /// + /// Random number generation + /// Linear congruential generator + /// Mersenne twister + /// Lagged Fibonacci generator + /// Xorshift + 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(); + } + } +} diff --git a/src/Examples/Sampling/Chebyshev.cs b/src/Examples/Sampling/Chebyshev.cs new file mode 100644 index 00000000..427614e5 --- /dev/null +++ b/src/Examples/Sampling/Chebyshev.cs @@ -0,0 +1,96 @@ +// +// 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. +// + +namespace Examples.Sampling +{ + using System; + using MathNet.Numerics.Sampling; + + /// + /// Example of generic function sampling and quantization provider + /// + public class Chebyshev : IExample + { + /// + /// Gets the name of this example + /// + public string Name + { + get + { + return "Sampling - Chebyshev"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Samples a function at the roots of the Chebyshev polynomial"; + } + } + + /// + /// Run example + /// + 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(); + } + + /// + /// Fucntion f(x) = (x * x) / 2 + /// + /// Input value + /// Calculation result + public double Function(double x) + { + return Math.Pow(x, 2) / 2; + } + } +} diff --git a/src/Examples/Sampling/Equidistant.cs b/src/Examples/Sampling/Equidistant.cs new file mode 100644 index 00000000..b0a6e3c8 --- /dev/null +++ b/src/Examples/Sampling/Equidistant.cs @@ -0,0 +1,127 @@ +// +// 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. +// + +namespace Examples.Sampling +{ + using System; + using MathNet.Numerics.Sampling; + + /// + /// Example of generic function sampling and quantization provider + /// + public class Equidistant : IExample + { + /// + /// Gets the name of this example + /// + public string Name + { + get + { + return "Sampling - Equidistant"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Samples a function equidistant"; + } + } + + /// + /// Run example + /// + 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(); + } + + /// + /// Fucntion f(x) = (x * x) / 2 + /// + /// Input value + /// Calculation result + public double Function(double x) + { + return Math.Pow(x, 2) / 2; + } + } +} diff --git a/src/Examples/Sampling/Random.cs b/src/Examples/Sampling/Random.cs new file mode 100644 index 00000000..c556e2ab --- /dev/null +++ b/src/Examples/Sampling/Random.cs @@ -0,0 +1,131 @@ +// +// 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. +// + +namespace Examples.Sampling +{ + using System; + using MathNet.Numerics.Distributions; + using MathNet.Numerics.Sampling; + + /// + /// Example of generic function sampling and quantization provider + /// + public class Random : IExample + { + /// + /// Gets the name of this example + /// + public string Name + { + get + { + return "Sampling - Random"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Samples a function randomly with the provided distribution"; + } + } + + /// + /// Run example + /// + 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(); + } + + /// + /// Fucntion f(x, y) = (x * y) / 2 + /// + /// Input value + /// Calculation result + public double Function(double x) + { + return Math.Pow(x, 2) / 2; + } + + /// + /// Fucntion f(x,y) = (x * y) / 2 + /// + /// X input value + /// Y input value + /// Calculation result + public double TwoDomainFunction(double x, double y) + { + return (x * y) / 2; + } + } +} diff --git a/src/Examples/SpecialFunctions/Beta.cs b/src/Examples/SpecialFunctions/Beta.cs new file mode 100644 index 00000000..2087fc1b --- /dev/null +++ b/src/Examples/SpecialFunctions/Beta.cs @@ -0,0 +1,96 @@ +// +// 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. +// +namespace Examples.SpecialFunctions +{ + using System; + using MathNet.Numerics; + + /// + /// Special Functions: Beta + /// + /// + public class Beta : IExample + { + /// + /// Gets the name of this example + /// + public string Name + { + get + { + return "Special Functions: Beta"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Beta, incomplete Beta, regularized Beta"; + } + } + + /// + /// Run example + /// + /// Beta function + 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(); + } + } +} diff --git a/src/Examples/SpecialFunctions/Common.cs b/src/Examples/SpecialFunctions/Common.cs new file mode 100644 index 00000000..8f842e88 --- /dev/null +++ b/src/Examples/SpecialFunctions/Common.cs @@ -0,0 +1,101 @@ +// +// 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. +// +namespace Examples.SpecialFunctions +{ + using System; + using MathNet.Numerics; + + /// + /// Special Functions + /// + /// + /// + public class Common : IExample + { + /// + /// Gets the name of this example + /// + public string Name + { + get + { + return "Special Functions"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Harmonic, DiGamma, Logit, Logistic"; + } + } + + /// + /// Run example + /// + /// Digamma function + /// Harmonic number + /// Generalized harmonic numbers + /// Logistic function + /// Logit function + 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(); + } + } +} diff --git a/src/Examples/SpecialFunctions/ErrorFunction.cs b/src/Examples/SpecialFunctions/ErrorFunction.cs new file mode 100644 index 00000000..ae6537ce --- /dev/null +++ b/src/Examples/SpecialFunctions/ErrorFunction.cs @@ -0,0 +1,129 @@ +// +// 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. +// +namespace Examples.SpecialFunctions +{ + using System; + using MathNet.Numerics; + using MathNet.Numerics.Sampling; + + /// + /// Special Functions: error functions + /// + public class ErrorFunction : IExample + { + /// + /// Gets the name of this example + /// + public string Name + { + get + { + return "Special Functions: error functions"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Error function (Gauss error function or probability integral)"; + } + } + + /// + /// Run example + /// + /// Error function + 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(); + } + } +} diff --git a/src/Examples/SpecialFunctions/Factorial.cs b/src/Examples/SpecialFunctions/Factorial.cs new file mode 100644 index 00000000..750eef65 --- /dev/null +++ b/src/Examples/SpecialFunctions/Factorial.cs @@ -0,0 +1,95 @@ +// +// 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. +// +namespace Examples.SpecialFunctions +{ + using System; + using MathNet.Numerics; + + /// + /// Special Functions: Factorial + /// + /// + /// + /// + public class Factorial : IExample + { + /// + /// Gets the name of this example + /// + public string Name + { + get + { + return "Special Functions: Factorial"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Factorial, Binomial, Multinomial"; + } + } + + /// + /// Run example + /// + /// Factorial + /// Binomial coefficient + /// Multinomial coefficients + 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(); + } + } +} diff --git a/src/Examples/SpecialFunctions/Gamma.cs b/src/Examples/SpecialFunctions/Gamma.cs new file mode 100644 index 00000000..c6aa79de --- /dev/null +++ b/src/Examples/SpecialFunctions/Gamma.cs @@ -0,0 +1,116 @@ +// +// 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. +// +namespace Examples.SpecialFunctions +{ + using System; + using MathNet.Numerics; + + /// + /// Special Functions: Gamma + /// + /// + public class Gamma : IExample + { + /// + /// Gets the name of this example + /// + public string Name + { + get + { + return "Special Functions: Gamma"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Gamma, incomplete Gamma, regularized Gamma"; + } + } + + /// + /// Run example + /// + /// Gamma function + 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(); + } + } +} diff --git a/src/Examples/SpecialFunctions/Stability.cs b/src/Examples/SpecialFunctions/Stability.cs new file mode 100644 index 00000000..684015bd --- /dev/null +++ b/src/Examples/SpecialFunctions/Stability.cs @@ -0,0 +1,80 @@ +// +// 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. +// +namespace Examples.SpecialFunctions +{ + using System; + using MathNet.Numerics; + + /// + /// Special Functions: Stability + /// + public class Stability : IExample + { + /// + /// Gets the name of this example + /// + public string Name + { + get + { + return "Special Functions: Stability"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Exponential, Hypotenuse, Series"; + } + } + + /// + /// Run example + /// + /// Hypotenuse + 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(); + } + } +} diff --git a/src/Examples/Statistics.cs b/src/Examples/Statistics.cs new file mode 100644 index 00000000..40a10ea6 --- /dev/null +++ b/src/Examples/Statistics.cs @@ -0,0 +1,133 @@ +// +// 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. +// + +namespace Examples +{ + using System; + using MathNet.Numerics.Distributions; + using MathNet.Numerics.Sampling; + using MathNet.Numerics.Statistics; + + /// + /// Statistics on set of data + /// + public class Statistics : IExample + { + /// + /// Gets the name of this example + /// + public string Name + { + get + { + return "Statistics"; + } + } + + /// + /// Gets the description of this example + /// + public string Description + { + get + { + return "Basic statistics on set of data, correlation"; + } + } + + /// + /// Run example + /// + /// Pearson product-moment correlation coefficient + 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(); + } + } +} diff --git a/src/Numerics/Distributions/Continuous/Chi.cs b/src/Numerics/Distributions/Continuous/Chi.cs index 5bd6d011..62c7f441 100644 --- a/src/Numerics/Distributions/Continuous/Chi.cs +++ b/src/Numerics/Distributions/Continuous/Chi.cs @@ -317,7 +317,7 @@ namespace MathNet.Numerics.Distributions var n = (int)_dof; 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); diff --git a/src/Numerics/Distributions/Continuous/ChiSquare.cs b/src/Numerics/Distributions/Continuous/ChiSquare.cs index 9987f903..5d88621a 100644 --- a/src/Numerics/Distributions/Continuous/ChiSquare.cs +++ b/src/Numerics/Distributions/Continuous/ChiSquare.cs @@ -278,7 +278,7 @@ namespace MathNet.Numerics.Distributions var n = (int)dof; 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; diff --git a/src/Numerics/Distributions/Discrete/Hypergeometric.cs b/src/Numerics/Distributions/Discrete/Hypergeometric.cs index 209e7abc..68ad0679 100644 --- a/src/Numerics/Distributions/Discrete/Hypergeometric.cs +++ b/src/Numerics/Distributions/Discrete/Hypergeometric.cs @@ -366,8 +366,9 @@ namespace MathNet.Numerics.Distributions } size--; + n--; } - while (1 < n); + while (0 < n); return x; } diff --git a/src/Numerics/Interpolation/Algorithms/BulirschStoerRationalInterpolation.cs b/src/Numerics/Interpolation/Algorithms/BulirschStoerRationalInterpolation.cs index b51e9ce5..bcfd4cec 100644 --- a/src/Numerics/Interpolation/Algorithms/BulirschStoerRationalInterpolation.cs +++ b/src/Numerics/Interpolation/Algorithms/BulirschStoerRationalInterpolation.cs @@ -168,7 +168,7 @@ namespace MathNet.Numerics.Interpolation.Algorithms double ho = (_points[i] - t) * d[i] / hp; double den = ho - c[i + 1]; - if (den == 0.0) + if (den.AlmostEqual(0.0)) { return double.NaN; // zero-div, singularity } diff --git a/src/Numerics/LinearAlgebra/Complex/Solvers/Iterative/CompositeSolver.cs b/src/Numerics/LinearAlgebra/Complex/Solvers/Iterative/CompositeSolver.cs index 0f4fca20..e70c5a95 100644 --- a/src/Numerics/LinearAlgebra/Complex/Solvers/Iterative/CompositeSolver.cs +++ b/src/Numerics/LinearAlgebra/Complex/Solvers/Iterative/CompositeSolver.cs @@ -264,6 +264,7 @@ namespace MathNet.Numerics.LinearAlgebra.Complex.Solvers.Iterative var interfaceTypes = new List(); foreach (var type in assembly.GetTypes().Where(type => (!type.IsAbstract && !type.IsEnum && !type.IsInterface && type.IsVisible))) { + interfaceTypes.Clear(); interfaceTypes.AddRange(type.GetInterfaces()); if (!interfaceTypes.Any(match => typeof(IIterativeSolverSetup).IsAssignableFrom(match))) { @@ -512,6 +513,7 @@ namespace MathNet.Numerics.LinearAlgebra.Complex.Solvers.Iterative if (_iterator.Status is CalculationConverged) { // We're done + internalResult.CopyTo(result); break; } @@ -522,7 +524,7 @@ namespace MathNet.Numerics.LinearAlgebra.Complex.Solvers.Iterative { // Copy the internal result to the result vector and // continue with the calculation. - internalInput.CopyTo(input); + internalResult.CopyTo(result); } else { diff --git a/src/Numerics/LinearAlgebra/Complex32/Solvers/Iterative/CompositeSolver.cs b/src/Numerics/LinearAlgebra/Complex32/Solvers/Iterative/CompositeSolver.cs index 6c9830ae..47fcdde7 100644 --- a/src/Numerics/LinearAlgebra/Complex32/Solvers/Iterative/CompositeSolver.cs +++ b/src/Numerics/LinearAlgebra/Complex32/Solvers/Iterative/CompositeSolver.cs @@ -264,6 +264,7 @@ namespace MathNet.Numerics.LinearAlgebra.Complex32.Solvers.Iterative var interfaceTypes = new List(); foreach (var type in assembly.GetTypes().Where(type => (!type.IsAbstract && !type.IsEnum && !type.IsInterface && type.IsVisible))) { + interfaceTypes.Clear(); interfaceTypes.AddRange(type.GetInterfaces()); if (!interfaceTypes.Any(match => typeof(IIterativeSolverSetup).IsAssignableFrom(match))) { @@ -512,6 +513,7 @@ namespace MathNet.Numerics.LinearAlgebra.Complex32.Solvers.Iterative if (_iterator.Status is CalculationConverged) { // We're done + internalResult.CopyTo(result); break; } @@ -522,7 +524,7 @@ namespace MathNet.Numerics.LinearAlgebra.Complex32.Solvers.Iterative { // Copy the internal result to the result vector and // continue with the calculation. - internalInput.CopyTo(input); + internalResult.CopyTo(result); } else { diff --git a/src/Numerics/LinearAlgebra/Double/Solvers/Iterative/CompositeSolver.cs b/src/Numerics/LinearAlgebra/Double/Solvers/Iterative/CompositeSolver.cs index 49c5c8d3..e102458b 100644 --- a/src/Numerics/LinearAlgebra/Double/Solvers/Iterative/CompositeSolver.cs +++ b/src/Numerics/LinearAlgebra/Double/Solvers/Iterative/CompositeSolver.cs @@ -263,6 +263,7 @@ namespace MathNet.Numerics.LinearAlgebra.Double.Solvers.Iterative var interfaceTypes = new List(); foreach (var type in assembly.GetTypes().Where(type => (!type.IsAbstract && !type.IsEnum && !type.IsInterface && type.IsVisible))) { + interfaceTypes.Clear(); interfaceTypes.AddRange(type.GetInterfaces()); if (!interfaceTypes.Any(match => typeof(IIterativeSolverSetup).IsAssignableFrom(match))) { @@ -511,6 +512,7 @@ namespace MathNet.Numerics.LinearAlgebra.Double.Solvers.Iterative if (_iterator.Status is CalculationConverged) { // We're done + internalResult.CopyTo(result); break; } @@ -521,7 +523,7 @@ namespace MathNet.Numerics.LinearAlgebra.Double.Solvers.Iterative { // Copy the internal result to the result vector and // continue with the calculation. - internalInput.CopyTo(input); + internalResult.CopyTo(result); } else { diff --git a/src/Numerics/LinearAlgebra/Single/Solvers/Iterative/CompositeSolver.cs b/src/Numerics/LinearAlgebra/Single/Solvers/Iterative/CompositeSolver.cs index b576bf20..5dbb7d69 100644 --- a/src/Numerics/LinearAlgebra/Single/Solvers/Iterative/CompositeSolver.cs +++ b/src/Numerics/LinearAlgebra/Single/Solvers/Iterative/CompositeSolver.cs @@ -263,6 +263,7 @@ namespace MathNet.Numerics.LinearAlgebra.Single.Solvers.Iterative var interfaceTypes = new List(); foreach (var type in assembly.GetTypes().Where(type => (!type.IsAbstract && !type.IsEnum && !type.IsInterface && type.IsVisible))) { + interfaceTypes.Clear(); interfaceTypes.AddRange(type.GetInterfaces()); if (!interfaceTypes.Any(match => typeof(IIterativeSolverSetup).IsAssignableFrom(match))) { @@ -511,6 +512,7 @@ namespace MathNet.Numerics.LinearAlgebra.Single.Solvers.Iterative if (_iterator.Status is CalculationConverged) { // We're done + internalResult.CopyTo(result); break; } @@ -521,7 +523,7 @@ namespace MathNet.Numerics.LinearAlgebra.Single.Solvers.Iterative { // Copy the internal result to the result vector and // continue with the calculation. - internalInput.CopyTo(input); + internalResult.CopyTo(result); } else { diff --git a/src/Numerics/NumberTheory/IntegerTheory.cs b/src/Numerics/NumberTheory/IntegerTheory.cs index f17ecba3..93b99c19 100644 --- a/src/Numerics/NumberTheory/IntegerTheory.cs +++ b/src/Numerics/NumberTheory/IntegerTheory.cs @@ -193,7 +193,7 @@ namespace MathNet.Numerics.NumberTheory /// /// The number to very whether it's a perfect square. /// True if and only if it is a perfect square. - public static bool IsPerfectSquare(int number) + public static bool IsPerfectSquare(this int number) { if (number < 0) { @@ -220,7 +220,7 @@ namespace MathNet.Numerics.NumberTheory /// /// The number to very whether it's a perfect square. /// True if and only if it is a perfect square. - public static bool IsPerfectSquare(long number) + public static bool IsPerfectSquare(this long number) { if (number < 0) {