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

时间:2015-10-07 23:11:59

标签: algorithm go artificial-intelligence

我为遗传算法构建了一个模拟轮盘赌选择功能。首先,我想在主函数中加上sum的{​​{1}}。在汇总fitnessScore之后,我想使用Go中的fitnessScore包随机化sum中的值。在这种情况下我应该如何使用rand包来如何修复math/rand以便随机输入值?

spin_wheel := rand.sum

1 个答案:

答案 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))
}
相关问题