Page - 189 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python
Image of the Page - 189 -
Text of the Page - 189 -
6.1 BruteForceMethods 189
Note thatif rootsevaluates toTrue ifroots is non-empty. This is a general
test inPython:if Xevaluates toTrue ifX isnon-emptyorhasanonzerovalue.
6.1.2 BruteForceOptimization
Numerical algorithm We realize that xi corresponds to a maximum point if
yi 1 < yi > yiC1. Similarly,xi corresponds to aminimumifyi 1 > yi < yiC1.
Wecando this test for all βinnerβ points i D 1;:: :;n 1 tofindall localminima
andmaxima. In addition, we need to add an end point, i D 0 or i D n, if the
correspondingyi is aglobalmaximumorminimum.
Implementation The algorithm above can be translated to the following Python
function (filebrute_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(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)
# Return x and y values
return [(x[i], y[i]) for i in minima], \
[(x[i], y[i]) for i in maxima]
Themax andmin functions are standardPython functions forfinding themaxi-
mumandminimumelementofa listoranobject thatonecan iterateoverwithafor
loop.
back to the
book Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python"
Programming for Computations β Python
A Gentle Introduction to Numerical Simulations with Python
- Title
- Programming for Computations β Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2016
- Language
- English
- License
- CC BY-NC 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 248
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik