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

我正在为遗传算法构建一个模拟轮盘选择函数。首先,我会想加起来sum的fitnessScore主功能。加起来后,fitnessScore我想sum使用math/randGo 中的包随机化一个值。在这种情况下我应该如何使用 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))

}


江户川乱折腾
浏览 211回答 1
1回答

千万里不及你

例如,package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "math/rand"&nbsp; &nbsp; "time")// Returns the selected weight based on the weights(probabilities)// Fitness proportionate selection:// https://en.wikipedia.org/wiki/Fitness_proportionate_selectionfunc rouletteSelect(weights []float64) float64 {&nbsp; &nbsp; // calculate the total weights&nbsp; &nbsp; sum := 0.0&nbsp; &nbsp; for _, weight := range weights {&nbsp; &nbsp; &nbsp; &nbsp; sum += weight&nbsp; &nbsp; }&nbsp; &nbsp; // get a random value&nbsp; &nbsp; value := rand.Float64() * sum&nbsp; &nbsp; // locate the random value based on the weights&nbsp; &nbsp; for _, weight := range weights {&nbsp; &nbsp; &nbsp; &nbsp; value -= weight&nbsp; &nbsp; &nbsp; &nbsp; if value <= 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return weight&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; // only when rounding errors occur&nbsp; &nbsp; return weights[len(weights)-1]}func main() {&nbsp; &nbsp; rand.Seed(time.Now().UnixNano())&nbsp; &nbsp; weights := []float64{0.1, 0.2, 0.3, 0.4}&nbsp; &nbsp; fmt.Println(rouletteSelect(weights))}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go