100% found this document useful (6 votes)
4K views493 pages

Physics With Excel and Python

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (6 votes)
4K views493 pages

Physics With Excel and Python

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 493

Dieter Mergel

Physics with Excel


and Python
Using the Same Data Structure
Volume I: Basics, Exercises and Tasks
Physics with Excel and Python
Dieter Mergel

Physics with Excel


and Python
Using the Same Data Structure
Volume I: Basics, Exercises and Tasks
Dieter Mergel
Fakultät für Physik
Universität Duisburg-Essen
Duisburg, Nordrhein-Westfalen, Germany

ISBN 978-3-030-82324-5 ISBN 978-3-030-82325-2 (eBook)


https://doi.org/10.1007/978-3-030-82325-2

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

Ψ E xcel—as powerful as necessary, Python—as simple as possible.


This book treats a series of physics exercises that were developed for
courses at the University of Duisburg-Essen for students training to become
physics/mathematics teachers or physics engineers. The exercises were intended to
introduce computational physics based on spreadsheet calculation combined with
simple VBA macros and also to broaden the beginner’s knowledge of physics.
This approach garnered positive reactions from practitioners and resulted in a text-
book in German.1 Furthermore, the methods developed turned out to be powerful
enough to treat a broad range of topics in undergraduate physics, resulting in a
second volume with exercises on particles, waves, fields, and random processes.2
Referees found the exercises interesting and ambitious enough to serve for
undergraduate education. However, concerns arose that spreadsheet techniques,
although useful in the business world, might be a dead end for students who would
be required to use scientific computing in their future research work. Therefore,
the concept has been changed for the present English version. Programming in
Python is now included from the beginning, while the same topics are addressed
as in the German textbook.
The key to all of the exercises is data structures, developed in introductory sec-
tions that explain the physical problems. They serve as an interface to both Excel
and Python, and potentially also to other applications for scientific computation.
To enable this approach, the Excel solutions in this edition use vectorized code
and matrix formulas to mimic broadcasting, an essential Python technique for
creating new arrays.
We feel that this approach is suitable as a low-threshold introduction to scien-
tific computing as early as high school all the way up to undergraduate physics

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,

Felder und Zufallsprozesse, Springer Spektrum (2018), https://doi.org/10.1007/978-3-662-575


13-0.

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.

Duisburg, Germany Dieter Mergel


Contents

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

2.4.5 Standard Plot Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39


2.4.6 Formatted Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
2.5 Matrix Calculations in Excel and Python . . . . . . . . . . . . . . . . . . . . . . 41
2.5.1 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 41
2.5.2 Operations on Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
2.5.3 Matrices in Spreadsheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
2.5.4 Matrices in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
2.6 Four Parabolas and Their Upper Envelope . . . . . . . . . . . . . . . . . . . . . 49
2.6.1 Graphical Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
2.6.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 51
2.6.3 Spreadsheet Calculation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
2.6.4 Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
2.6.5 Extrema Along Different Axes . . . . . . . . . . . . . . . . . . . . . . . . 56
2.7 Sum of Four Cosine Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
2.7.1 Sound and a Cosine Identity . . . . . . . . . . . . . . . . . . . . . . . . . . 57
2.7.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 62
2.7.3 Spreadsheet Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
2.7.4 Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
2.7.5 Producing Labels (as Strings) in Excel and Python . . . . 68
2.8 Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
3 Formula Networks and Linked Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . 75
3.1 Introduction: Well-Structured Sheets and Programs . . . . . . . . . . . . 75
3.2 Image Construction for Focusing and Diverging Lenses . . . . . . . . 78
3.2.1 Straight Line Equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
3.2.2 Geometrical Image Construction for a Thin
Focusing Lens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
3.2.3 Imaging Equation with Correct Signs . . . . . . . . . . . . . . . . . 82
3.2.4 Beam Through a Converging Lens that Really
Contributes to the Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
3.2.5 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 86
3.2.6 Spreadsheet Calculation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
3.2.7 Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
3.3 Doppler Effect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
3.3.1 A Formula for All Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
3.3.2 A Sound Source Passes a Remote Receiver . . . . . . . . . . . 95
3.3.3 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 96
3.3.4 Spreadsheet Calculation “Remote Receiver” . . . . . . . . . . . 97
3.3.5 Python Program “Remote Receiver” . . . . . . . . . . . . . . . . . . 97
3.4 Exponentials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
3.4.1 Explosive Character of Exponentials . . . . . . . . . . . . . . . . . . 99
3.4.2 General Exponential Function . . . . . . . . . . . . . . . . . . . . . . . . . 101
3.4.3 Representation in a Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . 102
3.4.4 Diode Characteristics I(U) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
3.4.5 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 104
Contents ix

3.4.6 Spreadsheet Calculation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105


3.4.7 Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
3.5 Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
4 Macros with Visual Basic and Their Correspondences in Python . . . 115
4.1 Introduction: For, If, Sub/Def . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
4.2 Basic Exercise: For- Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
4.2.1 Visual-Basic-Editor 1: Editing . . . . . . . . . . . . . . . . . . . . . . . . 118
4.2.2 Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
4.3 Macro-Controlled Drawings with For, Sub, If . . . . . . . . . . . . . . . . 123
4.3.1 Macro Recorder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
4.3.2 Visual-Basic Editor 2: Macro Recording,
Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
4.3.3 Programming Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
4.4 A Checkerboard Pattern (Excel) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
4.4.1 Checkerboard, Same-Colored and Multi-colored . . . . . . . 132
4.4.2 Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
4.5 A Checkerboard Pattern (Python) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
4.5.1 Turtle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
4.5.2 Differences to Visual Basic . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
4.5.3 Checkerboard with Squares, Triangles, and Circles . . . . 139
4.6 Drawing Densely-Packed Atomic Layers; Crystal Physics . . . . . . 143
4.6.1 Program Structure and Geometry . . . . . . . . . . . . . . . . . . . . . 143
4.6.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 146
4.6.3 Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
4.6.4 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
4.7 Text Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
4.7.1 Cutting and Joining Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
4.7.2 Data Structure and Program Flow . . . . . . . . . . . . . . . . . . . . . 153
4.7.3 Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
4.7.4 Programming Step by Step . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
4.7.5 VBA Constructs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
4.7.6 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
4.8 Processing the Protocol of a Measuring Device . . . . . . . . . . . . . . . . 160
4.8.1 Protocol of a Measuring Device . . . . . . . . . . . . . . . . . . . . . . . 161
4.8.2 Detection of Code Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
4.8.3 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 162
4.8.4 Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
4.8.5 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
4.9 User-Defined Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
4.9.1 User-Defined Functions as Add-In . . . . . . . . . . . . . . . . . . . . 168
4.9.2 Scalar Product and Vector Product . . . . . . . . . . . . . . . . . . . . 170
4.9.3 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
4.10 Questions and Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
x Contents

5 Basic Mathematical Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181


5.1 Introduction: Calculus, Vectors, and Linear Algebra . . . . . . . . . . . 181
5.2 Straight-Line Segment Under a Magnifying Glass . . . . . . . . . . . . . 182
5.2.1 Under a Magnifying Glass . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
5.2.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 183
5.2.3 Spreadsheet Calculation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
5.2.4 Plotting Vectors with Python Matplotlib . . . . . . . . . . . . . . . 185
5.3 Differentiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
5.3.1 First and Second Derivative . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
5.3.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 190
5.3.3 Spreadsheet Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
5.3.4 Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
5.4 Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
5.4.1 Area Under a Curve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
5.4.2 Length of a Curve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
5.4.3 Data Structure and Nomenclature for the Arrays
in the Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
5.4.4 Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
5.4.5 Spreadsheet Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
5.5 Vectors in the Plane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
5.5.1 Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
5.5.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 200
5.5.3 Spreadsheet Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
5.5.4 Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
5.6 Tangents to and Perpendiculars on a Curve . . . . . . . . . . . . . . . . . . . . 204
5.6.1 At/On a Polynomial and an Ellipse . . . . . . . . . . . . . . . . . . . 204
5.6.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 205
5.6.3 Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
5.6.4 Spreadsheet Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
5.7 Banked Curve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
5.7.1 Cross-Section of the Road . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
5.7.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 209
5.7.3 Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
5.7.4 Spreadsheet Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
5.8 Weighted Average . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
5.8.1 A Mobile with Two Arms . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
5.8.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 213
5.8.3 Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
5.8.4 Spreadsheet Calculation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
5.9 Systems of Linear Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
5.9.1 Polynomial and Electrical Network . . . . . . . . . . . . . . . . . . . 215
5.9.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 218
5.9.3 Spreadsheet Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
5.9.4 Python Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
Contents xi

5.10 Some Mathematical Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222


5.11 Questions and Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
6 Superposition of Movements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
6.1 Introduction: Translations and Rotations . . . . . . . . . . . . . . . . . . . . . . . 227
6.2 Projectile Trajectory with Velocity Vectors (T-T) . . . . . . . . . . . . . . . 229
6.2.1 Projectile Trajectory and Velocity Vectors . . . . . . . . . . . . . 229
6.2.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 230
6.2.3 Spreadsheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
6.2.4 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
6.2.5 Animation of Figures with FuncAnimation . . . . . . . . . . . . 234
6.3 Cycloid, Rolling Curve (R-T) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
6.3.1 Trace of a Writing Point Fixed at a Rolling Wheel . . . . 238
6.3.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 241
6.3.3 Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
6.3.4 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
6.4 Foucault’s Pendulum (T-R) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
6.4.1 A Lecture Experiment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
6.4.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 248
6.4.3 Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
6.4.4 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
6.5 Anchor, Deflected Out of Its Rest Position (R-R) . . . . . . . . . . . . . . 251
6.5.1 Deflected Anchor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
6.5.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 254
6.5.3 Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
6.5.4 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
6.6 Wavefronts, Sound Barriers, and Mach Cone (T-T) . . . . . . . . . . . . 258
6.6.1 Emitting Sound Waves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
6.6.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 261
6.6.3 Spreadsheet Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
6.6.4 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
6.7 Questions and Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
7 Integration of Newton’s Equation of Motion . . . . . . . . . . . . . . . . . . . . . . . . 269
7.1 Introduction: Approximated Mean Value Instead of Exact
Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
7.1.1 Newton’s Equation of Motion . . . . . . . . . . . . . . . . . . . . . . . . . 269
7.1.2 Four Methods for Estimating the Average
Acceleration in a Time Segment . . . . . . . . . . . . . . . . . . . . . . 271
7.1.3 Tactical Approaches in Python and Excel . . . . . . . . . . . . . 272
7.2 Harmonic Oscillation with “Progress with Look-Ahead”
and “Runge–Kutta” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
7.2.1 Equation of Motion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
7.2.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 275
7.2.3 Spreadsheet Calculation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
7.2.4 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
xii Contents

7.3 Falling from a (Not Too) Great Height . . . . . . . . . . . . . . . . . . . . . . . . 278


7.3.1 Limiting Cases, Analytically Solved . . . . . . . . . . . . . . . . . . 279
7.3.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 280
7.3.3 Spreadsheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
7.3.4 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
7.4 Stratospheric Jump . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
7.4.1 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 285
7.4.2 Spreadsheet Calculation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
7.4.3 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
7.5 A Car Drives with Variable Power . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
7.5.1 Various Types of Power . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
7.5.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 291
7.5.3 Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
7.5.4 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
7.6 Bungee Jump . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
7.6.1 Simulation of the Motion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
7.6.2 Analytical Calculations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
7.6.3 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 302
7.6.4 Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
7.6.5 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
7.7 Questions and Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
8 Random Numbers and Statistical Reasoning . . . . . . . . . . . . . . . . . . . . . . . 307
8.1 Introduction: Statistical Experiments Instead of Theoretical
Derivations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
8.2 Equi-Distributed Random Numbers, Frequencies
of Occurrence, Chi2 Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
8.2.1 A Spreadsheet Experiment with Random Numbers . . . . 310
8.2.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 315
8.2.3 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
8.3 Points Randomly Distributed in a Unit Square . . . . . . . . . . . . . . . . . 318
8.3.1 Creation and Distribution of the Points . . . . . . . . . . . . . . . . 318
8.3.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 321
8.3.3 Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
8.3.4 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
8.3.5 Why Calculate Twice? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
8.4 Set Operations in Numpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
8.4.1 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
8.4.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 330
8.4.3 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
8.5 Normally Distributed Random Numbers . . . . . . . . . . . . . . . . . . . . . . . 332
8.5.1 Normal Distribution, Probability Density
and Distribution Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
8.5.2 Random-Number Generator and Frequencies
of Occurrence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
Contents xiii

8.5.3 Where Do Observed and Theoretical Frequencies


Fit Better Together? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
8.5.4 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 340
8.5.5 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
8.5.6 Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
8.6 Random-Number Generator, General Principle . . . . . . . . . . . . . . . . . 345
8.7 Diffraction of Photons at a Double-Slit . . . . . . . . . . . . . . . . . . . . . . . . 348
8.7.1 Physical Background: Wave-Particle Dualism . . . . . . . . . 348
8.7.2 Cos2 Distribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
8.7.3 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 351
8.7.4 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
8.7.5 Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
8.7.6 Simulation in a Spreadsheet . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
8.8 Chi2 Distribution and Degrees of Freedom . . . . . . . . . . . . . . . . . . . . 358
8.8.1 Data Structure, Nomenclature . . . . . . . . . . . . . . . . . . . . . . . . . 359
8.8.2 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
8.9 Questions and Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
9 Evaluation of Measurements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
9.1 Introduction: We Know Everything and Play Stupid . . . . . . . . . . . 365
9.2 Weighing a Glass Substrate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
9.2.1 Discussion on the Accuracy of a Balance . . . . . . . . . . . . . 369
9.2.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 370
9.2.3 Excel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
9.2.4 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
9.3 A Procedure for Rounding to Relevant Digits . . . . . . . . . . . . . . . . . . 372
9.3.1 Numerical Evaluations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
9.3.2 Spreadsheet Calculation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
9.3.3 Python Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
9.3.4 VBA Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
9.4 Increasing the Measuring Accuracy Through Repetition . . . . . . . . 374
9.4.1 Standard Deviation and Standard Error
of the Mean Value of a Measurement Series . . . . . . . . . . . 375
9.4.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 379
9.4.3 Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
9.4.4 Spreadsheet Layout for This Task . . . . . . . . . . . . . . . . . . . . . 380
9.4.5 How to Report a Measurement Result . . . . . . . . . . . . . . . . . 381
9.5 The t Statistics Connects Confidence Interval
with Confidence Level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
9.5.1 Student’s t Distribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
9.5.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 386
9.5.3 Spreadsheet Calculation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
9.5.4 Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
9.6 Combining Results from Several Measurement Series . . . . . . . . . . 389
9.6.1 Combining Two Measurement Results . . . . . . . . . . . . . . . . 390
xiv 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

10.5 Solving Nonlinear Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448


10.5.1 Intersection of Straight Lines with a Parabola . . . . . . . . . 448
10.5.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 449
10.5.3 Spreadsheet Calculation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
10.5.4 Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
10.6 Temperature Dependence of the Saturation Magnetization
of a Ferromagnet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
10.6.1 Langevin Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
10.6.2 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 458
10.6.3 Spreadsheet Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
10.6.4 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
10.7 Fitting Gaussians to Spectral Lines with Nonlinear
Regression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
10.7.1 Fitting the Sum of Two Gaussians to Data Points . . . . . . 460
10.7.2 C-spec Errors of the Coefficients by a Statistical
Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
10.7.3 Data Structure and Nomenclature . . . . . . . . . . . . . . . . . . . . . 464
10.7.4 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
10.7.5 Spreadsheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468
10.7.6 C-spec Error of the Optimized Coefficients
by Simulation-Based t Adaptation . . . . . . . . . . . . . . . . . . . . 470
10.8 Questions and Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472

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

Possible errata and corrections in the internet at: go.sn.pub/Ob4vCR.


For every chapter, solutions for each two exercises in Excel and Python can be
found at internet adresses.

1.1 A Two-Track Didactical Approach

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.

© Springer Nature Switzerland AG 2022 1


D. Mergel, Physics with Excel and Python,
https://doi.org/10.1007/978-3-030-82325-2_1
2 1 Introduction

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.

Didactical advantages of the two-track system


We strive to combine the didactical advantages of both programming applications:

– Spreadsheets are interactive; charts react immediately to changes, and data


structures (but not formulas) are immediately visible in spreadsheets.
– In Python, formulas (but not data structures) are immediately visible.
– The VBA interpreter allows us to run the program step by step and to watch
intermediate results in a spreadsheet, or read the content of variables by mouse-
over in the code.

Our guideline: spreadsheet calculations as powerful as necessary, Python program-


ming as simple as possible.
Emphasis is not on mere computational techniques, but on exercises that may
be regarded as small projects so that project-related difficulties manifest and can be
addressed, e.g., by checking the consistency of equations and numerical solutions
with limiting cases that can be solved analytically.
We maintain that this approach is not only suitable as a low-threshold introduction
to scientific computing as early as High School and up to undergraduate Physics
classes at University. It should also be a good start for students who later choose to
specialize in Computational Physics or, more generally, for professional use.

1.2 What Can You Expect?

What can you, dear reader, expect from this book?


You can expect to be introduced to the world of Python and excel by:

– 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.

and, with that,

– getting a better understanding of certain mathematical and physical concepts.


1.2 What Can You Expect? 3

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!”.

1.3 What Do You Need?

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.

1.4 Tim, Alac, and Mag

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: Computers are not my thing

 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.

 Alac Why excel and Python?

 Mag All algorithm-oriented computer languages have a similar structure.


Knowledge of specific commands is not the most important thing. You have to
learn how to translate physical and technical problems into a computational struc-
ture. Furthermore, the mistakes that beginners make are always the same in all
computer languages. The most important thing is to track, correct, and, finally,
avoid them. Anyhow, as we shall have spreadsheet solutions and Python pro-
grams in parallel, you will be sensitized more towards common structures than the
peculiarities of specific software.

Alac: How do I become a master programmer?

 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.

 Alac And that is what this course will accomplish?

 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.

 Tim Data structures, procedures, controlling; that sounds pretty challenging.


How can I learn all of that?

 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.

 Tim Is that thorough enough?

 Alac Will I learn the more tricky constructions too late?

 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.

 Tim Can I manage this in addition to my studies in Physics?

 Mag I think so. Anyway, this course is about physics and will help you to pass
your exams.

1.5 Didactic Concept

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

Courses with 30 attendance hours


At the University of Duisburg-Essen, two excel-based courses were offered, each
with 30 attendance hours:

– 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.

Subjects from a one-year physics course


The exercises rely on the subject matter from the first year of undergraduate physics.
We do not intend to repeat physics that can be found in standard textbooks. Therefore,
the introductions to the tasks are concise, but the solutions are presented in great
detail. Experience shows that this creates the risk that the students might work through
the exercises mechanically without caring about the physics context. To counteract
this tendency, simple questions regarding physics and programming are asked in the
middle of the text and answered in footnotes.
In Chaps. 8, 9 and 10, statistical concepts are illustrated in greater detail through
simulations, because many students lack basic knowledge in this area. Although
no theorems are logically derived, their structure should become clear, because the
simulations follow the mathematical ideas.

Simple solutions preferred


