forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPiApproximation.java
More file actions
74 lines (64 loc) · 2.08 KB
/
PiApproximation.java
File metadata and controls
74 lines (64 loc) · 2.08 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.thealgorithms.maths;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Implementation to calculate an estimate of the number π (Pi).
*
* We take a random point P with coordinates (x, y) such that 0 ≤ x ≤ 1 and 0 ≤ y ≤ 1.
* If x² + y² ≤ 1, then the point is inside the quarter disk of radius 1,
* else the point is outside. We know that the probability of the point being
* inside the quarter disk is equal to π/4.
*
*
* @author [Yash Rajput](https://github.com/the-yash-rajput)
*/
public final class PiApproximation {
private PiApproximation() {
throw new AssertionError("No instances.");
}
/**
* Structure representing a point with coordinates (x, y)
* where 0 ≤ x ≤ 1 and 0 ≤ y ≤ 1.
*/
static class Point {
double x;
double y;
Point(double x, double y) {
this.x = x;
this.y = y;
}
}
/**
* This function uses the points in a given list (drawn at random)
* to return an approximation of the number π.
*
* @param pts List of points where each point contains x and y coordinates
* @return An estimate of the number π
*/
public static double approximatePi(List<Point> pts) {
double count = 0; // Points in circle
for (Point p : pts) {
if ((p.x * p.x) + (p.y * p.y) <= 1) {
count++;
}
}
return 4.0 * count / pts.size();
}
/**
* Generates random points for testing the Pi approximation.
*
* @param numPoints Number of random points to generate
* @return List of random points
*/
public static List<Point> generateRandomPoints(int numPoints) {
List<Point> points = new ArrayList<>();
Random rand = new Random();
for (int i = 0; i < numPoints; i++) {
double x = rand.nextDouble(); // Random value between 0 and 1
double y = rand.nextDouble(); // Random value between 0 and 1
points.add(new Point(x, y));
}
return points;
}
}