Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: add Gaussian sampler #169

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion spork/randgen.janet
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,41 @@
(def diff (- end start))
(+ start (math/floor (* diff (rand-uniform)))))

(defn rand-gaussian
"Get a random sample from the standard Gaussian distribution.
Optionall specify the mean m and the standard deviation sd. E.g.:
(rand-gaussian) # => 0.1324...
(rand-gaussian 5 0.1) # => 5.3397...
"
[&opt m sd]
(default m 0)
(default sd 1)
(defn scale [x] (+ m (* sd x)))

(def p (math/rng-uniform (get-rng)))
(def q (math/rng-uniform (get-rng)))

# We use the Box-Muller transform
(let [rho (math/sqrt (* -2 (math/log q)))
theta (* 2 math/pi p)
_box (* rho (math/cos theta))
_muller (* rho (math/sin theta))
box (scale _box)
muller (scale _muller)]

(yield box)
muller))

(defn sample-n
"Generate n samples based on the random sampler f. E.g.
(sample-n |(rand-int 0 3) 4) # => @[0 1 2 0]
(sample-n |(rand-uniform) 4)
(sample-n |(rand-gaussian 5 0.1) 4)
"
[f n]
(take n (generate [_ :iterate true]
(f))))

(defn rand-index
"Get a random numeric index of an indexed data structure"
[xs]
Expand Down Expand Up @@ -85,4 +120,3 @@
[weights & paths]
~(case (,rand-weights ,weights)
,;(array/concat @[] ;(map tuple (range (length paths)) paths))))

20 changes: 20 additions & 0 deletions test/suite-randgen.janet
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
(use ../spork/test)
(use ../spork/randgen)

(start-suite)

(assert-docs "/spork/randgen")

(def delta 0.000000000000009)

(assert (do
(set-seed 1)
(def expected @[5.00917440069385
5.0318756480189
4.97222830484943
5.10069692026214])
(def actual
(sample-n |(rand-gaussian 5 0.1) 4))
(and (all |(> delta (math/abs (- $0 $1)))
expected actual)))
"sample-rand-gaussian")
Loading