Skip to content

Instantly share code, notes, and snippets.

@kumanna
Created August 21, 2025 10:16
Show Gist options
  • Select an option

  • Save kumanna/37154d3dc2c9923f64ac76a9715dde71 to your computer and use it in GitHub Desktop.

Select an option

Save kumanna/37154d3dc2c9923f64ac76a9715dde71 to your computer and use it in GitHub Desktop.
import numpy as np
import matplotlib.pyplot as plt
# Minimize f(x) = 2 + (x - 3)^2
def f(x):
return 2 + (x - 3)**2
def fdash(x):
return 2 * (x - 3)
mu = 0.001
x0 = 0.5
epsilon = 1e-10
current_fval = 100000000
x_vals = [x0]
while np.abs(f(x0) - current_fval) > epsilon:
current_fval = f(x0)
x0 = x0 - mu * fdash(x0)
x_vals.append(x0)
print(f(x0))
x = np.arange(0, 6, 0.01)
plt.plot(x, f(x))
x_vals = np.array(x_vals)
plt.plot(x_vals, f(x_vals), 'ko')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment