Class: Hlockey::Utils::Rng

Inherits:
Object
  • Object
show all
Defined in:
lib/hlockey/utils.rb

Overview

Lehmer random number generator, to avoid incompatabilities in RNG between Ruby implementations. From en.wikipedia.org/wiki/Lehmer_random_number_generator#Sample_C99_code.

Constant Summary collapse

MOD_VAL =
0x7fffffff

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(seed) ⇒ Rng

Returns a new instance of Rng.

Parameters:

  • seed (Integer)


16
17
18
19
20
21
# File 'lib/hlockey/utils.rb', line 16

def initialize(seed)
  seed = seed.zero? ? 1 : seed.abs
  seed %= MOD_VAL if seed >= MOD_VAL

  @state = seed
end

Instance Attribute Details

#stateInteger (readonly)

Returns:

  • (Integer)


13
14
15
# File 'lib/hlockey/utils.rb', line 13

def state
  @state
end

Instance Method Details

#rand(bound = nil) ⇒ Numeric

Parameters:

  • upper_bound (Numeric, Range, nil)

    max value from RNG

Returns:

  • (Numeric)


25
26
27
28
29
30
31
32
33
34
35
# File 'lib/hlockey/utils.rb', line 25

def rand(bound = nil)
  if bound.is_a?(Range)
    start = bound.begin || 0
    return rand(bound.end.nil? ? nil : bound.end - start) + start
  end

  @state = @state * 48_271 % MOD_VAL
  return @state if bound.nil? || bound.zero?

  @state % bound
end