public override void ExecuteExample() { // <seealso cref="http://en.wikipedia.org/wiki/Cholesky_decomposition">Cholesky decomposition</seealso> MathDisplay.WriteLine("<b>Cholesky factorisation</b>"); // Format matrix output to console var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone(); formatProvider.TextInfo.ListSeparator = " "; // Create square, symmetric, positive definite matrix var matrix = DenseMatrix.OfArray(new[, ] { { 2.0, 1.0 }, { 1.0, 2.0 } }); MathDisplay.WriteLine(@"Initial square, symmetric, positive definite matrix"); MathDisplay.WriteLine(matrix.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // Perform Cholesky decomposition var cholesky = matrix.Cholesky(); MathDisplay.WriteLine(@"Perform Cholesky decomposition"); // 1. Lower triangular form of the Cholesky matrix MathDisplay.WriteLine(@"1. Lower triangular form of the Cholesky matrix"); MathDisplay.WriteLine(cholesky.Factor.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 2. Reconstruct initial matrix: A = L * LT var reconstruct = cholesky.Factor * cholesky.Factor.Transpose(); MathDisplay.WriteLine(@"2. Reconstruct initial matrix: A = L*LT"); MathDisplay.WriteLine(reconstruct.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 3. Get determinant of the matrix MathDisplay.WriteLine(@"3. Determinant of the matrix"); MathDisplay.WriteLine(cholesky.Determinant.ToString()); MathDisplay.WriteLine(); // 4. Get log determinant of the matrix MathDisplay.WriteLine(@"4. Log determinant of the matrix"); MathDisplay.WriteLine(cholesky.DeterminantLn.ToString()); MathDisplay.WriteLine(); // <seealso cref="http://en.wikipedia.org/wiki/Eigenvalue,_eigenvector_and_eigenspace">EVD decomposition</seealso> MathDisplay.WriteLine("<b>Eigenvalue, eigenvector and eigenspace factorisation</b>"); // Create square symmetric matrix matrix = DenseMatrix.OfArray(new[, ] { { 1.0, 2.0, 3.0 }, { 2.0, 1.0, 4.0 }, { 3.0, 4.0, 1.0 } }); MathDisplay.WriteLine(@"Initial square symmetric matrix"); MathDisplay.WriteLine(matrix.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // Perform eigenvalue decomposition of symmetric matrix var evd = matrix.Evd(); MathDisplay.WriteLine(@"Perform eigenvalue decomposition of symmetric matrix"); // 1. Eigen vectors MathDisplay.WriteLine(@"1. Eigen vectors"); MathDisplay.WriteLine(evd.EigenVectors.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 2. Eigen values as a complex vector MathDisplay.WriteLine(@"2. Eigen values as a complex vector"); MathDisplay.WriteLine(evd.EigenValues.ToString("N", formatProvider)); MathDisplay.WriteLine(); // 3. Eigen values as the block diagonal matrix MathDisplay.WriteLine(@"3. Eigen values as the block diagonal matrix"); MathDisplay.WriteLine(evd.D.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 4. Multiply V by its transpose VT var identity = evd.EigenVectors.TransposeAndMultiply(evd.EigenVectors); MathDisplay.WriteLine(@"4. Multiply V by its transpose VT: V*VT = I"); MathDisplay.WriteLine(identity.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 5. Reconstruct initial matrix: A = V*D*V' reconstruct = evd.EigenVectors * evd.D * evd.EigenVectors.Transpose(); MathDisplay.WriteLine(@"5. Reconstruct initial matrix: A = V*D*V'"); MathDisplay.WriteLine(reconstruct.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 6. Determinant of the matrix MathDisplay.WriteLine(@"6. Determinant of the matrix"); MathDisplay.WriteLine(evd.Determinant.ToString()); MathDisplay.WriteLine(); // 7. Rank of the matrix MathDisplay.WriteLine(@"7. Rank of the matrix"); MathDisplay.WriteLine(evd.Rank.ToString()); MathDisplay.WriteLine(); // Fill matrix by random values var rnd = new Random(1); for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { matrix[i, j] = rnd.NextDouble(); } } MathDisplay.WriteLine(@"Fill matrix by random values"); MathDisplay.WriteLine(matrix.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // Perform eigenvalue decomposition of non-symmetric matrix evd = matrix.Evd(); MathDisplay.WriteLine(@"Perform eigenvalue decomposition of non-symmetric matrix"); // 8. Eigen vectors MathDisplay.WriteLine(@"8. Eigen vectors"); MathDisplay.WriteLine(evd.EigenVectors.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 9. Eigen values as a complex vector MathDisplay.WriteLine(@"9. Eigen values as a complex vector"); MathDisplay.WriteLine(evd.EigenValues.ToString("N", formatProvider)); MathDisplay.WriteLine(); // 10. Eigen values as the block diagonal matrix MathDisplay.WriteLine(@"10. Eigen values as the block diagonal matrix"); MathDisplay.WriteLine(evd.D.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 11. Multiply A * V var av = matrix * evd.EigenVectors; MathDisplay.WriteLine(@"11. Multiply A * V"); MathDisplay.WriteLine(av.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 12. Multiply V * D var vd = evd.EigenVectors * evd.D; MathDisplay.WriteLine(@"12. Multiply V * D"); MathDisplay.WriteLine(vd.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 13. Reconstruct non-symmetriv matrix A = V * D * Vinverse reconstruct = evd.EigenVectors * evd.D * evd.EigenVectors.Inverse(); MathDisplay.WriteLine(@"13. Reconstruct non-symmetriv matrix A = V * D * Vinverse"); MathDisplay.WriteLine(reconstruct.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 14. Determinant of the matrix MathDisplay.WriteLine(@"14. Determinant of the matrix"); MathDisplay.WriteLine(evd.Determinant.ToString()); MathDisplay.WriteLine(); // 15. Rank of the matrix MathDisplay.WriteLine(@"15. Rank of the matrix"); MathDisplay.WriteLine(evd.Rank.ToString()); MathDisplay.WriteLine(); // <seealso cref="http://en.wikipedia.org/wiki/LU_decomposition">LU decomposition</seealso> // <seealso cref="http://en.wikipedia.org/wiki/Invertible_matrix">Invertible matrix</seealso> MathDisplay.WriteLine("<b>LU factorisation</b>"); // Create square matrix matrix = DenseMatrix.OfArray(new[, ] { { 1.0, 2.0 }, { 3.0, 4.0 } }); MathDisplay.WriteLine(@"Initial square matrix"); MathDisplay.WriteLine(matrix.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // Perform LU decomposition var lu = matrix.LU(); MathDisplay.WriteLine(@"Perform LU decomposition"); // 1. Lower triangular factor MathDisplay.WriteLine(@"1. Lower triangular factor"); MathDisplay.WriteLine(lu.L.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 2. Upper triangular factor MathDisplay.WriteLine(@"2. Upper triangular factor"); MathDisplay.WriteLine(lu.U.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 3. Permutations applied to LU factorization MathDisplay.WriteLine(@"3. Permutations applied to LU factorization"); for (var i = 0; i < lu.P.Dimension; i++) { if (lu.P[i] > i) { MathDisplay.WriteLine(@"Row {0} permuted with row {1}", lu.P[i], i); } } MathDisplay.WriteLine(); // 4. Reconstruct initial matrix: PA = L * U reconstruct = lu.L * lu.U; // The rows of the reconstructed matrix should be permuted to get the initial matrix reconstruct.PermuteRows(lu.P.Inverse()); MathDisplay.WriteLine(@"4. Reconstruct initial matrix: PA = L*U"); MathDisplay.WriteLine(reconstruct.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 5. Get the determinant of the matrix MathDisplay.WriteLine(@"5. Determinant of the matrix"); MathDisplay.WriteLine(lu.Determinant.ToString()); MathDisplay.WriteLine(); // 6. Get the inverse of the matrix var matrixInverse = lu.Inverse(); MathDisplay.WriteLine(@"6. Inverse of the matrix"); MathDisplay.WriteLine(matrixInverse.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 7. Matrix multiplied by its inverse identity = matrix * matrixInverse; MathDisplay.WriteLine(@"7. Matrix multiplied by its inverse "); MathDisplay.WriteLine(identity.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // QR factorization example. Any real square matrix A (m x n) may be decomposed as A = QR where Q is an // orthogonal matrix (m x m) // (its columns are orthogonal unit vectors meaning QTQ = I) and R (m x n) is an upper triangular matrix // (also called right triangular matrix). // In this example two methods for actually computing the QR decomposition presented: by means of the // Gram–Schmidt process and Householder transformations. // <seealso cref="http://reference.wolfram.com/mathematica/ref/QRDecomposition.html"/> MathDisplay.WriteLine("<b>QR factorisation</b>"); // Create 3 x 2 matrix matrix = DenseMatrix.OfArray(new[, ] { { 1.0, 2.0 }, { 3.0, 4.0 }, { 5.0, 6.0 } }); MathDisplay.WriteLine(@"Initial 3x2 matrix"); MathDisplay.WriteLine(matrix.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // Perform QR decomposition (Householder transformations) var qr = matrix.QR(); MathDisplay.WriteLine(@"QR decomposition (Householder transformations)"); // 1. Orthogonal Q matrix MathDisplay.WriteLine(@"1. Orthogonal Q matrix"); MathDisplay.WriteLine(qr.Q.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 2. Multiply Q matrix by its transpose gives identity matrix MathDisplay.WriteLine(@"2. Multiply Q matrix by its transpose gives identity matrix"); MathDisplay.WriteLine(qr.Q.TransposeAndMultiply(qr.Q).ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 3. Upper triangular factor R MathDisplay.WriteLine(@"3. Upper triangular factor R"); MathDisplay.WriteLine(qr.R.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 4. Reconstruct initial matrix: A = Q * R reconstruct = qr.Q * qr.R; MathDisplay.WriteLine(@"4. Reconstruct initial matrix: A = Q*R"); MathDisplay.WriteLine(reconstruct.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // Perform QR decomposition (Gram–Schmidt process) var gramSchmidt = matrix.GramSchmidt(); MathDisplay.WriteLine(@"QR decomposition (Gram–Schmidt process)"); // 5. Orthogonal Q matrix MathDisplay.WriteLine(@"5. Orthogonal Q matrix"); MathDisplay.WriteLine(gramSchmidt.Q.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 6. Multiply Q matrix by its transpose gives identity matrix MathDisplay.WriteLine(@"6. Multiply Q matrix by its transpose gives identity matrix"); MathDisplay.WriteLine((gramSchmidt.Q.Transpose() * gramSchmidt.Q).ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 7. Upper triangular factor R MathDisplay.WriteLine(@"7. Upper triangular factor R"); MathDisplay.WriteLine(gramSchmidt.R.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 8. Reconstruct initial matrix: A = Q * R reconstruct = gramSchmidt.Q * gramSchmidt.R; MathDisplay.WriteLine(@"8. Reconstruct initial matrix: A = Q*R"); MathDisplay.WriteLine(reconstruct.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // SVD factorization example. Suppose M is an m-by-n matrix whose entries are real numbers. // Then there exists a factorization of the form M = UΣVT where: // - U is an m-by-m unitary matrix; // - Σ is m-by-n diagonal matrix with nonnegative real numbers on the diagonal; // - VT denotes transpose of V, an n-by-n unitary matrix; // Such a factorization is called a singular-value decomposition of M. A common convention is to order the diagonal // entries Σ(i,i) in descending order. In this case, the diagonal matrix Σ is uniquely determined // by M (though the matrices U and V are not). The diagonal entries of Σ are known as the singular values of M. // <seealso cref="http://reference.wolfram.com/mathematica/ref/SingularValueDecomposition.html"/> MathDisplay.WriteLine("<b>SVD factorisation</b>"); // Create square matrix matrix = DenseMatrix.OfArray(new[, ] { { 4.0, 1.0 }, { 3.0, 2.0 } }); MathDisplay.WriteLine(@"Initial square matrix"); MathDisplay.WriteLine(matrix.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // Perform full SVD decomposition var svd = matrix.Svd(); MathDisplay.WriteLine(@"Perform full SVD decomposition"); // 1. Left singular vectors MathDisplay.WriteLine(@"1. Left singular vectors"); MathDisplay.WriteLine(svd.U.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 2. Singular values as vector MathDisplay.WriteLine(@"2. Singular values as vector"); MathDisplay.WriteLine(svd.S.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 3. Singular values as diagonal matrix MathDisplay.WriteLine(@"3. Singular values as diagonal matrix"); MathDisplay.WriteLine(svd.W.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 4. Right singular vectors MathDisplay.WriteLine(@"4. Right singular vectors"); MathDisplay.WriteLine(svd.VT.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 5. Multiply U matrix by its transpose var identinty = svd.U * svd.U.Transpose(); MathDisplay.WriteLine(@"5. Multiply U matrix by its transpose"); MathDisplay.WriteLine(identinty.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 6. Multiply V matrix by its transpose identinty = svd.VT.TransposeAndMultiply(svd.VT); MathDisplay.WriteLine(@"6. Multiply V matrix by its transpose"); MathDisplay.WriteLine(identinty.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 7. Reconstruct initial matrix: A = U*Σ*VT reconstruct = svd.U * svd.W * svd.VT; MathDisplay.WriteLine(@"7. Reconstruct initial matrix: A = U*S*VT"); MathDisplay.WriteLine(reconstruct.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 8. Condition Number of the matrix MathDisplay.WriteLine(@"8. Condition Number of the matrix"); MathDisplay.WriteLine(svd.ConditionNumber.ToString()); MathDisplay.WriteLine(); // 9. Determinant of the matrix MathDisplay.WriteLine(@"9. Determinant of the matrix"); MathDisplay.WriteLine(svd.Determinant.ToString()); MathDisplay.WriteLine(); // 10. 2-norm of the matrix MathDisplay.WriteLine(@"10. 2-norm of the matrix"); MathDisplay.WriteLine(svd.L2Norm.ToString()); MathDisplay.WriteLine(); // 11. Rank of the matrix MathDisplay.WriteLine(@"11. Rank of the matrix"); MathDisplay.WriteLine(svd.Rank.ToString()); MathDisplay.WriteLine(); // Perform partial SVD decomposition, without computing the singular U and VT vectors svd = matrix.Svd(false); MathDisplay.WriteLine(@"Perform partial SVD decomposition, without computing the singular U and VT vectors"); // 12. Singular values as vector MathDisplay.WriteLine(@"12. Singular values as vector"); MathDisplay.WriteLine(svd.S.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 13. Singular values as diagonal matrix MathDisplay.WriteLine(@"13. Singular values as diagonal matrix"); MathDisplay.WriteLine(svd.W.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 14. Access to left singular vectors when partial SVD decomposition was performed try { MathDisplay.WriteLine(@"14. Access to left singular vectors when partial SVD decomposition was performed"); MathDisplay.WriteLine(svd.U.ToString("#0.00\t", formatProvider)); } catch (Exception ex) { MathDisplay.WriteLine(ex.Message); MathDisplay.WriteLine(); } // 15. Access to right singular vectors when partial SVD decomposition was performed try { MathDisplay.WriteLine(@"15. Access to right singular vectors when partial SVD decomposition was performed"); MathDisplay.WriteLine(svd.VT.ToString("#0.00\t", formatProvider)); } catch (Exception ex) { MathDisplay.WriteLine(ex.Message); MathDisplay.WriteLine(); } }
public override void ExecuteExample() { // <a href="http://en.wikipedia.org/wiki/Binomial_distribution">Binomial distribution</a> MathDisplay.WriteLine("<b>Binomial distribution</b>"); // 1. Initialize the new instance of the Binomial distribution class with parameters P = 0.2, N = 20 var binomial = new Binomial(0.2, 20); MathDisplay.WriteLine(@"1. Initialize the new instance of the Binomial distribution class with parameters P = {0}, N = {1}", binomial.P, binomial.N); MathDisplay.WriteLine(); // 2. Distributuion properties: MathDisplay.WriteLine(@"2. {0} distributuion properties:", binomial); // Cumulative distribution function MathDisplay.WriteLine(@"{0} - Сumulative distribution at location '3'", binomial.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000")); // Probability density MathDisplay.WriteLine(@"{0} - Probability mass at location '3'", binomial.Probability(3).ToString(" #0.00000;-#0.00000")); // Log probability density MathDisplay.WriteLine(@"{0} - Log probability mass at location '3'", binomial.ProbabilityLn(3).ToString(" #0.00000;-#0.00000")); // Entropy MathDisplay.WriteLine(@"{0} - Entropy", binomial.Entropy.ToString(" #0.00000;-#0.00000")); // Largest element in the domain MathDisplay.WriteLine(@"{0} - Largest element in the domain", binomial.Maximum.ToString(" #0.00000;-#0.00000")); // Smallest element in the domain MathDisplay.WriteLine(@"{0} - Smallest element in the domain", binomial.Minimum.ToString(" #0.00000;-#0.00000")); // Mean MathDisplay.WriteLine(@"{0} - Mean", binomial.Mean.ToString(" #0.00000;-#0.00000")); // Median MathDisplay.WriteLine(@"{0} - Median", binomial.Median.ToString(" #0.00000;-#0.00000")); // Mode MathDisplay.WriteLine(@"{0} - Mode", binomial.Mode.ToString(" #0.00000;-#0.00000")); // Variance MathDisplay.WriteLine(@"{0} - Variance", binomial.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation MathDisplay.WriteLine(@"{0} - Standard deviation", binomial.StdDev.ToString(" #0.00000;-#0.00000")); // Skewness MathDisplay.WriteLine(@"{0} - Skewness", binomial.Skewness.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(); // 3. Generate 10 samples of the Binomial distribution MathDisplay.WriteLine(@"3. Generate 10 samples of the Binomial distribution"); for (var i = 0; i < 10; i++) { MathDisplay.Write(binomial.Sample().ToString("N05") + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // <a href="http://en.wikipedia.org/wiki/Bernoulli_distribution">Bernoulli distribution</a> MathDisplay.WriteLine("<b>Bernoulli distribution</b>"); // 1. Initialize the new instance of the Bernoulli distribution class with parameter P = 0.2 var bernoulli = new Bernoulli(0.2); MathDisplay.WriteLine(@"1. Initialize the new instance of the Bernoulli distribution class with parameter P = {0}", bernoulli.P); MathDisplay.WriteLine(); // 2. Distributuion properties: MathDisplay.WriteLine(@"2. {0} distributuion properties:", bernoulli); // Cumulative distribution function MathDisplay.WriteLine(@"{0} - Сumulative distribution at location '3'", bernoulli.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000")); // Probability density MathDisplay.WriteLine(@"{0} - Probability mass at location '3'", bernoulli.Probability(3).ToString(" #0.00000;-#0.00000")); // Log probability density MathDisplay.WriteLine(@"{0} - Log probability mass at location '3'", bernoulli.ProbabilityLn(3).ToString(" #0.00000;-#0.00000")); // Entropy MathDisplay.WriteLine(@"{0} - Entropy", bernoulli.Entropy.ToString(" #0.00000;-#0.00000")); // Largest element in the domain MathDisplay.WriteLine(@"{0} - Largest element in the domain", bernoulli.Maximum.ToString(" #0.00000;-#0.00000")); // Smallest element in the domain MathDisplay.WriteLine(@"{0} - Smallest element in the domain", bernoulli.Minimum.ToString(" #0.00000;-#0.00000")); // Mean MathDisplay.WriteLine(@"{0} - Mean", bernoulli.Mean.ToString(" #0.00000;-#0.00000")); // Mode MathDisplay.WriteLine(@"{0} - Mode", bernoulli.Mode.ToString(" #0.00000;-#0.00000")); // Variance MathDisplay.WriteLine(@"{0} - Variance", bernoulli.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation MathDisplay.WriteLine(@"{0} - Standard deviation", bernoulli.StdDev.ToString(" #0.00000;-#0.00000")); // Skewness MathDisplay.WriteLine(@"{0} - Skewness", bernoulli.Skewness.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(); // 3. Generate 10 samples of the Bernoulli distribution MathDisplay.WriteLine(@"3. Generate 10 samples of the Bernoulli distribution"); for (var i = 0; i < 10; i++) { MathDisplay.Write(bernoulli.Sample().ToString("N05") + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // <a href="http://en.wikipedia.org/wiki/Categorical_distribution">Categorical distribution</a> MathDisplay.WriteLine("<b>Categorical distribution</b>"); // 1. Initialize the new instance of the Categorical distribution class with parameters P = (0.1, 0.2, 0.25, 0.45) var binomialC = new Categorical(new[] { 0.1, 0.2, 0.25, 0.45 }); MathDisplay.WriteLine(@"1. Initialize the new instance of the Categorical distribution class with parameters P = (0.1, 0.2, 0.25, 0.45)"); MathDisplay.WriteLine(); // 2. Distributuion properties: MathDisplay.WriteLine(@"2. {0} distributuion properties:", binomialC); // Cumulative distribution function MathDisplay.WriteLine(@"{0} - Сumulative distribution at location '3'", binomialC.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000")); // Probability density MathDisplay.WriteLine(@"{0} - Probability mass at location '3'", binomialC.Probability(3).ToString(" #0.00000;-#0.00000")); // Log probability density MathDisplay.WriteLine(@"{0} - Log probability mass at location '3'", binomialC.ProbabilityLn(3).ToString(" #0.00000;-#0.00000")); // Entropy MathDisplay.WriteLine(@"{0} - Entropy", binomialC.Entropy.ToString(" #0.00000;-#0.00000")); // Largest element in the domain MathDisplay.WriteLine(@"{0} - Largest element in the domain", binomialC.Maximum.ToString(" #0.00000;-#0.00000")); // Smallest element in the domain MathDisplay.WriteLine(@"{0} - Smallest element in the domain", binomialC.Minimum.ToString(" #0.00000;-#0.00000")); // Mean MathDisplay.WriteLine(@"{0} - Mean", binomialC.Mean.ToString(" #0.00000;-#0.00000")); // Median MathDisplay.WriteLine(@"{0} - Median", binomialC.Median.ToString(" #0.00000;-#0.00000")); // Variance MathDisplay.WriteLine(@"{0} - Variance", binomialC.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation MathDisplay.WriteLine(@"{0} - Standard deviation", binomialC.StdDev.ToString(" #0.00000;-#0.00000")); // 3. Generate 10 samples of the Categorical distribution MathDisplay.WriteLine(@"3. Generate 10 samples of the Categorical distribution"); for (var i = 0; i < 10; i++) { MathDisplay.Write(binomialC.Sample().ToString("N05") + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // <a href="http://en.wikipedia.org/wiki/Conway%E2%80%93Maxwell%E2%80%93Poisson_distribution">ConwayMaxwellPoisson distribution</a> MathDisplay.WriteLine("<b>Conway Maxwell Poisson distribution</b>"); // 1. Initialize the new instance of the ConwayMaxwellPoisson distribution class with parameters Lambda = 2, Nu = 1 var conwayMaxwellPoisson = new ConwayMaxwellPoisson(2, 1); MathDisplay.WriteLine(@"1. Initialize the new instance of the ConwayMaxwellPoisson distribution class with parameters Lambda = {0}, Nu = {1}", conwayMaxwellPoisson.Lambda, conwayMaxwellPoisson.Nu); MathDisplay.WriteLine(); // 2. Distributuion properties: MathDisplay.WriteLine(@"2. {0} distributuion properties:", conwayMaxwellPoisson); // Cumulative distribution function MathDisplay.WriteLine(@"{0} - Сumulative distribution at location '3'", conwayMaxwellPoisson.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000")); // Probability density MathDisplay.WriteLine(@"{0} - Probability mass at location '3'", conwayMaxwellPoisson.Probability(3).ToString(" #0.00000;-#0.00000")); // Log probability density MathDisplay.WriteLine(@"{0} - Log probability mass at location '3'", conwayMaxwellPoisson.ProbabilityLn(3).ToString(" #0.00000;-#0.00000")); // Smallest element in the domain MathDisplay.WriteLine(@"{0} - Smallest element in the domain", conwayMaxwellPoisson.Minimum.ToString(" #0.00000;-#0.00000")); // Mean MathDisplay.WriteLine(@"{0} - Mean", conwayMaxwellPoisson.Mean.ToString(" #0.00000;-#0.00000")); // Variance MathDisplay.WriteLine(@"{0} - Variance", conwayMaxwellPoisson.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation MathDisplay.WriteLine(@"{0} - Standard deviation", conwayMaxwellPoisson.StdDev.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(); // 3. Generate 10 samples of the ConwayMaxwellPoisson distribution MathDisplay.WriteLine(@"3. Generate 10 samples of the ConwayMaxwellPoisson distribution"); for (var i = 0; i < 10; i++) { MathDisplay.Write(conwayMaxwellPoisson.Sample().ToString("N05") + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // <a href="http://en.wikipedia.org/wiki/Discrete_uniform">DiscreteUniform distribution</a> MathDisplay.WriteLine("<b>Discrete Uniform distribution</b>"); // 1. Initialize the new instance of the DiscreteUniform distribution class with parameters LowerBound = 2, UpperBound = 10 var discreteUniform = new DiscreteUniform(2, 10); MathDisplay.WriteLine(@"1. Initialize the new instance of the DiscreteUniform distribution class with parameters LowerBound = {0}, UpperBound = {1}", discreteUniform.LowerBound, discreteUniform.UpperBound); MathDisplay.WriteLine(); // 2. Distributuion properties: MathDisplay.WriteLine(@"2. {0} distributuion properties:", discreteUniform); // Cumulative distribution function MathDisplay.WriteLine(@"{0} - Сumulative distribution at location '3'", discreteUniform.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000")); // Probability density MathDisplay.WriteLine(@"{0} - Probability mass at location '3'", discreteUniform.Probability(3).ToString(" #0.00000;-#0.00000")); // Log probability density MathDisplay.WriteLine(@"{0} - Log probability mass at location '3'", discreteUniform.ProbabilityLn(3).ToString(" #0.00000;-#0.00000")); // Entropy MathDisplay.WriteLine(@"{0} - Entropy", discreteUniform.Entropy.ToString(" #0.00000;-#0.00000")); // Largest element in the domain MathDisplay.WriteLine(@"{0} - Largest element in the domain", discreteUniform.Maximum.ToString(" #0.00000;-#0.00000")); // Smallest element in the domain MathDisplay.WriteLine(@"{0} - Smallest element in the domain", discreteUniform.Minimum.ToString(" #0.00000;-#0.00000")); // Mean MathDisplay.WriteLine(@"{0} - Mean", discreteUniform.Mean.ToString(" #0.00000;-#0.00000")); // Median MathDisplay.WriteLine(@"{0} - Median", discreteUniform.Median.ToString(" #0.00000;-#0.00000")); // Mode MathDisplay.WriteLine(@"{0} - Mode", discreteUniform.Mode.ToString(" #0.00000;-#0.00000")); // Variance MathDisplay.WriteLine(@"{0} - Variance", discreteUniform.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation MathDisplay.WriteLine(@"{0} - Standard deviation", discreteUniform.StdDev.ToString(" #0.00000;-#0.00000")); // Skewness MathDisplay.WriteLine(@"{0} - Skewness", discreteUniform.Skewness.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(); // 3. Generate 10 samples of the DiscreteUniform distribution MathDisplay.WriteLine(@"3. Generate 10 samples of the DiscreteUniform distribution"); for (var i = 0; i < 10; i++) { MathDisplay.Write(discreteUniform.Sample().ToString("N05") + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // <a href="http://en.wikipedia.org/wiki/Geometric_distribution">Geometric distribution</a> MathDisplay.WriteLine("<b>Geometric distribution</b>"); // 1. Initialize the new instance of the Geometric distribution class with parameter P = 0.2 var geometric = new Geometric(0.2); MathDisplay.WriteLine(@"1. Initialize the new instance of the Geometric distribution class with parameter P = {0}", geometric.P); MathDisplay.WriteLine(); // 2. Distributuion properties: MathDisplay.WriteLine(@"2. {0} distributuion properties:", geometric); // Cumulative distribution function MathDisplay.WriteLine(@"{0} - Сumulative distribution at location '3'", geometric.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000")); // Probability density MathDisplay.WriteLine(@"{0} - Probability mass at location '3'", geometric.Probability(3).ToString(" #0.00000;-#0.00000")); // Log probability density MathDisplay.WriteLine(@"{0} - Log probability mass at location '3'", geometric.ProbabilityLn(3).ToString(" #0.00000;-#0.00000")); // Entropy MathDisplay.WriteLine(@"{0} - Entropy", geometric.Entropy.ToString(" #0.00000;-#0.00000")); // Largest element in the domain MathDisplay.WriteLine(@"{0} - Largest element in the domain", geometric.Maximum.ToString(" #0.00000;-#0.00000")); // Smallest element in the domain MathDisplay.WriteLine(@"{0} - Smallest element in the domain", geometric.Minimum.ToString(" #0.00000;-#0.00000")); // Mean MathDisplay.WriteLine(@"{0} - Mean", geometric.Mean.ToString(" #0.00000;-#0.00000")); // Median MathDisplay.WriteLine(@"{0} - Median", geometric.Median.ToString(" #0.00000;-#0.00000")); // Mode MathDisplay.WriteLine(@"{0} - Mode", geometric.Mode.ToString(" #0.00000;-#0.00000")); // Variance MathDisplay.WriteLine(@"{0} - Variance", geometric.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation MathDisplay.WriteLine(@"{0} - Standard deviation", geometric.StdDev.ToString(" #0.00000;-#0.00000")); // Skewness MathDisplay.WriteLine(@"{0} - Skewness", geometric.Skewness.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(); // 3. Generate 10 samples of the Geometric distribution MathDisplay.WriteLine(@"3. Generate 10 samples of the Geometric distribution"); for (var i = 0; i < 10; i++) { MathDisplay.Write(geometric.Sample().ToString("N05") + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // <a href="http://en.wikipedia.org/wiki/Hypergeometric_distribution">Hypergeometric distribution</a> MathDisplay.WriteLine("<b>Hypergeometric distribution</b>"); // 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); MathDisplay.WriteLine(@"1. Initialize the new instance of the Hypergeometric distribution class with parameters Population = {0}, Success = {1}, Draws = {2}", hypergeometric.Population, hypergeometric.Success, hypergeometric.Draws); MathDisplay.WriteLine(); // 2. Distributuion properties: MathDisplay.WriteLine(@"2. {0} distributuion properties:", hypergeometric); // Cumulative distribution function MathDisplay.WriteLine(@"{0} - Сumulative distribution at location '3'", hypergeometric.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000")); // Probability density MathDisplay.WriteLine(@"{0} - Probability mass at location '3'", hypergeometric.Probability(3).ToString(" #0.00000;-#0.00000")); // Log probability density MathDisplay.WriteLine(@"{0} - Log probability mass at location '3'", hypergeometric.ProbabilityLn(3).ToString(" #0.00000;-#0.00000")); // Largest element in the domain MathDisplay.WriteLine(@"{0} - Largest element in the domain", hypergeometric.Maximum.ToString(" #0.00000;-#0.00000")); // Smallest element in the domain MathDisplay.WriteLine(@"{0} - Smallest element in the domain", hypergeometric.Minimum.ToString(" #0.00000;-#0.00000")); // Mean MathDisplay.WriteLine(@"{0} - Mean", hypergeometric.Mean.ToString(" #0.00000;-#0.00000")); // Mode MathDisplay.WriteLine(@"{0} - Mode", hypergeometric.Mode.ToString(" #0.00000;-#0.00000")); // Variance MathDisplay.WriteLine(@"{0} - Variance", hypergeometric.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation MathDisplay.WriteLine(@"{0} - Standard deviation", hypergeometric.StdDev.ToString(" #0.00000;-#0.00000")); // Skewness MathDisplay.WriteLine(@"{0} - Skewness", hypergeometric.Skewness.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(); // 3. Generate 10 samples of the Hypergeometric distribution MathDisplay.WriteLine(@"3. Generate 10 samples of the Hypergeometric distribution"); for (var i = 0; i < 10; i++) { MathDisplay.Write(hypergeometric.Sample().ToString("N05") + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // <a href="http://en.wikipedia.org/wiki/Negative_binomial">NegativeBinomial distribution</a> MathDisplay.WriteLine("<b>Negative Binomial distribution</b>"); // 1. Initialize the new instance of the NegativeBinomial distribution class with parameters P = 0.2, R = 20 var negativeBinomial = new NegativeBinomial(20, 0.2); MathDisplay.WriteLine(@"1. Initialize the new instance of the NegativeBinomial distribution class with parameters P = {0}, N = {1}", negativeBinomial.P, negativeBinomial.R); MathDisplay.WriteLine(); // 2. Distributuion properties: MathDisplay.WriteLine(@"2. {0} distributuion properties:", negativeBinomial); // Cumulative distribution function MathDisplay.WriteLine(@"{0} - Сumulative distribution at location '3'", negativeBinomial.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000")); // Probability density MathDisplay.WriteLine(@"{0} - Probability mass at location '3'", negativeBinomial.Probability(3).ToString(" #0.00000;-#0.00000")); // Log probability density MathDisplay.WriteLine(@"{0} - Log probability mass at location '3'", negativeBinomial.ProbabilityLn(3).ToString(" #0.00000;-#0.00000")); // Largest element in the domain MathDisplay.WriteLine(@"{0} - Largest element in the domain", negativeBinomial.Maximum.ToString(" #0.00000;-#0.00000")); // Smallest element in the domain MathDisplay.WriteLine(@"{0} - Smallest element in the domain", negativeBinomial.Minimum.ToString(" #0.00000;-#0.00000")); // Mean MathDisplay.WriteLine(@"{0} - Mean", negativeBinomial.Mean.ToString(" #0.00000;-#0.00000")); // Mode MathDisplay.WriteLine(@"{0} - Mode", negativeBinomial.Mode.ToString(" #0.00000;-#0.00000")); // Variance MathDisplay.WriteLine(@"{0} - Variance", negativeBinomial.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation MathDisplay.WriteLine(@"{0} - Standard deviation", negativeBinomial.StdDev.ToString(" #0.00000;-#0.00000")); // Skewness MathDisplay.WriteLine(@"{0} - Skewness", negativeBinomial.Skewness.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(); // 3. Generate 10 samples of the NegativeBinomial distribution MathDisplay.WriteLine(@"3. Generate 10 samples of the NegativeBinomial distribution"); for (var i = 0; i < 10; i++) { MathDisplay.Write(negativeBinomial.Sample().ToString("N05") + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // <a href="http://en.wikipedia.org/wiki/Poisson_distribution">Poisson distribution</a> MathDisplay.WriteLine("<b>Poisson distribution</b>"); // 1. Initialize the new instance of the Poisson distribution class with parameter Lambda = 1 var poisson = new Poisson(1); MathDisplay.WriteLine(@"1. Initialize the new instance of the Poisson distribution class with parameter Lambda = {0}", poisson.Lambda); MathDisplay.WriteLine(); // 2. Distributuion properties: MathDisplay.WriteLine(@"2. {0} distributuion properties:", poisson); // Cumulative distribution function MathDisplay.WriteLine(@"{0} - Сumulative distribution at location '3'", poisson.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000")); // Probability density MathDisplay.WriteLine(@"{0} - Probability mass at location '3'", poisson.Probability(3).ToString(" #0.00000;-#0.00000")); // Log probability density MathDisplay.WriteLine(@"{0} - Log probability mass at location '3'", poisson.ProbabilityLn(3).ToString(" #0.00000;-#0.00000")); // Entropy MathDisplay.WriteLine(@"{0} - Entropy", poisson.Entropy.ToString(" #0.00000;-#0.00000")); // Largest element in the domain MathDisplay.WriteLine(@"{0} - Largest element in the domain", poisson.Maximum.ToString(" #0.00000;-#0.00000")); // Smallest element in the domain MathDisplay.WriteLine(@"{0} - Smallest element in the domain", poisson.Minimum.ToString(" #0.00000;-#0.00000")); // Mean MathDisplay.WriteLine(@"{0} - Mean", poisson.Mean.ToString(" #0.00000;-#0.00000")); // Median MathDisplay.WriteLine(@"{0} - Median", poisson.Median.ToString(" #0.00000;-#0.00000")); // Mode MathDisplay.WriteLine(@"{0} - Mode", poisson.Mode.ToString(" #0.00000;-#0.00000")); // Variance MathDisplay.WriteLine(@"{0} - Variance", poisson.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation MathDisplay.WriteLine(@"{0} - Standard deviation", poisson.StdDev.ToString(" #0.00000;-#0.00000")); // Skewness MathDisplay.WriteLine(@"{0} - Skewness", poisson.Skewness.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(); // 3. Generate 10 samples of the Poisson distribution MathDisplay.WriteLine(@"3. Generate 10 samples of the Poisson distribution"); for (var i = 0; i < 10; i++) { MathDisplay.Write(poisson.Sample().ToString("N05") + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // <a href="http://en.wikipedia.org/wiki/Zipf_distribution">Zipf distribution</a> MathDisplay.WriteLine("<b>Zipf distribution</b>"); // 1. Initialize the new instance of the Zipf distribution class with parameters S = 5, N = 10 var zipf = new Zipf(5, 10); MathDisplay.WriteLine(@"1. Initialize the new instance of the Zipf distribution class with parameters S = {0}, N = {1}", zipf.S, zipf.N); MathDisplay.WriteLine(); // 2. Distributuion properties: MathDisplay.WriteLine(@"2. {0} distributuion properties:", zipf); // Cumulative distribution function MathDisplay.WriteLine(@"{0} - Сumulative distribution at location '3'", zipf.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000")); // Probability density MathDisplay.WriteLine(@"{0} - Probability mass at location '3'", zipf.Probability(3).ToString(" #0.00000;-#0.00000")); // Log probability density MathDisplay.WriteLine(@"{0} - Log probability mass at location '3'", zipf.ProbabilityLn(3).ToString(" #0.00000;-#0.00000")); // Entropy MathDisplay.WriteLine(@"{0} - Entropy", zipf.Entropy.ToString(" #0.00000;-#0.00000")); // Largest element in the domain MathDisplay.WriteLine(@"{0} - Largest element in the domain", zipf.Maximum.ToString(" #0.00000;-#0.00000")); // Smallest element in the domain MathDisplay.WriteLine(@"{0} - Smallest element in the domain", zipf.Minimum.ToString(" #0.00000;-#0.00000")); // Mean MathDisplay.WriteLine(@"{0} - Mean", zipf.Mean.ToString(" #0.00000;-#0.00000")); // Mode MathDisplay.WriteLine(@"{0} - Mode", zipf.Mode.ToString(" #0.00000;-#0.00000")); // Variance MathDisplay.WriteLine(@"{0} - Variance", zipf.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation MathDisplay.WriteLine(@"{0} - Standard deviation", zipf.StdDev.ToString(" #0.00000;-#0.00000")); // Skewness MathDisplay.WriteLine(@"{0} - Skewness", zipf.Skewness.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(); // 3. Generate 10 samples of the Zipf distribution MathDisplay.WriteLine(@"3. Generate 10 samples of the Zipf distribution"); for (var i = 0; i < 10; i++) { MathDisplay.Write(zipf.Sample().ToString("N05") + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); }
/// <summary> /// Examples of generic function sampling and quantization providers /// </summary> public override void ExecuteExample() { MathDisplay.WriteLine("<b>Chebyshev sampling</b>"); // 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 roots = FindRoots.ChebychevPolynomialFirstKind(20, 0, 10); var result = Generate.Map <double, double>(roots, Function); MathDisplay.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++) { MathDisplay.Write(result[i].ToString("N") + @" "); } MathDisplay.WriteLine(); MathDisplay.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] roots = FindRoots.ChebychevPolynomialSecondKind(20, 0, 10); result = Generate.Map <double, double>(roots, Function); MathDisplay.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++) { MathDisplay.Write(result[i].ToString("N") + @" "); } MathDisplay.WriteLine(); MathDisplay.WriteLine("<b>Equidistant sampling</b>"); // 1. Get 11 samples of f(x) = (x * x) / 2 equidistant within interval [-5, 5] result = Generate.LinearSpacedMap <double>(11, -5, 5, Function); MathDisplay.WriteLine(@"1. Get 11 samples of f(x) = (x * x) / 2 equidistant within interval [-5, 5]"); for (var i = 0; i < result.Length; i++) { MathDisplay.Write(result[i].ToString("N") + @" "); } MathDisplay.WriteLine(); MathDisplay.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 = Generate.LinearSpaced(10, 1.0, 5.5); result = Generate.Map <double, double>(samplePoints, Function); MathDisplay.WriteLine(@"2. Get 10 samples of f(x) = (x * x) / 2 equidistant starting at x=1 with step = 0.5 and retrieve sample points"); MathDisplay.Write(@"Points: "); for (var i = 0; i < samplePoints.Length; i++) { MathDisplay.Write(samplePoints[i].ToString("N") + @" "); } MathDisplay.WriteLine(); MathDisplay.Write(@"Values: "); for (var i = 0; i < result.Length; i++) { MathDisplay.Write(result[i].ToString("N") + @" "); } MathDisplay.WriteLine(); MathDisplay.WriteLine(); // 3. Get 10 samples of f(x) = (x * x) / 2 equidistant within period = 10 and period offset = 5 result = Generate.PeriodicMap <double>(10, Function, 10, 1.0, 10, 5); MathDisplay.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++) { MathDisplay.Write(result[i].ToString("N") + @" "); } MathDisplay.WriteLine(); MathDisplay.WriteLine("<b>Random sampling</b>"); // 1. Get 10 random samples of f(x) = (x * x) / 2 using continuous uniform distribution on [-10, 10] var uniform = new ContinuousUniform(-10, 10); result = Generate.RandomMap <double>(10, uniform, Function); MathDisplay.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++) { MathDisplay.Write(result[i].ToString("N") + @" "); } MathDisplay.WriteLine(); MathDisplay.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); samplePoints = Generate.Random(10, exponential); result = Generate.Map <double, double>(samplePoints, Function); MathDisplay.WriteLine(@"2. Get 10 random samples of f(x) = (x * x) / 2 using Exponential(1) distribution and retrieve sample points"); MathDisplay.Write(@"Points: "); for (var i = 0; i < samplePoints.Length; i++) { MathDisplay.Write(samplePoints[i].ToString("N") + @" "); } MathDisplay.WriteLine(); MathDisplay.Write(@"Values: "); for (var i = 0; i < result.Length; i++) { MathDisplay.Write(result[i].ToString("N") + @" "); } MathDisplay.WriteLine(); MathDisplay.WriteLine(); // 3. Get 10 random samples of f(x, y) = (x * y) / 2 using ChiSquare(10) distribution var chiSquare = new ChiSquared(10); result = Generate.RandomMap2 <double>(10, chiSquare, TwoDomainFunction); MathDisplay.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++) { MathDisplay.Write(result[i].ToString("N") + @" "); } MathDisplay.WriteLine(); }
/// <summary> /// Executes the example. /// </summary> /// <seealso cref="http://en.wikipedia.org/wiki/Random_number_generation">Random number generation</seealso> /// <seealso cref="http://en.wikipedia.org/wiki/Linear_congruential_generator">Linear congruential generator</seealso> /// <seealso cref="http://en.wikipedia.org/wiki/Mersenne_twister">Mersenne twister</seealso> /// <seealso cref="http://en.wikipedia.org/wiki/Lagged_Fibonacci_generator">Lagged Fibonacci generator</seealso> /// <seealso cref="http://en.wikipedia.org/wiki/Xorshift">Xorshift</seealso> public override void ExecuteExample() { // All RNG classes in MathNet have the following counstructors: // - RNG(int seed, bool threadSafe): initializes a new instance using a specific seed value and thread // safe property // - RNG(int seed): initializes a new instance using a 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); MathDisplay.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.NextDoubles(10); for (var i = 0; i < randomValues.Length; i++) { MathDisplay.Write(randomValues[i].ToString("N") + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // 2. Multiplicative congruential generator using a modulus of 2^59 and a multiplier of 13^13 var mcg59 = new Mcg59(1); MathDisplay.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++) { MathDisplay.Write(mcg59.Next() + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // 3. Random number generator using Mersenne Twister 19937 algorithm var mersenneTwister = new MersenneTwister(1); MathDisplay.WriteLine(@"3. Generate 10 random integer values less then 100 using Mersenne Twister 19937 algorithm"); for (var i = 0; i < 10; i++) { MathDisplay.Write(mersenneTwister.Next(100) + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // 4. Multiple recursive generator with 2 components of order 3 var mrg32K3A = new Mrg32k3a(1); MathDisplay.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++) { MathDisplay.Write(mrg32K3A.Next(50, 100) + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // 5. Parallel Additive Lagged Fibonacci pseudo-random number generator var palf = new Palf(1); MathDisplay.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++) { MathDisplay.Write(bytes[i] + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // 6. A random number generator based on "System.Security.Cryptography.RandomNumberGenerator" class in // the .NET library var systemCrypto = new CryptoRandomSource(); MathDisplay.WriteLine(@"6. Generate 10 random decimal values using RNG based on 'System.Security.Cryptography.RandomNumberGenerator'"); for (var i = 0; i < 10; i++) { MathDisplay.Write(systemCrypto.NextDecimal().ToString("N") + @" "); } MathDisplay.WriteLine(); MathDisplay.WriteLine(); // 7. Wichmann-Hill’s 1982 combined multiplicative congruential generator var rngWh1982 = new WH1982(); MathDisplay.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++) { MathDisplay.Write(rngWh1982.NextFullRangeInt32() + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // 8. Wichmann-Hill’s 2006 combined multiplicative congruential generator. var rngWh2006 = new WH2006(); MathDisplay.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++) { MathDisplay.Write(rngWh2006.NextFullRangeInt32() + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); MathDisplay.WriteLine(); // 9. Multiply-with-carry Xorshift pseudo random number generator var xorshift = new Xorshift(); MathDisplay.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++) { MathDisplay.Write(xorshift.NextInt64() + @" "); } MathDisplay.FlushBuffer(); MathDisplay.WriteLine(); }
public override void ExecuteExample() { MathDisplay.WriteLine("<b>Linear interpolation between points</b>"); // 1. Generate 20 samples of the function x*x-2*x on interval [0, 10] MathDisplay.WriteLine(@"1. Generate 20 samples of the function x*x-2*x on interval [0, 10]"); double[] points = Generate.LinearSpaced(20, 0, 10); var values = Generate.Map <double, double>(points, TargetFunction1); MathDisplay.WriteLine(); // 2. Create a linear spline interpolation based on arbitrary points var method = Interpolate.Linear(points, values); MathDisplay.WriteLine(@"2. Create a linear spline interpolation based on arbitrary points"); MathDisplay.WriteLine(); // 3. Check if interpolation support integration MathDisplay.WriteLine(@"3. Support integration = {0}", method.SupportsIntegration); MathDisplay.WriteLine(); // 4. Check if interpolation support differentiation MathDisplay.WriteLine(@"4. Support differentiation = {0}", method.SupportsDifferentiation); MathDisplay.WriteLine(); // 5. Differentiate at point 5.2 MathDisplay.WriteLine(@"5. Differentiate at point 5.2 = {0}", method.Differentiate(5.2)); MathDisplay.WriteLine(); // 6. Integrate at point 5.2 MathDisplay.WriteLine(@"6. Integrate at point 5.2 = {0}", method.Integrate(5.2)); MathDisplay.WriteLine(); // 7. Interpolate ten random points and compare to function results MathDisplay.WriteLine(@"7. Interpolate ten random points and compare to function results"); var rng = new MersenneTwister(1); for (var i = 0; i < 10; i++) { // Generate random value from [0, 10] var point = rng.NextDouble() * 10; MathDisplay.WriteLine( @"Interpolate at {0} = {1}. Function({0}) = {2}", point.ToString("N05"), method.Interpolate(point).ToString("N05"), TargetFunction1(point).ToString("N05")); } MathDisplay.WriteLine(); // <seealso cref="http://en.wikipedia.org/wiki/Spline_interpolation">Spline interpolation</seealso> MathDisplay.WriteLine("<b>Akima spline interpolation</b>"); // 1. Generate 10 samples of the function x*x-2*x on interval [0, 10] MathDisplay.WriteLine(@"1. Generate 10 samples of the function x*x-2*x on interval [0, 10]"); points = Generate.LinearSpaced(10, 0, 10); values = Generate.Map <double, double>(points, TargetFunction1); MathDisplay.WriteLine(); // 2. Create akima spline interpolation method = CubicSpline.InterpolateAkima(points, values); MathDisplay.WriteLine(@"2. Create akima spline interpolation based on arbitrary points"); MathDisplay.WriteLine(); // 3. Check if interpolation supports integration MathDisplay.WriteLine(@"3. Support integration = {0}", ((IInterpolation)method).SupportsIntegration); MathDisplay.WriteLine(); // 4. Check if interpolation support differentiation MathDisplay.WriteLine(@"4. Support differentiation = {0}", ((IInterpolation)method).SupportsDifferentiation); MathDisplay.WriteLine(); // 5. Differentiate at point 5.2 MathDisplay.WriteLine(@"5. Differentiate at point 5.2 = {0}", method.Differentiate(5.2)); MathDisplay.WriteLine(); // 6. Integrate at point 5.2 MathDisplay.WriteLine(@"6. Integrate at point 5.2 = {0}", method.Integrate(5.2)); MathDisplay.WriteLine(); // 7. Interpolate ten random points and compare to function results MathDisplay.WriteLine(@"7. Interpolate ten random points and compare to function results"); rng = new MersenneTwister(1); for (var i = 0; i < 10; i++) { // Generate random value from [0, 10] var point = rng.NextDouble() * 10; MathDisplay.WriteLine( @"Interpolate at {0} = {1}. Function({0}) = {2}", point.ToString("N05"), method.Interpolate(point).ToString("N05"), TargetFunction1(point).ToString("N05")); } MathDisplay.WriteLine(); MathDisplay.WriteLine("<b>Barycentric rational interpolation without poles</b>"); // 1. Generate 10 samples of the function 1/(1+x*x) on interval [-5, 5] MathDisplay.WriteLine(@"1. Generate 10 samples of the function 1/(1+x*x) on interval [-5, 5]"); points = Generate.LinearSpaced(10, -5, 5); values = Generate.Map <double, double>(points, TargetFunctionWithoutPolesEx); MathDisplay.WriteLine(); // 2. Create a floater hormann rational pole-free interpolation based on arbitrary points // This method is used by default when create an interpolation using Interpolate.Common method method = Interpolate.RationalWithoutPoles(points, values); MathDisplay.WriteLine(@"2. Create a floater hormann rational pole-free interpolation based on arbitrary points"); MathDisplay.WriteLine(); // 3. Check if interpolation support integration MathDisplay.WriteLine(@"3. Support integration = {0}", method.SupportsIntegration); MathDisplay.WriteLine(); // 4. Check if interpolation support differentiation MathDisplay.WriteLine(@"4. Support differentiation = {0}", method.SupportsDifferentiation); MathDisplay.WriteLine(); // 5. Interpolate ten random points and compare to function results MathDisplay.WriteLine(@"5. Interpolate ten random points and compare to function results"); rng = new MersenneTwister(1); for (var i = 0; i < 10; i++) { // Generate random value from [0, 5] var point = rng.NextDouble() * 5; MathDisplay.WriteLine( @"Interpolate at {0} = {1}. Function({0}) = {2}", point.ToString("N05"), method.Interpolate(point).ToString("N05"), TargetFunctionWithoutPolesEx(point).ToString("N05")); } MathDisplay.WriteLine(); MathDisplay.WriteLine("<b>Rational interpolation with poles</b>"); // 1. Generate 20 samples of the function f(x) = x on interval [-5, 5] MathDisplay.WriteLine(@"1. Generate 20 samples of the function f(x) = x on interval [-5, 5]"); points = Generate.LinearSpaced(20, -5, 5); values = Generate.Map <double, double>(points, TargetFunctionWithPolesEx); MathDisplay.WriteLine(); // 2. Create a burlish stoer rational interpolation based on arbitrary points method = Interpolate.RationalWithPoles(points, values); MathDisplay.WriteLine(@"2. Create a burlish stoer rational interpolation based on arbitrary points"); MathDisplay.WriteLine(); // 3. Check if interpolation support integration MathDisplay.WriteLine(@"3. Support integration = {0}", method.SupportsIntegration); MathDisplay.WriteLine(); // 4. Check if interpolation support differentiation MathDisplay.WriteLine(@"4. Support differentiation = {0}", method.SupportsDifferentiation); MathDisplay.WriteLine(); // 5. Interpolate ten random points and compare to function results MathDisplay.WriteLine(@"5. Interpolate ten random points and compare to function results"); rng = new MersenneTwister(1); for (var i = 0; i < 10; i++) { // Generate random value from [0, 5] var point = rng.Next(0, 5); MathDisplay.WriteLine( @"Interpolate at {0} = {1}. Function({0}) = {2}", point.ToString("N05"), method.Interpolate(point).ToString("N05"), TargetFunctionWithPolesEx(point).ToString("N05")); } MathDisplay.WriteLine(); }
public override void ExecuteExample() { // <seealso cref="http://en.wikipedia.org/wiki/Biconjugate_gradient_stabilized_method">Biconjugate gradient stabilized method</seealso> MathDisplay.WriteLine("<b>Biconjugate gradient stabilised iterative solver</b>"); // 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 = DenseMatrix.OfArray(new[, ] { { 5.00, 2.00, -4.00 }, { 3.00, -7.00, 6.00 }, { 4.00, 1.00, 5.00 } }); MathDisplay.WriteLine(@"Matrix 'A' with coefficients"); MathDisplay.WriteLine(matrixA.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // Create vector "b" with the constant terms. var vectorB = new DenseVector(new[] { -7.0, 38.0, 43.0 }); MathDisplay.WriteLine(@"Vector 'b' with the constant terms"); MathDisplay.WriteLine(vectorB.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // Create stop criteria to monitor an iterative calculation. There are next available stop criteria: // - DivergenceStopCriterion: monitors an iterative calculation for signs of divergence; // - FailureStopCriterion: monitors residuals for NaN's; // - IterationCountStopCriterion: monitors the numbers of iteration steps; // - ResidualStopCriterion: monitors residuals if calculation is considered converged; // Stop calculation if 1000 iterations reached during calculation var iterationCountStopCriterion = new IterationCountStopCriterion <double>(1000); // Stop calculation if residuals are below 1E-10 --> the calculation is considered converged var residualStopCriterion = new ResidualStopCriterion <double>(1e-10); // Create monitor with defined stop criteria var monitor = new Iterator <double>(iterationCountStopCriterion, residualStopCriterion); // Create Bi-Conjugate Gradient Stabilized solver var solverBiCgStab = new BiCgStab(); // 1. Solve the matrix equation var resultX = matrixA.SolveIterative(vectorB, solverBiCgStab, monitor); MathDisplay.WriteLine(@"1. Solve the matrix equation"); MathDisplay.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; MathDisplay.WriteLine(@"2. Solver status of the iterations"); MathDisplay.WriteLine(monitor.Status.ToString()); MathDisplay.WriteLine(); // 3. Solution result vector of the matrix equation MathDisplay.WriteLine(@"3. Solution result vector of the matrix equation"); MathDisplay.WriteLine(resultX.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 4. Verify result. Multiply coefficient matrix "A" by result vector "x" var reconstructVecorB = matrixA * resultX; MathDisplay.WriteLine(@"4. Multiply coefficient matrix 'A' by result vector 'x'"); MathDisplay.WriteLine(reconstructVecorB.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); MathDisplay.WriteLine("<b>Generalized product biconjugate gradient solver</b>"); // 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 matrixA = DenseMatrix.OfArray(new[, ] { { 5.00, 2.00, -4.00 }, { 3.00, -7.00, 6.00 }, { 4.00, 1.00, 5.00 } }); MathDisplay.WriteLine(@"Matrix 'A' with coefficients"); MathDisplay.WriteLine(matrixA.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // Create vector "b" with the constant terms. vectorB = new DenseVector(new[] { -7.0, 38.0, 43.0 }); MathDisplay.WriteLine(@"Vector 'b' with the constant terms"); MathDisplay.WriteLine(vectorB.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // Create stop criteria to monitor an iterative calculation. There are next available stop criteria: // - DivergenceStopCriterion: monitors an iterative calculation for signs of divergence; // - FailureStopCriterion: monitors residuals for NaN's; // - IterationCountStopCriterion: monitors the numbers of iteration steps; // - ResidualStopCriterion: monitors residuals if calculation is considered converged; // Stop calculation if 1000 iterations reached during calculation iterationCountStopCriterion = new IterationCountStopCriterion <double>(1000); // Stop calculation if residuals are below 1E-10 --> the calculation is considered converged residualStopCriterion = new ResidualStopCriterion <double>(1e-10); // Create monitor with defined stop criteria monitor = new Iterator <double>(iterationCountStopCriterion, residualStopCriterion); // Create Generalized Product Bi-Conjugate Gradient solver var solverGpBiCg = new GpBiCg(); // 1. Solve the matrix equation resultX = matrixA.SolveIterative(vectorB, solverGpBiCg, monitor); MathDisplay.WriteLine(@"1. Solve the matrix equation"); MathDisplay.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; MathDisplay.WriteLine(@"2. Solver status of the iterations"); MathDisplay.WriteLine(monitor.Status.ToString()); MathDisplay.WriteLine(); // 3. Solution result vector of the matrix equation MathDisplay.WriteLine(@"3. Solution result vector of the matrix equation"); MathDisplay.WriteLine(resultX.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 4. Verify result. Multiply coefficient matrix "A" by result vector "x" reconstructVecorB = matrixA * resultX; MathDisplay.WriteLine(@"4. Multiply coefficient matrix 'A' by result vector 'x'"); MathDisplay.WriteLine(reconstructVecorB.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); MathDisplay.WriteLine("<b>Composite linear equation solver</b>"); // 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 matrixA = DenseMatrix.OfArray(new[, ] { { 5.00, 2.00, -4.00 }, { 3.00, -7.00, 6.00 }, { 4.00, 1.00, 5.00 } }); MathDisplay.WriteLine(@"Matrix 'A' with coefficients"); MathDisplay.WriteLine(matrixA.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // Create vector "b" with the constant terms. vectorB = new DenseVector(new[] { -7.0, 38.0, 43.0 }); MathDisplay.WriteLine(@"Vector 'b' with the constant terms"); MathDisplay.WriteLine(vectorB.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // Create stop criteria to monitor an iterative calculation. There are next available stop criteria: // - DivergenceStopCriterion: monitors an iterative calculation for signs of divergence; // - FailureStopCriterion: monitors residuals for NaN's; // - IterationCountStopCriterion: monitors the numbers of iteration steps; // - ResidualStopCriterion: monitors residuals if calculation is considered converged; // Stop calculation if 1000 iterations reached during calculation iterationCountStopCriterion = new IterationCountStopCriterion <double>(1000); // Stop calculation if residuals are below 1E-10 --> the calculation is considered converged residualStopCriterion = new ResidualStopCriterion <double>(1e-10); // Create monitor with defined stop criteria monitor = new Iterator <double>(iterationCountStopCriterion, residualStopCriterion); // Load all suitable solvers from current assembly. Below (see UserBiCgStab) there is a custom user-defined solver // "class UserBiCgStab : IIterativeSolverSetup<double>" which derives from the regular BiCgStab solver. However users can // create any other solver and solver setup classes that implement IIterativeSolverSetup<T> and load the assembly that // contains them using the following function: var solverComp = new CompositeSolver(SolverSetup <double> .LoadFromAssembly(Assembly.GetExecutingAssembly())); // 1. Solve the linear system resultX = matrixA.SolveIterative(vectorB, solverComp, monitor); MathDisplay.WriteLine(@"1. Solve the matrix equation"); MathDisplay.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; MathDisplay.WriteLine(@"2. Solver status of the iterations"); MathDisplay.WriteLine(monitor.Status.ToString()); MathDisplay.WriteLine(); // 3. Solution result vector of the matrix equation MathDisplay.WriteLine(@"3. Solution result vector of the matrix equation"); MathDisplay.WriteLine(resultX.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 4. Verify result. Multiply coefficient matrix "A" by result vector "x" reconstructVecorB = matrixA * resultX; MathDisplay.WriteLine(@"4. Multiply coefficient matrix 'A' by result vector 'x'"); MathDisplay.WriteLine(reconstructVecorB.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); MathDisplay.WriteLine("<b>Multiple-Lanczos biconjugate gradient stabilised iterative solver</b>"); // 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 matrixA = DenseMatrix.OfArray(new[, ] { { 5.00, 2.00, -4.00 }, { 3.00, -7.00, 6.00 }, { 4.00, 1.00, 5.00 } }); MathDisplay.WriteLine(@"Matrix 'A' with coefficients"); MathDisplay.WriteLine(matrixA.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // Create vector "b" with the constant terms. vectorB = new DenseVector(new[] { -7.0, 38.0, 43.0 }); MathDisplay.WriteLine(@"Vector 'b' with the constant terms"); MathDisplay.WriteLine(vectorB.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // Create stop criteria to monitor an iterative calculation. There are next available stop criteria: // - DivergenceStopCriterion: monitors an iterative calculation for signs of divergence; // - FailureStopCriterion: monitors residuals for NaN's; // - IterationCountStopCriterion: monitors the numbers of iteration steps; // - ResidualStopCriterion: monitors residuals if calculation is considered converged; // Stop calculation if 1000 iterations reached during calculation iterationCountStopCriterion = new IterationCountStopCriterion <double>(1000); // Stop calculation if residuals are below 1E-10 --> the calculation is considered converged residualStopCriterion = new ResidualStopCriterion <double>(1e-10); // Create monitor with defined stop criteria monitor = new Iterator <double>(iterationCountStopCriterion, residualStopCriterion); // Create Multiple-Lanczos Bi-Conjugate Gradient Stabilized solver var solverLanczos = new MlkBiCgStab(); // 1. Solve the matrix equation resultX = matrixA.SolveIterative(vectorB, solverLanczos, monitor); MathDisplay.WriteLine(@"1. Solve the matrix equation"); MathDisplay.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; MathDisplay.WriteLine(@"2. Solver status of the iterations"); MathDisplay.WriteLine(monitor.Status.ToString()); MathDisplay.WriteLine(); // 3. Solution result vector of the matrix equation MathDisplay.WriteLine(@"3. Solution result vector of the matrix equation"); MathDisplay.WriteLine(resultX.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 4. Verify result. Multiply coefficient matrix "A" by result vector "x" reconstructVecorB = matrixA * resultX; MathDisplay.WriteLine(@"4. Multiply coefficient matrix 'A' by result vector 'x'"); MathDisplay.WriteLine(reconstructVecorB.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); MathDisplay.WriteLine("<b>Transpose freee quasi-minimal residual iterative solver</b>"); // 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 matrixA = DenseMatrix.OfArray(new[, ] { { 5.00, 2.00, -4.00 }, { 3.00, -7.00, 6.00 }, { 4.00, 1.00, 5.00 } }); MathDisplay.WriteLine(@"Matrix 'A' with coefficients"); MathDisplay.WriteLine(matrixA.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // Create vector "b" with the constant terms. vectorB = new DenseVector(new[] { -7.0, 38.0, 43.0 }); MathDisplay.WriteLine(@"Vector 'b' with the constant terms"); MathDisplay.WriteLine(vectorB.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // Create stop criteria to monitor an iterative calculation. There are next available stop criteria: // - DivergenceStopCriterion: monitors an iterative calculation for signs of divergence; // - FailureStopCriterion: monitors residuals for NaN's; // - IterationCountStopCriterion: monitors the numbers of iteration steps; // - ResidualStopCriterion: monitors residuals if calculation is considered converged; // Stop calculation if 1000 iterations reached during calculation iterationCountStopCriterion = new IterationCountStopCriterion <double>(1000); // Stop calculation if residuals are below 1E-10 --> the calculation is considered converged residualStopCriterion = new ResidualStopCriterion <double>(1e-10); // Create monitor with defined stop criteria monitor = new Iterator <double>(iterationCountStopCriterion, residualStopCriterion); // Create Transpose Free Quasi-Minimal Residual solver var solverTFQMR = new TFQMR(); // 1. Solve the matrix equation resultX = matrixA.SolveIterative(vectorB, solverTFQMR, monitor); MathDisplay.WriteLine(@"1. Solve the matrix equation"); MathDisplay.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; MathDisplay.WriteLine(@"2. Solver status of the iterations"); MathDisplay.WriteLine(monitor.Status.ToString()); MathDisplay.WriteLine(); // 3. Solution result vector of the matrix equation MathDisplay.WriteLine(@"3. Solution result vector of the matrix equation"); MathDisplay.WriteLine(resultX.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); // 4. Verify result. Multiply coefficient matrix "A" by result vector "x" reconstructVecorB = matrixA * resultX; MathDisplay.WriteLine(@"4. Multiply coefficient matrix 'A' by result vector 'x'"); MathDisplay.WriteLine(reconstructVecorB.ToString("#0.00\t", formatProvider)); MathDisplay.WriteLine(); }
/// <summary> /// Executes the example. /// </summary> public override void ExecuteExample() { // <seealso cref="http://en.wikipedia.org/wiki/Beta_function">Beta function</seealso> MathDisplay.WriteLine("<b>Beta fuction</b>"); // 1. Compute the Beta function at z = 1.0, w = 3.0 MathDisplay.WriteLine(@"1. Compute the Beta function at z = 1.0, w = 3.0"); MathDisplay.WriteLine(SpecialFunctions.Beta(1.0, 3.0).ToString()); MathDisplay.WriteLine(); // 2. Compute the logarithm of the Beta function at z = 1.0, w = 3.0 MathDisplay.WriteLine(@"2. Compute the logarithm of the Beta function at z = 1.0, w = 3.0"); MathDisplay.WriteLine(SpecialFunctions.BetaLn(1.0, 3.0).ToString()); MathDisplay.WriteLine(); // 3. Compute the Beta incomplete function at z = 1.0, w = 3.0, x = 0.7 MathDisplay.WriteLine(@"3. Compute the Beta incomplete function at z = 1.0, w = 3.0, x = 0.7"); MathDisplay.WriteLine(SpecialFunctions.BetaIncomplete(1.0, 3.0, 0.7).ToString()); MathDisplay.WriteLine(); // 4. Compute the Beta incomplete function at z = 1.0, w = 3.0, x = 1.0 MathDisplay.WriteLine(@"4. Compute the Beta incomplete function at z = 1.0, w = 3.0, x = 1.0"); MathDisplay.WriteLine(SpecialFunctions.BetaIncomplete(1.0, 3.0, 1.0).ToString()); MathDisplay.WriteLine(); // 5. Compute the Beta regularized function at z = 1.0, w = 3.0, x = 0.7 MathDisplay.WriteLine(@"5. Compute the Beta regularized function at z = 1.0, w = 3.0, x = 0.7"); MathDisplay.WriteLine(SpecialFunctions.BetaRegularized(1.0, 3.0, 0.7).ToString()); MathDisplay.WriteLine(); // 6. Compute the Beta regularized function at z = 1.0, w = 3.0, x = 1.0 MathDisplay.WriteLine(@"6. Compute the Beta regularized function at z = 1.0, w = 3.0, x = 1.0"); MathDisplay.WriteLine(SpecialFunctions.BetaRegularized(1.0, 3.0, 1.0).ToString()); MathDisplay.WriteLine(); MathDisplay.WriteLine("<b>Common functions</b>"); // 1. Calculate the Digamma function at point 5.0 // <seealso cref="http://en.wikipedia.org/wiki/Digamma_function">Digamma function</seealso> MathDisplay.WriteLine(@"1. Calculate the Digamma function at point 5.0"); MathDisplay.WriteLine(SpecialFunctions.DiGamma(5.0).ToString()); MathDisplay.WriteLine(); // 2. Calculate the inverse Digamma function at point 1.5 MathDisplay.WriteLine(@"2. Calculate the inverse Digamma function at point 1.5"); MathDisplay.WriteLine(SpecialFunctions.DiGammaInv(1.5).ToString()); MathDisplay.WriteLine(); // 3. Calculate the 10'th Harmonic number // <seealso cref="http://en.wikipedia.org/wiki/Harmonic_number">Harmonic number</seealso> MathDisplay.WriteLine(@"3. Calculate the 10'th Harmonic number"); MathDisplay.WriteLine(SpecialFunctions.Harmonic(10).ToString()); MathDisplay.WriteLine(); // 4. Calculate the generalized harmonic number of order 10 of 3.0. // <seealso cref="http://en.wikipedia.org/wiki/Harmonic_number#Generalized_harmonic_numbers">Generalized harmonic numbers</seealso> MathDisplay.WriteLine(@"4. Calculate the generalized harmonic number of order 10 of 3.0"); MathDisplay.WriteLine(SpecialFunctions.GeneralHarmonic(10, 3.0).ToString()); MathDisplay.WriteLine(); // 5. Calculate the logistic function of 3.0 // <seealso cref="http://en.wikipedia.org/wiki/Logistic_function">Logistic function</seealso> MathDisplay.WriteLine(@"5. Calculate the logistic function of 3.0"); MathDisplay.WriteLine(SpecialFunctions.Logistic(3.0).ToString()); MathDisplay.WriteLine(); // 6. Calculate the logit function of 0.3 // <seealso cref="http://en.wikipedia.org/wiki/Logit">Logit function</seealso> MathDisplay.WriteLine(@"6. Calculate the logit function of 0.3"); MathDisplay.WriteLine(SpecialFunctions.Logit(0.3).ToString()); MathDisplay.WriteLine(); // <seealso cref="http://en.wikipedia.org/wiki/Error_function">Error function</seealso> MathDisplay.WriteLine("<b>Error function</b>"); // 1. Calculate the error function at point 2 MathDisplay.WriteLine(@"1. Calculate the error function at point 2"); MathDisplay.WriteLine(SpecialFunctions.Erf(2).ToString()); MathDisplay.WriteLine(); // 2. Sample 10 values of the error function in [-1.0; 1.0] MathDisplay.WriteLine(@"2. Sample 10 values of the error function in [-1.0; 1.0]"); var data = Generate.LinearSpacedMap <double>(10, -1.0, 1.0, SpecialFunctions.Erf); for (var i = 0; i < data.Length; i++) { MathDisplay.Write(data[i].ToString("N") + @" "); } MathDisplay.WriteLine(); MathDisplay.WriteLine(); // 3. Calculate the complementary error function at point 2 MathDisplay.WriteLine(@"3. Calculate the complementary error function at point 2"); MathDisplay.WriteLine(SpecialFunctions.Erfc(2).ToString()); MathDisplay.WriteLine(); // 4. Sample 10 values of the complementary error function in [-1.0; 1.0] MathDisplay.WriteLine(@"4. Sample 10 values of the complementary error function in [-1.0; 1.0]"); data = Generate.LinearSpacedMap <double>(10, -1.0, 1.0, SpecialFunctions.Erfc); for (var i = 0; i < data.Length; i++) { MathDisplay.Write(data[i].ToString("N") + @" "); } MathDisplay.WriteLine(); MathDisplay.WriteLine(); // 5. Calculate the inverse error function at point z=0.5 MathDisplay.WriteLine(@"5. Calculate the inverse error function at point z=0.5"); MathDisplay.WriteLine(SpecialFunctions.ErfInv(0.5).ToString()); MathDisplay.WriteLine(); // 6. Sample 10 values of the inverse error function in [-1.0; 1.0] MathDisplay.WriteLine(@"6. Sample 10 values of the inverse error function in [-1.0; 1.0]"); data = Generate.LinearSpacedMap <double>(10, -1.0, 1.0, SpecialFunctions.ErfInv); for (var i = 0; i < data.Length; i++) { MathDisplay.Write(data[i].ToString("N") + @" "); } MathDisplay.WriteLine(); MathDisplay.WriteLine(); // 7. Calculate the complementary inverse error function at point z=0.5 MathDisplay.WriteLine(@"7. Calculate the complementary inverse error function at point z=0.5"); MathDisplay.WriteLine(SpecialFunctions.ErfcInv(0.5).ToString()); MathDisplay.WriteLine(); // 8. Sample 10 values of the complementary inverse error function in [-1.0; 1.0] MathDisplay.WriteLine(@"8. Sample 10 values of the complementary inverse error function in [-1.0; 1.0]"); data = Generate.LinearSpacedMap <double>(10, -1.0, 1.0, SpecialFunctions.ErfcInv); for (var i = 0; i < data.Length; i++) { MathDisplay.Write(data[i].ToString("N") + @" "); } MathDisplay.WriteLine(); // <seealso cref="http://en.wikipedia.org/wiki/Factorial">Factorial</seealso> MathDisplay.WriteLine("<b>Factorial</b>"); // 1. Compute the factorial of 5 MathDisplay.WriteLine(@"1. Compute the factorial of 5"); MathDisplay.WriteLine(SpecialFunctions.Factorial(5).ToString("N")); MathDisplay.WriteLine(); // 2. Compute the logarithm of the factorial of 5 MathDisplay.WriteLine(@"2. Compute the logarithm of the factorial of 5"); MathDisplay.WriteLine(SpecialFunctions.FactorialLn(5).ToString("N")); MathDisplay.WriteLine(); // <seealso cref="http://en.wikipedia.org/wiki/Binomial_coefficient">Binomial coefficient</seealso> MathDisplay.WriteLine("<b>Binomial coefficient</b>"); // 3. Compute the binomial coefficient: 10 choose 8 MathDisplay.WriteLine(@"3. Compute the binomial coefficient: 10 choose 8"); MathDisplay.WriteLine(SpecialFunctions.Binomial(10, 8).ToString("N")); MathDisplay.WriteLine(); // 4. Compute the logarithm of the binomial coefficient: 10 choose 8 MathDisplay.WriteLine(@"4. Compute the logarithm of the binomial coefficient: 10 choose 8"); MathDisplay.WriteLine(SpecialFunctions.BinomialLn(10, 8).ToString("N")); MathDisplay.WriteLine(); // <seealso cref="http://en.wikipedia.org/wiki/Multinomial_theorem#Multinomial_coefficients">Multinomial coefficients</seealso> MathDisplay.WriteLine("<b>Multinomial coefficient</b>"); // 5. Compute the multinomial coefficient: 10 choose 2, 3, 5 MathDisplay.WriteLine(@"5. Compute the multinomial coefficient: 10 choose 2, 3, 5"); MathDisplay.WriteLine(SpecialFunctions.Multinomial(10, new[] { 2, 3, 5 }).ToString("N")); MathDisplay.WriteLine(); // <seealso cref="http://en.wikipedia.org/wiki/Gamma_function">Gamma function</seealso> MathDisplay.WriteLine("<b>Gamma function</b>"); // 1. Compute the Gamma function of 10 MathDisplay.WriteLine(@"1. Compute the Gamma function of 10"); MathDisplay.WriteLine(SpecialFunctions.Gamma(10).ToString("N")); MathDisplay.WriteLine(); // 2. Compute the logarithm of the Gamma function of 10 MathDisplay.WriteLine(@"2. Compute the logarithm of the Gamma function of 10"); MathDisplay.WriteLine(SpecialFunctions.GammaLn(10).ToString("N")); MathDisplay.WriteLine(); // 3. Compute the lower incomplete gamma(a, x) function at a = 10, x = 14 MathDisplay.WriteLine(@"3. Compute the lower incomplete gamma(a, x) function at a = 10, x = 14"); MathDisplay.WriteLine(SpecialFunctions.GammaLowerIncomplete(10, 14).ToString("N")); MathDisplay.WriteLine(); // 4. Compute the lower incomplete gamma(a, x) function at a = 10, x = 100 MathDisplay.WriteLine(@"4. Compute the lower incomplete gamma(a, x) function at a = 10, x = 100"); MathDisplay.WriteLine(SpecialFunctions.GammaLowerIncomplete(10, 100).ToString("N")); MathDisplay.WriteLine(); // 5. Compute the upper incomplete gamma(a, x) function at a = 10, x = 0 MathDisplay.WriteLine(@"5. Compute the upper incomplete gamma(a, x) function at a = 10, x = 0"); MathDisplay.WriteLine(SpecialFunctions.GammaUpperIncomplete(10, 0).ToString("N")); MathDisplay.WriteLine(); // 6. Compute the upper incomplete gamma(a, x) function at a = 10, x = 10 MathDisplay.WriteLine(@"6. Compute the upper incomplete gamma(a, x) function at a = 10, x = 100"); MathDisplay.WriteLine(SpecialFunctions.GammaLowerIncomplete(10, 10).ToString("N")); MathDisplay.WriteLine(); // 7. Compute the lower regularized gamma(a, x) function at a = 10, x = 14 MathDisplay.WriteLine(@"7. Compute the lower regularized gamma(a, x) function at a = 10, x = 14"); MathDisplay.WriteLine(SpecialFunctions.GammaLowerRegularized(10, 14).ToString("N")); MathDisplay.WriteLine(); // 8. Compute the lower regularized gamma(a, x) function at a = 10, x = 100 MathDisplay.WriteLine(@"8. Compute the lower regularized gamma(a, x) function at a = 10, x = 100"); MathDisplay.WriteLine(SpecialFunctions.GammaLowerRegularized(10, 100).ToString("N")); MathDisplay.WriteLine(); // 9. Compute the upper regularized gamma(a, x) function at a = 10, x = 0 MathDisplay.WriteLine(@"9. Compute the upper regularized gamma(a, x) function at a = 10, x = 0"); MathDisplay.WriteLine(SpecialFunctions.GammaUpperRegularized(10, 0).ToString("N")); MathDisplay.WriteLine(); // 10. Compute the upper regularized gamma(a, x) function at a = 10, x = 10 MathDisplay.WriteLine(@"10. Compute the upper regularized gamma(a, x) function at a = 10, x = 100"); MathDisplay.WriteLine(SpecialFunctions.GammaUpperRegularized(10, 10).ToString("N")); MathDisplay.WriteLine(); MathDisplay.WriteLine("<b>Numerical stability</b>"); // 1. Compute numerically stable exponential of 10 minus one MathDisplay.WriteLine(@"1. Compute numerically stable exponential of 4.2876 minus one"); MathDisplay.WriteLine(SpecialFunctions.ExponentialMinusOne(4.2876).ToString()); MathDisplay.WriteLine(); // 2. Compute regular System.Math exponential of 15.28 minus one MathDisplay.WriteLine(@"2. Compute regular System.Math exponential of 4.2876 minus one "); MathDisplay.WriteLine((Math.Exp(4.2876) - 1).ToString()); MathDisplay.WriteLine(); // 3. Compute numerically stable hypotenuse of a right angle triangle with a = 5, b = 3 MathDisplay.WriteLine(@"3. Compute numerically stable hypotenuse of a right angle triangle with a = 5, b = 3"); MathDisplay.WriteLine(SpecialFunctions.Hypotenuse(5, 3).ToString()); MathDisplay.WriteLine(); }
/// <summary> /// Execute example /// </summary> /// <seealso cref="http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient">Pearson /// product-moment correlation coefficient</seealso> public override void ExecuteExample() { // 1. Initialize the new instance of the ChiSquare distribution class with parameter dof = 5. var chiSquare = new ChiSquared(5); MathDisplay.WriteLine(@"1. Initialize the new instance of the ChiSquare distribution class with parameter DegreesOfFreedom = {0}", chiSquare.DegreesOfFreedom); MathDisplay.WriteLine(@"{0} distributuion properties:", chiSquare); MathDisplay.WriteLine(@"{0} - Largest element", chiSquare.Maximum.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(@"{0} - Smallest element", chiSquare.Minimum.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(@"{0} - Mean", chiSquare.Mean.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(@"{0} - Median", chiSquare.Median.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(@"{0} - Mode", chiSquare.Mode.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(@"{0} - Variance", chiSquare.Variance.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(@"{0} - Standard deviation", chiSquare.StdDev.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(@"{0} - Skewness", chiSquare.Skewness.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(); // 2. Generate 1000 samples of the ChiSquare(5) distribution MathDisplay.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 MathDisplay.WriteLine(@"3. Get basic statistics on set of generated data using extention methods"); MathDisplay.WriteLine(@"{0} - Largest element", data.Maximum().ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(@"{0} - Smallest element", data.Minimum().ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(@"{0} - Mean", data.Mean().ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(@"{0} - Median", data.Median().ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(@"{0} - Biased population variance", data.PopulationVariance().ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(@"{0} - Variance", data.Variance().ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(@"{0} - Standard deviation", data.StandardDeviation().ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(@"{0} - Biased sample standard deviation", data.PopulationStandardDeviation().ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(); // 4. Compute the basic statistics of data set using DescriptiveStatistics class MathDisplay.WriteLine(@"4. Compute the basic statistics of data set using DescriptiveStatistics class"); var descriptiveStatistics = new DescriptiveStatistics(data); MathDisplay.WriteLine(@"{0} - Kurtosis", descriptiveStatistics.Kurtosis.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(@"{0} - Largest element", descriptiveStatistics.Maximum.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(@"{0} - Smallest element", descriptiveStatistics.Minimum.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(@"{0} - Mean", descriptiveStatistics.Mean.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(@"{0} - Variance", descriptiveStatistics.Variance.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(@"{0} - Standard deviation", descriptiveStatistics.StandardDeviation.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(@"{0} - Skewness", descriptiveStatistics.Skewness.ToString(" #0.00000;-#0.00000")); MathDisplay.WriteLine(); // Generate 1000 samples of the ChiSquare(2.5) distribution var chiSquareB = new ChiSquared(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) MathDisplay.WriteLine(@"5. Correlation coefficient between 1000 samples of ChiSquare(5) and ChiSquare(2.5) is {0}", Correlation.Pearson(data, dataB).ToString("N04")); MathDisplay.WriteLine(@"6. Ranked correlation coefficient between 1000 samples of ChiSquare(5) and ChiSquare(2.5) is {0}", Correlation.Spearman(data, dataB).ToString("N04")); MathDisplay.WriteLine(); // 6. Correlation coefficient between 1000 samples of f(x) = x * 2 and f(x) = x * x data = Generate.LinearSpacedMap(1000, 0, 100, x => x * 2); dataB = Generate.LinearSpacedMap(1000, 0, 100, x => x * x); MathDisplay.WriteLine(@"7. Correlation coefficient between 1000 samples of f(x) = x * 2 and f(x) = x * x is {0}", Correlation.Pearson(data, dataB).ToString("N04")); MathDisplay.WriteLine(@"8. Ranked correlation coefficient between 1000 samples of f(x) = x * 2 and f(x) = x * x is {0}", Correlation.Spearman(data, dataB).ToString("N04")); MathDisplay.WriteLine(); }
/// <summary> /// Executes the example. /// </summary> public override void ExecuteExample() { // 1. Find out whether the provided number is an even number MathDisplay.WriteLine(@"1. Find out whether the provided number is an even number"); MathDisplay.WriteLine(@"{0} is even = {1}. {2} is even = {3}", 1, Euclid.IsEven(1), 2, 2.IsEven()); MathDisplay.WriteLine(); // 2. Find out whether the provided number is an odd number MathDisplay.WriteLine(@"2. Find out whether the provided number is an odd number"); MathDisplay.WriteLine(@"{0} is odd = {1}. {2} is odd = {3}", 1, 1.IsOdd(), 2, Euclid.IsOdd(2)); MathDisplay.WriteLine(); // 3. Find out whether the provided number is a perfect power of two MathDisplay.WriteLine(@"2. Find out whether the provided number is a perfect power of two"); MathDisplay.WriteLine( @"{0} is power of two = {1}. {2} is power of two = {3}", 5, 5.IsPowerOfTwo(), 16, Euclid.IsPowerOfTwo(16)); MathDisplay.WriteLine(); // 4. Find the closest perfect power of two that is larger or equal to 97 MathDisplay.WriteLine(@"4. Find the closest perfect power of two that is larger or equal to 97"); MathDisplay.WriteLine(97.CeilingToPowerOfTwo().ToString()); MathDisplay.WriteLine(); // 5. Raise 2 to the 16 MathDisplay.WriteLine(@"5. Raise 2 to the 16"); MathDisplay.WriteLine(16.PowerOfTwo().ToString()); MathDisplay.WriteLine(); // 6. Find out whether the number is a perfect square MathDisplay.WriteLine(@"6. Find out whether the number is a perfect square"); MathDisplay.WriteLine( @"{0} is perfect square = {1}. {2} is perfect square = {3}", 37, 37.IsPerfectSquare(), 81, Euclid.IsPerfectSquare(81)); MathDisplay.WriteLine(); // 7. Compute the greatest common divisor of 32 and 36 MathDisplay.WriteLine(@"7. Returns the greatest common divisor of 32 and 36"); MathDisplay.WriteLine(Euclid.GreatestCommonDivisor(32, 36).ToString()); MathDisplay.WriteLine(); // 8. Compute the greatest common divisor of 492, -984, 123, 246 MathDisplay.WriteLine(@"8. Returns the greatest common divisor of 492, -984, 123, 246"); MathDisplay.WriteLine(Euclid.GreatestCommonDivisor(492, -984, 123, 246).ToString()); MathDisplay.WriteLine(); // 9. Compute the extended greatest common divisor "z", such that 45*x + 18*y = z MathDisplay.WriteLine(@"9. Compute the extended greatest common divisor Z, such that 45*x + 18*y = Z"); long x, y; var z = Euclid.ExtendedGreatestCommonDivisor(45, 18, out x, out y); MathDisplay.WriteLine(@"z = {0}, x = {1}, y = {2}. 45*{1} + 18*{2} = {0}", z, x, y); MathDisplay.WriteLine(); // 10. Compute the least common multiple of 16 and 12 MathDisplay.WriteLine(@"10. Compute the least common multiple of 16 and 12"); MathDisplay.WriteLine(Euclid.LeastCommonMultiple(16, 12).ToString()); MathDisplay.WriteLine(); }