Class: Xoshiro256::Random

Inherits:
Object
  • Object
show all
Defined in:
lib/xoshiro256/random.rb

Overview

xoshiro256++ 1.0 with SplitMix64 seeding and reproducible raw-state streams.

Instances are mutable. Use a separate generator per thread or worker. Freezing an instance makes every sampling and jump method raise FrozenError. This generator is not suitable for cryptographic or security-sensitive use.

Examples:

Reproducible sampling

rng = Xoshiro256::Random.new(42)
rng.rand(100) # => an Integer in 0...100
rng.bytes(16) # => 16 binary bytes

See Also:

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(seed = ::Random.new_seed) ⇒ Random

Expands the low 64 bits of a seed into four state words using SplitMix64. Negative and arbitrarily large Integer seeds are accepted. Seeds with the same low 64 bits produce the same stream.

Parameters:

  • seed (Integer) (defaults to: ::Random.new_seed) —

    seed; defaults to Ruby's Random.new_seed

Raises:

  • (TypeError) —

    if seed is not an Integer



80
81
82
83
84
85
86
87
88
89
# File 'lib/xoshiro256/random.rb', line 80

def initialize(seed = ::Random.new_seed)
  raise TypeError, "seed must be an Integer" unless seed.is_a?(Integer)

  @seed = seed
  splitmix_state = seed & MASK_64
  @state = Array.new(4) do
    splitmix_state, value = splitmix64(splitmix_state)
    value
  end
end

Instance Attribute Details

#seed ⇒ Integer? (readonly)

Original seed, before normalization to its low 64 bits. Raw-state construction has no originating seed.

Returns:



43
44
45
# File 'lib/xoshiro256/random.rb', line 43

def seed
  @seed
end

Class Method Details

.from_state(state0, state1, state2, state3) ⇒ Random

Builds a generator from four exact unsigned 64-bit state words.

Bypasses SplitMix64. Words are preserved in s[0] through s[3] order.

Examples:

Restore a saved state

rng = Xoshiro256::Random.from_state(1, 2, 3, 4)
rng.next_u64 # => 0x0000000002800001
restored = Xoshiro256::Random.from_state(*rng.state)
restored.next_u64 == rng.next_u64 # => true

Parameters:

  • state0 (Integer) —

    first state word, in 0..2**64-1

  • state1 (Integer) —

    second state word, in 0..2**64-1

  • state2 (Integer) —

    third state word, in 0..2**64-1

  • state3 (Integer) —

    fourth state word, in 0..2**64-1

Returns:

Raises:

  • (TypeError) —

    if a word is not an Integer

  • (RangeError) —

    if a word is outside 0..2**64-1

  • (ArgumentError) —

    if all four words are zero, or the arity is incorrect



61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/xoshiro256/random.rb', line 61

def self.from_state(state0, state1, state2, state3)
  words = [state0, state1, state2, state3]
  raise TypeError, "state words must be Integers" unless words.all?(Integer)
  unless words.all? { |word| word.between?(0, MASK_64) }
    raise RangeError, "state words must be unsigned 64-bit integers"
  end
  raise ArgumentError, "state must not be all zero" if words.all?(&:zero?)

  allocate.tap do |rng|
    rng.instance_variable_set(:@seed, nil)
    rng.instance_variable_set(:@state, words)
  end
end

Instance Method Details

#bytes(length) ⇒ String

Generates a binary string by packing outputs in little-endian byte order. A partial final word consumes one full output and discards unused bytes; splitting a request into smaller calls can therefore change the byte stream. A zero-length request does not advance the generator.

Parameters:

  • length (Integer) —

    nonnegative number of bytes

Returns:

  • (String) —

    exactly length bytes, with Encoding::BINARY encoding

Raises:

  • (TypeError) —

    if length is not an Integer

  • (ArgumentError) —

    if length is negative

  • (FrozenError) —

    if the generator is frozen



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/xoshiro256/random.rb', line 153

def bytes(length)
  ensure_not_frozen
  raise TypeError, "length must be an Integer" unless length.is_a?(Integer)
  raise ArgumentError, "negative string size" if length.negative?

  output = String.new(capacity: length, encoding: Encoding::BINARY)
  remaining = length

  while remaining >= 8
    output << [step].pack("Q<")
    remaining -= 8
  end

  output << [step].pack("Q<").byteslice(0, remaining) if remaining.positive?
  output
end

#jump ⇒ self

Advances the state by the equivalent of 2128 calls to #next_u64. Spaced starting states can be used for streams of at most 2128 outputs.

