diff options
author | Andreas Rumpf <rumpf_a@web.de> | 2019-05-08 17:49:49 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-05-08 17:49:49 +0200 |
commit | 65b6250e59b8db6a54e01ba3e443c9ee0add6e48 (patch) | |
tree | dde80347119a9084f5f468f825ffcfd9e3d3eb7f | |
parent | 61380d0a070a4a691e820e18b25e9dd8fb420306 (diff) | |
parent | 5363b8cc594aa2986d474a2e5ece9d41c1db47c0 (diff) | |
download | Nim-65b6250e59b8db6a54e01ba3e443c9ee0add6e48.tar.gz |
Merge pull request #11199 from mratsim/allow-float-ranges-again
Reallow float ranges in random module
-rw-r--r-- | lib/pure/random.nim | 18 |
1 files changed, 14 insertions, 4 deletions
diff --git a/lib/pure/random.nim b/lib/pure/random.nim index dddbd9d58..a25c45ee7 100644 --- a/lib/pure/random.nim +++ b/lib/pure/random.nim @@ -318,10 +318,15 @@ proc rand*(max: float): float {.benign.} = ## f = 8.717181376738381e-07 rand(state, max) -proc rand*[T: Ordinal](r: var Rand; x: HSlice[T, T]): T = +proc rand*[T: Ordinal or SomeFloat](r: var Rand; x: HSlice[T, T]): T = ## For a slice `a..b`, returns a value in the range `a..b` using the given ## state. ## + ## Allowed input types are: + ## * Integer + ## * Floats + ## * Enums without holes + ## ## See also: ## * `rand proc<#rand,HSlice[T,T]>`_ that accepts a slice and uses the ## default random number generator @@ -333,9 +338,14 @@ proc rand*[T: Ordinal](r: var Rand; x: HSlice[T, T]): T = doAssert r.rand(1..6) == 4 doAssert r.rand(1..6) == 4 doAssert r.rand(1..6) == 6 - result = T(rand(r, int(x.b) - int(x.a)) + int(x.a)) - -proc rand*[T: Ordinal](x: HSlice[T, T]): T = + let f = r.rand(-1.0 .. 1.0) + ## f = 0.8741183448756229 + when T is SomeFloat: + result = rand(r, x.b - x.a) + x.a + else: # Integers and Enum types + result = T(rand(r, int(x.b) - int(x.a)) + int(x.a)) + +proc rand*[T: Ordinal or SomeFloat](x: HSlice[T, T]): T = ## For a slice `a..b`, returns a value in the range `a..b`. ## ## If `randomize<#randomize>`_ has not been called, the sequence of random |