Random Numbers {.en}

随机数 {.zh}

::: {.en} Go’s math/rand package provides pseudorandom number generation. :::

::: {.zh}

Go的math / rand包提供[伪随机数](http://en.wikipedia.org/wiki/Pseudorandom_number_generator)生成。

:::

  1. package main
  2. import "time"
  3. import "fmt"
  4. import "math/rand"
  5. func main() {

::: {.en} For example, rand.Intn returns a random int n, 0 <= n < 100. :::

::: {.zh}

例如,rand.Intn返回一个随机的intn,0 <= n <100

:::

  1. fmt.Print(rand.Intn(100), ",")
  2. fmt.Print(rand.Intn(100))
  3. fmt.Println()

::: {.en} rand.Float64 returns a float64 f, 0.0 <= f < 1.0. :::

::: {.zh}

rand.Float64返回float64``f0.0 <= f <1.0

:::

  1. fmt.Println(rand.Float64())

::: {.en} This can be used to generate random floats in other ranges, for example 5.0 <= f' < 10.0. :::

::: {.zh}

这可以用于在其他范围内生成随机浮点数,例如“5.0 <= f”<10.0`。

:::

  1. fmt.Print((rand.Float64()*5)+5, ",")
  2. fmt.Print((rand.Float64() * 5) + 5)
  3. fmt.Println()

::: {.en} The default number generator is deterministic, so it’ll produce the same sequence of numbers each time by default. To produce varying sequences, give it a seed that changes. Note that this is not safe to use for random numbers you intend to be secret, use crypto/rand for those. :::

::: {.zh}

默认数字生成器是确定性的,因此默认情况下每次都会生成相同的数字序列。要生成不同的序列,请给它一个变化的种子。注意这对于随机数使用是不安全的。 crypto / rand

:::

  1. s1 := rand.NewSource(time.Now().UnixNano())
  2. r1 := rand.New(s1)

::: {.en} Call the resulting rand.Rand just like the functions on the rand package. :::

::: {.zh}

调用生成的rand.Rand就像rand包中的函数一样。

:::

  1. fmt.Print(r1.Intn(100), ",")
  2. fmt.Print(r1.Intn(100))
  3. fmt.Println()

::: {.en} If you seed a source with the same number, it produces the same sequence of random numbers. :::

::: {.zh}

如果为具有相同编号的源播种,则会生成相同的随机数序列。

:::

  1. s2 := rand.NewSource(42)
  2. r2 := rand.New(s2)
  3. fmt.Print(r2.Intn(100), ",")
  4. fmt.Print(r2.Intn(100))
  5. fmt.Println()
  6. s3 := rand.NewSource(42)
  7. r3 := rand.New(s3)
  8. fmt.Print(r3.Intn(100), ",")
  9. fmt.Print(r3.Intn(100))
  10. }
  1. $ go run random-numbers.go
  2. 81,87
  3. 0.6645600532184904
  4. 7.123187485356329,8.434115364335547
  5. 0,28
  6. 5,87
  7. 5,87

::: {.en} See the math/rand package docs for references on other random quantities that Go can provide. :::

::: {.zh}

请参阅[math / rand](http://golang.org/pkg/math/rand/)包文档,以获取Go可提供的其他随机数量的参考。

:::