Tashay Green
Tashay Green

Reputation: 105

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

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)

Upvotes: 8

Views: 12199

Answers (4)

smichr
smichr

Reputation: 19125

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))

Upvotes: 9

asmeurer
asmeurer

Reputation: 91610

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])

Upvotes: 6

Bill Bell
Bill Bell

Reputation: 21663

Interactive Python session

The f.subs commands show two ways of displaying the value of the given function at x=3.5, the first as a rational approximation, the second as the exact fraction.

Graph produced by plot command

Upvotes: 0

BPL
BPL

Reputation: 9863

Here's a possible solution using 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 :-)

Upvotes: 4

Related Questions