Home > database >  How to find minima and maxima of a function. I am limited to using numpy, sympy and matplotlib
How to find minima and maxima of a function. I am limited to using numpy, sympy and matplotlib

Time:07-01

I am asked to find the maxima and minima of few functions. One of the functions is y = (9x^3) - (7x^2) (3x) 10 The code I could write so far is:

from sympy import*
import matplotlib.pyplot as plt

x = symbols ('x')
f = (9*x**3) - (7*x**2)   (3*x)   10

intervals = np.arange(-5, 7)

df = diff(f, x)
df2 = diff(f, x, 2)

f = lambdify (x, f)
y = f(intervals)

print (intervals)
print (y)

I am new to using these 3 libraries so I dont know how to find the answer using these 3 libraries

CodePudding user response:

SymPy can tell you the derivative and f and can tell you when a function is zero. Since max/min occur when the derivative is zero you can find the zeros and then determine if those values make the 2nd derivative positive or negative, e.g.

>>> from sympy import real_roots
>>> from sympy.abc import x
>>> f = -x**2   1
>>> d1 = f.diff(x)
>>> d2 = d1.diff(x)  # = f.diff(x,2)
>>> extrema = real_roots(d1)
>>> for i in extrema:
...   if d2.subs(x, i).is_positive:
...      print('minimum',i)
...   else:
...      print('maxima',i)

See also here. (If there are no real roots then there are no extrema for real values of x.)

CodePudding user response:

If you want to pass the values of intervals into the formula and then get the minimum value, you can specify the intervals firstly and then just put this array into the formula instead x:

intervals = np.random.permutation(10)
# [8 4 3 0 2 7 9 1 6 5]

f = (9 * intervals ** 3) - (7 * intervals ** 2)   (3 * intervals)   10
# [4194  486  199   10   60 2775 6031   15 1720  975]

f.argmin()    # --> will get index of the minimum value
# 3

f.min()       # --> will get minimum value resulted by the formula
# 10

or if you want to use the formula many times, you can define it as a function and just call it every time you need instead writing it again as:

def formula_1(x):
    return (9 * x ** 3) - (7 * x ** 2)   (3 * x)   10


results = formula_1(intervals)
results.min()
  • Related