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.
import com.imsl.stat.*;
public class ChiSquaredTestEx1 {
public static void main(String args[]) {
// Seed the random number generator
Random rn = new Random();
rn.setSeed(123457);
rn.setMultiplier(16807);
// Construct a ChiSquaredTest object
CdfFunction bindf = new CdfFunction() {
public double cdf(double x) {
return Cdf.binomial((int)x, 5, 0.3);
}
};
double cutp[] = {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
System.out.println("The Chi-squared statistic is "
+ cst.getChiSquared());
System.out.println("The P-value is "+cst.getP());
System.out.println("The Degrees of freedom are "
+ cst.getDegreesOfFreedom());
}
}
Output
The Chi-squared statistic is 4.79629666357389
The P-value is 0.44124295720552553
The Degrees of freedom are 5.0
Link to Java source.