Updated: How do I find the minimum of a function on a closed interval [0,3.5] in Python? So far I found the max and min but am unsure how to filter out the minimum from here.
更新:如何在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)
3 个解决方案
#1
1
Here's a possible solution using sympy:
以下是使用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
is giving you all points where the first derivative is zero, interval_solutions
is constraining those solutions to a closed interval. This should give you some good clues to find minimums and maximums :-)
all_solutions给出了一阶导数为零的所有点,interval_solutions将这些解决方案约束到一个闭区间。这应该给你一些很好的线索,找到最小值和最大值:-)
#2
1
Perhaps something like this
也许是这样的
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])
#3
#1
1
Here's a possible solution using sympy:
以下是使用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
is giving you all points where the first derivative is zero, interval_solutions
is constraining those solutions to a closed interval. This should give you some good clues to find minimums and maximums :-)
all_solutions给出了一阶导数为零的所有点,interval_solutions将这些解决方案约束到一个闭区间。这应该给你一些很好的线索,找到最小值和最大值:-)
#2
1
Perhaps something like this
也许是这样的
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])