Problem Statement (Asked By Google)
The formula for the area of a circle is given by πr². Use the Monte Carlo method to approximate the value of π to three decimal places.
Hint: The equation of a circle is x² + y² = r².
Problem link: N/A
Disclaimer: Try solving the problem on your own first! Use this solution only as a reference to learn and improve.
Monte Carlo methods use random sampling to estimate numerical results. In this case, we estimate the value of π\piπ using the ratio of the areas of a circle and a square:
import java.util.Random; public class MonteCarloPi { public static double estimatePi(int iterations) { Random random = new Random(); int inCircle = 0; for (int i = 0; i < iterations; i++) { double x = random.nextDouble() * 2 - 1; // Random x in [-1, 1] double y = random.nextDouble() * 2 - 1; // Random y in [-1, 1] if (x * x + y * y <= 1) { // Check if point is inside the circle inCircle++; } } return 4.0 * inCircle / iterations; } public static void main(String[] args) { int iterations = 1_000_000; double pi = estimatePi(iterations); System.out.printf("Estimated value of Pi: %.5f%n", pi); // Output Pi up to 5 decimal places } }
To parallelize the workload:
import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class MonteCarloPiParallel { public static double estimatePi(int iterations, int threads) throws Exception { ExecutorService executor = Executors.newFixedThreadPool(threads); int iterationsPerThread = iterations / threads; Callable<Integer> task = () -> { Random random = new Random(); int inCircle = 0; for (int i = 0; i < iterationsPerThread; i++) { double x = random.nextDouble() * 2 - 1; // Random x in [-1, 1] double y = random.nextDouble() * 2 - 1; // Random y in [-1, 1] if (x * x + y * y <= 1) { // Check if point is inside the circle inCircle++; } } return inCircle; }; // Submit tasks to threads Future<Integer>[] results = new Future[threads]; for (int i = 0; i < threads; i++) { results[i] = executor.submit(task); } // Aggregate results int totalInCircle = 0; for (Future<Integer> result : results) { totalInCircle += result.get(); } executor.shutdown(); return 4.0 * totalInCircle / iterations; } public static void main(String[] args) throws Exception { int iterations = 1_000_000; int threads = 4; double pi = estimatePi(iterations, threads); System.out.printf("Estimated value of Pi (Parallel): %.5f%n", pi); // Output Pi up to 5 decimal places } }
ExecutorService
for managing threads and Future
to collect results.This solution demonstrates the power of Monte Carlo simulations and how parallelization can significantly improve performance.
Did this solution help you understand the concept better? Let me know your thoughts in the comments below! Don’t forget to follow us on Instagram @coderz.py for more DSA tips and solutions to ace your coding interviews.
Find the length of the longest absolute path to a file within the abstracted file…
You manage an e-commerce website and need to keep track of the last N order…
You are given a stream of elements that is too large to fit into memory.…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…
Build an autocomplete system that, given a query string s and a set of possible…