「算法基礎」蒙特卡洛模擬方法—計算PI值

在抽獎、彩票甚至是賭博中計算盈利的概率,用到該方法。通過大量的隨機樣本,去了解系統和計算。

經典案例:求PI值。

PI=4*圓/方,隨機打入一個點,進入圓內或者圓外,最後可用PI=4*紅色點/所有點。

「算法基礎」蒙特卡洛模擬方法—計算PI值

//圓類

public class Circle {

private int x, y, r;

public Circle(int x, int y, int r){

this.x = x;

this.y = y;

this.r = r;

}

public int getX(){ return x; }

public int getY(){ return y; }

public int getR(){ return r; }

public boolean contain(Point p){

return Math.pow(p.x - x, 2) + Math.pow(p.y - y, 2) <= r*r; //判斷是否在圓內。

}

}

畫點

for(int i = 0 ; i < points.size() ; i ++){

Point p = points.get(i);

if(circle.contain(p))

AlgoVisHelper.setColor(g2d, AlgoVisHelper.Red);

else

AlgoVisHelper.setColor(g2d, AlgoVisHelper.Green);

AlgoVisHelper.fillCircle(g2d, p.x, p.y, 3);

}

隨機生成

for(int i = 0 ; i < N ; i ++){

frame.render(circle, points);

AlgoVisHelper.pause(DELAY);

int x = (int)(Math.random() * frame.getCanvasWidth());

int y = (int)(Math.random() * frame.getCanvasHeight());

Point p = new Point(x, y);

points.add(p);

}

進行計算

public void addPoint(Point p){

points.add(p);

if(circle.contain(p))

insideCircle ++;

}

public double estimatePi(){

if(points.size() == 0)

return 0.0;

int circleArea = insideCircle;

int squareArea = points.size();

return (double)circleArea * 4 / squareArea;

}


需要完整代碼,請關注學點乾貨,點贊並轉發該文章,然後私信乾貨菌獲取。


分享到:


相關文章: