-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMonteCarlo.java
More file actions
52 lines (44 loc) · 1.14 KB
/
MonteCarlo.java
File metadata and controls
52 lines (44 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/***
* Estimates the area under a curve or function using a Monte Carlo approach.
*
* @author kentcollins
*
*/
public abstract class MonteCarlo {
private double minX, minY, maxX, maxY;
private int totalThrows;
private int totalHits;
public MonteCarlo(double minX, double maxX, double minY,
double maxY) {
super();
this.minX = minX;
this.minY = minY;
this.maxX = maxX;
this.maxY = maxY;
this.totalThrows = 0;
this.totalHits = 0;
}
public void simulate() {
double[] rand = getRandomLocation(); // [x,y]
boolean hit = checkHit(rand);
if (hit)
totalHits++;
totalThrows++;
}
private double[] getRandomLocation() {
double x = Math.random() * (maxX - minX) + minX;
double y = Math.random() * (maxY - minY) + minY;
return new double[] { x, y };
}
public abstract boolean checkHit(double[] xy);
public double getHitRatio() {
if (totalThrows == 0)
throw new UnsupportedOperationException(
"Attempted division by zero -- no throws yet!");
return (double) totalHits / totalThrows;
}
public double getEstimatedArea() {
double totalArea = (maxY - minY) * (maxX - minX);
return totalArea * getHitRatio();
}
}