|
2 | 2 | import sympy as sp
|
3 | 3 |
|
4 | 4 |
|
5 |
| -def parse_function(user_input): |
| 5 | +def parse_function(user_input: str) -> callable: |
6 | 6 | """
|
7 | 7 | Convert user input from f(x, y) = x^2 + y^2 to a valid Python function.
|
8 | 8 |
|
9 | 9 | Parameters:
|
10 | 10 | user_input (str): The user-defined fitness function in string format.
|
11 | 11 |
|
12 | 12 | Returns:
|
13 |
| - function: A callable fitness function. |
| 13 | + callable: A callable fitness function. |
14 | 14 |
|
15 | 15 | Examples:
|
16 | 16 | >>> parse_function("f(x, y) = x^2 + y^2")
|
@@ -39,19 +39,19 @@ def parse_function(user_input):
|
39 | 39 | return fitness
|
40 | 40 |
|
41 | 41 |
|
42 |
| -def genetic_algorithm(user_fitness_function) -> None: |
| 42 | +def genetic_algorithm(user_fitness_function: callable) -> None: |
43 | 43 | """
|
44 | 44 | Execute the genetic algorithm to optimize the user-defined fitness function.
|
45 | 45 |
|
46 | 46 | Parameters:
|
47 |
| - user_fitness_function (function): The fitness function to be optimized. |
| 47 | + user_fitness_function (callable): The fitness function to be optimized. |
48 | 48 |
|
49 | 49 | Returns:
|
50 | 50 | None
|
51 | 51 |
|
52 | 52 | Example:
|
53 |
| - >>> def user_fitness_function(x): |
54 |
| - ... return x[0]**2 + x[1]**2 |
| 53 | + >>> def user_fitness_function(x, y): |
| 54 | + ... return x**2 + y**2 |
55 | 55 | >>> genetic_algorithm(user_fitness_function) # This will print outputs
|
56 | 56 | """
|
57 | 57 | rng = np.random.default_rng() # New random number generator
|
@@ -121,7 +121,6 @@ def genetic_algorithm(user_fitness_function) -> None:
|
121 | 121 | population = offspring
|
122 | 122 |
|
123 | 123 | print("\n--- Optimization Results ---")
|
124 |
| - print(f"User-defined function: f(x, y) = {user_input.split('=')[1].strip()}") |
125 | 124 | print(f"Best Fitness Value (Minimum): {best_fitness:.6f}")
|
126 | 125 | print(
|
127 | 126 | f"Optimal Solution Found: x = {best_solution[0]:.6f}, "
|
|
0 commit comments