Java 蒙特卡洛方法圆周率 π 值求解

liuyubobobo (Yubo Liu) · GitHub

MTKLExp.java

import java.awt.*;

public class MTKLExp {

    private int squareSide;
    private int N;
    private int outputInterval = 100;

    public MTKLExp(int squareSide, int N){
        if(squareSide <= 0 || N <= 0)
        {
            throw new IllegalArgumentException("squareSide and N must > 0");
        }

        this.squareSide = squareSide;
        this.N = N;
    }

    public void setOutputInterval(int interval){
        if ( interval <= 0)
        {
            throw new IllegalArgumentException("interval must be > 0");
        }

        this.outputInterval = interval;
    }

    public void run(){
        Circle circle = new Circle(squareSide/2, squareSide/2, squareSide/2);
        MonteCarloPiData data = new MonteCarloPiData(circle);

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

            if( i % outputInterval == 0)
                System.out.println(data.estimatePi());

            int x = (int)(Math.random()*squareSide);
            int y = (int)(Math.random()*squareSide);
            data.addPoint(new Point(x, y));

        }
    }

    public static void main(String[] args){

        int squareSide = 800;
        int N = 1000000;

        MTKLExp exp = new MTKLExp(squareSide, N);
        exp.setOutputInterval(100);
        exp.run();
    }
}

MonteCarloPiData.java
import java.util.LinkedList;
import java.awt.*;

public class MonteCarloPiData {

    private Circle circle;
    private LinkedList<Point> points;
    private int insideCircle = 0;

    public MonteCarloPiData(Circle circle){
        this.circle = circle;
        points = new LinkedList<Point>();
    }

    public Circle getCircle(){
        return circle;
    }

    public int getPointsNumber(){
        return points.size();
    }

    public Point getPoint(int i){
        if(i < 0 || i >= points.size())
            throw new IllegalArgumentException("out of bound in getPoint!");

        return points.get(i);
    }

    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;
    }
}

Circle.java
import java.awt.*;
import javax.swing.*;

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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值