如何在golang中获取随机数样本? [英] How to get a sample of random numbers in golang?

查看:70
本文介绍了如何在golang中获取随机数样本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

或者我必须使用简单的方法,例如:

Or I have to use straightforward way like:

var arr []int

for i := 0; i < 5; i++ {
    arr = append(arr, rand.Intn(100))
}

推荐答案

您所做的工作既干净又快速.您可以对此进行改进的是,预先分配切片并使用 for..range 循环将其填充,如下所示:

What you did is clean and fast enough. What you could improve on it is to pre-allocate the slice and fill it using a for.. range loop like this:

s := make([]int, 5)
for i := range s {
    s[i] = rand.Intn(100)
}

math/rand 软件包还具有 rand.Read() 函数,该函数用随机字节填充切片.因此,如果您想用随机数据填充 [] byte 切片,则只需这样做:

The math/rand package also has a rand.Read() function which fills a slice with random bytes. So if you want to fill a []byte slice with random data, this is all it takes:

s := make([]byte, 100)
rand.Read(s) // This never returns an error

另一种有趣的方式是利用 rand.Rand io.Reader .这意味着它具有 Read()方法,该方法会用随机数据填充 [] byte .

Another interesting way would be to take advantage of rand.Rand being an io.Reader. Which means it has a Read() method which fills a []byte with random data.

这与 encoding/binary 包结合在一起,您可以使用随机数据填充"变量.创建 rand.Rand 并将其传递给 binary.Read() 功能就是源代码.

This combined with the encoding/binary package, you can "fill" variables with random data. Create and pass a rand.Rand to the binary.Read() function as the source, and that's it.

它是这样的:

r := rand.New(rand.NewSource(time.Now().UnixNano()))

s := make([]int32, 5)
err := binary.Read(r, binary.BigEndian, &s)
if err != nil {
    panic(err)
}
fmt.Println(s)

输出:

[203443513 1611652563 -235795288 8294855 -802604260]

这足够酷",甚至可以填充结构,例如:

This is "cool" enough to even fill structs for example:

var point struct{ X, Y int16 }
err = binary.Read(r, binary.BigEndian, &point)
if err != nil {
    panic(err)
}
fmt.Printf("%+v", point)

输出:

{X:-15471 Y:2619}

游乐场上尝试这些示例.

使用 binary.Read()的一个障碍是-可以理解-它只能填充固定大小的类型的值,最著名的例外是常见的 int 类型,其大小不固定(取决于体系结构).因此,您不能使用 int 类型的字段填充 [] int 切片或结构.这就是为什么在上面的示例中使用 int32 int16 类型的原因.

One handicap of using binary.Read() is that–understandably–it can only fill values of fixed-size types, and the most famous exception is the common int type, whose size is not fixed (architecture dependent). So you can't fill an []int slice or a struct with a field of int type. That's why I used int32 and int16 types in the above examples.

当然,在这些解决方案中,您不能限制用于填充变量的随机数的范围.为此,初始循环仍然更容易.

Of course in these solutions you could not limit the range of random numbers that are used to fill your variables. For that, the initial loop is still easier.

这篇关于如何在golang中获取随机数样本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