Class: RubyLabs::RandomLab::PRNG

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

Overview

PRNG

A PRNG object is a pseudorandom number generator based on the mixed congruential method. Sequences generated by a PRNG are defined by three constants, named a, c, and m. If x[i] is the current item in the sequence, the equation for the next item x[i+1] is

x[i+1] = (a * x[i] + c) % m

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(a, c, m) ⇒ PRNG

Make a new pseudorandom number generator using constants a, c, and m.

Example – a random number generator that has the full period of m = 1000 but some surprising correlations between successive values:

p = PRNG.new(81, 337, 1000)
=> #<RandomLab::PRNG a: 81 c: 337 m: 1000>

Example: a better PRNG, using values suggested in Numerical Recipes (Press, et al):

>> p = PRNG.new(171, 11213, 53125)
=> #<RandomLab::PRNG a: 171 c: 11213 m: 53125>


70
71
72
73
74
75
# File 'lib/randomlab.rb', line 70

def initialize(a, c, m)
  @a = a
  @c = c
  @m = m
  @x = 0
end

Instance Attribute Details

#aObject

Returns the value of attribute a.



57
58
59
# File 'lib/randomlab.rb', line 57

def a
  @a
end

#cObject

Returns the value of attribute c.



57
58
59
# File 'lib/randomlab.rb', line 57

def c
  @c
end

#mObject

Returns the value of attribute m.



57
58
59
# File 'lib/randomlab.rb', line 57

def m
  @m
end

#xObject

Returns the value of attribute x.



57
58
59
# File 'lib/randomlab.rb', line 57

def x
  @x
end

Instance Method Details

#advanceObject

Get the next pseudorandom number in the sequence defined by this PRNG object. – :begin :advance



93
94
95
# File 'lib/randomlab.rb', line 93

def advance
  @x = (@x * @a + @c) % @m    
end

#inspectObject Also known as: to_s

Create a string that describes the attributes of this PRNG object.



111
112
113
# File 'lib/randomlab.rb', line 111

def inspect
  sprintf "#<RandomLab::PRNG a: #{@a} c: #{@c} m: #{@m}>"
end

#random(min, max) ⇒ Object

Get a random integer between min and max from this PRNG object. Calls advance the get the next value from the pseudorandom sequence, then maps it to an integer between min and max. – :begin :random



103
104
105
106
107
# File 'lib/randomlab.rb', line 103

def random(min, max)
  return nil if max <= min
  range = max - min + 1
  return (advance() % range) + min
end

#seed(val) ⇒ Object

Set the state of the pseudorandom sequence to val.



86
87
88
# File 'lib/randomlab.rb', line 86

def seed(val)
  @x = val
end

#stateObject

Return the current item in the pseudorandom sequence (the most recently generated random number).



80
81
82
# File 'lib/randomlab.rb', line 80

def state
  return @x
end