Examples:

Create a second stream

first = Xoshiro256::Random.new(42)
second = first.dup.jump

Returns:

  • (self) —

    this generator, mutated in place

Raises:

  • (FrozenError) —

    if the generator is frozen



177
178
179
180
181
# File 'lib/xoshiro256/random.rb', line 177

def jump
  ensure_not_frozen
  apply_jump(JUMP)
  self
end

#long_jump ⇒ self

Advances the state by the equivalent of 2**192 calls to #next_u64. Within each resulting stream, #jump can partition work further.

Returns:

  • (self) —

    this generator, mutated in place

Raises:

  • (FrozenError) —

    if the generator is frozen



187
188
189
190
191
# File 'lib/xoshiro256/random.rb', line 187

def long_jump
  ensure_not_frozen
  apply_jump(LONG_JUMP)
  self
end

#next_u64 ⇒ Integer Also known as: next

Returns the next xoshiro256++ output and advances the state by one step.

Returns:

  • (Integer) —

    unsigned 64-bit value in 0..2**64-1

Raises:

  • (FrozenError) —

    if the generator is frozen



94
95
96
97
# File 'lib/xoshiro256/random.rb', line 94

def next_u64
  ensure_not_frozen
  step
end

#rand(limit = nil) ⇒ Float #rand(limit) ⇒ Integer #rand(limit) ⇒ Float #rand(limit) ⇒ Integer #rand(limit) ⇒ Integer #rand(limit) ⇒ Float

Samples a Float, bounded Integer, or numeric range.

Integer bounds use rejection sampling, including bounds larger than 64 bits. As with Ruby's Random#rand, other non-Float Numeric limits (such as Rational) are truncated with to_int and sampled as Integer bounds. Numeric ranges with a non-Integer endpoint are converted to Float; their converted width must be positive and finite. Beginless, endless, empty, and non-numeric ranges are unsupported. Inclusive singleton ranges return their endpoint without advancing the generator.

Overloads:

  • #rand(limit = nil) ⇒ Float

    Returns value in [0, 1), using 53 random bits.

    Parameters:

    • limit (nil) (defaults to: nil) —

      omitted or nil

    Returns:

    • (Float) —

      value in [0, 1), using 53 random bits

  • #rand(limit) ⇒ Integer

    Returns value in 0...limit.

    Parameters:

    • limit (Integer) —

      positive exclusive upper bound

    Returns:

    • (Integer) —

      value in 0...limit

  • #rand(limit) ⇒ Float

    Returns value in [0, limit).

    Parameters:

    • limit (Float) —

      positive, finite exclusive upper bound

    Returns:

    • (Float) —

      value in [0, limit)

  • #rand(limit) ⇒ Integer

    Returns value in 0...limit.to_int.

    Parameters:

    • limit (Numeric) —

      non-Float bound whose to_int is positive

    Returns:

    • (Integer) —

      value in 0...limit.to_int

  • #rand(limit) ⇒ Integer

    Returns value respecting the range's inclusive or exclusive end.

    Parameters:

    • limit (Range<Integer>) —

      bounded Integer range

    Returns:

    • (Integer) —

      value respecting the range's inclusive or exclusive end

  • #rand(limit) ⇒ Float

    Returns scaled value; rounding may reach an inclusive endpoint, while an exclusive converted endpoint is excluded.

    Parameters:

    • limit (Range<Numeric>) —

      bounded numeric range with a non-Integer endpoint

    Returns:

    • (Float) —

      scaled value; rounding may reach an inclusive endpoint, while an exclusive converted endpoint is excluded

Returns:

  • (Integer, Float) —

    sampled value, according to the limit's type

Raises:

  • (ArgumentError) —

    if the bound or range is invalid or unsupported

  • (FrozenError) —

    if the generator is frozen



132
133
134
135
136
137
138
139
140
141
142
# File 'lib/xoshiro256/random.rb', line 132

def rand(limit = nil)
  ensure_not_frozen

  case limit
  when nil then float
  when Float then float_below(limit)
  when Range then rand_range(limit)
  when Numeric then integer_limit(limit)
  else raise invalid_argument(limit)
  end
end

#state ⇒ Array<Integer>

Returns a frozen copy of the current four state words, in s[0]..s[3] order. The snapshot remains unchanged as this generator advances. Pass its words to from_state to resume the stream from this point.

Returns:

  • (Array<Integer>) —

    four unsigned 64-bit words



197
198
199
# File 'lib/xoshiro256/random.rb', line 197

def state
  @state.dup.freeze
end