gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:16:28 30 4
gpt4 key购买 nike

我正在为遗传算法构建一个模拟轮盘赌选择函数。首先,我想在主函数中添加 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))
}

关于algorithm - 使用 Golang 的遗传算法中的轮盘赌选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33003974/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com