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

karl_zhao · · 4547 次点击
<a href="/user/254244460" title="@254244460">@254244460</a> 这个方式是可行的,只是描述的不清楚。首先第一次随机数在0~100之间的数据对应概率范围。比如,0~50之间的数对应50%的概率,51~70对应后20%的概率,70~90对应再后来的20%的概率,90~100之间的数字对应10%的概率,之后再根据概率区间随机生成对应的相应区间的数字。
#4
更多评论
import ( &#34;crypto/rand&#34; &#34;fmt&#34; &#34;math/big&#34; ) 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 &lt; 50 { return nrand(16) } if g &lt; 70 { return 16 + nrand(16) } if g &lt; 90 { return 32 + nrand(32) } return 64 + nrand(64) } func main(){ var p0, p1 ,p2 ,p3 []uint32 for i:= 0 ; i&lt; 1000 ; i++ { g := genNumber() if g &lt; 16 { p0 = append(p0, g) continue } if g &lt; 32 { p1 = append(p1,g) continue } if g &lt; 64 { p2 = append(p2,g) continue } p3 = append(p3,g) } fmt.Printf(&#34;0~15 %v\n&#34;, len(p0)) fmt.Printf(&#34;16~32 %v\n&#34;, len(p1)) fmt.Printf(&#34;32~64 %v\n&#34;, len(p2)) fmt.Printf(&#34;64~128 %v\n&#34;, len(p3)) }
#1
buscoop
纸上得来终觉浅,绝知此事要躬行!
很好看!!
#2