The material is presented in nine chapters, each featuring about five detailed exer-
cises. The aim is to pursue clear and simple solutions in which the physical
justification for each step is traceable. To achieve this, suboptimal solutions, sub-
optimal with respect to computational efficiency and numerical precision, are often
presented instead of solutions that are perfect from the outset. It has proven to be
didactically more efficient to point out the shortcomings of this first approach and
give the reader tools for improvements.

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.

1.6 Subject Matter

Block A, Fundamentals (Chaps. 2, 3 and 4)


Ψ The dollar makes it absolute.
The student will learn how to organize spreadsheets, design charts reasonably,
and implement simple programming procedures. The necessary computational tech-
niques are embedded in Physics tasks and trained with clearly arranged formula
calculations, presentations, interpretations of curves, and simple mathematics. The
reader should consult, in parallel, systematic introductions to Excel and Python
for help.

Block B, Physics and Mathematics


Ψ Half, half, whole, the halves count twice.
In Chap. 5, the reader will find exercises for analysis and vector and matrix
calculations in the form of a spreadsheet-specific introduction to mathematics with
parallel Python programs.
In Chap. 6, the knowledge gained in Chaps. 2 to 5 is applied to the kinematic
superposition of movements, including animated charts.
In Chap. 7, we deal with various methods for solving Newton’s equation of motion
and apply them to one-dimensional motions, such as a jump from the stratosphere,
Exercise 7.4, or a bungee jump, Exercise 7.6.

Block C, Simulation and analysis of experiments


 If in doubt, count!
Evaluation of measurements is regarded as a critical skill to be exercised at the
beginning of studies in Physics. Therefore, this block is particularly detailed and
illustrated with simulations based on chance, because, as experience shows, many
students’ most significant knowledge gaps are in the field of probability and statistics.
Furthermore, statistics is the branch of mathematics that is most important outside
of technical professions.
We intend to develop a good understanding of concepts through statistical experi-
ments with random numbers without going deep into formal mathematics. Statistical
rules are intended to be illustrated and checked through multiple repetitions of sim-
ulations designed to test the hit rate (“Does the error range capture the true value?”).
For this purpose, random number generators are introduced in Chap. 8, e.g., for
normal distributions.
The student will learn how to analyze and graphically represent measurements
(Chap. 9), emphasizing the precise meaning of error ranges (“C-spec errors” related
to confidence levels). Before this can be done, the measurement process must be
8 1 Introduction

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.

1.7 Getting Started with Excel

1.7.1 Start Menu

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.

1.7.2 Spreadsheet Presentation

 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 :

– the parameters of the task are defined in the range C2:C6,


– these cells get the names in B2:B6, with which they can be called in formulas,
– the most informative parameters of the exercise are integrated into a text, here, in
cell E4 (with the formula in E5) that can be taken as a legend in a figure.

Left of :

– the values for the independent variable t are in B14: B174.

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

1 Sub Protoc() Range("C3") = Tp 8


2 r2 = 13 Cells(r2, 10) = Tp 9
3 Cells(r2, 10) = "Tp" Cells(r2, 11) = Range("D174") 10
4 Cells(r2, 11) = "xT" Cells(r2, 12) = Range("E174") 11
5 Cells(r2, 12) = "yT" r2 = r2 + 1 12
6 r2 = r2 + 1 Next Tp 13
7 For Tp = 1 To 9 End Sub 14

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 :

– values are calculated from the parameters and independent variables,


– the range C14:G174 contains five columnar vectors of length 171 with the names
in row 13,
– row 12 includes, in oblique orientation and in italics, the text of the formulas in the
bold-printed cells of the column below. If no cell is printed in bold, the formula
applies to the entire column.

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.

1.8 Getting Started with Python

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

Fig. 1.4 Window opened to create a new program file

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.

1.9 Skills to Be Trained

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.

Spreadsheet operations (Exercise 2.3)

– Using cell addressing, absolute, relative, indirect


–  The dollar makes it absolute.
– Naming cell ranges and using the names in formulas
12 1 Introduction

Fig. 1.5 A program creating an output just below the program cell

– Using sliders to change cell contents


– Scaling and formatting XY scatter diagrams
– Creating smart legends by linking text and variables,  “Text” & Variables.
– Gamma structure of tables (Sect. 1.7.2)
–  Empty lines separate curves.
–  Ctrl + Shift + Enter. Magic “chord” to complete the entry of matrix functions
in excel (Exercise 2.6).

Python constructs (explained mainly in Exercises 2.4 and 2.5)

– Use of numpy arrays


– Ab-initio constructors np.arange, np.linspace
– Creating one and two-dimensional arrays with np.array (row vectors, column
vectors, matrices)
– Broadcasting row vectors, column vectors, and matrices together in algebraic
operations
– Slicing of lists
– List comprehension
– Creating smart legends by linking text and variables
– Applying a standard function to create scatter diagrams
– Creating animated figures (Exercise 6.2).

VBA-macros and Python instructions (Chap. 4)


The terms ‘routines’, ‘programs’, and ‘procedures’ are all used synonymously here.
The term ‘macro’ is for VBA only.
1.9 Skills to Be Trained 13

– For, if , Sub/def , basic structures of programming: loops, logical queries, subrou-


tines (Exercises 4.4 and 4.5)
– Loop2i, loops with a loop index and a running index incremented within the loop
(Exercises 4.2 and 4.8)
– Systematically modifying parameters and recording the results of the spreadsheet
calculations with rep-log procedures
– Processing and decoding texts for evaluation of the protocols of measuring
instruments (Exercises 4.8 and 4.9)
– Writing formulas into cells with procedures (Exercises 4.1 and 4.2)
– Creating user-defined functions and using them in spreadsheet calculations
(Exercise 4.9)
– Linking macros to control elements (command buttons, sliders) in spreadsheets
(Sect. 4.3.3).

Mathematical techniques
Ψ Imaging equation for lenses with plus and minus! (Exercise 3.2).

– Using the line equation constructively (Exercise 3.2)


– Calculating with vectors in the plane and displaying them in diagrams (Exercises
5.5, 5.6, 5.7)
– Calculating with matrices (Exercise 5.9)
– Converting polar coordinates and Cartesian coordinates into one another (Chap. 6)
– Ψ Doppler effect with plus and minus (Exercise 3.3)
– Differentiating (Exercise 5.3) and integrating (Exercise 5.4) numerically
– Weighted sum (Exercises 5.8 and 6.5) and weighted mean (Exercise 6.5).

Functions

– Properties of the exponential function (Exercise 3.4)


–  First, the tangent at x = 0! (Exercise 3.4)
–  Plus 1 becomes times e. (Exercise 3.4)
– Use of the logarithm function for different computing tasks (Exercise 9.3)
– Addition of sines and cosines: overtones and beats (Exercise 2.7)
–  Cos plus Cos equals mean value times half the difference. (Sum rule of cosines,
Exercise 2.7).

Integration of Newton’s equation of motion (Chap. 7)

–  Approximated average value instead of exact integral


– Four numerical methods (Sect. 7.1.2, Exercise 7.2):
– Euler
– Progress with look-ahead (our standard procedure in a spreadsheet calculation)
– Half-step
– Runge-Kutta of fourth order, Ψ half, half, whole, the halves count twice. (our
standard procedure as a Python function).
14 1 Introduction

Statistics (mainly Chap. 8)

–  Mostly, not always. Fundamental rule of statistical reasoning


–  If in doubt, count!
– Ψ Come to a decision! You may be wrong. (Exercise 9.6)
– Generating random numbers with specified distribution (Exercises 8.5, 8.6, 8.7)
– Ψ Chance is blind and checkered. (Exercise 8.3)
– Empirical frequency distribution (Exercise 8.2), in excel:  Always one more!
Yes, but of what and than what? In Python:  Always one less!
– Chi2 test for comparing theoretical and empirical frequency distributions (Exer-
cises 8.2, 8.8)
– Multiple repetitions of random experiments to test for uniform distribution of the
results of Chi2 tests (Exercise 8.2).

Evaluation of measurements (mainly Chaps. 9, 10)

–  We know everything and play stupid.


– Simulating measuring processes and evaluating the generated data sets statistically
(Exercises 9.2, 9.9).
– Mean, standard deviation,  Two within, one out of (the standard error range)
(Exercises 9.4 to 9.8)
– Specifying measurement uncertainty (Exercises 9.2, 9.7 and 9.8)
– Multiple repetition of random experiments to test for error rate (Exercises 9.4,
9.5 and 10.3)
– For only a few repetitions of measurements, taking the t-value into account
(Exercise 9.5).
–  Twice as good with four times the effort (Exercise 9.4).
– Error propagation (Exercises 9.7, 9.8), Ψ Calculate with variances, report the
C-spec error!
– Ψ From variance to confidence with Student’s t value (Exercise 9.8).
– Reducing measurement uncertainty by combining measurement series (Exercise
9.6).
–  Worse makes good even better.
– Linear regression, trend lines, coefficients with uncertainty (Sect. 10.2, 10.3 and
10.4).
– Applying non-linear regression using solver in excel and curve_fit in
Python (Exercises 10.5, 10.6 and 10.7).
– Decoding textual logs of measuring instruments and writing the relevant data into
tables using VBA macros or Python programs (Exercise 4.8).
Data Structures, Excel and Python
Basics 2

This chapter aims to develop computational solutions for physics problems,


parallel in excel and Python based on the same data structure and the
same type of list processing. In this way, excel may serve as a low-threshold
entry into scientific computation with a smooth transition to professional
platforms. We proceed in three steps: (1) Basic spreadsheet techniques are
introduced: absolute and relative addressing and naming of cells, creating
charts, and using sliders (scroll bars), with the didactic goal of addressing
variables in functions by their names, just as in mathematical formulas. (2)
Python basics are explained, with emphasis on the manipulation of Numpy
arrays essential for scientific computation. (3) Matrix operations are intro-
duced in excel, equivalent to those in Python. Finally, in one exercise,
a set of four parabolas and, in another exercise, a group of four cosines
(to simulate acoustic phenomena) are calculated and displayed in parallel in
both applications.

2.1 Introduction: Named Ranges in Excel, Arrays in Numpy

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

© Springer Nature Switzerland AG 2022 15


D. Mergel, Physics with Excel and Python,
https://doi.org/10.1007/978-3-030-82325-2_2
16 2 Data Structures, Excel and Python Basics

basic exercise, find a textbook about excel techniques that is best suited for your
learning style.
Required and practiced excel techniques are:

– relative and absolute cell addressing,


– direct and indirect cell addressing,
– naming of cells and cell ranges,
– creation of diagrams,
– application of sliders.

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.

2.2 Characteristics of a Parabola

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.

2.2.1 Different Definitions of a Parabola

Parabola from vertex


A parabola is to be presented in a diagram. Its standard form is defined as

y = a + b · x + c · x2 (2.1)

It is, however, more intuitive to start from its vertex form

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

Focus and directrix


A parabola may also be defined as the locus with equal distance to the focus (x F , yF )
and to the directrix (y = yD ), both of which are depicted in Fig. 2.1b. The coordinates
of the focus and the directrix are:
c c
x F = xV y F = yV + y D = yV − (2.4)
4 4
Ignoring reflection, all rays incident parallel to the symmetry axis of the parabola
have the same length up to the directrix, e.g., when calculated from the line y = 0.
By definition, they all have the same length up to the focus when reflected at the
parabola. This is why light incident parallel to the optical axis is focused in the focus
of a parabolic mirror.

Calculation points of a curve


Equations 2.1 and 2.2 represent continuous functions. In numerical calculations,
however, the function values y are calculated on only a finite number of discrete
x-values, x i (see the inset picture in Fig. 2.1a). The points (x i , yi ) are called the
calculation points of the function. They are the vertices of the polyline representing
the graph. In most of our exercises, the adjacent calculation points are equidistant on
the x axis , i.e., they all have the same distance to their respective neighbors, usually
specified in a parameter dx.

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

2.2.2 Data Structure and Nomenclature


(x V , yV ) coordinates of the vertex of the parabola
a, b, c coefficients of the parabola in standard form
yD ordinate value of the directrix of the parabola
(x F , yF ) focus of the parabola
dx distance between adjacent x values of calculation points
x sequence of x values
yP values of the polynomial for x
yA , yB, yC, yD values of the same polynomial but calculated in Excel with
column names
yMax upper envelope of yA , yB , yC , yD .

2.3 Basic Exercise in Spreadsheet Calculation

With the example of tabulating a parabola and displaying it in a diagram, we


train the basic spreadsheet techniques: absolute and relative cell addressing,
providing cells with names, connecting text and numeric variables to get
informative legends for diagrams, applying scroll bars to change cell contents
without typing numbers. After performing these exercises, the reader should
be able to select a more detailed textbook on excel techniques that is best
suited to her/his taste and needs. At the end of the exercise, an analogous
Python program with the same data structure is presented.

2.3.1 Cell Addressing

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.

Relative and absolute cell addressing


The coefficients of the vertex form of the parabola, x V , yV , and c, are defined in B1:B3
and recalculated in B4:B5 into b and a of the standard form, with the formulas in
C4:C5. The value in B6 specifies the horizontal distance dx between the calculation
points.
20 2 Data Structures, Excel and Python Basics

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

The independent variables x (left of ) are in A9:A169. They are obtained by


entering the initial value, here −8.0, into the first cell A9 of the range and the
formula A10 = A9 + $B$6 or A10 = [=A9 + dx] into the next cell and copying this
formula into the whole range. Copying is done by seizing the handle of A9 (see the
small black square at the lower right edge in the subpicture in column C) with the
pointer and dragging it down to A169.

 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

Questions concerning Fig. 2.2 (S):


From A9 to A10, x increases by dx = 0.1. Why is the increase 15.7 for the
next jump from −7.9 to + 8.0?2
Where is dx defined?3
Why is the name c_ in E7 provided with an underscore?4

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

identifier is automatically extended by an underscore.


22 2 Data Structures, Excel and Python Basics

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.

2.3.2 Graphical Representation of a Function

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.4 Scatter plot after completing Fig. 2.3

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

Formatting the chart


We reshape the diagram according to our taste, e.g., as in Fig. 2.1a. After clicking
on the diagram and home/format, the following components change:

– 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:

– Format/Chart Area/Border /No line


– Format/Plot Area/Border Color/Solid line/Color/Black and Width/1pt
24 2 Data Structures, Excel and Python Basics

– Format/Data Series/Marker Options / Built in/Diamond, Size 4 and Marker


Fill/Solid Fill/ Black
– Format/Horizontal (Value) Axis/Axis Options/Minimum /-8, /Maximum /8,
/Major Unit/4.

 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!

 Alac That’s cool! The diagram is alive!

 Tim Once created, it’s always up-to-date!

2.3.3 Smart Legends in Figures

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.

= a&” + ”&b&”x + ”&c_&“x” in D6 yielding 6.2 + −0.4x + −0.1x

If text is to be inserted, it must be enclosed in quotation marks, e.g., as above, “x


+ “. The concatenation operator is “&”. When the parameters a, b, or c_ change,
the text in D6 and the legend in the chart will immediately follow.

 excel Ψ “Text“& Variable concatenation with &

 Python Ψ „Text “ + Str(Variable) concatenation with +

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].

2.3.4 Scroll Bars

Cell contents are changed with a slider (a scroll bar)


We can play even more impressively with the curves when we change their parameters
with sliders. To introduce sliders, we select developer/controls/insert/activex
controls to get the tabs in Fig. 2.6a.
If the tab does not appear in your toolbar, you have to supplement the toolbar by
making a tick  in file\options\customize ribbon in the box before developer.
We need the slider to be an activex control element, and we click on the
icon for the slider in the top line on the far right, with the design mode turned on,
2.3 Basic Exercise in Spreadsheet Calculation 25

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.

Sliders in Fig. 2.2 (S)


In Fig. 2.2 (S), three sliders are introduced with linked cells E1:E3, wherefrom the
parameters a, b, and dx in B1:B3 are calculated. When one of the sliders is operated,
the cells’ value and the curve in Fig. 2.1a adapt immediately.
A slider can produce only positive integers. If other numbers are needed, plug the
value of the linkedcell into a formula in another cell. In Fig. 2.2 (S), the value of
the linkedcell (E3), set between 0 and 100, is changed with B3 = [=(E3−50)/10]
to the range −5 to 5, with intervals of 0.1.

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

Connecting a VBA macro to a control element


The following will be important in later chapters: We can connect a VBA routine to the
slider (an example is given in Exercise 10.5). A routine sub scrollbar1_change(
) … end sub is executed each time we move the scrollbar1 slider. To enter a
code, click on view code (Fig. 2.6b) and select the considered slider’s name in the
left-hand drop-down window that has popped up, then click change (or some other
action to trigger the routine) in the right-hand drop-down window.

2.3.5 Summary: Cell References and Name Manager

  The dollar makes it absolute.

Cell references, relative, absolute, indirect


The following formulas in a cell, C3 = [=A4], C3 = [=$A4], C3 = [=A$4], C3 =
[=$A$4], yield the same result: the value of cell A4 is written into the active cell C3.
However, if these formulas are copied into another cell, they change. For example, in
D4, there will be: [=B5], [=$A5], [=B$4], [=$A$4]. A $ sign before a column label
or a row number has the effect that the label or number are held fixed when copied.
A dollar makes a cell reference absolute. If the $ is missing, the label is incremented

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.

Assigning names to cell ranges


[=a*x + b] instead of [=B$2*$A6 + B$3]
Individual cells, ranges in a column (“column vectors”) or a row (“row vec-
tors”), and rectangular ranges (“matrices”) can be named and then inserted with
their names into formulas and worksheet functions as arguments. Naming is done
with the name manager by going through formulas/name manager. For details
on the name manager, see below. Make extensive use of this feature! Doing so, you
can write formulas and functions in mathematical language, e.g., [= A*sin(k*x)]
instead of [=A$1*sin($A5*B$2)]! Such a formula is valid for a set of sine functions
whose amplitudes A and wave number vectors k are stored in two row vectors with
names “A” and “k” and where the independent variable x is stored in a column vector
with the name “x”.

Name Manager of Excel


As an example to demonstrate the properties of the name nanager, we calculate
the electric field E x in x-direction of a point charge at (x 1 , 0) in the xy-plane:

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.

Calculating an electric field


In sheet “E.x” [Fig. 2.9 (S)], the x-component E x of the electric field is calculated:
x − x1
E x (x, y) =
r03

 Tim Which definitions for x, x 1 , and r 0 are valid in sheet “E.x”?

 Mag You can find this out by trial and error or by using filter in the name
manager.7

Referring to names in a cell


The ranges (vectors x and y, matrix r 0 , constant x 1 ) defined in the two sheets can be
called in each sheet cell-wise, however, they cannot be so within the complete range
of the sheet, but only within a range that matches the range in the sheet in which the
name is defined, for example, the matrix r 0 only within the range B4:F8. Outside of
this range, errors are reported (see Fig. 2.9a). The horizontal vector x may, for the
current definition of its coordinates, only be called in columns B to F, the vertical
vector y only in rows 4 to 8. The constant x 1 designates only a single cell and may
be called in the whole file without restriction.

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

Referring to names in a matrix function


