Reputation: 21
I'm building a mock roulette wheel selection function for genetic algorithm. First of, I would want to add up the sum
of the fitnessScore
in the main function. After adding up the fitnessScore
I wanted to randomize a value out of that sum
using the math/rand
package in Go. How should I use the rand package in this scenario how do I fix spin_wheel := rand.sum
in order to random a value?
package main
import(
"fmt"
"time"
"math/rand"
)
func rouletteWheel(fitnessScore []float64) []float64{
sum := 0.0
for i := 0; i < len(fitnessScore); i++ {
sum += fitnessScore[i]
}
rand.Seed(time.Now().UnixNano())
spin_wheel := rand.sum
partial_sum := 0.0
for i := 0; i < len(fitnessScore); i++{
partial_sum += fitnessScore[i]
if(partial_sum >= spin_wheel){
return fitnessScore
}
}
return fitnessScore
}
func main(){
fitnessScore := []float64{0.1, 0.2, 0.3, 0.4}
fmt.Println(rouletteWheel(fitnessScore))
}
Upvotes: 0
Views: 723
Reputation: 166895
For example,
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))
}
Upvotes: 1