一様分布乱数の応用
for (i=0;i<rndNum;i++){
fx=(float) Math.random();
fy=(float) Math.random();
if ((fx*fx + fy*fy)>1.0) {
g.setColor(cgreen);//円外部
}
else {
inCircl++;
g.setColor(cred);//円内部
}
g.drawLine((int)(rx*fx)+ox,(int)(ry-(int)(ry*fy))+oy,
(int)(rx*fx)+ox,(int)(ry-(int)(ry*fy))+oy);
}
最後に、(double)inCircl/(double)rndNum)の4倍の値を表示します。これはπの値に相当します。import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class monteSim extends Applet {
private boolean isStandalone = false;
boolean BultIn=true;
long arp;
private Button button1 = new Button();
private TextField textField1 = new TextField();
private Label label1 = 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 void init() {
this.setLayout(null);
button1.setLabel("試行");
button1.setBounds(new Rectangle(160, 250, 60, 20));
button1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
button1_actionPerformed(e);
}
});
textField1.setText("1000");
textField1.setBounds(new Rectangle(80, 250, 60, 20));
label1.setText("回数");
label1.setBounds(new Rectangle(90, 230, 450, 20));
label2.setBackground(SystemColor.activeCaptionText);
label2.setText("label2");
label2.setBounds(new Rectangle(20, 250, 60, 20));
label3.setText("πの値");
label3.setBounds(new Rectangle(20, 230, 40, 20));
this.add(label2, null);
this.add(label3, null);
this.add(textField1, null);
this.add(label1, null);
this.add(button1, null);
}
public void paint(Graphics g)
{
float fx,fy,sumr=0.0f,sumd=0.0f;
int i,inCircl=0;
int ox=10,oy=10;//表示原点
int rx=200,ry=200;//半径
int rndNum;//乱数の個数
Color cred=new Color(220,50,50);
Color cgreen=new Color(50,220,50);
rndNum=Integer.parseInt(textField1.getText());//回数を読む
g.setColor(new Color(255,255,255)); //白色
g.fillRect(ox,oy,rx,ry); //背景
g.setColor(new Color(0,0,0)); //黒色
g.drawArc(ox-rx,oy,rx*2,ry*2,0,90); //円弧を表示
for (i=0;i<rndNum;i++){
//乱数を発生
fx=(float) Math.random();
fy=(float) Math.random();
if ((fx*fx + fy*fy)>1.0) {
g.setColor(cgreen);//円の外部外部
}
else {
inCircl++;
g.setColor(cred);//円の内部内部
}
//点を表示 原点:(ox,oy)
g.drawLine((int)(rx*fx)+ox,(int)(ry-(int)(ry*fy))+oy,
(int)(rx*fx)+ox,(int)(ry-(int)(ry*fy))+oy);
}
//πの表示
label2.setText(Double.toString(4.0*((double)inCircl/(double)rndNum)));
}
void button1_actionPerformed(ActionEvent e) {
//シミュレーションを行うため再表示
repaint();
}
}