Example: The Chi-squared Goodness-of-fit Test
In this example, a discrete binomial random sample of size 1000 with binomial parameter
p
= 0.3 and binomial sample size 5 is generated via Random.nextBinomial. Random.setSeed is first used to set the seed. After the ChiSquaredTest constructor is called, the random observations are added to the test one at a time to simulate streaming data. The Chi-squared statistic, p
-value, and Degrees of freedom are then computed and printed.
using System;
using Imsl.Stat;
public class ChiSquaredTestEx1 : ICdfFunction
{
public double CdfFunction(double x)
{
return Cdf.Binomial((int) x, 5, 0.3);
}
public static void Main(String[] args)
{
// Seed the random number generator
Imsl.Stat.Random rn = new Imsl.Stat.Random(123457);
rn.Multiplier = 16807;
// Construct a ChiSquaredTest object
ICdfFunction bindf = new ChiSquaredTestEx1();
double[] cutp = new double[]{0.5, 1.5, 2.5, 3.5, 4.5};
int nParameters = 0;
ChiSquaredTest cst =
new ChiSquaredTest(bindf, cutp, nParameters);
for (int i = 0; i < 1000; i++)
{
cst.Update(rn.NextBinomial(5, 0.3), 1.0);
}
// Print goodness-of-fit test statistics
Console.Out.WriteLine
("The Chi-squared statistic is " + cst.ChiSquared);
Console.Out.WriteLine("The P-value is " + cst.P);
Console.Out.WriteLine
("The Degrees of freedom are " + cst.DegreesOfFreedom);
}
}
Output
The Chi-squared statistic is 4.79629666357389
The P-value is 0.441242957205526
The Degrees of freedom are 5
Imsl.Stat.ChiSquaredTest: An expected value is less than five.
Link to C# source.