Skip to content

Instantly share code, notes, and snippets.

@velrest
Created June 4, 2021 11:45
Show Gist options
  • Save velrest/4cec5221907c4b4e9b25cb86aef3c780 to your computer and use it in GitHub Desktop.
Save velrest/4cec5221907c4b4e9b25cb86aef3c780 to your computer and use it in GitHub Desktop.
Elixir calculate Pi from random points
defmodule Experiment do
def pi( data \\ %{total: 0, circle: 0}, num_points) do
%{total: total, circle: circle} = data
case num_points do
num_points when num_points == 0 ->
4 * circle/total
num_points ->
:math.pow(:rand.uniform, 2) + :math.pow(:rand.uniform, 2)
|> case do
x when x <= 1 ->
%{data | total: total + 1, circle: circle + 1}
_ ->
%{data | total: total + 1 }
end
|> pi(num_points - 1)
end
end
end
IO.puts Experiment.pi(100000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment