Difference between revisions of "CSC352 Homework 1 2013"
(→Computing Pi using the Monte Carlo Method: Is it worth multithreading?) |
|||
Line 18: | Line 18: | ||
<br /> | <br /> | ||
<source lang="java"> | <source lang="java"> | ||
− | + | /* MonteCarloPi.java | |
+ | * D. Thiebaut | ||
+ | * A simple demo program for computing an approximation of Pi using | ||
+ | * the Monte Carlo method. | ||
+ | * | ||
+ | */ | ||
import java.util.Random; | import java.util.Random; | ||
Line 46: | Line 51: | ||
</source> | </source> | ||
<br /> | <br /> | ||
+ | To run the program, save it in a file called MonteCarloPi.java and proceed as follows (user input is in bold): | ||
+ | |||
+ | '''javac MonteCarloPi.java''' | ||
+ | '''java MonteCarloPi ''' | ||
+ | 10000000 random samples yield an approximation of Pi = 3.140818 |
Revision as of 09:13, 11 September 2013
--D. Thiebaut (talk) 09:59, 11 September 2013 (EDT)
Computing Pi using the Monte Carlo Method:
Is it worth multithreading?
A Monte-Carlo Calculation of Pi, by Michael Jay Schillaci, Ph.D. at Roberts Wesleyan College, is a good introduction to computing Pi using Monte-Carlo (See Section 1.3).
The whole idea is to throw darts at a square target in which lies a concentric circle whose diameter is the same as the side of the square. After throwing a huge number N of darts randomly, i.e. not aiming for the circle but aiming just for the square, the ratio of holes created by the darts inside the circle, which we'll call Nc, relative to N is approximately Pi/4. The larger N is, the closer to Pi/4 the ratio becomes.
The goal for this assignment is to compute the speedup of a multithreaded java application where each thread computes its own version of Nc given N. The main program accumulates the different Nc values and the different N values from the threads and reports the resulting value of Pi, and the elapsed user time in ms.
Here is a simple serial version of the Monte Carlo program:
/* MonteCarloPi.java
* D. Thiebaut
* A simple demo program for computing an approximation of Pi using
* the Monte Carlo method.
*
*/
import java.util.Random;
public class MonteCarloPi {
static Random generator = new Random( System.currentTimeMillis() );
/**
* @param args
*/
public static void main(String[] args) {
long N = 10000000;
if ( args.length > 1 )
N = Long.parseLong( args[0] );
long Nc = 0;
for ( long i=0; i<N; i++ ) {
float x = generator.nextFloat()*2 - 1; // random float in [-1,1]
float y = generator.nextFloat()*2 - 1; // random float in [-1,1]
if ( x*x + y*y <= 1.0f )
Nc += 1;
}
System.out.println( N + " random samples yield an approximation of Pi = " + 4.0*Nc/N );
}
}
To run the program, save it in a file called MonteCarloPi.java and proceed as follows (user input is in bold):
javac MonteCarloPi.java java MonteCarloPi 10000000 random samples yield an approximation of Pi = 3.140818