The matrix r 0 can be called within any range of a spreadsheet when entering the
formulas as a matrix function, e.g., in I16:M20 in Fig. 2.9b (S). To do so, activate
the desired range, write the desired formula into the formula bar, in our case [=(x-
x.1)/r.0ˆ3], and finish with the “magic chord"! The matrix formula is enclosed in
curly brackets: {=(x − x.1)/r.0ˆ3}.

 Magic chord for completing matrix functions:  ctrl + shift +


enter.

2.3.6 What Have We Learned so Far, and How to Proceed


Further?

 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.

2.3.7 Python Program

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.1 Specifications corresponding to Fig. 2.2 (S)


1 xV=-2 #Coordinates of vertex
2 yV=6.6
3 c=-0.1 #Curvature
4 b=-2*c*xV #Coefficients of standard form
5 a=yV+c*xV**2
6 dx=0.1 #Horizontal distance between x
7 x=np.arange(-8,8+dx,dx) #Array of x values
8 yP=a+b*x+c*x**2 #Array of y values
9 print('a ={:5.2f}'.format(a),'; b ={:5.2f}'.format(b))
a = 6.20 ; b =-0.40

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

e.g., b = −2*c*x V recurring to variables specified earlier. The calculated values


of a and b (printed into the second cell) are the same as in Fig. 2.2 (S).
The term ‘a = {:5.2f}’ indicates that the printout starts with the text string ‘a
= ’ and that the value of the variable a in format(a) is to be printed right aligned
(:) in float format (f) with length 5 and 2 decimal places (5.2).
The coordinates of the focus and the directrix are calculated in Table 2.2 with
the same formulas as in Fig. 2.2 (S). A plot corresponding to Fig. 2.1b is produced
with the standard program FigStd explained in Sect. 2.4.5.

2.4 Python and NumPy Basics

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.

2.4.1 Basic Exercise

Table 2.3 displays a simple Python program developed in the Jupyter


notebook.
32 2 Data Structures, Excel and Python Basics

Table 2.3 Cell structure of Python in the Jupyter notebook

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

2.4.2 Data Structures

Data types
The following data types are available in Python:

– Int (integer, unlimited size),


– float (8 Bytes),
– bool (boolean),
– string (text),
– complex (only in numpy).

Lists
Lists contain one or more items. They:

– may contain items of different type: z = [1, 3.14, ‘abc’. 2 + 4],

– are mutable, e.g., can be changed by append or delete;


x.append(‘new’) → [x, ‘new’],

– can be concatenated by +: [x] + [y] → [x, y],


– can be concatenated by *: 3*[x] → [x, x, x],
– can be sliced, i.e., subarrays can be addressed with new identifiers: x2 =
[3:-1], from the fourth (indices 0,1,2,3,...) to the
penultimate element of x.

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:

We do not use dictionaries in this book.


2.4 Python and NumPy Basics 35

2.4.3 Python Libraries

Python libraries are collections of pre-compiled functions. They are open-source,


supported by a community of programmers, who are always there to answer
questions, e.g., on stackoverflow.com. We shall sometimes directly refer to such
advice.

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:

– npr.rand(N) generates an array of N random numbers between 0 and 1,


(Exercises 8.2 and 8.3).
– npr.randn(N) generates an array of N normally distributed random num-
bers (Exercise 8.5).

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,)

2.4.4 Numpy Constructions

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

How do the entries of xBool in Table 2.5 arise?8

8 Numerical 0 becomes False, = 0 becomes True. False is output as 0, True as 1.


2.4 Python and NumPy Basics 37

Ab-initio constructors
The following five functions construct an array from the specifications in the
argument list.

– np.ones(N) 1D-array of N ones


– np.zeros(N) 1D-array of N zeros
– np.linspace (start, stop, number of steps, endpoint =
True)
np.linspace(1.5, 3.5, 3) → [1.5 2.5 3.5], True is default.
np.linspace (1.5,3.5,2, endpoint = False) → [1.5 2.5].

– np.logspace
np.logspace(1, 3, 3, base = 10) → [ 10. 100. 1000.]

– np.arange (start, stop, step)


np.arange (0.0, 4.5, 1.5) → [0.0 1.5 3.0].

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:

– np.ones_like(Array) 1D-array of ones


– np.zeros_like(Array) 1D-array of zeros.

From the numpy.random library, imported as npr, we shall use:

– npr.rand(N) generating an array of N random numbers between 0 and 1.


– npr.randn(N) generating an array of N standard normally distributed random
numbers.

Identifiers to elements of 2-dimensional arrays


In Table 2.6, we construct 1-dimensional arrays with np.linspace and stack
them together to form a 2-dimensional array consisting of two rows. Furthermore,
identifiers to single rows, elements, columns, and 2D subarrays are specified.
38 2 Data Structures, Excel and Python Basics

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))

np.shape(Lis) (2, 4) #2 Rows with 4 entries each


Lis
[[ 0.00 1.00 2.00 3.00]
[ 10.00 11.00 12.00 13.00]]

Lis[0] [ 0.00 1.00 2.00 3.00]


Lis[0][2] 2.0

Lis[:,1] [ 1.00 11.00]


Lis[0][2:3] [ 2.00]
Lis[1][1:3] [ 11.00 12.00]

Lis[0:1][1:3]
[[ 1.00 2.00]
[ 11.00 12.00]]

 Recommendation: Use this type of presentation, printing out the shape


and content of matrices, to get an overview of your data structure!

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

– np.size(array) returns the total number of elements.


– np.shape(array)returns the shape, for 2-dimensional arrays in the form (r,c),
number r, c of rows and columns, respectively.

Stacking

– np.hstack ([list of arrays]) concatenates the 1D-arrays horizon-


tally into a long 1D-array, is defined more generally for multidimensional
arrays
– np.stack([list of 1D-arrays]) stacks the arrays (all of the same size
by necessity) in the list as rows into a 2D-array, is defined more generally for
multidimensional arrays.
2.4 Python and NumPy Basics 39

Functions

– np.sin, np.cos, np.tan, np.atan2


– np.power
– np.dot.

The function np.dot(A, B) performs a matrix multiplication of the two


matrices A and B. The same can be achieved with the operator@: A@B. Matrix
multiplication is dealt with in Exercise 2.5 in detail.
Atan2 is arcus tangens calculating the angle from the x-axis given the point
(x, y) . The order of arguments is atan2(y;x), different from excel:
np.arctan2(y, x) (Python) = atan2(x; y) (excel)
np.arctan2(3, 2) = 0.980.98 = atan2(2; 3).
np.arctan2(2, 3) = 0.590.59 = atan2(3; 2).
np.arctan2(4, 1) = 1.331.33 = atan2(1; 4).

2.4.5 Standard Plot Program

We create charts by using the library matplotlib.pyplot imported under the


name plt. As we deal almost exclusively with scatter diagrams for functions of
the form y = f(x), we do not need the full versatility of matplotlib. To profit
from this restriction, we have devised a function to plot a standard figure, FigStd,
in Table 2.7, where all necessary style information is coded within the function

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

Fig. 2.10 Parabola (the same


as in Fig. 2.1b) specified in
Tables 2.1 and 2.2 and plotted
with Table 2.8

Table 2.8 Applying our standard function for scatter plots


1 FigStd('x',-8,8,4,'y',0,10,2)
2 lblP="y=%4.2f+%4.2fx+%4.2fx²"%(a,b,c) #Label for parabola
3 plt.plot(x,yP,'k-',label=lblP) #’k-‘ Black full line
4 plt.plot(xV,yV,'kd') #’kd’ Black diamond
5 plt.plot([-8,8],[yD,yD],'k-',lw=0.5)
6 #’lw’ Line width
7 plt.plot(xF,yF,'kx')
8 for i in range(-7,-3,1):
9 plt.plot([i,i,xF],[yD,a+b*i+c*i**2,yF],
10 'k--',lw=0.5) #’k—-‘ Black dashed line
11 plt.legend()#Plots the labels for the curves within the fig

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

Table 2.9 Formatted output with %


1 a1,a2,a3=1.2345,3.4567,-4.5678
2 label="y=%4.2f*x**%4.2f +%6.1f"%(a1,a2,a3)
3 print(label)
y=1.23*x**3.46 + -4.6

2.4.6 Formatted Output

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.

2.5 Matrix Calculations in Excel and Python

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.

2.5.1 Data Structure and Nomenclature

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

a 1-dimensional array, e.g., of shape (2,), whereas a column vector is represented as


a 2-dimensional array with only one column, e.g., of shape (3, 1).

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:

U, V column vectors, shape (3, 1) 3 rows, 1 column


W, X row vectors, shape (2, ) 2 entries in the array
L, M matrices, shape (3, 2) 3 rows, 2 columns
N, O square matrices, shape (2, 2).

In the text, vectors are characterized by an underline, matrices by a double underline.


Additionally, we apply subscripts and underlines to make the variable names more
similar to the usual mathematical notation.

2.5.2 Operations on Arrays

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

Table 2.10 Functions of linear algebra


EXCEL Python

TRANSPOSE(M) np.transpose(M)

INDEX(M; r; c) M[r, c] or M[r][c]

Indexing starts in EXCEL with 1, and in Python with 0 in square brackets:

EXCEL: INDEX(W;1) Python W[0]

MDETERM(N) np.linalg.det(N)

MINVERSE(N) npl.linalg.inv(N)

MMULT(M1, M2) M1 @ M2 or np.dot(M1,M2)

In Python, a matrix is constructed as a list of row vectors. So, indexing M[2][0]


points to the first element [0] in the third row M[2]. The abbreviation stands for
numpy.linalg that is imported under that name.

Spreadsheet first
We start our overview of matrix calculations with spreadsheet constructs because the
data structure there is immediately visible on the screen.

2.5.3 Matrices in Spreadsheets

Row and column vectors, matrices


In the upper half of Fig. 2.11 (S), two column vectors U, V of shape (3,1), two row
vectors W, X of shape (2,), and two matrices L, M of shape (3,2) are defined, using
the notation for shapes in Python. In the lower half of the figure, elements of the
defined entities are singled out, with spreadsheet functions index(vector; index)
and index(matrix; row index; column index). In the last two rows, the scalar
product of the vectors W and X is calculated in Cartesian and polar coordinates.

The length l of a vector is determined with the equation l = xi2 , obtained
by nesting two functions: sqrt(sumsq(W). A 2-dimensional vector can be inter-
preted as a straight line in the xy-plane directed from (0,0) to (x,y). Its angle to the
horizontal is determined with the arcus tangens function, = atan2(x,y), which,
for vector W, reads as = atan2(index(W;1);index(W;2).
44 2 Data Structures, Excel and Python Basics

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.

{=U*V} {=V*W} {=W*V} {=V+W}


4 4 4 8 4 8 5 6
10 10 5 10 5 10 6 7
18 18 6 12 6 12 7 8

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

{=L*V} {=V*L} {=L*W} {=TRANSPOSE(L)}


4 8 4 8 1 4 1 3 5
15 20 15 20 3 8 2 4 6
30 36 30 36 5 12

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.

Operations of Linear Algebra


Operations and functions on mathematical matrices are shown in Fig. 2.14 (S). On
square matrices, the determinant can be obtained with mdeterm and its inverse
matrix with minverse.
Two matrices of suitable shapes, (n1 ,n2 ) and (n2 ,n3 ), can be multiplied with
MMult (Matrix1, Matrix2) ; the result is of shape (n1 , n3 ). Multiplying the original
matrix O with its inverse I yields the unit matrix.

2.5.4 Matrices in Python

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]]

np.shape(U) (3, 1) V*W


U [[ 4 8]
[[1] [ 5 10]
[2] [ 6 12]]
[3]]
np.sum(U*V) 32
U[0][0] [1]

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.

In Table 2.15, multiplication of L [shape (3,2)] with V [shape (3,1)] and W


[shape (2,)] is demonstrated. These are some further examples of broadcasting.
The effect of matrix transposition, np.transpose(L) , is also reported. Shape
(3,2) indicates 3 rows with 2 elements each, and may also be interpreted as a
matrix with 3 rows and 2 columns.

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

Table 2.16 Operations of linear algebra on square matrices


1 N=np.array([[1, 2], [3, 4]])
2 O=np.array([[4, 3], [2, 1]])
3 I=np.linalg.inv(N)
N np.linalg.det(N)
[[1 2] -2.0000000000000004
[3 4]]

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]

Questions concerning Tables 2.15, 2.16, and 2.17

What are the shapes of L, W, L*W, np.transpose(L)? 9

What is the shape and the type of N@I?10


What are the shapes of L, W, L@W ?11

2.6 Four Parabolas and Their Upper Envelope

Four parabolas are represented in a figure, together with their upper


envelope, first produced by a spreadsheet calculation and then by an anal-
ogous Python program intended to serve as a basic exercise in Python
programming and developed step by step in great detail.

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

2.6.1 Graphical Representation

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

^2 10^2 3*$A11^2 *$A10^2


*$A9 3*$A $ 3
9+B$3 $A10+C$ *$A11+D $A10+E$ E10) 2
*$A * * : _*x^
7 =A9+d
x +B$4 C$5+C$4 D$5+D$4 E$5+E$4 MAX(B10 *x+c
=B$ 5 = = = = =a+b
8 x yA yB yC yD yMax
9 -8.0 -10.0 2.4 4.8 -96.4 4.8
10 -7.9 -8.8 2.4 4.7 -94.8 4.7
11 -7.8 -7.7 2.3 4.7 -93.3 4.7
169 8.0 -330.0 5.0 1.0 -0.4 5.0
170

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.

2.6.2 Data Structure and Nomenclature

x V , yV arrays of the coordinates of the vertices of 4 parabolas


a, b, c arrays of the coefficients of 4 parabolas y = a + bx + cx 2
x array of x values (here, 161 from -8 to 8), separated by dx
yA , yB , yC , yC four parabolas defined over x
G matrix comprising yA , yB , yC , and yD as columns
yMax maximum of yA , yB , yC , and yD at the x values.

2.6.3 Spreadsheet Calculation

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.

Naming cell ranges


Row and column ranges can be provided with names (see Sect. 2.3.5). Activating
A1:E5 and going through formulas/create from selection/create names

12 b = -c·x V ; a = yV + c·x V 2 , see Fig. 2.2 (S) or Table 2.1.


52 2 Data Structures, Excel and Python Basics

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²

from values in the/left column does the job. Proceeding correspondingly


with A8:A169 gives us a column vector named x. The formula can now be B9 = [=a
+ b*x + c_*xˆ2] instead of B9 = [B$5 + …], and remains the same when copied
into the whole range B9:E169.

Application as a matrix formula


The formula [=a + b*x + c_*xˆ2] can be applied as a matrix formula within any
range of suitable size. In Fig. 2.15b, the range J17:M177 has been activated, the
formula entered and the process finished with the magic chord: Ψ Str + Alt + Enter.
The same numbers appear as in B9:E169 of Fig. 2.16 (S).

2.6.4 Python Program

Now, how to do all this in Python?


In the first cell of Table 2.18, we import the numpy library. We run the cell so
that the features and functions of numpy are available in the following cells.

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

13a = yv + c · xv2 and b = −2 · c · xv .


14Shape(c) = (4,), c with 4 explicit entries; b and a have the same shape, because they are
constructed with c.
2.6 Four Parabolas and Their Upper Envelope 53

Table 2.19 Creation of a column vector x


1 xS=np.linspace(-8,8,161) #Is a vector = 1D array
2 xR=np.array([xS]) #Is a matrix = 2D array with one row
3 x=xR.transpose(1,0) #Creates a column vector
4
5 np.set_printoptions(edgeitems=2,
6 formatter={'float': '{: 6.1f}'.format})
7 print(‘xS ‘,xS)
8 print(‘xR ‘,xR,'\n')
9 print(" x\n",x,'\n')
xS [ -8.0 -7.9 ... 7.9 8.0] x
xR [[ -8.0 -7.9 ... 7.9 8.0]] [[ -8.0]
[ -7.9]
...
[ 7.9]
[ 8.0]]

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]]

yA [ -10.0 -8.8 ... -324.8 -330.0] #First column

yMax [4.82 4.74 ... 4.92 5.0] #For every x

yMax = G.max(axis = 1). G is a two-dimensional array, and we have to


specify the axis along which the maximum value has to be found. Axis = 1
indicates that it is across columns for every entry in a row. The resulting curve is
shown in Fig. 2.17 as a bold gray line.
Figure 2.17 is similar to Fig. 2.15 obtained with excel, but now created by the
Python program FigStd described in Sect. 2.4.5.

Fig. 2.17 Similar to


Fig. 2.15, but produced with
the Python program in
Table 2.21
2.6 Four Parabolas and Their Upper Envelope 55

Table 2.21 Program for plotting Fig. 2.17


1 import matplotlib.pyplot as plt
2 FigStd('x',-8,8,4,'y',0,10,2)
3 plt.plot(xV,yV,'kd')
4 #’kd’ means points as black diamonds
5 plt.plot(x,yMax,color='gray',lw=4,label='yMax')
6 plt.plot(x,yA,'k-', lw=1, label=lbl_1) #’k-‘ Black Line
7 plt.plot(x,yB,'k--',lw=1.5,label=lbl_2) #-- Dashed line
8 plt.plot(x,yC,'k-.',lw=2, label=lbl_3) #-. Dash-dotted
9 plt.plot(x,yD,'k:', lw=3, label=lbl_4) #: Dotted
10 plt.legend()
11 plt.savefig('PhEx2-2 parabolas.png',dpi=1200)

Plotting four parabolas


The program for plotting Fig. 2.17 is given in Table 2.21, with the function FigStd
called in the second line. It produces a figure of size 4 cm × 4 cm with scaling and
labeling of the axes as specified in the arguments. The figure is made with the entries
label, minimum, maximum, and distance between the ticks, each for the x-axis and
the y-axis.
We add five curves with the statement plt.plot(). The plot statements all
get the pre-syllable plt, the short form under which the matplotlib library
has been imported. The x-values and the y-values of the curve to be plotted are
positional arguments and have to be the two first arguments of plt.plot. The
third argument specifies the color and style of the curve. The keyword ‘ks’ in line
2 specifies that the points (x Ext , yExt ) are to be marked with black (‘k’) squares
(‘s’). The next plot statements contain more keyword arguments, lw for linewidth,
and label for the curve’s label to be displayed in the legend. Additionally, in the
last plot statement, the curve’s color is explicitly specified with color=’gray’.
For more information on plot styles and options, consult Python Help!
The legend with all labels is plotted by calling the function plt.legend().
Generally, you can specify its position in the figure. The default is ‘loc’ =
0, indicating that the program should choose an optimum position. Specifying
‘loc’ = 2 would place the legend at the top-left part of the figure. Various style
specifications can also be incorporated with keyword arguments, e.g., fontsize
= 10. With the last statement, the figure is saved under the indicated name and
with the indicated resolution.

Question

The statement plt.legend will not plot the legend. Why?15

15The statement plt.legend() calls a function, and function identifiers have to be supplemented with
parentheses.
56 2 Data Structures, Excel and Python Basics

Table 2.22 Extrema of matrix G along different axes


