我为遗传算法构建了一个模拟轮盘赌选择功能。首先,我想在主函数中加上sum
的{{1}}。在汇总fitnessScore
之后,我想使用Go中的fitnessScore
包随机化sum
中的值。在这种情况下我应该如何使用rand包来如何修复math/rand
以便随机输入值?
spin_wheel := rand.sum
答案 0 :(得分:1)
例如,
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))
}