Example: Warning and WarningObject classes
This examples shows how to re-driect warning messages, instead of using the default System.err
. In this example, a warning message is captured, using methods in Warning and WarningObject classes, and re-printed later.
import com.imsl.*;
import com.imsl.stat.*;
import java.io.*;
public class WarningEx1 {
public static void main(String args[]) throws Exception {
// Capture warning message.
WarningObject w = Warning.getWarning();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(os);
WarningObject newWarning = new WarningObject();
newWarning.setOut(ps);
Warning.setWarning(newWarning);
// 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());
// Print warning message.
System.out.println(os.toString());
// Restore Warning.
Warning.setWarning(w);
ps.close();
os.close();
}
}
Output
The Chi-squared statistic is 4.79629666357389
The P-value is 0.44124295720552553
The Degrees of freedom are 5.0
com.imsl.stat.ChiSquaredTest: An expected value is less than five.
Link to Java source.