如何使用Python计算多项式在特定范围内的最小值?

4
我有一个多项式(例如,x ^ 3-3x ^ 2 + 4),我想使用Python在范围内(例如,在[-1,1]之间)计算其最小值。我认为使用NumPy和/或类似的库很容易找到解决方案,但是在Google上我没有找到解决方案。
我能否使用Python在特定范围内计算多项式分数(例如,(x ^ 2-1)/(x + 3))的最小值?

1
你可能正在寻找某种优化方法。也许是这个:https://docs.scipy.org/doc/scipy-1.1.0/reference/tutorial/optimize.html - Anton vBR
3个回答

6
使用 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]

我想知道是否有一种直接的方法来类似地找到一个负二次方程的最大值。从scipy.optimize中,我看不到直接的方法。我可以应用np.polyder(quad_eq)并在斜率为0时得到值,然后做类似于np.polyval(quad_eq, x=slope is 0)的事情。但我认为应该有更好的方法来做这件事。对此有何评论? - AGH

0

如果您不关心多项式的分数部分,可以使用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)

-2

我推荐使用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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接