How to Find the Global Maximum of (1‑x³)·sin(3x) Using Python and SciPy
This article demonstrates how to locate the global maximum of the function f(x) = (1‑x³)·sin(3x) by visualizing it with Matplotlib, applying SciPy’s optimization tools such as fminbound, and comparing deterministic methods with random sampling, highlighting the pitfalls of local optima.
1 Find the Global Optimum
1.1 Problem
Find the maximum value of the function f(x) = (1 - x³)·sin(3x).
1.2 Solution
To aid understanding, first plot the function.
<code>import numpy as np
from matplotlib.pyplot import rc, plot, show, savefig
from scipy.optimize import fminbound, fmin
rc('font', size=16)
fx = lambda x: (1 - x**3) * np.sin(3 * x)
x0 = np.linspace(-2 * np.pi, 2 * np.pi, 100)
y0 = fx(x0)
plot(x0, y0)
show()
</code>The plot shows the function reaches its maximum near x = -6 and x = 6, with a value close to 195. Using SciPy’s fminbound to solve yields:
<code>from scipy.optimize import fminbound
xm2 = fmin(lambda x: -fx(x), -2 * np.pi)
ym2 = fx(xm2)
print(xm2, ym2, '\n--------------')
</code>Result:
-3.7505026680508093 52.00462222535155This only finds a local maximum at x ≈ -3.75 with value ≈ 52, which is incorrect because fminbound can become trapped in local extrema, a common difficulty for many optimization algorithms.
Using a random sampling approach—generating 100 random points in the interval—produces a maximum around 194, much closer to the true global maximum.
<code>x = np.random.uniform(-2 * np.pi, 2 * np.pi, 100)
y = fx(x)
ym = y.max()
xm = x[y == ym]
print(xm, ym)
</code>Result:
[-5.81863236] 194.9001725139532Model Perspective
Insights, knowledge, and enjoyment from a mathematical modeling researcher and educator. Hosted by Haihua Wang, a modeling instructor and author of "Clever Use of Chat for Mathematical Modeling", "Modeling: The Mathematics of Thinking", "Mathematical Modeling Practice: A Hands‑On Guide to Competitions", and co‑author of "Mathematical Modeling: Teaching Design and Cases".
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.