@@ -29,11 +29,14 @@ def __init__(
29
29
self .mutation_prob = mutation_prob
30
30
self .num_variables = len (bounds )
31
31
32
+ # Initialize the random number generator
33
+ self .rng = np .random .default_rng ()
34
+
32
35
def initialize_population (self ):
33
36
"""
34
37
Initialize a population of random solutions within the bounds.
35
38
"""
36
- return np . random .uniform (
39
+ return self . rng .uniform (
37
40
low = self .bounds [:, 0 ],
38
41
high = self .bounds [:, 1 ],
39
42
size = (self .population_size , self .num_variables ),
@@ -50,7 +53,7 @@ def select_parents(self, population, fitness_scores):
50
53
"""
51
54
Select parents using tournament selection.
52
55
"""
53
- selected_indices = np . random .choice (
56
+ selected_indices = self . rng .choice (
54
57
range (self .population_size ), size = 2 , replace = False
55
58
)
56
59
return population [selected_indices [np .argmin (fitness_scores [selected_indices ])]]
@@ -63,10 +66,8 @@ def crossover(self, parent1, parent2):
63
66
if self .num_variables == 1 :
64
67
return parent1 , parent2 # No crossover needed for single-variable functions
65
68
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
70
71
child1 = np .concatenate ((parent1 [:point ], parent2 [point :]))
71
72
child2 = np .concatenate ((parent2 [:point ], parent1 [point :]))
72
73
return child1 , child2
@@ -76,9 +77,9 @@ def mutate(self, individual):
76
77
"""
77
78
Apply mutation to an individual with a given mutation probability.
78
79
"""
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 (
82
83
self .bounds [index , 0 ], self .bounds [index , 1 ]
83
84
)
84
85
return individual
0 commit comments