Multiprocessing Python Program Using Monte Carlo to Compute Pi

From dftwiki3
Revision as of 15:48, 2 February 2017 by Thiebaut (talk | contribs) (Lujun's Program)
Jump to: navigation, search

--D. Thiebaut (talk) 15:46, 2 February 2017 (EST)


Lujun's Program


This program computes an approximation of Pi using the Monte Carlo approach, and using a Manager/Workers multi-processing approach. Here the manager forks out the work to P different processes, which receive a number N equal to the number of random points they must generate. Along with N, each process receives a reference to a queue where they should input their result. The manager dequeues the P different results and aggregate them into an approximation of Pi.

# undocumented program using Multiprocessing for computing Pi
# following the Monte Carlo approach.

from __future__ import print_function
from random import random
import multiprocessing
import datetime

def random_dot(n):
    inside_thread = 0
    for i in range( n ):
        x = random()
        y = random()
        if x*x + y*y < 1:
            inside_thread += 1
    return inside_thread

class WorkerProcess(multiprocessing.Process):

    def __init__( self, args ):
        multiprocessing.Process.__init__( self, args=args )
        self.n = args[0]
        self.q = args[1]

    def run(self):
        self.q.put(random_dot(self.n))

def main():
    start_time = datetime.datetime.now()
    N = 1000000
    num_p = int( input( "> How many processes do you want? " ) )

    jobs = []
    q = multiprocessing.Queue()
    for i in range( num_p ):
        pro = WorkerProcess( args=(N/num_p, q) )
        pro.start()
        jobs.append( pro )

    sum_inside = 0
    for i in range( num_p ):
        sum_inside += q.get()

    print( "%1.12f" % (4.0*sum_inside/N) )
    end_time = datetime.datetime.now()
    print( "time used:", (end_time - start_time) )
    print()
    
main()