我有一个多项式(例如,x ^ 3-3x ^ 2 + 4),我想使用Python在范围内(例如,在[-1,1]之间)计算其最小值。我认为使用NumPy和/或类似的库很容易找到解决方案,但是在Google上我没有找到解决方案。
我能否使用Python在特定范围内计算多项式分数(例如,(x ^ 2-1)/(x + 3))的最小值?
我能否使用Python在特定范围内计算多项式分数(例如,(x ^ 2-1)/(x + 3))的最小值?
scipy.optimize
中的 minimize
:from scipy.optimize import minimize
def fun(x):
return x**3 - 3*x**2 + 4
fit = minimize(fun, x0=10)
print(fit.x)
输出:
[2.00000006]
方法
之一(有关详细信息,请参见链接文档页面中的方法
)。from scipy.optimize import minimize
def fun(x):
return x**3 - 3*x**2 + 4
fit = minimize(fun, x0=1, method='L-BFGS-B', bounds=((1,3),))
print(fit.x)
输出:
[1.99999989]
如果您不关心多项式的分数部分,可以使用numpy.polynomial
:
def poly_min(poly, x_low, x_high):
# get local minima and maxima
x_minmax = p.deriv().roots()
# ignore the ones out of the range
in_range = True
if x_low is not None:
in_range &= x_low <= x_minmax
if x_high is not None:
in_range &= x_minmax < x_high
x_minmax = x_minmax[in_range]
# append start and end points, if needed
x_candidates = (x_minmax,)
if x_low is not None:
x_candidates = (x_low,) + x_candidates
if x_high is not None:
x_candidates = x_candidates + (x_high,)
# find the lowest of all possible candidates
x_candidates = np.concatenate(x_candidates)
return p(x_candidates).min()
from numpy.polynomial.polynomial import Polynomial
p = Polynomial([4, 1, -3]) # 4 + x^3 - 3x^2
poly_min(p, -1, 1)
我推荐使用numpy中的arrange函数。
import numpy as np
def function(x):
return x**3 - 3*x**2 + 4
def search_min(set, end, freq):
section = np.arange(set, end, freq)
arr = []
for i in section:
arr.append(function(i))
## This is check mid-process
## If this is verified you can delete this sentence
for j in arr:
print(j)
print()
###################################################
return min(arr)
print('result : ',end='')
print(search_min(-1, 1, 0.1))
输出:
## mid-process
0.0
0.8409999999999997
1.5679999999999996
2.187
2.7039999999999997
3.1249999999999996
3.4559999999999995
3.703
3.872
3.969
4.0
3.971
3.8880000000000003
3.757
3.5840000000000005
3.375000000000001
3.136000000000001
2.8730000000000007
2.592000000000001
2.2990000000000017
0.0 ## result val