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