// // Buffon(ビュフォンの針) 2001/11/03 by ONOZATO Takehisa // // // import java.awt.*; import java.awt.event.*; import java.applet.*; public class Buffon extends Applet implements ActionListener{ Image ofs; Graphics grf; //オフスクリーン int ofsWidth=440; int ofsHeight=360; Color ofsBG=new Color(255,239,223); //背景色 Font fnt; String fname; int fstyle; //フォント int originX=60; int originY=280; //原点 int unit=40; //単位当たりのピクセル数 int needle; int needleSum; //投げた本数 int count; int countSum; //平行線にかかった本数 Button btn1,btn2; //ボタン boolean flg; //false:クリア true:試行結果表示 public void init(){ ofs=createImage(ofsWidth,ofsHeight); grf=ofs.getGraphics(); fnt=grf.getFont(); //フォント fname=fnt.getName(); fstyle=fnt.getStyle(); grf.setFont(new Font(fname,fstyle,16)); //16pt btn1=new Button("Trial"); btn1.addActionListener(this); add(btn1); btn2=new Button("Clear"); btn2.addActionListener(this); add(btn2); flg=false; needle=0; needleSum=0; count=0; countSum=0; } public void update(Graphics g) { paint(g); } public void paint(Graphics g){ grf.setColor(ofsBG); grf.fillRect(0,0,ofsWidth,ofsHeight); //背景 btn1.setBounds(340,40,50,25); //ボタンの配置 btn2.setBounds(340,70,50,25); grf.setColor(Color.gray); for(double x=0; x<6; x=x+1){ grf.drawLine(picX(x),picY(-1),picX(x),picY(6)); //平行線 } if(flg){ drawNeedle(); } g.drawImage(ofs,0,0,this); //オフスクリーンからアプレットへ描画 } /*** ボタンのイベント ***/ public void actionPerformed(ActionEvent e){ if(e.getActionCommand()=="Clear"){ flg=false; needle=0; needleSum=0; count=0; countSum=0; }else{ flg=true; } repaint(); } /*** 試行結果の表示 ***/ void drawNeedle(){ needle=100; needleSum=needleSum+100; count=0; for(int i=1; i<=100; i++){ double x1=5*Math.random(); double y1=5*Math.random(); double theta=2*Math.PI*Math.random(); double x2=x1+Math.cos(theta); double y2=y1+Math.sin(theta); int hit=Math.abs((int)(x1+1)-(int)(x2+1)); if(hit==1){ count=count+1; grf.setColor(Color.red); }else{ grf.setColor(Color.blue); } grf.drawLine(picX(x1),picY(y1),picX(x2),picY(y2)); } countSum=countSum+count; int p1=(int)(20000*((double)needle/(double)count)); int p2=(int)(20000*((double)needleSum/(double)countSum)); double p=(double)p1/10000; double q=(double)p2/10000; grf.setColor(Color.black); grf.drawString("N = "+needle,310,140); grf.drawString("n = "+count,310,165); grf.drawString("2(N/n) = "+p,310,190); grf.drawString("累計",310,220); grf.drawString("N = "+needleSum,310,245); grf.drawString("n = "+countSum,310,270); grf.drawString("2(N/n) = "+q,310,295); } /*** 座標の換算 ***/ int picX(double x){ int xx=originX+(int)(x*unit); return xx; } int picY(double y){ int yy=originY-(int)(y*unit); return yy; } }