rand

package
v1.25.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 5, 2025 License: MIT Imports: 1 Imported by: 0

Documentation

Overview

randパッケージは、シミュレーションなどのタスクに適した擬似乱数生成器を実装しますが、セキュリティに敏感な作業には使用しないでください。

乱数は Source によって生成され、通常は Rand でラップされます。 両方のタイプは一度に1つのゴルーチンから使用されるべきです:複数のゴルーチン間で共有するには何らかの同期が必要です。

トップレベルの関数、例えば Float64Int は、 複数のゴルーチンによる並行使用が安全です。

このパッケージの出力は、どのようにシードされていても容易に予測可能かもしれません。セキュリティに敏感な作業に適した乱数については、 crypto/rand パッケージを参照してください。

Example
answers := []string{
	"It is certain",
	"It is decidedly so",
	"Without a doubt",
	"Yes definitely",
	"You may rely on it",
	"As I see it yes",
	"Most likely",
	"Outlook good",
	"Yes",
	"Signs point to yes",
	"Reply hazy try again",
	"Ask again later",
	"Better not tell you now",
	"Cannot predict now",
	"Concentrate and ask again",
	"Don't count on it",
	"My reply is no",
	"My sources say no",
	"Outlook not so good",
	"Very doubtful",
}
fmt.Println("Magic 8-Ball says:", answers[rand.IntN(len(answers))])
Example (Rand)

この例は、*Randの各メソッドの使用を示しています。 グローバル関数の使用は、レシーバなしで同じです。

// ジェネレータを作成し、シードを設定します。
// 通常、固定されていないシードを使用するべきです。例えば、Uint64(), Uint64()のようなものです。
// 固定シードを使用すると、毎回同じ出力が生成されます。
r := rand.New(rand.NewPCG(1, 2))

// ここでのtabwriterは、私たちが整列した出力を生成するのを助けてくれます。
w := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0)
defer w.Flush()
show := func(name string, v1, v2, v3 any) {
	fmt.Fprintf(w, "%s\t%v\t%v\t%v\n", name, v1, v2, v3)
}

// Float32とFloat64の値は[0, 1)の範囲内にあります。
show("Float32", r.Float32(), r.Float32(), r.Float32())
show("Float64", r.Float64(), r.Float64(), r.Float64())

// ExpFloat64の値は平均が1ですが、指数関数的に減衰します。
show("ExpFloat64", r.ExpFloat64(), r.ExpFloat64(), r.ExpFloat64())

// NormFloat64の値は平均が0で、標準偏差が1です。
show("NormFloat64", r.NormFloat64(), r.NormFloat64(), r.NormFloat64())

// Int32、Int64、およびUint32は指定された幅の値を生成します。
// Intメソッド(ここでは示されていません)は'int'のサイズに応じてInt32またはInt64のように動作します。
show("Int32", r.Int32(), r.Int32(), r.Int32())
show("Int64", r.Int64(), r.Int64(), r.Int64())
show("Uint32", r.Uint32(), r.Uint32(), r.Uint32())

// IntN、Int32N、およびInt64Nは、出力がn未満になるように制限します。
// これらは、r.Int()%nを使用するよりも慎重に行います。
show("IntN(10)", r.IntN(10), r.IntN(10), r.IntN(10))
show("Int32N(10)", r.Int32N(10), r.Int32N(10), r.Int32N(10))
show("Int64N(10)", r.Int64N(10), r.Int64N(10), r.Int64N(10))

// Permは、数値[0, n)のランダムな順列を生成します。
show("Perm", r.Perm(5), r.Perm(5), r.Perm(5))
Output:

Float32     0.95955694          0.8076733            0.8135684
Float64     0.4297927436037299  0.797802349388613    0.3883664855410056
ExpFloat64  0.43463410545541104 0.5513632046504593   0.7426404617374481
NormFloat64 -0.9303318111676635 -0.04750789419852852 0.22248301107582735
Int32       2020777787          260808523            851126509
Int64       5231057920893523323 4257872588489500903  158397175702351138
Uint32      314478343           1418758728           208955345
IntN(10)    6                   2                    0
Int32N(10)  3                   7                    7
Int64N(10)  8                   9                    4
Perm        [0 3 1 4 2]         [4 1 2 0 3]          [4 3 2 0 1]

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExpFloat64

