Skip to content

Commit

Permalink
Merge pull request #47 from spakin/master
Browse files Browse the repository at this point in the history
🐛 CrossUniformFloat64 should preserve total values
  • Loading branch information
MaxHalford authored Nov 14, 2020
2 parents ba4b995 + f37a515 commit 0c1a5a9
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
6 changes: 4 additions & 2 deletions crossover.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ import (
func CrossUniformFloat64(p1 []float64, p2 []float64, rng *rand.Rand) {
for i := range p1 {
var p = rng.Float64()
p1[i] = p*p1[i] + (1-p)*p2[i]
p2[i] = (1-p)*p1[i] + p*p2[i]
var o1 = p*p1[i] + (1-p)*p2[i]
var o2 = (1-p)*p1[i] + p*p2[i]
p1[i] = o1
p2[i] = o2
}
}

Expand Down
8 changes: 8 additions & 0 deletions crossover_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@ func TestCrossUniformFloat64(t *testing.T) {
t.Error("New values are not contained in hyper-rectangle")
}
}
// Check that each parent sum equals the offspring sum
for i := 0; i < len(p1); i++ {
pSum := p1[i] + p2[i]
oSum := o1[i] + o2[i]
if math.Abs(pSum-oSum) > 1e-14 {
t.Errorf("Total value is not preserved from parents to offsprings (%v vs. %v)", pSum, oSum)
}
}
}

func TestGNX(t *testing.T) {
Expand Down
2 changes: 1 addition & 1 deletion ga_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ func TestGALog(t *testing.T) {
ga.init(NewVector)
ga.evolve()
var expected = "pop_id=QrZ min=-21.342844 max=16.086140 avg=-2.554992 std=11.673396\n" +
"pop_id=QrZ min=-29.052226 max=10.630133 avg=-11.885364 std=8.266295\n"
"pop_id=QrZ min=-29.052226 max=10.630133 avg=-12.575381 std=8.436837\n"
if s := b.String(); s != expected {
t.Errorf("Expected %s, got %s", expected, s)
}
Expand Down

0 comments on commit 0c1a5a9

Please sign in to comment.