/* S0510.java * ビュフォンの針 * (C) H.Ishikawa 2008 */ package simulation; import java.applet.*; import java.awt.*; import java.awt.event.*; import window.Window; public class S0510 extends Applet implements ActionListener { Button button0; Button button1; boolean sw = false; public void init() { button0 = new Button(" 実行 "); button1 = new Button("クリア"); add(button0); add(button1); button0.addActionListener(this); button1.addActionListener(this); } public void actionPerformed(ActionEvent e) { String label = e.getActionCommand(); if (label.equals(" 実行 ")) sw = true; else sw = false; repaint(); } public void paint(Graphics g) { Window w; w = new Window(); int height; int width; int NUMBER = 1000; /* 落とした針の本数 */ double MAX = 8.0; double P = 0.5; /* 確率p */ int j; /* forのカウンタ */ int xl; /* forのカウンタ */ int n1 = 0; /* 針が交わった回数 */ double x0, y0; /* 針の中央の座標 */ double x1, y1, x2, y2; /* 針の先端の座標 */ double th; /* θ */ /* スクリーンの大きさを読み取る */ width = getSize().width; height = getSize().height; /* グラフィックの準備 */ w.setWindow(0, 0, 0, MAX, MAX * height / width, 0, height, width - 1, 0); for (xl = 0; xl <= MAX; xl++) { w.line(0, xl, 0, xl, MAX, g); /* 平行線 */ } g.setColor(Color.green); /* 緑 */ /* メイン */ if (sw == true) { for (j = 1; j <= NUMBER; j++) { x0 = MAX * Math.random(); y0 = MAX * height / width * Math.random(); th = 2 * Math.PI * Math.random(); x1 = x0 + Math.cos(th) / 2; y1 = y0 + Math.sin(th) / 2; x2 = x0 - Math.cos(th) / 2; y2 = y0 - Math.sin(th) / 2; w.line(0, x1, y1, x2, y2, g); if ((int)x1 != (int)x2) { /* (1)針の両端の座標の整数部が異なっている時 */ n1 = n1 + 1; } } g.setColor(Color.black); g.drawString("pi = " + (double)(j) /(double)(n1) * 2.0, 20, 10); } } }