from math import sin
import matplotlib.pyplot as plt
from scipy.optimize import minimize

min_x, max_x, points = -8.0, 10.0, 1000

trace = []  # remember for which x, f(x) was computed

def f(x):
    value = x ** 2 + 10 * sin(x)
    trace.append((x, value))
    return value

X = [min_x + i * (max_x - min_x) / (points - 1) for i in range(points)]
Y = [f(x) for x in X]

plt.style.use('dark_background')
plt.plot(X, Y, 'w-')
for start, color in [(8, 'red'), (-6, 'yellow')]:
    trace = []
    
    solution = minimize(f, [start], method='nelder-mead')

    x, y = solution.x[0], solution.fun
    plt.plot(*zip(*trace), '.-', c=color,
             label=f'start {start:.1f}')
    plt.text(x, -23, f'{x:.3f}', ha='center', c=color)
    plt.plot([x, x], [-18, y], '--', c=color)
    plt.plot(*trace[0], 'o', c=color)
plt.xticks(range(-5, 15, 5))
plt.yticks(range(-25, 100, 25))
plt.minorticks_on()
plt.legend()
plt.show()
