1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-12 16:52:29 +08:00

Compare commits

...

3 Commits

Author SHA1 Message Date
dudaodong
a0d97cf38e Merge branch 'rc' into v2 2024-12-25 16:13:04 +08:00
残念
1f6bab467c Merge pull request #282 from Yurunsoft/fix-RandFloats
fix the bug of random.RandFloats() infinite loop and the result of random.RandFloat() sometimes equals to max.
2024-12-25 15:14:17 +08:00
Yurun
2e5b9bc200 fix: fix the bug of random.RandFloats() infinite loop and the result of random.RandFloat() sometimes equals to max. 2024-12-25 14:13:11 +08:00
2 changed files with 21 additions and 1 deletions

View File

@@ -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; {

View File

@@ -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) {