正規分布の確率
double gauss(double x,double sd){ return (1.0/(Math.sqrt(2.0*Math.PI)*sd))*Math.exp(-x*x/(2.0*sd*sd)); }ここではこのグラフを表示し、指定範囲の確率を数値積分法で計算します。
double gs=0.0; double dh=0.01; for(x=0.0;x<rx;x=x+dh){ gs = gs + (gauss(x,1.0)+gauss(x+dh,1.0))*dh/2.0; }この方法は、関数の変化が緩やかな場合は正確に計算できますが、変化が激しいときは誤差が大きくなります。
import java.awt.*; import java.awt.event.*; import java.applet.*; /** * <p>タイトル: </p> * <p>説明: </p> * <p>著作権: Copyright (c) 2004</p> * <p>会社名: </p> * @author 未入力 * @version 1.0 */ public class Applet1 extends Applet { private boolean isStandalone = false; double rx=0.0; private Scrollbar scrollbar1 = new Scrollbar(); private Label pblabel = new Label(); private Label xlabel = new Label(); private Label label2 = new Label(); private Label label3 = new Label(); //引数値の取得 public String getParameter(String key, String def) { return isStandalone ? System.getProperty(key, def) : (getParameter(key) != null ? getParameter(key) : def); } //アプレットのビルド public Applet1() { } //アプレットの初期化 public void init() { try { jbInit(); } catch(Exception e) { e.printStackTrace(); } } //コンポーネントの初期化 private void jbInit() throws Exception { this.setLayout(null); scrollbar1.setMaximum(50); scrollbar1.setOrientation(0); scrollbar1.setBounds(new Rectangle(27, 174, 94, 18)); scrollbar1.addAdjustmentListener(new java.awt.event.AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { scrollbar1_adjustmentValueChanged(e); } }); pblabel.setText("0.0"); pblabel.setBounds(new Rectangle(220, 172, 45, 20)); xlabel.setText("0.0"); xlabel.setBounds(new Rectangle(146, 172, 47, 20)); label2.setText("x"); label2.setBounds(new Rectangle(146, 157, 37, 20)); label3.setText("確率"); label3.setBounds(new Rectangle(217, 156, 53, 17)); this.add(label3, null); this.add(label2, null); this.add(scrollbar1, null); this.add(xlabel, null); this.add(pblabel, null); } //アプレットの情報取得 public String getAppletInfo() { return "アプレット情報"; } //引数情報の取得 public String[][] getParameterInfo() { return null; } public void paint(Graphics g){ double x=0.0,y; int ox=20,oy=120; double px,py; px=-4.0; py=gauss(px,1.0); for(x=-4.0;x<4.0;x=x+0.02){ y=gauss(x,1.0); g.drawLine((int)((px+4.0)*30.0)+ox,(int)(oy-py*200.0), (int)((x+4.0)*30.0)+ox,(int)(oy-y*200.0)); //範囲なら縦線表示 if( x>0.0 && x<rx){ g.setColor(Color.blue); g.drawLine((int)((x+4.0)*30.0)+ox,oy, (int)((x+4.0)*30.0)+ox,(int)(oy-y*200.0)); g.setColor(Color.black); } px=x;py=y; } } double gauss(double x,double sd){ return (1.0/(Math.sqrt(2.0*Math.PI)*sd))*Math.exp(-x*x/(2.0*sd*sd)); } double area(double rx){ double x; double gs=0.0; double dh=0.01; for(x=0.0;x<rx;x=x+dh){ gs = gs + (gauss(x,1.0)+gauss(x+dh,1.0))*dh/2.0; } //System.out.println("rx:"+rx+" area:"+gs); pblabel.setText(Double.toString(gs)); xlabel.setText(Double.toString(rx)); return gs; } void scrollbar1_adjustmentValueChanged(AdjustmentEvent e) { rx=(double)e.getValue()/10.0; area((double)rx); repaint(); } }