VincentN
VincentN

Reputation: 111

Find global maximum of an equation using python

I am trying to write some codes to find the global maximum of an equation, e.g. f = -x**4.

Here is what I have got at the moment.

import sympy
x = sympy.symbols('x')
f = -x**4
df = sympy.diff(f,x)
ans = sympy.solve(df,x)

Then I am stuck. How should I substitute ans back into f, and how would I know if that would be the maximum, but not the minimum or a saddle point?

Upvotes: 1

Views: 2718

Answers (1)

Chris du Plessis
Chris du Plessis

Reputation: 1370

If you are just looking for the global maximum and nothing else, then there is already a function for that. See the following:

from sympy import *

x = symbols('x')
f = -x**4
print(maximum(f, x))  # 0

If you want more information such as the x value that gives that max or maybe local maxima, you'll have to do more manual work. In the following, I find the critical values as you have done above and then I show the values as those critical points.

diff_f = diff(f, x)
critical_points = solve(diff_f, x)
print(critical_points)  # x values
for point in critical_points:
    print(f.subs(x, point))  # f(x) values

This can be extended to include the second derivative test as follows:

d_f = diff(f, x)
dd_f = diff(f, x, 2)
critical_points = solve(d_f, x)
for point in critical_points:
    if dd_f.subs(x, point) < 0:
        print(f"Local maximum at x={point} with f({point})={f.subs(x, point)}")
    elif dd_f.subs(x, point) > 0:
        print(f"Local minimum at x={point} with f({point})={f.subs(x, point)}")
    else:
        print(f"Inconclusive at x={point} with f({point})={f.subs(x, point)}")

To find the global max, you would need to take all your critical points and evaluate the function at those points. Then pick the max from those.

outputs = [f.subs(x, point) for point in critical_points]
optimal_x = [point for point in critical_points if f.subs(x, point) == max(outputs)]

print(f"The values x={optimal_x} all produce a global max at f(x)={max(outputs)}")

The above should work for most elementary functions. Apologies for the inconsistent naming of variables.

If you are struggling with simple things like substitution, I suggest going through the docs for an hour or two.

Upvotes: 3

Related Questions