dongyiluan1718
dongyiluan1718
2017-08-18 09:38
浏览 108
已采纳

为什么要重复相同的随机数?

I'm new to Go and not sure why it prints the same number for rand.Intn(n int) int for every run:

package main

import (
    "fmt"
    "math/rand"
)


func main() {
    fmt.Println(rand.Intn(10)) 
}

The docs says :

Intn returns, as an int, a non-negative pseudo-random number in [0,n) from the default Source. It panics if n <= 0.

And how do I properly seed the random number generation?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dth20986
    dth20986 2017-08-18 09:42
    已采纳

    By calling the rand.Seed() function, passing it a (random) seed (typically the current unix timestamp). Quoting from math/rand package doc:

    Top-level functions, such as Float64 and Int, use a default shared Source that produces a deterministic sequence of values each time a program is run. Use the Seed function to initialize the default Source if different behavior is required for each run.

    Example:

    rand.Seed(time.Now().UnixNano())
    

    If rand.Seed() is not called, the generator behaves as if seeded by 1:

    Seed uses the provided seed value to initialize the default Source to a deterministic state. If Seed is not called, the generator behaves as if seeded by Seed(1).

    点赞 评论
  • dongyata3336
    dongyata3336 2017-12-28 22:26
    package main
    
    import
    
    (
    "fmt"
    "math/rand"
    "time"
    )
    
    func randomGen(min, max int) int {
    rand.Seed(time.Now().Unix())
    return rand.Intn(max - min) + min
    }
    
    func main() {
    randNum := randomGen(1, 10)
    fmt.Println(randNum)
    }
    
    点赞 评论
  • doude4924
    doude4924 2018-08-22 12:39

    Under the package, math/rand, you can find a type Rand.

    func New(src Source) *Rand - New returns a new Rand that uses random values from src to generate other random values.

    It actually needs a seed to generate it.

    1. step 1: create a seed as a source using new Source. time.Now().UnixNano() is used for the accuracy.
    2. step 2: create a type Rand from the seed
    3. step 3: generate a random number.

    Example:

    package main
    
    import (
        "fmt"
        "math/rand"
        "time"
    )   
    
    func main() {  
        source := rand.NewSource(time.Now().UnixNano())    
        r := rand.New(source)    
        fmt.Println(r.Intn(100))    
    }
    
    点赞 评论

相关推荐