1 回答
TA贡献1784条经验 获得超9个赞
例如,
package main
import (
"fmt"
"math/rand"
"time"
)
// Returns the selected weight based on the weights(probabilities)
// Fitness proportionate selection:
// https://en.wikipedia.org/wiki/Fitness_proportionate_selection
func rouletteSelect(weights []float64) float64 {
// calculate the total weights
sum := 0.0
for _, weight := range weights {
sum += weight
}
// get a random value
value := rand.Float64() * sum
// locate the random value based on the weights
for _, weight := range weights {
value -= weight
if value <= 0 {
return weight
}
}
// only when rounding errors occur
return weights[len(weights)-1]
}
func main() {
rand.Seed(time.Now().UnixNano())
weights := []float64{0.1, 0.2, 0.3, 0.4}
fmt.Println(rouletteSelect(weights))
}
- 1 回答
- 0 关注
- 210 浏览
添加回答
举报