From 1abb63df0d404ceecfc754ae23a9819cca46c6d9 Mon Sep 17 00:00:00 2001 From: SuramyaRanjan <154046510+SuramyaRanjan@users.noreply.github.com> Date: Sat, 25 Oct 2025 21:33:16 +0530 Subject: [PATCH] Add Hill Climbing algorithm in HillClimp.py Implement a hill climbing algorithm to maximize a quadratic function. --- HillClimp.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 HillClimp.py diff --git a/HillClimp.py b/HillClimp.py new file mode 100644 index 0000000..91d10b7 --- /dev/null +++ b/HillClimp.py @@ -0,0 +1,30 @@ +import numpy as np + +# Define the objective function (for example: maximize f(x) = -x^2 + 5) +def objective(x): + return -x[0] ** 2 + 5 + +# Generate neighboring solutions +def generate_neighbors(x, step_size=0.1): + return [np.array([x[0] + step_size]), np.array([x[0] - step_size])] + +# Hill Climbing Algorithm +def hill_climbing(objective, initial, n_iterations=100, step_size=0.1): + current = np.array([initial]) + current_eval = objective(current) + for i in range(n_iterations): + neighbors = generate_neighbors(current, step_size) + neighbor_evals = [objective(n) for n in neighbors] + best_idx = np.argmax(neighbor_evals) + if neighbor_evals[best_idx] > current_eval: + current = neighbors[best_idx] + current_eval = neighbor_evals[best_idx] + print(f"Step {i+1}: x = {current[0]:.4f}, f(x) = {current_eval:.4f}") + else: + print("No better neighbors found. Algorithm converged.") + break + return current, current_eval + +# Example usage +final_position, final_value = hill_climbing(objective, initial=2.0) +print("Best solution:", final_position, "Optimal value:", final_value)