0% found this document useful (0 votes)
4 views

Python for Engineering and Scientific Computing 1st Edition Veit Steinkamp download

The document provides information about the e-book 'Python for Engineering and Scientific Computing' by Veit Steinkamp, including its availability for download in various formats. It also lists additional related publications in the Rheinwerk Computing series, which aims to enhance skills for professionals in engineering and scientific computing. The e-book covers topics such as programming structures, numerical calculations, function plotting, and symbolic computation using Python.

Uploaded by

turraaroma87
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python for Engineering and Scientific Computing 1st Edition Veit Steinkamp download

The document provides information about the e-book 'Python for Engineering and Scientific Computing' by Veit Steinkamp, including its availability for download in various formats. It also lists additional related publications in the Rheinwerk Computing series, which aims to enhance skills for professionals in engineering and scientific computing. The e-book covers topics such as programming structures, numerical calculations, function plotting, and symbolic computation using Python.

Uploaded by

turraaroma87
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Python for Engineering and Scientific Computing

1st Edition Veit Steinkamp pdf download

https://ebookname.com/product/python-for-engineering-and-
scientific-computing-1st-edition-veit-steinkamp/

Get Instant Ebook Downloads – Browse at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Techniques of scientific computing for the energy and


environment Frederic Magoules

https://ebookname.com/product/techniques-of-scientific-computing-
for-the-energy-and-environment-frederic-magoules/

Mathematics for Electrical Engineering and Computing


1st Edition Mary Patricia Attenborough

https://ebookname.com/product/mathematics-for-electrical-
engineering-and-computing-1st-edition-mary-patricia-attenborough/

Stochastic Methods in Scientific Computing 1st Edition


Massimo D'Elia

https://ebookname.com/product/stochastic-methods-in-scientific-
computing-1st-edition-massimo-delia/

The languages of global hip hop 1st Edition Marina


Terkourafi

https://ebookname.com/product/the-languages-of-global-hip-
hop-1st-edition-marina-terkourafi/
Statics 1st Edition N. P. Bali

https://ebookname.com/product/statics-1st-edition-n-p-bali/

Audience Research Methodologies Between Innovation and


Consolidation 1st Edition Geoffroy Patriarche

https://ebookname.com/product/audience-research-methodologies-
between-innovation-and-consolidation-1st-edition-geoffroy-
patriarche/

Medicynical Cartoons from the Daily Routine in Medicine


1st Edition Prof. Dr. Med. Volker Lange (Auth.)

https://ebookname.com/product/medicynical-cartoons-from-the-
daily-routine-in-medicine-1st-edition-prof-dr-med-volker-lange-
auth/

Spooky Texas Tales of Hauntings Strange Happenings and


Other Local Lore 1st Edition S. E. Schlosser

https://ebookname.com/product/spooky-texas-tales-of-hauntings-
strange-happenings-and-other-local-lore-1st-edition-s-e-
schlosser/

The Arabs A History 1st ed 2009 First Edition Eugene


Rogan

https://ebookname.com/product/the-arabs-a-history-1st-
ed-2009-first-edition-eugene-rogan/
An Introduction to the Non Perturbative Foundations of
Quantum Field Theory 1st Edition Franco Strocchi

https://ebookname.com/product/an-introduction-to-the-non-
perturbative-foundations-of-quantum-field-theory-1st-edition-
franco-strocchi/
Rheinwerk Computing
The Rheinwerk Computing series offers new and established professionals comprehen-
sive guidance to enrich their skillsets and enhance their career prospects. Our publica-
tions are written by the leading experts in their fields. Each book is detailed and hands-on
to help readers develop essential, practical skills that they can apply to their daily work.

Explore more of the Rheinwerk Computing library!


Johannes Ernesti, Peter Kaiser
Python 3: The Comprehensive Guide
2022, 1036 pages, paperback and e-book
www.rheinwerk-computing.com/5566

Philip Ackermann
JavaScript: The Comprehensive Guide
2022, 1292 pages, paperback and e-book
www.rheinwerk-computing.com/5554

Sebastian Springer
Node.js: The Comprehensive Guide
2022, 834 pages, paperback and e-book
www.rheinwerk-computing.com/5556

Bernd Öggl, Michael Kofler


Git: Project Management for Developers and DevOps Teams
2023, 407 pages, paperback and e-book
www.rheinwerk-computing.com/5555

Sebastian Springer
React: The Comprehensive Guide
2024, 676 pages, paperback and e-book
www.rheinwerk-computing.com/5705

www.rheinwerk-computing.com
Veit Steinkamp

Python for
Engineering and
Scientific Computing
Imprint

This e-book is a publication many contributed to, specifically:

Editor Meagan White


Acquisitions Editor Hareem Shafi
German Edition Editor Christoph Meister
Translation Winema Language Services, Inc.
Copyeditor Yvette Chin
Cover Design Graham Geary
Photo Credit iStockphoto: 137993550/© OGphoto, 1336159068/© cemagraphics
Layout Design Vera Brauner
Production E-Book Kelly O’Callaghan
Typesetting E-Book SatzPro, Germany

We hope that you liked this e-book. Please share your feedback with us and read the
Service Pages to find out how to contact us.

Library of Congress Cataloging-in-Publication Control Number: 2024930350

ISBN 978-1-4932-2559-0 (print)


ISBN 978-1-4932-2560-6 (e-book)
ISBN 978-1-4932-2561-3 (print and e-book)

© 2024 by Rheinwerk Publishing, Inc., Boston (MA)


1st edition 2024
1st German edition published 2023 by Rheinwerk Verlag, Bonn, Germany
Notes on Usage

This e-book is protected by copyright. By purchasing this e-book, you have agreed to
accept and adhere to the copyrights. You are entitled to use this e-book for personal pur-
poses. You may print and copy it, too, but also only for personal use. Sharing an electronic
or printed copy with others, however, is not permitted, neither as a whole nor in parts. Of
course, making them available on the Internet or in a company network is illegal as well.

For detailed and legally binding usage conditions, please refer to the section
Legal Notes.

This e-book copy contains a digital watermark, a signature that indicates which person
may use this copy:
Contents

1 Introduction 17

1.1 Development Environments ............................................................................................ 18


1.1.1 IDLE .............................................................................................................................. 18
1.1.2 Thonny ....................................................................................................................... 19
1.1.3 Spyder ......................................................................................................................... 20
1.1.4 Pip ................................................................................................................................ 21
1.2 The Modules of Python ....................................................................................................... 22
1.2.1 NumPy ........................................................................................................................ 22
1.2.2 Matplotlib ................................................................................................................. 23
1.2.3 SymPy ......................................................................................................................... 24
1.2.4 SciPy ............................................................................................................................ 24
1.2.5 VPython ..................................................................................................................... 25
1.3 The Keywords of Python .................................................................................................... 26

1.4 Your Path through This Book ........................................................................................... 27

2 Program Structures 29

2.1 Linear Program Structures ................................................................................................. 29


2.1.1 Linear Programs without Function Calls ........................................................ 30
2.2 Functions ................................................................................................................................... 37
2.2.1 Built-In Functions ................................................................................................... 38
2.2.2 Functions without Parameters and without Return Values .................... 39
2.2.3 Functions with Parameters and a Return ...................................................... 40
2.2.4 Functions with Multiple Return Values .......................................................... 42
2.2.5 Functions Call Other Functions ......................................................................... 44
2.3 Branching Structures ........................................................................................................... 45
2.3.1 Single Selection ....................................................................................................... 46
2.3.2 Multiple Selection .................................................................................................. 47
2.4 Repetitive Structures ........................................................................................................... 50
2.4.1 The while Loop ........................................................................................................ 50
2.4.2 The for Loop .............................................................................................................. 56

7
Contents

2.5 Data Structures ....................................................................................................................... 63


2.5.1 Tuples ......................................................................................................................... 63
2.5.2 Lists ............................................................................................................................. 66
2.5.3 Dictionaries .............................................................................................................. 72
2.5.4 Sets .............................................................................................................................. 75
2.6 Functional Program Style ................................................................................................... 76

2.7 Object-Oriented Program Style ....................................................................................... 79


2.7.1 Objects and Classes ............................................................................................... 80
2.7.2 Inheritance ................................................................................................................ 84
2.8 Project Task: Dimensions of a Shaft .............................................................................. 86

2.9 Tasks ............................................................................................................................................ 88

3 Numerical Calculations Using NumPy 91

3.1 NumPy Functions ................................................................................................................... 91


3.1.1 Creating One-Dimensional Arrays Using arange() and linspace() ......... 91
3.1.2 Creating Two-Dimensional Arrays Using array() ......................................... 94
3.1.3 Slicing ......................................................................................................................... 96
3.1.4 Mathematical NumPy Functions ...................................................................... 97
3.1.5 Statistical NumPy Functions ............................................................................... 99
3.2 Vectors ........................................................................................................................................ 101
3.2.1 Addition of Vectors ................................................................................................ 101
3.2.2 Scalar Product .......................................................................................................... 103
3.2.3 Cross Product ........................................................................................................... 105
3.2.4 Triple Product ........................................................................................................... 107
3.2.5 Dyadic Product ........................................................................................................ 108
3.3 Matrix Multiplication .......................................................................................................... 109
3.3.1 Chain Shape with B Parameters ........................................................................ 113
3.3.2 Usage Example: Calculating the Energy of a Rotating Rigid Body
in Space ...................................................................................................................... 114
3.4 Linear Systems of Equations ............................................................................................. 116
3.4.1 Systems of Equations with Real Coefficients ................................................ 116
3.4.2 Systems of Equations with Complex Coefficients ...................................... 118
3.5 Project Task: Lightning Protection System ................................................................ 121

3.6 Tasks ............................................................................................................................................ 124

8
Contents

4 Function Plots and Animations


Using Matplotlib 125

4.1 2D Function Plots ................................................................................................................... 125


4.1.1 Basic Structure of a Function Plot ..................................................................... 125
4.1.2 Gridlines .................................................................................................................... 132
4.1.3 Labels .......................................................................................................................... 134
4.1.4 Line Styles ................................................................................................................. 137
4.1.5 Designing Axes ........................................................................................................ 138
4.1.6 Coloring Areas ......................................................................................................... 144
4.1.7 Subplots ..................................................................................................................... 147
4.1.8 Parameter Representation .................................................................................. 154
4.1.9 Changing Function Parameters Interactively ............................................... 158
4.1.10 Contour Plots ........................................................................................................... 163
4.2 3D Function Plots ................................................................................................................... 166
4.2.1 Helical Line ................................................................................................................ 166
4.2.2 Circular Ring ............................................................................................................. 168
4.2.3 Combining a 3D Plot with a Contour Plot ...................................................... 169
4.3 Vectors ........................................................................................................................................ 171
4.3.1 Vector Addition ....................................................................................................... 171
4.3.2 Vector Field ............................................................................................................... 173
4.4 Displaying Figures, Lines, and Arrows .......................................................................... 174
4.4.1 Rectangles ................................................................................................................. 174
4.4.2 Circles and Lines ...................................................................................................... 176
4.4.3 Arrows ........................................................................................................................ 178
4.4.4 Polygons .................................................................................................................... 179
4.4.5 Usage Example: A Metal Rod in a Magnetic Field ....................................... 181
4.5 Animations ............................................................................................................................... 182
4.5.1 A Simple Animation: Shifting a Sine Function ............................................. 183
4.5.2 Animated Oblique Throw .................................................................................... 186
4.5.3 Animated Planetary Orbit .................................................................................... 188
4.6 Project Task: Stirling Cycle ................................................................................................ 190

4.7 Project Task: Animating a Thread Pendulum ........................................................... 197

4.8 Project Task: Animating a Transmission ..................................................................... 201

4.9 Tasks ............................................................................................................................................ 204

9
Contents

5 Symbolic Computation Using SymPy 207

5.1 Basic Mathematical Operations ...................................................................................... 211


5.1.1 Addition ..................................................................................................................... 211
5.1.2 Multiplication of Terms ........................................................................................ 212
5.1.3 Multiplication of Linear Factors ......................................................................... 213
5.1.4 Division ...................................................................................................................... 214
5.1.5 Exponentiation ........................................................................................................ 215
5.1.6 Usage Example: Analyzing an Electrical Power
Transmission System ............................................................................................ 216
5.2 Multiplying Matrixes ........................................................................................................... 217
5.2.1 Calculation Rule ...................................................................................................... 217
5.2.2 Transmission Function of a Catenary Circuit ................................................ 218
5.3 Equations .................................................................................................................................. 220
5.3.1 Linear Systems of Equations ............................................................................... 221
5.3.2 Nonlinear Systems of Equations ....................................................................... 223
5.4 Simplifications of Terms ..................................................................................................... 226

5.5 Series Expansion .................................................................................................................... 227

5.6 Partial Fractions ..................................................................................................................... 228

5.7 Continued Fractions ............................................................................................................. 231

5.8 Limits ........................................................................................................................................... 234


5.8.1 Limits of Sequences ............................................................................................... 234
5.8.2 Limits of Functions ................................................................................................. 236
5.8.3 Differential Quotient ............................................................................................ 237
5.9 Differentiation ........................................................................................................................ 238
5.9.1 Usage Example: Curve Sketching ..................................................................... 239
5.10 Integrations .............................................................................................................................. 240
5.10.1 Indefinite Integral .................................................................................................. 241
5.10.2 Definite Integral ...................................................................................................... 242
5.10.3 Usage Example: Stored Electrical Energy ....................................................... 243
5.11 Differential Equations ......................................................................................................... 245
5.11.1 Linear First-Order Differential Equations ....................................................... 246
5.11.2 General Solution of a Second-Order Differential Equation ...................... 250
5.11.3 Special Solution of a Second-Order Differential Equation ....................... 252
5.12 Laplace Transform ................................................................................................................. 254
5.12.1 Solving Differential Equations ........................................................................... 255
5.12.2 Analyzing Networks with Transmission Functions .................................... 259
5.13 Project Task: Step Response of a Catenary Circuit ................................................. 262

10
Contents

5.14 Project Task: Bending a Beam That Is Fixed at One End ...................................... 265
5.14.1 Second Moment of Area ...................................................................................... 265
5.14.2 Equation of the Bending Line ............................................................................. 267
5.15 Project Task: Reaction Kinetics ........................................................................................ 270

