Skip to content

Commit 07e7915

Browse files
fix: respect a zero mutation probability (#15)
Mutation now uses an explicit `is not None` check so a configured mutation probability of 0.0 is honoured instead of falling back to the default (the previous falsy check treated 0.0 as unset). Adds a regression test for the zero-probability case.
1 parent 4707bb0 commit 07e7915

2 files changed

Lines changed: 8 additions & 1 deletion

File tree

genetic_algorithm/chromosome.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ def __probability_mutation(self, probability):
173173

174174
def mutate(self, method="probability_mutation", mutation_prob=None):
175175
if method == "probability_mutation":
176-
mutation_prob = mutation_prob if mutation_prob else 1 / len(self.data)
176+
mutation_prob = mutation_prob if mutation_prob is not None else 1 / len(self.data)
177177
return self.__probability_mutation(mutation_prob)
178178
elif method == "twors":
179179
return self.__twors_mutate()

tests/test_chromosome.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,13 @@ def test_mutation_methods_preserve_length(method):
5555
assert len(out) == 6
5656

5757

58+
def test_probability_mutation_allows_zero_probability():
59+
random.seed(1)
60+
c = Chromosome(3, [(0, 0)] * 3, data=[1.0, 2.0, 3.0])
61+
out = c.mutate(method="probability_mutation", mutation_prob=0)
62+
assert out == [1.0, 2.0, 3.0]
63+
64+
5865
def test_permutation_mutations_preserve_multiset():
5966
c = Chromosome(5, [(0, 100)] * 5, data=[1.0, 2.0, 3.0, 4.0, 5.0])
6067
random.seed(2)

0 commit comments

Comments
 (0)