Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix the bug of random.RandFloats() infinite loop and the result of random.RandFloat() sometimes equals to max. #282

Merged
merged 1 commit into from
Dec 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion random/random.go
Original file line number Diff line number Diff line change
Expand Up @@ -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; {
Expand Down
8 changes: 8 additions & 0 deletions random/random_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Loading