1 yMax=G.max(axis=1) #Across columns, for every x
2
3 yMaxCol=G.max(axis=0) #Down the rows, for every column
4 iMaxCol=G.argmax(axis=0) #Index of Max in the row
5 xMaxCol=x[iMaxCol] #Corresponding x value
6
7 yMinCol=G.min(axis=0)
8 xMinCol=x[G.argmin(axis=0)] #Two statements in one
9 np.set_printoptions(precision=2)
xMaxCol yMax [4.82 4.75 ... 4.92 5. ]
[[-5.] #1 Max. for every column:
[ 8.] yMaxCol [ 8. 5. 4.82 5.]
[-8.] xMaxCol[:,0] [-5. 8. -8. 5.]
[ 5.]] #1 Min. for every column:
yMinCol [-330. 1. 0.5 -96.4]
xMinCol[:,0] [ 8. -2. 4. -8. ]

2.6.5 Extrema Along Different Axes

In Table 2.22, we determine the extrema of the 2-dimensional matrix G, defined


in Table 2.20 and containing the y values of the parabolas. The variable yMax
contains the maxima for axis 1, i.e., across the columns (index 1), for every entry
in the rows, i.e., for the same value of x. This is the upper envelope of the four
parabolas.
Next, we will find the individual extrema (minima and maxima) of the four
parabolas. To do so, we have to build the maxima yMaxCol and minima yMinCol for
every single curve. This is done down the rows (index 0), for axis = 0. The
arrays yMaxCol and yMinCol contain 4 entries each. The indices iMaxCol at which the
maxima occur in the columns of G are found with iMax = G.argmax(axis
= 0); x MaxCol = x[iMaxCol ] gives the corresponding x values. For the coordinates
yminCol and x minCol of the minima, we proceed accordingly with argmin.
In the printout cell, we realize that x Max is a column vector, i.e., a matrix with
only one column. The slice xMaxCol [:,0] extracts the column within the matrix
and displays it as a row.

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

Fig. 2.18 Illustration to


demonstrate indexing of G[0,:]

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.

2.7 Sum of Four Cosine Functions

We sum up four cosine functions with different angular frequencies ωi . When


the frequencies are multiples (overtones) of a fundamental frequency, such
sums mimic the time signals of sound. Beats are generated when the fre-
quencies are equally spaced within a small frequency range. The formula
for the addition of cosines is illustrated by setting each two frequencies as
equal, with the result being described by the broom rule  “Cos plus cos
yields mean times half the difference”.

2.7.1 Sound and a Cosine Identity

Vibrations of a string

 Mag Take a look at the microphone signal in Fig. 2.19a! How would you
describe the signal?

 Alac Well, a peak is repeated periodically, and in between, there is a lot of


fidgeting.

 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

 Tim The period is one-and-a-half grid distance, 7.5 ms, corresponding to a


frequency of 133 Hz. But what are harmonics?

 Mag Let’s consider the vibrations of a guitar string. How does a string vibrate?

 Tim It is sinusoidally excited, as in the bottom part of Fig. 2.19b.

 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.

 Alac In between, it may also go through zero.

 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

 Alac I guess it is the sum of the harmonics.

 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).

Task in this exercise

 Tim Now, are we going to emulate the microphone signal?

 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).

Beats and the uncertainty relation


Beats are shown in Fig. 2.21a. The four frequencies are again equidistant, but packed
together in a small frequency range ω. As control parameters for the calculation,
to be systematically varied later, we take the lowest frequency ω1 and the width
of the frequency range ω, i.e., the difference between the highest and the lowest
60 2 Data Structures, Excel and Python Basics

w.0=4; Delta.w=3 w.0=2; Delta.w=1


4 4
y y
2 2

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

 Mag With that statement, you have found an uncertainty relation:  f · t =


3/2 ≥ 1.

 Tim Heisenberg’s uncertainty relation?

 Mag Yes, it is related to the commutation relation of time t and energy E =


h f , E · t = 23 h ≥ h.
Sum of cosines

 Mag How do you write cos(x) + cos(y) as a product of two trigonometric


functions?

 Alac Is it necessary to know such things? You can look it up in handbooks.

 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.

 Mag Exactly, and if x = 0 and y = 0, then 1 + 1 = 2 must be the result.


This explains the pre-factor on the right-hand side of Eq. 2.8. We can test the sum
formula for two cosines with our calculation model by making each two of our
four frequencies equal so that only two different frequencies remain and setting all
amplitudes to 0.5. The result of such a calculation can be seen as the thick gray
curve in Fig. 2.22.
The black dotted curve corresponds to the function.

dw
2 cos w0 + t (the mean frequency)
2
and the dashed curve to.

dw
2 · cos ·t (half the difference of the frequencies).
2
We see that the cosine with half the difference frequency (dashed line)
envelopes the sum. The curve oscillates with the mean frequency (dotted line).
The product of the two curves experiences a phase shift π after each zero crossing
of the envelope.
62 2 Data Structures, Excel and Python Basics

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

2.7.2 Data Structure and Nomenclature

dt distance between adjacent points of time


t vector of 801 equidistant points of time
c1 , c2 , c3 , c4 cosine functions at t
c matrix [c1 , c2 , c3 , c4 ]
A array of 4 amplitudes
ω array of 4 circular frequencies
ω0 lowest frequency
Δω width of the frequency range of a beat
dω distance between frequencies
φ array of 4 phase shifts.
sumC sum c1 + c2 + c3 + c4

2.7.3 Spreadsheet Layout

From the very beginning: a clear layout!


We set up a worksheet calculation to sum up four cosine functions, with their ampli-
tudes A, angular frequencies ω, and zero phases φ to be chosen freely. The functions
are to be calculated from t = 0 to t = 32 s for 801 sampling points. The basic -
structure of a suitable spreadsheet set-up can be seen in Fig. 2.23 (S). The names c1 ,
c2 , c3 , c4 of the cosine functions are written in the spreadsheet with a dot separating
the letter and the number, c.1, etc., because C1, etc., are cell addresses.

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.24 (S) Parameters for a beat; ω (“omega”) is coded as w


64 2 Data Structures, Excel and Python Basics

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.

2.7.4 Python Program

Program flow in Jupyter


The program flow in the cell structure of Jupyter is shown in Fig. 2.26. The
parameters for five subtasks are specified in five program cells. The identifiers of the
parameters are the same in all five cells shown in Table 2.26 and Table 2.27. The
main program gets the parameter values from the cell that has been run immediately
before the main program is started. To keep track of the program flow, labels that
contain all relevant parameters are created in all subtasks and displayed in the main
program as legends in figures.

Fig. 2.26 Program flow: the


Overtones, all
parameters for five subtasks
are specified in five cells and
alternatively fed into the main Overtones, odd Main program
program
Columnar vector t
Beats 1
Calculate c, sumC
Beats 2
Plot sumC

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]]

calculated as c = A*np.cos(w*t + phi) and for sumC reported in the


third cell of Table 2.24.

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

To calculate the four cosines, we apply the same formula, an operation on


three row vectors and one column vector as in range B8:E808 in the spreadsheet
(Fig. 2.23 (S)).
excel: [range] = [=a*cos(w*t + phi)]
Python:c = A*np.cos(w*t + phi)
Both operations yield a 2D array, excel by dragging into a 2D range, Python
by automatic broadcasting.
You should have noticed that our spreadsheet layout has been translated line-
by-line into Python. The striking similarity between the two platforms when using
vector notation is the reason why mathematical-physical calculations can be sensi-
bly performed in excel. training such calculations is a good introductory exercise
for computational physics.
There is a difference between the spreadsheet and the Python solution
presented here:

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.

Summing up the four cosines is done in excel with the formula in F9 =


[=Sum(B9:E9)] of Fig. 2.23 (S) and in Python with np.sum(c,axis = 1).
The resulting variable sumC is a 1D vector. It is the sum across the columns (axis
= 1) for a specific value of t, and has the rows’ length. Attention: The choice of
axes does not seem intuitive, but becomes apparent when sumC is plotted versus
t; both have to be of the same length. For an overview, see Fig. 2.18.

Same data structure in Excel and Python


In spreadsheets, the formulas behind the values in the cells are usually hidden. To
report them in our figures, we have copied their text in italic into neighboring cells.
Contrastingly, in Python, the formulas are evident, but the data are hidden. To
make them visible, we print them out in a well-structured manner (see Table 2.24).
A comparison with Fig. 2.23 (S) shows that we have reached our goal to implement
the same data structure in excel and Python.

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.

Table 2.25 Specifications of the parameters for harmonics


1 A=[0.23,0.75,0.63,0.72]
2 w=[1,2,3,4] #Overtones, all
3 phi=[0,0,0,0]
4 lbl_0="ω0="+str(w[0])+", all"
5 ymin,ymax,dy=-2,3,1 #Scaling the y-axis
6 FigName="PhExI 7-4 Overtones all" #File name for later use
7 A=[0.23,0.75,0.63,0.72]
8 w=[0.5,1.5,2.5,3.5] #Overtones, odd
9 phi=[0,0,0,0]
10 lbl_0="ω0="+str(w[0])+" (odd)"
11 ymin,ymax,dy=-3,3,1
12 FigName="PhExI 7-4 Overtones odd" #In plt.savefig(FigName)
68 2 Data Structures, Excel and Python Basics

Table 2.26 Specifications of the parameters for beats


1 #Beats 1
2 A=[0.5,1.5,1.5,0.5]
3 Delta_w=1
4 dw=Delta_w/3
5 w1=2
6 w=[w1,w1+dw,w1+2*dw,w1+3*dw]
7 phi=[0,0,0,0]
8 lbl_0=("ω1="+str(w1)+"; Δω="+str(Delta_w)) #Label for curve
9 ymin,ymax,dy=-4,4,2
10 FigName="PhExI 2-7-4 Beats1" #File name in savefig()
11 #Beats 2
12 A=[0.5,1.5,1.5,0.5]
13 Delta_w=3
14 dw=Delta_w/3
15 w1=4
16 w=[w1,w1+dw,w1+2*dw,w1+3*dw]
17 phi=[0,0,0,0]
18 lbl_0=("ω1="+str(w1)+ "; Δω="+str(Delta_w))
19 ymin,ymax,dy=-4,5,2
20 FigName="PhExI 2-7-4 Beats2" #File name

Table 2.27 Specification of the parameters for the addition of cosines


1 #Addition of cosines
2 A=[0.5,0.5,0.5,0.5]
3 Delta_w=1
4 dw=Delta_w/3
5 w1=2
6 w=[w1,w1+dw,w1,w1+dw]
7 phi=[0,0,0,0]
8 lbl_0=("ω1="+str(w1)+"; dω="+str(np.round(dw,2)))
9 ymin,ymax,dy=-3,3,1 #Scaling of y axis
10 FigName="PhExI 2-7-4 Sum Cos" #File name

Beats and the addition of cosines


The parameters for the other situations are set in Table 2.26 (beats) and Table 2.27
(addition theorem of cosines).

2.7.5 Producing Labels (as Strings) in Excel and Python

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

Fig. 2.28 The sum of the


four cosines specified in
Fig. 2.27 (S)
70 2 Data Structures, Excel and Python Basics

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

4. (Python) Write a program that realizes the spreadsheet calculation in


Fig. 2.27 (S), using an instruction C = A*np.cos(w*t)! Calculate the sum
of the four cosines and plot them as shown in Fig. 2.28, with a statement
plt.plot(t,Ctot,’k-’)!

Spreadsheet function Indirect

5. Look at the entries in eight cells of a table: A1 = 5; B2 = K; E1 = 5; K5 = 7; W1


= “E"&1; W2 = indirect(W1); W3 = B2&A1; W4 = indirect(W3). Which
numbers appear in cells W2 and W4?

Arrays in Python

6. Array x is specified as x = np.arange (-8,8 + dx,dx) with dx = 1.


How many elements does x comprise and what are its first and last elements?
7. What are the elements of np.linspace (0,3,4)?
8. What is the shape of arrays U = np.array([1,2,3]), UR =
np.array([[1,2,3]]) and UT = UR.transpose(1,0)?
9. What is the shape of np.array([[1,2],[2,3],[3,4]])?
10. Let V = np.array([[1,2,3]] and W = np.array([3,2,1]).
What is the shape of U = V * W and V.transpose(1,0)?

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

Fig. 2.30 Two settings of a slider

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?

Sliders (scroll bars)


In Fig. 2.30, you can see two settings of a slider.

16. Which is the linked cell?


17. What are the minimum and maximum values of the slider?
18. The formula in F27 accesses cell D27. How does it look like?
19. The formula = (A5-500)/100 is used to generate decimal numbers between -5
and 5 recurring to a slider. What is the linked cell, and what are min and max
of this slider? What is the distance between two decimal numbers.

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.

21. How big are the numbers dPhi and r K ?

Apply names for cell ranges, if defined, in the answers to the next three questions!

22. What formulas are in cells B15 and B26?


23. Which formula is in column C below x?
72 2 Data Structures, Excel and Python Basics

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

24. Which formula is in column D below y?


25. (Python) Complete the following program by replacing # to get a figure similar
to Fig. 2.31a:

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

In this chapter, we practice clearly-structured calculations with formulas. Our


aim for spreadsheets:—formulas in cells should be similar to mathematical
formulas, a feat that is achieved by naming variables, calling them by their
name, and clearly separating independent and dependent variables. As in
every chapter, parallel solutions in Python are presented. For both excel
and Python, we aim to document intermediate results step by step from
top to bottom and accompany them with charts. This way, the results are
checked during the implementation of the formulas, and the calculation is
easy to understand, even weeks later. With these rules in mind, we treat
image construction for lenses, the Doppler effect, and exponential growth.

3.1 Introduction: Well-Structured Sheets and Programs

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.

Physical tasks with networks of formulas


Many tasks in secondary education, or in physics courses at colleges, or even in
regard to minor subjects at universities, are based on simple formulas used to solve
practical tasks. In this chapter, we solve such tasks through spreadsheet calculations
and Python programs:

– image constructions for optical lenses,


– the Doppler effect with a general formula and for an observer off a race track, and
– exponential diode characteristics.

© Springer Nature Switzerland AG 2022 75


D. Mergel, Physics with Excel and Python,
https://doi.org/10.1007/978-3-030-82325-2_3
76 3 Formula Networks and Linked Diagrams

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.

Solve step by step and write it down in mathematical language!


The student shall learn to keep an overview by developing the solution step by step
and displaying the results graphically, e.g., as optical ray construction. The diagrams
should adapt automatically to any change in the parameters of the task.

Illustration: Draw a rectangle!


We consider a simple task: Specifying the width w and height h of a rectangle,
calculating its area A, and drawing the rectangle as a chain of straight lines with
vertices (x, y), with its center at the origin of the coordinate system (see Fig. 3.1a).

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.

Formula network in spreadsheets


In spreadsheet calculations, we have to pay special attention in order to achieve our
goal. It is necessary to call all variables by names such that the cell formulas can
be written like mathematical formulas. It is often useful to present the calculation
in four columns: designation of the quantity, variable name as an identifier for cells,
numerical value, and physical unit. An example is given in Fig. 3.1b. All independent
variables are in a block at the top left of the sheet, with names in B2:B5 and units in
D2:D5.
If one of the independent variables is changed, the entire calculation and all
diagrams should follow, without corrections having to be made somewhere in the
3.1 Introduction: Well-Structured Sheets and Programs 77

Table 3.1 Specifying the coordinates of a rectangle around (0, 0)


1 w=2 #[m] Width
2 h=3 #[m] Height
3 A=h*w #[m²] Area
4 x=[-w/2, -w/2, +w/2, +w/2, +w/2]
5 y=[-h/2, +h/2, +h/2, -h/2, -h/2]

sheet. We call a spreadsheet structure corresponding to these requirements a ‘formula


network’. It is often useful to change independent variables with sliders that can
quickly be used to get an impression of the trend of the solution (not realized in
Fig. 3.1b).
The area is calculated as F = h * w = height by width. If you write “= h * b”
into cell C5, C5 = [= h * w], then immediately “6” appears after you hit Enter.
In columns F and G of Fig. 3.1b, the coordinates for the graphical representation in
Fig. 3.1b are calculated. The formulas are the same as for x and y in Table 3.1. Cells
and cell areas must be named, e.g., F2:F6 with “x”. A good formula network must
not only be correct, but also clear!

Provide cells in spreadsheets with names


There are several ways to name cell areas. We already became acquainted with this in
the last chapter in Exercise 2.1 and Sect. 2.3.5. You can also find out more about this
in the excel help under the keyword “Create a name”. We prefer to use the variant
formulas/defined names/create from selection, which has the advantage
that the names given in the name manager are visible in the spreadsheet, and thus
contribute to the clarity of the calculation.

Check the solution with diagrams


For the representation of the rectangle in a diagram, here, Fig. 3.1a, the coordinates
x, y are calculated from the values for width w and height h. The drawings should
adapt automatically to any change in the parameters of the task. Therefore, in the
spreadsheet of Fig. 3.1b, columns F and G contain formulas and not just numbers.
The entries for w and h control all computations in the sheet and the figure, giving
the impression of a “living spreadsheet”.
Experience has shown that it is especially appealing to many students to work on
the tasks until the diagram “obeys on command”. In the case of more complex tasks,
it is also easier to see whether the formula is correct.

Question

What are the formulas for x and y in Fig. 3.1b (S)?1

1 x = +w/ 2 or x = –w/ 2; y = +h/ 2 or y = –h/ 2, always correctly combined.


78 3 Formula Networks and Linked Diagrams

Mathematical functions
In this chapter, we apply four mathematical functions:

– straight lines for image constructions of geometrical optics,


– exponentials for diode characteristics,
– polar coordinates with sine and cosine.

3.2 Image Construction for Focusing and Diverging Lenses

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.

3.2.1 Straight Line Equation

In this exercise, a straight line is defined by two points (x 1 , y1 ) and (x 2 , y2 ). For a


given third coordinate x 3 , a coordinate y3 is to be calculated so that the point (x 3 ,
y3 ) lies on the straight line.

Straight line equation


Given two points (x 1, y1 ) and (x 2 , y2 ) of a straight line, the straight-line equation is

y(x) = y1 + m · (x − x1 ) (3.1)

or

y(x) = y2 + m · (x − x2 ) (3.2)

both times with the slope

y2 − y1
m= (3.3)
x2 − x1

We call the respective points (x 1 , y1 ) in the first straight-line equation and (x 2 , y2 )


in the second the reference points of the straight line.
3.2 Image Construction for Focusing and Diverging Lenses 79

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

Questions concerning Fig. 3.2a (S):


What are the linked cells for the three sliders?2
Which number range (the same for all) is presumably covered by the
sliders?3
If the coordinates, to be set by sliders with min = 0 and max = 800, take
on values between −4 and 4, what are the formulas in cells B1, B5, and B8,
with which the coordinates are calculated from the cells linked to the sliders?4

2 The linked cells are C1, C5, and C8.


3 The number range of all sliders runs from 0 to 800.
4 B1 = [=(C1 − 400)/100]; B5 = [=(C5 − 400)/100]; B8 = [=(C8 − 400)/100].
80 3 Formula Networks and Linked Diagrams

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

If we have done everything correctly, the graphic presentation in Fig. 3.2a


should adapt to every change of the values for y1 , x 2 , x3 by the three sliders,
and the three points should lie on a straight line every time.

3.2.2 Geometrical Image Construction for a Thin Focusing Lens

Image construction by ray drawing


Figure 3.3 illustrates how the image of an object point is constructed with three
characteristic rays in the xy-plane.
The x-axis represents the optical axis and also the axis of the circularly shaped
lens. A thin lens is represented by its principal plane and its focal length. The shape
of the lens does not play a role anymore. The principal plane is the plane x = 0 in
which the y-axis is situated.

Question

How does the parallel ray in an image construction run?6

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

= 0 and then through the image-side focus.


3.2 Image Construction for Focusing and Diverging Lenses 81

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.

  Lens equation with plus and minus!

3.2.3 Imaging Equation with Correct Signs

 Mag Do you know the imaging equation for lenses?

 Alac Sure, I’ve already learned it at school:

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

General imaging equation for lenses


For the analytical computation of images of lenses, the imaging equation has
to be written with signs:

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).

