使用 Golang 的遗传算法中的轮盘赌选择

Roulette Wheel Selection in Genetic Algorithm using Golang

我正在为遗传算法构建一个模拟轮盘赌选择函数。首先,我想在 main 函数中添加 fitnessScoresum。在添加 fitnessScore 之后,我想使用 Go 中的 math/rand 包从 sum 中随机化一个值。在这种情况下我应该如何使用 rand 包如何修复 spin_wheel := rand.sum 以便随机值?

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))
}

例如,

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))
}