英文:
How to choose a random number from the range?
问题
我阅读了函数Intn的文档https://golang.org/pkg/math/rand/#Intn,但我不明白它们的意思。
我知道随机数与伪随机数的区别。但是如何模拟一个在1到1000范围内的随机数呢?
package main
import (
"fmt"
"math/rand"
)
func main() {
fmt.Println(randInt(1, 1000))
}
func randInt(min int, max int) int {
return min + rand.Intn(max-min)
}
答案总是879
func main() {
fmt.Print(rand.Intn(100))
}
答案总是81
英文:
I read the documentation for the function Intn https://golang.org/pkg/math/rand/#Intn but I don't understand what they mean
I know how random differs from pseudo-random. But how can I simulate a random in the range from 1 to 1000 for example?
package main
import (
"fmt"
"math/rand"
)
func main() {
fmt.Println(randInt(1, 1000))
}
func randInt(min int, max int) int {
return min + rand.Intn(max-min)
}
The answer is always 879
func main() {
fmt.Print(rand.Intn(100))
}
The answer is always 81
答案1
得分: 5
你需要“种子化”随机数生成器。这就像是告诉伪随机数生成器如何生成你的数字的代码。现在,你不能随便给它一个数字,否则每次生成的结果都会相同。通常一个好的做法是用当前时间作为种子。
package main
import (
"fmt"
"math/rand"
"time" //添加
)
func main() {
// 种子应该在程序运行期间只设置一次,最好的地方是在 func init() 中
rand.Seed(time.Now().UTC().UnixNano()) //添加
fmt.Println(randInt(1, 1000))
}
func randInt(min int, max int) int {
return min + rand.Intn(max-min)
}
现在每次调用你的 randInt()
函数时,它将使用种子函数被调用时的时间来生成随机数。
英文:
You need to "Seed" the random number generator. This is like the code that tells the pseudo random number generator how to generate your numbers. Now, you can't just give this any number, or you are going to generate the same set every time. Often a good practice is to seed with the current time.
package main
import (
"fmt"
"math/rand"
"time" #ADDED
)
func main() {
// Seed should be set once, better spot is func init()
rand.Seed(time.Now().UTC().UnixNano()) #ADDED
fmt.Println(randInt(1, 1000))
}
func randInt(min int, max int) int {
return min + rand.Intn(max-min)
}
Now every time you call your randInt()
function, it will use the time from when the seed function was called to generate the random number.
答案2
得分: 1
两点。首先,正如math/rand
文档顶部所述:
如果需要每次运行时都有不同的行为,请使用Seed函数初始化默认的Source。
如果你不在每次运行时使用不同的种子(例如时钟时间)进行初始化,那么每次运行都会得到相同的结果,因为默认种子始终为1。
其次,如果你在Playground上运行此代码,无论何时都会得到相同的结果,因为它会缓存执行的结果。如果代码相同,结果也将相同。
英文:
Two points. First, as the documentation for math/rand
states right at the top:
> Use the Seed function to initialize the default Source if different behavior is required for each run.
If you don't Seed it with something different each run (e.g. clock time), you'll get the same result every run, because the default seed is always 1.
Second, if you're running this on the Playground, you'll get the same result every time regardless because it caches the results of executions. If the code is the same, the result will be the same.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论