更新:如何在Python中的闭区间[0,3.5]找到函数的最小值?到目前为止,我发现了最大值和最小值,但我不确定如何从这里过滤出最小值。
import sympy as sp
x = sp.symbols('x')
f = (x**3 / 3) - (2 * x**2) + (3 * x) + 1
fprime = f.diff(x)
all_solutions = [(xx, f.subs(x, xx)) for xx in sp.solve(fprime, x)]
print (all_solutions)
答案 0 :(得分:1)
以下是使用sympy的可能解决方案:
import sympy as sp
x = sp.Symbol('x', real=True)
f = (x**3 / 3) - (2 * x**2) - 3 * x + 1
#f = 3 * x**4 - 4 * x**3 - 12 * x**2 + 3
fprime = f.diff(x)
all_solutions = [(xx, f.subs(x, xx)) for xx in sp.solve(fprime, x)]
interval = [0, 3.5]
interval_solutions = filter(
lambda x: x[0] >= interval[0] and x[0] <= interval[1], all_solutions)
print(all_solutions)
print(interval_solutions)
all_solutions
为您提供了一阶导数为零的所有点,interval_solutions
将这些解决方案限制在一个封闭的时间间隔内。这应该给你一些很好的线索来找到最小值和最大值: - )
答案 1 :(得分:1)
也许是这样的
from sympy import solveset, symbols, Interval, Min
x = symbols('x')
lower_bound = 0
upper_bound = 3.5
function = (x**3/3) - (2*x**2) - 3*x + 1
zeros = solveset(function, x, domain=Interval(lower_bound, upper_bound))
assert zeros.is_FiniteSet # If there are infinite solutions the next line will hang.
ans = Min(function.subs(x, lower_bound), function.subs(x, upper_bound), *[function.subs(x, i) for i in zeros])
答案 2 :(得分:1)
自this PR起,您应该可以执行以下操作:
from sympy.calculus.util import *
f = (x**3 / 3) - (2 * x**2) - 3 * x + 1
ivl = Interval(0,3)
print(minimum(f, ivl))
print(maximum(f, ivl))
print(stationary_points(f, ivl))
答案 3 :(得分:0)