想用go实现一个按着设置的概率产生一定范围内的随机数,请大牛指教

karl_zhao · · 4571 次点击
import ( "crypto/rand" "fmt" "math/big" ) func nrand(l int64) uint32 { max := big.NewInt(l) bigx, _ := rand.Int(rand.Reader, max) x := bigx.Int64() return uint32(x) } func genNumber() uint32{ g := nrand(100) if g < 50 { return nrand(16) } if g < 70 { return 16 + nrand(16) } if g < 90 { return 32 + nrand(32) } return 64 + nrand(64) } func main(){ var p0, p1 ,p2 ,p3 []uint32 for i:= 0 ; i< 1000 ; i++ { g := genNumber() if g < 16 { p0 = append(p0, g) continue } if g < 32 { p1 = append(p1,g) continue } if g < 64 { p2 = append(p2,g) continue } p3 = append(p3,g) } fmt.Printf("0~15 %v\n", len(p0)) fmt.Printf("16~32 %v\n", len(p1)) fmt.Printf("32~64 %v\n", len(p2)) fmt.Printf("64~128 %v\n", len(p3)) }
#1
更多评论
buscoop
纸上得来终觉浅,绝知此事要躬行!
很好看!!
#2
两次随机,第一次随机范围0-100确定区间,第二次再确定具体的数值,比如第一次得到49,对应区间0-15,再随机0-15
#3