MCMCで積分求める
/**
* Copyright uwi ( http://wonderfl.net/user/uwi )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/5hPg
*/
package {
import flash.display.*;
import flash.events.*;
import flash.text.TextField;
import flash.utils.getTimer;
import flash.geom.*;
public class Test extends Sprite {
private var _tf : TextField;
private var _bmd : BitmapData;
private var _x : Number;
private var _y : Number;
private var _sum : Number;
private var _step : Number;
public function Test() {
_tf = new TextField();
_tf.width = 465;
_tf.height = 465;
_bmd = new BitmapData(465, 465, false, 0xffffff);
addChild(new Bitmap(_bmd));
addChild(_tf);
_x = _y = 0;
_cur = f(_x, _y);
_sum = 0;
_step = 0;
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private var _ct : ColorTransform = new ColorTransform(1, 1, 1, 1, 20, 20, 40);
private var _cur : Number;
private function onEnterFrame(e : Event) : void
{
_bmd.lock();
for(var i : uint = 0;i < 30000;i++){
var r : Number = choose() * 1.0;
var nx : Number = (i & 1) == 0 ? _x + r : _x;
var ny : Number = (i & 1) == 0 ? _y : _y + r;
if(nx * nx + ny * ny > 100)continue;
var nex : Number = f(nx, ny);
var p : Number = nex / _cur;
if(p > Math.random()){
_x = nx;
_y = ny;
_cur = nex;
_bmd.setPixel(_x * 20 + 465 / 2, _y * 20 + 465 / 2, 0x000000);
}
_sum += _cur;
_step++;
}
_bmd.colorTransform(_bmd.rect, _ct);
_bmd.unlock();
// なんで0.5になるんだ・・
tr(_step, _sum / _step);
}
private function choose() : Number
{
return (Math.random() + Math.random() + Math.random()) * 2 / 3 - 1.0;
}
private function f(x : Number, y : Number) : Number
{
return Math.exp(-(x * x + y * y));
}
private function tr(...o : Array) : void
{
_tf.appendText(o + "\n");
_tf.scrollV = _tf.maxScrollV;
}
}
}