5.16 Project Task: Dual Mass Oscillator ................................................................................. 274

5.17 Tasks ............................................................................................................................................ 277

6 Numerical Computations and Simulations


Using SciPy 279

6.1 Numerical Computation of Zeros ................................................................................... 280

6.2 Optimizations ......................................................................................................................... 282

6.3 Interpolations .......................................................................................................................... 284

6.4 Numerical Differentiation ................................................................................................. 286


6.4.1 Methods of Numerical Differentiation ........................................................... 286
6.4.2 Drawing a Tangent Slope .................................................................................... 287
6.4.3 Derivative of a Sine Function .............................................................................. 289
6.4.4 Usage Example: Free Fall ..................................................................................... 291
6.5 Numerical Integration ......................................................................................................... 293
6.5.1 Methods of Numerical Integration .................................................................. 293
6.5.2 Definite Integral ...................................................................................................... 295
6.5.3 Integrating a Constant ......................................................................................... 296
6.5.4 Usage Example: Free Fall ..................................................................................... 298
6.5.5 Improper Integral ................................................................................................... 300
6.5.6 Calculating Arc Lengths ........................................................................................ 302
6.5.7 Volume and Surfaces of Rotating Bodies ....................................................... 303
6.5.8 Double Integrals ..................................................................................................... 305
6.5.9 Triple Integrals ......................................................................................................... 306
6.6 Solving Differential Equations Numerically .............................................................. 307
6.6.1 Numerical Solution of Differential Equations .............................................. 307
6.6.2 First-Order Linear Differential Equation ......................................................... 312
6.6.3 Second-Order Linear Differential Equation ................................................... 315
6.6.4 Nonlinear Second-Order Differential Equation ............................................ 318
6.6.5 Second-Order Differential Equation System:
Coupled Spring-Mass System ............................................................................. 322
6.6.6 Nonlinear Second-Order Differential Equation System:
Double Pendulum .................................................................................................. 325

11
Contents

6.7 Discrete Fourier Transform ............................................................................................... 328


6.7.1 Basic Use of the Fast Fourier Transform Algorithm .................................... 329
6.7.2 Frequency Spectra of Non-Sinusoidal Periodic Signals ............................. 330
6.7.3 Reconstructing a Noisy Signal ............................................................................ 332
6.8 Writing and Reading Sound Files ................................................................................... 334
6.8.1 Generating and Saving Signals .......................................................................... 334
6.8.2 Reading and Displaying Signals ......................................................................... 335
6.9 Signal Processing ................................................................................................................... 337
6.9.1 Frequency Response of a Butterworth Lowpass .......................................... 337
6.9.2 Frequency Response of a Crossover ................................................................. 339
6.9.3 Filtering Signals ....................................................................................................... 341
6.10 Project Task: Simulation of a Rolling Bearing Damage ........................................ 342

6.11 Project Task: Predator-Prey Model ................................................................................ 345


6.11.1 Exponential Growth .............................................................................................. 346
6.11.2 Logistic Growth ....................................................................................................... 346
6.11.3 Predator-Prey Relationship for Exponential Growth .................................. 346
6.11.4 Predator-Prey Relationship for Logistic Growth .......................................... 347
6.12 Project Task: Simulation of an Epidemic ..................................................................... 349

6.13 Tasks ............................................................................................................................................ 352

7 3D Graphics and Animations Using VPython 355

7.1 The Coordinate System ....................................................................................................... 356


7.2 Basic Shapes, Points, and Lines ....................................................................................... 358
7.2.1 Cylinder ...................................................................................................................... 359
7.2.2 Cuboid ........................................................................................................................ 361
7.2.3 Points .......................................................................................................................... 363
7.2.4 Lines ............................................................................................................................ 364
7.2.5 Sphere ........................................................................................................................ 366
7.2.6 Penetration ............................................................................................................... 369
7.2.7 Composite Bodies ................................................................................................... 370
7.3 Bodies in Motion .................................................................................................................... 371
7.3.1 Vertical Movement ................................................................................................ 372
7.3.2 Horizontal Movement .......................................................................................... 373
7.3.3 Movement in Space ............................................................................................... 374
7.3.4 Composite Motion ................................................................................................. 377
7.3.5 Rotational Motion .................................................................................................. 378
7.3.6 Random Motion ...................................................................................................... 383

12
Contents

7.4 Animation of Oscillations .................................................................................................. 385


7.4.1 Simple Pendulum ................................................................................................... 385
7.4.2 Spring Pendulum .................................................................................................... 387
7.5 Event Processing .................................................................................................................... 389

7.6 Project Task: Animation of a Coupled Spring Pendulum ..................................... 392

7.7 Project Task: Animation of Two Coupled Simple Pendulums ........................... 395

7.8 Tasks ............................................................................................................................................ 398

8 Computing with Complex Numbers 399

8.1 Mathematical Operations ................................................................................................. 400

8.2 Euler’s Formula ....................................................................................................................... 402


8.2.1 Symbolic Method .................................................................................................... 403
8.3 Calculating with Complex Resistors ............................................................................. 403

8.4 Function Plots with Complex Magnitudes ................................................................. 406


8.4.1 Complex Frequency Response of a Series Resonant Circuit .................... 406
8.4.2 Locus Curves ............................................................................................................. 408
8.5 Project Task: Electric Power Transmission System ................................................. 410
8.5.1 Task ............................................................................................................................. 411
8.5.2 Equivalent Circuit Diagram of a Three-Phase Power Line ........................ 413
8.6 Tasks ............................................................................................................................................ 415

9 Statistical Computations 417

9.1 Generating, Saving, and Reading Measurement Values ..................................... 419


9.1.1 Generating Measurement Values .................................................................... 419
9.1.2 Converting a Measurement Series into a Table ........................................... 420
9.1.3 Writing Measurement Values to a File ........................................................... 422
9.1.4 Reading Measurement Values from a File ..................................................... 423
9.2 Frequency Distribution ....................................................................................................... 423
9.2.1 Frequency Tables .................................................................................................... 424
9.2.2 Histograms ............................................................................................................... 425
9.3 Location Parameters ............................................................................................................ 426
9.3.1 Arithmetic Mean ..................................................................................................... 427
9.3.2 Mode, Median, Harmonic Mean, and Geometric Mean ............................ 428

13
Contents

9.4 Dispersion Parameters ........................................................................................................ 430

9.5 Normal Distribution ............................................................................................................. 434


9.5.1 Graphical Representation of the Density Function .................................... 434
9.5.2 Probability Distribution ........................................................................................ 435
9.6 Skew ............................................................................................................................................ 437

9.7 Regression Analysis .............................................................................................................. 439


9.7.1 Computing the Regression Parameters .......................................................... 439
9.7.2 Representing the Scatter Plot and the Regression Line ............................. 442
9.8 Project Task: Simulation of a Quality Control Chart .............................................. 443

9.9 Tasks ............................................................................................................................................ 448

10 Boolean Algebra 449

10.1 Logical Operations ................................................................................................................ 450


10.1.1 Conjunction .............................................................................................................. 450
10.1.2 Disjunction ............................................................................................................... 451
10.1.3 Negation .................................................................................................................... 452
10.2 Laws of Boolean Algebra .................................................................................................... 453
10.2.1 Simple Postulates ................................................................................................... 453
10.2.2 De Morgan’s Laws .................................................................................................. 454
10.2.3 Distributive Law ...................................................................................................... 455
10.3 Circuit Synthesis ..................................................................................................................... 456
10.3.1 Simplifying Logic Functions by Factoring Out .............................................. 456
10.3.2 Simplification Using the Disjunctive Normal Form .................................... 457
10.3.3 Simplification Using the Conjunctive Normal Form .................................. 460
10.4 Project Task: Seven-Segment Coding ........................................................................... 460
10.5 Tasks ............................................................................................................................................ 463

11 Interactive Programming Using Tkinter 465

11.1 Interactions with Command Buttons, Textboxes, and Labels .......................... 466
11.1.1 Labels .......................................................................................................................... 467
11.1.2 Textboxes and Command Buttons ................................................................... 468
11.2 The Layout Manager of Tkinter ....................................................................................... 468
11.2.1 The pack Method .................................................................................................... 470

14
Contents

11.2.2 The grid Method ..................................................................................................... 472


11.2.3 Summary ................................................................................................................... 474
11.3 Selection with Radio Button ............................................................................................. 475

11.4 Slider ............................................................................................................................................ 477

11.5 The Canvas Drawing Area .................................................................................................. 478


11.5.1 Representing Lines ................................................................................................. 478
11.5.2 Function Plots .......................................................................................................... 480
11.5.3 Querying Mouse Coordinates ............................................................................ 482
11.6 Project Task: Rotational Frequency Control of an Externally
Excited DC Motor ................................................................................................................... 484

11.7 Tasks ............................................................................................................................................ 496

Appendices 497

A.1 Glossary: Basic Applied Computer Science Terminology ..................................... 497

A.2 Derivatives of Elementary Functions ............................................................................ 498

A.3 Antiderivative of Elementary Functions ..................................................................... 499

A.4 Fourier Series of Important Electrotechnical Voltage Characteristics ........... 500

A.5 Correspondence Table of Important Inverse Laplace Transforms ................... 500

A.6 Bibliography ............................................................................................................................. 501

The Author ............................................................................................................................................... 503


Index .......................................................................................................................................................... 505
Service Pages .............................................................................................................................................. I
Legal Notes .................................................................................................................................................. II

