Documentation
¶
Overview ¶
Package ga implements the genetic algorithm.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Entity ¶
type Entity interface {
// Fitness represents the fitness of this entity.
Fitness() float64
// Mutate is the mutation operation.
Mutate() Entity
// Cross is the crossover operation.
Cross(float64, Entity) Entity
}
Entity represents an entity of GA model.
type GA ¶
type GA struct {
// contains filtered or unexported fields
}
GA represents the GA model.
Example ¶
package main
import (
"fmt"
"math/rand"
"gitee.com/ofunc/ga"
)
// V is an entity of GA model.
type V struct {
X, Y float64
}
// Fitness is the fitness of this entity.
// The problem to be solved is:
//
// max = 2x + 3y
// 4x + 3y <= 10
// 3x + 5y <= 12
// x, y >= 0
func (v V) Fitness() float64 {
s, f := 0.0, 2*v.X+3*v.Y
if d := (4*v.X+3*v.Y)/10 - 1; d > 0 {
s += d
}
if d := (3*v.X+5*v.Y)/12 - 1; d > 0 {
s += d
}
if s > 0 {
return -s
} else {
return f
}
}
// Mutate is the mutation operation.
func (v V) Mutate() ga.Entity {
return V{10 * rand.Float64(), 10 * rand.Float64()}
}
// Crossover is the crossover operation.
func (v V) Cross(w float64, e ga.Entity) ga.Entity {
a := e.(V)
return V{w*v.X + (1-w)*a.X, w*v.Y + (1-w)*a.Y}
}
func main() {
m := ga.New(1000, V{}.Mutate)
e, f, ok := m.Evolve(30, 10000)
fmt.Println("fitness: ", f)
fmt.Println("elite:", e)
fmt.Println("isok:", ok)
}
Click to show internal directories.
Click to hide internal directories.