Go区间随机数

更新于 2022-05-04 00:28 294
专栏: Golang 标签: Go

区间随机数获取

  1. import (
  2. "crypto/rand"
  3. "math"
  4. "math/big"
  5. )
  6. func RandInt64(min, max int64) int64 {
  7. if min > max {
  8. panic("the min is greater than max!")
  9. }
  10. if min < 0 {
  11. f64Min := math.Abs(float64(min))
  12. i64Min := int64(f64Min)
  13. result, _ := rand.Int(rand.Reader, big.NewInt(max+1+i64Min))
  14. return result.Int64() - i64Min
  15. } else {
  16. result, _ := rand.Int(rand.Reader, big.NewInt(max-min+1))
  17. return min + result.Int64()
  18. }
  19. }