aboutsummaryrefslogtreecommitdiffstats
path: root/lib/stdlib/src/rand.erl
diff options
context:
space:
mode:
authorGuilherme Andrade <[email protected]>2017-03-18 19:48:23 +0000
committerGuilherme Andrade <[email protected]>2017-04-20 21:30:53 +0100
commitdff85f3d6fdb4b3453d863bf9208073564a9fcf2 (patch)
tree57bd88d6776d40a89ae975e7f3cb569d783c2154 /lib/stdlib/src/rand.erl
parent2cc47f22e4cb775422a6a7fb1b94836e7cf51143 (diff)
downloadotp-dff85f3d6fdb4b3453d863bf9208073564a9fcf2.tar.gz
otp-dff85f3d6fdb4b3453d863bf9208073564a9fcf2.tar.bz2
otp-dff85f3d6fdb4b3453d863bf9208073564a9fcf2.zip
rand: Support arbitrary normal distributions
Diffstat (limited to 'lib/stdlib/src/rand.erl')
-rw-r--r--lib/stdlib/src/rand.erl16
1 files changed, 15 insertions, 1 deletions
diff --git a/lib/stdlib/src/rand.erl b/lib/stdlib/src/rand.erl
index 1f457b9e0e..cef83da287 100644
--- a/lib/stdlib/src/rand.erl
+++ b/lib/stdlib/src/rand.erl
@@ -28,7 +28,7 @@
export_seed/0, export_seed_s/1,
uniform/0, uniform/1, uniform_s/1, uniform_s/2,
jump/0, jump/1,
- normal/0, normal_s/1
+ normal/0, normal/2, normal_s/1, normal_s/3
]).
-compile({inline, [exs64_next/1, exsplus_next/1,
@@ -178,6 +178,13 @@ normal() ->
_ = seed_put(Seed),
X.
+%% normal/2: returns a random float with N(μ, σ²) normal distribution
+%% updating the state in the process dictionary.
+
+-spec normal(Mean :: number(), Variance :: number()) -> float().
+normal(Mean, Variance) ->
+ Mean + (math:sqrt(Variance) * normal()).
+
%% normal_s/1: returns a random float with standard normal distribution
%% The Ziggurat Method for generating random variables - Marsaglia and Tsang
%% Paper and reference code: http://www.jstatsoft.org/v05/i08/
@@ -198,6 +205,13 @@ normal_s(State0) ->
false -> normal_s(Idx, Sign, -X, State)
end.
+%% normal_s/3: returns a random float with normal N(μ, σ²) distribution
+
+-spec normal_s(Mean :: number(), Variance :: number(), state()) -> {float(), NewS :: state()}.
+normal_s(Mean, Variance, State0) when Variance > 0 ->
+ {X, State} = normal_s(State0),
+ {Mean + (math:sqrt(Variance) * X), State}.
+
%% =====================================================================
%% Internal functions