遺伝的アルゴリズムのための模擬ルーレットホイール選択関数を作成しています。まずの、私は追加したいと思うsum
のがfitnessScore
主な機能で。合計した後、Go のパッケージfitnessScore
をsum
使用して、値をランダム化したかったのmath/rand
です。このシナリオで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))
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加