3.2.4 Beam Through a Converging Lens that Really Contributes


to the Image

 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

Cross-section of the lens


We are going to add the cross-section of the lens to the drawings. To do so, we need
to construct segments of a circle. We make use of the circle equation:

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.

3.2.5 Data Structure and Nomenclature

fI image-side focal length


(x O , yO ) coordinates of the object point
(x I , yI ) coordinates of the image point, to be calculated with the imaging
equation.

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.

x Par , yPar 3 characteristic points of the parallel ray


x Cen , yCen 3 characteristic points of the central ray
x Foc , yFoc 3 characteristic points of the object-side focal ray
mPar , mCen , mFoc slopes of the non-horizontal parts of the three rays
x Lens , yLens cross-section of a converging lens, calculated with Eq. 3.8.

3.2.6 Spreadsheet Calculation

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.

 Ψ Empty rows separate curves.

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.

 Alac A fascinating experience!


The parameters in Fig. 3.7 (S) are for a converging lens (f I = 6.0) and an object
distance (x O = −15) beyond the focal length (Fig. 3.3). With f I = 3.0, x O = −9,
and yO = 7, Fig. 3.4a results. With f I = 3.0, x O = −2 (within the focal length),
and yO = 3, Fig. 3.4b results.
For a diverging lens (Fig. 3.5), we choose f I = −6 and x O = −10 (a) or x O =
−5 (b).
88 3 Formula Networks and Linked Diagrams

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

Ray bundle through the lens


We use a VBA subroutine7 as in Fig. 3.8 (P) to draw the ray bundle that physically
contributes to the image. The rays run from the object point (x O , yO ) to a point in the
lens, and finally to the image point (x I , yI ). The coordinates of the points are in C3:C7
of a spreadsheet; they are read in the first lines of the sub-routine. The parameters
of the lens are specified within the subroutine. The defining points of the rays are
written into columns 6 (c2 , F) and 7 (c2 + 1, G) of the spreadsheet.

3.2.7 Python Program

Specifications for three different types of images


The Python program is organized into four cells. The first three cells contain the
specifications and a filename to store the resulting figure, each for

– a converging lens (Table 3.2, resulting in a figure similar to Fig. 3.3),


– a diverging lens with the object outside the focal length (Table 3.3 top, resulting
in Fig. 3.5a),
– a diverging lens with the object inside the focal length (Table 3.3 bottom, resulting
in Fig. 3.5b).

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.

7 VBA macros are introduced in Chap. 4.


3.2 Image Construction for Focusing and Diverging Lenses 89

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)

General program for drawing the image construction


The main program is in Table 3.4; it performs the image construction according to
the specifications in the cell executed earlier. Arrows representing the object and the
image are drawn. The coordinates of the object follow directly from the specifications
90 3 Formula Networks and Linked Diagrams

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.

Plotting an arrow in Python


A user-defined function for drawing an arrow from point P0 to point P1 is shown in
Table 3.6.
The arrow is plotted from P0 to P1 , with color c, linewidth lw, and headwidth
hw entered as keyword arguments. If the function call does not specify the values
of the keywords, the default values specified in the header are taken. The coor-
dinates of the two points have to be translated into the expected entries of the
function plt.arrow of the MatPlotLib library.

Cross-section of the lens


The program for drawing the cross-section of a lens is given in Table 3.7.
The arrays y and x specify only one-quarter of the cross-section (see the values
in the bottom cell). They run from (2.0, 0.0) up to (0.0, 6.0). For a complete
cross-section, we need three more curves. They are obtained with the help of the
functions
np.flipud (“flip up down”) reversing the order of the elements in an array,
and
np.hstack concatenating arrays to one long array, x Lens resp. yLens .
The concatenated arrays x Lens and yLens are used for the drawing performed in
Table 3.8, line 21. The curve begins at (0.0, 6.0), runs to (2.0,0.0), continues to
(0.0, −6.0), then to (−2.0, 0.0), and closes the cross-section by running to (0.0,
6.0).
3.2 Image Construction for Focusing and Diverging Lenses 91

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]

Bundle of rays through the lens


The coordinates of the nR = 11 rays going through the lens are calculated in Table
3.8 with pre-specified coordinates of the object and the image point, e.g., in Table
3.4. The rays are drawn in a for-loop, starting with a y-coordinate at the bottom of
the lens and increasing it by y = 2·r L /(nR − 1). The cross-section of the lens is
drawn with the plot-statement in line 21, using the coordinates x Lens , yLens calculated
in Table 3.7. The complete drawing, i.e., image construction, lens, and ray bundle,
is shown in Fig. 3.6.

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

3.3 Doppler Effect

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.

3.3.1 A Formula for All Cases

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.

Formula for intuitive use (Doppler)


The relationship between frequencies f (frequency ratio) and speed v is given by
the following formula:

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

8 f R / f S = c/(c − v S ), the received frequency becomes higher.


3.3 Doppler Effect 93

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

Sender overtakes receiver


Let us apply Eq. 3.9 to the situation in which the sender and receiver both move in
the same direction, and the sender overtakes the receiver.
Before overtaking, the sender is approaching the receiver, thereby increasing the
received frequency (minus sign in the denominator). The receiver is moving away
from the sender, also reducing the received frequency (minus sign in the numerator):

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 |

Remember: |vR | und |vS | are speeds (amount of the velocities).

Motion on a straight line, analytical formula (Doppler)


We formulate a general formula in which the signs are automatically correct:

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.

9 (a) f R / f S = (c−v R )/(c − v R ) = 1; (b) f R / f S = (c+v R )/(c + v R ) = 1; the received frequency


is, in both cases, equal to the sent frequency.
94 3 Formula Networks and Linked Diagrams

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

 Alac Proof by trial and error? You can’t do that in math!

 Mag With trial and error, proof is not possible, but serious mistakes can be
uncovered. You can later rigorously prove the formula.

Check the analytical formula in a spreadsheet


In Fig. 3.9 (S), ten situations are listed (D:E) in which sender and receiver move to
the left or the right or one of them is at rest, and it is also distinguished as to whether
the sender is to the left or the right of the receiver. In column F, the frequency ratio
is calculated according to Eq. 3.9, “for intuitive use”, considering which signs are to
be used for each formula. In column M, the analytical formula Eq. 3.13 is applied
relating to the values 1, 0, or −1 indicating the direction of the movements (s.vR,
s.vS) and the relative position (x.S, x.R), with respect to the zero of the straight line,
of receiver and sender. The quantity x Rel is defined as sign(x R − x S ).

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).

Unwrapping a list with *


The function Doppler defined in Table 3.9 expects three positional arguments. The
parameters of our lists are, however, specified in one object, the list var1. Calling
Doppler(var1) results in an error message: TypeError: Doppler() missing
1 required positional argument: ‘vR’. In the call of Doppler in line
11, list var1 has, therefore, been unwrapped (*var1) so that the elements of var1
are transferred and not the list as one object.
3.3 Doppler Effect 95

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

3.3.2 A Sound Source Passes a Remote Receiver

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

Velocity on line connecting sender and receiver


The velocity along the current connection line (dashed) determines the perceived
frequency. The quantities vR (receiver) and vS (sender) in Eq. 3.9 are the velocity
components on the current connecting line between sender and receiver, i.e., on the
dashed lines in Fig. 3.10a.
The velocity must have the correct sign. The upper signs in Eq. 3.9 apply when
the car is approaching, and the lower signs when it is driving away. For the situation
described above, the sender’s velocity component in the direction of the stationary
receiver is to be determined by differentiating the distance with respect to time. This
yields a negative velocity when the car is left of x = 0 and a positive velocity when
is it right of x = 0, so that the frequency ratio

fR 1
= (3.14)
fS 1 + vcS

is valid for the whole track.


Frequency curves for the distances yR = 20, 50, and 100 m are displayed in
Fig. 3.10b. The closer the receiver is to the track, the stronger the frequency varies
with the position of the car. When the sender is at the receiver’s height, the received
frequency is identical to the sent frequency.
The interesting thing about the computation model in this exercise is that the time-
dependent distance of the sender to the receiver is to be calculated (with Pythagoras)
at each interval boundary. Then, the velocity component on the connecting line is
obtained through numerical differentiation. In this way, more complicated geometries
can also be treated, e.g., when the transmitter is moving at varying speed on a circular
path, or if transmitter and receiver are moving on different paths.

3.3.3 Data Structure and Nomenclature

c speed of sound in air


vS velocity of sender in x direction
vR velocity of receiver in x direction
fS frequency of sender
fR frequency at receiver
xS position of sender
xR position of receiver
x array of 201 equidistant positions of a sender on the x-axis
t(x) points of time corresponding to x
yR distance of the receiver to the x-axis 
dist current distance sender-receiver, dist = x 2 + y 2R .
v relative speed along the line connecting sender and receiver
3.3 Doppler Effect 97

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

3.3.4 Spreadsheet Calculation “Remote Receiver”

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.

 Mag The frequency ratio is calculated numerically in columns F and G. Over


which local coordinates do you plot the calculated frequencies? Perhaps over x in
column B?

 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.

 Mag Right! The centers of the intervals are calculated as x C in column H.

3.3.5 Python Program “Remote Receiver”

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

concerning Table 3.10:


What are the arguments and the global parameters accessed in FreqLine?10
The local variable x C over which the received frequency is to be plotted
is calculated in the main program. Would it be more consistent to calculate
x C in FreqLine and return it together with the normalized frequency (def
FreqLine(x, yR) …. return xC,fRes)?11

Question

concerning Table 3.11


What does the keyword argument lw=1.5 in the plot function specify?12
What does the label in line 8 look like?13
How do we specify that the figure is saved with a resolution of 1200 dpi?14

The plot program in Table 3.11 calculates and displays the frequency curves
for the three distances yR = 20, 50, and 100 m.

10 FreqLine, argument: yR, global parameters x, dist, c, Dt.


11 Discuss!
12 Line width lw = 1.5 point.
13 The label is “yR = 20”.
14 plt.savefig (’Doppler off, multiple.png’, dpi=1200), dpi is a key

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.

3.4.1 Explosive Character of Exponentials

Rice grains on a chessboard


In a classic bet from far eastern literature, a clever chess player agreed with his
king that his winnings would be paid by placing a rice grain on the first square of
a chessboard and then doubling the number of grains repetitively on each of the
following 63 squares.
In Fig. 3.12a (S), the doubling of the number of rice grains is simulated with a
spreadsheet calculation. In A3:A66, the 64 squares of the checkerboard are numbered
from n = 0 to 63. In B3, a rice grain is placed on the first field (n = 0, B3 = [1]). In
the following cells, the preceding number is doubled until the huge number 263 =
9.22 × 1018 is reached in B66 (n = 63), on the 64th square.

 Ψ 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

Fig. 3.12 a (left, S) Powers of 2, y = 2n , obtained by repetitive multiplication by 2 (column B)


and by potentiation (C: E). The formula in E1 refers to E3 b (right) Graphical representation of the
powers of 2 of a

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?

 Alac Perhaps once.

 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!

 Alac Crazy! A disaster! This cannot be true! What’s the catch?

 Mag There is no catch. The catastrophe results from the rule  plus 1 yields
times 2 governing the exponential 2n .

The power function y = 2n is calculated in column C of Fig. 3.12a (S). It


is entered as the worksheet formula [= 2ˆn] and yields the same results as the
repetitive multiplication by 2 in column B. The argument of the power function
does not have to be an integer. In E3, the value for the power in D3 (= 62.4) is
calculated and inserted as a filled diamond in Fig. 3.12b.

Maximum float number


We continue doubling the preceding number in the worksheet beyond n = 63 until
the application can no longer store the resulting number. As of row 66 in Fig. 3.12a
(S), the numbers are represented in exponential form, 9.22E+18+18 = 9.22 × 1018 .
The number 21024 can no longer be calculated in excel2019; see the error message
#num! in row 1027.
In Python 3, the int format can store arbitrarily large numbers. However, if
the number is to be calculated as float, the same limit holds as in Excel: 2**1023 gives
8.988e+307 and 2**1024 returns the OverflowError: int too large to
convert to float.

3.4.2 General Exponential Function

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).

Exponential function with characteristic length


The normalized exponential function is usually written in mathematical textbooks
as follows:

f (x) = |a| · exp(ax) = |a| · eax (3.15)


 1
The letter e denotes Euler’s number e = ∞ 0 n! = 2.718. Normalized means that
the integral from 0 to +∞ (for a < 0) or from 0 to −∞ (for a > 0) is 1. The integral
is dimensionless because the product of the units of dx and a is 1.
102 3 Formula Networks and Linked Diagrams

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.

3.4.3 Representation in a Diagram

First, the tangent at t = 0!


Two exponential functions, together with their tangents at t = 0, are shown in
Fig. 3.13a. Here, the independent variable is time t.

 Mag Do you now know how to draw an exponential function Ae ·exp(t/t 0 ) by


hand on a piece of paper?

 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

 Mag Correct, just as in Fig. 3.13b! Keep in mind:

  Plus one in x, times e in y


 Expo with kink and straight line

 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.

3.4.4 Diode Characteristics I(U)

The current I through a semiconductor diode depends exponentially on the applied


voltage U. The I (U) characteristics of a semiconductor diode are described by an
exponential function passing through zero:
   
U
I = Is · exp −1 (3.17)
UT

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

Also shown in Fig. 3.14a is an exponential function without the term −1 in


the parentheses of Eq. 3.17. This function intersects the I-axis at I s . It grows by
a factor of exp(1) ≈ 2.7 whenever U progresses by dU. The curves in Fig. 3.14a
appear to be exponential, the way they are usually represented.
For exponential functions to the base e, the broom rule is  Plus 1 yields times
e. In the concrete case, this means that, if U advances by U T (the distance between
the vertical gridlines in Fig. 3.14), exp increases by a factor of about 2.7.
In Fig. 3.14b, the same data as in Fig. 3.14a are shown twice, only with different
scaling of the two I-axes: I Max is now at 2.5 × 10–5 A (left vertical axis) or 2.5 ×
10–3 A (right vertical axis); the curves seem to exhibit a kink at about 0.5 and
0.6 V. In electrical engineering, this voltage is called the “kink voltage”, “knee
voltage” or “cut voltage”.
The increase of the U-value by a factor of 2.7 when progressing from U =
0.475 to U = 0.500 V looks like a steep rise. It increases, however, by the same
factor when it progresses from U = 0 to U = 0.025 V but then appears like the
familiar soft curvature of the exponential. The position of the seeming kink on the
U-axis is a function of the scaling of the I-axis.
In Fig. 3.15a, the I-axis is logarithmic. In this representation, the diode charac-
teristics appear as a straight line, except for the points below U = 0.05, because,
there, the term −1 is quantitatively significant. A kink is nowhere to be seen.

3.4.5 Data Structure and Nomenclature

Exponential function

A, B amplitudes of functions expA and expB


tA, tB time constants of expA and expB
dt length of time interval
t array of instants of time, separated by dt
expA , expB values at times t.

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).

3.4.6 Spreadsheet Calculation

Initial slope of the exponential function


In Fig. 3.16 (S), two exponential functions are calculated for 51 points equidistant
in t,
 
t t
ex p A (t) = A · ex p = A · e tA (3.18)
tA

and expB correspondingly. The characteristic time, t A or t B , may be positive or


negative. The distance dt between the points is set in B3.

 For the exponential function y = ex , applies;  Plus 1 (in the


argument) yields times e (in the value).
For the power of 2, y = 2n holds:  Plus 1 yields times 2.
106 3 Formula Networks and Linked Diagrams

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:

19 A6 = [5], A7 = [= A6 + dt] = 7; A8 = [= A7 + dt] = 9.


20 Straight line through the points (0, A) und (−t e , 0).
21 The distance of adjacent points is dt = 2 (see Fig. 3.16 (S), B3).
22 The definite integral is 90, based on Eq. 3.16, because 3 = 1 · 90.
30
3.4 Exponentials 107

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.

Formatting the axis of a diagram


The axis of a diagram is formatted by activating it with the left mouse button and
then clicking format. In the current selection group to the left of the ribbon,
vertical (value) axis shows up in the bar. Upon clicking format selection,
a window opens that allows you to set the minimum, maximum and other param-
eters of the axis. If the axis is to be scaled logarithmically, the appropriate box, 
logarithmic scale, must be activated with a checkmark.

3.4.7 Python Program

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:

– L1 = np.arange(−20, 80+dt, dt) with dt = 1,24


– L2 = np.linspace (−20, 80, 100),25
– L3 = np.linspace (−20, 80, 101)26
– L2 = np.linspace (−20, 80, 100, endpoint=False).27

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”).

23 plt.plot([0,tA],[A,0],’k-‘), compare F5:H8 in Fig. 3.16 (S)!


24 L1, size 101, last element L1[−1] is 80.
25 L2, size 100, last element 80.
26 L3, size 101, last element 80.
27 L4, size 100, last element 80 − 100/100 = 79.
3.4 Exponentials 109

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

1. To practice programming, translate the spreadsheet solutions of this chapter into


Python and compare with the suggested programs!

Python-specific

2. Let x=np.linspace(−100,100,101). What is the distance between


neighboring elements? What does x[1:]−x[:−1] look like? What are the first
and last elements of (x[1:] + x[:−1])/2 ?
3. Let A = 3.001 and t A = −30.0. How can we produce a label “3.0*exp(t/−30)”?

Concerning Table 3.15:

4. What is the size of the list col?


5. What are the first two elements of col?
6. What are the last two elements of col?
7. How do you compile the four lines into one line with list comprehension?

Check your answers by programming!

Table 3.15 Producing a list x*y


1 col=[]
2 for x in range(1,11):
3 for y in range(1,6):
4 col.append(x*y)
110 3 Formula Networks and Linked Diagrams

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

8. Explain the broom rules:


Ψ Lens equation with plus and minus.
Ψ Blank lines separate curves.
Ψ Doppler effect with plus and minus.

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

Image construction with converging and diverging lenses

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!

28 Equations 3.5 and 3.6.


112 3 Formula Networks and Linked Diagrams

Fig. 3.20 Gravitational F g


and centrifugal F c force 8 Bank line
when driving through a curve
Fg, Fc

0
0 2 4 6 8 10

Forces when driving through a curve

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

30. What is the distance d SR between car and pedestrian as a function of t?


31. What is the formula for calculating the relative velocity vSR in the direction of
the link line? To answer this question, you have to define vectors x R , yR and d SR .

