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

时间:2018-11-25 19:27:03

标签: python numpy math

我有一个多项式(例如x ^ 3-3x ^ 2 + 4),我想使用Python计算某个范围(例如[-1,1]之间)的最小值。我以为使用NumPy和/或类似的库会很容易,但是,我无法使用Google找到解决方案。

我可以使用Python计算特定范围内的多项式分数的最小值(例如(x ^ 2 -1)/(x + 3))吗?

3 个答案:

答案 0 :(得分:2)

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

如果要设置特定范围,则需要使用可以支持该范围的methods之一(有关详细信息,请参见链接的文档页面中的methods)。

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]

答案 1 :(得分: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 :(得分:-2)

我建议从numpy中安排功能。

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