亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Golang 在遺傳算法中選擇輪盤賭

使用 Golang 在遺傳算法中選擇輪盤賭

Go
江戶川亂折騰 2021-11-15 15:31:43
我正在為遺傳算法構建一個模擬輪盤選擇函數。首先,我會想加起來sum的fitnessScore主功能。加起來后,fitnessScore我想sum使用math/randGo 中的包隨機化一個值。在這種情況下我應該如何使用 rand 包如何修復spin_wheel := rand.sum以隨機化一個值?package mainimport(    "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 回答

?
千萬里不及你

TA貢獻1784條經驗 獲得超9個贊

例如,


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))

}


查看完整回答
反對 回復 2021-11-15
  • 1 回答
  • 0 關注
  • 254 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號