func ExpFloat64() float64

ExpFloat64は、デフォルトのSourceからレートパラメータ(lambda)が1で平均が1/lambda(1)の指数分布に従う 範囲(0, +math.MaxFloat64]の指数分布のfloat64を返します。 異なるレートパラメータの分布を生成するために、呼び出し元は出力を調整できます:

sample = ExpFloat64() / desiredRateParameter

func Float32

func Float32() float32

Float32は、デフォルトのSourceから半開放区間[0.0,1.0)内の擬似乱数をfloat32として返します。

func Float64

func Float64() float64

Float64は、デフォルトのSourceから半開放区間[0.0,1.0)内の擬似乱数をfloat64として返します。

func Int

func Int() int

Intは、デフォルトのSourceから非負の擬似乱数intを返します。

func Int32

func Int32() int32

Int32は、デフォルトのSourceから非負の擬似乱数31ビット整数をint32として返します。

func Int32N

func Int32N(n int32) int32

Int32Nは、デフォルトのSourceから半開放区間[0,n)内の非負の擬似乱数をint32として返します。 nが0以下の場合、パニックを引き起こします。

func Int64

func Int64() int64

Int64は、デフォルトのSourceから非負の擬似乱数63ビット整数をint64として返します。

func Int64N

func Int64N(n int64) int64

Int64Nは、デフォルトのSourceから半開放区間[0,n)内の非負の擬似乱数をint64として返します。 nが0以下の場合、パニックを引き起こします。

func IntN

func IntN(n int) int

IntNは、デフォルトのSourceから半開放区間[0,n)内の非負の擬似乱数をintとして返します。 nが0以下の場合、パニックを引き起こします。

Example
fmt.Println(rand.IntN(100))
fmt.Println(rand.IntN(100))
fmt.Println(rand.IntN(100))

func N

func N[Int intType](n Int) Int

Nは、デフォルトのSourceから半開放区間[0,n)内の擬似乱数を返します。 型パラメータIntは任意の整数型にすることができます。 nが0以下の場合、パニックを引き起こします。

Example
// 半開放区間[0, 100)内のint64を出力します。
fmt.Println(rand.N(int64(100)))

// 0から100ミリ秒の間のランダムな期間スリープします。
time.Sleep(rand.N(100 * time.Millisecond))

func NormFloat64

func NormFloat64() float64

NormFloat64は、デフォルトのSourceから標準正規分布(平均 = 0、標準偏差 = 1)に従う 範囲[-math.MaxFloat64, +math.MaxFloat64]の正規分布のfloat64を返します。 異なる正規分布を生成するために、呼び出し元は出力を調整できます:

sample = NormFloat64() * desiredStdDev + desiredMean

func Perm

func Perm(n int) []int

Permは、デフォルトのSourceから半開放区間[0,n)内の整数の擬似乱数順列をn個のintのスライスとして返します。

Example
for _, value := range rand.Perm(3) {
	fmt.Println(value)
}
Output:

1
2
0

func Shuffle

func Shuffle(n int, swap func(i, j int))

ShuffleはデフォルトのSourceを使用して要素の順序を擬似ランダムにします。 nは要素の数です。n < 0の場合、Shuffleはパニックを引き起こします。 swapは、インデックスiとjの要素を交換します。

Example
words := strings.Fields("ink runs from the corners of my mouth")
rand.Shuffle(len(words), func(i, j int) {
	words[i], words[j] = words[j], words[i]
})
fmt.Println(words)
Example (SlicesInUnison)
numbers := []byte("12345")
letters := []byte("ABCDE")
// 数字をシャッフルし、同時にlettersの対応するエントリを交換します。
rand.Shuffle(len(numbers), func(i, j int) {
	numbers[i], numbers[j] = numbers[j], numbers[i]
	letters[i], letters[j] = letters[j], letters[i]
})
for i := range numbers {
	fmt.Printf("%c: %c\n", letters[i], numbers[i])
}

func Uint added in v1.23.0

func Uint() uint

Uint はデフォルトのソースから擬似乱数の uint を返します。

func Uint32

func Uint32() uint32

Uint32は、デフォルトのSourceから擬似乱数32ビット値をuint32として返します。

func Uint32N

func Uint32N(n uint32) uint32

