Skip to content

Commit

Permalink
use ~ instead of - plus unsigned to obtain positive numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
rfourquet committed Sep 28, 2023
1 parent da15abd commit 7eaf94f
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 11 deletions.
13 changes: 5 additions & 8 deletions stdlib/Random/src/RNGs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -303,15 +303,12 @@ This is an internal function, subject to change.
"""
function make_seed(n::Integer)
neg = signbit(n)
n = abs(n) # n can still be negative, e.g. n == typemin(Int)
if n < 0
# we assume that `unsigned` can be called on integers `n` for which `abs(n)` is
# negative; `unsigned` is necessary for `n & 0xffffffff` below, which would
# otherwise propagate the sign bit of `n` for types smaller than UInt32
n = unsigned(n)
if neg
n = ~n
end
@assert n >= 0
seed = UInt32[]
# we directly encode the bit pattern of `abs(n)` into the resulting vector `seed`;
# we directly encode the bit pattern of `n` into the resulting vector `seed`;
# to greatly limit breaking the streams of random numbers, we encode the sign bit
# as the upper bit of `seed[end]` (i.e. for most positive seeds, `make_seed` returns
# the same vector as when we didn't encode the sign bit)
Expand All @@ -333,7 +330,7 @@ function from_seed(a::Vector{UInt32})::BigInt
neg = !iszero(a[end] & 0x80000000)
seed = sum((i == length(a) ? a[i] & 0x7fffffff : a[i]) * big(2)^(32*(i-1))
for i in 1:length(a))
neg ? -seed : seed
neg ? ~seed : seed
end


Expand Down
5 changes: 2 additions & 3 deletions stdlib/Random/src/Xoshiro.jl
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
# Lots of implementation is shared with TaskLocalRNG

"""
Xoshiro(seed)
Xoshiro(seed::Integer)
Xoshiro()
Xoshiro256++ is a fast pseudorandom number generator described by David Blackman and
Expand All @@ -21,7 +21,6 @@ multiple interleaved xoshiro instances).
The virtual PRNGs are discarded once the bulk request has been serviced (and should cause
no heap allocations).
The `seed` may be an integer or a vector of `UInt32` integers.
If no seed is provided, a randomly generated one is created (using entropy from the system).
See the [`seed!`](@ref) function for reseeding an already existing `Xoshiro` object.
Expand Down Expand Up @@ -98,7 +97,7 @@ Using or seeding the RNG of any other task than the one returned by `current_tas
is undefined behavior: it will work most of the time, and may sometimes fail silently.
When seeding `TaskLocalRNG()` with [`seed!`](@ref), the passed seed, if any,
may be an integer or a vector of `UInt32` integers.
may be any integer.
!!! compat "Julia 1.11"
Seeding `TaskLocalRNG()` with a negative integer seed requires at least Julia 1.11.
Expand Down

0 comments on commit 7eaf94f

Please sign in to comment.