更新:如何在 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)
Run Code Online (Sandbox Code Playgroud)
自此PR以来,您应该能够执行以下操作:
from sympy.calculus.util import *
f = (x**3 / 3) - (2 * x**2) - 3 * x + 1
ivl = Interval(0,3)
print(minimum(f, x, ivl))
print(maximum(f, x, ivl))
print(stationary_points(f, x, ivl))
Run Code Online (Sandbox Code Playgroud)
也许是这样的
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])
Run Code Online (Sandbox Code Playgroud)
这是使用 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)
Run Code Online (Sandbox Code Playgroud)
all_solutions给出一阶导数为零的所有点,interval_solutions将这些解限制在闭区间。这应该会给你一些很好的线索来找到最小值和最大值:-)
| 归档时间: |
|
| 查看次数: |
10959 次 |
| 最近记录: |