Browse Source

加入区间随机数

master v0.2.5
listen 3 years ago
parent
commit
c02fce39fb
1 changed files with 44 additions and 0 deletions
  1. +44
    -0
      rand.go

+ 44
- 0
rand.go View File

@ -0,0 +1,44 @@
package helper
import (
"crypto/rand"
"math/big"
)
/**
* 获取int类型的区间随机数
*/
func GetRandInt(min, max int) (r int, err error) {
_r, err := GetRandInt64(int64(min), int64(max))
if err != nil {
return
}
r = int(_r)
return
}
/**
* 获取int64类型的区间随机数
*/
func GetRandInt64(min, max int64) (r int64, err error) {
if min == max {
r = min
return
}
if min > max {
max, min = min, max
}
result, err := rand.Int(rand.Reader, big.NewInt(max-min))
if err != nil {
return
}
r = result.Int64() + min
b, err := rand.Int(rand.Reader, big.NewInt(2))
if err == nil && b.Int64() == 1 {
r += 1
}
return
}

Loading…
Cancel
Save