Skip to content

Instantly share code, notes, and snippets.

@gavinking
Last active December 25, 2015 04:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gavinking/6918556 to your computer and use it in GitHub Desktop.
Save gavinking/6918556 to your computer and use it in GitHub Desktop.
Parallel algorithm for π, originally by Russel Winder
import java.util.concurrent {
Callable,
ScheduledThreadPoolExecutor
}
void execute(Integer numberOfTasks) {
value n = 1G; // same number of iterations as Java
value delta = 1.0 / n;
value startTime = process.nanoseconds;
value sliceSize = n / numberOfTasks;
value executor = ScheduledThreadPoolExecutor(numberOfTasks);
class Task(Integer id) satisfies Callable<Float> {
shared actual Float call() {
value start = 1 + id * sliceSize;
value end = (id + 1) * sliceSize;
variable value sum = 0.0;
for (i in start..end) {
value x = (i - 0.5) * delta;
sum += 1.0 / (1.0 + x*x);
}
return sum;
}
}
value futures = [for (i in 0:numberOfTasks) executor.submit(Task(i))];
assert (nonempty futures);
value pi = 4.0 * delta * sum { for (f in futures) f.get() };
value elapseTime = (process.nanoseconds - startTime) / 1.0G;
outputN("pi_ceylon_futures", pi, n, elapseTime, numberOfTasks);
}
"Calculate π using quadrature realized with a parallel algorithm using callables, futures and executors."
by("Russel Winder")
void run() {
execute(1);
execute(2);
execute(8);
execute(32);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment