module Random

Overview

Random provides an interface for random values generation, using a pseudo random number generator (PRNG).

Random.new_seed # => 112705036
Random.rand     # => 0.167595
Random.rand(5)  # => 2

The above methods delegate to a Random instance.

r = Random.new
r.rand      # => 0.0372991
r.next_bool # => true
r.next_int  # => 2223112

This module also defines a global method #rand, which Array#sample and Array#shuffle delegates.

rand     # => 0.293829
rand(10) # => 8

Direct including types

Defined in:

random/mt19937.cr
random.cr

Constant Summary

DEFAULT = MT19937.new

Class Method Summary

Instance Method Summary

Class Method Detail

def self.new(seed = new_seed) #

Initiates an instance with the given seed. (Default: #new_seed)


[View source]
def self.new_seed : UInt32 #

Returns a UInt32 read from a counter value generated by the cycle counter register.


[View source]
def self.rand : Float64 #

see #rand


[View source]
def self.rand(x) #

[View source]

Instance Method Detail

def next_bool : Bool #

Generates a random Bool.

Random.new.next_bool # => true

[View source]
def next_float : Float64 #

see #rand


[View source]
def next_int : Int32 #

Generates a random Int32.

Random.new.next_int # => 440038499
Random.new.next_int # => -1848788484

[View source]
abstract def next_u32 #

Generates a random UInt32.


[View source]
def rand(range : Range(Float, Float)) : Float64 #

Returns a random Float64 in the given range.

Random.new.rand(6.2..21.768) # => 15.2989

[View source]
def rand : Float64 #

Generates a random Float64 between 0 and 1.

r = Random.new
r.rand # => 0.167595
r.rand # => 0.0372991

[View source]
def rand(range : Range(Int, Int)) : Int32 #

Returns a random Int32 in the given range.

Random.new.rand(10..20) # => 14

[View source]
def rand(max : Int) : Int32 #

Returns a random Int32 which is greater than 0 and less than max.

Random.new.rand(10)   # => 5
Random.new.rand(5000) # => 2243

[View source]
def rand(max : Float) : Float64 #

Returns a random Float64 which is greater than or equal to 0 and less than max.

Random.new.rand(3.5)    # => 2.88938
Random.new.rand(10.725) # => 7.70147

[View source]