Class: MiscHacks::Random
- Inherits:
-
Object
- Object
- MiscHacks::Random
- Includes:
- Singleton
- Defined in:
- lib/mischacks/random.rb
Instance Method Summary collapse
-
#exp(size_bits) ⇒ Object
0 ≤ return_value < 2^size_bits.
- #float(n = 1) ⇒ Object
-
#initialize ⇒ Random
constructor
A new instance of Random.
- #inspect ⇒ Object
- #int(n) ⇒ Object
Constructor Details
#initialize ⇒ Random
Returns a new instance of Random.
24 25 26 27 28 |
# File 'lib/mischacks/random.rb', line 24 def initialize @mutex = Mutex.new @pool = 0 @pool_size = 0 end |
Instance Method Details
#exp(size_bits) ⇒ Object
0 ≤ return_value < 2^size_bits
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/mischacks/random.rb', line 31 def exp size_bits @mutex.synchronize do while @pool_size < size_bits # Push 32×8 bits to the pool. SecureRandom.random_bytes(32).unpack('Q*').each do |byte| @pool = (@pool << 64) | byte @pool_size += 64 end end # Unshift size_bits bits from the pool. @pool_size -= size_bits bits = @pool >> @pool_size @pool ^= bits << @pool_size bits end end |
#float(n = 1) ⇒ Object
50 51 52 |
# File 'lib/mischacks/random.rb', line 50 def float n=1 n*Math.ldexp(exp(Float::MANT_DIG), -Float::MANT_DIG) end |
#inspect ⇒ Object
58 59 60 |
# File 'lib/mischacks/random.rb', line 58 def inspect "#<#{self.class}: pool_size=#{@pool_size}>" end |
#int(n) ⇒ Object
54 55 56 |
# File 'lib/mischacks/random.rb', line 54 def int n float(n).floor end |