Class: Rough::Random

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

Overview

Seeded pseudo-random number generator using Park-Miller LCG. Produces deterministic sequences for a given seed, matching the JavaScript rough.js implementation exactly.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(seed) ⇒ Random

Returns a new instance of Random.



8
9
10
# File 'lib/rough/random.rb', line 8

def initialize(seed)
  @seed = seed.to_i
end

Class Method Details

.new_seedObject



26
27
28
# File 'lib/rough/random.rb', line 26

def self.new_seed
  rand(2**31)
end

Instance Method Details

#nextObject



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/rough/random.rb', line 12

def next
  if @seed != 0
    # Match JS: (2**31 - 1) & Math.imul(48271, seed)
    # Math.imul truncates to 32-bit signed int, then & masks to 31 bits
    product = (48271 * @seed) & 0xFFFFFFFF
    # Convert to signed 32-bit (as JS Math.imul does)
    product -= 0x100000000 if product >= 0x80000000
    @seed = (2**31 - 1) & product
    @seed.to_f / 2**31
  else
    Kernel.rand
  end
end