Uint32Nは、デフォルトのSourceから半開区間[0,n)内の擬似乱数をuint32として返します。 nが0の場合、パニックを引き起こします。

func Uint64

func Uint64() uint64

Uint64は、デフォルトのSourceから擬似乱数64ビット値をuint64として返します。

func Uint64N

func Uint64N(n uint64) uint64

Uint64Nは、デフォルトのSourceから半開区間[0,n)内の擬似乱数をuint64として返します。 nが0の場合、パニックを引き起こします。

func UintN

func UintN(n uint) uint

UintNは、デフォルトのSourceから半開区間[0,n)内の擬似乱数をuintとして返します。 nが0の場合、パニックを引き起こします。

Types

type ChaCha8

type ChaCha8 struct {
	// contains filtered or unexported fields
}

ChaCha8は、ChaCha8ベースの暗号的に強力な 乱数生成器です。

func NewChaCha8

func NewChaCha8(seed [32]byte) *ChaCha8

NewChaCha8は、指定されたシードで初期化された新しいChaCha8を返します。

func (*ChaCha8) AppendBinary added in v1.25.0

func (c *ChaCha8) AppendBinary(b []byte) ([]byte, error)

AppendBinaryは encoding.BinaryAppender インターフェースを実装します。

func (*ChaCha8) MarshalBinary

func (c *ChaCha8) MarshalBinary() ([]byte, error)

MarshalBinaryは encoding.BinaryMarshaler インターフェースを実装します。

func (*ChaCha8) Read added in v1.23.0

func (c *ChaCha8) Read(p []byte) (n int, err error)

Readは、pに正確にlen(p)バイトを読み込みます。 常にlen(p)とnilエラーを返します。

ReadとUint64の呼び出しが交互に行われる場合、 両者によって返されるビットの順序は未定義であり、 Readは最後のUint64の呼び出し前に生成されたビットを返すことがあります。

func (*ChaCha8) Seed

func (c *ChaCha8) Seed(seed [32]byte)

Seedは、ChaCha8をNewChaCha8(seed)と同じように動作するようにリセットします。

func (*ChaCha8) Uint64

func (c *ChaCha8) Uint64() uint64

Uint64は、一様に分布したランダムなuint64値を返します。

func (*ChaCha8) UnmarshalBinary

func (c *ChaCha8) UnmarshalBinary(data []byte) error

UnmarshalBinaryは encoding.BinaryUnmarshaler インターフェースを実装します。

type PCG

type PCG struct {
	// contains filtered or unexported fields
}

PCGは、128ビットの内部状態を持つPCGジェネレータです。 ゼロのPCGは、NewPCG(0, 0)と同等です。

func NewPCG

func NewPCG(seed1, seed2 uint64) *PCG

NewPCGは、与えられた値でシードされた新しいPCGを返します。

func (*PCG) AppendBinary added in v1.25.0

func (p *PCG) AppendBinary(b []byte) ([]byte, error)

AppendBinaryは encoding.BinaryAppender インターフェースを実装します。

func (*PCG) MarshalBinary

func (p *PCG) MarshalBinary() ([]byte, error)

MarshalBinaryは encoding.BinaryMarshaler インターフェースを実装します。

func (*PCG) Seed

func (p *PCG) Seed(seed1, seed2 uint64)

Seedは、PCGをNewPCG(seed1, seed2)と同じように動作するようにリセットします。

func (*PCG) Uint64

func (p *PCG) Uint64() uint64

Uint64は、一様に分布したランダムなuint64の値を返します。

func (*PCG) UnmarshalBinary

func (p *PCG) UnmarshalBinary(data []byte) error

UnmarshalBinaryは encoding.BinaryUnmarshaler インターフェースを実装します。

type Rand

type Rand struct {
	// contains filtered or unexported fields
}

Randは、乱数のソースです。

func New

func New(src Source) *Rand

Newは、他の乱数を生成するためにsrcから乱数を使用する新しいRandを返します。

func (*Rand) ExpFloat64

func (r *Rand) ExpFloat64() float64

ExpFloat64は、レートパラメータ(lambda)が1で平均が1/lambda(1)の指数分布に従う 範囲(0, +math.MaxFloat64]の指数分布のfloat64を返します。 異なるレートパラメータの分布を生成するために、呼び出し元は出力を調整できます:

