「算法基础」蒙特卡洛模拟方法—计算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;

}


需要完整代码,请关注学点干货,点赞并转发该文章,然后私信干货菌获取。


分享到:


相關文章: