package rand
import rand "math/rand/v2"
Package rand 实现了适用于模拟等任务的伪随机数生成器, 但不应用于安全敏感的工作。
随机数由 Source 生成,通常包装在 Rand 中。 这两种类型同一时间都应由单个 goroutine 使用:在多个 goroutine 之间共享需要某种形式的同步。
顶层函数,例如 Float64 和 Int, 可安全地由多个 goroutine 并发使用。
无论以何种方式设置种子,本包的输出都很容易被预测。
对于适用于安全敏感工作的随机数,请参见
crypto/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.
Output:Example
package main
import (
"fmt"
"math/rand/v2"
)
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))])
}
Example (Rand)
package main
import (
"fmt"
"math/rand/v2"
"os"
"text/tabwriter"
)
func main() {
// Create and seed the generator.
// Typically a non-fixed seed should be used, such as Uint64(), Uint64().
// Using a fixed seed will produce the same output on every run.
r := rand.New(rand.NewPCG(1, 2))
// The tabwriter here helps us generate aligned output.
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).
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.
show("ExpFloat64", r.ExpFloat64(), r.ExpFloat64(), r.ExpFloat64())
// NormFloat64 values have an average of 0 and a standard deviation of 1.
show("NormFloat64", r.NormFloat64(), r.NormFloat64(), r.NormFloat64())
// Int32, Int64, and Uint32 generate values of the given width.
// The Int method (not shown) is like either Int32 or Int64
// depending on the size of 'int'.
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, and Int64N limit their output to be < n.
// They do so more carefully than using 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 generates a random permutation of the numbers [0, n).
show("Perm", r.Perm(5), r.Perm(5), r.Perm(5))
}
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
- func ExpFloat64() float64
- func Float32() float32
- func Float64() float64
- func Int() int
- func Int32() int32
- func Int32N(n int32) int32
- func Int64() int64
- func Int64N(n int64) int64
- func IntN(n int) int
- func N(n Int) Int
- func NormFloat64() float64
- func Perm(n int) []int
- func Shuffle(n int, swap func(i, j int))
- func Uint() uint
- func Uint32() uint32
- func Uint32N(n uint32) uint32
- func Uint64() uint64
- func Uint64N(n uint64) uint64
- func UintN(n uint) uint
-
type ChaCha8
- func NewChaCha8(seed [32]byte) *ChaCha8
- func (c *ChaCha8) AppendBinary(b []byte) ([]byte, error)
- func (c *ChaCha8) MarshalBinary() ([]byte, error)
- func (c *ChaCha8) Read(p []byte) (n int, err error)
- func (c *ChaCha8) Seed(seed [32]byte)
- func (c *ChaCha8) Uint64() uint64
- func (c *ChaCha8) UnmarshalBinary(data []byte) error
- type PCG
-
type Rand
- func New(src Source) *Rand
- func (r *Rand) ExpFloat64() float64
- func (r *Rand) Float32() float32
- func (r *Rand) Float64() float64
- func (r *Rand) Int() int
- func (r *Rand) Int32() int32
- func (r *Rand) Int32N(n int32) int32
- func (r *Rand) Int64() int64
- func (r *Rand) Int64N(n int64) int64
- func (r *Rand) IntN(n int) int
- func (r *Rand) NormFloat64() float64
- func (r *Rand) Perm(n int) []int
- func (r *Rand) Shuffle(n int, swap func(i, j int))
- func (r *Rand) Uint() uint
- func (r *Rand) Uint32() uint32
- func (r *Rand) Uint32N(n uint32) uint32
- func (r *Rand) Uint64() uint64
- func (r *Rand) Uint64N(n uint64) uint64
- func (r *Rand) UintN(n uint) uint
- type Source
- type Zipf
Examples
Functions
func ExpFloat64
func ExpFloat64() float64
ExpFloat64 从默认 Source 返回一个在范围 (0, +math.MaxFloat64] 内服从指数分布的 float64,其速率参数 (lambda) 为 1,均值为 1/lambda (1)。 要产生具有不同速率参数的分布, 调用者可以使用以下方式调整输出:
sample = ExpFloat64() / desiredRateParameter
func Float32
func Float32() float32
Float32 从默认 Source 以 float32 返回半开区间 [0.0,1.0) 内的 一个伪随机数。
func Float64
func Float64() float64
Float64 从默认 Source 以 float64 返回半开区间 [0.0,1.0) 内的 一个伪随机数。
func Int
func Int() int
Int 从默认 Source 返回一个非负的伪随机 int。
func Int32
func Int32() int32
Int32 从默认 Source 以 int32 返回一个 非负的伪随机 31 位整数。
func Int32N
func Int32N(n int32) int32
Int32N 从默认 Source 以 int32 返回半开区间 [0,n) 内的 一个伪随机数。 如果 n <= 0,它会 panic。
func Int64
func Int64() int64
Int64 从默认 Source 以 int64 返回一个 非负的伪随机 63 位整数。
func Int64N
func Int64N(n int64) int64
Int64N 从默认 Source 以 int64 返回半开区间 [0,n) 内的 一个伪随机数。 如果 n <= 0,它会 panic。
func IntN
func IntN(n int) int
IntN 从默认 Source 以 int 返回半开区间 [0,n) 内的
一个伪随机数。
如果 n <= 0,它会 panic。
Example
package main
import (
"fmt"
"math/rand/v2"
)
func main() {
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,它会 panic。
Example
package main
import (
"fmt"
"math/rand/v2"
"time"
)
func main() {
// Print an int64 in the half-open interval [0, 100).
fmt.Println(rand.N(int64(100)))
// Sleep for a random duration between 0 and 100 milliseconds.
time.Sleep(rand.N(100 * time.Millisecond))
}
func NormFloat64
func NormFloat64() float64
NormFloat64 从默认 Source 返回一个在范围 [-math.MaxFloat64, +math.MaxFloat64] 内服从 标准正态分布(均值 = 0,标准差 = 1)的 float64。 要产生不同的正态分布,调用者可以使用以下方式 调整输出:
sample = NormFloat64() * desiredStdDev + desiredMean
func Perm
func Perm(n int) []int
Perm 从默认 Source 以 n 个 int 的切片形式返回半开区间 [0,n) 内
整数的一个伪随机排列。
Output:Example
package main
import (
"fmt"
"math/rand/v2"
)
func main() {
for _, value := range rand.Perm(3) {
fmt.Println(value)
}
}
1
2
0
func Shuffle
func Shuffle(n int, swap func(i, j int))
Shuffle 使用默认 Source 对元素的顺序进行伪随机化。
n 是元素的数量。如果 n < 0,Shuffle 会 panic。
swap 交换索引为 i 和 j 的元素。
Example
package main
import (
"fmt"
"math/rand/v2"
"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)
package main
import (
"fmt"
"math/rand/v2"
)
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 Uint
func Uint() uint
Uint 从默认 Source 返回一个伪随机 uint。
func Uint32
func Uint32() uint32
Uint32 从默认 Source 以 uint32 返回一个 伪随机 32 位值。
func Uint32N
func Uint32N(n uint32) uint32
Uint32N 从默认 Source 以 uint32 返回半开区间 [0,n) 内的 一个伪随机数。 如果 n == 0,它会 panic。
func Uint64
func Uint64() uint64
Uint64 从默认 Source 以 uint64 返回一个 伪随机 64 位值。
func Uint64N
func Uint64N(n uint64) uint64
Uint64N 从默认 Source 以 uint64 返回半开区间 [0,n) 内的 一个伪随机数。 如果 n == 0,它会 panic。
func UintN
func UintN(n uint) uint
UintN 从默认 Source 以 uint 返回半开区间 [0,n) 内的 一个伪随机数。 如果 n == 0,它会 panic。
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
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
func (c *ChaCha8) Read(p []byte) (n int, err error)
Read 恰好将 len(p) 个字节读入 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
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 返回一个新的 Rand,它使用来自 src 的随机值 来生成其他随机值。
func (*Rand) ExpFloat64
func (r *Rand) ExpFloat64() float64
ExpFloat64 返回一个在范围 (0, +math.MaxFloat64] 内服从指数分布的 float64,其速率参数 (lambda) 为 1,均值为 1/lambda (1)。 要产生具有不同速率参数的分布, 调用者可以使用以下方式调整输出:
sample = ExpFloat64() / desiredRateParameter
func (*Rand) Float32
func (r *Rand) Float32() float32
Float32 以 float32 返回半开区间 [0.0,1.0) 内的一个伪随机数。
func (*Rand) Float64
func (r *Rand) Float64() float64
Float64 以 float64 返回半开区间 [0.0,1.0) 内的一个伪随机数。
func (*Rand) Int
func (r *Rand) Int() int
Int 返回一个非负的伪随机 int。
func (*Rand) Int32
func (r *Rand) Int32() int32
Int32 以 int32 返回一个非负的伪随机 31 位整数。
func (*Rand) Int32N
func (r *Rand) Int32N(n int32) int32
Int32N 以 int32 返回半开区间 [0,n) 内的一个非负伪随机数。 如果 n <= 0,它会 panic。
func (*Rand) Int64
func (r *Rand) Int64() int64
Int64 以 int64 返回一个非负的伪随机 63 位整数。
func (*Rand) Int64N
func (r *Rand) Int64N(n int64) int64
Int64N 以 int64 返回半开区间 [0,n) 内的一个非负伪随机数。 如果 n <= 0,它会 panic。
func (*Rand) IntN
func (r *Rand) IntN(n int) int
IntN 以 int 返回半开区间 [0,n) 内的一个非负伪随机数。 如果 n <= 0,它会 panic。
func (*Rand) NormFloat64
func (r *Rand) NormFloat64() float64
NormFloat64 返回一个在 范围 -math.MaxFloat64 到 +math.MaxFloat64(含两端)内, 服从标准正态分布(均值 = 0,标准差 = 1)的 float64。 要产生不同的正态分布,调用者可以使用以下方式 调整输出:
sample = NormFloat64() * desiredStdDev + desiredMean
func (*Rand) Perm
func (r *Rand) Perm(n int) []int
Perm 以 n 个 int 的切片形式返回半开区间 [0,n) 内 整数的一个伪随机排列。
func (*Rand) Shuffle
func (r *Rand) Shuffle(n int, swap func(i, j int))
Shuffle 对元素的顺序进行伪随机化。 n 是元素的数量。如果 n < 0,Shuffle 会 panic。 swap 交换索引为 i 和 j 的元素。
func (*Rand) Uint
func (r *Rand) Uint() uint
Uint 返回一个伪随机 uint。
func (*Rand) Uint32
func (r *Rand) Uint32() uint32
Uint32 以 uint32 返回一个伪随机 32 位值。
func (*Rand) Uint32N
func (r *Rand) Uint32N(n uint32) uint32
Uint32N 以 uint32 返回半开区间 [0,n) 内的一个非负伪随机数。 如果 n == 0,它会 panic。
func (*Rand) Uint64
func (r *Rand) Uint64() uint64
Uint64 以 uint64 返回一个伪随机 64 位值。
func (*Rand) Uint64N
func (r *Rand) Uint64N(n uint64) uint64
Uint64N 以 uint64 返回半开区间 [0,n) 内的一个非负伪随机数。 如果 n == 0,它会 panic。
func (*Rand) UintN
func (r *Rand) UintN(n uint) uint
UintN 以 uint 返回半开区间 [0,n) 内的一个非负伪随机数。 如果 n == 0,它会 panic。
type Source
type Source interface { Uint64() uint64 }
Source 是范围 [0, 1<<64) 内均匀分布 伪随机 uint64 值的来源。
Source 不能安全地由多个 goroutine 并发使用。
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 变量生成器。 该生成器生成值 k ∈ [0, imax], 使得 P(k) 与 (v + k) ** (-s) 成正比。 要求:s > 1 且 v >= 1。
func (*Zipf) Uint64
func (z *Zipf) Uint64() uint64
Uint64 返回一个从 Zipf 对象所描述的 Zipf 分布中抽取的值。