15
Chapter 1
Introduction
This chapter provides a brief overview of the extensibility, application
areas, and functionality of the Python programming language.

If you need to perform extensive calculations for your scientific work and also want to
present the results in a graphically appealing way, then you should seriously consider
using Python. Python is a programming language whose functionality is similar to that
of MATLAB when extended with appropriate modules. In addition, Python and all its
extension modules are provided free of charge. Using Python, you can, for example,
solve systems of equations, create function plots, differentiate, integrate, and also
solve differential equations. You can also create graphical user interfaces (GUIs). For
almost every problem in engineering and natural sciences, solutions exist that not
only cover a wide range of applications, but also excel in their user-friendliness and
performance.
The Python programming language was developed in the early 1990s by Dutchman
Guido van Rossum at Centrum voor Wiskunde & Informatica (CWI) in Amsterdam. Its
name has nothing to do with the snake but refers instead to the British comedy group
Monty Python.
The particular advantages and features of this programming language include the fol-
lowing:
쐍 Python is an easy-to-learn and powerful programming language.
쐍 It provides efficient data structures.
쐍 It also allows object-oriented programming (OOP).
쐍 It has a clear syntax and dynamic typing.
쐍 Python programs are compiled using an interpreter and are therefore suitable for
the rapid development of prototypes.
쐍 Python is available for Linux, macOS, and Windows.
쐍 Python can be extended by modules.

The module concept is the cornerstone and one of Python’s outstanding strengths.
A module is a component of a software system and represents a functionally self-
contained unit that provides a specific service. For a definable scientific problem, a
module that is tailored precisely to this problem is provided in each case. In this book,
I will introduce you to the NumPy, Matplotlib, SymPy, SciPy, and VPython modules.

17
1 Introduction

1.1 Development Environments


A development environment is a software program that consists of a text editor, a
debugger, and an interpreter. The text editor of a development environment supports
a programmer in writing programs, for example, with features like syntax highlight-
ing, automatic indentation of the source code, and so on. The debugger helps pro-
grammers find errors, and the interpreter executes the program’s statements. Of the
many development environments that can be used to develop Python programs, only
the Integrated Development and Learning Environment (IDLE), Thonny, and Spyder
development environments will be briefly presented here.

1.1.1 IDLE
The abbreviation IDLE stands for “Integrated Development and Learning Environ-
ment.” Figure 1.1 shows the user interface for IDLE.

Figure 1.1 The IDLE Development Environment

IDLE is part of the standard Python download. During the installation of Python, IDLE
is installed at the same time as the Pip package manager. You can download the latest
version of Python for the Linux, macOS, and Windows operating systems at https://
www.python.org/downloads/. Then, you’ll need to install the NumPy, Matplotlib,
SymPy, SciPy, and VPython modules individually using the Pip package manager (Sec-
tion 1.1.4). This step may cause problems if you install a new Python version: The mod-
ules can no longer be imported with the new IDLE version, and the programs will no
longer run. I will show you a way to fix this problem in Section 1.1.4. If the installation
of the Python modules fails, I recommend you use the Thonny development environ-
ment.

18
1.1 Development Environments

When you click Run • Python Shell, the Python shell will open. Next to the >>> input
prompt, you can directly enter Python commands or mathematical expressions, such
as 2+3, 3*5, or 7/5. Note that you must complete each entry by pressing the (Return) key.

1.1.2 Thonny
Compared to the professional solutions, Thonny is a rather simply designed develop-
ment environment with a comparatively small range of functions. However, it is par-
ticularly suitable for programming beginners due to its ease of use. Using Thonny, you
can run and test all the sample programs discussed in this book. Figure 1.2 shows the
user interface.

Figure 1.2 The Thonny Development Environment

Thonny is available for Linux, macOS, and Windows and can be downloaded at https://
thonny.org.
The source code of the program must be entered into the text editor (upper left area).
Once the program has been started via the (F5) function key or by clicking the Start
button, a window opens where you’ll need to enter the file name of the program. The

19
1 Introduction

result of numerical calculations is then output in the Command Line window at the bot-
tom left of the Python shell. Each function plot of Matplotlib programs will be output
in a separate window. In the shell, also referred to as the Python console, you can also
enter Python commands directly. The Assistant in the main window, on the right, sup-
ports you in terms of troubleshooting, although you should temper your expectations
about its capabilities.
A particularly important feature of Thonny is that you can easily install and update the
NumPy, Matplotlib, SymPy, SciPy, and VPython modules. For these tasks, all you need
to do is open the Tools • Manage Packages dialog box, as shown in Figure 1.3. Then, in
the text box in the top-left corner, enter the name of the module you want to install
and click Install or Update.

Figure 1.3 Installing Modules

To remove a module, you must select the corresponding module in the pane on the
left. Then, the Uninstall command button appears to the right of the Install command
button. One notable advantage of the package manager in Thonny is that you can also
test older versions of all available modules. For this task, simply click the ... command
icon to the right of the Install button, which will open a window where you can select
the desired version of the module.

1.1.3 Spyder
Spyder is the development environment of the Anaconda distribution of Python.
Except for VPython, the modules covered in this book—NumPy, Matplotlib, SymPy,
and SciPy—are already built in.

20
1.1 Development Environments

Figure 1.4 The Spyder Development Environment

Spyder is available as a free download for Linux, macOS, and Windows at https://
www.spyder-ide.org.
To run an animation using a Matplotlib program, you must select Automatic as the
backend in the settings under IPython Console • Graphics. After starting the program, a
separate window will open where the animation will run. Matplotlib programs contain-
ing slider controls can also be executed interactively only with this option.
Spyder is an immensely powerful development environment. However, one disadvan-
tage is that the subsequent installation of modules that are not installed by default,
such as VPython, can be difficult for beginners. For more information on installing
Python modules, see the documentation for Spyder at https://www.spyder-ide.org.

1.1.4 Pip
To use development environments other than Thonny or Spyder, you can install
Python modules using Pip. Pip is not a development environment but the package
manager for Python that installs modules from the Python Package Index (PyPI) (https://
pypi.org/). Pip allows you to download and update modules easily—when you use
Python, Pip is a particularly important tool.
If you have installed Python and want to add only the NumPy module, for example,
you can enter the following command in a terminal on Windows, Linux, or macOS:

21
1 Introduction

pip install numpy

The following command enables you to update an existing NumPy installation:

pip install –-upgrade numpy

If you use IDLE (e.g., version 3.9) and install a new version of Python (e.g., 3.11), then the
previously installed Python modules will no longer be imported into the updated ver-
sion. In this case, you should try installing via pip3.11 install numpy.
For more information about using Pip, see https://pypi.org/project/pip. If the installa-
tion or update of the Python modules fails, I recommend using the Thonny develop-
ment environment instead.

1.2 The Modules of Python


For our first look at the capabilities and features of the module concept in Python, I first
want to describe the five modules in a keyword-like manner. Instead of module, the
terms library or software library are also commonly used. The capabilities of Python are
best illustrated by using short sample programs. Of course, you don’t need understand
the source code shown in this section yet. After all, understanding is what the other
chapters are for.

1.2.1 NumPy
The NumPy module (numerical Python) enables you to perform extensive numerical
calculations. For example, you can solve linear systems of equations, even with com-
plex numbers. Listing 1.1 shows a simple vector calculus program.

01 import numpy as np
02 A=np.array([1, 2, 3])
03 B=np.array([4, 5, 6])
04 print("Vector A:",A)
05 print("Vector B:",B)
06 print("Total A+B:",A+B)
07 print("Product A*B:",A*B)
08 print("Cross product :",np.cross(A,B))
09 print("Scalar product:",np.dot(A,B))

Listing 1.1 A NumPy Program

Output

Vector A: [1 2 3]
Vector B: [4 5 6]

22
1.2 The Modules of Python

Total A+B: [5 7 9]
Product A*B: [ 4 10 18]
Cross product : [-3 6 -3]
Scalar product: 32

The NumPy module is described in Chapter 3.

1.2.2 Matplotlib
The Matplotlib module allows you to display mathematical functions, histograms, and
many other diagram types as well as to simulate and animate physical processes. The
graphical design options are remarkably diverse and rich in detail. Listing 1.2 shows a
simple example of the function plot of a polynomial.

01 import numpy as np
02 import matplotlib.pyplot as plt
03 x=np.arange(-2,6,0.01)
04 y=x**3-7*x**2+7*x+15
05 plt.plot(x,y)
06 plt.show()

Listing 1.2 Function Plot with Matplotlib

Output
Figure 1.5 shows the output of the function plot.

Figure 1.5 A Function Plot Created Using Matplotlib

The Matplotlib module is discussed in detail in Chapter 4.

23
1 Introduction

1.2.3 SymPy
Using SymPy (symbolic Python), you can calculate integrals or derivatives symboli-
cally or solve differential equations symbolically. A simplification of mathematical
terms is also possible (and much more). Listing 1.3 shows a simple example of symbolic
differentiation and integration.

01 from sympy import *


02 x=symbols("x")
03 y=x**3-7*x**2+7*x+15
04 y_1=diff(y,x,1)
05 y_2=diff(y,x,2)
06 y_3=diff(y,x,3)
07 Y=integrate(y,x)
08 print("1. Derivative:",y_1)
09 print("2. Derivative:",y_2)
10 print("3. Derivative:",y_3)
11 print(" Integral :",Y)

Listing 1.3 Symbolic Differentiation and Integration Using SymPy

Output

1. Derivative: 3*x**2 - 14*x + 7


2. Derivative: 2*(3*x - 7)
3. Derivative: 6
Integral : x**4/4 - 7*x**3/3 + 7*x**2/2 + 15*x

The SymPy module is described in detail in Chapter 5.

1.2.4 SciPy
SciPy (scientific Python) allows you to numerically differentiate, integrate, and numer-
ically solve systems of differential equations. SciPy is as comprehensive as it is versa-
tile. The capabilities of SciPy can only be partially described in this book. Listing 1.4
shows a simple example of a numerical integration program.

01 import scipy.integrate as integral


02 def f(x):
03 return x**2
04 A=integral.quad(f,0,5)
05 print("Area A=",A[0])

Listing 1.4 Numerical Integration Using SciPy

24
1.2 The Modules of Python

Output

Area A= 41.66666666666666

The SciPy module is described in Chapter 6.

1.2.5 VPython
Using VPython, you can display fields in a 3D view or even animate their movements
in 3D space. As of version 7, the animations are displayed in the standard browser after
the program starts. Listing 1.5 shows an example of how you can program the anima-
tion of a bouncing ball.

01 from vpython import *


02 r=1. #radius
03 h=5. #height
04 scene.background=color.white
05 scene.center=vector(0,h,0)
06 box(pos=vector(0,0,0),size=vector(2*h,r/2,h), color=color.green)
07 ball = sphere(radius=r, color=color.yellow)
08 ball.pos=vector(0,2*h,0) #drop height
09 ball.v = vector(0,0,0) #initial velocity
10 g=9.81
11 dt = 0.01
12 while True:
13 rate(100)
14 ball.pos = ball.pos + ball.v*dt
15 if ball.pos.y < r:
16 ball.v.y = -ball.v.y
17 else:
18 ball.v.y = ball.v.y - g*dt

Listing 1.5 Animation of a Bouncing Ball

Output
Figure 1.6 shows a snapshot of the animation. The VPython module is described in
Chapter 7. Of course, not all the capabilities of the Python modules we’ve mentioned
can be treated exhaustively in this book. If you miss a particular topic, I recommend
referring to the online documentation as a supplemental source of information. A
module’s maintainers should have a website where you’ll find tutorials for each mod-
ule to get you started, including complete module descriptions.

25
Exploring the Variety of Random
Documents with Different Content
damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for


the “Right of Replacement or Refund” described in paragraph 1.F.3,
the Project Gutenberg Literary Archive Foundation, the owner of the
Project Gutenberg™ trademark, and any other party distributing a
Project Gutenberg™ electronic work under this agreement, disclaim
all liability to you for damages, costs and expenses, including legal
fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR
NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR
BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK
OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL
NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF
YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of receiving
it, you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or
entity that provided you with the defective work may elect to provide
a replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.

1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of damages.
If any disclaimer or limitation set forth in this agreement violates the
law of the state applicable to this agreement, the agreement shall be
interpreted to make the maximum disclaimer or limitation permitted
by the applicable state law. The invalidity or unenforceability of any
provision of this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation,


the trademark owner, any agent or employee of the Foundation,
anyone providing copies of Project Gutenberg™ electronic works in
accordance with this agreement, and any volunteers associated with
the production, promotion and distribution of Project Gutenberg™
electronic works, harmless from all liability, costs and expenses,
including legal fees, that arise directly or indirectly from any of the
following which you do or cause to occur: (a) distribution of this or
any Project Gutenberg™ work, (b) alteration, modification, or
additions or deletions to any Project Gutenberg™ work, and (c) any
Defect you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers.
It exists because of the efforts of hundreds of volunteers and
donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will
remain freely available for generations to come. In 2001, the Project
Gutenberg Literary Archive Foundation was created to provide a
secure and permanent future for Project Gutenberg™ and future
generations. To learn more about the Project Gutenberg Literary
Archive Foundation and how your efforts and donations can help,
see Sections 3 and 4 and the Foundation information page at
www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-profit
501(c)(3) educational corporation organized under the laws of the
state of Mississippi and granted tax exempt status by the Internal
Revenue Service. The Foundation’s EIN or federal tax identification
number is 64-6221541. Contributions to the Project Gutenberg
Literary Archive Foundation are tax deductible to the full extent
permitted by U.S. federal laws and your state’s laws.

The Foundation’s business office is located at 809 North 1500 West,


Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up
to date contact information can be found at the Foundation’s website
and official page at www.gutenberg.org/contact

Section 4. Information about Donations to


the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission of
increasing the number of public domain and licensed works that can
be freely distributed in machine-readable form accessible by the
widest array of equipment including outdated equipment. Many
small donations ($1 to $5,000) are particularly important to
maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws regulating


charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states where


we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot make


any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.

Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.
Project Gutenberg™ eBooks are often created from several printed
editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookname.com

You might also like