rand.go (726B)
1 package rand 2 3 import ( 4 "crypto/rand" 5 "fmt" 6 "io" 7 "math/big" 8 ) 9 10 func init() { 11 Reader = rand.Reader 12 } 13 14 // Reader provides a random reader that can reset during testing. 15 var Reader io.Reader 16 17 var floatMaxBigInt = big.NewInt(1 << 53) 18 19 // Float64 returns a float64 read from an io.Reader source. The returned float will be between [0.0, 1.0). 20 func Float64(reader io.Reader) (float64, error) { 21 bi, err := rand.Int(reader, floatMaxBigInt) 22 if err != nil { 23 return 0, fmt.Errorf("failed to read random value, %v", err) 24 } 25 26 return float64(bi.Int64()) / (1 << 53), nil 27 } 28 29 // CryptoRandFloat64 returns a random float64 obtained from the crypto rand 30 // source. 31 func CryptoRandFloat64() (float64, error) { 32 return Float64(Reader) 33 }