forked from: モンテカルロ法で円周率
// forked from ton's モンテカルロ法で円周率
package {
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.Event;
import flash.text.TextField;
[SWF(width=465, height=465, frameRate=120)]
public class MonteCarlo extends Sprite {
private const SCALE:int = 465;
private var n:int = 0;
private var r:int = 0;
private var tf:TextField = new TextField();
private var bd:BitmapData = new BitmapData (SCALE, SCALE, false, 0xFFFFFF);
public function MonteCarlo():void {
this.graphics.lineStyle(0);
this.graphics.drawCircle(0, 0, 1 * SCALE);
this.graphics.lineStyle();
bd.draw (this);
this.graphics.clear ();
addChild (new Bitmap (bd));
tf.autoSize = "left";
tf.background = true;
addChild(tf);
addEventListener(Event.ENTER_FRAME, onEnterFrameHandler);
}
private function onEnterFrameHandler(e:Event):void {
bd.lock ();
for (var boost:int = 0; boost < 10000; boost++) {
n++;
var _x:Number = Math.random();
var _y:Number = Math.random();
if (Math.sqrt(_x * _x + _y * _y) <= 1.0) {
r++;
bd.setPixel(_x*SCALE, _y*SCALE, 0xff0000);
}else {
bd.setPixel(_x*SCALE, _y*SCALE, 0x000000);
}
}
bd.unlock ();
tf.text = r + "/" + n + "\n" + "π=" + 4 * r / n;
}
}
}