doutang2382 2015-10-07 23:11
浏览 83
已采纳

Golang遗传算法中的轮盘选择

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))
}
  • 写回答

1条回答 默认 最新

  • dongmuyan5638 2015-10-08 01:58
    关注

    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))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了