Random Numbers in Julia

Julia’s Random module provides pseudorandom number generation.

using Random

# For example, `rand(1:100)` returns a random integer n,
# 1 <= n <= 100.
print(rand(1:100), ",")
println(rand(1:100))

# `rand()` returns a Float64 f,
# 0.0 <= f < 1.0.
println(rand())

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

# If you want a known seed, create a new
# `MersenneTwister` and use it to generate numbers.
rng = MersenneTwister(42)
print(rand(rng, 1:100), ",")
println(rand(rng, 1:100))

# Using the same seed will produce the same sequence of random numbers.
rng2 = MersenneTwister(42)
print(rand(rng2, 1:100), ",")
println(rand(rng2, 1:100))

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

$ julia random_numbers.jl
68,56
0.8090228139659177
5.840125017402497,6.937056298890035
94,49
94,49

See the Random module documentation for references on other random quantities that Julia can provide.

In Julia, we use the Random module for random number generation. The rand() function is used to generate random numbers. For integer ranges, we use rand(start:end).

Instead of creating a new random source with a seed, Julia uses the MersenneTwister type, which can be initialized with a seed. This allows for reproducible random number sequences.

Note that Julia’s random number generation might produce different results compared to other languages, even with the same seed, due to differences in the underlying algorithms.