Skip to content

Commit 0697e97

Browse files
committed
Update genetic_algorithm_optimization.py
1 parent 7f8befa commit 0697e97

File tree

1 file changed

+10
-9
lines changed

1 file changed

+10
-9
lines changed

genetic_algorithm/genetic_algorithm_optimization.py

+10-9
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,14 @@ def __init__(
2929
self.mutation_prob = mutation_prob
3030
self.num_variables = len(bounds)
3131

32+
# Initialize the random number generator
33+
self.rng = np.random.default_rng()
34+
3235
def initialize_population(self):
3336
"""
3437
Initialize a population of random solutions within the bounds.
3538
"""
36-
return np.random.uniform(
39+
return self.rng.uniform(
3740
low=self.bounds[:, 0],
3841
high=self.bounds[:, 1],
3942
size=(self.population_size, self.num_variables),
@@ -50,7 +53,7 @@ def select_parents(self, population, fitness_scores):
5053
"""
5154
Select parents using tournament selection.
5255
"""
53-
selected_indices = np.random.choice(
56+
selected_indices = self.rng.choice(
5457
range(self.population_size), size=2, replace=False
5558
)
5659
return population[selected_indices[np.argmin(fitness_scores[selected_indices])]]
@@ -63,10 +66,8 @@ def crossover(self, parent1, parent2):
6366
if self.num_variables == 1:
6467
return parent1, parent2 # No crossover needed for single-variable functions
6568

66-
if np.random.rand() < self.crossover_prob:
67-
point = np.random.randint(
68-
1, self.num_variables
69-
) # Updated to handle the edge case
69+
if self.rng.random() < self.crossover_prob:
70+
point = self.rng.integers(1, self.num_variables) # Updated to handle edge case
7071
child1 = np.concatenate((parent1[:point], parent2[point:]))
7172
child2 = np.concatenate((parent2[:point], parent1[point:]))
7273
return child1, child2
@@ -76,9 +77,9 @@ def mutate(self, individual):
7677
"""
7778
Apply mutation to an individual with a given mutation probability.
7879
"""
79-
if np.random.rand() < self.mutation_prob:
80-
index = np.random.randint(0, self.num_variables)
81-
individual[index] = np.random.uniform(
80+
if self.rng.random() < self.mutation_prob:
81+
index = self.rng.integers(0, self.num_variables)
82+
individual[index] = self.rng.uniform(
8283
self.bounds[index, 0], self.bounds[index, 1]
8384
)
8485
return individual

0 commit comments

Comments
 (0)