更奇怪的是,我大年夜来没有提到过这些办法的接口。请记住,因为没有对象,也没有持续。QuadraticGA构造体是一个空白对象,隐式地作为GeneticAlgorithmRunner。每个必须的办法都在括号中绑定到该构造体,就像Java中的“@ override”。如今,构造体和设置须要传递给运行该算法的模块。
- settings := ga.GeneticAlgorithmSettings{
- PopulationSize: 5,
- MutationRate: 10,
- CrossoverRate: 100,
- NumGenerations: 20,
- KeepBestAcrossPopulation: true,
- }
- best, err := ga.Run(QuadraticGA{}, settings)
- if err != nil {
- println(err)
- }else{
- fmt.Printf("Best: x: %f y: %f\n", best, calculate(best.(float64)))
- }
- Best: x: 3.072833 y: -6.994695
很简单,对吧?“QuadraticGA {}”只是简单地创建了该构造的一个新实例,其余的则由Run()办法完成。该办法返回搜刮结不雅和产生的任何缺点,因为Go不信赖try / catch——另一场战斗作者采取了严格的设计立场。
- func makeNewEntry() float64 {
- return highRange * rand.Float64()
- }
- func calculate(x float64) float64 {
- return math.Pow(x, 2) - 6*x + 2 // minimum should be at x=3
- }
- func Run(geneticAlgoRunner GeneticAlgorithmRunner, settings GeneticAlgorithmSettings) (interface{}, error){
- population := geneticAlgoRunner.GenerateInitialPopulation(settings.PopulationSize)
- geneticAlgoRunner.Sort(population)
- bestSoFar := population[len(population) - 1]
- for i:= 0; i < settings.NumGenerations; i++ {
- newPopulation := make([]interface{}, 0, settings.PopulationSize)
- if settings.KeepBestAcrossPopulation {
- newPopulation = append(newPopulation, bestSoFar)
- }
- // perform crossovers with random selection
- probabilisticListOfPerformers := createStochasticProbableListOfIndividuals(population)
- newPopIndex := 0
推荐阅读
Tech Neo技巧沙龙 | 11月25号,九州云/ZStack与您一路商量云时代收集界线治理实践 10 月浏览器市场份额数据显示,Chrome 市场份额持续晋升,下个月有望冲破 60% 。Edge 浏览器的份额出现下>>>详细阅读
本文标题:Go语言如何实现遗传算法
地址:http://www.17bianji.com/lsqh/38942.html
1/2 1