生成Go中某个范围内的随机数

问题描述 投票:20回答:4

math/rand中的所有整数函数都会生成非负数。

math/rand

我想生成[-m,n)范围内的随机数。换句话说,我想产生一个正数和负数的组合。

random go
4个回答
26
投票

我在rand.Int() int // [0, MaxInt] rand.Int31() int32 // [0, MaxInt32] rand.Int31n(n int32) int32 // [0, n) rand.Int63() int64 // [0, MaxInt64] rand.Int63n(n int64) int64 // [0, n) rand.Intn(n int) int // [0, n) 处发现了这个示例,它等效于Go Cookbook(如果存在该函数):

rand.Range(min, max int)

5
投票

为防止一遍又一遍地重复rand.Intn(max - min) + min min,我建议在考虑范围时随机切换。这是我发现可以正常使用的内容:

max

package main import ( "fmt" "math/rand" ) // range specification, note that min <= max type IntRange struct { min, max int } // get next random value within the interval including min and max func (ir *IntRange) NextRandom(r* rand.Rand) int { return r.Intn(ir.max - ir.min +1) + ir.min } func main() { r := rand.New(rand.NewSource(55)) ir := IntRange{-1,1} for i := 0; i<10; i++ { fmt.Println(ir.NextRandom(r)) } }

指定范围

菜谱中的See on Go Playground未能准确地指定solution you foundmin的工作方式,但是它当然满足您的要求[-min,max))。我决定将范围指定为封闭间隔([-min,max],这意味着其边界已包含在有效范围内)。相比我对菜谱描述的理解:

为您指定的任意两个正数内的随机数(在本例中为1和6)。

(可以在max中找到]

Cookbook的实现是一个人完成(当然,这使它与很多程序相伴的优秀公司相处得很好)。


3
投票

这将在给定范围[a,b]中生成随机数

below the code snippet in the Golang Cookbook

rand.Seed(time.Now().UnixNano()) n := a + rand.Intn(b-a+1)


2
投票

我写的用于生成随机切片的小实用程序(非常类似于python范围)

代码-source

https://github.com/alok87/goutils/blob/master/pkg/random/random.go
© www.soinside.com 2019 - 2024. All rights reserved.