Skip to content

Instantly share code, notes, and snippets.

@dotcypress
Created January 16, 2013 12:38
Show Gist options
  • Save dotcypress/4546852 to your computer and use it in GitHub Desktop.
Save dotcypress/4546852 to your computer and use it in GitHub Desktop.
Вычисляем PI методом Монте-Карло
%% Вычисляем PI методом Монте-Карло
-module(pi).
-export([calculate/1, parallel_calculate/2, start_worker/2]).
calculate(Hits) ->
Acc = test_hit(Hits, 0),
{ok, 4.0 * Acc / Hits}.
parallel_calculate(Hits, Workers) ->
start_workers(Workers, Hits),
Acc = start_receivers(Workers, 0),
{ok, 4.0 * Acc / (Hits * Workers)}.
start_workers(0, _) ->
ok;
start_workers(Amount, Hits) ->
spawn(pi, start_worker, [Hits, self()]),
start_workers(Amount - 1, Hits).
start_receivers(0, Acc) ->
Acc;
start_receivers(Amount, Acc) ->
receive
Value ->
start_receivers(Amount - 1, Acc + Value)
end.
start_worker(Hits, PID) ->
Acc = test_hit(Hits, 0),
PID ! Acc.
test_hit(0, Acc) ->
Acc;
test_hit(Amount, Acc) ->
test_hit(Amount - 1, Acc + sample()).
sample() ->
X = random:uniform(),
Y = random:uniform(),
Hypo = math:sqrt(X * X + Y * Y),
if
Hypo < 1 ->
1;
true ->
0
end.
@maxlapshin
Copy link

Отвратительная сходимость, если честно.

@maxlapshin
Copy link

Да и распределенность ни к черту:

3> timer:tc(fun() -> pi:calculate(10000000) end).
{5630091,{ok,3.1413384}}
4> timer:tc(fun() -> pi:parallel_calculate(10000000, 8) end).
{10569714,{ok,3.1419864}}

Надо обсчитывать среднее в воркерах а не слать миллион сообщений

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment