Random Numbers in Crystal

Crystal’s Random module provides pseudorandom number generation.

require "random"

# For example, `Random.new.rand(100)` returns a random `Int32` n,
# `0 <= n < 100`.
print Random.new.rand(100), ","
print Random.new.rand(100)
puts

# `Random.new.rand` returns a `Float64` f,
# `0.0 <= f < 1.0`.
puts Random.new.rand

# This can be used to generate random floats in
# other ranges, for example `5.0 <= f' < 10.0`.
print (Random.new.rand * 5) + 5, ","
print (Random.new.rand * 5) + 5
puts

# If you want a known seed, create a new
# `Random` instance with a seed.
r2 = Random.new(42)
print r2.rand(100), ","
print r2.rand(100)
puts

# Using the same seed will produce the same sequence
# of random numbers.
r3 = Random.new(42)
print r3.rand(100), ","
print r3.rand(100)
puts

Some of the generated numbers may be different when you run the sample.

$ crystal random_numbers.cr
37,93
0.5026172570766397
5.021822584235394,9.805990003782578
71,2
71,2

See the Random module docs for references on other random quantities that Crystal can provide.

Crystal’s Random module is similar to Go’s math/rand/v2 package, but with some differences:

  1. Crystal uses Random.new to create a new random number generator, while Go uses rand.New.
  2. In Crystal, you can directly use Random.new.rand(100) to get a random integer between 0 and 99, while in Go you would use rand.IntN(100).
  3. Crystal’s Random.new.rand returns a Float64 between 0 and 1, similar to Go’s rand.Float64().
  4. Crystal doesn’t have a direct equivalent to Go’s NewPCG, but you can create a seeded random number generator using Random.new(seed).

The overall functionality is similar, allowing you to generate random integers, floats, and create seeded random number generators for reproducible sequences.

查看推荐产品

Comments powered by Disqus