In case Flash no longer exists; a copy of this site is included in the Flashpoint archive's "ultimate" collection.

Dead Code Preservation :: Archived AS3 works from wonderfl.net

モンテカルロ法で円周率

課題ができない友人に捧げるモンテカルロ(謎
相当長いこと置いておかないと精度良い結果は得られません
※重いので注意
Get Adobe Flash player
by ton 07 Feb 2009
//課題ができない友人に捧げるモンテカルロ(謎
//相当長いこと置いておかないと精度良い結果は得られません
//※重いので注意
package {
    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();
        public function MonteCarlo():void {
            this.graphics.lineStyle(0);
            this.graphics.drawCircle(0, 0, 1 * SCALE);
            this.graphics.lineStyle();
            tf.autoSize = "left";
            tf.background = true;
            addChild(tf);
            
            addEventListener(Event.ENTER_FRAME, onEnterFrameHandler);
        }
        
        private function onEnterFrameHandler(e:Event):void {
            n++;
            var _x:Number = Math.random();
            var _y:Number = Math.random();
            if (Math.sqrt(_x * _x + _y * _y) <= 1.0) {
                r++;
                this.graphics.beginFill(0xff0000);
            }else {
                this.graphics.beginFill(0x000000);
            }
            this.graphics.drawCircle(_x*SCALE, _y*SCALE, 1);
            tf.text = r + "/" + n + "\n" + "π=" + 4 * r / n;
        }
    }
}