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

Reallow float ranges in random module #11199

Merged
merged 1 commit into from
May 8, 2019
Merged
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
18 changes: 14 additions & 4 deletions lib/pure/random.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Copy link
Contributor

@kaushalmodi kaushalmodi May 8, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mratsim While you are working on this PR, can you add the spaces around dotdot in the above 3 doAsserts too?

PS: I am wondering how the doAsserts on rands always pass .. How is it predicted that the first two rands will always give 4, and the third will always give 6?! Seems like one or more of those doasserts is bound to fail some time.

## 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
Expand Down