一般的な乱数
0と1 の間の値を取る乱数は Base.rand() で取得できます。
この関数はデフォルトでは上記のような乱数を返しますがオプションを指定すると乱数の範囲、型(整数など)の指定、次元(行列など)の指定もできます。
julia> rand(1:100) # 整数 1~100の乱数
29
julia> rand(1:100)
34
julia> rand('A':'Z') # 文字の乱数
'R': ASCII/Unicode U+0052 (category Lu: Letter, uppercase)
julia> rand('A':'Z')
'A': ASCII/Unicode U+0041 (category Lu: Letter, uppercase)
julia> rand(3, 3) # 3x3の0~1のFloat64
3×3 Matrix{Float64}:
0.56848 0.138164 0.0733432
0.539703 0.83782 0.317063
0.036541 0.623098 0.390291
ulia> rand(Int32, 3, 3) # Int32の3x3行列
3×3 Matrix{Int32}:
-1057114174 -999388178 1296397317
-2070187498 -121350132 -1971020113
627422604 -1030086586 -361264995
Base.rand() の定義は次のようになっています。
rand([rng=GLOBAL_RNG], [S], [dims...])
rng はシード値、S は型やレンジ、dims は次元です。シード値は次のようにして取得できます。
なお、rand() は Base パッケージに含まれているので、パッケージインポートは不要ですが、それ以外の関数は Random パッケージの関数なので “Random” のインポートが必要です。
julia> using Random
julia> rng = MersenneTwister(1234)
rand() は Base パッケージに含まれるのでインポートしなくても使えます。Random パッケージをインポートすると rand() 以外にも多くの乱数発生機能を利用できます。
次の rand!() はパッケージ Random に含まれる関数です。これは既存の配列を乱数で埋めます。
julia> A = Matrix{Int8}(undef, 2, 2)
2×2 Matrix{Int8}:
80 34
32 -82
julia> rand!(A)
2×2 Matrix{Int8}:
84 -109
-6 121
julia> rand!(A)
2×2 Matrix{Int8}:
83 -30
5 15
正規分布や指数分布を持つ乱数
randn() や randn!() は平均が 0 で標準偏差が 1 の正規分布に従う乱数を発生します。また、randexp() や randexp!() は尺度 1 の指数分布に従う乱数を発生します。
julia> rand()
0.6056531121505694
julia> rand()
0.6306483941786045
julia> rand(1.0:10.0)
6.0
julia> rand(1.0:10.0)
4.0
julia> randexp()
0.1083628567822738
julia> randexp(3)
3-element Vector{Float64}:
0.11316847843214593
0.45746821083363404
0.562927391348907
シャッフル
shuffle() 関数は配列の要素をランダムに入れ替えます。
julia> a = [1, 2, 3, 4, 5]
5-element Vector{Int64}:
1
2
3
4
5
julia> shuffle(a)
5-element Vector{Int64}:
3
5
4
1
2
部分列や置換
部分列や置換を行う関数がいくつか用意されています。一例としてrandsubseq() を挙げます。
この例では 1:10 のうちから5割の確率で値を取り出してベクトルとして返します。
julia> randsubseq(1:10, 0.5)
7-element Vector{Int64}:
3
5
6
7
8
9
10
次のように値の組をレンジでなくベクトルでも指定できます。
julia> randsubseq([1, 2, 3, 4, 5], 0.5)
2-element Vector{Int64}:
1
3
確率を 1.0 にすると常にすべての要素が選ばれます。
julia> randsubseq([1, 2, 3, 4, 5], 1.0)
5-element Vector{Int64}:
1
2
3
4
5