Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the minimum of a function on a closed interval with Python

Tags:

python

sympy

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.

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)
like image 217
Tashay Green Avatar asked Jun 09 '26 06:06

Tashay Green


2 Answers

Since this PR you should be able to do the following:

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))
like image 58
smichr Avatar answered Jun 11 '26 20:06

smichr


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])
like image 42
asmeurer Avatar answered Jun 11 '26 18:06

asmeurer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!