栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

Go语言——随机数(math/rand包)

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Go语言——随机数(math/rand包)

概述:
  1. 使⽤时需要import “math/rand”,rand包实现了伪随机数⽣成器。
  2. 随机数从资源⽣成。包⽔平的函数都使⽤的默认的公共资源。该资源会在程序每次运⾏时都产⽣确定的序列。如果需要每次运⾏产⽣不同的序列,应使⽤Seed函数进⾏初始化。默认资源可以安全的⽤于多协程并发。
rand包中类型及⽅法
  1. type Source
    func NewSource(seed int64) Source
  2. type Rand
    func New(src Source) *Rand
    func (r *Rand) Seed(seed int64)
    func (r *Rand) Int() int
    func (r *Rand) Int31() int32
    func (r *Rand) Int63() int64
    func (r *Rand) Uint32() uint32
    func (r *Rand) Intn(n int) int
    func (r *Rand) Int31n(n int32) int32
    func (r *Rand) Int63n(n int64) int64
    func (r *Rand) Float32() float32
    func (r *Rand) Float64() float64
    func (r *Rand) NormFloat64() float64
    func (r *Rand) ExpFloat64() float64
    func (r *Rand) Perm(n int) []int
  3. type Zipf
    func NewZipf(r *Rand, s float64, v float64, imax uint64) *Zipf
    func (z *Zipf) Uint64() uint64
    func Seed(seed int64)
    func Int() int
    func Int31() int32
    func Int63() int64
    func Uint32() uint32
    func Intn(n int) int
    func Int31n(n int32) int32
    func Int63n(n int64) int64
    func Float32() float32
    func Float64() float64
    func NormFloat64() float64
    func ExpFloat64() float64
    func Perm(n int) []int
rand包中核⼼⽅法介绍
  1. func NewSource(seed int64) Source
    使⽤给定的种⼦创建⼀个伪随机资源。
  2. func New(src Source) Rand
    返回⼀个使⽤src⽣产的随机数来⽣成其他各种分布的随机数值的Rand。
  3. func (r*Rand) Seed(seed int64)
    使⽤给定的seed来初始化⽣成器到⼀个确定的状态。
  4. func (r *Rand) Int() int
    返回⼀个⾮负的伪随机int值。
  5. func (r *Rand) Intn(n int) int
    返回⼀个取值范围在[0,n)的伪随机int值,如果n<=0会panic。
  6. func (r *Rand) Float64() float64
    返回⼀个取值范围在[0.0, 1.0)的伪随机float64值。
获取随机数的⼏种⽅式:
  1. 通过默认随机数种⼦获取随机数
    rand.Int()
    rand.Float64()
    rand.Intn(n) // 例如获取0-n之间随机数
    总是⽣成固定的随机数。默认情况下,随机数种⼦都是1。seed是⼀个64位整数。
  2. 动态随机数种⼦⽣成随机资源,实例随机对象来获取随机数
    s1 := rand.NewSource(time.Now().UnixNano())
    r1 := rand.New(s1)
    randnum := r1.Intn(n) // 例如获取0-n之间随机数
  3. 简写形式:动态变化随机数种⼦来获取随机数
    (1)、获取整型随机数[0,10]
    rand.Seed(time.Now().UnixNano())
    rand.Intn(10)
    (2)、 获取浮点型0.0⾄1.0之间的随机数
    rand.Seed(time.Now().UnixNano())
    rand.Float64()
    (3)、 获取两数之间随机数[m , n]
    rand.Seed(time.Now().UnixNano())
    随机数 = rand.Intn(n - m + 1) + m
    例如:获取[5,11]之间随机数: rand.Intn(7) + 5
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/990628.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号