Physics With Excel and Python
Physics With Excel and Python
Based on the German language edition: Physik mit Excel und Visual Basic by Dieter Mergel,
© 2017 2017. Published by Springer-Spectrum. All Rights Reserved, and extended with Python solutions.
© Springer Nature Switzerland AG 2022
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of
the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology
now known or hereafter developed.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication
does not imply, even in the absence of a specific statement, that such names are exempt from the relevant
protective laws and regulations and therefore free for general use.
The publisher, the authors and the editors are safe to assume that the advice and information in this book
are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or
the editors give a warranty, expressed or implied, with respect to the material contained herein or for any
errors or omissions that may have been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.
This Springer imprint is published by the registered company Springer Nature Switzerland AG
The registered company address is: Gewerbestrasse 11, 6330 Cham, Switzerland
Preface
1 Dieter Mergel, Physik mit Excel und Visual Basic Grundlagen, Beispiele und Aufgaben, Springer
Spektrum (2017), https://doi.org/10.1007/978-3-642-37857-7.
2 Dieter Mergel, Physik lernen mit Excel und Visual Basic, Anwendungen auf Teilchen, Wellen,
v
vi Preface
classes at the university and may also be a good start for students who later choose
to specialize in computational physics.
Our approach is intended to make the student fit for a computer-oriented world,
be it for spreadsheet calculations in business, scientific computing in research, or
mathematics and physics teaching in high school. We take into account that not all
students have the same attitude towards programming; some have to be encouraged
to venture into a new world, whereas others have to be cautioned not to rush into
blind programming.
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 A Two-Track Didactical Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 What Can You Expect? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 What Do You Need? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Tim, Alac, and Mag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.5 Didactic Concept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.6 Subject Matter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.7 Getting Started with Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.7.1 Start Menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.7.2 Spreadsheet Presentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.8 Getting Started with Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.9 Skills to Be Trained . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2 Data Structures, Excel and Python Basics . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.1 Introduction: Named Ranges in Excel, Arrays in Numpy . . . . . . . 15
2.2 Characteristics of a Parabola . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.2.1 Different Definitions of a Parabola . . . . . . . . . . . . . . . . . . . . 17
2.2.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 19
2.3 Basic Exercise in Spreadsheet Calculation . . . . . . . . . . . . . . . . . . . . . 19
2.3.1 Cell Addressing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.3.2 Graphical Representation of a Function . . . . . . . . . . . . . . . 22
2.3.3 Smart Legends in Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.3.4 Scroll Bars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.3.5 Summary: Cell References and Name Manager . . . . . . . 26
2.3.6 What Have We Learned so Far, and How
to Proceed Further? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.3.7 Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.4 Python and NumPy Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.4.1 Basic Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.4.2 Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
2.4.3 Python Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2.4.4 Numpy Constructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
vii
viii Contents
9.6.2
Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 393
9.6.3
Spreadsheet Calculation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
9.6.4
Python, Internally and Externally Consistent Error
of the Combined Result . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
9.7 Propagation of Standard Deviations . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
9.7.1 Rules for Propagation of Standard Deviations . . . . . . . . . 397
9.7.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 402
9.7.3 Spreadsheet Calculation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402
9.7.4 Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
9.8 Propagation of Confidence Intervals . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
9.8.1 From Variance to Confidence . . . . . . . . . . . . . . . . . . . . . . . . . 407
9.8.2 Sum and Product of Two Measurands . . . . . . . . . . . . . . . . . 408
9.9 Mass of a Thin Film on a Glass Substrate . . . . . . . . . . . . . . . . . . . . . 409
9.9.1 Instructions for Use for Accurate Measurements
and Their Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
9.9.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 413
9.9.3 Spreadsheet Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
9.9.4 Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
9.10 Questions and Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
10 Fitting Trend Curves to Data Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
10.1 Introduction: Linear and Nonlinear Regression . . . . . . . . . . . . . . . . . 419
10.1.1 Straight Line Through Data Points by Sight . . . . . . . . . . . 419
10.1.2 Multilinear Regression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
10.1.3 Nonlinear Regression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
10.1.4 Coefficient of Determination R2 . . . . . . . . . . . . . . . . . . . . . . . 422
10.1.5 C-spec Error with Iterative t Adaptation . . . . . . . . . . . . . . . 423
10.2 Linear Trend Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
10.2.1 Creating Data Points and Evaluating Them . . . . . . . . . . . . 424
10.2.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 426
10.2.3 Spreadsheet Calculation with Linest . . . . . . . . . . . . . . . . . . . 426
10.2.4 Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
10.3 Fitting a Polynomial Trend Line to Data Points
with Multilinear Regression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
10.3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
10.3.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 435
10.3.3 Spreadsheet Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
10.3.4 Python Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
10.4 Exponential Trend Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
10.4.1 Exponential and Logarithm . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
10.4.2 Exponential or Polynomial? . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
10.4.3 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 445
10.4.4 Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
10.4.5 Spreadsheet Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
Contents xv
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
About the Author
Dieter Mergel studied physics in Göttingen, obtained his doctorate at the Techni-
cal University of Clausthal in the field of solid-state physics, and worked 11 years
in the Philips Research Laboratories Hamburg/Aachen on automatic speech recog-
nition and optical data storage. Since 1993, he is Professor of Technical Physics
at the University of Duisburg-Essen. His professional activities include research
in the field of solid-state layers and lectures for students in teaching and medical
professions.
xvii
Introduction
1
History
The exercises in this book arise from a German textbook that emerged from courses
for prospective teachers and students of Technical Physics at the University of
Duisburg-Essen with the intention to prepare the students for a computerized world.
The participants in the courses had already been studying physics for at least one
year. However, the explanations of the exercises are so explicit that they should also
be suitable for beginners.
Said courses are based on excel and Visual Basic (VBA). The current English
version includes Python from the very beginning so as to make it more generally
useful for students who later choose to dive deeper into Scientific Computation.
Exercises
The subject matter is presented in nine chapters as a series of exercises. Every exercise
consists of three steps:
1. The physical concept is introduced with mathematical equations and diagrams.
2. An adequate data structure is set up independent of the implementation in a
particular programming platform, but taking care that the same nomenclature
can be used in both mathematical equations and programming. This serves as an
interface to any programming application.
3. Solutions in excel and Python are designed so that a solution in one application
can directly be translated into the other one.
To enable this approach, training in excel emphasizes vectorized code, matrix for-
mulas, and constructs that allow for broadcasting in the same way as Python.
Furthermore, programming VBA macros interacting with spreadsheets introduces
looping, logical queries, and functions.
– training to work with numpy arrays, list slicing and broadcasting in Python,
– working with similar constructs, vector structures, and matrix operations also
in excel,
– learning how to write programs with looping, logical queries, and functions in
Python and VBA for excel,
– training how to lay out spreadsheets clearly so that they are apt for simple
scientific computing,
– developing VBA macros that exchange data with spreadsheets,
– applying standard mathematical methods numerically.
After having successfully completed the exercises, you should have gained so
much self-confidence that you can answer the question “Programming practice?”
with an enthusiastic “Yes!”.
You will need a Physics textbook (anyone will do, e.g., the one you have at hand
during your studies anyway) and two more books on programming as indicated
below.
EXCEL
To work with excel, you only need a computer in which excel has been imple-
mented (any version; the exercises in this book have been checked in excel 2010
and excel 2019) and an introduction to excel (do not buy one before having done
the basic exercise in Sect. 2.3). In particular, you do not need a special development
environment for visual basic, because it is included in all versions of excel.
Python
You will need to install Anaconda, a free and open-source distribution of the Python
and R programming languages that also comprises the Jupyter Notebook by
default. The examples in this book were obtained with Python 3.7 in Jupyter.
You are advised to use both a book and internet courses to broaden your training
systematically. Make your choice after having gone through Exercises 2.4 and 2.5.
You will soon meet two types of students and a tutor who will accompany
us throughout this book. The character named Tim (which stands for “timidus”
or “timida”, meaning shy)) represents those students who are somewhat hesi-
tant, fearing that they may fall short of the requirements, although they study
hard. The character named Alac (which stands for “alacer”, meaning alacritous,
high-flying) is typical of those vehemently self-confident students (men are gen-
erally over-represented) who believe that they already have a superior overview
and do not have to deal with what they consider mere bits and pieces. Mag
(for Magister/Magistra, i.e., the tutor who runs the course) tries to engage with
both characters, encouraging Tim and cautioning Alac, and clarifying that both
approaches are valuable and that every Physics student should venture into the
Computer world.
4 1 Introduction
Tim I see how well some fellow students are juggling programming tools, but
I’d rather stand back. I prefer to learn the stuff from textbooks.
Mag This course is not intended to turn you into a computer nerd. You will not
learn any cool tricks. We restrict ourselves to some basic techniques that are prac-
ticed again and again. The computational techniques do not stand by themselves,
but are always taught in connection with physical problems.
Tim But I have often heard that programming is a black art for which you have
to be specially talented.
Mag Here, you will learn the most basic computer techniques that every
scientist, engineer, and science teacher must master to succeed in their profession.
Mag A master can be recognized by how he/she deals with errors. Any unno-
ticed error in spreadsheet formulas and programs can lead to disaster. It is essential
that you gain experience with data structures and programming constructs.
Mag Yes! By using data structures in spreadsheets and Python programs and
setting up graphical representations that are comprehensible, even when you look
at them after some time. And by developing simple procedures that control the
program flow.
Mag Let’s compare this course with learning a foreign language. How do you
learn foreign languages?
1.4 Tim, Alac, and Mag 5
Alac Learning? For foreign languages, academic learning is useless in the long
run. You simply have to go abroad; the rest follows by itself.
Tim Oh, I couldn’t learn like that. I couldn’t form a proper sentence in a for-
eign language without profound foreknowledge. I would have to learn the correct
grammar and vocabulary first before I would dare to speak.
A good balance
Mag We are trying to find a good balance. You will learn the most straightfor-
ward “sentence” structures, but will also be “sent abroad” right off, and you will
have to make your way there. If you pass this test, you can be confident of being
able to learn the more complex “grammar” if necessary.
Mag Don’t worry! Working through this book will make you fit for a computer-
oriented world, be it for spreadsheet calculations in business or scientific comput-
ing in research. This can be tedious, but it will be worthwhile, whether it be as
early as learning at school or working for a Bachelor’s or Master’s, or even as late
as working on a Ph.D. thesis.
Mag I think so. Anyway, this course is about physics and will help you to pass
your exams.
Workshop atmosphere
Having cleared up the doubts harbored by Tim and Alac, we now explain the didactic
concept of this book.
In the courses at the University of Duisburg-Essen on Physics with Excel and
visual basic, learning was mostly done in a workshop, such as in physics labs for
beginners. The students dealt with the tasks alone or in pairs while in a computer
lab, ideally also helping each other out across groups and consulting the supervisor
when needed. Students could continue to work on their tasks outside of attendance
time so that everyone could work according to their learning progress.
Experience shows that the students enjoy the tasks, and the learning progress is
fastest when all three aspects—programming, physics, and mathematics—are com-
bined. The systematic practice of various isolated spreadsheet and programming
techniques is often perceived as too dull. The combination of calculations and graphs,
realized in nearly all exercises in this book, proved to be particularly instructive.
6 1 Introduction
– a basic course for beginners, in which two tasks from each of the six Chaps. 2, 3,
4, 8, 9 and 10 were worked on and had to be presented to the supervisor;
– an advanced course with two tasks each from Chaps. 5, 6 and 7, and one task that
had not yet been worked on from the chapters of the beginner’s course. Sometimes,
two short exercises were combined into one task.
Broom rules
To many beginners, spreadsheet calculations and, especially, computer programming
seem like witchcraft. We like to address this idea by setting up “broom rules” that
the students hopefully will not forget so easily. Some examples: “ Half, half, full;
the halves count twice” (Runge–Kutta of the 4th order) or “ Mostly, not always.
(“fundamental rule” of statistical reasoning, no statement is 100% sure).
In addition, Mag puts stumbling blocks along the learning path, in talks with the
two student characters, Tim, who learns the material from the beginner’s course dili-
gently, and Alac, who does not hesitate to implement premature ad-hoc solutions. It
is important to emphasize that both attitudes have their advantages and shortcom-
ings, and neither student should feel denigrated. It is just that some students have
to be encouraged to venture into the programming world, whereas others have to be
cautioned against rushing too quickly into coding.
1.5 Didactic Concept 7
Exam questions
At the end of every chapter, a collection of rehearsals and tasks is presented, typically
requested in written and oral examinations.
simulated realistically to obtain data that can be evaluated. Our tools for simulation
are random numbers generated according to the desired distribution.
With linear regression, mathematical functions are fitted to sets of measured values
to get trend lines through data points (Chap. 10). Furthermore, an introduction to
the important technique of non-linear regression with solver functions will be given,
again, in both excel and Python.
Follow-up book A follow-up book, “Physics with Excel and Python, Using the
Same Data Structure. Applications”, is being prepared, dealing, in the same style,
with advanced topics, structured according to physical and mathematical aspects,
such as:
– properties of oscillations,
– motions in the plane,
– the steady-state Schrödinger equation,
– partial differential equations,
– Monte Carlo methods,
– wave optics,
– statistical physics, and
– variational calculus.
In Fig. 1.1, you see the start menu of excel 2019, where the main tab for-
mulas has been activated, and the cursor has been positioned over the group
Ribbon
Formula bar
Command
Column header
Active cell
Handle
Row number
Fig. 1.1 The start menu of excel, with the main tab formulas activated
1.7 Getting Started with Excel 9
function library to show the command math&trig. Arrows indicate the dif-
ferent elements of the start menu, namely ribbon, tab, group, formula bar, and
command, as well as elements of the working area, column header, row num-
ber, active cell, and handle of a cell. To indicate a “click path” in the text,
we write a sequence tab/group/command/function, e.g., formulas/function
library/math&trig/cos to call the cosine function.
Throughout this book, we will take screenshots from excel 2019. Experience
has shown that students can work with these instructions in every version of excel
without major difficulties.
structure of a spreadsheet
In Fig. 1.2 (S), a spreadsheet organization in the structure, often employed in our
exercises, is shown. With (“gamma”), we refer to the straight lines above C14:G14
and to the left of C14: C174.
Above :
Left of :
A B C D E F G H
1 Prespecifications
2 Amplitude of pendulum Ap 1.50
3 Period of pendulum Tp 1.20
4 Period of rotation Tr 9.00 Tp=1.2; Tr=9
5 Time interval dt 0.0173 ="Tp="&Tp&"; Tr="&Tr
6 Suspension point vs. rot. axis xSh 0.00
7 Calculated therefrom
8 Angular frequency pendulum wP 5.24 =2*PI()/Tp
9 Angular frequency rotating disc wR -0.70 =-2*PI()/Td
10
c disc
ot. dis n rot.
. on r tylo o
ndu lum ace pend c e s
11 Pe Tr Tra
t) +xSh *t) t)
(wP * (wR wR*t) (wR* wR*t)
+dt COS xP*COS SIN( Ap*COS Ap*SIN(
12 =B14 =Ap* = =xP* = =
13 t xP xT yT xSt ySt
14 0.000 1.50 1.50 0.00 1.50 0.00
15 0.017 1.49 1.49 -0.02 1.50 -0.02
174 2.768 -0.52 0.18 0.49 -0.53 -1.40
Fig. 1.2 (S) Typical structure of a spreadsheet, here, for the calculation of the trace of a Foucault
pendulum; rows 16–173 are hidden
10 1 Introduction
Fig. 1.3 (P) Log procedure, changes the period of the rotational motion in Fig. 1.2 (S) and logs
the values of x T and yT at the last instant of the calculation period
Below :
Nomenclature
Python-typical terms are printed in the Courier font.
When excel-typical terms are referred to in the text, e.g., function names, they are
set in small caps; examples: if(condition; then; else) . Spreadsheet formulas
are given in the form B15 = [=B14 + dt]. The expression in rectangular brackets
corresponds exactly to the entry in the cell, including the equal sign. The equal sign
specifies that it is a formula that is in the cell.
Three types of figure are distinguished, two of which are denoted by suffixes, (S)
for spreadsheets, e.g., Fig. 1.2 (S), and (P) for the code of Visual Basic programs,
e.g., Fig. 1.3 (P). Figures without a suffix are line drawings or screenshots, e.g.,
Fig. 1.1.
Names given by the programmer are printed in the text in italics, e.g., f, d. Some-
times in excel, names are used that contain a dot, e.g., “T.1” or “x.2”. This is because
T1 and X2 are reserved for cell addresses. The associated variables are referenced
in the text without a dot, but with subscripts, i.e., as T 1 and x 2 .
Physical units
Sometimes, no physical units are specified in the axis labels of the figures. They can
then be deduced from the physical units of the parameters.
You first have to install Anaconda with Python. There are many instructions on
the Internet as to how to achieve that, e.g., https://docs.anaconda.com/anaconda/ins
tall/windows/ or https://www.jcchouinard.com/install-python-with-anaconda-on-
windows/ (2020-09-02).
1.8 Getting Started with Python 11
When the Jupyter Notebook is opened, an overview of the filers and single
files on the localhost is shown. The programs used for this book are in a sub-filer
“Py PhExI” of the main filer “Python”. When we click Python/Py PhEx I, the
window in Fig. 1.4 pops up. To edit an already existing file, we have to click on
that file.
To create a new file, we open the list “New” and click on “Python 3”. A new
window pops up, opening a new file “Untitled22” with an empty program
cell “In [ ]”. The version in Fig. 1.5 is displayed after a small program has
been written into that cell. “In [5]” indicates that the 5th version of the code is
shown. This program is executed by clicking the button “Run”. The result of the
instruction print[x] is displayed in the output cell created automatically below
the program cell.
The different programming techniques are distributed over various exercises. For
the purpose of learning about them and how to revise them, the following lists
of keywords and broom rules have been compiled. They are meant to assist
the readers with the revision of subjects and, of course, their preparation for
examinations.
Fig. 1.5 A program creating an output just below the program cell
Mathematical techniques
Ψ Imaging equation for lenses with plus and minus! (Exercise 3.2).
Functions
Solutions of Exercises 2.3 (Excel), 2.4 (Python), 2.5 (Excel), and 2.6 (Python) can
be found at the internet address: go.sn.pub/9Rtzxi.
Spreadsheet technology
This chapter is about how cells are addressed, figures are created and formatted,
and sliders are used to change cell contents. This will be easy for you if you are
already familiar with excel and know how to write formulas into cells. If you are
less experienced, you will first have to go through the basic exercise step by step. If
necessary, consult the excel help guide, and, finally, after having gone through the
basic exercise, find a textbook about excel techniques that is best suited for your
learning style.
Required and practiced excel techniques are:
We first exercise different types of cell addressing. Our goal, however, is to write
formulas as mathematically as possible, i.e., with letters representing variables.
Then, they will be identical to formulas in Python. For this purpose, individual
cells, ranges of cells within rows (row vectors) or columns (column vectors), and
two-dimensional cell ranges (matrices) are to be designated by names. All of these
techniques will be introduced step by step in the individual exercises and summa-
rized again in Sect. 2.3.5. The systematic use of vectors and matrices is the reason
why spreadsheet calculations can be translated nearly literally into Python.
Figures representing spreadsheets are characterized by the supplement (S), e.g.,
Fig. 2.2 (S).
Formulas in spreadsheets
Formulas in spreadsheets are reported in italic and often in oblique orientation, valid
for a cell in the neighborhood in bold font. They will be written in the text in brackets;
e.g., for the content of cell A11, we write A11 = [=A10 + dx]. We have to distinguish
whether or not an equality sign is written in the cell. For the expressions A9 = [x]
and A10 = [3], no equal sign is written in the cell; [x] is thus interpreted as text and
[3] as a number.
Python constructs
We will learn Python programming by working with the program cell structure
of the Jupyter notebook, first dealing with list processing and then focusing on
operations on arrays in Numpy. The explanations are less technically detailed than
for excel, because list processing is the core business of Python and has been
well described in numerous textbooks and online courses. However, our examples
are designed so that the essence of the definitions and procedures should become
obvious.
The Python constructs for list generation (np.linspace and np.arange
in the numpy library) will be used to define vectors that are later transformed with
standard functions into other vectors using list comprehension and broadcasting. To
mimic the column vectors in spreadsheets, a two-dimensional list with only one row
has to be introduced and transposed.
2.1 Introduction: Named Ranges in Excel, Arrays in Numpy 17
Matrix operations
Having provided excel with the necessary matrix formulas, we can finally demon-
strate broadcasting for algebraic operations and some operations of linear algebra
parallel in excel and Python (Exercise 2.5).
Applications
We practice our newly acquired knowledge in an exercise on four parabolas and
their upper envelope. The chapter concludes with a physically meaningful exercise
treating the sum of four cosines so as to demonstrate overtones, beats, and the addition
theorem of cosines.
Starting from its vertex form, we set up a data structure to tabulate and plot
a parabola, together with its characteristic features focus and directrix. The
data structure set up here is to be used in Exercise 2.3 for a single parabola
and in Exercise 2.6 for a set of 4 parabolas.
y = a + b · x + c · x2 (2.1)
y = yV + c · (x − x V )2 (2.2)
because its shape is immediately clear: its vertex is at (x V , yV ), and its curvature is
proportional to c (positive or negative). Transforming into the standard form yields
a = yV + c · x V2 and b = −2 · c ∗ x V (2.3)
In Fig. 2.1a, a parabola is shown with its vertex marked with a diamond.
Question
What are the coordinates (x V , yV ) of the vertex and the value of c in Fig. 2.1a?1
18 2 Data Structures, Excel and Python Basics
10 10
y y
8 8
6 6
4 4
directrix
vertex
6.2+-0.4x+-0.1x²
2 2 4.572+-1.56x+-0.3x²
focus
rays
0 0
-8 -4 0 x 4 8 -8 -4 0 x 4 8
Fig. 2.1 a (left) A parabola with its maximum at (−2.6, 6.6). b (right) Connecting the parabola
with its focus and its directrix; compare Fig. 2.10
1 x V ≈ −2, yV ≈ 6.5 from visual inspection in the coordinate system; c = −0.1 from the legend
in the figure.
2.2 Characteristics of a Parabola 19
Spreadsheet layout
A spreadsheet layout for generating a parabola yP = f (x) is displayed in Fig. 2.2 (S).
We are going to review three regions successively: A1:B6 (to explain cell addressing),
D1:H3 (to name cells and apply sliders), and A8:E169 (to name cell ranges). All
relevant cells and the ranges x, yP , and yA get names from the beginning. The formulas
in cells are printed in neighboring cells in italic to keep track of the calculations.
Fig. 2.2 (S) Tabulation of a parabola with the parameters c, b, a in B3:B5; F1:H3, sliders to deter-
mine the parameters x V , yV , c; E8:E169, alternative tabulation of the parabola using the named
cells a, b, c_ and the column range x
Task Change the contents of cell B6, named “dx”! All x values in cells
A10:A169 should adjust themselves immediately.
The values for yP are obtained by entering the formula reported in B7 into B10
and dragging it up to B9 and down to B169. The formula is most conveniently
obtained by first entering [=], and then by clicking on the corresponding cells and
continuing with the operators * for multiplication and ˆ for potentiation, resulting
in B10 = [=B5 + B4*A10 + B3*A10ˆ2]. In the last term, the variable taken from
A10 must be squared. This is done with the power operator ˆ. You have to press
the button with the ˆ-sign and then the desired power, “2” in our case. Only after
the second step does the operator [ˆ2] appear in the cell.
When this formula is copied into another cell, the cell addresses change accord-
ingly. Copying into C11 would yield C11 = [=C6 + C5*B11-C4*B11ˆ2), realizing
relative addressing but not giving the desired result, because we would like to keep
the cells with the coefficients constant. This is achieved by making the references
to B3:B5 absolute, with dollars as prefixes: $B$5, $B$4, $B$3, either by introduc-
ing the $ sign explicitly before the column letter or the row number or by pressing
the function key F4, resulting in the formula reported in B7.
2.3 Basic Exercise in Spreadsheet Calculation 21
Having now copied this into C11, we would get C11 = [=$B$5 + $B$4*B10-
$B$3*B10ˆ2], with the values for x copied incorrectly (A10 becomes B10),
because they are still relatively addressed. Making the address of column A abso-
lute is achieved with $A10, B10 = [=$B$5 + $B$4*$A10-$B$3*$A10ˆ2]. If we
now copy this formula into another cell, only the row number 10 changes, e.g.,
into 12 when copied into any column in row 12.
Making a cell reference absolute can also be achieved by pressing the function
key F4 several times. Key words for the excel help: Absolute, relative, and mixed
cell references.
There is a more elegant way to copy a formula down a column: clicking onto
the “fill handle” (the bottom right corner) of the cell that contains the formula.
Then, the cell contents are immediately continued down to the 169th row, i.e., for
all cells for which there is an entry in the neighboring column, here column A,
until the first empty neighbor cell is encountered.
Questions
Having gotten this far, we have programmed our first function. Changing the values
of x V , yV , and c in B1, B2, B3, the function values in column B adapt imme-
diately. We may now proceed to the section “Graphical representation” to see the
resulting curve, but should come back to learn about naming cells.
Naming cells
In the range B1:B6 of Fig. 2.2 (S), parameters are defined that are accessed in various
parts of the worksheet. To call them like variables in mathematical equations, we
provide the cells with the names written to the left of them. This is done by activating
the range A1:B6 comprising names and values and clicking through (excel 2019):
formulas/defined names/create from selection.
A prompt appears, “create names from values in the left column?”.
The answer is yes, that the agent has correctly detected, and we confirm this by
clicking ok. For more about the name manager, see Sect. 2.3.5. We can now refer
to these cells by their names, anywhere in the spreadsheet and, indeed, throughout
the whole book.
When writing, e.g., [=a] into a cell somewhere in the spreadsheet and pressing
enter, this cell immediately gets the numerical value corresponding to a, in our
2 Rows 11 to 168 are hidden. The jump is over 159 advances of dx; -7.9 + 15.9 = 8.0.
3 The value for dx is set in cell B6, which is given the name in A6.
4 The name c is protected for excel-internal use. A name c in a cell intended to become an
example, 6.2. When the content of cell B5 is changed, the value of all cells with [=a]
changes as well.
We can even name cell ranges, e.g., A9:A169 with the name x and B9:B169 with
yP. When activating A8:B169 and proceeding as above, the Name Manager prompts
us: "create names from values in the top row?”, and we confirm this
by clicking OK.
We may now write = a + b*x + c_*xˆ2 into E9, more elegant and clearer than
the formula in B7, with absolute and relative cell addressing, and copy down to D
169 to get the same values as for yP . For x, the formula in a cell takes the value in
the same row in column A. The name manager has changed c into c because the
letter c conflicts with a protected name in excel.
After having created the function table of a parabola so beautifully, we would like
to visualize the curve. To do so, we set the cursor into an empty cell, away from
the filled cells, and click in the insert tab on insert/ charts/, and on scatter
within the charts section. A blank chart is inserted.
Upon our activation of design/select data (see Fig. 2.5b), a select data
source window opens. We click add, and a window as shown in Fig. 2.3 opens.
For series name, we click on cell B8 of Fig. 2.2, and for series x values, we
activate A9:A169 and hit return. For series y values, we activate B9:B169 and
hit return. The empty chart changes to that shown in Fig. 2.4.
As the legend “yP” has been taken from a cell in the spreadsheet, it will adapt
immediately when the cell entry is changed. If a legend in a chart is identical to
that in the spreadsheet indicating the data, it helps in keeping the overview.
Spreadsheet
symbol
Fig. 2.3 Insertion of a data series into a chart; the series name is best taken from the worksheet
by activating the relevant range, not by entering it as text
2.3 Basic Exercise in Spreadsheet Calculation 23
yP
08
06
04
02 yP
00
-10 -05 00 05 10
-02
-04
Fig. 2.5 Tabs, which are important for diagrams, after insert/charts/scatter/with only
markers in the Start menu (excel 2019, excel 2010 similar) or after activating an existing chart,
a (left) format/current selection, to the left of the start bar, to format an element of the dia-
gram, b (center left) design tab / data group /select data to select data to be entered into
the diagram, c (center right) design tab /chart styles, d (right) format/size, appears after
activating a diagram, to the right of the start bar, to specify the size of the diagram
– Size (7 cm high, 8 cm wide) (in the start bar to the far right, see Fig. 2.5d).
Also, after clicking on the relevant element of the diagram or selecting it from
the leftmost register in the format tab (Fig. 2.5a, at first, only chart area
appears, but after opening the list by clicking on ▼, all items of the diagram
appear), we choose before clicking format selection:
Task Change the value of the parameters x V , yV , c in Fig. 2.2 (S) and observe
how the spreadsheet entries and the chart change!
Smart legends are created by concatenating variables and text. In Fig. 2.4, we
have specified the parabola with its name in the spreadsheet, in simple text. In
Fig. 2.1a, however, the legend contains the actual parabola equation generated in
D6 of Fig. 2.2 (S) with “Text” &variable.
Often, float values have to be rounded. When, e.g., B3 = [= 1/3], then only 0.33
is displayed in the cell. However, if B3 is inserted into a legend, 0.333333333
appears. Setting round(B3, 2), 0.33 is returned: [= “c_ = “&round(B3; 2)]
results in the cell content [c_ = 0.33].
Fig. 2.6 (excel 2019, excel 2010 similar) a (left) Tab after going through devel-
oper/controls/insert/activex controls. A slider is listed in the upper row on the right,
at the foot of the arrow. b (center) In J1:L1, a slider has been installed by clicking on the control
element and pulling it up in said spreadsheet area. c (right) Menu for defining the properties
of the slider (scrollbar). It appears after we click on properties in a; important parameters:
linkedcell, minimum and maximum values
and then pull up a rectangle with the mouse at the desired place in the spreadsheet.
In Fig. 2.6b, this is done in cells J1:L1. Now, with the design mode still on, we
can configure the slider. In Fig. 2.6c, the properties list of the activated scrollbar
is shown. We specify that it is cell I1 (linkedcell) into which the number is to be
written, and that the number should be between 0 (min) and 100 (max). We then
turn the design mode off by clicking on this icon again (see Fig. 2.6a) and move
the slider’s thumb with the mouse. Immediately, a number appears in I1.
design mode is activated and deactivated by clicking on the icon. When
activated, existing control elements can be modified, or new ones added. When
deactivated, the control elements can be operated.
When we grab the thumb (the rectangular bar in the middle of the slider)
with the cursor and move it, the output in the linked cell changes. SmallChange
specifies the jumps (to the left or the right) of the numbers when we click on the
(left or right ) edge of the slider. LargeChange sets the jumps’ size when
⍓
we click within the slider bar left or right of the thumb. Try it out!
Conversely, if we change the contents of a linkedcell, the new value is entered
into the slider’s memory, and its thumb will move.
We can use a slider (scroll bar) to enter integers between 0 and 32,767 (=
215 − 1) into a cell (LinkedCell). Settings are specified in the properties group:
26 2 Data Structures, Excel and Python Basics
For linkedcell, specify the address of the cell to be written into. min and max
can limit the value range.
Questions
Which numbers can appear in I1 (range and minimum distance to each other),
according to the information in Fig. 2.6c?5
What is the range of the numbers for x V in Fig. 2.2 (S), provided that Min
= 0 and Max = 80 for the slider in F1:H1. What is the minimum step size?6
5 MIN = 0; MAX = 100; integers between 0 and 100 can appear in I1, distance = 1.
6 B1 = [=(E1-40)/5] (see D1), range -8 (for E1 = 0) to + 8 (for E1 = 80) in steps of 1/5 = 0.2.
2.3 Basic Exercise in Spreadsheet Calculation 27
by the column or line spacing between the old and new cells; this is a relative cell
reference.
The spreadsheet function indirect(cell) expects a cell address as an argument.
It writes the contents of the cell with this address into the current cell. For example,
with A4 = [=indirect(A5)] ; A5 = [X7]; X7 = [3.4] the value in A4 will be 3.4.
x − x1
Ex = 3
(2.5)
(x − x1 )2 + y 2
The definition of variables and constants and the calculation are distributed over
two sheets, “Dist” and “E.x”. The values of r = (x − x1 )2 + y 2 , representing the
planar distance to point (x 1 , 0) for x and y from -2 to 2, are calculated in Fig. 2.7a
(S) (Sheet “Dist”).
The x values are in B3 to F3, the y values in A4 to A8. The value for x 1 is specified
in B1. The calculation can be performed with mixed cell references, as in cell B5:
B5 = = SQRT (B$3 − Dist!$B$1)∧ 2 + A$5∧ 2 (2.6)
The formula is, however, more intuitive when cell names are used, as in D6,
displayed in D2:
D6 = = SQRT (x − x.1)∧ 2 + y∧ 2 (2.7)
To achieve this, we have to designate, e.g., range B3:F3 with the name x,
already present in cell G3. We activate B3:G3 and follow the menu formu-
las/defined names/create from selection. To “activate” the range means
28 2 Data Structures, Excel and Python Basics
Fig. 2.7 (S) a (left) Sheet “Dist”; the values in the matrix B4:F8 are calculated with the values in
the horizontal vector x = B3:F3 and the vertical vector y = A4:A8, together with the value of x 1 in
cell $B$1, using mixed cell references in B5 and variable names in D6. b (right) After activating
B3:G3 in a, the dialogue box of formulas/ defined names suggests providing B3:F3 with the
name in G3 ( right column)
that the cells are marked with the left mouse button pressed. A window like the
one shown in Fig. 2.7b (S) pops up. The assistant has already recognized a poten-
tial name in the immediate neighborhood of the activated range, namely, in the
right-most column of the activated range. This name corresponds to our intention,
and we click OK.
The matrix range B4:F8 is named by activating it and selecting formu-
las/defined names/define name. A window marked new name pops up with
the refers to field already filled in, because a cell range was activated before the
selection. We have to fill in the name field, in our case, with “r.0”.
The formulas/defined names/name manager window, displayed in
Fig. 2.8 (S), gives us an overview of all of the named ranges.
Fig. 2.8 (S) The name manager lists all names and ranges (“refers to”) and the scopes for which
they are valid
2.3 Basic Exercise in Spreadsheet Calculation 29
A B C D E F G I J K L M N O
1 Sheet E.x 14
0^3 0^3} rmula
.1)/r. .1)/r. trix fo
2 =(x-x -x a
15 {=(x as m
3 ### ### ### ### ### #VALUE!
16 -0.1 -0.1 0.0 0.1 0.1 #N/A #N/A
4 -0.1 -0.1 0.0 0.1 0.1 #VALUE!
17 -0.2 -0.3 -0.1 0.4 0.2 #N/A #N/A
5 -0.2 -0.3 -0.1 0.4 0.2 #VALUE!
18 -0.2 -0.8 -100.0 1.2 0.3 #N/A #N/A
6 -0.2 -0.8 -100 1.2 0.3 #VALUE!
19 -0.2 -0.3 -0.1 0.4 0.2 #N/A #N/A
7 -0.2 -0.3 -0.1 0.4 0.2 #VALUE!
20 -0.1 -0.1 0.0 0.1 0.1 #N/A #N/A
8 -0.1 -0.1 0.0 0.1 0.1 #VALUE!
21 #N/A #N/A #N/A #N/A #N/A #N/A #N/A
9
22
Fig. 2.9 a (left, S) Sheet “E.x”. The x component of the electric field of a point charge at (x 1 ,
0) is calculated. In row 3 and column G, the index is outside of the permitted range. b (right, S)
Alternative calculation in an arbitrary position with a matrix formula
The names are valid in the entire workbook when they are first defined. The
names “x” and “y” appear twice. When they were first defined in the “Dist” spread-
sheet, they were valid throughout the workbook, as shown in the scope column.
When they are defined a second time in another sheet, here, “MMult”, their scope
is limited to this spreadsheet, and the previous definitions of x and y do not apply
here, although they still do in the rest of the workbook.
Mag You can find this out by trial and error or by using filter in the name
manager.7
7The named ranges in sheet “Dist” are valid throughout the whole workbook, except for “MMult”,
so they are also so in “E.x”.
30 2 Data Structures, Excel and Python Basics
Alac That’s all really super easy. Worksheet calculation seems to be a children’s
game. That wasn’t clear to me until now.
Tim Well. Might we have acquired knowledge in only a narrow section for
particular tasks?
Mag We have traveled quickly across a wide area on a narrow path. This is
actually a fast track to success, at least for the tasks we intend to tackle.
Tim Is it not better to learn thoroughly so that one does not become lost when
the tasks are set a little differently?
Alac You can always tackle modified tasks through trial and error.
Mag Yes, trial and error is a possibility. You should do this anyway with all of
the programming constructs with which you are not already familiar. Nevertheless,
you should also go to a bookstore or into the internet and find books that instruct
you in excel. Browse along the learning path you have just gotten to know. It will
not take long for you to figure out which of the books explains the computational
procedures in a way that you can understand. You should buy that book!
The same advice holds for Python, which you will get to know in the next
section.
Table 2.1 presents a Python program corresponding to Fig. 2.2 (S) for complete-
ness. The reader may study it after having gone through Exercise 2.4.
The program consists of a list of simple assignments of type x V = -2, with the
name x V being called the identifier, or simple formulas assigned to an identifier,
2.3 Basic Exercise in Spreadsheet Calculation 31
Table 2.2 Calculating the coordinates (for Fig. 2.1b) of the focus and the directrix
10 xF=xV #Coordinates of the focus
11 yF=yV+1/4/c
12 yD=yV-1/4/c #y Coordinate of directrix
We will learn how to work with program cells in the Jupyter notebook,
and get acquainted with arrays in numpy. For more detailed information
about Python specifics, the reader is referred to Stewart, J. (2014). Python
for Scientists. Cambridge: Cambridge University Press. https://doi.org/10.
1017/CBO9781107447875, Chap. 3 (A Short Python Tutorial), Chap. 4
(NumPy), and Chap. 5 (Two-Dimensional Graphics) or other textbooks
treating the same subjects.
We can start running the program with any cell. However, if referring to vari-
ables or functions, we have to define them ahead of time. Starting Cell 1 before
Cell 2, or Cell 3 before Cell 4, leads to a #NameError.
We are now running the program cell by cell in sequence.
Cell 1: The print statement tries to get yA from the memory. As yA is not yet
defined, a #NameError message is returned.
2.4 Python and NumPy Basics 33
Cell 2: Three lists, characterized by square brackets, are defined, and their con-
tents are printed out. When we now run Cell 1 again, no error message appears,
but the contents of yA are printed out.
Cell 3: The statement tries to assign a value to variable z by calling a function
add2 that is not yet defined, so that a name error occurs.
Cell 4: The function add2 is defined. Now, running Cell 3 does not result in an
error message.
Cell 5: Function add2 is applied to variables x and y, and the result is printed
out. When applied to lists, the formula 2*a + b is not an algebraic function; list x
is concatenated twice and then list y once to yield the list [x, x, y].
Cell 6: The numpy library is imported under the abbreviation np. Two numpy
arrays are created from the lists x and y. The function add2 is applied to x np
and ynp , yielding an error message. When applied to arrays, it is the algebraic
operations addition and multiplication that are performed element-wise. As the
two arrays have different size, this does not work, and a #ValueError message
results: “Operands could not be broadcast together with shapes (4,) and (3,)”.
Cell 7: List y is extended with a new element to have the same length as xnp.
The function add2 can now be applied, with the result now being an array of the
same length and a linear combination of the two initial arrays. The formula 2*a
+ b is now interpreted as an algebraic operation and performed element-wise on
the arrays.
Copy
Parts of the memory may get various names, e.g., the statement AddTwo = add2
assigns the additional identifier AddTwo to the function add2 defined in Cell 4 of
Table 2.3, so that this function may also be called by AddTwo. Such assignments
are different from making a copy, as is demonstrated in Table 2.4. The statement YA
= Y[3:5] produces only a name (an identifier) for part of list Y, whereas with YC
= np.copy(Y[3:5]), a new object with its own memory space is created. Y C
is an object of its own and is not affected by subsequent changes of Y.
Table 2.4 Identifier of a subarray vs. copying a subarray into a new object; only one print state-
ment is reported in the first cell; the other print statements are similar. The results of all print
statements are reported in the second and the fourth cells
1 Y=np.array([0,1,2,3,4,5,6,7,8,9])
2 YA=Y[3:5]
3 YC=np.copy(Y[3:5])
4 print("Y ", Y)
5 Y [0 1 2 3 4 5 6 7 8 9]
6 YA [3 4]
7 YC [3 4]
8
9 Y[3]=8 #Another program line
Y [0 1 2 8 4 5 6 7 8 9]
YA [8 4]
YC [3 4] #YC is independent of Y
34 2 Data Structures, Excel and Python Basics
Data types
The following data types are available in Python:
Lists
Lists contain one or more items. They:
Append, add, and multiply result in longer lists. The new identifier x2 points to a
sublist of x from the 3rd to the penultimate (−1) element. The method append, as
well as the operators + and *, are demonstrated in Table 2.3 (def add2). Lists can
be multidimensional, but in our exercises, only one- and two-dimensional lists are
used.
Sets {}
Sets contain unordered collections of unique elements to which standard mathe-
matical set operations can be applied. These are intersection, union, difference, and
symmetric difference. Examples are given in Exercise 8.4. Sets do not record ele-
ment position and, as a consequence, do not support indexing, slicing, or other
sequence-like behavior.
Dictionaries {}
Dictionaries comprise pairs of an identifier (data type string) and an object (arbitrary
data type). The objects are addressed by their identifiers:
Numpy
Numpy is a fast and efficient array-processing package designed for numerical com-
puting that provides functionalities comparable to MATLAB. We are using it as our
standard. It is usually imported under the name np: import numpy as np, see
Cell 6 in Table 2.3.
Numpy.random
Random number routines produce pseudo-random numbers. We import
Numpy.random as npr and make use of two functions:
Matplotlib
Matplotlib is a package for designing a variety of charts or even arrays of charts. We
import matplotlib.pyplot as plt. We restrict ourselves to producing
simple scatterplots with a user-defined function (Sect. 2.4.5) that is able to display
nearly all results of our exercises, similar to excel charts. In order to plot arrows,
we introduce a second user-defined function (Sect. 3.2.7).
Scipy
Scipy is designed for scientific computing and is especially suited for machine
learning. We need only certain functions for optimization [minimize (Exer-
cise 10.6), fsolve (Exercise 10.5), curve_fit (Exercise 10.7)], linear algebra
[solve (Exercise 5.9)], and statistics (Chisquare from Scipy.stats).
Pandas
Pandas mimics spreadsheet calculation within Python, enabling input to and
output from excel files and text files. We use it only occasionally, e.g., in Exercise
4.8, to make the reader aware that such things exist and are useful.
36 2 Data Structures, Excel and Python Basics
Table 2.5 Data types in numpy demonstrated with arrays built with lists from Cell 2 of Table 2.3
1 import numpy as np
2 xInt = np.array(x,dtype=int)
3 yFloat = np.array(y,dtype=float)
4 yAfloat = np.array(yA,dtype=float)
5 xBool = np.array(x,dtype=bool)
6 xComplex = np.array(x,dtype=complex)
7 xStr = np.array(x,dtype=str)
xInt [ 0 1 2 3] shape (4,)
yFloat [ 0.00 4.00 5.00 -1.00] shape (4,)
yAfloat [ 0.00 4.00 5.00] shape (3,)
xBool [ 0 1 1 1]
xComplex [0.+0.j 1.+0.j 2.+0.j 3.+0.j]
xStr ['0' '1' '2' '3']
xInt*yFloat [ 0. 4. 10. -3.]
xInt*yAfloat ValueError: operands could not be broadcast
together with shapes (4,) (3,)
Numpy is usually imported under the name np: import numpy as np.
Ndarrays
Ndarrays are, in general, n-dimensional arrays. One- and two-dimensional ones
have analogies in spreadsheets. For scientific computing, they have an advantage
over spreadsheets when the data becomes large.
They:
– are immutable, with size and datatype specified when the object is introduced,
– are operated element-wise in algebraic operations: x + y → [x + y],
– can be arguments in mathematical functions.
In Table 2.5, one-dimensional arrays of various data types are built with the func-
tion np.array(.) expecting a list as an argument, here taken from Table 2.3.
Two numerical arrays can be multiplied element-wise when they have the same
shape, e.g., x Int and yfloat , but not x Int and yAFloat .
Question
Ab-initio constructors
The following five functions construct an array from the specifications in the
argument list.
– np.logspace
np.logspace(1, 3, 3, base = 10) → [ 10. 100. 1000.]
In np.arange, the stop value is not included. This is favorable when stacking
np.aranges together:
np.hstack([np.arange(1,4,1),np.arange(4,10,2)])
–
→ [1 2 3 4 6 8]
We can start the second np.arange with the stop of the first np.arange and
have the stop/start value only once.
The following two functions construct arrays of the same shape as Array in the
argument:
Table 2.6 Constructing a 2D array with two 1D arrays obtained with linspace; identifiers to
single rows, elements, columns, and 2D subarrays; only one print statement reported in Cell 1
1 X=np.linspace(0,3,4)
2 Y=np.linspace(10,13,4)
3 Lis=np.array([X,Y])
4 print(“np.shape(Lis) “, np.shape(Lis))
Lis[0:1][1:3]
[[ 1.00 2.00]
[ 11.00 12.00]]
Lis[0][2] means: from the first row (index 0), take the third element (index 2).
Alternative interpretation: take the matrix element from row = 0, column = 2.
Lis[1] [1:3] means: from the second row (index 1), take the second (index 1)
to the third (index 2, index 3 exclusive) elements.
Lis[0][1:-1] means: from the first row (index 0), take the second (index 1) to
the penultimate (index -1) elements.
Lis[:,1] means: take the second column (index 1).
Information on arrays
Stacking
Functions
Table 2.7 User-defined function for creating a scatter plot; this cell is run in all programs at the
beginning
1 import numpy as np
2 import matplotlib.pyplot as plt
3 np.set_printoptions(precision=2, threshold=10,edgeitems=3,
4 formatter={'float': '{: 7.2f}'.format})
5
6 def FigStd(xlabel, xmin, xmax, dx,
7 ylabel, ymin, ymax,dy,
8 xlength=4,ylength=4):
9 plt.figure(figsize=(xlength, ylength))
10 plt.axis([xmin, xmax, ymin, ymax])
11 plt.rcParams.update({'font.size': 10,
12 'font.style':'italic'})
13 plt.xlabel(xlabel)
14 plt.xticks(np.arange(xmin, xmax+dx, dx))
15 plt.ylabel(ylabel)
16 plt.yticks(np.arange(ymin, ymax+dy, dy))
17 plt.plot([xmin,xmax],[0,0],'k-',lw=1) #x Axis through 0
18 plt.plot([0,0],[ymin,ymax],'k-',lw=1)
40 2 Data Structures, Excel and Python Basics
body, and the information concerning the x-axis and the y-axis has to be speci-
fied in positional arguments. The axes’ lengths in the figure have default values
(xlength = 4, ylength = 4) that can optionally be specified otherwise.
The plot in Fig. 2.10, corresponding to Fig. 2.1b, is produced with the program
in Table 2.8 (continuation of Table 2.1 and Table 2.2).
In the instruction [yD, a + b*i + c*i**2,yF], the values are cre-
ated implicitly within the list.
Extensions
In Sect. 3.4.7, we introduce two extensions of our standard figure: a secondary y-
axis, a logarithmic scaling of the y-axis with the statement plt.yscale(value
= ”log”).
2.4 Python and NumPy Basics 41
The example in Table 2.9 shows how a formatted output can be achieved. There is
a format string with three text variables “y = $*x**$ + $”. The $ here is a proxy;
it starts with a “%” and is followed by a format, e.g., 4.2f for a floating number
4 characters long and to be displayed with 2 decimal places. Following the string
is a % sign and the name of the variables as a tuple, here %(a1, a2, a3) with the
three entries replacing the three % in the format string.
We define row and column vectors and 2-dimensional matrices, and explain
operations on them, parallel in excel and Python. We apply broadcasting
in excel and Python to adapt the shape of operands so as to fit with each
other in the intended operation. Finally, we get to know and apply the matrix
operations transposition and inversion of linear algebra.
Data structure
The data structure in scientific computing is based on arrays. Python, especially its
numpy library, is designed for vectorized code, so that the programmer is forced to
work with it from the first line of a code. This is its core business, described in all
introductory textbooks, so we do not need to explain it here in detail.
Spreadsheet software, in contrast, is primarily designed for business calculations.
In order to make it suitable for scientific computing, we have to create said vectorized
data structure. This is achieved by identifying cell ranges with names so that most of
the operations on vectors and matrices known from Python programs can also be
applied in spreadsheet calculations. This is the essence of our approach to making
spreadsheet calculations suitable for elementary scientific computing.
The treatment in this book is restricted to 1-dimensional arrays called vectors and
2-dimensional arrays called matrices. Vectors are of two types, row and column. We
designate the shape of vectors and matrices with a tuple (r, c), where r and c are the
number of rows and columns, respectively. In Python, a row vector is regarded as
42 2 Data Structures, Excel and Python Basics
Nomenclature
We not only strive to use the same notation of variables in Python and excel, but
also to use a similar one in mathematical equations in the text. For this exercise, we
have chosen the following nomenclature:
Element-wise operation
Functions with scalar arguments, e.g., cos(x), are applied element-wise on vectors
and matrices, resulting in an output of the same shape as the argument. The same
holds for the algebraic operations addition and multiplication on arrays of the same
shape. Function names and operations are usually the same in excel and Python,
with one important exception: arcus tangens, as already mentioned in Sect. 2.4.4.
Broadcasting
Broadcasting is a technical term for an essential tool in Python, but the underlying
operations are also available in excel. If two operands of an operation are of different
but compatible shapes, they can be broadcast together. For a row vector of size n
and a column vector of size m, this is done by repeating the row vector vertically
and the column vector horizontally so as to get the same shape as an (n, m)-matrix.
When such vectors are, e.g., multiplied, the result is a matrix of shape (n, m), with
the elements being the element-wise product of the broadcast matrices.
Also, other operations, such as the multiplication of two vectors or the exponen-
tiation of a vector with another vector, are performed as if each of the operands were
repeated, so that matrices with a common shape are obtained that are then processed
element-wise.
Linear Algebra
Functions applied in linear algebra comprise determinant, inverse, and matrix
multiplication. Their names are listed in Table 2.10.
2.5 Matrix Calculations in Excel and Python 43
TRANSPOSE(M) np.transpose(M)
MDETERM(N) np.linalg.det(N)
MINVERSE(N) npl.linalg.inv(N)
Spreadsheet first
We start our overview of matrix calculations with spreadsheet constructs because the
data structure there is immediately visible on the screen.
U V W 1 2 L M
1 4 1 2 6 5
2 5 X 3 4 3 4 4 3
3 6 5 6 2 1
)
W;2)
);IN DEX(
) W;1
;1;2) Q(W) DEX(
EX(U
;3)
EX(M RT(SUMS N2(IN
=IND =IND =SQ =ATA
3 5 lW 2.24 aW 1.1
lX 5.00 aX 0.93
11.0 {=SUM(W*X)}
11.0 =lW*lX*COS(aW-aX)
Fig. 2.11 (S) Column vectors U, V, row vectors W, X, and matrices L, M are defined as named
ranges, and some operations are applied to them in the lower half of the figure
Broadcasting
Addition and multiplication of a row vector and a column vector, and of two matrices,
is demonstrated in Fig. 2.12 (S).
In the upper half of Fig. 2.12 (S), two vectors are added with the operator + or
multiplied with the operator *. When the operations are performed on two vectors
of the same type, row or column, they must be of the same size. The operations
are then performed element-wise, and the result is a vector of the same shape.
Activating a larger range leads to a repetition of the 1-dimensional result [see U*V
in Fig. 2.12 (S)]. Algebraic operations on matrices of the same shape result in a
matrix of the same shape (see L ∗ M).
All operations in Fig. 2.12 (S) are of the spreadsheet matrix type, as indicated
by the fact that they are enclosed in curly brackets. To recall: You have to activate
a range of size suitable for the result, enter the formula, and finish with the magic
chord: Ψ Ctrl, Shift, Enter.
Multiplying or adding a column vector (r,) (e.g., V) and a row vector (,c) (e.g.,
W) results in a matrix of shape (r,c) (see the results for W*V and V + W). The
operations are performed as if each of the operands is repeated, so that matrices
with a common shape are obtained that are then multiplied or added element-wise.
scal 2
{=L+M} {=L*M} {=L*scal} {=L^2} {=SQRT(L)}
7 7 6 10 2 4 1 4 1.00 1.41
7 7 12 12 6 8 9 16 1.73 2.00
7 7 10 6 10 12 25 36 2.24 2.45
Fig. 2.12 (S) Arithmetic operations on vectors and matrices defined in Fig. 2.11 (S)
2.5 Matrix Calculations in Excel and Python 45
Fig. 2.13 (S) Operations on vectors and matrices with different shapes, defined in Fig. 2.11 (S)
after broadcasting
} } )}
N;O) W;N) SE(O
MMULT( MMULT( MINVER
{= {= {=
N O I
1 2 4 3 8 5 7 10 -0.5 1.5
3 4 2 1 20 13 7 10 1 -2
#N/A #N/A 7 10
-2 =MDETERM(N)
1 0 =MMULT(O;I)
0 1
Fig. 2.14 (S) Mathematical matrix operations on the square matrices N and O
The same holds for the multiplication of a vector or a matrix with a scalar (see
L*scal). Functions applied to vectors or matrices are also performed element-wise
and yield a range of the same shape as the argument (see {=Lˆ2} or {=sqrt(L)}).
In Fig. 2.13 (S), operations combining a vector and a matrix are performed.
Before an element-wise operation, the vectors are repeated so as to obtain the
same shape as the matrix that also becomes the result’s shape.
A matrix is transposed with the function {=transpose(Matrix)}. In Fig. 2.13
(S), this is applied to L.
Before operating with numpy, we have to import this library (see line 1 in Table
2.11, where we also set the printoptions for arrays that are to be printed,
here, in the float format 0.2f with 2 decimal places and one blank between the
printed numbers. The “0” in 0.2f indicates that the number of characters is not
fixed but adapted to the current number. Additional separating blanks are obtained
by inserting them between ‘ and {, or after {: as in line 3. In the following, print
46 2 Data Structures, Excel and Python Basics
Table 2.11 Importing numpy and setting a print option for arrays
1 import numpy as np
2 np.set_printoptions(formatter={'float':'{: 0.2f}'.format})
3 x=np.linspace(0,10,4)
4 print(‘x \n’,x) #\n Makes a line feed
x
[ 0.00 3.33 6.67 10.00]
statements similar to that in line 5 of Table 2.11 are not explicitly reported, but
only the results, as in the bottom cell of Table 2.11. The key word “\n” induces a
line feed.
Row vectors
In Table 2.12, row vectors W and X are created as an array with the same
elements as in Fig. 2.11.The length of W, calculated correspondingly with
np.sqrt(np.sum(W*W)), is the same. The scalar product of two vectors
can be calculated with the function np.dot or with the operator @ for matrix
multiplication: W @ W.
Column vectors
Row vectors can be transformed into column vectors by transposition, most
simply with the function np.transpose(), but also with the extension
.transpose(1,0) fixed to the identifier of a vector (or, more generally, of a
matrix) (see Table 2.13). The original vector UR is not defined as a row vector, but as
a matrix with only one row, characterized by enclosing the list within double square
brackets, [[ …]]. This (1, 3)-matrix can be transposed with np.transpose(UR)
or UR.transpose(1, 0) to become a (3,1)-matrix equivalent to a column
vector. The transpose operation can also be applied to more-dimensional matrices.
In said table, we also demonstrate the element-wise multiplication of two column
vectors U, V and the broadcasting that occurs when a row vector (W from Table
2.12) and a column vector V are multiplied. An instruction [1,2,3]*[1,2] results in
an error message: “Operands could not be broadcast together”. The operation * is
commutative: W*V = V*W.
Table 2.12 Creating row vectors in Python and determining their scalar product; print state-
ments are not reported in Cell 1, and only their results are reported in Cell 2
1 W = np.array([1, 2]) W, np.shape(W) [1 2]
2 X = np.array([3, 4]) (2,)
3 lW = np.sqrt(np.sum(W*W)) lW 2.24
4 ld = np.dot(W, W) ld 5
1 W @ W 5
2.5 Matrix Calculations in Excel and Python 47
Table 2.13 Creating column vectors in Python, multiplication of two column vectors
and multiplying column vector V with row vector W (from Table 2.12). The entries in the
lower cells are obtained by print statements in the top cell that are not reported there, e.g.,
print("np.shape(UR)", np.shape(UR))
1 UR = np.array([[1, 2, 3]])
2 U1 = np.transpose(UR)
3 U = UR.transpose(1, 0)
4 V = np.array([[4, 5, 6]]).transpose(1,0)
np.shape(UR) (1, 3) V
UR [[4]
[[1 2 3]] [5]
[6]]
np.shape(U1) (3, 1)
U1 U*V
[[1] [[ 4]
[2] [10]
[3]] [18]]
Matrices
In Table 2.14, we see how 2-dimensional matrices are created with the function
np.array( …) . The argument of np.array is a list of 1-dimensional lists all
of the same size. Algebraic operations such as L*M on matrices with equal shape
are again performed element-wise.
Linear Algebra
In Table 2.16, we learn about linear algebra operations on square matrices (shape
(n, n)) using the functions inv and det of the linalg sublibrary of numpy
that is often imported as np. Np.linalg.det returns the determinant and
np.linalg.inv() the inverse of a square matrix.
48 2 Data Structures, Excel and Python Basics
Table 2.14 Creating 2-dimensional matrices in Python and performing algebraic operations on
them; the entries in the bottom cells are obtained by print statements in the top cell that are not
reported there, e.g., print("L\n",L)
1 L = np.array([[1, 2], [3, 4], [5, 6]])
2 M = np.array([[6, 5], [4, 3], [2, 1]])
np.shape(L) (3, 2) L*M
[[ 6 10]
L [12 12]
[[1 2] [10 6]]
[3 4]
[5 6]] L**2
[[ 1 4]
M [ 9 16]
[[6 5] [25 36]]
[4 3]
[2 1]] np.sqrt(L)
[[ 1.00 1.41]
[ 1.73 2.00]
[ 2.24 2.45]]
Table 2.15 Product of a 2-dimensional matrix (L defined in Table 2.14) with 1-dimensional
vectors V, W defined in Tables 2.13 and 2.12, respectively; the entries are obtained with, e.g.,
print("L*V\n", L*V)
L L*V
[[1 2] [[ 4 8]
[3 4] [15 20]
[5 6]] [30 36]]
V L*W
[[4] [[ 1 4]
[5] [ 3 8]
[6]] [ 5 12]]
W np.transpose(L)
[1 2] [[1 3 5]
[2 4 6]]
The determinant of matrix N is 1·4 – 2·3 = −2. Python deviates from that value
in the 16th decimal. This is because the calculations are performed in the binary
system.
The operator @ stands for matrix multiplication. The matrix product of a matrix
with its inverse yields the unit matrix (see lines 18 to 20 in Table 2.16). The differ-
ence to the algebraic multiplication with the operator *, operating element-wise, is
demonstrated in Table 2.17, L*W vs. L@W.
2.5 Matrix Calculations in Excel and Python 49
O
[[4 3] N @ I #Mathematical matrix multiplication
[2 1]] [[ 1.00 0.00]
[ 0.00 1.00]]
I
[[-2.00 1.00]
[ 1.50 -0.50]]
Table 2.17 Array multiplication with * versus mathematical matrix multiplication with @
L L*W
[[1 2] [[ 1 4]
[3 4] [ 3 8]
[5 6]] [ 5 12]]
W L @ W
[1 2] [ 5 11 17]
9 Shape(L) = (3, 2), shape(W ) = (2,), shape(L*W ) = (3, 2), shape (np.transpose(L)) = (2, 3).
10 N@I is a diagonal matrix, shape = (2, 2).
11 Shape(L) = (3, 2), shape(W ) = (2,), shape(L@W ) = (3,).
50 2 Data Structures, Excel and Python Basics
Figure 2.15 shows four parabolas with their vertices marked with diamonds and
their upper envelope always running on the, at the respective position, top parabola.
The spreadsheet for producing this figure is given in Fig. 2.16 (S). It is briefly
described in the following section on the basis of Exercise 2.2. The corresponding
10 J K L M
(xV, yV)
y yA 17 -10.0 2.4 4.8 -96.4
8 yB 18 -8.8 2.4 4.7 -94.8
yC 19 -7.7 2.3 4.7 -93.3
yD 177 -330.0 5.0 1.0 -0.4
6 yMax
0
-8 -4 0 x 4 8
Fig. 2.15 a (left) Four parabolas for the parameters specified in Fig. 2.16 (S). b (S, right) Coordi-
nates for the four parabolas obtained with a matrix formula, J17:M177 = [{=a + b*x + c_*xˆ2}]
A B C D E F G H
1 xV -5 -2 4 5
2 yV 8 1 0.5 5 (xV, yV)
3 c_ -2 0.04 0.03 -0.6
4 b -20 0.16 -0.24 6
5 a -42 1.16 0.98 -10
6 dx 0.1
Fig. 2.16 (S) Four parabolas defined by the parameters in row vectors in rows 1 to 5; the formula
reported in G7 is a better alternative for the formulas in B7:E7
2.6 Four Parabolas and Their Upper Envelope 51
Python program is developed in detail in Sect. 2.6.4, serving as the basic exercise
in Python programming.
Figure 2.16 (S) shows a spreadsheet tabulating four parabolas for the values of x in
A9:A169 and the parameters in rows 1 to 5, valid for the y-values of the parabolas
in the respective column.
Question
What are the formulas for b in B4:E4 and a in B5:E4 of Fig. 2.16 (S)?12
The task is to write a formula into cell B9 with relative and absolute addresses
so that it can be copied into the whole range B9:E169 to produce the values of
the four parabolas yA , yB , yC , yD with the parameters c_, b, and a in range B3:E5.
Parameter vector c_ is specified directly by entering the desired values into B3:E3.
Parameter vectors b and a are obtained from the coordinates of x V and yV of the
vertex with the same formula as in Fig. 2.2 (S), realizing Eq. 2.3. In column F,
the maximum yMax of the four parabolas is built, giving their upper envelope. The
result is shown in Fig. 2.15a.
The column vector x is defined in A9:A169 in 161 steps of dx = 0.1. The
values of the four parabolas are then generated by typing the equation reported in
B7 into B9 and copying right and down to E169, the range spanned by x and the
row vectors a, b, c_. The resulting curves are shown in Fig. 2.15a, together with
the vertices (x V , yV ) and the curve yMax calculated in column F.
Table 2.18 Specification of the coefficients of 4 parabolas and composition of their labels
1 import numpy as np
2 #Specify position (xV,yv) of vertices!
3 xV=np.array([-5.0,-2.0,4.0,5.0])
4 yV=np.array([ 8.0, 1.0,0.5,5.0])
5 #Define coefficients of y=a+bx+cx³
6 c=np.array([-2.0,0.04,0.03,-0.6])
7 b=-2*c*xV
8 a=yV+c*xV**2
9 #Compose labels for the figure
10 lbl_1=str(a[0])+"+"+str(b[0])+"⋅x+"+str(c[0])+'*x²'
11 lbl_2=str(a[1])+"+"+str(b[1])+"⋅x+"+str(c[1])+'*x²'
12 lbl_3=str(a[2])+"+"+str(b[2])+"⋅x+"+str(c[2])+'*x²'
13 lbl_4=str(a[3])+"+"+str(b[3])+"⋅x+"+str(c[3])+'*x²'
14 print(lbl_1)
15 -42.0+-20.0⋅x+-2.0*x²
Questions
What are the formulas to get a and b from the coordinates of the vertex?13
What are the shapes of c, b, and a in Table 2.18?14
The next cell contains that part of the main program that reproduces the def-
initions and the data structure of the spreadsheet solution. The parameters x V ,
yV and a are specified exactly as before in numerical row vectors with four ele-
ments. The parameters b and c are obtained with the formulas mentioned above
(in Sect. 2.2.1), also as row vectors.
In the third cell, the labels of the four curves in Fig. 2.15 are composed.
Remember: the concatenation operator in Python is + (contrary to & in
excel), and numerical values have to be converted explicitly into a string, e.g.,
str(a[0]). They are used as the legend in the chart.
In Table 2.19, the column vector x, representing the independent variable, is
constructed. We could achieve that in one statement:
x = np.array ([np.linspace(0.0,1.0,11)]).transpose(1,0)
but use the three lines in the first cell instead, so as to make the construction
clearer. First, a simple list x S with 161 items equally spaced between −8 and 8,
including 8 as the last element, is generated. In the output (bottom) cell, it shows
up as a 1-dimensional row vector. To get a column vector, we first have to make
it a matrix (2-dimensional array) x R by defining an np.array with just one row
showing up in the output cell as a list within double square brackets [[…]]. This
matrix is transposed, with x = xR.transpose(1,0), indicating that the axes
0 and 1 are interchanged, now yielding a matrix x with just one column. This is
the desired column vector.
In Table 2.20, a two-dimensional array named G is constructed with G = a
+ b*x + c*x**2. It has the same shape and the same content as the range
B9:E169 in Fig. 2.16 (S). The four columns of array G get additional names yA to
yD , as in the spreadsheet. Remember: Python is zero-addressing; first index is 0.
In column F of Fig. 2.16 (S), we have calculated the maximum of the four
parabolas for each value of x. The same is achieved in Python with the statement
54 2 Data Structures, Excel and Python Basics
Table 2.20 Creating the y values of all 4 parabolas; G[:,0] indicates first column
1 G=a+b*x+c*x**2 5 print(G,'\n')
2 yA=G[:,0] #1st col. 6 print(yA)
3 yB=G[:,1] #2nd col. 7 yMax=G.max(axis=1)
4 yC,yD=G[:,2],G[:,3] #Max. across the columns for every x
8 print(yMax)
G
[[ -10.0 2.4 4.8 -96.4]
[ -8.8 2.4 4.7 -94.8]
...
[-324.8 4.9 1.0 -0.0]
[-330.0 5.0 1.0 -0.4]]
Question
15The statement plt.legend() calls a function, and function identifiers have to be supplemented with
parentheses.
56 2 Data Structures, Excel and Python Basics
Questions
Are the values for (x Min , yMin ) and (x Max , yMax ) consistent with the prespecified
values of the vertices (x V , yV )? Compare with Fig. 2.17!16
16 The four vertices show up as the 1st and 4th point in (x Max , yMax ) and the 2nd and 3rd point in
(x Min , yMin ). The other points are at the boundaries of the x range.
2.6 Four Parabolas and Their Upper Envelope 57
axis = 0
matrices
G[:,0]
axis = 1
The indexing of rows, columns, and axes seems not to be very intuitive.
Therefore, we illustrate it in Fig. 2.18. G[0,:] addresses the first row: axis = 0
means across the rows yielding a number of values corresponding to the num-
ber of columns. G[:,0] addresses the first column, axis = 1 means across the
columns yielding a number of values corresponding to the number of rows , in
our example for every value of x.
Vibrations of a string
Mag Take a look at the microphone signal in Fig. 2.19a! How would you
describe the signal?
Mag Yes and no. Yes, there is a fundamental frequency of repetition, and no,
sound is not fidgeting; it is composed of harmonics.
Figure 2.19a is the record of the sound of a guitar string. What is the
fundamental frequency in this case?
58 2 Data Structures, Excel and Python Basics
Fig. 2.19 a (left) Oscilloscope image of a microphone signal of a vibrating guitar string as a func-
tion of time (courtesy of Norbert Renner, University of Duisburg-Essen), time unit of the grid =
5 ms., b (right) Fundamental) and first harmonic oscillations (first overtones) of a reed of length l
fixed on one end (top), l = (λn /4)·(2n + 1) and a string of length l fixed on both ends (bottom), l
= (λn /2)·(n + 1); n indicates the number of internal nodes
Mag Let’s consider the vibrations of a guitar string. How does a string vibrate?
Mag Yes.
Figure 2.19b suggests that there are only discrete values of the wavelength with
which a string can vibrate. You can determine them by considering the boundary
conditions.
Tim The sine must go through zero, where the string is clamped.
Mag Exactly. The zero-crossings are called nodes. The boundary conditions
require that the string length l be a multiple of half the wavelength, l = (n + 1) ·
λn /2, n = 0, 1, 2, … The possible frequencies are multiples of the fundamental fre-
quency c/(2l)), where c is the velocity of sound on the string. The corresponding
vibrations are called harmonics. The mode with n = 0 is called the fundamental
mode. Now, let me repeat my question: How do you now describe the microphone
signal?
2.7 Sum of Four Cosine Functions 59
3 3
ω0=1, all ω0=0.5, odd
2 2
y y
1 1
0 t 0 t
0 10 20 30 0 10 20 30
-1 -1
-2 -2
Fig. 2.20 a (left) Sum of a fundamental tone with ω0 = 1 and three overtones at 2 x, 3 x, 4 x ω0 .
The time unit is 1 s when the values for ω are given in 1/s. b (right): Sum of a fundamental tone
with ω0 = 0.5 and three overtones with 3 x, 5 x, 7 x ω0 . Time unit = 1 s
Mag Right, it is the sum of the allowed vibrations with individual amplitudes.
In the case of a string clamped on both ends, the frequencies are multiples (1, 2,
3, …) of the fundamental frequency, f n = f 0 · (n + 1), or correspondingly for the
circular frequencies ωn . In cases in which one end of the vibrating medium is free,
such as, for example, in a saxophone reed clamped on one side, the frequencies
are odd multiples (1, 3, 5, …) of the fundamental frequency, f n = f 0 · (2n +
1). Examples are given in Fig. 2.20. There, you see the sum of four cosines with
a fundamental frequency ω0 = 1 and multiples 2ω0 , 3ω0 , 4ω0 (Fig. 2.20a) or
multiples 3ω0 , 5ω0 , 7ω0 (Fig. 2.20b).
Mag Yes, but in the more general context of summing up four cosine functions
whose frequencies satisfy certain conditions.
In this exercise, we shall use the form y = A·cos(ω · t + φ) with the parameters
amplitude A, circular frequency ω, and zero phase φ. We set up a calculation
model with four cosines, with their circular frequencies specified by a fundamental
frequency and either three multiples thereof (to get harmonics) or three more
frequencies at a distance of dω (to get beats or demonstrate the addition theorem
of cosines).
0 0
0 10 20 30 0 10 20 30
t t
-2 -2
-4 -4
Fig. 2.21 a (left) Beats arising from four cosine functions; the initial angular frequency ω0 = 4,
the width in the frequency range ω = 3, b (right) another beat with initial angular frequency ω0
= 2, and width in the frequency range ω = 1
frequencies. As a result, the signal clusters together into wave packets. In Fig. 2.21,
they are separated by black markings. We shall determine the width of such wave
packets based on an uncertainty rule.
Mag The amplitudes of the cosine components of a beat are not freely chosen,
but rather derived from binomial coefficients. How do you get such coefficients?
Alac Well, with Pascal’s triangle. Why so precise rules for the amplitudes?
Can’t we choose them as we like?
Mag With said choice of amplitudes, we get a clear picture of the beat in the
time domain, with the envelope being similar to a bell curve. Initially, you are to
change only the lowest frequency ω0 and the spectral width ω and observe the
function’s behavior in the time domain. Later, you may select the amplitudes at
will and see whether the observed regularity is preserved.
Task You are to insert points into the diagrams at the position of the nodes
of the oscillations. To do so, you may create formulas that specify the marker
points’ coordinates when the width of a packet t and an initial time offset t 0 are
specified. In a spreadsheet, it would be best for you to use sliders that change the
coordinates so that the points in the diagram lie precisely on the nodes of the beat.
Mag Have you figured out the rule for the width of a wave packet?
Tim The time interval t for a packet is proportional to the inverse of the
spectral width t = 3π/ω = 1.5/ f . The width is certainly smaller, because
the signal goes to zero well before the marker points.
2.7 Sum of Four Cosine Functions 61
Tim I’ve memorized it: “the mean times half the difference.”
Cos plus Cos yields the mean, times half the difference.
Mag This broom rule is a useful mnemonic if you can reconstruct the full form
from it:
x+y x−y
cos(x) + cos(y) = 2 · cos cos (2.8)
2 2
Alac I’m certainly never going to forget such a crazy saying. The first cosine
in the product has the average of the two primary cosines, the second half the
difference.
2
y
1
0
0 10 20 30
-1
t
-2
w.0=2; Delta.w=1 w=w.0+dw/2 w=dw/2 black diamonds
-3
Fig. 2.22 Thick gray curve: the sum of two cosine functions with the frequencies ω1 and (ω1 +
ω); black dotted curve: cosine function with the mean frequency; black solid curve: envelope
with half the difference of the frequencies
Overtones
The problem of generating overtones (higher harmonics) is a special case of the
general task. The functions are to be calculated within a matrix range of, in our
2.7 Sum of Four Cosine Functions 63
A B C D E F G H I J
1 =w.0 =2*w.0 =3*w.0 =4*w.0 , all
2 A 0.23 0.75 0.63 0.72
3 w 1.00 2.00 3.00 4.00 w.0 1.00 ω0
4 phi 0 0 0 0 ω0=1, all =J3&"="&w.0&G1
5 0.04
i) i) i) i)
t+ph (w*t+ph (w*t+ph (w*t+ph 9:E9)
$A$5 O S(w*
O S O S O S (B
6 =A8+ =A*C =A*C =A*C =A*C =SUM
7 t c.1 c.2 c.3 c.4 sumC
8 0.00 0.23 0.75 0.63 0.72 2.33 Write formula into B8!
9 0.04 0.23 0.75 0.63 0.71 2.31 Dragg into B8:E808!
808 32.00 0.19 0.29 -0.11 -0.50 -0.13
Fig. 2.23 (S) Four cosine functions c1 to c4 are calculated in the matrix range B8:E808 (below ),
the cells of which always contain the same formula. The four functions are summed up in column F.
The formulas in the columns are displayed in row 6 in oblique orientation. The time t (the indepen-
dent variable) is defined as column vector A8:A808 (left of ) with the name t. The amplitudes A,
the angular frequencies ω, and the zero phases ϕ are defined as row vectors B2:E2, B3:E3, B4:E4,
respectively (above ). Here, the angular frequencies are multiples of the fundamental frequency
ω0
particular case, width 4 (number of functions) and height 801 (number of data points)
. We write the desired values for amplitudes A, circular frequencies ω, and zero phase
φ in rows above the matrix range and the independent variable t in a column to the
left of the matrix range.
You are to organize the worksheet calculation such that you need to write a formula
into only one cell that is then copied to the entire calculation area (here B8:E808)
for the four functions by dragging down and to the right.
Beats
The parameters for beats are specified in H2:I4 of Fig. 2.24 (S), namely, the first
frequency ω1 and the frequency range ω, from which dω, the distance between
neighboring frequencies, is obtained. The amplitudes A are binomial coefficients (up
to a factor of 2) and can be determined using Pascal’s triangle.
Cosine identity
Figure 2.25 (S) presents a spreadsheet layout for obtaining the cosine identity shown
in Fig. 2.22, the same as for beats. Here, however, c1 = c3 ; c2 = c4 , and all amplitudes
A B C D E F G H I J
1 =w.0 =B3+dw =C3+dw =D3+dw =Delta.w/3
2 A 0.5 1.5 1.5 0.5 Delta.w 1.00
3 w 2.00 2.33 2.67 3.00 dw 0.33
4 phi 0 0 0 0 w.0 2
5 0.04 w.0=2; Delta.w=1
Fig. 2.25 (S) Parameter set for a sum of two cosine functions; c1 = c3 ; c2 = c4 ; H5 displays the
legend for one of the curves in Fig. 2.22, while there are formulas in K6:L6 for the angular fre-
quencies of the fast oscillation and the envelope according to the sum formula, Eq. 2.8, applied in
K8:K808 and L8:L808; the amplitudes are taken from cell $F$8. K4 and L5 contain the legend for
the other two curves in Fig. 2.22
are equal (= 0.5). The legends for the fast oscillation (with medium frequency) and
the envelope (with half the difference frequency) are assembled in K1:L5.
Add Cosines
2.7 Sum of Four Cosine Functions 65
Table 2.23 Main program for calculating 4 cosine functions and plotting their sum sumC ;yMin ,
yMax , and FigName are specified in Tables 2.25–2.27
1 t0=np.linspace(0,32,801)
2 t1=np.array([t0])
3 t=t1.transpose(1,0)
4 c=A*np.cos(w*t+phi)
5 sumC=np.sum(c,axis=1)
6
7 FigStd('t',0,30,10,'y',ymin,ymax,dy)
8 plt.plot(t,sumC,'k-',label=lbl_0)
9 plt.legend(loc=0,fontsize=11) #loc = 0, best free place
10 plt.savefig(FigName) #Store figure as a file!
Main program
The main program for calculating the four cosine functions and plotting their sum is
given in Table 2.23. We assume that we have imported the two libraries numpy and
matplotlib.pyplot under the shortcuts np and plt, as well as the function
FigStd described in Sect. 2.4.5. This shall be done in all future programs and shall
not be reported explicitly. The coefficients A, ω, φ, as well as the label lbl 0 for the
curve and the name FigName of the file name under which the figure is saved, have
to be specified ahead of time. Figures 2.20, 2.21, and 2.22 all have different scaling
of the y axis, so that the corresponding axis parameters ymin , ymax , dy must also be
specified in the subtask cells before calling FigStd.
This is done in the program cells for the different situations: harmonics (Table
2.25), beats (Table 2.26), and the addition of cosines (Table 2.27).
In order to get the same data structure as in the spreadsheet solution, we have
to construct t as a column vector. We first define our discrete time points accord-
ing to column A in Fig. 2.23 (S). This is done with t0 = np.linspace(0,
32, 801) specifying that the range from 0 to 32 is scanned with 801 equidis-
tant points. The endpoint 32 is included by default. If we do not want that, we
have to include “endpoint = False” as an entry behind the three positional
arguments: np.linspace (0, 32, 801, endpoint = False), but we
won’t do that here.
The variable t 0 is now a row vector. To make it a column vector, we first
transform it into a two-dimensional array by including the array t 0 within square
brackets as the argument for t1 = np.array(), with one row only (shape =
(1, 801); axis 0 has one element, a list with 801 elements. We then transpose the
array between the two axes 1 and 0 by t1.transpose(1,0). The shape and the
first and last elements of the three vectors are reported in the second cell of Table
2.24. The column vector t has the same shape and contains the same numbers
as the variable t in A8:A808 of Fig. 2.23 (S). The same holds for the matrix c
66 2 Data Structures, Excel and Python Basics
Table 2.24 Second cell: data structure of the variables of the main program, printed with instruc-
tions similar to those in the first cell. Third cell: matrix of the y values of four cosines
print("t0,
1 shape:", np.shape(t0))
print(t0)
2
t0, shape: (801,) c, shape: (801, 4)
[ 0.00 0.04 ... 31.96 32.00] [[ 0.23 0.75 0.63 0.72]
[ 0.23 0.75 0.63 0.71]
t1, shape: (1, 801) ...
[[ 0.00 0.04 ... 31.96 32.00]] [ 0.20 0.35 -0.04 -0.41]
[ 0.19 0.29 -0.11 -0.50]]
t, shape: (801, 1)
[[ 0.00] sumC,shape: (801,)
[ 0.04] [ 2.33 2.31 ... 0.10 -
... 0.13]
[ 31.96]
[ 32.00]]
Question
Which parameters relevant in the main program in Table 2.23 have to be spec-
ified in the sub-programs executed immediately before the main program?17
17(1) Labels that contain information on the characteristic frequency and frequency range. (2)
Scalings of the y-axis. (3) Name under which the resulting figure is stored. (4) Parameters A, w,
phi.
2.7 Sum of Four Cosine Functions 67
– In excel, the four column ranges get the names c.1, c.2, c.3, c.4, with which
they can be called.
– In Python, all four curves are stored in the columns of the two-dimensional
list c and can be called by c[:,i] with i = 0, 1, 2, 3.
Harmonics
In Table 2.25, we specify the harmonics’ parameters in the same way as in the
spreadsheet, in the first cell for all multiples (of ω0 = 1) and in the second cell
for odd multiples of the lowest frequency ω0 = 0.5. The values for amplitude A,
circular frequency ω, and zero phase φ are specified as vectors, in Python realized
as lists (characterized by square [] brackets). From these parameters, we compose a
label lbl 0, later to be reported in the figure showing the result of our calculation.
Furthermore, we specify in FigName the name under which the corresponding chart
is to be stored. In lines 5 and 11, we specify the scale of the y-axis according to
Fig. 2.20.
When producing labels, the following differences between excel and Python
have to be taken into account:
2.7 Sum of Four Cosine Functions 69
excel (G4 in Fig. 2.23 (S)) A1 = [=”w0 & w.0 & “, all”]
The concatenation operator is & (ampersand), and numeric values are automat-
ically converted into a string.
Python (Table 2.25):lbl_0 = “ω0” + str(w[0]) + “, all”
The concatenation operator is + ; numeric values have to be converted explicitly
into a string. In both applications, text is enclosed in quotation marks.
When numbers x have to be rounded to n decimal places, we can use
round(x;n) in excel and np.round(x,n) in numpy.
2.8 Questions
Cell references
1. What does the broom rule Ψ The dollar makes it absolute tell us?
2. What formula must be written in cell B5 of Fig. 2.27 (S), with absolute and relative
references, so that copying this formula into the range B5:E205 creates four sine
functions?
3. (Python) Specify arrays A, ω, t, so that an instruction C = A*np.cos(ω*t)
generates the four cosines C a , C b , C c , C d of Fig. 2.27(S) in one matrix C. How
do you replace the # in F sum = np.#(C, axis = #) to get the sum of the four
cosines?
A B C D E F G H
1 1 2 3 4 Amplitude
2 4 3 2 1 Angular frequency
3
4 Ca Cb Cc Cd
5 0 =A*COS(w*t)
6 1
7 2
205 200
Fig. 2.27 (S) structure of a spreadsheet for displaying four cosine functions
A B C D E F
1
2
a
m
2.00
1.00 10.00 y=1x+2
3 y=1x+2 8.00
4 x y
6.00
5 1.00 3.00
6 2.00 4.00 4.00
7 3.00 5.00 2.00 y=1x+2
8 4.00 6.00
9 5.00 7.00 0.00
10 6.00 8.00 0.00 2.00 4.00 6.00 8.00
Fig. 2.29 a (left, S) A straight line is defined in the spreadsheet and displayed in the diagram. b
(middle) Standard chart of the data in a. c (right) The design/select data/edit dialog box,
which is used to insert the data series x, y from a into the diagram
Arrays in Python
Diagrams
In Fig. 2.29a (S), you see data series x and y, in Fig. 2.29b, the corresponding chart,
and in Fig. 2.29c, the dialog box with which the data series was inserted into this
diagram.
11. Which spreadsheet ranges contain series name, series x values, and series
y values?
12. How do you create the expression y = 1x + 2 in the spreadsheet, and how do
you insert it into the chart in Fig. 2.29b as a legend?
13. (Python) Below, you find a program for plotting a chart similar to the one
in Fig. 2.29a, additionally with labels ‘x’ for the horizontal and ‘y’ for the
vertical axis. Fill in the missing entries! The graph should be a straight line with
diamonds, all black.
2.8 Questions 71
A B C D E F
27 1000 5.00
A B C D E F
27 0 -5.00
FigStd( … )
x=[ … ]
y=[ … ]
plt.plot(x,y, … )
14. (Python) How do you produce the string y = 1x + 2 when a = 2.0023 and m
= 1.001 are specified?
15. (Python) How do you produce a string 3.0*exp(t/-30.0) when A = 3.001 and
t A = -30.0 are specified?
Polar coordinates
20. The coordinates of a circle are best given in polar coordinates with the angle φ
and the radius r. How do you get the cartesian coordinates x and y needed for
an xy diagram?
The figure in Fig. 2.31a is generated by the spreadsheet organization in Fig. 2.31b
(S). Cells C11 and E11 have the names shown to their left. The column area B14:B26
gets the name phi.
Apply names for cell ranges, if defined, in the answers to the next three questions!
15
y
B C D E
10 11 dPhi 0.5236 rK 10
12
5 13 phi x y
14 0.00 10.00 0.00
0 15 0.52 8.66 5.00
-15 -10 -5 0 5 10
x
15 16 1.05 5.00 8.66
-5 17 1.57 0.00 10.00
24 5.24 5.00 -8.66
-10
25 5.76 8.66 -5.00
26 6.28 10.00 0.00
-15
Fig. 2.31 a (left) Representation of a circle with 12 line segments; b (right, S) Coordinates for the
circle in a
rK=10
phi = np.arange(0,#,dPhi)
x=rK*#
y=rK*#
FigStd(#,#,#,#,#,#,#,#)
Cosine functions
Figures 2.32a and b display two cosine functions.
15 15
CosA CosB
10 10
y y
5 5
0 0
-10 0 10 20 t 30 -10 0 10 20 t 30
-5 -5
-10 -10
-15 -15
Fig. 2.32 a (left) Cosine function CosA . b (right) Cosine function CosB
2.8 Questions 73
26. What are the amplitudes and cycle times of the functions CosA and CosB shown
in Fig. 2.32?
27. What are the angular frequencies of the two functions shown in Fig. 2.32?
28. What are the overtones to the fundamental with the frequency f = 100 Hz?
29. How do you interpret the broom rule: Ψ Cos plus Cos = mean value times half
the difference?
30. A second cosine function is added to a cosine function with f = 100 Hz. What
frequency must the second cosine function have to produce a beat of 1 Hz?
Formula Networks and Linked
Diagrams 3
Solutions of Exercises 3.2 (Excel), 3.3.1 (Python), 3.3.5 (Python), and 3.4 (Excel)
can be found at the internet address: go.sn.pub/McoItP.
3
A B C D E F G
y [m]
1 Designation Name Value Unit x y
2
2 Width w 2 m -1 -1.5
3 Height h 3 m -1 1.5
1 4 1 1.5
5 Area A 6 m² =h*w 1 -1.5
0 6 -1 -1.5
-3 -2 -1 0 1 2 3
-1 x [m]
-2
-3
Fig. 3.1 a (left) A rectangle around the origin of the coordinate system b (right, S) Calculation of
the area of a rectangle; Independent variables in B2:C3; coordinates x, y for the representation in
a are calculated in columns F and G. b (right) Spreadsheet solution; coordinates for the rectangle
shown in a, symmetrical to the origin of the coordinate system
For this purpose, a system of formulas has to be built using the results of other
formulas. The spreadsheet set-ups and the Python programs should reflect the line
of thought and be easily traceable, even weeks later.
Python program
In Python, every object has to have an identifier (a name) so that, from the outset, the
implementation is similar to mathematical formulas. For Fig. 3.1a, we apply Table
3.1.
Question
Mathematical functions
In this chapter, we apply four mathematical functions:
We construct the image point that a lens generates from an object point with
three characteristic rays, applying the general imaging equation valid for both
a focusing lens and a diverging lens. Lens equation with plus and minus.
We draw the bundle of rays through the lens, which actually contributes to
the image point. After this exercise, the reader should be able to master the
straight-line equation blindfolded.
y(x) = y1 + m · (x − x1 ) (3.1)
or
y(x) = y2 + m · (x − x2 ) (3.2)
y2 − y1
m= (3.3)
x2 − x1
A B C D E F 6
1 x.1 -1.91 209
2 y.1 3.00 y.1; y.2 y.1; y.2
3 4 y.3
4 x.2 2.00 Straight line
5 y.2 -2 200 2
6
7 m -1.28 =(y.2-y.1)/(x.2-x.1)
8 x.3 1.63 563 0
9 y.3 -1.53 =y.2+m*(x.3-x.2) -4 -2 0 2 4
10
11 Straight line -2
12 -10 13.35 =y.2+m*(B12-x.2)
13 10 -12.23 =y.3+m*(B13-x.3)
-4
Fig. 3.2 a (left, S) Spreadsheet layout for the diagram in b; the values of x 1 and y1 are obtained
by means of sliders. b (right) The point “y.3” is to lie on a straight line given by the two points
“y1; y2”
We demonstrate Eq. 3.1 through the spreadsheet in Fig. 3.2a. The y-value y1 of
the first and the x-value x 2 of the second defining point are directly written into
cells B2 and B4, respectively. The associated values x 1 and y2 in B1 and B5 are
determined using the two sliders in D1:F1 and D5:F5. From these coordinates, the
slope m is calculated in B7 with Eq. 3.3. The x value x 3 of the third point in B8
is selected with the slider in D8:F8, and the corresponding y-value y3 in B9 is
obtained with the straight-line equation Eq. 3.2. These three points are represented
in Fig. 3.2b with diamonds.
In range B12:C13 of Fig. 3.2a (S), the straight-line coordinates are calculated
for x values −10 to 10 extending beyond the range of the x-axis in Fig. 3.2b so
that the straight line goes through the whole picture. The straight line is entered
into the figure with series x- values: (B12:B13), series y- values: (C12:C13).
Questions
10
0
-20 -16 -12 -8 -4 0 4 8 12 16 20
Focal points
Rays -5
Object arrow
Image arrow
-10
Fig. 3.3 Image construction for a focusing lens with parallel, central and focus rays
In C12 and C13, the y coordinates of the straight line are calculated with
two different formulas. Why do both formulas describe the same straight line?5
Question
5 The slopes are the same for both straight lines. As reference points, (x 2 , y2 ) has been chosen for
C12 and (x 3 , y3 ) for C13. As both lie on the straight line, the third point also lies on the same line.
6 The parallel ray runs from the object point parallel to the x-axis (that is, the optical axis) up to x
10 10
5 5
0 0
-10 -5 0 5 10 -10 -5 0 5 10
Focal Focal
points -5 points -5
Rays Rays
-10 -10
Fig. 3.4 a Converging lens, a (left) real inverted image for an object distance outside double
the focal length. b (right) Virtual, upright image for an object distance within the focal length;
corresponds to a look through a magnifying glass from the right
Mag Do you remember how to determine the image point of an object point
geometrically?
Alac Yes, as in Fig. 3.4a. We draw two rays starting from the object point, one
through the center of the lens and another parallel to the optical axis up to the
principal plane and then through the focal point on the right side of the lens. The
image point is where the two rays intersect.
Mag So you can do it. Your construction is valid for a converging lens. How-
ever, a lens has two focal points, one on the image-side and another one on the
object-side. In the image construction just described, you have exploited the fact
that all rays incident parallel to the optical axis go through the image-side focus
after having passed through the lens.
Tim We have often drawn a third ray from the object point through the focal
point on the left of the lens, which imagine is called the object-side focal point.
After passing through the lens, this ray is parallel to the optical axis and then
passes through the image point.
Mag Yes, all three construction rays intersect at the image point, as in Fig. 3.4.
That’s what we want to reproduce with our exercise.
In Fig. 3.4, the image construction for a converging lens using the principal rays
(parallel, central, and focal) is represented in a Cartesian coordinate system. By
convention, the optical axis is the x-axis. The optical center and the lens’s principal
plane are respectively located in the origin of the coordinate system in the plane
x = 0. We take it as given that the object is always to the left of the lens, i.e., the
object distance is always negative.
82 3 Formula Networks and Linked Diagrams
We know (from physics courses) that an inverted real image is formed to the
right of the lens when the object distance is bigger in magnitude than the focal
length (Fig. 3.4a). If the object distance is smaller in magnitude than the focal
length, the result is an erect virtual image to the left of the lens (Fig. 3.4b). The
general imaging equation for optical lenses considers these relationships by sign
conventions for the variables that enter the imaging equation, Eq. 3.4.
1 1 1
+ = (3.4)
xO xI f
where x O and x I are the object and the image distance, respectively, and f is the
focal length.
Mag This equation is useful only for handmade geometric constructions. For
an analytical calculation, we must use a more accurate one, namely, Eq. 3.5, in
which two modifications with respect to Eq. 3.4 have been introduced. Now, f I
is the image-side focal length, x I the image distance, and x O the object distance.
The object distance is, in principle, negative, because the object is, by convention,
placed to the left of the lens.
Alac With the old equation, we always got the correct values for image distance
and image size.
Mag Yes, the absolute values are calculated correctly. However, no signs, plus
or minus, are considered. Let’s adopt the more general notation. The object dis-
tance x o is negative if the object is to the left of the lens. The image is often upside
down. This is automatically considered in Eq. 3.6, which calculates the image size
yI from the object size yO .
Furthermore, Eqs. 3.5 and 3.6 are also valid for a diverging lens if a negative
image-side focal length is introduced, f I < 0.
3.2 Image Construction for Focusing and Diverging Lenses 83
1 1 1
− + = (3.5)
xO xI fI
The x-axis is the optical axis. The principal plane of the lens is in the
plane x = 0; the object distance x O is negative. The image-side focal length
f I is positive for converging lenses and negative for diverging lenses. The
image distance x I may result positive or negative. The imaging scale is
yI xI
= (3.6)
yO xO
with yO being the object size and yI the image size that can be positive
or negative.
Converging lens
In Fig. 3.4, you see the usual image construction for a focusing lens (f I > 0) employing
parallel, center, and focus rays.
Diverging lens
For the image construction of a diverging lens, you can use the same spreadsheet
calculation or Python program as for a converging lens. You only have to enter
a negative image-side focal length f I . Figure 3.5 shows two examples (obtained
from Table 3.3).
Mag In your geometric ray constructions, you did not draw the cross-section of
the lens. What can you say about the lens?
Alac In all cases, the center is thicker than the edge; otherwise, it would not be
a converging lens.
Tim The principal plane of the lens is located in the plane x = 0. The center of
the lens is at the origin of the coordinate system.
Mag How big should the diameter of the lens be, e.g., in Fig. 3.4?
84 3 Formula Networks and Linked Diagrams
Fig. 3.5 Imaging with a diverging lens, the geometric construction being the same as for a con-
verging lens, but with negative focal length (f I < 0) (drawings obtained with the Python program
in Table 3.4). a (left) upright image for an object distance larger than the focal length. b (right) As
with a, but for an object distance smaller than the focal length
Table 3.2 Specifications for an image construction with a converging lens, resulting in a figure
similar to Fig. 3.3
6 #Converging lens
7 fI=6.0
8 xO=-15
9 yO=6
10 xMin, xMax, Dx = -20, 20, 5 #Scaling of figure axes
11 yMin, yMax, Dy = -10, 10, 2.5
12 FigName='Converging lens' #File name in plt.savefig()
Table 3.3 Specifications for image constructions with a diverging lens, resulting in Fig. 3.5
1 #Diverging lens, Object beyond focal length
2 fI=-6
3 xO=-10
4 yO=12
5 xMin, xMax, Dx = -12, 12, 4
6 yMin, yMax, Dy = -8, 16, 4
7 FigName='Diverging lens, outside' #In plt.savefig()
8 #Diverging lens, Object within focal length
9 fI=-6
10 xO=-5
11 yO=12
12 xMin, xMax, Dx = -12, 12, 4
13 yMin, yMax, Dy = -8, 16, 4
14 FigName='Diverging lens, inside' #In plt.savefig()
3.2 Image Construction for Focusing and Diverging Lenses 85
Alac I would draw the lens from y = −7 to y = 7 so that the three constructing
rays pass through the lens. The diameter would be roughly the same as those of
the lenses used for lecture experiments.
Mag Be cautious; think of cameras! In that case, the lens diameter is much
smaller than, for example, the elephant you are photographing.
Tim That’s right. But does it mean that the construction rays do not go through
the lens?
Mag They don’t, indeed. They exist only in thought and on paper. Which rays
actually do contribute to the image point for a camera lens?
Alac Only the central ray, or perhaps other rays that really do pass through the
lens.
Mag Yes, the image point is formed by a bundle of rays through the lens, as
we will draw now. The lens itself has not shown up in the figures presented so
far. The size of the lens is irrelevant to the image construction; only the principal
plane and the focal length are needed to construct the image point.
Figure 3.6 shows the ray construction of the image point, together with the
cross-section of the lens and eleven rays going from the object point through posi-
tions in the lens’s full span and finally focusing in the image point. The parallel
ray and the focus ray run outside the lens. They do not exist in physical reality.
Fig. 3.6 (By program in Tables 3.4 and 3.5) Light beam contributing to the image formation in
Fig. 3.3
86 3 Formula Networks and Linked Diagrams
x 2 + y2 = r 2 (3.7)
The parameters are the coordinates x 0 of the center point on the x-axis, the radius
the lens’s curvature, and the lens diameter DL = 2r L (in
r K of the circle determining
front view). With x0 = r Lens
2 − r L2 , we calculate the distance of the center of the
sphere, limiting the surface of the lens to the origin of the drawing. With
x= 2
r Lens − y 2 − x0 , (3.8)
we get the x-coordinate for a given y-coordinate on the surface of the lens.
Three rays for the geometrical construction of the image, without prior knowledge
of the coordinates of the image point, are defined by f I and the object point from
which characteristic slopes have to be calculated.
Imaging equations
We calculate the ray path coordinates for imaging with a converging lens, and there-
with set up an image construction that should adapt automatically whenever the
parameters are changed. The coordinates of the three constructing rays’ defining
points are shown in Fig. 3.7 (S).
3.2 Image Construction for Focusing and Diverging Lenses 87
A B C D E F G H I J K L M
1 Specifications Rays
2 Image-side focal length fI 6.0 Central ray
3 Object distance xO -15.0 slope -15 =xO 6 =yO
4 Object height yO 6.0 0 =0 0 =0
5 Imaging equation mCen -0.4 20 -8 =mCen*J5
6 Image distance xI 10.0 =(1/fI+1/xO)^-1 =yO/xO Parallel ray
7 Image height yI -4.00 =yO*xI/xO -15 =xO 6 =yO
8 0 =0 6 =yO
9 Focal points 6 =fI 0 mPar -1 20 -14 =yO+mPar*J9
10 -6 =-fI 0 =-yO/fI Focal ray
11 Object arrow -15 =xO 0 -15 =xO 6 =yO
12 -15 =xO 6 =yO -6 =-fI 0 =0
13 Image arrow 10 =xI 0 =0 mFoc -0.67 0 -4 =yO+mFoc*-xO
14 10 =xI -4 =yI =yO/(xO+fI) 20 -4 =L13
Fig. 3.7 (S) Imaging equation for a converging lens; the quantities related to the object and the
image are designated with the indices O and I. x = 20 in column J indicates the right border of
Fig. 3.3
The five parameters (focal length, object distance, and height, as well as the
image distance and height that are dependent on them) are provided with the names
in column B, with which they are entered into the image equations (B6:C7) and the
coordinates of the construction rays (J:M).
The coordinates of the focal, central, and parallel rays are introduced as data series
into the diagrams of Fig. 3.4a, b. We may enter the column range J3:J14 as series
x values and L3:L14 as series y values to get three separate straight lines,
because empty rows separate their coordinates. The designations Central ray, etc.,
are in column K, not in column J or column L.
Note that, in most cells, there are formulas. So, you cannot simply copy the
numbers from the spreadsheets displayed in this text. If you have done the
implementation correctly, images such as those in Fig. 3.4a, b should result, auto-
matically adapting whenever you change the parameters of focal length, object
distance, and object height.
Fig. 3.8 (P) Drawing rays from the object point through the lens to the image point; the coordi-
nates of the object point and the image point are read from column C of a spreadsheet, e.g., Fig. 3.7
(S). Dy is the distance between rays at x = 0
The fourth cell, represented in Tables 3.4 and 3.5, draws arrows representing
the image and the object, together with the image construction, with rays using
the specifications of one of the three initial cells that were run earlier.
The specifications in the three cells comprise not only focal length and the
coordinates of the object point, but also parameters for axis scaling of the image
and the name of the file wherein the image is to be stored. When the program in
one of these cells is run, the resulting parameters are valid for the following image
construction in Fig. 3.4. So, each of the three situations can be the basis of an
image.
Table 3.4 Drawing object and image arrows, function ArrowP presented at the end of this section
1 FigStd('x',xMin,xMax,Dx,'y',yMin,yMax,Dy,xlength=8)
2 plt.plot((-fI,fI),(0,0),'ko',
markersize=4,label="$f_I=$"+str(fI))
3 ArrowP((xO,0),(xO,yO),lw=1.5) #Object
4 lbl_1=r'$x_O$='+str(xO)+r', $y_O$='+str(yO)
#’$x_O$=’ becomes xO=
5 plt.text(xO,yO+0.5,r"($x_O$,$y_O$)",fontsize=10)
6 #Calculated image
7 xI=1.0/(1.0/fI+1.0/xO)
8 yI=yO*xI/xO
9 Arrow((xI,0),(xI,yI),lw=1.5,ls='--') #Image
10 lbl_2=(r'$x_I$='+str(round(xI,2))
11 +r', $y_I$='+str(round(yI,2))) #$x_I$ as xI in legend
12 plt.text(xI+0.5,yI+0.5,"($x_I$,$y_I$)",fontsize=10)
Table 3.5 Continuation of Table 3.4; setting up the image construction with the parameters spec-
ified in other cells without explicitly referring to the image point
13 #Parallel ray
14 xPar=[xO,0,1.5*xI]
15 mPar=-yO/fI #Slope in image space
16 yPar=[yO,yO,yO+mPar*xPar[2]]
17 plt.plot(xPar,yPar,ls='-',color='k',
18 lw=1,label=lbl_1)
19 #Central ray
20 xCen=[xO,0,1.5*xI]
21 mCen=yO/xO #Slope in whole space
22 yCen=[yO,0,mCen*xCen[2]]
23 plt.plot(xCen,yCen,ls='-',
24 color='k',lw=1.,label=lbl_2)
25 #Ray through object-side focus
26 xFoc=[xO,-fI,0,1.5*xI]
27 mFoc=-yO/(xO+fI) #Slope in object space
28 yg0=yO+mFoc*xO
29 yFoc=[yO,0,yg0,yg0]
30 plt.plot(xFoc,yFoc,ls='-', color='k',lw=1.)
31 plt.legend(loc=4,fontsize=10) #loc= 4 ,”Lower right”
32 plt.axis('scaled')
33 plt.savefig(FigName)
Table 3.6 User-defined function for drawing an arrow from point P0 to point P1 in the xy-plane
(construct explained in Chap. 4)
1 def Arrow(P0,P1,c="k",ls='-',lw=1,hw=0.4):
2 (x0,y0)=P0
3 (x1,y1)=P1
4 #c has to be given as c="k", not c='k'
5 plt.arrow(x0,y0,x1-x0,y1-y0,
6 length_includes_head=True,
7 head_width=hw,fill=False,
8 linestyle=ls, color=c,linewidth=lw)
in Table 3.2 or Table 3.3, whereas those of the image have to be calculated with the
image equation (lines 7 and 8).
The program reproduced in Tables 3.4 and 3.5 calculates with the values
obtained in one of the three cells in Tables 3.2 and 3.3. The ray constructions
in Fig. 3.1 are obtained with the specifications in Table 3.5. The arrows are drawn
with a function reproduced in Table 3.6 at the end of this section.
The three characteristic rays are drawn with the Python program in Table 3.5.
Table 3.7 Coordinates of the cross-section of a lens with radius r L of the disk and radius r O of
curvature of the surface of the lens
1 rL=6
2 rO = 10
3 xO=np.sqrt(rO**2-rL**2)
4 y=np.linspace(0,rL,3)
5 x=np.sqrt(rO**2-y**2)-xO
6 xf=np.flipud(x) #First becomes last
7 yf=np.flipud(y)
8 FigStd('x',-20,20,5,'y',-10,10,2.5,xlength=8)
9 xLens=np.hstack([ xf, x,-xf,-x]) #One long array
10 yLens=np.hstack([ yf,-y,-yf, y])
x [ 2.00 1.54 0.00]
y [ 0.00 3.00 6.00]
Table 3.8 Drawing a bundle of rays from the object point through the lens to the image point
11 #Bundle of rays through the lens
12 #Object point and image point are known.
13 nR=11 #Number of rays
14 rL=3 #Diameter of lens
15 x=np.zeros(3)
16 y=np.zeros(3)
17 (x[0], y[0])=(xO, yO) #Object point
18 (x[2], y[2])=(xI, yI) #Image point
19 x[1]=0
20 FigStd('x',-20,20,5,'y',-10,10,2.5,xlength=8)
21 plt.plot(xLens,yLens,'k')
22 Arrow((xO,0),(xO,yO),lw=1.5) #Object
23 Arrow((xI,0),(xI,yI),lw=1.5,ls='--') #Image
24 Dy=2*rL/(nR-1)
25 for i in range(nR): #Bundle of rays
26 y[1]=-rL+i*Dy #Position in lens
27 plt.plot(x,y,'k-',lw=0.5)
92 3 Formula Networks and Linked Diagrams
When a sound source (a “sender”) and a receiver move relative to air, the
receiver perceives a frequency that is different from the transmitted one. We
set up a formula for all cases of movements of the two agents on a straight
line. We determine the frequency trajectory recorded at a receiver off the
sender’s track.
When a sound source (in the following, designated as sender S) and a receiver R
are approaching or moving away from one another on a straight line, the receiver
perceives a frequency different from that emitted. In the following, we develop a
formula for the cases when sender and receiver move on the same straight line.
fR c ± vR
= (3.9)
fS c ∓ vS
The letters f, c, and v denote the frequency, the speed of sound, and the speed
(≥0) of the agents relative to air. The upper sign in the formula is valid when the
agents are approaching each other and the lower sign when they are moving apart.
Note, as a mnemonic, that, above the fraction bars, there are quantities with index R
and, below the fraction bars, quantities with index S, for both sides of the equation.
Doppler effect with plus and minus
It is best to consider which signs are to be used for every individual case. An
example: S → R →; the sender moves towards the receiver, and the frequency
increases (/(c − vS )); the receiver moves away from the sender (c − vR ), and the
frequency decreases; thus f R /f S = (c − vR )/(c − vS ).
Questions
How may Eq. 3.9 be simplified when the receiver is stationary and the sender
is approaching him?8
What frequency does the receiver hear when he travels at the same speed as
the sender, (a) in front of and (b) behind the sender?9
fR c − |v R |
= (3.10)
fS c − |v S |
After overtaking, it is the other way around: The sender is moving away, the
receiver is approaching, and a plus sign must be inserted in both the numerator and
denominator:
fR c + |v R |
= (3.11)
fS c + |v S |
fR c − v R · sgn(x R − x S )
= (3.12)
fS c − v S · sgn(x R − x S )
with x S , x R being the positions of the sender and the receiver, respectively, on the x-
axis. The mathematical function sgn (“signum”) is available as a spreadsheet function
sign and as np.sign in numpy. To be able to better compare the formula with the
previous calculations, we rewrite it with the speeds (amounts):
fR c − |v R | · sgn(v R ) · sgn(x R − x S )
= (3.13)
fS c − |v S | · sgn(v S ) · sgn(x R − x S )
Tim I could never develop a formula like that. I would always set the wrong
sign or change the correct order.
Mag Nor could I. I’ve been toying around with this, checking whether the
outcome corresponds to the intuitive formula Eq. 3.9 in ten different situations.
A B C D E F G H I J K L M
1 =(c.s-vR*s.vR*xRel)/(c.s-v.S*s.vS*xRel)
2 =SIGN(x.R-x.S)
3 fE/fS s.vR s.vS x.S x.R xRel
4 cs 340 m/s S--> R* 1.05 =(cs)/(cs-vS) 0 1 -1 1 1 1.05
5 vS 17 m/s R* S--> 0.95 =(cs)/(cs+vS) 0 1 1 -1 -1 0.95
6 vR 10 m/s S* R--> 0.97 =(cs-vR)/(cs) 1 0 -1 1 1 0.97
7 R--> S* 1.03 =(cs+vR)/(cs) 1 0 1 -1 -1 1.03
8 S--> R--> 1.02 =(cs-vR)/(cs-vS) 1 1 -1 1 1 1.02
9 R--> S--> 0.98 =(cs+vR)/(cs+vS) 1 1 1 -1 -1 0.98
10 S--> <--R 1.08 =(cs+vR)/(cs-vS) -1 1 -1 1 1 1.08
11 <--R S--> 0.92 =(cs-vR)/(cs+vS) -1 1 1 -1 -1 0.92
12 <--S R--> 0.92 =(cs-vR)/(cs+vS) 1 -1 -1 1 1 0.92
13 R--> <--S 1.08 =(cs+vR)/(cs-vS) 1 -1 1 -1 -1 1.08
Fig. 3.9 (S) Frequency ratio for ten cases, in column F, calculated with Eq. 3.9 and with individual
considerations for each case, in column M, calculated with the general formula Eq. 3.13
Mag With trial and error, proof is not possible, but serious mistakes can be
uncovered. You can later rigorously prove the formula.
Checking in Python
In the Python program of Table 3.9, a function Doppler is defined realizing Eq. 3.12,
taking the velocities vS and vR (with correct sign + or −), respectively, of the sender
and the receiver, together with a keyword argument pos as input and returning the
frequency ratio f R /f S . The string argument pos specifies the relative position of
sender and receiver, ‘SR’ indicating that the receiver is to the right and ‘RS’ to the
left of the sender. The same parameters as in Fig. 3.9 (S) are specified successively
in a list var1 that is passed to Doppler expecting three positional arguments; so, the
list var1 has to be unwrapped (*var1 in line 11). The results of Doppler are the same
as in Fig. 3.9 (S).
Table 3.9 A general formula for calculating the Doppler shift for sender and receiver moving on
the same straight line
1 def Doppler(vS,vR,pos = 'SR'):
2 if pos == 'SR': sgnX=1
3 if pos == 'RS': sgnX=-1
4 fR=c-vR*sgnX
5 fS=c-vS*sgnX
6 return fR/fS
7 c=340.0
8 vS=17.0
9 vR=10.0
10 var1=[vS,0.0,'SR']
11 print(var1,'{:5.2f}'.format(Doppler(*var1)))
[17.0, 0.0, 'SR'] 1.05 [17.0, 10.0, 'RS'] 0.98
[17.0, 0.0, 'RS'] 0.95 [17.0, -10.0, 'SR'] 1.08
[0.0, 10.0, 'SR'] 0.97 [17.0, -10.0, 'RS'] 0.92
[0.0, 10.0, 'RS'] 1.03 [-17.0, 10.0, 'SR'] 0.92
[17.0, 10.0, 'SR'] 1.02 [-17.0, 10.0, 'RS'] 1.08
Figure 3.10a illustrates the ride of a car on a straight road, on the line y = 0 from x
= −100 m to x = 100 m. At a distance of yR = 30 m off the road, a receiver is at
position (0, 30). The car constantly sends out a tone of 200 Hz. Which frequency
does the receiver perceive when the car passes by?
1.2
Track fR/fS
Connection to receiver vS=55.56m/s
1.1 ; yR=20m
y [m] yR=50m
30 yR=100m
1.0
0.9
0 0.8
-100 -50 0 50 100
-100 -50 0 50
x [m] x [m] 100
Fig. 3.10 a (left) An observer (receiver) at point (0; 30) hears a car (sender) passing on the x-axis
(in the figure compressed). The velocity along the current connection line (dashed) determines the
perceived frequency. b (right) The perceived frequency, relative to the frequency of the source,
when a sound source passes the receiver at different distances yR at speed vS = 55.56 m/s
96 3 Formula Networks and Linked Diagrams
fR 1
= (3.14)
fS 1 + vcS
A B C D E F G H I
1 200.00 km/h
2 Velocity of sender vS 55.56 m/s
3 Frequency of sender fS 200.00 Hz =B2&"="&ROUND(vS;2)&"m/s; "
4 Speed of sound c_ 340.00 m/s &B5&"="&yR&"m"
5 Distance of receiver yR 20.00 m vS=55.56m/s; yR=20m
2) 9)
/vS +yR^ /(t-C )
1 +(x-B9) QRT(x^2 dist-D9) S/(1+v/cs /fS B9)/2
7 =B9+ =C9 =S =( =f =f =(x+
8 x t dist v f fNorm xC
9 -100 0 101.98
10 -99 0.02 101.00 -54.47 238.15 1.19 -99.50
209 100 3.60 101.98 54.47 172.38 0.86 99.50
Fig. 3.11 (S) A sound source moves on the x-axis past an observer at a distance d R . The x position
in column B is the independent variable. From that, the time (column C), the distance source-
observer (column D), the velocity of the sender in the direction of the connecting line (E), and the
observed frequency (F, G) are calculated with Eq. 3.14. Attention: The time in column C depends
on the speed of the source! In column H, x C is the center of the intervals
A possible calculation model is shown in Fig. 3.11 (S), where we have chosen the
x-coordinate of the car on the track as the independent variable, and time, distance,
and velocity along the connecting line as dependent variables. You could just as
easily choose time as the independent variable. The x in the formula C10 = [=
C9 + (x - B9)/vS] refers to B10, the entry of the column vector x in the same
row.
Tim Well, since you asked it in that way, it probably isn’t. I remember this
much: We take the centers of the considered distance intervals because the speeds
were calculated with the (t, x) coordinates of the interval boundaries.
A Python program that solves the task is given in Table 3.10, the main program in
the upper cell, the function FreqLine for realizing Eq. 3.14 for the complete fre-
quency curve in the lower cell. List slicing is used to calculate the interval centers
x C in the main program, and the velocities v when differentiating the distance dist
in FreqLine.
98 3 Formula Networks and Linked Diagrams
Table 3.10 a (top) Specifications of the situation in which a receiver is at rest at a distance yR off
the sender’s track. b (bottom) Function for calculating the frequency curve when yR is given
1 vS=55.56 #Speed of sender
2 fS=200 #Frequency of sender
3 c=340 #Speed of sound
4
5 x=np.linspace(-100.0,100.0,201)
6 #Center xC of path segments
7 xC=(x[1:]+x[:-1])/2
8
9 #Time segments Dt
10 Dt=(x[1:]-x[:-1])/vS
11 #Time t
12 t=np.cumsum(Dt) #Integrates over dt
13 def FreqLine(yR):
14 dist=np.sqrt(x**2+yR**2)
15 v=((dist[1:]-dist[:-1])/Dt)
16 fRS=1/(1+v/c)
17 return fRS #Frequency ratio
Questions
Question
The plot program in Table 3.11 calculates and displays the frequency curves
for the three distances yR = 20, 50, and 100 m.
word argument.
3.4 Exponentials 99
Table 3.11 Plotting several frequency trajectories with the parameters specified in Table 3.10
1 FigStd('x',-100,100,25,'f/fQ',0.8,1.2,0.1)
2 plt.plot([-100, 100],[1,1],ls='-',color='k',lw=1)
3 #Horizontal through y=1
4 yR=20 #Distance to track
5 fRS=FreqLine(yR)
6 plt.plot(xC,fRS,'k-', lw=1.5,label='yR='+str(yR))
7 yR=50; fRS=FreqLine(yR)
8 plt.plot(xC,fRS,'k--',lw=1.5,label='yR='+str(yR))
9 yR=100; fRS=FreqLine(yR)
10 plt.plot(xC,fRS,'k-.',lw=1.5,label='yR='+str(yR))
11 plt.legend(loc=0,fontsize=10)
12 #plt.savefig('Doppler off, multiple.png')
3.4 Exponentials
For exponential functions, apply Plus 1 yields times e; plus 1 in the argu-
ment yields times e in the value. An exponential function A · exp(−t/t0 )
is best drawn by hand (Really? Yes, also by hand!), beginning with its tan-
gent at t = 0. Diode characteristics seemingly exhibit a “kink voltage” that
depends on the scaling of the y-axis; more generally, exponential functions
seem to explode.
Ψ Plus (in the argument) yields times (in the result) for exponentials.
For y = 2x , plus 1 (in the argument) yield times 2 (in the result).
100 3 Formula Networks and Linked Diagrams
A B C D E 1,E+19
1 =A3+1 =B3*2 3
=2^n =2^D
2 n y y =2^n 2^62.4 8,E+18 y =2^n
3 0 1 1 62.4 6.1E+18 2^62,4
y
4 1 2 2
5 2 4 4 6,E+18
6 3 8 8
7 4 16 16
4,E+18
8 5 32 32
9 6 64 64
66 63 9.22E+18 9.22E+18 2,E+18
67 64 1.84E+19 1.84E+19
1025 1022 4.5E+307 4.5E+307
1026 1023 9.0E+307 9.0E+307 0,E+00
1027 1024 #NUM! #NUM! 0 16 32 48 n 64 80
The values are graphically displayed in Fig. 3.12b. You can see that the explosion
by a factor 1019 takes place on the last few squares. On squares 0–62, there are
263 –1 grains, on all squares together, 264 −1 grains.
Profit
Question
What would be the share of the internationally traded rice in 2016 if the loser
of the game (a wealthy medieval Sultan) had been able to deliver?15
What is the value of 10E3 in excel and 10e3 in Python? Be careful!16
Mag Can the winner satisfy his hunger with his win?
Tim I’ve heard that exponential growth means explosion. So, maybe the winner
can live well on his heap of rice for a week.
Mag World rice production in 2015/16 was 470 million metric tons, but only
about 5% were traded on the world market. Unlike wheat, rice is consumed by
more than 95% of the population in the cultivating countries.
15 For 64 fields, the winner would have received 264 –1 = 18 × 1018 grains, corresponding to about
1018 g = 1012 tons of rice. This is the 2000-fold amount of the rice harvest 2015/16 of 470 million
tons.
16 10E3 = 10 × 103 = 104 = 10,000, the same with 10e3 in Python.
3.4 Exponentials 101
Tim I’ve counted. One kilogram of rice contains about 40,000 = 4 × 104 grains.
According to the rule of the game, more than 10,000 times the volume of one
year’s world trade of rice should pile up on the chessboard. Incredible!
Mag There is no catch. The catastrophe results from the rule plus 1 yields
times 2 governing the exponential 2n .
The power function can be generalized to y = ax , where a and x are real num-
bers. If a is Euler’s number e = 2.718, then the power function becomes the
known exponential function with the formula [= exp(…)] (excel) or np.exp()
(Python).
It is, however, often physically more sensible to write the exponential with a
characteristic x value x 0 :
1 x 1 x
f (x) = · exp = · e x0 (3.16)
x0 x0 x0
Thus, the unit of x 0 is equal to the unit of x, e.g., a length or a time, and has an
intuitive meaning: the tangent at x = 0 intersects the y-axis at the amplitude |1/x0 |,
and the x-axis at the characteristic length x 0 .
When the function is specified with an amplitude |xA0 | , its integral from 0 to,
respectively, +∞ (for a < 0) or −∞ (for a > 0), is A.
Alac Sure! First, mark the amplitude Ae on the vertical axis and the charac-
teristic time t 0 on the horizontal and pass a straight line through the two points.
The exponential curve approaches the tangent at t = 0 and the horizontal axis for
t → ∞ or t → –∞, depending on the characteristic parameter’s sign.
3 3·exp(t/-30)
y 1·exp(t/15)
2
tangents
0
-20 0 20 40 60 80
t
Fig. 3.13 a (left) Two exponential functions Ae ·exp(t/t 0 ) with their tangents at the intersections
with the y-axis. b (right) How to draw an exponential function by hand: First, the tangent as a
straight line with its intersections with the x- and y-axes!
3.4 Exponentials 103
Tim “Plus one” and “Straight line” are clear, but why “kink”?
Mag You have seen this in Fig. 3.12b; it will be explained in Sect. 3.4.4. An
essential feature of an exponential is an explosion on a suitably scaled y-axis.
This function has two parameters: the strength of the reverse current I s also
called the saturation current, and the thermal voltage U T , which is given by k B T/e,
with k B being the Boltzmann constant, e the elementary charge, and T the absolute
temperature. At room temperature, U T = 25 mV. The current through a diode is
zero when the applied voltage is zero.
We will represent such a function for I s = 1 × 10–14 A and U T = 0.025 V in
various plots (see Fig. 3.14).
Fig. 3.14 a (left) Diode characteristics and associated exponential function, representation for
small currents. b (right) Twice the same exponential as in a, but with different scaling of the I axes;
left y-axis for the left curve, right y-axis for the right curve; the vertical grid lines have a distance
U T = 25 mV
104 3 Formula Networks and Linked Diagrams
Questions
Which of the curves in Fig. 3.14a, b are exponential functions? Which are
shifted on the I-axis? Which are shifted on the U-axis?17
At which U-values in Fig. 3.14b are you most likely to find the “kink points”,
in electronic engineers’ jargon?18
Exponential function
17 All curves represent exponential functions. The diode curve in Fig. 3.14a is shifted downwards
on the I-axis by the saturation current I s , so that it passes through zero. The curves in Fig. 3.14b
have not been shifted on the U-axis.
18 At about 0.5 and 0.6 V.
3.4 Exponentials 105
Fig. 3.15 a (left) Diode characteristics, logarithmic scale of the I axis (semi-log plot). The curve
can only be represented for I > 0, because the logarithm is defined only for positive values. b (right)
Spreadsheet layout for calculating diode characteristics, I s = saturation current, U T = temperature
voltage, dU = U T
Diode characteristics
Is saturation current
UT thermal voltage, 25 mV at room temperature, characteristic parameter of the
exponential
dU interval width, here, dU = U T
U sequence of voltages, dU apart
exp exponential function with I s and U T as amplitude and characteristic voltage
I diode current, I(U).
A B C D E F G H I
1 A 3.0 tA -30.0 3·exp(t/-30) =A&"·exp(t/"&tA&")"
2 B 1.0 tB 15.0 1·exp(t/15)
3 dt 2.0
) tB)
t P(t/tA XP(t/
4 =A6+d =A*EX =B*E
5 t expA expB tangents
6 -20.0 5.8 0.3 30 =-tA 0.0
7 -18.0 5.5 0.30 0.0 3 =A
8 -16.0 5.1 0.34 -30 =tA 6 =2*A
56 80.0 0.2 207.13
Fig. 3.16 (S) Two exponential functions whose independent variable t is specified as column vec-
tor A6:A56 and their parameters amplitude A, B and time constant t A , t B are given in A1:D2. The
legends for the functions are compiled in F1 and F2 with the formula in G1 of type “Text” &
Variables
The table in Fig. 3.16 (S) has a typical layout. The 51 values of the independent
variable time t are located to the left of in a column vector named “t”. The
parameters A, B, and t A , t B of the curves are specified above , as well as the
time interval dt, the distance on the horizontal axis between the calculation points.
The initial value of t, here, −20, has to be entered into cell A6. The values for the
remaining 50 t values are determined successively from the respective predecessor.
The t-predecessor for cell A7 is cell A6, A7 = [=A6 + dt]. In the formula, A6 is
not provided with a dollar sign. It is a relative reference, so that the address of the
addressed cell adapts during copying. Therefore, A56 = [=A55 + dt].
Questions
Suppose that A6 contains an initial time t = 5 and the length of a time segment
is stored in a cell with the name dt and has the value 2. What values for time t
are in cells A7 and A8?19
How can the coordinates of the tangent to the exponential Ae ·exp(t/t 0 ) at t
= 0 be derived from the parameters of the exponential function?20
What is the distance on the horizontal axis between the functions’ calculation
points in Fig. 3.13a created 21
∞ from Fig.
t3.16 (S)?
What is the value of 0 3 · exp − 30 dt? 22
Task Change the parameters A, t A , and dt and check whether the diagram reacts
accordingly! This is the case if each cell contains the correct formula. Remember:
you cannot merely transfer the numbers from the figures to your worksheet. Most
cells contain a formula; only sometimes are numerical values entered directly.
Diode characteristics
A possible calculation model is presented in Fig. 3.15b (S).
The parameters I s and U T of the diode characteristics are set in the named
cells C1:C2. In C3, the horizontal distance between neighboring sampling points
is defined. Here, we have chosen dU = U T = 0.025 V that is valid for room temper-
ature. The I-U characteristics are illustrated in Fig. 3.14. They intersect the I-axis at
0, showing that no current flows without applied voltage.
Initial slope
A Python program for drawing the exponentials of Fig. 3.13a and their slopes at t
= 0 is given in Table 3.12.
The list t of time instants is created by np.arange (−20, 80 + dt, dt), mimicking
the construction of the time vector in the spreadsheet of Fig. 3.16 (S) with, e.g., A8
= [=A7 + dt]. The lower limit −20 corresponds to the value in A6. To come to
80 (in A56), we have to specify 80 + dt as the upper limit, because np.arange
creates an interval that is open at its right end with the endpoint excluded. ExpA and
expB are constructed from t with the corresponding amplitudes and time constants
Table 3.12 a (top) Specifications of two exponential functions, equivalent to rows 1 through 3 in
Fig. 3.16 (S); b (bottom) labels for the two functions created in lines 7 and 8
1 dt=2.0
2 A,tA= 3.0,-30.0 #Amplitude and time constant
3 B,tB=1.0,15.0
4 t=np.arange(-20,80+dt,dt)
5 expA=A*np.exp(t/tA)
6 expB=B*np.exp(t/tB)
7 lblA=(str(A)+'*'+'exp(t/'+str(tA)+')')
8 lblB=(str(B)+'*'+'exp(t/'+str(tB)+')')
lblA 3.0*exp(t/-30.0)
lblB 1.0*exp(t/15.0)
108 3 Formula Networks and Linked Diagrams
Table 3.13 Specifications for diode characteristics, the same as in Fig. 3.15b
1 Is=1e-14
2 UT=2.5e-2
3 dU=2.5e-2
4 U=np.arange(-0.2,1.05+dU,dU)
5 exp=Is*np.exp(U/UT)
6 I=Is*(np.exp(U/UT)-1) #Diode characteristics
(A, t A ) and (B, t B ). The curves can be plotted with our standard function StdFig.
In Fig. 3.13a, they are represented with open symbols. In Python, this is specified
by plt.plot(…., fillstyle=’none’, …).
Questions
What are the instructions for plotting the tangents in Fig. 3.13a?23
What are the size and last element of:
Diode characteristics
A Python program corresponding to the spreadsheet layout in Fig. 3.15b is shown
in Table 3.13.
Subplots
A plot like Fig. 3.14b with two vertical axes cannot be achieved with our standard
figure, the function FigStd defined in Sect. 2.4.5. We have to refer to the function
subplots of the pyplot library (see Table 3.14). I(U) is plotted twice, with
ax1.axis([0.3, 0.7, 0, 2e-5]) for the primary (left) y-axis from 0 to
2e−5 and with ax2.axis([0.3,0.7,0,2e-3]) for a second y-axis from 0 to
2e−5, declared with ax2 = ax1.twinx() as the secondary (right) y-axis.
Logarithmic scaling
Logarithmic scaling of an axis can be achieved with plt.yscale
(value=”log”) and plt.xscale(value=”log”).
Table 3.14 Setting up a diagram similar to Fig. 3.14b with primary and secondary axes, variables
specified in Table 3.13
1 fig, ax1 = plt.subplots()
2 ax1.plot(U, I, 'k-')
3 ax1.axis([0.3, 0.7, 0, 2e-5])
4 for x in np.arange(0.3,0.7,dU):
5 ax1.plot([x,x],[0,2e-5],'k-',lw=0.6)
6
7 ax2 = ax1.twinx() #Secondary axis
8 ax2.axis([0.3,0.7,0,2e-3])
9 ax2.plot(U, I, 'r--')
10 plt.show()
3.5 Questions
General advice
Python-specific
2 2
y.1 y.2 y y.1 y.2
y.1 y.2 y.3 y Einheitsvektoren
unit vectors
y.3 1 1
0 0
-2 -1 0 1 x 2 -2 -1 0 1 x 2
-1 -1
-2 -2
Fig. 3.17 a (left) The segment defined by two points (x 1 , y1 ) and (x 2 , y2 ) is extended to a third
point whose x-coordinate x 3 can be selected arbitrarily. b (right) The unit vectors in the direction
of the line and perpendicular to the line are attached to the line, defined in Fig. a, at the left point
Broom rules
Straight-line equation
A straight line is defined by two points (x 1 , y1 ) and (x 2 , y2 ) (see Fig. 3.17a).
9. What is the equation for determining the distance between the two points?
10. Which equation must be used to find the value y3 for a given horizontal position
x 3 so that (x 3 , y3 ) lies on the straight line?
11. Deduce from the coordinates of the two points the direction vector (Dx , Dy ) of
the straight line normalized to length 1!
12. How do the coordinates of the two points result in the vector (Px , Py), the
perpendicular to the straight line and normalized to length 1?
A spreadsheet layout for three points on a straight line is shown in Fig. 3.18
(S).
13. What is the linked cell and min and max of the slider in F4:H4?
14. What formulas are in B3 (input from E3) and D4 (input from E4)?
15. Write a Python program that performs the calculations of Fig. 3.18 (S)! Replace
the function of the sliders with simple assignments with random functions: E1=
… ; E4= … !
3.5 Questions 111
A B C D E F G H I J K M N P
1 Three points on a straight line Unit vectors
2 x.1 -0.6 y.1 -0.5 along the straight line
3 x.2 0.92 y.2 0.57 92 x.1 -0.6 y.1 -0.5
4 x.3 1.5 y.3 0.98 57 x.p -0.03 y.p -0.1
5 perpend. to the straight line
6 Length of segment 1-2 Slope of segment 1-->2 x.1 -0.6 y.1 -0.5
7 l.12 2.66 m.12 0.70 x.v -0.2 y.v -1.07
Fig. 3.18 (S) Spreadsheet layout used to create the coordinates for Fig. 3.17a and b, B3 and D4
depend on the outputs on the sliders. The slider in F4:H4 goes from 0 to 80
0
-8 -4 0 4 8
Object and image
Lens
-4
Fig. 3.19 Incomplete image construction for imaging with a converging lens
16. In school, one usually learns the equation 1/f = 1/o + 1/i for imaging with
converging lenses (o is object distance, i is image distance). How is this imaging
equation modified according to DIN 133528 and made suitable for numerical
calculation in spreadsheets and Python both for converging and diverging
lenses?
17. How is the magnification factor defined in DIN 1335?
18. What characterizes a converging lens in the imaging equation?
19. What characterizes a diverging lens in the imaging equation?
20. Draw the rays for the image construction in Fig. 3.19!
21. What is the image-side focal length?
22. Draw the bundle of rays that contributes to the image formation!
0
0 2 4 6 8 10
23. What are the formulas for the gravitational force F g and the centrifugal force
F c on a car of mass m, traveling with speed v through a curve with radius r?
24. What do you have to do to get a true-angle display when the x-axis is scaled
from −2 to 8 km and the y-axis from 10 to 15 km, in excel and in Python?
25. How is the static friction force defined? What does a static friction coefficient
μ = 0.5 mean?
26. Draw in Fig. 3.20, with a triangle ruler, the resulting force, the force in the
plane, and the force perpendicular to the plane! Which force determines the
static friction?
27. Draw a vector in the bank line and another one perpendicular to it!
28. What are the vector equations for determining the quantities of Question 26?
Doppler effect
fE c ± vE
= (3.19)
fQ c ∓ vQ
29. What do the letters in Eq. 3.19 stand for? Which signs are to be used when?
Adjust the formula for the three cases in Fig. 3.21!
A car (sender S) drives along the x-axis. Its position at time t is specified in an array
named x S . A pedestrian (receiver R) moves along the y-axis towards the x-axis. Its
position at time t is indicated in an array named yR .
S R R S R S
Fig. 3.21 A sound source S and a sound receiver R move on a straight line
3.5 Questions 113
Exponential function
Solutions of Exercises 4.3 (Excel), 4.5 (Python), 4.7 (Excel), and 4.8 (Python) can
be found at the internet address: go.sn.pub/gTtbiH.
Mag This chapter will teach us to program, to let macros interact with
spreadsheet calculations, and to realize parallel solutions in Python.
Tim That sounds pretty demanding. Is it at all manageable for beginners like
me?
Mag Quite clearly: Yes. Many people have already achieved that, even students
who had never before written a line of code. Visual Basic is a good-natured pro-
gramming language that does not require much knowledge, at least not for the
tasks that we want to tackle. This chapter will not only take away your fear of
programming, but you will also find it fun to write programs that do amusing
things.
Tim Well, people who had just finished the course told me that they had to deal
with routines, macros, programs, and procedures.
Mag Don’t worry, we don’t make any distinction among those terms, we
use them all synonymously. Our programs include both EXCEL-typical command
sequences and classical algorithmic structures.
Alac I’m not afraid of VISUAL BASIC or Python; after all, I already took a
course about another programming language and used it to write funny programs.
Mag That is certainly a good prerequisite for faster success. You will have an
easier time than Tim. Nevertheless, don’t take the tasks for granted. In our course,
programming tasks are combined with physics exercises (so much for our hopes
for just “funny”:-)). I’ve often experienced instances in which mere programmers
have been discouraged by their limited progress in this kind of programming and
have given up.
Mag Not only that. You should certainly understand more about physics after
the course than before. Nevertheless, the exercises will also familiarize you with
good programming skills: to develop systematically, to document carefully, to
detect and correct mistakes.
Tim One more question. Many workplaces require programming skills in spe-
cial programming languages. Wouldn’t it be better for me to learn such languages
from the onset?
Mag Don’t worry.’ In our tasks with VISUAL BASIC and Python, you will have
room to make a sufficient number of mistakes to learn from so that you can be con-
fident in becoming a computer expert. The algorithmic constructions are the same
in all programming languages. More important than acquiring special knowledge
at an early stage is that you gain the ability to cope with “hard” programming
tasks and master the rules for good programming.
4.1 Introduction: For, If, Sub/Def 117
How do we proceed?
This course cannot give a general introduction to programming, because that would
require an excess of repetition of things that are already well described in specific
textbooks. As in Chap. 2, we will do a basic exercise that you should follow step by
step and convert into your own program. It contains all of the commands and con-
structions that we will need later, but not much more. However, this basic knowledge
will enable you to find your way around in EXCEL help or Python internet aid and
choose suitable textbooks for programming with VISUAL BASIC and Python.
Pandas
Pandas (“Python Data Analysis”) is a library for Python, based on NumPy.
It is designed for data management and analysis and works with structured data
(DataFrame (2-dimensional)) and time series (Series (1-dimensional)), thus
118 4 Macros with Visual Basic and Their Correspondences in Python
mimicking spreadsheet calculations. We shall use it in this book only in Exercise 4.8
“Processing the protocol of a measuring device”.
In the menu ribbon (see Sect. 1.7), click on the main group DEVELOPER and then
on the tab VISUAL BASIC; the “SHEET1 (CODE)” window appears (Fig. 4.1).
If the right lower rectangle (below “(General)”) is gray, double-click the SHEET1
line in the MICROSOFT EXCEL OBJECTS so that it turns white. Instructions that you
write into this sheet in the VISUAL BASIC editor are executed in Sheet1.
Fig. 4.1 Spreadsheet and associated VISUAL BASIC sheet after executing DEVELOPER/VISUAL BASIC
(EXCEL 2019)
4.2 Basic Exercise: FOR-Loops 119
4.2.2 Programming
Task First, write only this one line [CELLS(1,1) = “Annegret”] into the VBA sheet
and start the program by pressing the start button (high-lighted in Fig. 4.2b). For
the procedure to be executed, the pointer | must be somewhere in the procedure.
Then, insert the other lines of SUB ANNEGRET one after the other, execute the macro
after each line and observe what happens in the spreadsheet:
Fig. 4.2 SUB Annegret in b (right) writes into range A1:B3 in a (left). The text after the apostro-
phe’ is interpreted by the VBA interpreter as a comment and not as program code
120 4 Macros with Visual Basic and Their Correspondences in Python
[=A1]. If the contents of A1 in the spreadsheet are now changed, the new value
also appears in cell B2.
Task Delete all entries in the spreadsheet again and then run through the pro-
gram step by step by placing the cursor | in the program and repeatedly pressing
the function key F8 (also obtained and explained in the VBA developer, Fig. 4.9, by
DEBUG/ STEP INTO). Step by step, the previously deleted entries will appear again in
the spreadsheet.
FOR loops The macros in Fig. 4.4 (P), Fig. 4.5 (P), and Fig. 4.6 (P), wherein
FOR loops are used, fill in the spreadsheet in Fig. 4.3 (S).
SUB Protoc1 in Fig. 4.4 (P) fills in column A. Line 2: the text “x” is written
into A1. In the FOR loop, the variable x is incremented from 3 to 9.5 in steps of
0.25 and written into cells in A. The variable x takes on 3 as the first value and
is then incremented by 0.25 each time the loop is traversed until the value 9.5 is
reached. The variable of the FOR loop, here, x, is called the loop index. In line 9,
a formula is entered into C6, normal text enclosed in quotation marks but starting
with an equal sign.
A B C D E F G H I J K
1 x 9.50 x Cos(x) Sin(x) Tan(x)
2 3.00 -1.00 =COS(C1) 3.00 -0.99 0.14 -0.14 3 9.50
3 3.25 -0.08 =SIN(C1) 3.25 -0.99 -0.11 0.11 4
4 3.50 0.08 =TAN(C1) 3.50 -0.94 -0.35 0.37 5 x
5 3.75 3.75 -0.82 -0.57 0.70 6 Cos(x)
6 4.00 0.99 =COS(C1)^2 4.00 -0.65 -0.76 1.16 7 Sin(x)
7 4.25 4.25 -0.45 -0.89 2.01 8 Tan(x)
8 4.50 4.50 -0.21 -0.98 4.64
23 8.25 8.25 -0.39 0.92 -2.39 3 0.08
24 8.50 8.50 -0.60 0.80 -1.33 4 =TAN(C1)
25 8.75 8.75 -0.78 0.62 -0.80 5 3.50
26 9.00 9.00 -0.91 0.41 -0.45 6 -0.94
27 9.25 9.25 -0.98 0.17 -0.18 7 -0.35
28 9.50 9.50 -1.00 -0.08 0.08 8 0.37
Fig. 4.3 (S) Column A is filled in by SUB Protoc1 in Fig. 4.4 (P). The formula in C6 has also been
entered by SUB Protoc1. The list in columns E:H is obtained from the spreadsheet calculation in
C1:C4 by executing SUB Protoc2 in Fig. 4.5 (P). The range C1:H4 is transferred by SUB ScanCopy
in Fig. 4.6 (P) into the two columns J and K
1 Sub Protoc1() r2 = r2 + 1 6
2 Cells(1, 1) = "x" Next x 7
3 r2 = 2 8
4 For x = 3 To 9.5 Step 0.25 Range("C6") = "=Cos(C1)^2" 9
5 Cells(r2, 1) = x End Sub 10
Fig. 4.4 (P) SUB Protoc1 fills in A in Fig. 4.3 (S) and a formula into C6. Syntax for calling a cell:
CELLS (ROW, COLUMN)
4.2 Basic Exercise: FOR-Loops 121
Fig. 4.5 (P) SUB Protoc2 changes the value in cell C1 (line 5) and writes the function values from
C2:C4 consecutively into the columns F (6th) to H (8th) of the spreadsheet in Fig. 4.3 (S)
Loop2i structure
In Fig. 4.4 (P) , we have introduced a running index r 2 , which specifies the row
of the cell to be filled in. It is set in line 2 to 2 before the start of the loop and is
incremented by 1 in line 6 at the end of each loop cycle, so that the values of x are
sequentially written into lines 2 to 28. We will often use such structures, call them
Loop2i, because they comprise two indices, and we memorize them with a broom
rule .
Questions
Fig. 4.6 (P) SUB ScanCopy writes the contents of the range A1:F4 of Fig. 4.3 (S) consecutively
into columns J and K of the same spreadsheet. CELLS (2,3) corresponds to C2 in the spreadsheet
Nested loops
SUB ScanCopy in Fig. 4.6 (P) transfers the range (r = 1 to 4: c = 3 to 8), i.e., C1:H4
of the table, to columns J and K of Fig. 4.3 (S).
Range C1:H4 is read horizontally, row by row, and written consecutively verti-
cally into column K (c2 + 1 = 11) with the (c = ) loop; line 8: The running index
r 2 is incremented, indicating the next free row in the spreadsheet.
To be read, the range with the two coordinates row number r (from 1 to 4) and
column number c (from 3 to 8) must be scanned with the cells being addressed
with CELLS(R,C). This is done with two nested loops, an outer loop (FOR r = ), and
an inner loop (FOR c = ) that is called within the outer loop and ends in line 9
with NEXT C. SUB ScanCopy also writes the index c into column J (line 6, c2 = 10
from line 3).
The line index r 2 is incremented by one at the end of each of the two loops FOR
c = and FOR r = . The increment in the inner loop (FOR r = ) causes the adjacent
entries in a row of the table, e.g., C1:H1, to be written consecutively into rows 2
to 7 of J, J2:J7. The increment in the outer loop (FOR c = ) causes a row, e.g., row
8 in the table in Fig. 4.3 (S), to be skipped.
Questions
Using the variables x and r 2 in the loop2i in SUB Protoc2 in Fig. 4.5 (P), explain
the broom rule: Loop2i: Continue counting (the running index) in the loops!4
It would have been easier to specify the columns in SUB ScanCopy in Fig. 4.6
(P) as numbers, i.e. CELLS(r 2 , 11) instead of CELLS(r 2 , c2 + 1). Does the variant
CELLS(r 2 , c2 + 1) offer any advantage?5
Why is J8:K8 in Fig. 4.3 (S) not filled in?6
What is the value of r 2 at the end of SUB ScanCopy in Fig. 4.6 (P)?7
4 The rows from r = 1 to 4 and the columns from c = 3 to 8 are scanned in the nested for-loops. The
24 scanned values are stored in successive rows. The index of these rows, r 2 , must be incremented
in the inner FOR loop after every entry.
5 If the data is to be output to another range of the spreadsheet, only one parameter for the columns,
We are going to record the commands that are executed when we insert an ellipse
into a spreadsheet and format it. The recorded macro is converted into a sub-
routine that is called several times by the main program with modified coordinates.
In Fig. 4.7a, you see a decorative spiral drawn with the tools acquired in this
exercise. The starting point is a macro (Fig. 4.7b), recorded when an ellipse was
inserted and formatted.
Mag Once you have completed this task, you can create images like the one in
Fig. 4.7a.
Mag More importantly, you will master Visual Basic statements such as those
in Fig. 4.7b (P).
Tim Terribly complicated! I will never be able to keep all of that in my head at
the same time.
Mag You’re not supposed to. Figure 4.7b (P) contains a series of instructions
that the Macro Recorder has recorded when an ellipse has been inserted by hand.
Fig. 4.7 a (left) Decorative spiral, drawn by a macro. b (right, P) Macro recorded by the macro
recorder while an ellipse is inserted into the spreadsheet. Superfluous instructions have been
deleted. If possible, do not write such code by hand! Get it using DEVELOPER/ RECORD MACRO and
modify it as needed!
4.3 Macro-Controlled Drawings with FOR, SUB, IF 125
Mag No, you still have to modify the recorded code, introduce variables and
learn the basic program constructions: loops (FOR i = … TO …), logical branches
(IF THEN … ELSE …), and sub-routines. (CALL SUB(a, b, c, …)).
Fig. 4.8 The DEVELOPER/RECORD MACRO tab records all program code associated with
the spreadsheet operations performed by the user, e.g., introducing a rectangle as in
F1:H2 (INSERT/ILLUSTRATIONS/SHAPES). The VISUAL BASIC button (far left) activates the
VISUAL BASIC EDITOR (see Fig. 4.1)
126 4 Macros with Visual Basic and Their Correspondences in Python
Fig. 4.9 Visual basic editor. You have to activate PROJECT EXPLORER (with VIEW/PROJECT EXPLORER)
to see all open files. The recorded macro is located in Module 1 (hidden in the group MODULES) of
the VBA project (4–2 Basic Exercise Annegret)
VBA is the abbreviation for “Visual Basic for Applications”. The addition “for
applications” indicates that the application’s instructions, here, EXCEL, are available
as internal instructions, e.g., ACTIVESHEET. ADDSHAPE, with which a geometric form
is inserted into the spreadsheet.
We can review the result of our macro recording in the Visual Basic editor. This
editor is activated when you click on DEVELOPER/VISUAL BASIC (far left in Fig. 4.1)
or press ALT F11. A window like that in Fig. 4.9 appears when the program page of
a sheet or a module is additionally double-clicked. SHEET1 has been clicked here,
which already contains SUB Annegret from Sect. 4.3.2.
Upon clicking on the “View” tab, a menu opens up that has been placed over
SUB Annegret in Fig. 4.9.
We click on the PROJECT EXPLORER button, and the PROJECT—VBAPROJECT sub-
window appears. In this window, each worksheet (SHEET1, SHEET2, SHEET3, SHEET4)
is assigned a VBA sheet in which Visual Basic code can be generated and edited.
In Fig. 4.9, SHEET1 (Tabelle1(Annegret)) has been clicked, and in the editor, the
macro SUB ANNEGRET from Sect. 4.2.2 has popped up.
Since we have already recorded a macro, another object MODULE1
appears under Modules . It contains the program code SUB MACRO1, which we
have transferred to Fig. 4.7b (P), with four instructions:
– Lines 3 and 4: An ellipse (MSOSHAPEOVAL) has been created. The first two num-
bers in the argument list are the x and y coordinates; both are measured from
the upper left corner of the spreadsheet. The next two numbers in the list are
the two diameters of the ellipse.
– Line 7: The area within the ellipse is colored.
– Line 13: The border of the ellipse is colored.
– Line 18: The thickness of the border of the ellipse is specified.
You can edit the macro commands in the editor like normal text. The syntax must,
of course, comply with the rules of the VBA interpreter.
Debug/Step Into
Let the macro run again; best if you do it step by step! If you place the cursor in a
program in the Visual Basic Editor and press the function key F8, each step of the
program is executed individually (DEBUG/STEP INTO). You can then see exactly what
is happening and check whether the drawing is changing as you expect. You can
also change the instructions before they are executed. Going through a macro step
by step is a good way to detect programming errors.
If you place the cursor on a variable name, the value of that variable will pop up.
Task Change the coordinates and the size of the diameters by modifying the
instructions!
Mag Now, the real programming starts, with loops and sub-routines!
128 4 Macros with Visual Basic and Their Correspondences in Python
Fig. 4.10 a (left, P) Variable names are introduced, MACRO1() from Fig. 4.7b (P) becomes
Macro2(). The macro SUB CommandButton1 is triggered by the command button in Fig. 4.11b.
b (right, P) Macro2() is converted into a sub-routine Disc(x,y), which is called repeatedly by the
main program Circles with various values for x and y, with the result in Fig. 4.11b
A B C D A B C D
1 1
2 2
3 3
4 4
5 5
CommandBuon1
6 6
7 drawn by Macro1 7
Fig. 4.11 a (left, S) Circle and ellipse after executing SUB Macro2 in Fig. 4.10a (P). b (right, S)
Result of the procedure Circles in Fig. 4.10b (P)
4.3 Macro-Controlled Drawings with FOR, SUB, IF 129
Questions
Sub-routines
We want to summarize the relevant instructions in a sub-routine “Disc”, which con-
tains, in the procedure header, the coordinates (x, y) of the center of the circle in
the parameter list, Disc(x, y). This sub-routine is called from a main program with
different values for (x, y). Figure 4.10b (P) suggests a solution for this task, with the
main program SUB Circles and the sub-routine SUB Disc. Superfluous specifications
in the recorded macro have been deleted.
The diameter of the circular disc is set to d = 50 in SUB Disc (line 28). Grey
is now selected as the fill color, lines 31, 32. The line width remains as before
(… LINE.WEIGHT = 1). These parameters cannot be changed by the main program,
because they are not in the procedure header.
When placing the circular disc in the spreadsheet, note that the center of the
circle is passed via the procedure header (SUB Disc(x,y)), but that it is the upper
left corner of the shape that must be specified in the drawing command.
The ratio of the scaling in Visual Basic to the grid scale in the spreadsheet can
be seen from the following data:
A procedure header in Fig. 4.10b (P) reads SUB Disc(x,y). This sub-routine is called
in SUB Circles() with CALL Disc(I*50 + 60, I*25). The first entry in the header in SUB
Disc is taken over as x, and the second entry as y. We often name the variables
in the main program the same as in the sub-routine. So, we could write x = i*50
+ 60 and y = i*25 within the loop in SUB Circles() and then call CALL Disc(x, y),
with the same result as above.
If we executed CALL Disc(y, x), the first entry, here, y from the main program,
would be interpreted as x in the subprogram and the second entry as y. The row of
the three circular discs would start at A8 and go down more steeply. In the main
program, we could also choose completely different variable names, e.g., a and b,
and then proceed with CALL Disc(a, b) or CALL Disc(b, a).
Name the variables such that you are best able to keep an overview!
Questions
Main Program
A main program is characterized by the fact that it contains no parameters in the
procedure header. Only main programs are executable programs. Sub-routines gen-
erally contain parameters in the header that must be assigned values by a higher-level
program. Examples:
– SUB circles() in Fig. 4.10b (P) is a main program that the user can start.
– SUB disc(x,y) in Fig. 4.10b (P) is a sub-routine with x and y in the procedure
header. It cannot run on its own, but can only be called by another procedure with
specified values for the parameters x and y.
Task Change the procedure so that, in addition to the coordinates of the cen-
ter point, the diameter d of the circle and the thickness w of the boundary
(SHAPE OUTLINE) are selected in the main program and are transferred to the
sub-routine as parameters in the procedure header!13
FOR loop
The main program Circles calls the sub-routine DISC in the loop (FOR i = ) three
times. The centres of the circular disks are set to (110, 25), (160, 50) and (210,75)
for i = 1, 2, 3. The drawing resulting from these specifications is shown in Fig. 4.11b.
A FOR loop is used in the macro Circles. The general syntax for a FOR loop is:
FOR x = xmin TO xmax STEP delta_x
{LIST OF COMMANDS}
NEXT x
An example with integers:
r2 = 10
FOR N = –211 TO 453 STEP 12
CELLS(R2, 2)=N
R2 = R2 +1
NEXT N
When this loop is executed, the loop index n assumes the values −211, −199,
…, 437, 449. CELLS(10,2) to CELLS(65,2) are filled in. In the argument of CELLS,
the row number comes first and the column number second. Cells B10 to B65 are
therefore filled in with −211, −199, …, 449.
A further example is the loop in SUB Circles(), in which the sub-routine Disc is
called three times:
FOR I = 1 TO 3
CALL DISC(I*50+60, I*25)
NEXT I
Task Develop a macro for drawing a row of rectangles! “Develop” means that
you get the instructions with RECORD MACRO and redesign the recorded macro using
variables, sub-routines, and loops.
Task Write a macro that draws a (4 × 4) array of filled circles, the colors thereof
being composed of fractions of red and green, with the green fraction systemati-
cally increasing in each row and the red fraction systematically increasing in each
column!
SUB DRAWI1 in Fig. 4.13 (P) is the main program that randomly calls one of the sub-
routines Rect, Ova, or Tria, ten times in each of eight rows, drawing a rectangle,
ellipse, or triangle at the current position of x and y. Its core is a nested loop with
two loop indices, k for the row and i for the column address within a row.
The variable ROT in SUB drawi1 determines whether a rectangle, an ellipse
(oval) or a triangle shall be drawn. In line 5, the variable ROT is randomly assigned
a value 0, 1, or 2. Chance is brought in by the function RND() generating a random
number between 0 and 1, which is then multiplied by 3. This real number is turned
into an integer by INT (into the variable ROT). To give some examples: INT(0.75*3)
= INT(2.25) = 2; INT(0.22*3) = INT(0.66) = 0; INT(0.54*3) = INT(1.53) = 1.
4.4 A Checkerboard Pattern (Excel) 133
Fig. 4.12 a (left) A checkerboard pattern of rectangles, circles and triangles, all equally formatted,
drawn with SUB drawi1 in Fig. 4.13 (P). b (right) Like a, but with forms differently formatted, filled
with different colors, and surrounded with borders of different thickness and different color, drawn
with SUB drawi in Fig. 4.14 (P)
Fig. 4.13 (P) Procedure SUB drawi1 with which Fig. 4.12a is drawn
Task First, draw only one row by omitting the loop (FOR k = …)! The sub-
routines Rect(x,y), Ova(x,y) and Tri(x,y) should be written according to the model
of sub Disc(x,y) in Fig. 4.10b (P). Apart from MSOSHAPEOVAL, MSOSHAPERECTANGLE
and MSOSHAPETRIANGLE have to be used.
Fig. 4.14 (P) SUB drawi is the main program calling, 10 times in each of 8 rows, one of the sub-
routines Rect, Ova, or Tria, which draw a rectangle, ellipse, or triangle at the current position of x
and y. Similar to Fig. 4.13 (P), but with parameters stored in global variables x, y defined in line 1
Fig. 4.15 (P) SUB Rect draws a rectangle with a fixed size, but with randomly selected colors for
the border (line 3) and interior (line 5). The instructions for coloring are executed in the Lin and
Interi sub-routines in Fig. 4.16 (P)
Global variables are also valid in sub-routines. They must be declared as PRIVATE
or PUBLIC before the routines (see line 1 in Fig. 4.14 (P)). Variables of type PRIVATE
are only available in the module in which they are declared, those of type PUBLIC
in the whole workbook. The positions (Left, Top) of the shapes are now stored in
global variables x and y that can be read and modified by each sub-routine.
The data type SINGLE in line 1 of Fig. 4.14 (P) denotes a single-precision
floating-point number stored in 4 bytes. Decimal numbers of the data type DOUBLE
are stored in 8 bytes. You can find out more about other data types with EXCEL
help in the VBA-Editor.
Don’t just copy the macros if you already have some programming
practice! Rehearse the sequence of instructions in your mind and get
the commands for drawing shapes through macro recording!
In SUB Rect in Fig. 4.15 (P), a square is drawn, and its interior and border are for-
matted with the sub-routines Lin and Interi in Fig. 4.16 (P). The position is taken
from the global variables (x, y) and passed to MSOSHAPERECTANGLE through the
procedure header of AddShape. Both side lengths are fixed to 10. The arguments
4.4 A Checkerboard Pattern (Excel) 135
Fig. 4.16 (P) SUB Lin and SUB Interi color the border and the interior of the shape (line 2), respec-
tively, according to the variables r (red), g (green), and b (blue). The thickness (weight) of the
border is specified in w, set to 10 in Fig. 4.15 (P)
in the headers of Lin and Interi are generated in SUB Rect(...) with RND() which
returns a random number between 0 and 1.
Questions
4.5.1 Turtle
In order to draw a set of shapes with Python, we use the library turtle. This
simple plot program’s illustrative idea is that of turtles running across the screen,
thereby creating colorful traces.
In Table 4.1, the libraries turtle and numpy.random are imported and a
turtle named t is created. This will be the first cell in every program; it must
be run before the functions are compiled, because they resort to these libraries.
Generally, several turtles can be active at the same time. We use, however, only
Table 4.1 Importing relevant libraries; creating a screen with a title; the internet address in line
1 points to an introduction to Turtle graphics
1 #https://docs.python.org/3.3/library/turtle.html
2 import turtle
3 import numpy.random as npr
4 t=turtle.Turtle() #Creates a turtle with name t
5 turtle.title("Checkerboard")
Fig. 4.17 a (left) Turtle screen created by the Python program in this section, in a frame spanned
by the points (−400, −400) and (400, 400). b (right) Triangles of different size and at different
positions in a square
one turtle instance called t. In the second cell in Table 4.1, a screen is created
with a program-specific name, here, Checkerboard.
The standard size of the screen is 1000 pt × 800 pt spanned between (−500,
−400) to (500, 400). Such a screen with a checkerboard pattern is shown in
Fig. 4.17a. Turtle and EXCEL apply coordinate systems with different origins.
In EXCEL, it is at the upper left corner of the spreadsheet, and all coordinates are
positive. In Turtle, the origin is at the center of the screen, and the coordinates
are positive or negative.
Attention: The turtle window may be below the Python window.
in contrast to the equilateral triangle at top left. The bottom right triangle has its top
point at the midpoint of the upper side of the square. It is shifted in the upper right
figure so that its centroid coincides with the square’s center.
Measurements:
Question
How do you get the position of a turtle named doro in polar coordinates? There
are two possibilities.16
Table 4.2 Function drawSquare in Python, drawing a square with center (x, y) and size sz that
is filled if the keyword variable fill is set to True
1 def drawSquare(x,y,sz,fill=False):
2 r=sz/2
3 t.pu() #Pen up!
4 t.setpos(x-r,y-r) #Run to position!
5 t.pd() #Pen down!
6 if fill==True: t.begin_fill()
7 for i in range(4):
8 t.fd(sz) #Forward!
9 t.lt(90) #Turn left!
10 if fill==True: t.end_fill() #Fill square with color!
11 t.pu()
12 t.setpos(x,y)
Global parameters
The first line in the VISUAL BASIC program in Fig. 4.18, before the procedures, defines
an array col of integers with three elements accessible in the whole module. It is
written in the main program on lines 4 to 6 and read in drawSquare on line 21.
In Python, arrays can be declared anywhere in the program, e.g., by col = [100,
200, 0]. All variables, as well as arrays, are valid in subordinate functions unless the
variable name is again declared in a function with an equal sign, e.g., col = [10, 100,
10], creating a new object with own memory space.
Case-sensitivity
Python is case-sensitive: True and False have to be written with capital T and F;
x and X are two different variables. Visual Basic is case-insensitive: an input “true”
is automatically changed to “TRUE”; x and X are regarded as the same variable. When
we change the case of the first letter anywhere in the program, names in other places
will automatically adapt.
In the three functions mentioned above, the turtle runs along a shape, starting
at its current position and with its current direction. It was, however, intended by
the programmer that the turtle start running straight to the right. This is indeed
140 4 Macros with Visual Basic and Their Correspondences in Python
assured in our current main program, but nevertheless, not making this intention
explicit is considered a big mistake in Software Engineering.
Questions
The turtle named t in Tables 4.2, 4.3, and 4.4 is a global instance accessed
within the functions. This is possible because you have only one turtle running.
What do you do if several turtles are on the field?17
In Table 4.4, it is implicitly assumed by the programmer that the turtle is
heading straight to the right at start, a big programming mistake. How do you
avoid this bug?18
17 The turtle name has to be an argument, e.g. t, def drawSquare(t, x, y, sz, fill
= false), so that it is no longer regarded as a global instance in the functions.
18 Introduce t.setheading(0) before the turtle starts running. If necessary, store the orig-
inal direction at the beginning, e.g., phi0 = t.heading() and reset it at the end with
t.setheading(phi0).
4.5 A Checkerboard Pattern (Python) 141
Table 4.6 Drawing the checkerboard pattern with a nested loop; when lines 3 and 20 are activated,
the turtle runs faster
1 turtle.clearscreen()
2 t=turtle.Turtle()
3 #turtle.tracer(0, 0)
4 #Draw checkerboard pattern
5 for rn in range(-280,285,80):
6 for c in range(-360,365,80):
7 r=npr.rand()
8 g=npr.rand()
9 b=npr.rand()
10 tup=(r,g,b) #Red, green, blue
11 tup2=(g,b,r) #g=Red, b=green, r=blue
12 t.pen(pencolor=tup2, fillcolor=tup,
13 pensize=4, speed=0)
14 if r<0.33:
15 drawTria(c,rn,60,fill=True)
16 elif r<0.67:
17 drawSquare(c,rn,60,fill=True)
18 else: drawCircle(c,rn,60,fill=True)
19 t.dot()
20 #turtle.update()
The function dash in Table 4.5 draws a dash at the current position perpendic-
ular to the current turtle heading, of extension ds to both sides.
Main program
The main program has three parts. The first part is shown in Table 4.1, importing the
necessary libraries and creating a screen with the title Checkerboard. Then, in Table
4.6, the checkerboard pattern is drawn with a nested loop over 10 x positions and 8
y positions, with randomly choosing one of our three shapes.
Before we call the draw* functions, the pen specifications have to be set in the main
program, pencolor and fillcolor in our program, by rgb (red, green, blue) in
standard mode with values between 0 and 1, randomly chosen with npr.rand().
142 4 Macros with Visual Basic and Their Correspondences in Python
The keyword variable pencolor expects a tuple with 3 elements to specify the
color. The individual variables r (red), g (green), b (blue) are set in lines 7 to 9 and
assembled into two different tuples, tup for fillcolor and tup2 for pencolor.
Questions
19 The function drawTriangle draws a triangle with all angles equal to 60° so that it becomes
equilateral.
20 Let the turtle run with setpos(..) along (x-sz/2,y-sz/2), (x + xz/2,
What is the direction of the turtle after having been guided by the code
snippet in Table 4.7?21
We trigger variant (3) when we activate lines 8 and 25 in Table 4.6. The instruction
turtle.tracer(0,0) eliminates the millisecond delays that occur when the
screen is updated after every turtle change. The screen is refreshed with the complete
picture by turtle.update() (Table 4.8).
We draw two different stackings of three planes with densely packed spheres
that correspond to the cubic face-centered (fcc) or hexagonal dense-packed
(hdp) crystal structure.
21 The turtle turns 90 + 180 + 180 – 90 = 360° = 0° toward its original direction.
144 4 Macros with Visual Basic and Their Correspondences in Python
A B C D E F G H
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Fig. 4.19 (S) Hexagonally packed plane, drawn with SUB DIEB from Fig. 4.22 (P), here, however,
in half-size
Fig. 4.20 Two densely packed planes and only two “atoms” in the third plane; dark grey “atom”
with dotted border top left: position as in the hexagonal close packing (hcp); middle grey “atom”
with black border: position as in the face-centered cubic (fcc) shape; the drawing is obtained with
Tables 4.11 and 4.12
of the first disc are passed. An extended main program puts a second plane onto
the gaps in the first plane, and ultimately places two discs, one at a position typ-
ical of the face-centered cubic (fcc) structure and the other one characteristic of
hexagonal densest packing (hdp), resulting in Fig. 4.20.
Questions
Fig. 4.21 a (left) Geometry of a hexagonal packing in a plane, displacement of the second row of
atoms with respect to the first row of atoms. b (right) Position of an atom in the second plane
The drawings in Fig. 4.21 indicate the coordinates of the centers of the circular
disc in the planes. Figure 4.21a gives the position of a disc in a row relative to
the previous row, and Fig. 4.21b that of a disc in a plane relative to the previous
plane.
– It lies exactly above the first plane, as in the crystal structure of hexagonal close
packing (hcp). For the drawing in Fig. 4.20, only one circular disk is placed in
the correct position (dark grey, top left in the picture).
– It lies above the still visible gaps in the first plane, as in the cubic face-centered
(fcc) crystal structure. In Fig. 4.20, this is done only for one circular disk,
drawn in middle grey with a black border. The displacement of the third plane
in the x- and y-directions is, for fcc, twice as large as the displacement of the
second plane, both with respect to the first plane.
The positions of the discs in the following list are deduced from Fig. 4.21:
d disc diameter
(x 0 , y0 ) position of the first disc, top left
(delX, delY ) shift of a plane with respect to (x0 , y0 )
delX = 0, delY = 0 for the 1st plane
delX = d/2 for the 2nd plane (see Fig. 4.21b)
delY = −d/2·tan(30/180·π) for the 2nd plane (see Fig. 4.21b)
with:
d34 = d · 3/4 (4.1)
4.6.3 Excel
A row of discs
We draw four rows of circular disks so that the disks touch each other, using four
consecutive FOR-loops (see SUB DiEb Fig. 4.22 (P)).
The sub-routine SUB Disc(x,y), already reported in Fig. 4.10b, is called with
individual positions x, y passed via the procedure header. Contrary to the figure,
the disc’s diameter is set in the main procedure to d = 100. In each row, the x-
position of the following circle is shifted to the right by a circle’s diameter. The
y-position is always the same for a row.
Stacking planes
To draw several planes, one on top of the others, we convert the main program DiEb
described above into the sub-routine SUB Plane(delX, delY) (repeated in Fig. 4.23
(P)) to which the coordinates of the top left disc are transferred. The displacements
delX and delY can be determined with the help of Fig. 4.21b.
4.6 Drawing Densely-Packed Atomic Layers; Crystal Physics 147
1 Sub DiEb() 15
2 x0 = 100 '3rd row of discs 16
3 y0 = 100 dx = 0 'shift with respect to 1st row 17
4 d = 100 'diameter of the disc dy = d * Sqr(3 / 4) * 2 18
5 '1st row of discs For i = 0 To 7 19
6 For i = 0 To 7 Call Disc(x0 + dx + i * d, y0 + dy) 20
7 Call Disc(x0 + i * d, y0) Next i 21
8 Next i '4th row of discs 22
9 '2nd row of discs dx = d / 2 'shift with respect to 1st row 23
10 dx = d / 2 'shift with respect to 1st row dy = d * Sqr(3 / 4) * 3 24
11 dy = d * Sqr(3 / 4) For i = 0 To 6 25
12 For i = 0 To 6 Call Disc(x0 + dx + i * d, y0 + dy) 26
13 Call Disc(x0 + dx + i * d, y0 + dy) Next i 27
14 Next i End Sub 28
Fig. 4.22 (P) SUB Dieb for drawing a plane; the four rows of atoms are drawn using four loops,
result shown in Fig. 4.19 (S)
Fig. 4.23 (P) SUB DiEb is converted into a sub-routine Plane to which the initial coordinates are
transferred by a higher-level program
In the main program SUB hcp fcc in Fig. 4.24 (P), SUB Plane is called twice,
for the initial layer with delX = 0 and delY = 0 and for the second layer with its
1 Sub hcp_fcc() dy = 0 10
2 x0 = 100 dx = 100 * 1 11
3 y0 = 100 Call Disc(x0 + dx, y0 + dy) 12
4 Call Plane(0, 0) 'fcc 13
5 delx = 100 / 2 dy = 100 * Sqr(3 / 4) - 100 / 2 * Tan(30 _ 14
6 dely = 100 / 2 * Tan(30 _ / 180 * 3.14159265) 15
7 / 180 * 3.14159265) dx = 100 * 5 16
8 Call Plane(delx, dely) Call Disc(x0 + dx, y0 + dy) 17
9 hdp End Sub 18
Fig. 4.24 (P) Main program, which calls SUB Plane twice, places two atoms on top (with SUB Disc
from Fig. 4.10b (P)), and thus draws a picture similar to Fig. 4.20
148 4 Macros with Visual Basic and Their Correspondences in Python
discs on the gaps of the first layer. There are two possibilities for the third plane,
hcp or fcc, represented with one disc each in lines 12 and 17.
Questions
In Fig. 4.23 (P), the variables in the header are called delX and delY. In the
body of the procedure, the formulas refer to different names, delx and dely.
Will this discrepancy lead to error messages?24
How do you have to change SUB Disc in Fig. 4.10b (P) so that d becomes a
global variable?25
Task Group your drawing into an image of type png, tif , or some other image
format, and copy this image to another area of the spreadsheet or to another appli-
cation, e.g., to a PowerPoint file! To do so, select the object, click COPY, move
the cursor to another location in the table, click PASTE/PASTE SPECIAL, and select the
desired format.
4.6.4 Python
In the first cell of Table 4.9, the relevant libraries are imported. In the next cell,
a screen with the name “Crystal planes” is created, and global parameters are
specified, with the disc diameter d being set to 50 and the position of the first disc
in the upper left corner at (x 0 , y0 ) = (−175, 175). In the third cell, the first row of
discs is drawn, comprising eight discs drawn from left to right, using the function
drawCircle in Table 4.4. When developing the program, you should check this
snippet of code and see whether a row of gray discs is really plotted from left to
right.
Comments concerning Table 4.9:
Table 4.9 Importing relevant libraries; creating a screen and setting global parameters; drawing
1st row of discs, function disc from Table 4.4
1 #https://docs.python.org/3.3/library/turtle.html
2 import turtle
3 import numpy as np
4 import numpy.random as npr
5 turtle.clearscreen()
6 t=turtle.Turtle() #Create turtle with name t!
7 turtle.title("Crystal planes")
8 tup=(0.9,0.9,0.9) #Light grey
9 t.pen(pencolor="black", fillcolor=tup, pensize=1, speed=10)
10
11 x0=-175
12 y0=175
13 d=50 #Disc diameter
14 #1st row of discs
15 dx=0
16 dy=0
17 for i in range(8):
18 drawCircle(x0+dx+i*d,y0+dy,d,fill=True)
19 print(t.pos()) #Current position
Table 4.10 Function for drawing a close-packed plane; delX, delY position of top left disc with
respect to (x 0 , y0 ), drawCircle from Table 4.4
1 def Plane(delX,delY):
2 #1st row of discs
3 dx=0+delX
4 dy=0+delY
5 for i in range(8):
6 drawCircle(x0+dx+i*d,y0+dy,d,fill=True)
7 #2nd row of discs
8 dx=d/2+delX
9 dy=-d*np.sqrt(3/4)+delY
10 for i in range(7):
11 drawCircle(x0+dx+i*d,y0+dy,d,fill=True)
12 #3rd row of discs
13 dx=0+delX
14 dy=-d*np.sqrt(3/4)*2+delY
15 for i in range(8):
16 drawCircle(x0+dx+i*d,y0+dy,d,fill=True)
17 #4th row of discs
18 dx=d/2+delX
19 dy=-d*np.sqrt(3/4)*3+delY
20 for i in range(7):
21 drawCircle(x0+dx+i*d,y0+dy,d,fill=True)
150 4 Macros with Visual Basic and Their Correspondences in Python
Questions
To produce a figure like that in Fig. 4.20, two planes and, additionally, two
discs have to be placed at appropriate positions. The function for drawing a close-
packed plane is shown in Table 4.10. Its arguments are the shifts delX and delY of
the first disc’s position with respect to (x 0 , y0 ). The four rows of discs are drawn
with loops calling drawCircle (from Table 4.4), always with the same variables,
but with dx and dy set for each row individually, according to Eq. (4.1).
The first two planes are drawn with the program in Table 4.11. Two atoms in the
third plane representative of the hexagonal-dense packed and face-centered cubic
structures, respectively, are drawn in Table 4.12. For hdp, the position is just on
top of a disc in the first plane, whereas for fcc, x and y get a double shift from a
disc in the first plane, whereby the x position becomes identical to the neighboring
disc in the first plane and the y position is in the center of a gap in the second
plane.
Question
26 The position of the turtle after the first row is x = -175 + 7·50 = +175; y = 175, as can be
deduced from lines 18 and 19 in Tab. 4.9.
27 pencolor = "black", fillcolor = tup, tup = (0.9, 0.9, 0.9), a light gray.
28 The disc diameter d is a global parameter accessed in drawCircle. It is also used in line 18
to specify the shift of the position of the current disc with respect to the preceding one.
29 When the value of the global parameter d is changed, these instructions do not follow. Set dx =
Table 4.12 Drawing an atom of the third plane, either hdp or fcc
26 #hdp
27 tup=(0.3,0.3,0.3) #Dark grey
28 t.pen(pencolor="black", fillcolor=tup,pensize=1, speed=0)
29 dx=50*1
30 dy=0
31 drawCircle(x0+dx,y0+dy,d,fill=True)
32
33 #fcc
34 tup=(0.6,0.6,0.6) #Middle grey
35 t.pen(pencolor="black", fillcolor=tup,pensize=1, speed=0)
36 dx=50*5
37 dy=-50/2*np.tan(30/180*np.pi)*2
38 drawCircle(x0+dx,y0+dy,d,fill=True)
Swirling characters
Text It is siad taht a txet can be undesrtood eevn if you lvaee olny the begiinnng
and the end lteter in ecah wrod in plcae but exahcnge middle lettsre. Do you
beileve taht or is it nonnesse?
Task Write a pogrram that fsirt rades a text from a sersadehept. This text is then
to be bokren down into wsodr. The idnuvidial words are tnorsfarmed so that the
frsit and last letrets raiemn in pcela, but the iennr ltrtees are ramlondy swapped.
Text It is said that a text can be understood even if you leave only the beginning
and the end letter in each word in place but exchange middle letters. Do you
believe that, or is it nonsense?
Task Write a program that first reads a text from a spreadsheet. This text is then
to be broken down into words. The individual words are transformed so that the
first and last letters remain in place, but the inner letters are randomly swapped.
Splits a string expression into words and stores them in an array. Unless
otherwise specified, a space is interpreted as a separator between words.
LEN(STRING) len(String)
Cuts out a piece of length Length from a character string starting from the
left.
Cuts out a piece of length Length from a character string starting from the
right.
Questions
Let the variable Tx contain the text “Cutting out”. With which instructions do
you get the first, last, and second characters of Tx? How do you copy the string
“ing” from Tx to a new variable Wd? In Visual Basic,30 in Python?31
Consider the string Sente = “This is. Our goal.” How do you separate the
string into the two sentence fragments terminated by full stops? Use the Split
command! How do you get a new string JS = “This is.” including a full stop?
EXCEL?32 Python?33 Compare!
30 LEFT(Tx, 1), RIGHT(Tx, 1), MID(Tx,2, 1), Wd = MID(Tx, 5, 3); the first character has index 1.
31 Tx[0], Tx[-1], Tx[1], Wd = Tx[4:7]; the first character has index 0.
32 SINGSENT = SPLIT(SENTE, "."): DIM NEWSENT(1) AS STRING: NEWSENT(0) = SINGSENT(0): NEWSENT(1) = ".":
JS = (NEWSENT, ""), 5 statements; the colon is the separator between statements in a line.
33 SingSent = Sente.split(“.”); JS = ‘’.join ([SingSent[0], “.”]),
2 statements; the semicolon is the separator between statements in a line.
154 4 Macros with Visual Basic and Their Correspondences in Python
In the VISUAL BASIC program in Sect. 4.7.3, we use one array of words containing
the original words at the beginning and the new words at the end. In Python
in Sect. 4.7.6, we are using two arrays: Words, with original data remaining
unchanged, and WordsNew obtained consecutively by appending one scrambled
word after the other.
4.7.3 Excel
In the following, first, a complete program (main program Scramble and sub-
routine XWord) that solves the task is introduced. Do not copy it, but rather
continue reading! Then, the program is developed step by step in test macros to
follow the effect of the individual instructions.
Please be aware that, in the following continuous text, according to our spelling
convention, the words in SMALL CAPS are VBA internal terms, while the words in
italics are invented by the programmer.
Split (Sentence)
The main program Scramble() (Fig. 4.25 (P)) reads a text from cell A1 of the spread-
sheet (Text = CELLS(1,1)), splits it into words (Words = SPLIT(Text), line 3) and passes
the words one by one to the sub-routine XWord(Word) (line 7) which exchanges
two letters. If two letters are to be exchanged for a second time, line 8, now com-
mented out, has to be activated. The instruction SPLIT specifies the variable Words
automatically as an array. For the data type array, see Sect. 4.7.5.
The sub-routine XWord (Word) (Fig. 4.26 (P)) splits the word transferred via
the header into individual letters (lines 18–22), randomly exchanges two inner
letters (lines 23–28), puts together the new word in lines 30 to 34, and returns
the modified word to the higher-level procedure from which the sub-routine was
called.
Fig. 4.25 (P) SUB Scramble reads a text from cell A1, splits it into words stored in the array Words,
and passes the words one by one to the sub-routine XWord. The words returned by XWord (in the
variable Word in the header) are assembled into a new sentence in line 10 and output to cell A7
(CELLS(7,1)) of the spreadsheet. Line 8, now a comment, has to be activated when two letters are
to be exchanged for a second time
4.7 Text Processing 155
Fig. 4.26 (P) SUB XWord detects the length of the transferred word (line 16), splits it into letters
(lines 18–22), swaps two inner letters (lines 23–28), and reassembles the letters into the modi-
fied word (line 31). Commented lines 21 and 32 have to be activated to obtain SUB XWord Test,
mentioned in Sect. 4.7.4
Join (Sentence)
The main program SUB Scramble in Fig. 4.25 (P) reassembles the modified words
into a text (newText = JOIN(Words, “ ”), line 10) and writes it into cell A7 (Cells(7,1)
= newText). The second entry “ ” in JOIN causes a space to be inserted after each
element of the array Words.
– CELLS(r, c): cell in the row r and column c of the current spreadsheet,
– FOR … TO …; DO WHILE … LOOP; ON ERROR GOTO;
– The functions SPLIT(…); JOIN(…); INT(…); RND().
– a, b, c, d, e, f, g, h, i, j, k,
All combinations of letters and numbers are allowed as variable names, but the
first character must be a letter. Such names are italicized in the text. To keep the
program clear, you should choose variable names that easily convey their meaning
in the program.
Attention: l (small el) and I (capital i) can easily be confused! Variable names
in different places of the program then look the same but designate two different
variables. So, it is better to use a capital L: LWord instead of lWord.
Questions
What should lines 2 and 11 of Fig. 4.25 (P) be if the statement is formulated
with RANGE instead of CELLS?34
Which variable names in Fig. 4.25 (P) did the programmer come up with
himself/herself?35
Which variable names in Fig. 4.26 (P) did the programmer come up with
himself/herself?36
Do lines 23 and 24 of Fig. 4.26 (P) guarantee that two letters are always
exchanged?37
Step by step, we develop a program that performs the text swirling described in
Sect. 4.7.1. It interacts with the spreadsheet, i.e., reads from cells and fills in the
spreadsheet cells as shown in Fig. 4.27 (S).
A B C D
1 A sentence is to be decomposed. A s s
2 sentence e e
3 is n n
4 to t t
5 be e n
6 decomposed. n e
7 A sentnece is to be decomposed. c c
8 e e
Fig. 4.27 (S) A1 contains the sentence to be processed. B, C, D, and cell A7 are filled in by the
program. The individual words are in B, the individual letters of the second word are in C, those
of the swirled word in D
We modify the procedures SUB Scramble in Fig. 4.25 (P) by activating the still
out-commented line 5 (filling in column B of Fig. 4.27 (S)) and SUB XWord by
activating lines 21 (filling in column C) and 32 (filling in column D).
The sub-routine XWord Test(Word) is the same as XWord(Word) in Fig. 4.26
(P), however, with the lines 21, 22, and 33 to 35 activated that now output
intermediate results into the spreadsheet.
Question
After checking these macros to see if they do what we want them to do, we
transform them into a procedure that reads a sentence from cell A1 and outputs the
changed sentence in A2, like SUB Scramble in Fig. 4.25 (P). We now only swap
letters from the word’s interior, i.e., leave the first and last letters as they are.
Task Do this exercise with other texts as well, and surprise your friends with
playful letters!
For example, [DIM Fel(2) AS DOUBLE] defines an array with three cells (to be
addressed with 0, 1, 2), where each cell can contain a real number of type DOUBLE.
DIM AR(2,3) AS INTEGER defines a two-dimensional array of integers of shape 3 rows ×
4 columns.
4.7.6 Python
The basic functions and methods for text processing, namely, splitting a text into
words, a word into letters, and, the other way around, joining letters to form a new
38 Text read from A1 (CELLS(1,1)), words written into B, letters of the selected word into C, swirled
letters into D (CELLS(R,4)), modified text into A7. Compare with Fig. 4.27 (S)!
158 4 Macros with Visual Basic and Their Correspondences in Python
word, are presented in Table 4.13. The join() method creates a new string from
“precursor strings”, e.g., a list of letters. The letters in the new word are separated
by a colon as specified in a prefix to join (see lines 5).
These basic functions are again applied in Table 4.14 to split a longer text
into words, pass each individual word to the function ExchLett (reported in Table
4.15), and join the scrambled words into a new text, with blanks as separators. The
content of the variable Text starts with three quotation marks """, indicating that
the following text covering several lines up to the next three quotation marks """
is a string. To enter multi-line strings, use triple codes to start and end them!39
The function ExchLett in the third cell of Table 4.15 uses the function
random.sample from the random library to choose two different internal
letters and then exchange them. This function was found with a search in stack-
overflow.com. Its syntax and mode of action can be deduced from the second cell,
which presents the result of line 23.
In lines 30 to 32, the temporary variable L 0 is introduced in order to swap two
variables. The code in line 34 does the same, but without the use of any temporary
variable. In Python, a backslash (\) indicates that the instruction line is continued.
Statements can also be split up after a comma.
39 https://stackoverflow.com/questions/10660435/pythonic-way-to-create-a-long-multi-line-
string.
4.7 Text Processing 159
Table 4.14 Rewriting scrambled words in a text a (left) program; b (right) result
10 Text="""It is said that you can read a text also if you
leave only the beginning and the end letter in each word as
they are and swirl two middle letters. Do you believe that
or is it nonsense?"""
11
12 Words=Text.split()
13 WordsNew=[]
14 for i in range(len(Words)):
15 WN= ExchLett(Words[i])
16 WordsNew.append(WN)
17 sentNew=' '.join(WordsNew) #Concatenate with blank
18 print(sentNew, "\n")
It is siad taht you can raed a txet aslo if you lvaee olny the
beginning and the end lteter in ecah wrod as tehy are and
swril two mildde ltteers. Do you belveie taht or is it
noesnnse?
Questions
Write lines 30 to 32 of Table 4.16, swapping two variables using the temporary
variable L0, as one statement!40
How can lines 5 and 6 of Table 4.15 be merged into one statement?41
How can you introduce an additional line of code into Table 4.16 to achieve
two letter swappings in a word?42
Table 4.16 processes the second text passage, now performing two letter
exchanges.
the knowledge gained in this exercise, you may earn a small bit of extra
income from a side job in scientific projects!
Many measuring devices output a plain-text file as a protocol containing both text
and numbers. As an example, we will use the output of chemical analysis with RBS
(Rutherford Back Scattering) concerning the composition of four Nb-doped TiO2
layers on a silicon substrate (spreadsheet in Fig. 4.28 (S)). Every layer contains
different fractions of Ti (titanium), O (oxygen), Nb (niobium), and Ar (argon). We
will convert this information into a table, as in Fig. 4.29 (S).
A B C D
1 T1.lay T2.lay T3.lay T4.lay
2 !----------------- !----------------- !----------------- !------------------
3 d=0.20E18 d=0.25E18 d=0.30E18 d=0.35E18
4
5 Ti#,1 Ti#,1 Ti#,1 Ti#,1
6 O#,2.5 O#,2.4 O#,2.3 O#,2.2
7 Nb#,0.03 Nb#,0.05 Nb#,0.07 !------------------
8 Ar#,0.01 !----------------- Ar#,0.008 s=
9 !----------------- s= !----------------- Si#,1
10 s= Si#,1 s=
11 Si#,1 Si#,1
Fig. 4.28 (S) Protocol of RBS measurements, transferred into an EXCEL spreadsheet; row 1 =
names of four different samples; parameters: d = number of atoms per cm2 ; Ti, O, Nb, Ar =
elements found in the layer with their indices in the chemical formula
A B C D E F
1
2 SampNam NAtoms Ti O Nb Ar
3 T1 2,00E+17 1 2,5 0,03 0,010
4 T2 2,50E+17 1 2,4 0,05
5 T3 3,00E+17 1 2,3 0,07 0,008
6 T4 3,50E+17 1 2,2
7
Fig. 4.29 (S) The data from Fig. 4.28 (S) have been written into this table in a spreadsheet with
the name “TabLay”. Each sample has its own row. The first row is left blank in order to insert an
index for the next free row later
162 4 Macros with Visual Basic and Their Correspondences in Python
Fig. 4.30 (P) Cuts off the first two letters of a data string (line 39) and checks whether this is the
code word “d =”
Fig. 4.31 (P) Complete program for rearranging the raw data from Fig. 4.28 (S) into a table as in
Fig. 4.29 (S); continued in Fig. 4.32 (P)
The information in a column of Fig. 4.28 (S) is to be decoded and stored in a row
of Fig. 4.29 (S). The main task is to identify certain code words that indicate the
physical or technical quantity to which the following numbers refer. An extract
from the complete Visual Basic decoding program (Fig. 4.32 (P)) can be found in
Fig. 4.30 (P).
The data set for a layer is read line by line. The data strings “d = 0.20E18” and
“Ti#,1” contain information about the number of atoms per cm2 and the titanium
content in the sample, respectively. When the program processes the file, it is not
clear from the outset what type of data string is currently involved. For decoding,
therefore, the first parts of the data line are separated (line 39 in Fig. 4.30 (P)),
and it is queried as to whether this part is “d =” (line 40). If this is the case,
the following string is interpreted as a number and written into the corresponding
variable; for “d =”, this is NAtoms (line 40 in Fig. 4.30 (P)).
In Python, the task is tackled with the library Pandas, which mimics
spreadsheet calculation.
4.8.4 Excel
The complete decoding procedure can be found in Fig. 4.31 (P) and Fig. 4.32 (P).
SUB DecodeRBS writes headings into the spreadsheet “TabLay” (lines 7 to 13),
successively reads rows 3 through 30 from the spreadsheet “RBSData” (line 23,
index r1), determines the last row of useful data (line 26), decodes the useful data
(FOR loop in rows 36 through 47), and finally writes the decoded data row by row
(index r 3 ) into the spreadsheet “TabLay” (rows 49 through 55).
The loops are of type loop2i, with the loop index r and the running index r 3 ,
indicating the next free row in the table and set to 2 at the beginning (line 6)
and incremented in line 56 after the extracted values for the parameters have been
entered into the output table within the For-loop with the index r scanning the
input table.
Since the code words have different lengths (“d =” has two letters, “Ti#,” has
four letters), in lines 39, 41, and 43, two, three, and four letters are, one after the
other, cut off from the beginning of the data string and it is checked as to whether
they correspond to one of the code words. The part of the data string following
the cut-off contains a number separated with RIGHT(..) and then assigned to the
corresponding variable (e.g., NAtoms, Ti, …). This separation is easy because all
numbers have the same format.
Questions
Module in VBA
Since the program SUB DecodeRBS refers, with SHEETS(“RBS-data”).SELECT and
SHEETS(“TabLay”).SELECT, to two different spreadsheets, it must be operated in a
module. If it stands in the VBA sheet associated with a spreadsheet, it operates only
in that spreadsheet with instructions like CELLS(r,c) = .
Tim The presented program sorts the data of exactly four samples into another
table. What if a new set of samples comes in and the table is to be continued? Can
the program remember the value of the index r 3 for the next free row and use it
for the next call?
Mag No, the program forgets the values of the variables when it finishes its
execution.
Alac Then, I will simply adapt the code before each new call. In line 14, the
next free row in the table of Fig. 4.29 (S) is entered, r 3 = 7, and for the last FOR
loop index in line 15, I will enter the current number of samples.
43 „d = “ is queried.
44 The code words „Ti#,“, „Nb#,“ and „Ar#,“ have the length 4.
4.8 Processing the Protocol of a Measuring Device 165
Mag That’s a practical idea, and it works. But it can also be done more elegantly
with the following two pieces of program.
You can use the first row in Fig. 4.29 (S), still empty, e.g., cell A1, to store the
number of the first free row after the previous entries, and cell D1 to specify the
number of new samples. This information is then read with r 3 = RANGE(“A1”) in
line 14 and … TO RANGE(“D1”) in line 15. Cell A1 is now overwritten with the
value of r 3 by a new instruction at the end of SUB DecodeRBS. The number of new
samples must be entered manually in D1 when a new data series is to be decoded,
or the programmer can devise a query to automatically determine the number of
samples in the raw data of Fig. 4.28 (S).
DO … LOOP UNTIL
The next free row can also be determined by querying the current cell content in a
loop to see if the current cell is empty:
DO
r3 = r3 + 1
LOOP UNTIL CELLS(r 3 , 1) = EMPTY
Similarly, the number of NOT EMPTYs in a new raw data file can be obtained.
4.8.5 Python
R1C0 in Pandas
In Table 4.17, the EXCEL workbook ‘RBS_data.xlsx’ (Fig. 4.28 (S)) is opened, so that
its data are available in Pandas. Without further specification, the workbook must
be in the same directory as the Python program. The data in Sheet1 are entered into
a two-dimensional matrix sh. This matrix can be addressed in A1 or R1C0 reference
style (see second cell). In A1 style, a column is addressed by a letter and a row by a
number starting at 1; in R1C0 style, both are addressed by numbers, with columns
being numbered starting at 0.
With the statement in line 5, the contents in the cells will be copied directly. If
a cell contains a formula, this formula will be transferred. If it is desired that all
166 4 Macros with Visual Basic and Their Correspondences in Python
Table 4.17 a (top cell) opening an EXCEL workbook; b (bottom cell) addressing cells and ranges
and reading their content
1 import numpy as np
2 import pandas as pd
3 import openpyxl #A Python library to read/write Excel 2010
4
5 wb=openpyxl.load_workbook(‘RBS_data.xlsx')
6 sh=wb['Sheet1']
Sh: <Worksheet "Sheet1">
sh['A1'].value: T1.lay
sh[1][0].value: T1.lay
7 for r in range(1,4):
8 print(sh[r][0].value)
range(1,6):
T1.lay
!--------------------------
d=0.20E18
None
Ti#,1
formulas be evaluated and only the results transferred, the opening has to include
a keyword argument data_only = True:
In Table 4.18, the sample name is extracted from the first entry in c = 0 (column
A), reported in the second cell. The content of the bottom cell is produced by the
print statements shown explicitly in lines 5 to 9. In contrast to this, print statements
Table 4.18 Extracting the sample name from the first entry in column c; print statements resulting
in the output cell (bottom cell) are explicitly reported in lines 5 to 9
1 c=0
2 SN=list(sh[1][c].value)[:-4] #Delete “.lay”
3 SampNam=''.join(list(SN))
4
5 print("sh[1][c] ",sh[1][c])
6 print("sh[1][c].value ",sh[1][c].value)
7 print("list(sh[1][c].value)",list(sh[1][c].value))
8 print("SN ",SN)
9 print("SampNam ",SampNam)
sh[1][c] <Cell 'Sheet1'.A1>
sh[1][c].value T1.lay
list(sh[1][c].value) ['T', '1', '.', 'l', 'a', 'y']
SN ['T', '1']
SampNam T1
4.8 Processing the Protocol of a Measuring Device 167
Table 4.19 Getting the last row of useful information; line 5 contains an error
1 def LastRow(c):
2 for r1 in range(2,15):
3 cl=sh[r1][c] #Cell address
4 if cl.value!=None:
5 cll=''.join(list(cl.value)[:5])
6 #Indentation 4 spaces!
7 if cll=='!----': r2=r1-1
8 return r2
are usually omitted in our tables reporting Python programs; only the results are
usually reported in an output cell.
Questions
In Table 4.19, column c is scanned for the occurrence of “!––”, the code word
signaling the end of the information on the first layer.
Table 4.20 reports the function for decoding the string in the cell in column c,
row r 2 . The Python code mimics the VBA procedure in Fig. 4.32 (P).
In Table 4.21, a data frame out is created reproducing the EXCEL sheet in
Fig. 4.29 (S). A For loop runs over sample with sample data, determining the
last row r 2 with useful information and decodes the range rows 3 to r 2 of the
column. The print statement in line 11 produces the output in the lower cell.
To write the data into an already existing file, we have to open that file and
specify a writer (lines 8 and 9 in Table 4.22).
Functions in modules
We often call built-in functions in cells, e.g., trigonometric functions with formulas
like B5 = [=B$1*cos(B$2*$A5]). We can also create functions ourselves and apply
them in the same way. As an example, we implement a function CosSq(x), calcu-
lating the square of a cosine. This has to be done in a module that we create with
INSERT/MODULE in the project explorer (see Fig. 4.33a).
The function is implemented in the corresponding Visual Basic sheet MODULE1. The
qualifier is FUNCTION, not SUB, as for procedures. For a function, a value must be
4.9 User-Defined Functions 169
Table 4.21 Data frame reproducing the structure of the EXCEL sheet in Fig. 4.29 (S); NaN stands
for “Not a number”
1 out = pd.DataFrame(index=range(1,8), s=list('ABCDEF'))
2 title=['SampNam','NAtoms','Ti','O','Nb', 'Ar']
3 out.iloc[1]=title
#iloc is integer position from 0 to length-1 of the axis
4 for sample in range(4):
5 SampNam=sh[1][sample].value
6 SampNam=SampNam[:-4] #Remove .lay
7 r2=LastRow(sample)
8 nAtoms,Ti,O,Nb,Ar=decode(sample,r2)
9 result=[SampNam,nAtoms,Ti,O,Nb,Ar]
10 out.iloc[sample+2]=result
11 print(out)
12 out.to_excel("output.xlsx",sheet_name="Sheet2",
13 header=False,index=False) #A…F and 1…7 not transferred
#NaN means “Not a number”
A B C D E F
1 NaN NaN NaN NaN NaN NaN
2 SampNam NAtoms Ti O Nb Ar
3 T1 2e+17 1 2.5 0.03 0.01
4 T2 2.5e+17 1 2.4 0.05 None
5 T3 3e+17 1 2.3 0.07 0.008
6 T4 3.5e+17 1 2.2 None None
7 NaN NaN NaN NaN NaN NaN
Table 4.22 a (top cell) Creates a new file and writes the data into the specified sheet; b (bottom
cell) Opens an existing file and adds a new sheet
14 out.to_excel('RBS_data3.xlsx',sheet_name="Sheet3",
15 header=False,index=False)
16 #Creates a new workbook with one sheet “Sheet3”.
17 #Overwrites 'RBS_data3.xlsx' if it exists already.
18 """https://stackoverflow.com/questions/20219254/
19 how-to-write-to-an-existing-excel-file-
20 without-overwriting-data-using-pandas"""
21 wb2 = openpyxl.load_workbook('RBS_data2.xlsx')
22 writer = pd.ExcelWriter('RBS_data2.xlsx',
engine='openpyxl')
23 writer.book = wb2 #Necessary for not deleting other sheets
24 out.to_excel(writer, "data3",header=False,index=False)
25 writer.save()
170 4 Macros with Visual Basic and Their Correspondences in Python
Fig. 4.33 a (left) PROJECT-EXPLORER window; the user-defined spreadsheet function CosSq is in
MODULE1. b (right) CosSq pops up after typing “=Cos” among the other functions starting with cos
assigned to the function identifier within the function’s body, in our case cosSq =
COS(x)ˆ2. When now “=Cos” is written into a cell, a list pops up with all functions
starting with Cos, including our CosSq (see Fig. 4.33b).
If you want to use your functions in every EXCEL file, they must be saved as an
ADD-IN. To do so, create an EXCEL file, enter your function codes into VBA mod-
ules, and finish with: SAVE AS/EXCEL ADD-IN. This add-in must be activated in the
EXCEL options. Upon selecting FILE/OPTIONS/ADD-INS/ a list appears with an entry “
Dieter’s Functions” that must be included by ticking the box . In the VBA edi-
tor, VBA PROJECT Dieters Funktionen.xlam now also appears in the project explorer
under PROJECT–VBA PROJECT (see Fig. 4.33a, bottom line).
We are developing functions for the scalar and vector products of two three-
dimensional vectors stored in cell ranges that are entered as arguments in the
functions. Let’s consider two three-dimensional vectors:
r 1 · r 2 = x1 · x2 + y1 · y2 + z 1 · z 2 (4.2)
r 1 × r 2 = (y1 · z 2 − y2 · z 1 , z 1 · x2 − z 2 · x1 , x1 · y2 − x2 · y1 ) (4.3)
4.9 User-Defined Functions 171
Fig. 4.34 (P) User-defined functions for the scalar product Scl and the vector product Crs of two
three-dimensional vectors r 1 and r 2; ; the function Crsm can process and output both column and
row vectors
The output of the scalar product is one number returned into the cell with the
corresponding formula; that of the vector product is a set of three components to
be entered into a row range or a column range.
These two products are calculated with the two user-defined spreadsheet
functions Scl and Crs in Fig. 4.34 (P).
Questions
How many components does the array cs(2) in Fig. 4.34 (P) have?47
What are the differences between the arrays named cs in the functions Crs
and Crsm in Fig. 4.34 (P)?48
Scalar product
The scalar product is easy to program. It can be calculated in one code line (line 2
in Fig. 4.34 (P)). Two three-dimensional cell ranges must be entered as arguments.
These can both be column ranges or both row ranges or one column range and one
row range (see Fig. 4.35 (S)). Consequently, the variables in the function header are
declared as RANGE.
Vector product
The result of a vector product is again a vector. In Fig. 4.36 (S), two column vectors
a and b are defined in range A2:B4. The row vectors c and d in range B6:D7 contain
the same coefficients as a and b. In column D, the cross-product a x b is calculated
with spreadsheet formulas.
47The array DIM cs(2) has the three components cs(0), cs(1), cs(2).
48In Crs, a one-dimensional array (type cs(2)) is written, in Crsm, a two-dimensional array (type
cs(2,2)).
172 4 Macros with Visual Basic and Their Correspondences in Python
A B C D E F G H I J K L
1 a b 12 =Scl(A2:A4;B2:B4)
2 1 2 c_ 1 2 3 12 =Scl(A2:A4;E3:G3)
3 2 2 d 2 2 2 12 =Scl(a;b)
4 3 2 12 =Scl(c_;d)
5 12 =Scl(a;d)
Fig. 4.35 (S) Contains the results of the user-defined spreadsheet function Scl, which calculates
the scalar product of two three-dimensional vectors
A B C D E F G H I J K L M N O
) )
;b) _;d) _;b) (a;b) (c_;d (c_;b
1 a b axb =crs(a =crs(c =crs(c =crsm =crsm =crsm
2 3,0 -2,0 -10,0 =A3*B4-B3*A4 -10,0 -10,0 -10,0 -10,0 -10,0 -10,0
3 2,0 8,0 -20,0 =A4*B2-B4*A2 -10,0 -10,0 -10,0 -20,0 -20,0 -20,0
4 2,5 5,0 28,0 =A2*B3-B2*A3 -10,0 -10,0 -10,0 28,0 28,0 28,0
5
6 c_ 3,0 2,0 2,5 -10,0 -20,0 28,0 =crs(a;b) -10,0 -20,0 28,0 =crsm(a;b)
7 d -2,0 8,0 5,0 -10,0 -20,0 28,0 =crs(c_;d) -10,0 -20,0 28,0 =crsm(c_;d)
8 -10,0 -20,0 28,0 =crs(a;d) -10,0 -20,0 28,0 =crsm(a;d)
Fig. 4.36 (S) The vector product a x b is calculated in column D using spreadsheet formulas; the
range G2:I8 contains results of the user-defined function crs, which can only output row vectors
(wrong results in G2:I4); the range L2:N8 contains results of the user-defined spreadsheet function
crsm, which can accept and output row and column vectors
In columns G to I, the function Crs is used. As you can see from the results, this
function accepts row and column vectors as input, but only returns correct values
if they are output as row vectors (see G6:J8); the results in G2:I4 are wrong.
In columns L to N, the function Crsm from Fig. 4.34 (P) is applied, which can
output the result either as a row vector (e.g., L6:N6) or as a column vector (e.g.,
L2:L4). This is because, in this function, a 3 × 3 matrix is written into the range
declared with DIM cs(2,2), of which only one row or one column is output if only
one row range or one column range is activated.
The functions Crs and Crsm must be called as matrix functions. In Fig. 4.36
(S), for example, the area G6:I6 was activated, the formula entered according to
J6 and closed with the magic chord (Ctl + Shift) + Enter. In L2:L4, a column
area was activated, and in L6:N6, a row area, so that in each case, vectors with
three components are returned by crsm.
Questions
Table 4.23 Two column vectors a, b and two row vectors c, d are specified
1 a=np.array([[1,2,3]]).transpose(1,0)
2 b=np.array([[2,2,2]]).transpose(1,0)
3 c=np.array([1,2,3])
4 d=np.array([2,2,2])
a b
[[1] [[2] c [1 2 3]
[2] [2]
[3]] [2]] d [2 2 2]
How can this function be used to output row and column vectors to a
spreadsheet?50
4.9.3 Python
Scalar product
The specifications in Table 4.23 for column vectors a, b, and row vectors c, d are the
same as in Fig. 4.35 (S).
The function Scl (for “scalar product”) as reported in Table 4.24 corresponds
literally to the Visual Basic function of the same name (Fig. 4.34 (P)). Its output
is, however, only a scalar if two row vectors are multiplied.
Column vectors are two-dimensional arrays; a scalar product with one of them
is broadcast into a one-dimensional array (see lines 10 and 12 of Table 4.24). If a
scalar is always desired, line 8 has to be activated by removing the # character.
50 Because internally a 3 × 3-matrix is created, see explanations for Fig. 4.36 (S)!
174 4 Macros with Visual Basic and Their Correspondences in Python
Table 4.25 Cross product of two three-dimensional vectors, output optionally transposed in line
16 to become a column vector
1 def Crsm(r1, r2, C):
2 cs=np.empty(3)
3 cs[0]=r1[1]*r2[2]-r1[2]*r2[1]
4 cs[1]=r1[2]*r2[0]-r1[0]*r2[2]
5 cs[2]=r1[0]*r2[1]-r1[1]*r2[0]
6 if C==True:cs=np.array([cs]).transpose(1,0)
7 return cs
In Table 4.26, again, two column vectors a, b and two row vectors c, d are
specified. Their pairwise cross-product, obtained with Crsm, is reported in the
lower cells of the table. If only the vectors are transferred to the function, row
vectors are returned (bottom left cell), whereas a column vector is returned if the
optional parameter C is assigned “True” (bottom right cell).
Program-controlled drawings
Record macro
The diagram in Fig. 4.37 (S) has been created with the macro recorder switched on.
The program code can be found in Fig. 4.38 (P). The diagram has been formatted
4.10 Questions and Tasks 175
A B C D E F G H I
1 Curve
2 x y 120
3 1 1 100
4 2 4
80
5 3 9 y
6 4 16 60
7 5 25
40
8 6 36 Curve
9 7 49 20
10 8 64 0
11 9 81 0 5 10 x 15
12 10 100
1 Sub Macro1() 1
2 ActiveSheet.Shapes.AddChart2(240, xlXYScatterLines).Select 2
3 ActiveChart.SeriesCollection.NewSeries 3
4 ActiveChart.FullSeriesCollection(1).Name = "=Diagram!$B$1" 4
5 ActiveChart.FullSeriesCollection(1).XValues = "=Diagram!$A$3:$A$12" 5
6 ActiveChart.FullSeriesCollection(1).Values = "=Diagram!$B$3:$B$12" 6
7 End Sub 7
Fig. 4.38 (P) Instructions recorded by the macro recorder when the diagram in Fig. 4.37 (S) was
created
with the programs in Fig. 4.38 (P) and Fig. 4.40 (P). Your task is to analyze the
VISUAL BASIC programs and redraw the diagram with our standard FigStd and plt
(matplotlib.pyplot) commands in Python.
Plotting a diagram
5. Of what type is the diagram in Fig. 4.37 (S) (LINE, BAR, or SCATTER)?
6. What is the equation for y?
7. How do you create the arrays x and y in Python?
8. With SUB MACRO1 in Fig. 4.38 (P), retrace how the chart was created and interpret
the program lines 3 to 6!
9. (Python) What does a header in FigStd (numpy and matplotlib) look
like when leading to a diagram like that in Fig. 4.37 (S)?
10. SUB MACRO2 in Fig. 4.39 (P) has recorded the instructions executed to format the
data series in the diagram of Fig. 4.37 (S). Interpret the formatting instructions!
How do you implement them in the plot command of plt.plot(?) of the
plotlib library?
11. SUB MACRO3 in Fig. 4.40 (P) has recorded the commands executed to format the
x-axis in the diagram of Fig. 4.37 (S). Interpret the instructions that follow the
two WITH SELECTION commands!
176 4 Macros with Visual Basic and Their Correspondences in Python
Fig. 4.39 (P) SUB MAKRO2 contains the commands that were recorded by the macro recorder when
the data series for the diagram in Fig. 4.37 (S) was formatted
Fig. 4.40 (P) SUB MACRO3 contains commands recorded by the macro recorder when the diagram
in Fig. 4.37 (S) was formatted
12. Write a Python program that produces a similar diagram with FigStd
(numpy and matplotlib) ! It should include formatting the data series in
the function header and changing the thickness of the x-axis within FigStd.
13. With which instructions do you get the first, the last, and the 4th letters of Tx?
14. How do you copy the fragment “re cu” from Tx to a new variable Wd?
15. Of what type are the variables A, B, C, and D in the commands A = Split(B) and
C = Join(D)?
16. Write a macro SUB XY1() that writes all products x·y from x = 1 to 10 and from
y = 1 to 5 successively into a spreadsheet, with x and y being integers!
17. Do the same in another macro SUB XY2() for x and y being half-integers (1, 3/2,
2, 5/2, …)!
18. Do the same as in SUB XY2() in a new macro SUB XY3(), but insert a blank line
after every third entry into the spreadsheet!
19. Create a similar Python program using the.append method and nested loops
running over arrays x and y created by np.linspace! For the equivalent of
inserting an empty row into a spreadsheet, append ‘None’ to the list!
20. Make a hand-drawn sketch of straight-line segments in the xy plane, with the x
values in line 1 and the y values in line 2 of Fig. 4.41 (S)!
4.10 Questions and Tasks 177
Rep-log procedure
In Fig. 4.42a, a circle is represented, calculated in the spreadsheet in Fig. 4.43 (S)
in columns G:I. The coordinates of the centers of these circles are taken from the
table in Fig. 4.41 (S). Figure 4.42b shows four circles whose coordinates have been
obtained from the table in Fig. 4.43 (S) with a rep-log procedure that systematically
changes the center point and the radius.
20 20
y Circle y
10 10
0 0
-10 0 10 20 30 -10 0 10 20 x 30
x
-10 -10
Circles Centers
-20 -20
Fig. 4.42 a (left) A circle with r 0 = 4 and x 0 = 3. b (right) The circle from a was enlarged three
times and shifted along the x-axis; in the diagram, all four circles are represented as one data series
A B C D E F G H I J K L M N O
1 r.0 4.00 c.s 4.00
2 x.0 3.00 v.F 3.00 Circle Circles Centers
+x.0
hi) hi)
dphi COS(p SIN(p
3 =G5+ =r.0* =r.0*
4 30 ° phi x y x y xC yC
5 dphi 0.524 0.00 7.00 0.00 7.00 0.00 3 0
6 0.52 6.46 2.00 6.46 2.00 6 0
17 6.28 7.00 0.00 7.00 0.00
Fig. 4.43 (S) Spreadsheet calculation for Fig. 4.42. The variable cs contains the factors with
which the radius of the circle is increased. The variable vF is the velocity with which the circle
center is shifted on the x-axis
178 4 Macros with Visual Basic and Their Correspondences in Python
21. What are the radii and the coordinates of the circles’ center points in
Fig. 4.42b?
22. The coordinates of the circle are to be calculated four times by changing the
parameters in the table and then to be stored successively in columns Q and
R (column indices 17 and 18, respectively) of the spreadsheet and graphically
displayed in a diagram as one data series (to yield Fig. 4.42b). The centers’
coordinates are in columns N and O (column indices 14 and 15, respectively).
The circle radius should increase with r 0 = vs ·t, and the center point should
be shifted on the x-axis with x 0 = vF ·t. Write such a log procedure in Visual
Basic!
23. For the answer of Question 23 in Python, create empty lists Q and R and
extend them with the.append method in a nested loop! Instead of an empty
line, insert “None”! Finally, plot (Q, R) with a correct label and observe
whether four separated circles show up!
Formula-generating routine
In Fig. 4.44b, you see a parabola connected to the horizontal axis by vertical lines.
The spreadsheet calculation for the coordinates is shown in Fig. 4.44a (S).
24. The y-value of the parabola is calculated in the usual way with named cell
ranges (see the formula in B5). Every tenth point of the parabola is connected
to the horizontal axis with a vertical line (“Dashes”). Write a routine that
writes the formulas for the vertical lines’ coordinates into columns D and E!
25. Create a corresponding Python program with two variants. (a) The vertical
lines are plotted one after the other in a loop. (b) The coordinates of all vertical
lines are stored in lists named D and E separated by empty cells, and plotted
as one data series.
A B C D E 80
1 a.1 2.00 c.1 4.00
y=2(x-4)²+4
2 b.1 4.00 dx 0.10 y
3
4 y=2(x-4)²+4 Dashes
60 Dashes
+c.1
.1)^2
*(x-b
5 =a.1 =A17 =B17 40
6 x y x.s y.s
7 0.00 36.00 0.00 36.00
8 0.10 34.42 0.00 0.00
9 0.20 32.88 20
10 0.30 31.38 1.00 22.00
11 0.40 29.92 1.00 0.00
12 0.50 28.50
13 0.60 27.12 2.00 12.00 0
107 10.00 76.00 0 2 4 6 8 x 10
4
A B C D E F G H I J
y 1 G, 2P
2 x y
3 1 -1.8 2.3
2 4 2 3.20 -1 4
5
6 G, 3.P S S, mirrored
0)
0 $4;B1
x 4 $4;$C
-4 -2 0 2 $C$3;$B4 }
) 3;
ND( ht($B$ D()*$F$ D()*$F$ 4 ;F10)
G, 2P 8*RA ig r(E10
7 =-4+ =Stra =RAN =RAN ={Mir
G, 3.P
-2 8 x y xS yS xSm ySm
S 9 1.89 -0.14 3.72 2.58 -3.72 -2.58
S, mirrored 10 3.27 -1.05 3.60 3.85 -3.60 -3.85
11 1.63 0.03 1.81 1.11 -1.81 -1.11
12 0.76 0.61 2.97 0.62 -2.97 -0.62
-4
Fig. 4.45 a (left) Two points “G, 2P” define a straight line (18a); the points in the third quadrant
are mirrored at the zero point into the first quadrant (18b). b (right, S) Spreadsheet calculation for
a; the coordinates for the points on the straight line are in columns B and C; the coordinates in
columns H and I are the mirror images of the coordinates in columns E and F
26. What are the names of the two user-defined functions reported in line 7 in
Fig. 4.45b (S)?
27. Write a function (VISUAL BASIC or Python) of the type y3 = f(x 1 , y1 , …)
that calculates the y-value y3 of a third point from the coordinates of the two
defining points of a straight line and the x-value x 3 of the third point!
28. Write a function (VISUAL BASIC or Python) of the type (x sp , ysp ) = f(x,y)
that mirrors the coordinates x and y of a point at the origin of the coordinate
system!
Macros
29. You want to trigger a macro whenever a slider named SCROLLBAR1 is changed.
What is the name of the associated macro?51
30. At a mail-order company, some data from all outgoing packets are entered in the
spreadsheet of Fig. 4.46 (S). Write a protocol routine (Visual Basic or Python)
that reads some data from Fig. 4.46 (S) and enters it into a table as in Fig. 4.47
(S)! The packets have to be numbered consecutively.
51 SUB SCROLLBAR1_CHANGE().
180 4 Macros with Visual Basic and Their Correspondences in Python
A B C D E F G H I
1 Name Mary B.
2 Running number 46
Protoc
3
4 Width (cm) w 5 Volume (l) V 1.80 =w*l*h/1000
5 Length (cm) l 18 Surface (m²) S 0.11 =(w*l+w*h+l*h)*2/10^4
6 Hight(cm) h 20 Time 07.09.2020 17:21 =NOW()
Fig. 4.46 (S) Table section in which the width, length, and height of packages, as well as the
sender’s name, are to be entered
K L M N O P Q R S
6 12 next free row
m m m²
7 Numb
er e h/cm ength/c eight/c olume/l urface /
Nam Time Widt L H V S
8 43 Otto L. 7.9.20 17:03 17 17 14 4.05 0.15
9 44 James L. 7.9.20 17:16 20 10 10 2.00 0.10
10 45 Henry M. 7.9.20 17:16 18 28 8 4.03 0.17
11 46 Mary B. 7.9.20 17:21 5 18 20 1.80 0.11
Fig. 4.47 (S) The data from Fig. 4.46 (S) are to be reorganized in this way
Basic Mathematical Techniques
5
Solutions of Exercises 5.3 (Excel), 5.5 (Python), 5.6 (Python), and 5.7 (Excel) can
be found at the internet address: go.sn.pub/VYYbJL.
Straight-line segment
Straight-line segments are central for vector calculation, and also for calculus,
because we approximate all curves by sequences of such elements. In the intro-
ductory Exercise 5.2, we calculate vector entities related to a straight-line segment,
e.g., line vector and mid-perpendicular, as well as length, slope, and area enclosed
with the x-axis.
Mathematical functions
In Sect. 5.10, some useful mathematical functions are listed, both in excel and
numpy notation, together with short descriptions.
The functions we are investigating in this textbook are all continuous. They are
approximated as polylines, i.e., as sequences of straight-line segments. Therefore,
all operations of calculus, such as differentiation, integration, and integration along
a line, are based on such properties of segments as length, slope, line vector, and
mid-perpendicular.
In this exercise, we specify a straight segment in a plane by its two endpoints A,
B formulated as positional vectors. The unit line vector AB of the segment and its
perpendicular AB_p to be erected at the midpoint AB_C are calculated with matrix
operations. An example is shown in Fig. 5.1.
The equation of the line passing along the segment is
y = y A + m · (x − x A ) (5.1)
5.2 Straight-Line Segment Under a Magnifying Glass 183
4 4
y y
2 2
0 0
-4 -2 0 2 x 4 -4 -2 0 2 x 4
segment AB segment AB
AB_ AB_
-2 -2
AB_p AB_p
{=AB_p+AB_C} {=AB_p+AB_C}
on line on line
-4 -4
Fig. 5.1 Line vector and mid-perpendicular of a straight-line segment. The cross is drawn with a
function based on the coordinates of the two endpoints, a (left) with the settings from Fig. 5.2 (S),
b (right) other settings
with m being the slope of the segment and (x A , yA ) the coordinates of point A.
In Fig. 5.1a, the point (ys , x s ) on this line for x s = −1.76 is represented by a
cross. We use vector calculation, e.g., P·AB to obtain the unit vector perpendicular
to the segment with P, the 90° rotation matrix, and AB, the unit line vector.
In the spreadsheet calculation of Fig. 5.2 (S), the coordinates of the starting point
A are determined with sliders in A2:B3, ranging from 0 to 100. The values in the
linked cells are transformed into coordinates ranging from −4 to 4 (G2:G3). The
coordinates of the endpoint B are typed directly into cells J2:J3.
The cells G2:G3 get multiple identifiers: x A and yA refer to single cells, whereas
A refers to the whole range and can be processed as a column vector. The same
applies to B.
The length ds of the segment is calculated in A6 from the coefficients of A and
B. It can also be calculated with the matrix formula {=sqrt(sumxmy2(B;A))}.
sumxmy2 stands for “Sum of all individual (x – y)2 ”. The innermost operation A
– B involves two matrices, but the output is only a scalar. So, we have to enclose
the formula in curly brackets and finish with the magic chord Ψ Ctl + Shift +
Return.
The result of this calculation is shown in Fig. 5.1a. The perpendicular unit
vector AB p is also drawn from the center AB C of the line to AB C + AB p
(J6:J7).
In Fig. 5.3 (S), we calculate the primary segments of calculus dx, dy, and the
area dA between the segment and the x-axis. Furthermore, we set up the equation
A B C D E F G H I J K
1 A_ B_
2 55.00 xA 0.40 =(D2-50)/12.5 xB -3.00
3 92.00 yA 3.36 =(D3-50)/12.5 yB -3.50
2)
-xA)^
)^2+(xB gth_A
B} _)
P_;AB
yB }
((yA- _)/len )/2} B_C
RT A_-B ULT( _+B_ =AB_p+A
4 =S Q {=( =MM {=(A {
5 ds AB_ AB_p AB_C
6 7.66 0.00 0.44 0.00 0.90 =D7 -1.30 -0.40
7 0.00 0.90 0.00 -0.44 =-D6 -0.07 -0.51
8
Fig. 5.2 (S) Coordinates of points A and B, line vector AB and center position vector AB C; the
perpendicular vector AB p is obtained from AB through matrix multiplication with P, the 90°
rotational matrix P presented in Fig. 5.3 (S)
L M N O P Q R S T
5 area dA 0.24 =(yA+yB)/2*dx P_
6 dx -3.40 =xB-xA 0 -1
7 dy -6.86 =yB-yA 1 0
8 slope m 2.02 =dy/dx
9
10 on line x -1.76 28
11 y -1.00 =yA+m*(x-xA)
Fig. 5.3 (S) Continuation of Fig. 5.2 (S). Characteristics of a straight-line segment important for
calculus, and the equation for the line running along the segment
5.2 Straight-Line Segment Under a Magnifying Glass 185
To plot vectors with Python, we have to use the function arrow of the library
pyplot,to be imported with import matplotlib.pyplot as plt. We inte-
grate this function into a user-defined function ArrowP with standard formatting
parameters (see Table 5.1).
In excel, arrowheads are a design feature of a line: … line/end arrow type.
The constructor arguments of plt.arrow comprise, among others, the
keyword arguments:
Some arrows are plotted in Fig. 5.4 to demonstrate the effect of the construc-
tors. The arrow pointing upwards is drawn with our standard function ArrowP
(overhang = 1) in Table 5.1.
5.3 Differentiation
Table 5.1 User-defined function ArrowP for drawing an arrow from point P0 to point P1 in a
plane; the argument list of plt.arrow does not contain all possible keyword arguments (similar
to Tables 5.3, 5.4, 5.5 and 5.6)
1 def ArrowP(P0,P1,c="k",ls='-',lw=1,hw=0.2):
2 (x0,y0)=P0 #Decomposes the foot position vector
3 (x1,y1)=P1 #Decomposes the tip position vector
4 print(lw,hw)
5 #c has to be given as c="k", not c='k'
6 plt.arrow(x0,y0,x1-x0,y1-y0,
7 length_includes_head=True,
8 head_width=hw,overhang=1,fill=False,
9 linestyle=ls, color=c, linewidth=lw)
186 5 Basic Mathematical Techniques
points. The first derivative must be plotted over the middle between two grid
points, the second derivative over the central of three grid points.
The first derivative of a curve is the slope of its tangent to the curve at the specified
x-value. The derivative of a function f(x) with respect to x is defined as
For our discrete functions, the first derivative in the center of a segment is
approximated by y/x, the slope of the segment between adjacent points. The
values are to be plotted over the center of the interval. It is evident that the smaller
x is, the better the accuracy of the approximation.
5.3 Differentiation 187
The second derivative of a function is the derivative of the first derivative, thus,
d 2 f (x) d d
= f (x) (5.4)
dx2 dx dx
which is equivalent to applying Eq. 5.2 twice. The second derivative describes
the change of the slope, and is thus a measure of the curvature of the curve. The
difference equation for grid points x i at equal intervals x is
d 2 f (x) 1 f(xi+1 ) − f(xi )) f(xi ) − f(xi−1 )
≈ −
dx2 x x x
f(xi+1 ) − 2f(xi ) + f(xi−1 )
= (5.5)
x2
The second derivative at point x can be calculated directly without a detour via
the first derivative with function values at the grid points x, x – dx and x + dx.
It must be plotted over point x (x i in Eq. 5.5), the coordinate of the middle grid
point.
Sine function
To give an example, we differentiate the sine function, knowing beforehand that its
first and second derivatives are the cosine and the negative sine, respectively. So, we
can check whether our numerical calculations reproduce this result. This is indeed
confirmed in Fig. 5.5, with 100 calculation points in one period 2π. The shape of a
cosine is clearly visible in the numerically calculated y1d in Fig. 5.5a, and that of a
negative sine in y2d in Fig. 5.5b.
Oscillation of a mass-spring-system
Consider the oscillation z(t) of a mass-spring system. The second derivative z̈ with
respect to time is the acceleration a, which, in turn, is proportional to the restoring
1.5 1.5
y = sin(x) y = sin(x)
y2d
1.0 y1d 1.0 -Sin(x)
0.5 0.5
0.0 0.0
0 2 4 6 0 2 4 6
-0.5 -0.5
x x
-1.0 -1.0
-1.5 -1.5
Fig. 5.5 Derivatives of a sine function a (left) first derivative, b (right) second derivative, numer-
ically (dashed line) and theoretically (x) calculated, dx = 2π/100
188 5 Basic Mathematical Techniques
force −kz of the spring. The curvature of the displacement is thus proportional to the
force. This leads to the simple equation of a harmonic oscillator based on Newton’s
law:
F = −k · z = m · a = m · z̈
or
k
z̈ = − ·z (