Page - 179 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 179 -
Text of the Page - 179 -
7.1 BruteForceMethods 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 thatif rootsevaluates toTrue ifroots isnon-empty.This is ageneral test
inPython:if Xevaluates toTrue ifX isnon-emptyorhasa nonzerovalue.
Running theprogramgives theoutput
[0.39270091800495166, 1.1781066425246509, 1.9635022750438742,
2.7489089483136029, 3.534319340895673]
7.1.2 BruteForceOptimization
Numerical Algorithm We realize that xi corresponds to a maximum point if
yi−1 <yi > yi+1. Similarly,xi corresponds to a minimum if yi−1 > yi < yi+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
correspondingyi is a globalmaximumorminimum.
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(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)
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
- Title
- Programming for Computations – Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Volume
- Second Edition
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2020
- Language
- English
- License
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 356
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik