Skip to content

Instantly share code, notes, and snippets.

@zhouji
Created January 20, 2012 09:44
Show Gist options
  • Save zhouji/1646469 to your computer and use it in GitHub Desktop.
Save zhouji/1646469 to your computer and use it in GitHub Desktop.
Stupid Pi Caculator
package funny;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
/**
*
* @author zhouji
*/
public class StupidPi {
static AtomicLong outerArea = new AtomicLong(0);
public static void calc(long x1, long y1, long x2, long y2, long radius) {
int rtn = 0;
for (long x = x1; x < x2; x++) {
for (long y = y1; y < y2; y++) {
if (((x - radius) * (x - radius)) + ((y - radius) * (y - radius)) > radius * radius) {
rtn++;
}
}
}
outerArea.addAndGet(rtn);
}
public static void main(String[] args) throws InterruptedException {
if( args.length == 0 ){
System.out.println("Usage: java -cp . funny.StupidPi [radius] [split]");
return;
}
final long radius = Long.parseLong(args[0]);
long split = Integer.parseInt(args[1]);
long start = System.nanoTime();
long totalArea = (2 * radius) * (2 * radius);
ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
List<Callable<Object>> todo = new ArrayList<Callable<Object>>();
for (int x = 0; x < split; x++) {
for (int y = 0; y < split; y++) {
final long x1 = x * radius * 2 / split;
final long x2 = (x + 1) * radius * 2 / split;
final long y1 = y * radius * 2 / split;
final long y2 = (y + 1) * radius * 2 / split;
todo.add(Executors.callable(new Runnable() {
public void run() {
calc(x1, y1, x2, y2, radius);
}
}));
}
}
Object answers = es.invokeAll(todo);
es.shutdown();
double pi = (totalArea - outerArea.get() + 0.0) / radius / radius;
System.out.printf("PI=%.20f\n", pi);
System.out.println("using " + (System.nanoTime() - start) / (10000000.0));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment