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

报告相同问题?

悬赏问题

  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动