7.1 Brute Force Methods
179
def demo():
from numpy import exp, cos
roots = brute_force_root_finder(
lambda x: exp(-x**2)*cos(4*x), 0, 4, 1001)
if roots:
print(roots)
else:
print(’Could not find any roots’)
Note that if roots evaluates to True if roots is non-empty. This is a general test
in Python: if X evaluates to True if X is non-empty or has a nonzero value.
Running the program gives the output
[0.39270091800495166, 1.1781066425246509, 1.9635022750438742,
2.7489089483136029, 3.534319340895673]
7.1.2 Brute Force Optimization
Numerical Algorithm We realize that x i corresponds to a maximum point if
y i−1 < y i > y i+1 . Similarly, x i corresponds to a minimum if y i−1 > y i < y i+1 .
We can do this test for all “inner” points i = 1, . . . , n − 1 to find all local minima
and maxima. In addition, we need to add an end point, i = 0 or i = n, if the
corresponding y i is a global maximum or minimum.
Implementation The algorithm above can be translated to the following Python
function (file brute_force_optimizer.py):
def brute_force_optimizer(f, a, b, n):
from numpy import linspace
x = linspace(a, b, n)
y = f(x)
# Let maxima and minima hold the indices corresponding
# to (local) maxima and minima points
minima = []
maxima = []
for i in range(1, n-1):
if y[i-1] < y[i] > y[i+1]:
maxima.append(i)
if y[i-1] > y[i] < y[i+1]:
minima.append(i)
# What about the end points?
y_max_inner = max([y[i] for i in maxima])
y_min_inner = min([y[i] for i in minima])
if y[0] > y_max_inner:
maxima.append(0)
if y[len(x)-1] > y_max_inner:
maxima.append(len(x)-1)
if y[0] < y_min_inner:
minima.append(0)
if y[len(x)-1] < y_min_inner:
minima.append(len(x)-1)
Précédent

- 200/350

Suivant