Exponential function

32. To draw an exponential function freehand on paper, it is useful to start with a


straight line as a guide. How is this straight line determined by the exponential
function parameters, amplitude A and time constant τ ?
33. An exponential function increases from 1 to 2 when the argument is increased
from t = 0.0 to 0.1 s. How much does it increase if the argument is increased
from 0.0 to 0.2 s? Think binary! How much does it increase if the argument is
increased from t = 0.8 to 1.0 s? Sketch the same exponential function twice,
each time with the t-axis from 0 to 1.2, but with a y-axis scaling from 0 to 4 for
the first sketch and from 0 to 16 × 4 for the second sketch! What do you see in
the second sketch that is not obvious in the first sketch?
Macros with Visual Basic and Their
Correspondences in Python 4

We practice the basic programming structures: loops, branches, sub-routines


(FOR, IF, SUB/def), with particular emphasis on data exchange between
spreadsheets and procedures. We will learn to obtain the sequences for
EXCEL-typical spreadsheet operations by recording the associated commands
with a macro recorder. With this knowledge, we will:

– draw dense-packed crystal planes,


– decode protocols of measuring instruments and compile clear summaries
of the results,
– systematically modify the parameters of calculation models with log and
control procedures and continuously enter the results of the calculations
into another range of the spreadsheet, and
– outsource complicated formulas into user-defined spreadsheet functions
in order to arrange the tables more clearly.

We will present parallel solutions in Python creating the drawings with


the library turtle.

4.1 Introduction: For, If, Sub/Def

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.

Tim worries, Alac brags

 Mag This chapter will teach us to program, to let macros interact with
spreadsheet calculations, and to realize parallel solutions in Python.

© Springer Nature Switzerland AG 2022 115


D. Mergel, Physics with Excel and Python,
https://doi.org/10.1007/978-3-030-82325-2_4
116 4 Macros with Visual Basic and Their Correspondences 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.

 Alac So, I’m essentially learning more physics?

 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.

Only a few algorithmic constructions


In our programs, we use constructions that are the same in all algorithmic languages:
Loops, logical branches, sub-routines (FOR, IF, SUB/def) . Special EXCEL instructions,
e.g., for handling files or creating drawings, will be provided to us by the macro
recorder, which records commands that the user makes when setting up spreadsheet
calculations.
Three types of program will be used repeatedly in the following chapters: log
procedures, formula procedures, and user-defined functions.

Rep-log and scan-log procedures


Two tools can be used sensibly for every task in EXCEL: Sliders and log procedures.
With a slider, variables in a spreadsheet can easily be changed manually, and the
user can see how the results change, as we have learned in the basic Exercise 2.2. A
rep-log procedure systematically changes independent variables in the spreadsheet
and continuously writes the calculation results into another spreadsheet range. The
spreadsheet calculation works like a function. The equivalent in Python is functions
that are repetitively called in loops. Scan-log procedures scan a range of a spread-
sheet and write the data into another range in a structured manner. The program in
Fig. 4.5 (P) is a simple example. In Chaps. 8 to 10, log procedures repeat stochastic
experiments to illustrate statistical rules and laws.

User-defined functions in visual basic


We generally recommend performing calculations step by step in several rows or
columns. If the calculation runs without errors, spreadsheet space and calculation
time can be saved if you execute this calculation in a user-defined spreadsheet func-
tion, with values transferred from the spreadsheet into the program, and with values
written into the spreadsheet by the function, exactly as we learned with built-in
spreadsheet functions, e.g., COS(x) or SIN(x). As examples, we shall implement func-
tions for the scalar and the vector products of three-dimensional vectors, as usual, in
both 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”.

4.2 Basic Exercise: FOR-Loops

We get to know the VISUAL-BASIC-Editor and practice reading cell con-


tents and filling in cells. We are using For-loops to execute tasks one after
the other with systematically changed parameters. This often involves incre-
menting a running index in the loop that indicates a cell’s position in
the spreadsheet. Such loops are called loop2i, obeying the broom rule 
Continue counting in the loop!

4.2.1 Visual-Basic-Editor 1: Editing

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

Enter values and formulas into cells


Write SUB Name into the first line of the white area! For “Name”, enter your own
name. The editor adds one line END SUB. You can now write statements between SUB
Name and END SUB. In Fig. 4.2b, SUB Annegret has been created with four instructions.
Cell B1 in a spreadsheet can be addressed in two ways, with CELLS(1,2) or with
RANGE(“B1”). CELLS(r,c) addresses the cell in the rth row and cth column. Cell A1
(= CELLS(1,1)) is filled with a text in quotation marks, here, with “Annegret”. Of
course, you should write your own name.
Individual cells can also be addressed with instructions of the type
[RANGE(“A1”) = …], as in lines 3 and 5 of the macro in Fig. 4.2b. In loops,
the addressing with CELLS(r,c) can be used more effectively, if, e.g., the row index
r or the column index c is to be scanned systematically.

 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:

– a number is written into Cell B1, here, 12.25.


– CELLS(2,1) = CELLS(1,2) means that cell A2 (CELLS(2,1)) is being filled in with
the contents of cell B1 (CELLS(1,2)). The content of B1 is transferred once to
A2 by the program, and A2 remains unchanged, even if the content of B1 is
changed later.
– The text “ = A1” is written into cell B2, interpreted in the spreadsheet as a
formula. The corresponding cell is filled in with the contents of cell A1, B2 =

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

1 Sub Protoc2() Cells(r2, 6) = Cells(2, 3) '6 = column F 7


2 r2 = 2 'Running index for writing to cells Cells(r2, 7) = Cells(3, 3) '7 = column G 8
3 Cells(1, 6) = "Cos(x)" Cells(r2, 8) = Cells(4, 3) '8 = column H 9
4 For x = 3 To 9.5 Step 0.25 r2 = r2 + 1 10
5 Cells(1, 3) = x 'Column C Next x 11
6 Cells(r2, 5) = x 'Column E End Sub 12

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 .

  Loop2i: Continue counting (the running index) in the loop!

Spreadsheet calculation used as a function


In cells C2:C4 of Fig. 4.3 (S), formulas with the trigonometric functions COS, SIN,
and TAN are written by hand with the argument in C1, e.g., C1 = [9.50] and C2 =
[=COS(C1)]. These spreadsheet calculations are used by SUB Protoc2 in Fig. 4.5 (P)
as a function. It is a typical rep-log procedure, changing a parameter in a spreadsheet
calculation and writing the calculation results to another range of the spreadsheet.
SUB Protoc2 changes the value in cell C1 in the (x = )-loop, which is used as an
argument in the functions in C2:C4, and transfers the results of the spreadsheet
calculation from C2:C4 (one below the other) to F to H (side by side).
The statement in line 3 is: CELLS(1,6) = ”Cos(x)”. The quotation marks indi-
cate a text in between, which is to be written as text into the cell. An instruction
CELLS(1,6) = COS(x) would cause the program first to calculate the cosine of the
variable x, to which one would have to have assigned a value somewhere earlier
in the procedure, and then write the result, a number, into the cell. An instruction
CELLS(1,6) = ‘ = COS(x)’ would write a formula into the cell, similar to line 9 in
Fig. 4.4 (P).
All cell references with fixed row and column indices can also be expressed
with RANGE, e.g., RANGE(“C2”) instead of CELLS(2,3).

Questions

concerning SUB Protoc2, Fig. 4.5 (P)


122 4 Macros with Visual Basic and Their Correspondences in Python

1 Sub ScanCopy() Cells(r2, c2 + 1) = Cells(r, c) 7


2 r2 = 2 'Row 2 r2 = r2 + 1 8
3 c2 = 10 'Column J Next c 9
4 For r = 1 To 4 'Rows 1 to 4 r2 = r2 + 1 10
5 For c = 3 To 8 'columns C to H Next r 11
6 Cells(r2, c2) = c End Sub 12

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

What do the instructions in lines 3 and 5 have to be if you want to address


with RANGE?1
Which instructions must be added to the code to write the headings in G1
and H1 of Fig. 4.3 (S)?2
How would you have to change the for-loop in lines 4 to 11 if you want to
read the x values from column A?3

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.

1 RANGE(„F1“) = “Cos(x)”: RANGE(„C1“) = x.


2 RANGE(„G1“) = “Sin(x)”: RANGE(„H1“) = „Tan(x)“; do not forget the quotation marks!
3 FOR r = 2 TO 28: x = CELLS(r, 1): … To put multiple statements on one line in VBA, separate the
statements by a colon “:”!
4.2 Basic Exercise: FOR-Loops 123

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

How do we proceed further?


In this basic exercise, we have learned how to read content from cells into proce-
dures and fill in cells. We have also become familiar with FOR loops and the special
construction of loop2i with a loop index and a running index. In this chapter’s next
exercises, we will get to know sub-routine calls (SUB) and logical queries (IF) . FOR,
SUB, IF are already the essential basic structures of programming, which we will
repeat in Python (def instead of SUB) and apply in the following chapters over and
over again.

4.3 Macro-Controlled Drawings with FOR, SUB, IF

We construct a macro for drawing filled circles of variable diameter at dif-


ferent coordinates in the spreadsheet. The required instructions are obtained
by recording macros generated when a circle is inserted and formatted as
a shape by hand. They are combined in a sub-routine to be called from
the main program, specifying the circles’ position. Similarly, we get the
instructions for drawing rectangles and triangles. We are practicing the basic
structures of programming: FOR, IF, SUB.

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,

namely, c2 , must be adjusted in addition to r 2 .


6 Because, in ScanCopy in Fig. 4.6 (P), at the end of the loop FOR r = 1 to 4, the index r is
2
incremented without data having previously been written into cells in that row.
7 At the end of ScanCopy, the following applies: r = 2 (initial value) + 4 × 6 = 24 (c-loop) + 4
2
(r-loop) = 28 (Row 28 in Fig. 4.3 (S)).
124 4 Macros with Visual Basic and Their Correspondences in Python

4.3.1 Macro Recorder

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.

What do We Learn in This Exercise?

 Mag Once you have completed this task, you can create images like the one in
Fig. 4.7a.

 Alac Great, that will amaze my friends!

 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

 Alac So, everything is done by the macro recorder?

 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, …)).

The tab DEVELOPER/RECORD MACRO


We want to apply a VBA macro to draw a series of filled circles. First, we have to
get the elementary commands for drawing a circle. These can be found, in principle,
in manuals for VISUAL BASIC FOR APPLICATIONS. Nevertheless, we make life easier for
us and use the macro recording function. You can find it in the main register tab
DEVELOPER, (see Fig. 4.8). Further explanations can be found in EXCEL help under
the keyword CREATE A MACRO.
If the main tab DEVELOPER does not appear in your ribbon, you must activate it in
the EXCEL options, with FILE/OPTIONS/CUSTOMIZE RIBBON/MAIN TABS/ DEVELOPER.

Circles, Squares, Triangles, by Hand and by Macro


After turning on the macro recording function, we draw a circle by hand
(INSERT/ILLUSTRATIONS/SHAPES) and format it. For example, we select the color of the
filling and the thickness and color of the border. When we have finished the drawing,
we end the macro recording by clicking the STOP RECORDING button, which appears in
the toolbar in place of RECORD MACRO. The recorded macro is in a project MODULE (see
Fig. 4.9 under “Modules”), not in a VBA sheet connected with a spreadsheet.

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.

Select Objects and Edit them Together


You can select objects with the arrow cursor. To do this, click
HOME/FIND AND SELECT/SELECT OBJECTS at the ribbon’s far-right. With the
new mouse pointer held down, you can now span a rectangle within which
all drawing objects are selected and edit this set of objects as a whole, for
example, color them, group them, or delete them.
Within a VBA macro, use the command ACTIVESHEET.DRAWINGOBJECTS.SELECT
to select all drawing objects in the active worksheet. With SELECTION.DELETE, you
can delete all objects.
4.3 Macro-Controlled Drawings with FOR, SUB, IF 127

4.3.2 Visual-Basic Editor 2: Macro Recording, Debugging

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

4.3.3 Programming Elements

Variables Instead of Numbers


In SUB MACRO2 in Fig. 4.10 (P), we have replaced the current numbers in ADDSHAPE
with variables x, y, dx and dy, to which we have assigned values in lines 2 to 5. If
we run this macro, one of the shapes in Fig. 4.11a (S) is created, or a similar one if
other values have been chosen.
The colors in lines 9, 12, 32, and 35 are composed of red, green, and blue com-
ponents (intensity between 0 and 255) via the specification RGB (red, green,
blue).

1 Sub Macro2() Sub Circles() 20


2 x = 400 For i = 1 To 3 21
3 y = 20 Call Disc(i * 50 + 60, i * 25) 22
4 dx = 100 Next i 23
5 dy = 50 End Sub 24
6 ActiveSheet.Shapes.AddShape(msoShapeOval, _ 25
7 x, y, dx, dy).Select Sub Disc(x, y) 26
8 With Selection.ShapeRange.Fill 'x and y are the coordinates of the center 27
9 .ForeColor.RGB = RGB(220, 220, 220) d = 50 'diameter of the circle 28
10 End With ActiveSheet.Shapes.AddShape(msoShapeOval, _ 29
11 With Selection.ShapeRange.Line x - d / 2, y - d / 2, d, d).Select 30
12 .ForeColor.RGB = RGB(180, 0, 0) With Selection.ShapeRange.Fill 31
13 .Weight = 1 .ForeColor.RGB = RGB(220, 220, 220) 32
14 End With End With 33
15 End Sub With Selection.ShapeRange.Line 34
16 .ForeColor.RGB = RGB(180, 0, 0) 35
17 Private Sub CommandButton1_Click() .Weight = 1 36
18 Call Circles End With 37
19 End Sub End Sub 38

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

Which color is created with RGB(180, 0, 0)?8


Which color is created with RGB(220,220,220)?9
How can you tell that a circular disc, and not an elongated ellipse, is
produced with SUB Disc?10

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 circle with diameter 100 points has a diameter of 3.53 cm.


– 28.4 point correspond to 1 cm.
– 28.5; 28.6; 28.7 point all correspond to 1.01 cm.
– 28,8 point correspond to 1.02 cm.

Transferring parameters to sub-routines

 When parameters are passed to sub-routines, the order in the argument


list in the procedure header is decisive; the names in the main program
are not significant.

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

8 RGB(180, 0, 0) is a strong red, intensity 180 of 255.


9 RGB(220,220,220) is a light grey; red, green and blue
are equally present.
10 In lines 29, 30, ACTIVESHEET.SHAPES.ADDSHAPE(…,., d, d), the same variable d is used for both
diagonals of the ellipse.
130 4 Macros with Visual Basic and Their Correspondences in Python

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

concerning Fig. 4.10b (P)


Which three circle centers are passed to SUB Disc(x,y) in SUB Circles?11
Which argument in CELLS(a,b) stands for the row index in the spreadsheet?12

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.

11 (x, y) = (110, 25), (160, 50) and (210, 75).


12 The first argument, a, stands for the row: CELLS(row, columns).
13 SUB DISC(X,Y,D,W), LINE 36, WEIGHT = W.
4.3 Macro-Controlled Drawings with FOR, SUB, IF 131

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!

Command Button, Design Mode On/Off


In Fig. 4.11b, a command button has been inserted in "Design mode" in A5:B6 with
DEVELOPER/INSERT/ACTIVEX CONTROLS/COMMAND BUTTON (visible when the mouse is
over the ▭ icon).

In the PROPERTIES card, revealedby right-hand clicking on


COMMAND BUTTON/PROPERTIES, COMMANDBUTTON1 (as text) is assigned both as
a NAME and a CAPTION for the command button. As is usually the case with
controls, with the DESIGN MODE turned on (click the DESIGN MODE button on the
DEVELOPER tab, see Fig. 4.1 and Fig. 1.1 of Sect. 1.7), the PROPERTIES can be
changed, e.g., name and caption. When the design mode is switched off (by
clicking the DESIGN MODE button again), the control can be operated.
132 4 Macros with Visual Basic and Their Correspondences in Python

The procedure SUB COMMANDBUTTON1_CLICK in Fig. 4.10a (P) is assigned to


the command button. In detail, proceed as follows: In the VISUAL BASIC Edi-
tor (Fig. 4.9), click on the arrow ▿ at (GENERAL). A list opens up in which
SUB COMMANDBUTTON1 appears. This entry is activated by clicking on it. Next,
click on the arrow ▼ next to the cell with the inscription “Annegret” (as shown in
Fig. 4.9, or the name you have chosen). A list opens up in which CLICK appears,
together with other commands. Click on this entry, and SUB COMMANDBUTTON1
is immediately completed to SUB COMMANDBUTTON1_CLICK. The upper line in the
VBA editor will now read COMMANDBUTTON1 ▼; CLICK().
In our case, in Fig. 4.10a (P), only one procedure, SUB Circles, is called. We
could omit SUB COMMANDBUTTON1_CLICK by naming the command button Circles
and completing SUB Circles() to SUB Circles_CLICK(). Please note that we would
have to change the name of the button, which is independent of its caption.

4.4 A Checkerboard Pattern (Excel)

We obtain the VBA commands for drawing elementary geometric shapes


by recording macros and incorporate them into a sub-routine that executes
the drawing in the desired layout. The shapes’ position in the spreadsheet is
passed to the procedure via its header or via global variables. The respec-
tive shapes, as well as the color of their borders and interiors, are selected
randomly.

4.4.1 Checkerboard, Same-Colored and Multi-colored

Checkerboard with same-colored shapes


In this exercise, a checkerboard of rectangles, triangles, and circles, as shown in
Fig. 4.12a, is to be drawn. The procedure for this is shown in Fig. 4.13 (P).

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)

1 Sub drawi1() If ROT = 2 Then Call Tria(x, y) 8


2 x = 100 x = x + 15 9
3 For k = 1 To 8 'next row Next i 10
4 For i = 1 To 10'within row x = 100 'reset left position 11
5 ROT = Int(Rnd() * 3) '0, 1 or 2 y = y + 15 'advance top position 12
6 If ROT = 0 Then Call Rect(x, y) Next k 13
7 If ROT = 1 Then Call Ova(x, y) End Sub 14

Fig. 4.13 (P) Procedure SUB drawi1 with which Fig. 4.12a is drawn

In lines 6 to 8, logical IF queries determine which shape is drawn. After the


shape has been drawn, the x value is increased by 15 (line 9).

 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.

 Task Draw the complete checkerboard pattern!

A randomly more colored checkerboard pattern


We draw 8 rows with 10 shapes each, such as shown in Fig. 4.12b. The format of the
shapes, namely, the color to be filled in and the color and thickness of the border, is
now determined using a random number. In addition, the positions (left, top) of the
shapes are not passed to the sub-routines through the procedure header, but via global
variables. The main procedure can be found in Fig. 4.14 (P), a typical sub-routine in
Fig. 4.15 (P).
134 4 Macros with Visual Basic and Their Correspondences in Python

1 Private x, y As Single If ROT = 0 Then Call Rect 10


