-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculatingPI.java
More file actions
31 lines (30 loc) · 1.3 KB
/
Copy pathCalculatingPI.java
File metadata and controls
31 lines (30 loc) · 1.3 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
/* *****************************************************************************
* Name: Ada Lovelace
* Coursera User ID: 123456
* Last modified: October 16, 1842
**************************************************************************** */
public class CalculatingPI {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
long trials = Long.parseLong(args[1]);
double radius = 0.5 * a;
StdDraw.setCanvasSize(a, a);
StdDraw.setScale(-radius - 50, radius + 50);
StdDraw.circle(0, 0, radius);
StdDraw.square(0, 0, 0.5 * a);
int point_inside_circle = 0;
for (int i = 0; i < trials; i++) {
double randomX = -radius + Math.random() * (2 * radius);
double y = Math.sqrt(radius * radius - randomX * randomX);
double randomY = -radius + Math.random() * (2 * radius);
StdDraw.setPenColor(StdDraw.BLUE);
StdDraw.point(randomX, randomY);
if (Math.abs(randomY) <= y)
point_inside_circle++;
}
double pi = (double) (4 * point_inside_circle) / trials;
String s = "pi = (4 * point inside circle/ points inside square)" + " = " + pi;
StdDraw.text(0, 0, s);
System.out.println(pi);
}
}