Created
June 4, 2021 11:45
-
-
Save velrest/4cec5221907c4b4e9b25cb86aef3c780 to your computer and use it in GitHub Desktop.
Elixir calculate Pi from random points
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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