Differences between revisions 12 and 13
Revision 12 as of 2011-12-21 00:54:17
Size: 2430
Editor: 147
Comment:
Revision 13 as of 2013-04-17 10:50:29
Size: 2436
Editor: 59
Comment:
Deletions are marked like this. Additions are marked like this.
Line 30: Line 30:
{{{ {{{#!java

Pi Estimator

The value of PI can be calculated in a number of ways. In this example, we are estimating PI using following way:

  • Each task executes locally its portion of the loop a number of times.

  iterations = 10000
  circle_count = 0

  do j = 1,iterations
  generate 2 random numbers between 0 and 1
  xcoordinate = random1
  ycoordinate = random2
  if (xcoordinate, ycoordinate) inside circle
  then circle_count = circle_count + 1
  end do

  PI = 4.0*circle_count/iterations
  • One task acts as master and collects the results through the BSP communication interface.

  PI = pi_sum / n_processes

1) Each process computes the value of Pi locally, and 2) sends it to master task using send() function. Then, 3) the master task can recieve the messages using sync() function. Finally, we can calculate the average value of sum of PI values from each peers as below:

   1     @Override
   2     public void bsp(
   3         BSPPeer<NullWritable, NullWritable, Text, DoubleWritable> peer)
   4         throws IOException, SyncException, InterruptedException {
   5 
   6       int in = 0, out = 0;
   7       for (int i = 0; i < iterations; i++) {
   8         double x = 2.0 * Math.random() - 1.0, y = 2.0 * Math.random() - 1.0;
   9         if ((Math.sqrt(x * x + y * y) < 1.0)) {
  10           in++;
  11         } else {
  12           out++;
  13         }
  14       }
  15 
  16       double data = 4.0 * (double) in / (double) iterations;
  17       DoubleMessage estimate = new DoubleMessage(peer.getPeerName(), data);
  18 
  19       peer.send(masterTask, estimate);
  20       peer.sync();
  21     }
  22 
  23     @Override
  24     public void setup(
  25         BSPPeer<NullWritable, NullWritable, Text, DoubleWritable> peer)
  26         throws IOException {
  27       // Choose one as a master
  28       this.masterTask = peer.getPeerName(peer.getNumPeers() / 2);
  29     }
  30 
  31     public void cleanup(
  32         BSPPeer<NullWritable, NullWritable, Text, DoubleWritable> peer)
  33         throws IOException {
  34       if (peer.getPeerName().equals(masterTask)) {
  35         double pi = 0.0;
  36         int numPeers = peer.getNumCurrentMessages();
  37         DoubleMessage received;
  38         while ((received = (DoubleMessage) peer.getCurrentMessage()) != null) {
  39           pi += received.getData();
  40         }
  41 
  42         pi = pi / numPeers;
  43         peer
  44             .write(new Text("Estimated value of PI is"), new DoubleWritable(pi));
  45       }
  46     }
  47   }

PiEstimator (last edited 2013-04-17 10:50:29 by 59)