2 'Position of the shape to be currently drawn If ROT = 1 Then Call Ova 11
3 If ROT = 2 Then Call Tria 12
4 Sub drawi() Next i 13
5 x = 100 'left position x = 100 'reset left position 14
6 y = 100 'top position y = y + 15 'advance top position 15
7 For k = 1 To 8 'next row Next k 16
8 For i = 1 To 10 'within row End Sub 17
9 ROT = Int(Rnd() * 3) '0, 1 or 2 18

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

1 Sub Rect() ' Draws a rectangle of width 10 and height 10 1


2 ActiveSheet.Shapes.AddShape(msoShapeRectangle, x, y, 10, 10).Select 2
3 Call Lin(255 * Rnd(), 63 * Rnd(), 63 * Rnd(), 10) 'Rim of shape 3
4 'Formats rim: Red fully varied, green and blus, half intensity, strength 4
5 Call Interi(63 * Rnd(), 128 + 127 * Rnd(), 63 * Rnd()) 'Interior of shape 5
6 'Formats interior: Green always more intense than 50% 6
7 x = x + 15 'Advances position in the row 7
8 End Sub 8

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)

4.4.2 Global Variables

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

1 Sub Lin(r, g, b, w) Sub Interi(r, g, b) 8


2 red, green, blue and weight w 'red, green, blue 9
3 With Selection.ShapeRange.Line With Selection.ShapeRange.Fill 10
4 .ForeColor.RGB = RGB(r, g, b) .ForeColor.RGB = RGB(r, g, b) 11
5 .Weight = w End With 12
6 End With End Sub 13
7 End Sub 14

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

concerning Fig. 4.15 (P):


The procedure header of SUB Rect is empty. How does the sub-routine know
the position in the spreadsheet where the rectangle is to be drawn?14
Which color dominates the border of the shapes?15

4.5 A Checkerboard Pattern (Python)

We draw a multi-colored checkerboard pattern using the Python library


turtle, setting up a similar program structure as for EXCEL in Sect. 4.4, but
considering the differences in code from Visual Basic.

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

14 SUB Rect accesses the global variables x, y.


15 Line 5 in Fig. 4.15 (P): Green = 128 + 127*RND() is represented at least with strength 128.
136 4 Macros with Visual Basic and Their Correspondences in Python

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.

Different types of triangle


The centroid (x C , yC ) of a triangle, corresponding to its center of gravity, is calculated
as
x1 + x2 + x3 y1 + y2 + y3
xC = , yC =
3 3
It is marked in Fig. 4.17b with dots.
The function drawTria, used to draw Fig. 4.17a, draws an equilateral triangle
(bottom left in Fig. 4.17b) whose centroid does not coincide with the square’s center,
4.5 A Checkerboard Pattern (Python) 137

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.

Basic functions and measurements


The basic functions (always completed with parentheses ()), attributed to the instance
of a turtle, e.g., t.penup() or t.pos(), are.
Settings:

.pen( … ) specifying speed, pensize, pencolor, fillcolor


.pu() pen up
.pd() pen down
.setpos(x,y) moving to the specified position
.setheading(φ) setting the orientation as angle φ in ° with respect to the
x-axis
.rt(φ) right turn by angle φ in °
.lt(φ) left turn by angle φ in °
.fd(r) step forward by r pixels
.bk(r) step backward by r pixels
.dot(s,c) plots a dot with diameter s and color c at current position
.begin_fill() beginning to fill in the contour
.end_fill() ending to fill in the contour

Measurements:

.pos() returns Cartesian coordinates of turtle


.heading() returns angle of direction
.distance(x,y) returns distance to point (x, y)

Question

How do you get the position of a turtle named doro in polar coordinates? There
are two possibilities.16

4.5.2 Differences to Visual Basic

We will demonstrate some syntactic differences between Python and


VISUAL BASIC by means of the function drawSquare, which creates a square shape.

16r = doro.distance(0,0), phi = doro.heading()/180*np.pi() or x


= doro.pos(0), y = doro.pos(1), r = np.sqrt(x**2 + y**2), phi =
np.arctan2(y,x)
138 4 Macros with Visual Basic and Their Correspondences in Python

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)

In Table 4.2, it is implemented in Python with four segments of equal length


and a 90° turn after each segment; the features of the pen have been specified
in a superordinate program. In Fig. 4.18 (P), this is realized in a Visual Basic
sub-routine that is called from the main program SUB DSQ().

Positional and keyword arguments


The procedure headers in both cases, Python and VBA, contain positional arguments
x, y, sz, and a keyword argument fill that decides whether or not the contour is
filled (with the default set to False).
The first three positions in the header must contain appropriate values when the
function is called. It is the position in the header that determines the variable in the
procedure to which the value is assigned. In Fig. 4.18 (P), a variable y with value
40 is passed through the third position to the procedure, where it is assigned to a
variable named sz.
The keyword argument fill is defined in the procedure header with a default value
taken in the procedure, if not specified otherwise.

1 Dim col(2) As Integer Sub drawSquare(x, y, sz, _ 13


2 Optional fill As Boolean = False) 14
3 Sub dSq() ActiveSheet.Shapes.AddShape( _ 15
4 col(0) = 100 msoShapeRectangle, x, y, sz, sz).Select 16
5 col(1) = 200 Selection.ShapeRange.fill.Visible = msoFalse 17
6 col(2) = 0 If fill = True Then 18
7 y = 40 With Selection.ShapeRange.fill 19
8 For a = 100 To 200 Step 50 .Visible = msoTrue 20
9 Call drawSquare(a, 100, y, fill:=True) .ForeColor.rgb = rgb(col(0), col(1), col(2)) 21
10 Next a End With 22
11 Call drawSquare(100, 100, y, fill:=True) End If 23
12 End Sub End Sub 24

Fig. 4.18 (P) DrawSquare realized in visual basic for EXCEL


4.5 A Checkerboard Pattern (Python) 139

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.

Grouping blocks of code


In Python, indentation has a syntactic function. A block of code is necessar-
ily grouped by the same amount of indentation. In Table 4.2, there are two examples:
the statements of the function are all indented by 4 spaces; the two statements to be
executed in the for-loop are further indented by another 4 spaces.
EXCEL uses code words to state the end of a block. In Fig. 4.18 (P), the procedure
(sub-routine) ends with END SUB, the IF block with END IF, and the WITH block with
END WITH. The (FOR A = ) block in the main program ends with NEXT A. Although
indentation does not have a syntactic function in Visual Basic, we use it to maintain
a better overview of the program structure.

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.

4.5.3 Checkerboard with Squares, Triangles, and Circles

User-defined functions for square, triangle, circle, dash


To draw a checkerboard pattern as in Fig. 4.17a, we need functions that draw, besides
the rectangle already realized in Table 4.2, a triangle and a circle. They should have
the same procedure header as drawSquare, with the center point (x,y) and the size
sz as positional arguments and fill as a keyword argument.
Drawing a triangle in Table 4.3 is similar to how it is done in drawSquare. Drawing
a circle with radius r is achieved with the built-in function circle(r) (see Table
4.4). There, the turtle runs along a circle of radius r, starting at its current position
and with its current direction.

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

Table 4.3 Drawing a triangle with center (x, y)


13 def drawTria(x,y,sz,fill=False):
14 r=sz/2
15 t.pu()
16 t.setpos(x-r,y-r) #Left lower edge
17 t.pd()
18 if fill==True: t.begin_fill()
19 for i in range(3):
20 t.fd(sz) #Forward!
21 t.lt(120) #Turn left!
22 if fill==True: t.end_fill()
23 t.pu()
24 t.setpos(x,y)

Table 4.4 Drawing a circle with center (x, y)


25 def drawCircle(x,y,sz,fill=False):
26 r=sz/2
27 t.penup()
28 t.setpos(x,y-r)
29 t.pendown()
30 if fill==True: t.begin_fill()
31 t.circle(r) #Is a function within turtle
32 if fill==True: t.end_fill()
33 t.penup()
34 t.setpos(x,y)

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.5 Drawing a dash


35 def dash(ds):
36 t.rt(90) #Right turn
37 t.fd(ds)
38 t.rt(180) #180° to the right
39 t.fd(2*ds)
40 t.rt(180)
41 t.fd(ds) #Back to zero
42 t.lt(90) #90° to the left, original direction

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

Table 4.7 Drawing a frame with dashes around the checkerboard


21 #Draw frame with dashes
22 t.pen(pencolor="black", pensize=1, speed=10)
23 t.penup()
24 t.setpos(-400,-400) #Left bottom corner
25 t.pendown()
26 for k in range(4): #4 straight lines
27 for i in range(10): #10 segments with dashes
28 dash(6)
29 t.fd(80) #Forward!
30 dash(6)
31 t.lt(90) #Left turn 90°!
32 #turtle.update()

Table 4.8 Drawing the axes of the coordinate system


33 #Axes of the coordinate system
34 t.pu(), t.setpos(-400,0), t.pd()
35 t.fd(800) #Forward!
36 t.pu(), t.setpos(0,-400), t.pd()
37 t.setheading(90) #Direction 90° to x axis
38 t.fd(800)
39 #turtle.update()

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.

Frame around the figure in Turtle


The main program is continued in Tables 4.7 and 4.8, through drawing of a frame
around the checkerboard and the axes of the coordinate system, respectively.

Questions

What type of triangle is specified in drawTria, Table 4.3: equilateral, or acute-


angled?19
How do you draw a triangle touching a square at two neighboring corners
and the center of the opposite side (see Fig. 4.17b, bottom right)?20

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,

y-sz/2), (0, y + sz/2), back to (x-sz/2,y-sz/2)!


4.5 A Checkerboard Pattern (Python) 143

What is the direction of the turtle after having been guided by the code
snippet in Table 4.7?21

How do we speed up Python’s turtle function?


The answer is found with an internet search (2020):
https://stackoverflow.com/questions/16119991/how-to-speed-up-pythons-turtle-
function-and-stop-it-freezing-at-the-end
with the answers:

– (1) Set turtle.speed() to fastest.


– (2) Use the turtle.mainloop() functionality to do work without screen
refreshes.
– (3) Disable screen refreshing with turtle.tracer(0, 0), then, at the end,
do turtle.update()

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).

4.6 Drawing Densely-Packed Atomic Layers; Crystal Physics

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.

4.6.1 Program Structure and Geometry

In this task, a top view of a close-packed plane of atoms is to be drawn with a


program based on a nested For-loop. The subordinate loop draws a horizontal row
of discs, representing the atoms, touching each other. This is achieved by shifting
a new disk to the right by the diameter d relative to the previous disc. In a higher-
level loop, the rows are to be shifted one after the other in the plane so that the
circular disks touch each other in a hexagonal arrangement, as shown in Fig. 4.19.
In a second development step, the main program resulting from the first step is
to be converted into a procedure that draws a plane and to which the coordinates

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

How many neighbors does a sphere in a close-packed plane have?22

22 Six nearest neighbours.


4.6 Drawing Densely-Packed Atomic Layers; Crystal Physics 145

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

How many neighbors does a sphere in a stack of close-packed planes have?23

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.

Three stacked planes


The first row of circular disks starts at (x 0 , y0 ). The second row is offset from the first
row in the x- and y-directions by distances indicated in the geometric construction in
Fig. 4.21a. A second plane is to be placed over the first one, with the circular disks
lying over the gaps in the first plane (see Fig. 4.21b), resulting in the assembly of
light grey discs in Fig. 4.20.

For the third plane, there are two possibilities:

– 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.

23 12 nearest neighbours, 6 of them in its own plane, 3 below and 3 above.


146 4 Macros with Visual Basic and Their Correspondences in Python

4.6.2 Data Structure and Nomenclature

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)

x = x 0 + delX + dx + i·d position of disc i.

dx = delX + 0 1st and 3rd rows (see Fig. 4.21a)


= delX + d/2 2nd and 4th rows (see Fig. 4.21a)
y = y0 + dy y position of disc i (see Fig. 4.21a)
dy = delY + d 34 ·n nth row (see Fig. 4.21a and Eq. 4.1)

with:

d34 = d · 3/4 (4.1)

read from Fig. 4.21a.

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)

1 Sub Plane(delX, delY) 15


2 x0 = 100 'Offset to left upper corner dx = 0 + delx 16
3 y0 = 100 'of the worksheet dy = d * Sqr(3 / 4) * 2 + dely 17
4 d = 100 'Diameter of the disc For i = 0 To 7 18
5 dx = delx Call Disc(x0 + dx + i * d, y0 + dy) 19
6 dy = dely Next i 20
7 For i = 0 To 7 dx = d / 2 + delx 21
8 Call Disc(x0 + dx + i * d, y0 + dy) dy = d * Sqr(3 / 4) * 3 + dely 22
9 Next i For i = 0 To 6 23
10 dx = d / 2 + delx Call Disc(x0 + dx + i * d, y0 + dy) 24
11 dy = d * Sqr(3 / 4) + dely Next i 25
12 For i = 0 To 6 End Sub 26
13 Call Disc(x0 + dx + i * d, y0 + dy) 27
14 Next i 28

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

Grouping and copying shapes in various picture formats


To group the shapes into an integrated picture, activate the white arrow
SELECT OBJECTS in the FIND&SELECT tab (far right in the HOME tab of the EXCEL rib-
bon, Fig. 1.1 in Sect. 1.7), drag the selection rectangle around the shapes, then click
FORMAT/GROUP. You can now copy the group as one graphic into other applications,
e.g., into a Word file or a PowerPoint file.

 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:

– Line 1, link for an introduction into the basic features of turtle,


– Line 5, the screen is cleared. This is important when developing a program,
and you have to improve the code and repeat it again and again until it runs
error-free.

24No, Visual Basic is case-insensitive, contrary to Python.


25Skip line 28 “d = 50”, insert dim d AS INTEGER as the first program line, and specify d = …
somewhere in the program before SUB Disc is called for the first time.
4.6 Drawing Densely-Packed Atomic Layers; Crystal Physics 149

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

Table 4.11 Plotting the first and second planes


22 Plane(0,0)
23 delX=50/2
24 delY=-50/2*np.tan(30/180*np.pi)
25 Plane(delX,delY)

Questions

concerning Table 4.9


What is the position of the turtle after having drawn the first row?26
What are the pen color and fill color of the turtle?27
What is the global parameter accessed in drawCircle?28

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

In line 29 of Table 4.12, dx = 50*1 is specified; the number 50 is precisely


the disc diameter. Nevertheless, what is bad about this instruction, and likewise
about the instructions in lines 36 and 37, and lines 23 and 24 in Table 4.11?29

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 =

d*1 in lines 47, 48, 53, 60, 61 instead!


4.7 Text Processing 151

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)

4.7 Text Processing

Operations on strings (texts) are practiced by the example of swapping letters


within words. We will use the functions Len, Split, Join in both Visual Basic
and Python. The functions LEFT, RIGHT, and MID are used in VISUAL BASIC to
cut out pieces of strings, achieved in Python through list slicing.

4.7.1 Cutting and Joining Strings

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.

We are going to write a program that exchanges letters in an originally correctly


written text. Such a program has already swirled the first two paragraphs of this
description. The number of letter swappings in the above text: 1 (Text), 2 (Task).
152 4 Macros with Visual Basic and Their Correspondences in Python

Plain text of the first two paragraphs

 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.

VBA instructions for text processing


We need the following VBA instructions that affect character strings:
LEN(…), SPLIT(…), JOIN(…) , LEFT(…), RIGHT(.) and MID(…).
An overview is given in the box. For more information, refer to VBA help! There,
you can find out, for example, about the MID function:
Returns a Variant (String) containing a specified number of characters from a string.

 Syntax MID (STRING, START [, LENGTH]).

STRING Required. String expression from which characters are returned.


START Required; Long. Character position in STRING at which the part to be
taken begins.
LENGTH Optional; Variant (Long). Number of characters to return.

Text processing in VBA and Python


VISUAL BASIC Python
SPLIT(STRING, [SEPARATOR…) String.split(“separator”)

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)

Determines the length of a given string.

LEFT(STRING, LENGTH) String[:Length]

Cuts out a piece of length Length from a character string starting from the
left.

RIGHT(STRING, LENGTH) String[-Length:]


4.7 Text Processing 153

Cuts out a piece of length Length from a character string starting from the
right.

MID(STRING, START, LENGTH) String[Start: Stop]

Cuts out a piece of length LENGTH or (Stop – Start) from a charac-


ter string starting from position START and to the right of it. Attention:
VISUAL BASIC starts indexing from 1, Python from 0.

