这里用到的是scipy.optimize的fmin和fminbound
import numpy as np from matplotlib import pyplot as plt from scipy.optimize import fmin,fminbound def f(x): return x**2+10*np.sin(x)+1 x=np.linspace(-10,10,num=500) min1=fmin(f,3)#求3附近的极小值 min2=fmin(f,0)#求0附近的极小值 min_global=fminbound(f,-10,10)#这个区域的最小值 print(min1) print(min2) print(min_global) plt.plot(x,f(x)) plt.show()
输出:
Optimization terminated successfully. Current function value: 9.315586 Iterations: 15 Function evaluations: 30 Optimization terminated successfully. Current function value: -6.945823 Iterations: 26 Function evaluations: 52 [3.83745117] [-1.3064375] -1.306440096615395
以上这篇python实现函数极小值就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。