1
1
import numpy as np
2
-
2
+ import sympy as sp
3
3
4
4
def parse_function (user_input ):
5
5
"""
@@ -23,16 +23,18 @@ def parse_function(user_input):
23
23
else :
24
24
raise ValueError ("Invalid function format. Please use 'f(x, y) = ...'." )
25
25
26
- # Replace variable names and power operator
27
- expression = expression .replace ("^" , "**" ).replace ("x" , "x[0]" ).replace ("y" , "x[1]" )
26
+ # Create sympy symbols for x and y
27
+ x , y = sp .symbols ('x y' )
28
+
29
+ # Replace power operator and parse the expression
30
+ expression = expression .replace ('^' , '**' )
31
+ func_expr = eval (expression ) # Safe to use as we're controlling the input format
28
32
29
- # Create the fitness function
30
- def fitness (x ):
31
- return eval (expression )
33
+ # Create the fitness function using sympy
34
+ fitness = sp .lambdify ((x , y ), func_expr )
32
35
33
36
return fitness
34
37
35
-
36
38
def genetic_algorithm (user_fitness_function ) -> None :
37
39
"""
38
40
Execute the genetic algorithm to optimize the user-defined fitness function.
@@ -63,7 +65,8 @@ def genetic_algorithm(user_fitness_function) -> None:
63
65
fitness_values = []
64
66
65
67
for individual in population :
66
- fitness_value = user_fitness_function (individual )
68
+ # Call the fitness function with individual x and y
69
+ fitness_value = user_fitness_function (individual [0 ], individual [1 ])
67
70
68
71
if fitness_value is None or not isinstance (fitness_value , (int , float )):
69
72
print (
@@ -90,7 +93,7 @@ def genetic_algorithm(user_fitness_function) -> None:
90
93
91
94
# Selection
92
95
selected_parents = population [rng .choice (population_size , population_size )]
93
-
96
+
94
97
# Crossover
95
98
offspring = []
96
99
for i in range (0 , population_size - 1 , 2 ): # Ensure even number of parents
@@ -127,7 +130,6 @@ def genetic_algorithm(user_fitness_function) -> None:
127
130
f"{ best_solution [1 ]:.6f} ) = { function_value :.6f} "
128
131
)
129
132
130
-
131
133
if __name__ == "__main__" :
132
134
user_input = input (
133
135
"Please enter your fitness function in the format 'f(x, y) = ...':\n "
0 commit comments