import com.imsl.math.Sfun; import com.imsl.stat.Random; import com.imsl.chart.*; import java.awt.*; import javax.swing.*; public class SampleHistogram extends JFrameChart { public SampleHistogram() { int nSamples = 1000; int nBins = 20; // Setup the bins double bins[] = new double[nBins]; double dx = 6.0/nBins; double x[] = new double[nBins]; for (int k = 0; k < nBins; k++) { x[k] = -3.0 + (k+0.5)*dx; } Random r = new Random(123457); for (int k = 0; k < nSamples; k++) { double t = r.nextNormal(); int j = (int)Math.round((t+3.0-0.5*dx)/dx); if (j >= 0 && j < nBins) bins[j]++; } // Scale the bins for (int k = 0; k < nBins; k++) { bins[k] /= nSamples*dx; } // create the chart Chart chart = getChart(); AxisXY axis = new AxisXY(chart); chart.getChartTitle().setTitle("Normal Distribution"); chart.getLegend().setPaint(true); chart.getLegend().setViewport(0.7, 1.0, 0.2, 0.3); chart.getLegend().setFillOutlineType(chart.FILL_TYPE_NONE); Bar bar = new Bar(axis, x, bins); bar.setBarType(bar.BAR_TYPE_VERTICAL); bar.setFillColor(Color.green); bar.setBarWidth(0.5*dx); bar.setTitle("Random Samples"); // plot the expected curve ChartFunction f = new ChartFunction() { public double f(double x) { return Math.exp(-0.5*x*x)/Math.sqrt(2.0*Math.PI); } }; Data data = new Data(axis, f, -3, 3.0); data.setLineColor(Color.blue); data.setTitle("Exact Curve"); data.setLineWidth(2.0); } public static void main(String argv[]) { new SampleHistogram().setVisible(true); } }