Menu

Part 2 Multithreaded pi estimation [10 marks]: In the class PiEstimation is a simple algorithm that makes an estimate of Pi. The algorithm works by throwing theoretical darts at a dart board like the …

Question

Part 2 Multithreaded pi estimation [10 marks]: In the class…

Part 2 Multithreaded pi estimation [10 marks]:
In the class PiEstimation is a simple algorithm that makes an estimate of Pi. The algorithm
works by throwing theoretical darts at a dart board like the one in the drawing below,
darts that hit the board fall within the quarter circle darts that miss are outside it. The
dartboard has a height and width of 1, this makes our calculations easier. We throw a dart
by generating a random x and y coordinate for the dart between 0 and 1. A dart is said to
hit the board if the distance from the origin is less than 1, we can calculate this using
pythagorus (x2+y2 = dist2) If we take the proportion of darts that hit the board (divide the
number of hits by the total number of darts thrown) and multiply by 4 we get a
surpassingly accurate estimate for Pi.

This estimate only works because we have thrown a lot of darts. Rewrite the application
so that it can be run across multiple threads. 

 

You answer should include the following:
 

• A TotalWithin class that keeps track of the number of darts that are within the dart board
• A class that extends Thread which throws darts, works out their distance from the origin
and increases the value held within TotalWithin if needed.
• Test your programme with 4 threads running and get an estimate of pi based on 1 billion
darts.

 

import java.util.Random;

public class PiEstimator {
    //number of iterations the algorithm, a larger number here should result in a more accurate estimate
    public static int numberOfDarts = 1000000;
    public static void main(String[] args) {
        //how many darts lie within the quarter circle region
        int within = 0;
        Random r = new Random();
        for(int i = 0; i< numberOfDarts; i++){
            //get x and y coordinates for the darts
            double x = r.nextDouble();
            double y = r.nextDouble();
            //calculate the distance from the origin (0, 0) darts with a distance less than 1 are within the
            //quarter circle so add these to within
            double dist = Math.sqrt((x*x) + (y*y));
            if(dist < 1)
                within++;
        }

        //estimate pi by getting proportion of darts in the quarter circle and multiplying by 4.
        double estimate = (double)within/numberOfDarts *4;
        System.out.println(estimate);

    }
}


OR

Leave a Reply

Your email address will not be published. Required fields are marked *