優化示例(布倫特)
布倫特的方法是其他尋根演算法的更復雜的演算法組合; 但是,得到的圖形與黃金方法生成的圖形沒有太大差別。
import numpy as np
import scipy.optimize as opt
from scipy import special
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 500)
y = special.j0(x)
# j0 is the Bessel function of 1st kind, 0th order
minimize_result = opt.minimize_scalar(special.j0, method='brent')
the_answer = minimize_result['x']
minimized_value = minimize_result['fun']
# Note: minimize_result is a dictionary with several fields describing the optimizer,
# whether it was successful, etc. The value of x that gives us our minimum is accessed
# with the key 'x'. The value of j0 at that x value is accessed with the key 'fun'.
plt.plot(x, y)
plt.axvline(the_answer, linestyle='--', color='k')
plt.show()
print("The function's minimum occurs at x = {0} and y = {1}".format(the_answer, minimized_value))
結果圖
http://i.stack.imgur.com/ZZgZa.jpg
輸出:
The function's minimum occurs at x = 3.8317059554863437 and y = -0.4027593957025531