I have this short program that attempts to compute an approximate value of \$\pi\$:
package net.coderodde.fun;
import java.awt.geom.Point2D;
import java.util.Arrays;
import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* This class computes an approximate value of Pi.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Feb 23, 2018)
*/
public class MonteCarloPiComputer {
/**
* The default radius of the simulated circle.
*/
private static final double DEFAULT_RADIUS = 0.5;
/**
* The random number generator.
*/
private final Random random;
public MonteCarloPiComputer(Random random) {
this.random =
Objects.requireNonNull(
random,
"The input random number generator is null.");
}
public MonteCarloPiComputer() {
this(new Random());
}
/**
* Computes an approximate value of Pi via a Monte Carlo method. The method
* creates {@code samples} random points, computes the percentage of all
* points within the radius from the center of the simulated square and
* multiplies it by {@code 4.0}.
*
* @param samples the number of points to create.
* @param radius the radius of the simulated circle.
* @return an approximate value of Pi.
*/
public double computeApproximateValueOfPi(int samples, double radius) {
Point2D.Double center = new Point2D.Double(radius, radius);
double squareSideLength = 2.0 * radius;
long numberOfPointsWithinCircle =
IntStream.range(0, samples)
.mapToObj(
(i) -> {
return new Point2D.Double(
squareSideLength * random.nextDouble(),
squareSideLength * random.nextDouble());
})
.filter((point) -> {
return point.distance(center) < radius;
}).count();
return (4.0 * numberOfPointsWithinCircle) / samples;
}
/**
* Computes an approximate value of Pi via a Monte Carlo method with default
* radius.
*
* @param samples the number of points to create.
* @return an approximate value of Pi.
*/
public double computeApproximateValueOfPi(int samples) {
return computeApproximateValueOfPi(samples, DEFAULT_RADIUS);
}
public static void main(String[] args) {
MonteCarloPiComputer computer = new MonteCarloPiComputer();
for (int samples = 100_000; samples <= 1_000_000; samples += 100_000) {
double approximation =
computer.computeApproximateValueOfPi(samples);
double percentage = approximation / Math.PI;
System.out.print(String.format("%7d: ", samples));
System.out.print(String.format("%10f", approximation));
System.out.println(
String.format(
", percentage from exact Pi: %10f",
(100.0 * percentage)));
}
}
}
Critique request
I would like to hear any comments and improvement suggestions.