# 29.7. Distributed Execution Example

In this example, parallel distributed execution is used to approximate the value of Pi (π)
1. As shown below, the area of a square is:
Area of a Square (S) = 4r 2
2. The following is an equation for the area of a circle:
Area of a Circle (C) = π x r 2
3. Isolate r 2 from the first equation:
r 2 = S/4
4. Inject this value of r 2 into the second equation to find a value for Pi:
C = Sπ/4
5. Isolating π in the equation results in:
C = Sπ/4
4C = Sπ
4C/S = π Figure 29.1. Distributed Execution Example

If we now throw a large number of darts into the square, then draw a circle inside the square, and discard all dart throws that landed outside the circle, we can approximate the C/S value.
The value of π is previously worked out to 4C/S. We can use this to derive the approximate value of π. By maximizing the amount of darts thrown, we can derive an improved approximation of π.
In the following example, we throw 10 million darts by parallelizing the dart tossing across the cluster:

Example 29.6. Distributed Execution Example

```public class PiAppx {

public static void main (String [] arg){
List<Cache> caches = ...;
Cache cache = ...;

int numPoints = 10000000;
int numServers = caches.size();
int numberPerWorker = numPoints / numServers;

DistributedExecutorService des = new DefaultExecutorService(cache);
long start = System.currentTimeMillis();
CircleTest ct = new CircleTest(numberPerWorker);
List<Future<Integer>> results = des.submitEverywhere(ct);
int countCircle = 0;
for (Future<Integer> f : results) {
countCircle += f.get();
}
double appxPi = 4.0 * countCircle / numPoints;

System.out.println("Distributed PI appx is " + appxPi +
" completed in " + (System.currentTimeMillis() - start) + " ms");
}

private static class CircleTest implements Callable<Integer>, Serializable {

/** The serialVersionUID */
private static final long serialVersionUID = 3496135215525904755L;

private final int loopCount;

public CircleTest(int loopCount) {
this.loopCount = loopCount;
}

@Override
public Integer call() throws Exception {
int insideCircleCount = 0;
for (int i = 0; i < loopCount; i++) {
double x = Math.random();
double y = Math.random();
if (insideCircle(x, y))
insideCircleCount++;
}
return insideCircleCount;
}

private boolean insideCircle(double x, double y) {
return (Math.pow(x - 0.5, 2) + Math.pow(y - 0.5, 2))
<= Math.pow(0.5, 2);
}
}
}```