def f(x):
return x**2
from scipy.optimize import minimize_scalar
res = minimize_scalar(f)
print("最大值:", res.fun)
print("参数值:", res.x)
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return x**2
x = np.linspace(-1, 1, 1000)
y = f(x)
res = minimize_scalar(f)
plt.plot(x, y)
plt.scatter(res.x, res.fun, s=100, c='r')
plt.text(res.x, res.fun+1, 'max: {:.2f}'.format(res.fun), ha='center', fontsize=14)
plt.title('x^2 Function')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize_scalar
def f(x):
return np.sin(x)
x = np.linspace(-5, 5, 1000)
y = f(x)
res = minimize_scalar(lambda x: -f(x))
plt.plot(x, y)
plt.scatter(res.x, res.fun, s=100, c='r')
plt.text(res.x, res.fun-0.5, 'max: {:.2f}'.format(-res.fun), ha='center', fontsize=14)
plt.title('sin Function')
plt.show()
标签: 网购