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

rng: avoid extreme values in gaussian #8

Open
wants to merge 3 commits into
base: devel
Choose a base branch
from
Open
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
7 changes: 4 additions & 3 deletions src/rng/milcrng.nim
Original file line number Diff line number Diff line change
Expand Up @@ -148,14 +148,15 @@ proc gaussian*(prn: var RngMilc6): float32 =
result = prn.gset
else:
const
TINY = 9.999999999999999e-308
MAX = 0x01000000.float
SCALE1 = 1.0 / (MAX + 1.0)
var
v: cdouble
p: cdouble
r: cdouble
v = prn.uniform
v = SCALE1 * (prn.uniform * MAX + 1.0)
p = prn.uniform * 2.0 * PI
r = sqrt(-2.0 * ln(v + TINY))
r = sqrt(-2.0 * ln(v))
result = r * cos(p)

# Only needed for non-vectorized RNGs.
Expand Down
5 changes: 3 additions & 2 deletions src/rng/mrg32k3a.nim
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ proc seed*(prn: var MRG32k3a; sed,index: auto) {.inline.} =
seedIndep(prn, ss, index)

proc uniform*(prn:var MRG32k3a):float =
## Uniform random numbers from 0 to 1, excluding 0 and 1.
var p1,p2:float
p1 = a12 * prn.s1[1].float - a13n * prn.s1[0].float
p1 = p1 mod m1
Expand All @@ -145,11 +146,11 @@ proc uniform*(prn:var MRG32k3a):float =
proc gaussian*(prn: var MRG32k3a): float =
## Gaussian normal deviate
## Probability distribution exp( -x*x/2 ), so < x^2 > = 1
const TINY = 9.999999999999999e-308
# uniform excludes 0 and 1
var v,p,r: float
v = prn.uniform
p = prn.uniform * 2.0 * PI
r = sqrt(-2.0 * ln(v + TINY))
r = sqrt(-2.0 * ln(v))
result = r * cos(p)

import maths/types
Expand Down