Skip to content

Instantly share code, notes, and snippets.

@volgar1x
Last active August 29, 2015 14:15
Show Gist options
  • Save volgar1x/587ece6f41b416d49c0d to your computer and use it in GitHub Desktop.
Save volgar1x/587ece6f41b416d49c0d to your computer and use it in GitHub Desktop.
defmodule Montecarlo.PI do
def sample(_, 0, acc) do
acc
end
def sample(state, n, acc) do
{x, state} = :random.uniform_s(state)
{y, state} = :random.uniform_s(state)
res = x*x+y*y
if res < 1 do
sample(state, n-1, acc+1)
else
sample(state, n-1, acc)
end
end
def sample(n, sender) do
:random.seed(:erlang.now())
result = sample(:random.seed(), n, 0)
send sender, result
end
def run(samples, c) when is_integer(c) do
n = trunc(samples / c)
for _ <- 1..c do
spawn(__MODULE__, :sample, [n, self])
end
results = for _ <- 1..c do
receive do
result -> result
end
end
result = Enum.reduce(results, fn(acc, x) -> acc + x end)
result / samples * 4
end
end
Montecarlo.PI.run(1000000000, 4)
import java.util.stream.IntStream;
import java.util.Random;
public class MontecarloPI {
static IntStream repeat(int value, int times) {
int[] tab = new int[times];
for (int i = 0; i < times; i++) {
tab[i] = value;
}
return IntStream.of(tab);
}
static int sample(int iters) {
Random r = new Random(System.nanoTime());
int inside = 0;
for (int i = 0; i < iters; i++) {
double x = r.nextDouble(),
y = r.nextDouble();
if (x*x+y*y < 1.0) {
inside++;
}
}
return inside;
}
public static void main(String[] args) {
final int precision = Integer.parseInt(args[0]);
final int concurrency = Integer.parseInt(args[1]);
final int iters = precision / concurrency;
int result = repeat(iters, concurrency)
.parallel()
.map(MontecarloPI::sample)
.reduce(0, Integer::sum);
double pi = (double) result / precision * 4;
System.out.println(pi);
}
}
$ time java MontecarloPI 1000000000 4
3.141590992
java MontecarloPI 1000000000 4 105.96s user 0.06s system 380% cpu 27.828 total
$ time mix run
Compiled lib/montecarlo_pi.ex
Generated montecarlo_pi.app
mix run 1591.47s user 1.79s system 383% cpu 6:55.77 total
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment