rand

原文:https://pkg.go.dev/math/rand@go1.23.0

Package rand implements pseudo-random number generators unsuitable for security-sensitive work.

rand包实现了伪随机数生成器,不适合用于安全敏感的工作。

Random numbers are generated by a Source, usually wrapped in a Rand. Both types should be used by a single goroutine at a time: sharing among multiple goroutines requires some kind of synchronization.

​ 随机数由Source生成,通常封装在Rand中。这两种类型都应该一次只由一个goroutine使用:多个goroutine之间的共享需要某种同步。

Top-level functions, such as Float64 and Int, are safe for concurrent use by multiple goroutines.

​ 顶层函数,如Float64Int,对于多个goroutine的并发使用是安全的。

This package’s outputs might be easily predictable regardless of how it’s seeded. For random numbers suitable for security-sensitive work, see the crypto/rand package.

​ 无论如何设置种子,这个包的输出都可能是很容易预测的。对于适合安全敏感工作的随机数,请参见crypto/rand包。

示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package main

import (
	"fmt"
	"math/rand"
)

func main() {
	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))])
}

示例(Rand)

This example shows the use of each of the methods on a *Rand. The use of the global functions is the same, without the receiver.

​ 此示例展示了在*Rand上的每个方法的使用。全局函数的使用方式相同,只是没有接收器。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main

import (
	"fmt"
	"math/rand"
	"os"
	"text/tabwriter"
)

func main() {
	// Create and seed the generator.
    // 创建并种子生成器。
	// Typically a non-fixed seed should be used, such as time.Now().UnixNano().
    // 通常应使用非固定种子,例如time.Now().UnixNano()。
	// Using a fixed seed will produce the same output on every run.
    // 使用固定种子将在每次运行时产生相同的输出。
	r := rand.New(rand.NewSource(99))

	// The tabwriter here helps us generate aligned output.
    // 此处的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 and Float64 values are in [0, 1).
    // Float32和Float64的值在[0,1)之间。
	show("Float32", r.Float32(), r.Float32(), r.Float32())
	show("Float64", r.Float64(), r.Float64(), r.Float64())

	// ExpFloat64 values have an average of 1 but decay exponentially.
    // ExpFloat64的值平均值为1,但呈指数衰减。
	show("ExpFloat64", r.ExpFloat64(), r.ExpFloat64(), r.ExpFloat64())

	// NormFloat64 values have an average of 0 and a standard deviation of 1.
    // NormFloat64的值平均值为0,标准偏差为1。
	show("NormFloat64", r.NormFloat64(), r.NormFloat64(), r.NormFloat64())

	// Int31, Int63, and Uint32 generate values of the given width.
    // Int31、Int63和Uint32生成给定宽度的值。
	// The Int method (not shown) is like either Int31 or Int63
	// depending on the size of 'int'.
    // Int方法(未显示)类似于Int31或Int63,具体取决于'int'的大小。
	show("Int31", r.Int31(), r.Int31(), r.Int31())
	show("Int63", r.Int63(), r.Int63(), r.Int63())
	show("Uint32", r.Uint32(), r.Uint32(), r.Uint32())

	// Intn, Int31n, and Int63n limit their output to be < n.
    // Intn、Int31n和Int63n将它们的输出限制为<n。
	// They do so more carefully than using r.Int()%n.
    // 它们比使用r.Int()%n更谨慎。
	show("Intn(10)", r.Intn(10), r.Intn(10), r.Intn(10))
	show("Int31n(10)", r.Int31n(10), r.Int31n(10), r.Int31n(10))
	show("Int63n(10)", r.Int63n(10), r.Int63n(10), r.Int63n(10))

	// Perm generates a random permutation of the numbers [0, n).
    // Perm生成一个[0,n)的随机排列。
	show("Perm", r.Perm(5), r.Perm(5), r.Perm(5))
}
Output:

Float32     0.2635776           0.6358173           0.6718283
Float64     0.628605430454327   0.4504798828572669  0.9562755949377957
ExpFloat64  0.3362240648200941  1.4256072328483647  0.24354758816173044
NormFloat64 0.17233959114940064 1.577014951434847   0.04259129641113857
Int31       1501292890          1486668269          182840835
Int63       3546343826724305832 5724354148158589552 5239846799706671610
Uint32      2760229429          296659907           1922395059
Intn(10)    1                   2                   5
Int31n(10)  4                   7                   8
Int63n(10)  7                   6                   3
Perm        [1 4 2 3 0]         [4 2 1 3 0]         [1 2 4 0 3]

常量

This section is empty.

变量

This section is empty.

函数

func ExpFloat64

1
func ExpFloat64() float64

ExpFloat64 returns an exponentially distributed float64 in the range (0, +math.MaxFloat64] with an exponential distribution whose rate parameter (lambda) is 1 and whose mean is 1/lambda (1) from the default Source. To produce a distribution with a different rate parameter, callers can adjust the output using:

ExpFloat64 函数返回一个指数分布的 float64 数字,范围在 (0, +math.MaxFloat64],其指数分布的率参数(lambda)为 1,均值为 1/lambda (1),来自默认的源。要生成具有不同率参数的分布,调用者可以通过以下公式调整输出:

1
sample = ExpFloat64() / desiredRateParameter

func Float32

1
func Float32() float32

Float32 returns, as a float32, a pseudo-random number in the half-open interval [0.0,1.0) from the default Source.

Float32 函数作为一个 float32 返回来自默认源的半开半闭区间 [0.0,1.0) 中的一个伪随机数。

func Float64

1
func Float64() float64

Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0) from the default Source.

Float64 作为一个 float64 返回来自默认源的半开半闭区间 [0.0,1.0) 中的一个伪随机数。

func Int

1
func Int() int

Int returns a non-negative pseudo-random int from the default Source.

Int 函数从默认源返回一个非负的伪随机 int 数。

func Int31

1
func Int31() int32

Int31 returns a non-negative pseudo-random 31-bit integer as an int32 from the default Source.

Int31 函数作为一个 int32 从默认源返回一个非负的伪随机 31 位整数。

func Int31n

1
func Int31n(n int32) int32

Int31n returns, as an int32, a non-negative pseudo-random number in the half-open interval [0,n) from the default Source. It panics if n <= 0.

Int31n 函数作为一个 int32,从默认源返回半开半闭区间 [0,n) 中的一个非负伪随机数。如果 n <= 0,它会抛出panic。

func Int63

1
func Int63() int64

Int63 returns a non-negative pseudo-random 63-bit integer as an int64 from the default Source.

Int63 函数作为一个 int64 从默认源返回一个非负的伪随机 63 位整数。

func Int63n

1
func Int63n(n int64) int64

Int63n returns, as an int64, a non-negative pseudo-random number in the half-open interval [0,n) from the default Source. It panics if n <= 0.

Int63n 函数作为一个 int64,从默认源返回一个在半开区间 [0,n) 中的非负伪随机数。如果 n <= 0,它会抛出panic。

func Intn

1
func Intn(n int) int

Intn returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n) from the default Source. It panics if n <= 0.

Intn 函数作为一个 int,从默认源返回一个在半开区间 [0,n) 中的非负伪随机数。如果 n <= 0,它会抛出panic。

Intn Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package main

import (
	"fmt"
	"math/rand"
)

func main() {
	fmt.Println(rand.Intn(100))
	fmt.Println(rand.Intn(100))
	fmt.Println(rand.Intn(100))
}

func NormFloat64

1
func NormFloat64() float64

NormFloat64 returns a normally distributed float64 in the range [-math.MaxFloat64, +math.MaxFloat64] with standard normal distribution (mean = 0, stddev = 1) from the default Source. To produce a different normal distribution, callers can adjust the output using:

NormFloat64 函数返回一个在区间 [-math.MaxFloat64, +math.MaxFloat64] 的正态分布的 float64,带有标准正态分布(均值 = 0,标准差 = 1)来自默认源。为了产生不同的正态分布,调用者可以使用以下公式调整输出:

sample = NormFloat64() * desiredStdDev + desiredMean

func Perm

1
func Perm(n int) []int

Perm returns, as a slice of n ints, a pseudo-random permutation of the integers in the half-open interval [0,n) from the default Source.

Perm 函数作为 nint 的切片返回,这是来自默认源的半开区间 [0,n) 中的整数的伪随机排列。

Perm Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package main

import (
	"fmt"
	"math/rand"
)

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

}
Output:

1
2
0

func Read <- DEPRECATED

1
func Read(p []byte) (n int, err error)

Read generates len(p) random bytes from the default Source and writes them into p. It always returns len(p) and a nil error. Read, unlike the Rand.Read method, is safe for concurrent use.

Read 函数生成 len(p) 个随机字节,并将它们写入 p 中。它总是返回 len(p) 和一个 nil 错误。与 Rand.Read 方法不同,Read 函数可安全用于并发调用。

Deprecated: For almost all use cases, crypto/rand.Read is more appropriate.

已弃用:对于几乎所有用例,crypto/rand.Read 更加合适。

func Seed <- DEPRECATED

1
func Seed(seed int64)

Seed uses the provided seed value to initialize the default Source to a deterministic state. Seed values that have the same remainder when divided by 2³¹-1 generate the same pseudo-random sequence. Seed, unlike the Rand.Seed method, is safe for concurrent use.

Seed 函数使用提供的种子值来初始化默认的数据源,以获得确定性状态。如果两个种子值在除以 2³¹-1 后余数相同,则它们将生成相同的伪随机序列。与 Rand.Seed 方法不同,Seed 函数可安全用于并发调用。

If Seed is not called, the generator is seeded randomly at program startup.

​ 如果没有调用 Seed,生成器将在程序启动时随机进行种子初始化。

Prior to Go 1.20, the generator was seeded like Seed(1) at program startup. To force the old behavior, call Seed(1) at program startup. Alternately, set GODEBUG=randautoseed=0 in the environment before making any calls to functions in this package.

​ 在 Go 1.20 之前,生成器在程序启动时的行为类似于 Seed(1)。要恢复旧的行为,可以在程序启动时调用 Seed(1)。另外,可以在调用该包中的任何函数之前,在环境中设置 GODEBUG=randautoseed=0,以强制使用旧的行为。

Deprecated: Programs that call Seed and then expect a specific sequence of results from the global random source (using functions such as Int) can be broken when a dependency changes how much it consumes from the global random source. To avoid such breakages, programs that need a specific result sequence should use NewRand(NewSource(seed)) to obtain a random generator that other packages cannot access.

已弃用:程序在调用 Seed 然后期望全局随机源具有特定结果序列的情况下,当依赖项更改其从全局随机源消耗的数据量时,可能会导致问题。为避免此类问题,需要特定结果序列的程序应该使用 NewRand(NewSource(seed)) 来获取其他包无法访问的随机生成器。

func Shuffle <- go1.10

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

Shuffle pseudo-randomizes the order of elements using the default Source. n is the number of elements. Shuffle panics if n < 0. swap swaps the elements with indexes i and j.

Shuffle 函数使用默认源伪随机化元素的顺序。n 是元素的数量。如果 n < 0,Shuffle 会抛出panic。swap 交换索引 ij 上的元素。

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package main

import (
	"fmt"
	"math/rand"
	"strings"
)

func main() {
	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)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package main

import (
	"fmt"
	"math/rand"
)

func main() {
	numbers := []byte("12345")
	letters := []byte("ABCDE")
	// Shuffle numbers, swapping corresponding entries in letters at the same time.
	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 Uint32

1
func Uint32() uint32

Uint32 returns a pseudo-random 32-bit value as a uint32 from the default Source.

Uint32 函数从默认源返回一个伪随机的 32 位值作为一个 uint32

func Uint64 <- go1.8

1
func Uint64() uint64

Uint64 returns a pseudo-random 64-bit value as a uint64 from the default Source.

Uint64 函数从默认源返回一个伪随机的 64 位值作为一个 uint64

类型

type Rand

1
2
3
type Rand struct {
	// contains filtered or unexported fields
}

A Rand is a source of random numbers.

Rand 是随机数的来源。

func New

1
func New(src Source) *Rand

New returns a new Rand that uses random values from src to generate other random values.

New 函数返回一个使用src的随机值生成其他随机值的新Rand

(*Rand) ExpFloat64

1
func (r *Rand) ExpFloat64() float64

ExpFloat64 returns an exponentially distributed float64 in the range (0, +math.MaxFloat64] with an exponential distribution whose rate parameter (lambda) is 1 and whose mean is 1/lambda (1). To produce a distribution with a different rate parameter, callers can adjust the output using:

ExpFloat64 方法返回一个指数分布的float64,范围在 (0, +math.MaxFloat64],其指数分布的率参数(lambda)为1,均值为1/lambda(1)。要生成具有不同率参数的分布,调用者可以使用以下方法调整输出:

sample = ExpFloat64() / desiredRateParameter

(*Rand) Float32

1
func (r *Rand) Float32() float32

Float32 returns, as a float32, a pseudo-random number in the half-open interval [0.0,1.0).

Float32 方法作为一个float32返回,是在半开半闭区间[0.0,1.0)中的伪随机数。

(*Rand) Float64

1
func (r *Rand) Float64() float64

Float64 returns, as a float64, a pseudo-random number in the half-open interval [0.0,1.0).

Float64 方法作为一个float64返回,是在半开半闭区间[0.0,1.0)中的伪随机数。

(*Rand) Int

1
func (r *Rand) Int() int

Int returns a non-negative pseudo-random int.

Int 方法返回一个非负的伪随机int

(*Rand) Int31

1
func (r *Rand) Int31() int32

Int31 returns a non-negative pseudo-random 31-bit integer as an int32.

Int31 方法返回一个作为int32的非负伪随机31位整数。

(*Rand) Int31n

1
func (r *Rand) Int31n(n int32) int32

Int31n returns, as an int32, a non-negative pseudo-random number in the half-open interval [0,n). It panics if n <= 0.

Int31n 方法返回一个int32类型的伪随机数,该数是在半开半闭区间[0, n)内的非负数。如果n <= 0,则会引发panic。

(*Rand) Int63

1
func (r *Rand) Int63() int64

Int63 returns a non-negative pseudo-random 63-bit integer as an int64.

Int63 方法返回一个作为int64的非负伪随机63位整数。

(*Rand) Int63n

1
func (r *Rand) Int63n(n int64) int64

Int63n returns, as an int64, a non-negative pseudo-random number in the half-open interval [0,n). It panics if n <= 0.

Int63n 方法返回一个int64类型的伪随机数,该数是在半开半闭区间[0, n)内的非负数。如果n <= 0,则会引发panic。

(*Rand) Intn

1
func (r *Rand) Intn(n int) int

Intn returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n). It panics if n <= 0.

Intn 方法返回一个int类型的伪随机数,该数是在半开半闭区间[0, n)内的非负数。如果n <= 0,则会引发panic。

(*Rand) NormFloat64

1
func (r *Rand) NormFloat64() float64

NormFloat64 returns a normally distributed float64 in the range -math.MaxFloat64 through +math.MaxFloat64 inclusive, with standard normal distribution (mean = 0, stddev = 1). To produce a different normal distribution, callers can adjust the output using:

NormFloat64 方法返回一个float64类型的数,该数遵循标准正态分布(均值为0,标准差为1),范围在-math.MaxFloat64到+math.MaxFloat64之间(包含两端)。要生成不同的正态分布,调用者可以使用以下公式调整输出:

sample = NormFloat64() * desiredStdDev + desiredMean

(*Rand) Perm

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

Perm returns, as a slice of n ints, a pseudo-random permutation of the integers in the half-open interval [0,n).

Perm 方法返回一个长度为nint类型切片,该切片是半开半闭区间[0, n)内的整数的伪随机排列。

(*Rand) Read <- go1.6

1
func (r *Rand) Read(p []byte) (n int, err error)

Read generates len(p) random bytes and writes them into p. It always returns len(p) and a nil error. Read should not be called concurrently with any other Rand method.

Read 方法生成len(p)个随机字节并将它们写入p。它总是返回len(p)和一个nil错误。不应同时调用 Read 和其他 Rand 方法。

(*Rand) Seed

1
func (r *Rand) Seed(seed int64)

Seed uses the provided seed value to initialize the generator to a deterministic state. Seed should not be called concurrently with any other Rand method.

Seed 方法使用提供的种子值将生成器初始化为确定性状态。不应同时调用 Read 和其他 Seed 方法。

(*Rand) Shuffle <- go1.10

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

Shuffle pseudo-randomizes the order of elements. n is the number of elements. Shuffle panics if n < 0. swap swaps the elements with indexes i and j.

Shuffle方法伪随机化元素的顺序。n是元素的数量。如果n < 0,Shuffle会引发panic。swap交换索引ij处的元素。

(*Rand) Uint32

1
func (r *Rand) Uint32() uint32

Uint32 returns a pseudo-random 32-bit value as a uint32.

Uint32 方法返回一个作为uint32的伪随机32位整数。

(*Rand) Uint64 <- go1.8

1
func (r *Rand) Uint64() uint64

Uint64 returns a pseudo-random 64-bit value as a uint64.

Uint64 方法返回一个作为uint64的伪随机64位整数。

type Source

1
2
3
4
type Source interface {
	Int63() int64
	Seed(seed int64)
}

A Source represents a source of uniformly-distributed pseudo-random int64 values in the range [0, 1«63).

Source表示在范围[0, 1<<63)内的均匀分布的伪随机int64值的来源。

A Source is not safe for concurrent use by multiple goroutines.

​ Source对于多个goroutine的并发使用是不安全的。

func NewSource

1
func NewSource(seed int64) Source

NewSource returns a new pseudo-random Source seeded with the given value. Unlike the default Source used by top-level functions, this source is not safe for concurrent use by multiple goroutines. The returned Source implements Source64.

NewSource函数返回一个用给定值作为种子的新的伪随机Source。与顶层函数使用的默认Source不同,此源对于多个goroutine的并发使用是不安全的。返回的Source实现了Source64接口。

type Source64 <- go1.8

1
2
3
4
type Source64 interface {
	Source
	Uint64() uint64
}

A Source64 is a Source that can also generate uniformly-distributed pseudo-random uint64 values in the range [0, 1«64) directly. If a Rand r’s underlying Source s implements Source64, then r.Uint64 returns the result of one call to s.Uint64 instead of making two calls to s.Int63.

Source64是一种Source接口,它可以直接在范围[0, 1<<64)内生成均匀分布的伪随机uint64值。如果Rand r的基础Source s实现了Source64,那么r.Uint64返回的是对s.Uint64的一次调用结果,而不是对s.Int63的两次调用。

type Zipf

1
2
3
type Zipf struct {
	// contains filtered or unexported fields
}

A Zipf generates Zipf distributed variates.

​ Zipf 生成服从 Zipf 分布的随机数。

Zipf生成Zipf分布的变量。

func NewZipf

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

NewZipf returns a Zipf variate generator. The generator generates values k ∈ [0, imax] such that P(k) is proportional to (v + k) ** (-s). Requirements: s > 1 and v >= 1.

NewZipf返回一个Zipf变量生成器。该生成器生成值k ∈ [0, imax],使得P(k)(v + k) ** (-s)成比例。要求:s > 1v >= 1

(*Zipf) Uint64

1
func (z *Zipf) Uint64() uint64

Uint64 returns a value drawn from the Zipf distribution described by the Zipf object.

Uint64函数返回一个从Zipf对象的Zipf分布中抽取的值。

最后修改 October 10, 2024: 更新 (a4b8f85)