Seeding rand.Intn

polaris · · 3446 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hey guys, I am messing around on A Tour of Go and The Go Playground trying to get a random number and it doesn&#39;t seem to be working. Should the following code work?</p> <p>package main </p> <p>import (<br/> &#34;fmt&#34;<br/> &#34;math/rand&#34;<br/> &#34;time&#34;<br/> ) </p> <p>func main() {<br/> rand.Seed(time.Now().UnixNano())<br/> fmt.Println(&#34;My favorite number is&#34;, rand.Intn(10))<br/> } </p> <hr/>**评论:**<br/><br/>dlsniper: <pre><p>The playground caches the results. Also random is deterministic. And finally the time in playground is always the same. See more info by clicking the About section of the playground.</p></pre>liahkim3: <pre><p>Woo! I was hoping this was the case. It said that rand.Intn was deterministic and to use the Seed method to get a random number so I thought I was doing something wrong. Thanks!</p></pre>sleepydog: <pre><p>Just so you know, if you don&#39;t want outsiders to be able to guess what the next number will be, seeding an RNG with the local time is undesirable. In such a use case, you should use the OS&#39;s entropy source, which in Go is exposed through the Reader variable in the crypto/rand package. Something like this: <a href="" rel="nofollow"></a></p></pre>Thomasdezeeuw: <pre><p>You should be using crypto/rand for generating anything that needs to be random (or the closed thing to it). It is however a little slower then math/rand, so you could seed math/rand with a seed generated by crypto/rand.</p></pre>dchapes: <pre><p>On some systems the entropy pool for the system wide <code>/dev/urandom</code> (or equivalent) is limited. Unless you really need cryptographic secure random numbers you should <strong>not</strong> use <code>crypto/rand</code>.</p> <p>A really good compromise is to use <code>crypto/rand</code> to seed <code>math/rand</code> (as both you and sleepydog <a href="" rel="nofollow">said above</a>). IMO, there should be a convenience function to do this in the standard library (ala BSD&#39;s <a href="" rel="nofollow">srandomdev(3)</a> which also can set the PRNG state to more values than a single int64 can).</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

3446 次点击  
加入收藏 微博
0 回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传