JOIN(ARRAY[, DELIMITER) ‘Delimiter’.join(Array)

Returns a string created by joining several substrings contained in an array.


If ‘Delimiter’ is omitted, the space character (“ ”) is used.

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!

4.7.2 Data Structure and Program Flow

Text text to be processed, words separated by spaces


Words list of the words in Text

For every Word in Words:

Exchange two letters with function ExchLett(Word)


Split Word → Letters list of letters in Word
Join Letters → NewWord
Join sequence of NewWord → NewSentence

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.

1 Sub Scramble() Call XWord(Words(lS)) 'Letters are exchanged 7


2 Text = Cells(1, 1) 'Call XWord(Words(lS)) '... a second time 8
3 Words = Split(Text) Next lS 9
4 For lS = 0 To UBound(Words) newText = Join(Words, " ") 10
5 'Cells(lS + 1, 2) = Words(lS) Cells(7, 1) = newText 11
6 'activate for Scramble_test End Sub 12

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

13 Sub XWord(Word) 'Random positions 2 to lWord-1 25


14 Dim Letter(20) As String L0 = Letter(n1) 26
15 Debug.Print (Word) Letter(n1) = Letter(n2) 27
16 lWord = Len(Word) '#Letters in the word Letter(n2) = L0 28
17 If lWord >= 4 Then 29
18 For n = 1 To lWord For n = 1 To lWord 30
19 'Letters are singled out. Word = Join(Letter, "") 31
20 Letter(n) = Mid(Word, n, 1) 'Cells(n, 4) = Letter(n) 32
21 'Cells(n, 3) = Letter(n) 'Output to spreadsheet in Xword_test 33
22 Next n Next n 34
23 n1 = Int(Rnd() * (lWord - 2)) + 2 End If 35
24 n2 = Int(Rnd() * (lWord - 2)) + 2 End Sub 36

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.

VBA terms and user-defined variable names


In the procedures Scramble and XWord, there are terms that VBA assigns a precisely
defined meaning to:

– 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().

Such terms are printed in the text in SMALL CAPS.


There are also eleven variable names, which the programmer has invented
himself/herself:

– Text, Words, lSent, newText, lWord, Letter, n1 , n2 , L 0 , x, n.

He might as well have taken eleven letters:

– a, b, c, d, e, f, g, h, i, j, k,

or eleven combinations of letters and numbers:

– a1, a2, a3, a4, b5, b6, b7, b8, × 1, × 2, × 3.


156 4 Macros with Visual Basic and Their Correspondences in Python

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

4.7.4 Programming Step by Step

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

34 Text = RANGE(“A1”); RANGE(“A7”) = newText.


35 Text, Words, lS, newText.
36 Word, Letter, lWord, n, n , n , L
1 2 0.
37 No, n and n can be identical, so that there is no effective exchange.
1 2
4.7 Text Processing 157

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

concerning Fig. 4.26 (P):


Which program lines guarantee that the first and last letter of a word are not
displaced? From which range of the spreadsheet is the text to be processed read?
Into which ranges of the spreadsheet are the individual words of the text, the
individual letters of a word, the swirled letters, and the modified text written?38

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!

4.7.5 VBA Constructs

The data type Array in VBA


Arrays are declared in VBA as follows:

DIM Variable name(shape) AS data type

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

Table 4.13 Basic functions for text processing


1 Text="""A sentence is decomposed."""
2 Words=Text.split()
3 Letters=list(Words[1])
4 L=Letters[4]
5 NewWord=':'.join(Letters[1:-1]) #Concatenate with “:”

6 print(Words) ['A', 'sentence', 'is', 'decomposed.']


7 print(Letters) ['s', 'e', 'n', 't', 'e', 'n', 'c', 'e']
8 print(L) e
9 print(NewWord) e:n:t:e:n:c

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?

Table 4.15 Swapping internal letters


19 #https://stackoverflow.com/questions/9755538/
20 #how-do-i-create-a-list-of-random-numbers-without-
duplicates
21
22 import random
23 random.sample(range(0,10), 10)
[7, 2, 5, 9, 0, 6, 3, 4, 8, 1]
24 def ExchLett(Word):
25 #Split a word into letters
26 Letters=list(Word)
27 #Exchange two internal letters of a word
28 if len(Letters)>=4:
29 n=random.sample(range(1,len(Letters)-1), 2)
30 L0=Letters[n[0]]
31 Letters[n[0]]=Letters[n[1]]
32 Letters[n[1]]=L0 #Join letters into a word!
33 return ''.join(Letters)
34 Letters[n[0]],Letters[n[1]=\
Letters[n[1]],Letters[n[0]]
160 4 Macros with Visual Basic and Their Correspondences in Python

Table 4.16 Scrambling a text passage


1
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 their place, but the inner
letters are randomly swapped."""
2 Words=Task.split()
3 WordsNew=[]
4 for i in range(len(Words)):
5 WN= ExchLett(Words[i])
6 WordsNew.append(WN)
7 sentNew=' '.join(WordsNew)
8 print(sentNew)
Wrtie a porgram taht frist rdaes a txet form a sprdaesheet.
Tihs txet is tehn to be broekn dwon itno worsd. The indaviduil
wodrs are transofrmed so taht the fisrt and lsat lettres
remian in thier palce, but the inner lettres are rdnaomly
seappwd.

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.

4.8 Processing the Protocol of a Measuring Device

Continuous text is decomposed and rearranged in tables. Knowledge


acquired by processing texts in the previous exercise is applied to separate
text and numbers in reports created by measuring instruments, with the aim
to recognize code words and rearrange the essential results in tables.—The
Python program is based on the library Pandas.—A piece of advice: With

40 Letters[n[0]], Letters[n[1]] = Letters[n[1]], Letters[n[0]].


41 WN = EXCHLETT(EXCHLETT(WORDS[I]).
42 Introduce WN = ExchLett(WN) after line 5!
4.8 Processing the Protocol of a Measuring Device 161

the knowledge gained in this exercise, you may earn a small bit of extra
income from a side job in scientific projects!

4.8.1 Protocol of a Measuring Device

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

36 For r = 3 To r2 cll = Left(cl, 2) 'take first two letters 39


37 cl = Cells(r, sample) 'e.g.: d=0.20E18 If cll = "d=" Then NAtoms = Right(cl, Le - 2) 40
38 Le = Len(cl) 'length of the string Next r 47

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 =”

1 Sub DecodeRBS() For sample = 1 To 4 15


2 'Original data in sheet "RBS-data" Sheets("RBS-data").Select 'original data 16
3 'Table with sample characteristics in "TabLay" 'Get sample name! 17
4 Dim cl, cll As String SampNam = Cells(1, sample) 'sample name 18
5 'Write headers! Le = Len(SampNam) 'length of the name 19
6 r3 = 2 SampNam = Left(SampNam, Le - 4) 20
7 Sheets("TabLay").Select ' ".lay" is removed 21
8 Cells(r3, 1) = "SampNam" 'Identify range with information on sample! 22
9 Cells(r3, 2) = "NAtoms" For r1 = 3 To 30 'scans rows 3 to 30 23
10 Cells(r3, 3) = "Ti" cl = Cells(r1, sample) 'Content of cell 24
11 Cells(r3, 4) = "O" cll = Left(cl, 5) 25
12 Cells(r3, 5) = "Nb" If cll = "!----" Then r2 = r1 - 1 26
13 Cells(r3, 6) = "Ar" 'r2 = last row of information on the sample 27
14 r3 = r3 + 1 ' next free row for output Next r1 28

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)

4.8.2 Detection of Code Words

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.3 Data Structure and Nomenclature

wb name in Pandas of the workbook containing the data


sh name in Pandas of the worksheet within the workbook
T1, T2, T3, T4 identifiers of samples
4.8 Processing the Protocol of a Measuring Device 163

„!----“ code word to indicate the end of useful information


“d=” two-character code word for atomic coverage, atoms per
cm2
“O#,” three-character code word for oxygen
“Ti#,”, “Nb#,”, “Ar#,” four-character code words for titanium, niobium, and
argon
r2 last row of useful information
r3 current row in the spreadsheet for output
NAtoms number of atoms per cm2
O, Ti, Nb, Ar fraction of the respective element

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

29 'Remove old information! If cll = "Ti#," Then Ti = Right(cl, Le - 4) 44


30 NAtoms = Empty If cll = "Nb#," Then Nb = Right(cl, Le - 4) 45
31 O = Empty If cll = "Ar#," Then Ar = Right(cl, Le - 4) 46
32 Ti = Empty Next r 47
33 Nb = Empty 'Write decoded data into a different sheet! 48
34 Ar = Empty Sheets("TabLay").Select 49
35 'Decode information in rows 3 to r2! Cells(r3, 1) = SampNam 50
36 For r = 3 To r2 Cells(r3, 2) = NAtoms 51
37 cl = Cells(r, sample) 'e.g.: d=0.20E18 Cells(r3, 3) = Ti 52
38 Le = Len(cl) 'length of the string Cells(r3, 4) = O 53
39 cll = Left(cl, 2) 'take first two letters Cells(r3, 5) = Nb 54
40 If cll = "d=" Then NAtoms = Right(cl, Le - 2) Cells(r3, 6) = Ar 55
41 cll = Left(cl, 3) 'take first three letters r3 = r3 + 1 'next free row 56
42 If cll = "O#," Then O = Right(cl, Le - 3) Next sample 57
43 cll = Left(cl, 4) 'take first four letters End Sub 58

Fig. 4.32 (P) Continuation of Fig. 4.31 (P)


164 4 Macros with Visual Basic and Their Correspondences in Python

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

Which code word is queried in Fig. 4.30 (P)?43


Which code words in Fig. 4.32 (P) have length 4?44

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) = .

VBA keyword empty


In lines 36 to 47 of Fig. 4.32 (P), the variables O, Ti, Nb and Ar are only filled in if the
assigned code words occur in the original protocol. If a code word does not occur in
the current data line, the content of the associated variable is not overwritten, and the
old value persists. To prevent this from happening, we have entered the assignments
in lines 30 to 34, e.g., Nb = EMPTY. EMPTY is a VBA keyword, to ensure that the
variables do not contain any value when a new sample is processed.
Sample T4 does not contain any Nb; cell E6 in Fig. 4.29 (S) thus remains
empty. If we had not set Nb = EMPTY before decoding, then Nb would still contain
the value 0.07 of the previous sample and would have been incorrectly entered into
the table of results. This would be a grave error in content!

The table is continued the next time the macro is called

 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.

For more information on the instructions DO … LOOP, DO WHILE … LOOP, and


DO … LOOP UNTIl, see EXCEL help!

4.8.5 Python

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
mimicking spreadsheet calculations. We use it only in this exercise to read data
from an EXCEL book, decode the measurement protocol, and write the results into
an EXCEL sheet, in the same form as in Fig. 4.29 (S).

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:

wb = openpyxl.load_workbook( RBS_data.xlsx , 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

What are the values of sh[1][0].value and


list(sh[1][0].value)[0]?45
Line 5 of Table 4.19 contains a bug. Which one?46

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.

Output from Pandas to an Excel file


Writing our results into an EXCEL file requires some care. The simple statement
in Table 4.22a creates a new file RBS data3.xlsx and writes our frame out into a
sheet with the name Sheet3. If a file with said name already exists, it is overwritten.
The keyword arguments header = False, index = False cause row 1 and
column 1 of Table 4.21 (bottom cell) not to be output.

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).

45 sh[1][0].value -> T1.lay, list(sh[1][0].value)[0] -> T.


46 Indentation with respect to the if line is only 3 spaces; it must be 4 spaces.
168 4 Macros with Visual Basic and Their Correspondences in Python

Table 4.20 Function for decoding a string


1 def decode(c,r2): #Column c, row r2
2 nAtoms=None
3 O=None
4 Ti=None
5 Nb=None
6 Ar=None
7 #Decode information in rows 3 to r2!
8 #First index in array starts with 0
9 for r in range(2,r2+1):
10 cl=sh[r][c] #Cell address
11 if cl.value!=None: # != means “not equal”
12 cll=''.join(list(cl.value)[:2])
13 if cll=='d=':
14 nAtoms=''.join(list(cl.value)[2:])
15 cll=''.join(list(cl.value)[:3])
16 if cll=='O#,': O =''.join(list(cl.value)[3:])
17 cll=''.join(list(cl.value)[:4])
18 if cll=='Ti#,': Ti=''.join(list(cl.value)[4:])
19 if cll=='Nb#,': Nb=''.join(list(cl.value)[4:])
20 if cll=='Ar#,': Ar=''.join(list(cl.value)[4:])
21 nAtoms=float(nAtoms)
22 return(nAtoms,Ti,O,Nb,Ar)

4.9 User-Defined Functions

We code functions in VISUAL BASIC that can be applied in spreadsheets just


like built-in functions. As examples, we realize the vector operations scalar
product and cross-product with three-component vectors as arguments and
with, respectively, a scalar and a vector as the return variable.

4.9.1 User-Defined Functions as Add-In

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).

4.9.2 Scalar Product and Vector Product

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 = (x1 , y1 , z 1 ) and r 2 = (x2 , y2 , z 2 )

Their scalar product is defined as.

r 1 · r 2 = x1 · x2 + y1 · y2 + z 1 · z 2 (4.2)

Their vector product (or cross product) is defined as.

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

1 Function Scl(r1 As Range, r2 As Range) Function Crsm(r1 As Range, r2 As Range) 12


2 Scl = r1(1) * r2(1) + r1(2) * r2(2) + r1(3) * r2(3) Dim cs(2, 2) 13
3 End Function cs(0, 0) = r1(2) * r2(3) - r1(3) * r2(2) 14
4 cs(1, 0) = r1(3) * r2(1) - r1(1) * r2(3) 15
5 Function Crs(r1 As Range, r2 As Range) cs(2, 0) = r1(1) * r2(2) - r1(2) * r2(1) 16
6 Dim cs(2) cs(0, 1) = cs(1, 0) 17
7 cs(0) = r1(2) * r2(3) - r1(3) * r2(2) cs(0, 2) = cs(2, 0) 18
8 cs(1) = r1(3) * r2(1) - r1(1) * r2(3) Crsm = cs 19
9 cs(2) = r1(1) * r2(2) - r1(2) * r2(1) End Function 20
10 Crs = cs 21
11 End Function 22

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

Why is cs(2,2) in FUNCTION Crsm sufficient as an array for a 3 x 3 matrix?49

49 DIM cs(2,2) is a (0, 1, 2) x (0, 1, 2)-Matrix. The indices begin at 0.


4.9 User-Defined Functions 173

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]

Table 4.24 Scalar product, line 8 deactivated


5 def Scl(r1,r2):
6 o=r1[0]*r2[0]+r1[1]*r2[1]+r1[2]*r2[2]
7 out=o
8 #if type(o) == np.ndarray: out = o[0]
9 return out
Scl(a,b) [12]
Scl(c,d) 12
Scl(a,d) [12]

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.

Vector product or cross product


A function Crsm for calculating the cross-product of two three-dimensional vectors
is reported in Table 4.25.

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

Table 4.26 Cross-product of row and column vectors


1 a=np.array([[3,2,2.5]]).transpose(1,0)
2 b=np.array([[-2,8,5]]).transpose(1,0)
3 c=np.array([3,2,2.5])
4 d=np.array([-2,8,5])
Crsm(c,b,True)
Crsm(a,b) [-2.00 4.00 -2.00] [[-2.00]
[ 4.00]
Crsm(c,d) [-2.00 4.00 -2.00] [-2.00]]

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).

4.10 Questions and Tasks

Densely packed planes

1. How many neighbors does a sphere have in a closely-packed plane?


2. How many neighbors does a sphere have in a stack of closely-packed planes?

Program-controlled drawings

3. Write a macro that writes the numbers 1 to 20 in a diagonal of a table, e.g., in


cells A1, B2, etc.
4. What does the broom rule  Empty lines separate curves mean?

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

Fig. 4.37 (S) Diagram of the data in columns A and B

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

8 Sub Macro2() .ForeColor.ObjectThemeColor _ 13


9 ActiveChart.FullSeriesCollection(1).Select = msoThemeColorText1 14
10 Selection.MarkerStyle = 2 .Weight = 1.25 15
11 Selection.MarkerSize = 7 End With 16
12 With Selection.Format.Line End Sub 17

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

18 Sub Macro3() ActiveChart.Axes(xlValue).Select 25


19 ActiveSheet.ChartObjects("Chart 1").Activate With Selection.Format.Line 26
20 ActiveChart.Axes(xlCategory).Select .ForeColor.ObjectThemeColor \ 27
21 With Selection.Format.Line '= msoThemeColorBackground1 28
22 .ForeColor.ObjectThemeColor \ .ForeColor.Brightness = -0.5 29
23 '= msoThemeColorText1 End With 30
24 .Weight = 1# End Sub 31

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.

Text processing in VISUAL BASIC and Python


The following three questions refer to both Visual Basic for EXCEL and Python.
The variable Tx contains the text “We are cutting.”

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)?

 Loop2i; continue counting in the loop!

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

Fig. 4.41 (S) Coordinates for straight-line segments in the xy plane

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

Fig. 4.44 a (left, S) Polynomial y = a1 (x − b1 )2 + c1 in columns A and B; coordinates x s , ys for


the vertical lines of Fig. b in columns D and E. b (right) Display of the data from a
4.10 Questions and Tasks 179

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

User-defined spreadsheet functions


In Fig. 4.45a, the results of two user-defined spreadsheet functions are displayed.
One function adds additional points, “G, 3.P”, onto a straight line “G, 2P” defined
by two points. The other function mirrors points in the first quadrant at (0, 0) into
the third quadrant. The coordinates of the points in Fig. 4.45a are calculated in the
spreadsheet of Fig. 4.45b (S).

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

With the methods learned in Chaps. 2–4 (list processing, programming


constructs for, if, sub/def), we practice differentiation, integration, and cal-
culating with vectors. We get to know a new technique: solving systems of
linear equations with matrix calculation.

5.1 Introduction: Calculus, Vectors, and Linear Algebra

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.

Differentiation and integration


We get to know simple techniques with which the first and second derivatives of a
function can be obtained (Exercise 5.3) and with which a function can be integrated.
With integration, the area between the curve of a function and the x-axis (Sect. 5.4.1)
and the length of a curve (Sect. 5.4.2) can be calculated. We pay special attention to
the x-value over which the results must be plotted: at the beginning, in the middle,
or at the end of the interval for which the elementary calculation was done.

© Springer Nature Switzerland AG 2022 181


D. Mergel, Physics with Excel and Python,
https://doi.org/10.1007/978-3-030-82325-2_5
182 5 Basic Mathematical Techniques

Vectors in the plane


We discuss the addition and the scalar product of two vectors and convert planar
Cartesian and planar polar coordinates one into the other (Exercise 5.5). In Exercise
5.6, the tangents to and the perpendiculars on a polynomial are drawn. As a physically
relevant example, we calculate the forces acting on a car running through a banked
curve (Exercise 5.7). In Exercise 5.8, we calculate a mobile’s equilibrium by using
the mathematical construction of a weighted average.

Systems of linear equations


Systems of linear equations (with small rank) are solved by bringing them into matrix
form and forming the inverse matrix of the coefficient matrix (Exercise 5.9). With
this method, we get the coefficients of a polynomial from a given set of points on
the curve and determine currents in electrical networks with Kirchhoff’s rules. In
Python, we also use functions from the numpy.linalg library for these tasks.

Mathematical functions
In Sect. 5.10, some useful mathematical functions are listed, both in excel and
numpy notation, together with short descriptions.

5.2 Straight-Line Segment Under a Magnifying Glass

A straight-line segment is specified by its two endpoints. Its center, line


vector, and perpendicular vector are obtained with vector operations. The
basic pieces of calculus, dx, dy, dA (the area under the curve), are calculated.

5.2.1 Under a Magnifying Glass

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.

5.2.2 Data Structure and Nomenclature

A, B the two endpoints of a straight segment in the plane


x A , yA coordinates of point A
x B , yB coordinates of point B
dx = (x B – x A ) their distance in the x-direction
dy= (y B – yA ) their distance in the y-direction
ds = dx 2 + dy 2 length of the segment
m slope dy/dx
y = yA + m · (x − xA ) function describing the line through the segment
A = (yA + yB )/2 · dx area between the segment and the x-axis
A = (x A , yA ) vector representation of point A
B = (x B , yB ) vector representation of point B
AB C = (A + B)/2 center of the segment
AB =(B - A)/ds
 unit line vector
0 −1
P= 90°- rotation matrix.
1 0
AB_ p_ = P · AB unit vector perpendicular to the segment.
184 5 Basic Mathematical Techniques

5.2.3 Spreadsheet Calculation

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

y = yA + m·(x − x A ) of the line along the segment. The value of x is determined


with a slider so that the cross in Fig. 5.1 runs along this line.

5.2.4 Plotting Vectors with Python Matplotlib

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:

width float (default: 0.001) width of full arrow tail


fill bool
linestyle or ls {’-’, ’–’, ’-.’, ’:’, ”, (offset, on–off-seq), …}
linewidth or lw float or None
head_length float or None (default: 1.5 * head_width) length of
arrow head
overhang float (default: 0, triangular) fraction that the arrow is swept
back

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

We learn how to approximate the first and second derivatives of a function


f(x) numerically with difference quotients between neighboring calculation

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

Fig. 5.4 Arrows plotted with


different constructor
arguments in the procedure
head of plt.arrow

points. The first derivative must be plotted over the middle between two grid
points, the second derivative over the central of three grid points.

5.3.1 First and Second Derivative

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

d f (x) f (x + x) − f (x)


= lim (5.2)
dx x→0 x

More specifically, Eq. 5.2 is called the right derivative.


Such an approach to the limit cannot be carried out for discrete functions; they
are specified as a list of x-values (x = […x i …]) and y-values (y = […yi …]).
Instead, we calculate the difference quotient of neighboring grid points i and i +
1:
 
d f xi +x2 i+1 f (xi+1 ) − f (xi ) yi+1 − yi
≈ = (5.3)
dx xi+1 − xi xi+1 − xi

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 (