You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go_mqtt/utils/RandomNumber.go

82 lines
1.6 KiB
Go

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package utils
import (
"fmt"
"github.com/shopspring/decimal"
"math"
"math/rand"
"testing"
"time"
)
func init() {
// 初始化rand模块的Seed要不然所有的随机值会一样
rand.Seed(time.Now().UnixNano())
}
// 获取随机float64 保留2位小数 Notice 不四舍五入
func GetRandomFloat64(min, max float64) float64 {
min, max = math.Abs(min), math.Abs(max)
min, max = GetMinFloat64WHW(min, max), GetMaxFloat64WHW(min, max)
// 到这里确保 max>=min 并且二者一定是正数
ret := GetMinFloat64WHW(min, max) + rand.Float64()*(max-min)
// 不四舍五入
ret, _ = decimal.NewFromFloat(ret).RoundFloor(2).Float64()
if ret > max {
ret = max
}
if ret < min {
ret = min
}
return ret
}
func GetMaxFloat64WHW(min, max float64) float64 {
if min >= max {
return min
}
return max
}
func GetMinFloat64WHW(min, max float64) float64 {
if min <= max {
return min
}
return max
}
func TestRandFloat64222(t *testing.T) {
fmt.Println(GetRandomFloat64(1, 2))
fmt.Println(GetRandomFloat64(-1.2233, 2.123))
fmt.Println(GetRandomFloat64(3.2, 2))
fmt.Println(GetRandomFloat64(0.01, 0.1))
fmt.Println(GetRandomFloat64(-0.01, 0.1))
}
// 随机数
// 生成min与max之间的整数包含
func GenRandomInt(min, max int) int {
if min == max {
return min
}
// 为了保险取两个值之间大的那个作为max
randNum := rand.Intn(GetMaxInt(min, max)-min) + min
return randNum
}
func GetMaxInt(min, max int) int {
if max >= min {
return max
}
return min
}
func GetMinInt(min, max int) int {
if min <= max {
return min
}
return max
}