From 2e5b9bc200817b84b937c0f7a04a00967dfdb6da Mon Sep 17 00:00:00 2001 From: Yurun Date: Wed, 25 Dec 2024 14:13:11 +0800 Subject: [PATCH] fix: fix the bug of random.RandFloats() infinite loop and the result of random.RandFloat() sometimes equals to max. --- random/random.go | 14 +++++++++++++- random/random_test.go | 8 ++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/random/random.go b/random/random.go index ae0c2587..993e23b5 100644 --- a/random/random.go +++ b/random/random.go @@ -126,12 +126,24 @@ func RandFloat(min, max float64, precision int) float64 { n := rand.Float64()*(max-min) + min - return mathutil.RoundToFloat(n, precision) + return mathutil.FloorToFloat(n, precision) } // RandFloats generate a slice of random float64 numbers of length that do not repeat. // Play: https://go.dev/play/p/I3yndUQ-rhh func RandFloats(length int, min, max float64, precision int) []float64 { + if max < min { + min, max = max, min + } + + maxLength := int((max - min) * math.Pow10(precision)) + if maxLength == 0 { + maxLength = 1 + } + if length > maxLength { + length = maxLength + } + nums := make([]float64, length) used := make(map[float64]struct{}, length) for i := 0; i < length; { diff --git a/random/random_test.go b/random/random_test.go index eb4a822b..602cb15b 100644 --- a/random/random_test.go +++ b/random/random_test.go @@ -197,6 +197,14 @@ func TestRandFloats(t *testing.T) { } assert.Equal(len(numbers), 5) + + numbers2 := RandFloats(10, 3.14, 3.2, 2) + for _, n := range numbers2 { + assert.GreaterOrEqual(n, 3.14) + assert.Less(n, 3.2) + } + + assert.Equal(len(numbers2), 6) } func TestRandIntSlice(t *testing.T) {