sample = ExpFloat64() / desiredRateParameter

func (*Rand) Float32

func (r *Rand) Float32() float32

Float32は、半開放区間[0.0,1.0)内の擬似乱数をfloat32として返します。

func (*Rand) Float64

func (r *Rand) Float64() float64

Float64は、半開放区間[0.0,1.0)内の擬似乱数をfloat64として返します。

func (*Rand) Int

func (r *Rand) Int() int

Intは、非負の擬似乱数intを返します。

func (*Rand) Int32

func (r *Rand) Int32() int32

Int32は、非負の擬似乱数31ビット整数をint32として返します。

func (*Rand) Int32N

func (r *Rand) Int32N(n int32) int32

Int32Nは、半開放区間[0,n)内の非負の擬似乱数をint32として返します。 nが0以下の場合、パニックを引き起こします。

func (*Rand) Int64

func (r *Rand) Int64() int64

Int64は、非負の擬似乱数63ビット整数をint64として返します。

func (*Rand) Int64N

func (r *Rand) Int64N(n int64) int64

Int64Nは、半開放区間[0,n)内の非負の擬似乱数をint64として返します。 nが0以下の場合、パニックを引き起こします。

func (*Rand) IntN

func (r *Rand) IntN(n int) int

IntNは、半開放区間[0,n)内の非負の擬似乱数をintとして返します。 nが0以下の場合、パニックを引き起こします。

func (*Rand) NormFloat64

func (r *Rand) NormFloat64() float64

NormFloat64は、標準正規分布(平均 = 0、標準偏差 = 1)に従う 範囲[-math.MaxFloat64, +math.MaxFloat64]の正規分布のfloat64を返します。 異なる正規分布を生成するために、呼び出し元は出力を調整できます:

sample = NormFloat64() * desiredStdDev + desiredMean

func (*Rand) Perm

func (r *Rand) Perm(n int) []int

Permは、半開放区間[0,n)内の整数の擬似乱数順列をn個のintのスライスとして返します。

func (*Rand) Shuffle

func (r *Rand) Shuffle(n int, swap func(i, j int))

Shuffleは要素の順序を擬似ランダムにします。 nは要素の数です。n < 0の場合、Shuffleはパニックを引き起こします。 swapは、インデックスiとjの要素を交換します。

func (*Rand) Uint added in v1.23.0

func (r *Rand) Uint() uint

Uint は擬似乱数の uint を返します。

func (*Rand) Uint32

func (r *Rand) Uint32() uint32

Uint32は、擬似乱数32ビット値をuint32として返します。

func (*Rand) Uint32N

func (r *Rand) Uint32N(n uint32) uint32

Uint32Nは、半開放区間[0,n)内の非負の擬似乱数をuint32として返します。 nが0の場合、パニックを引き起こします。

func (*Rand) Uint64

func (r *Rand) Uint64() uint64

Uint64は、擬似乱数64ビット値をuint64として返します。

func (*Rand) Uint64N

func (r *Rand) Uint64N(n uint64) uint64

Uint64Nは、半開放区間[0,n)内の非負の擬似乱数をuint64として返します。 nが0の場合、パニックを引き起こします。

func (*Rand) UintN

func (r *Rand) UintN(n uint) uint

UintNは、半開放区間[0,n)内の非負の擬似乱数をuintとして返します。 nが0の場合、パニックを引き起こします。

type Source

type Source interface {
	Uint64() uint64
}

Sourceは、範囲[0, 1<<64)内の一様に分布した 擬似乱数uint64値のソースです。

Sourceは、複数のゴルーチンによる並行使用には安全ではありません。

type Zipf

type Zipf struct {
	// contains filtered or unexported fields
}

Zipfは、Zipf分布に従う変量を生成します。

func NewZipf

func NewZipf(r *Rand, s float64, v float64, imax uint64) *Zipf

NewZipfは、Zipf変量ジェネレータを返します。 このジェネレータは、P(k)が(v + k) ** (-s)に比例するような値k ∈ [0, imax]を生成します。 要件:s > 1 および v >= 1。

func (*Zipf) Uint64

func (z *Zipf) Uint64() uint64

Uint64は、Zipfオブジェクトで記述されたZipf分布から抽出された値を返します。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL