blob: 84ae08583ced22ea476b83930c3450b16d34a91f (
plain)
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
|
import java.util.Random;
public class CalculatePI {
static Random r = new Random();
static double piApproximation = 1.0f;
static int repetitions = 500000;
static int iteration = 0;
static double inSquare = 0;
static double inCircle = 0;
public static void main(String[] args) {
for (iteration = 0;iteration<repetitions;iteration++) approximate();
piApproximation = (inCircle/inSquare)*4.0f;
System.out.println("After "+repetitions+" iterations, pi is estimated to be "+piApproximation);
}
public static void approximate() {
double x = r.nextDouble();
double y = r.nextDouble();
inSquare++;
if (x*x + y*y < 1) {inCircle++;}
}
}
|