Skip to content

Instantly share code, notes, and snippets.

@krthkj
Last active August 31, 2023 18:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save krthkj/9c1868c1f69142c2952683ea91ca2a37 to your computer and use it in GitHub Desktop.
Save krthkj/9c1868c1f69142c2952683ea91ca2a37 to your computer and use it in GitHub Desktop.
Multi-Thread code - Value of Pi - Monte Carlo
// Estimate the value of Pi using Monte-Carlo Method, using sequential program
package assignments;
public class Assignment101 {
public static void main(String[] args) {
int nThrows = 100000;
long startTime = System.currentTimeMillis();
double x = 0, y = 0;
int nSuccess = 0;
for (int i = 1; i <= nThrows; i++) {
x = Math.random();
y = Math.random();
if (x * x + y * y <= 1)
nSuccess++;
}
double value = 4.0 * nSuccess / nThrows;
long stopTime = System.currentTimeMillis();
System.out.println("Approx value:" + value);
System.out.println("Difference to exact value of pi: " + (value - Math.PI));
System.out.println("Error: " + (value - Math.PI) / Math.PI * 100 + " %");
System.out.println("Time Duration: " + (stopTime - startTime) + "ms");
}
}
// Estimate the value of Pi using Monte-Carlo Method, using parallel program
package assignments;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
class PiMonteCarlo {
AtomicInteger nAtomSuccess;
int nThrows;
double value;
class MonteCarlo implements Runnable {
@Override
public void run() {
double x = Math.random();
double y = Math.random();
if (x * x + y * y <= 1)
nAtomSuccess.incrementAndGet();
}
}
public PiMonteCarlo(int i) {
this.nAtomSuccess = new AtomicInteger(0);
this.nThrows = i;
this.value = 0;
}
public double getPi() {
int nProcessors = Runtime.getRuntime().availableProcessors();
ExecutorService executor = Executors.newWorkStealingPool(nProcessors);
for (int i = 1; i <= nThrows; i++) {
Runnable worker = new MonteCarlo();
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
value = 4.0 * nAtomSuccess.get() / nThrows;
return value;
}
}
public class Assignment102 {
public static void main(String[] args) {
PiMonteCarlo PiVal = new PiMonteCarlo(100000);
long startTime = System.currentTimeMillis();
double value = PiVal.getPi();
long stopTime = System.currentTimeMillis();
System.out.println("Approx value:" + value);
System.out.println("Difference to exact value of pi: " + (value - Math.PI));
System.out.println("Error: " + (value - Math.PI) / Math.PI * 100 + " %");
System.out.println("Available processors: " + Runtime.getRuntime().availableProcessors());
System.out.println("Time Duration: " + (stopTime - startTime) + "ms");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment