Python For Engineering and Scientific Computing - Rheinwerk Publishing Inc - E-Book

Python For Engineering and Scientific Computing E-Book

Rheinwerk Publishing Inc

0,0
49,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

This book provides a thorough introduction to Python programming designed for engineers and scientists. It begins with foundational topics like development environments and program structures, then introduces key Python libraries such as NumPy, SymPy, SciPy, Matplotlib, and VPython. Clear explanations and practical exercises help readers write efficient, well-structured code while progressing through increasingly complex projects.
The content covers core programming paradigms including functions, branching, and object-oriented design, followed by numerical analysis with NumPy and symbolic math with SymPy. Detailed chapters on data visualization with Matplotlib and 3D animations with VPython enhance comprehension. Additional focus on statistical computations, Boolean algebra, and interactive GUI programming with Tkinter prepares readers for real-world applications. Each chapter ends with project tasks reinforcing hands-on learning.
Throughout the book, readers build a strong skill set combining programming expertise and scientific problem-solving. By the end, they will confidently use Python’s libraries to solve diverse engineering and scientific challenges. This practical, project-based approach ensures knowledge is both solid and immediately useful in research and professional work.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 656

Veröffentlichungsjahr: 2025

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Dr. Veit Steinkamp

Python for Engineering and Scientific Computing

Imprint

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

Editor   Meagan WhiteAcquisitions Editor   Hareem ShafiGerman Edition Editor   Christoph MeisterCopyeditor   Yvette ChinTranslation   Winema Language ServicesCover Design   Graham GearyPhoto Credit    iStockphoto: 137993550/© OGphoto, 1336159068/© cemagraphicsProduction E-Book   Kelly O’CallaghanTypesetting E-Book   Satz-Pro, 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.

The Library of Congress Cataloging-in-Publication Control Number for the printed edition is as follows: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

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 purposes. 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:

Notes on the Screen Presentation

You are reading this e-book in a file format (EPUB or Mobi) that makes the book content adaptable to the display options of your reading device and to your personal needs. That’s a great thing; but unfortunately not every device displays the content in the same way and the rendering of features such as pictures and tables or hyphenation can lead to difficulties. This e-book was optimized for the presentation on as many common reading devices as possible.

If you want to zoom in on a figure (especially in iBooks on the iPad), tap the respective figure once. By tapping once again, you return to the previous screen. You can find more recommendations on the customization of the screen layout on the Service Pages.

Table of Contents

Notes on Usage

Table of Contents

1   Introduction

1.1   Development Environments

1.1.1   IDLE

1.1.2   Thonny

1.1.3   Spyder

1.1.4   Pip

1.2   The Modules of Python

1.2.1   NumPy

1.2.2   Matplotlib

1.2.3   SymPy

1.2.4   SciPy

1.2.5   VPython

1.3   The Keywords of Python

1.4   Your Path through This Book

2   Program Structures

2.1   Linear Program Structures

2.1.1   Linear Programs without Function Calls

2.2   Functions

2.2.1   Built-In Functions

2.2.2   Functions without Parameters and without Return Values

2.2.3   Functions with Parameters and a Return

2.2.4   Functions with Multiple Return Values

2.2.5   Functions Call Other Functions

2.3   Branching Structures

2.3.1   Single Selection

2.3.2   Multiple Selection

2.4   Repetitive Structures

2.4.1   The while Loop

2.4.2   The for Loop

2.5   Data Structures

2.5.1   Tuples

2.5.2   Lists

2.5.3   Dictionaries

2.5.4   Sets

2.6   Functional Program Style

2.7   Object-Oriented Program Style

2.7.1   Objects and Classes

2.7.2   Inheritance

2.8   Project Task: Dimensions of a Shaft

2.9   Tasks

3   Numerical Calculations Using NumPy

3.1   NumPy Functions

3.1.1   Creating One-Dimensional Arrays Using arange() and linspace()

3.1.2   Creating Two-Dimensional Arrays Using array()

3.1.3   Slicing

3.1.4   Mathematical NumPy Functions

3.1.5   Statistical NumPy Functions

3.2   Vectors

3.2.1   Addition of Vectors

3.2.2   Scalar Product

3.2.3   Cross Product

3.2.4   Triple Product

3.2.5   Dyadic Product

3.3   Matrix Multiplication

3.3.1   Chain Shape with B Parameters

3.3.2   Usage Example: Calculating the Energy of a Rotating Rigid Body in Space

3.4   Linear Systems of Equations

3.4.1   Systems of Equations with Real Coefficients

3.4.2   Systems of Equations with Complex Coefficients

3.5   Project Task: Lightning Protection System

3.6   Tasks

4   Function Plots and Animations Using Matplotlib

4.1   2D Function Plots

4.1.1   Basic Structure of a Function Plot

4.1.2   Gridlines

4.1.3   Labels

4.1.4   Line Styles

4.1.5   Designing Axes

4.1.6   Coloring Areas

4.1.7   Subplots

4.1.8   Parameter Representation

4.1.9   Changing Function Parameters Interactively

4.1.10   Contour Plots

4.2   3D Function Plots

4.2.1   Helical Line

4.2.2   Circular Ring

4.2.3   Combining a 3D Plot with a Contour Plot

4.3   Vectors

4.3.1   Vector Addition

4.3.2   Vector Field

4.4   Displaying Figures, Lines, and Arrows

4.4.1   Rectangles

4.4.2   Circles and Lines

4.4.3   Arrows

4.4.4   Polygons

4.4.5   Usage Example: A Metal Rod in a Magnetic Field

4.5   Animations

4.5.1   A Simple Animation: Shifting a Sine Function

4.5.2   Animated Oblique Throw

4.5.3   Animated Planetary Orbit

4.6   Project Task: Stirling Cycle

4.7   Project Task: Animating a Thread Pendulum

4.8   Project Task: Animating a Transmission

4.9   Tasks

5   Symbolic Computation Using SymPy

5.1   Basic Mathematical Operations

5.1.1   Addition

5.1.2   Multiplication of Terms

5.1.3   Multiplication of Linear Factors

5.1.4   Division

5.1.5   Exponentiation

5.1.6   Usage Example: Analyzing an Electrical Power Transmission System

5.2   Multiplying Matrixes

5.2.1   Calculation Rule

5.2.2   Transmission Function of a Catenary Circuit

5.3   Equations

5.3.1   Linear Systems of Equations

5.3.2   Nonlinear Systems of Equations

5.4   Simplifications of Terms

5.5   Series Expansion

5.6   Partial Fractions

5.7   Continued Fractions

5.8   Limits

5.8.1   Limits of Sequences

5.8.2   Limits of Functions

5.8.3   Differential Quotient

5.9   Differentiation

5.9.1   Usage Example: Curve Sketching

5.10   Integrations

5.10.1   Indefinite Integral

5.10.2   Definite Integral

5.10.3   Usage Example: Stored Electrical Energy

5.11   Differential Equations

5.11.1   Linear First-Order Differential Equations

5.11.2   General Solution of a Second-Order Differential Equation

5.11.3   Special Solution of a Second-Order Differential Equation

5.12   Laplace Transform

5.12.1   Solving Differential Equations

5.12.2   Analyzing Networks with Transmission Functions

5.13   Project Task: Step Response of a Catenary Circuit

5.14   Project Task: Bending a Beam That Is Fixed at One End

5.14.1   Second Moment of Area

5.14.2   Equation of the Bending Line

5.15   Project Task: Reaction Kinetics

5.16   Project Task: Dual Mass Oscillator

5.17   Tasks

6   Numerical Computations and Simulations Using SciPy

6.1   Numerical Computation of Zeros

6.2   Optimizations

6.3   Interpolations

6.4   Numerical Differentiation

6.4.1   Methods of Numerical Differentiation

6.4.2   Drawing a Tangent Slope

6.4.3   Derivative of a Sine Function

6.4.4   Usage Example: Free Fall

6.5   Numerical Integration

6.5.1   Methods of Numerical Integration

6.5.2   Definite Integral

6.5.3   Integrating a Constant

6.5.4   Usage Example: Free Fall

6.5.5   Improper Integral

6.5.6   Calculating Arc Lengths

6.5.7   Volume and Surfaces of Rotating Bodies

6.5.8   Double Integrals

6.5.9   Triple Integrals

6.6   Solving Differential Equations Numerically

6.6.1   Numerical Solution of Differential Equations

6.6.2   First-Order Linear Differential Equation

6.6.3   Second-Order Linear Differential Equation

6.6.4   Nonlinear Second-Order Differential Equation

6.6.5   Second-Order Differential Equation System: Coupled Spring-Mass System

6.6.6   Nonlinear Second-Order Differential Equation System: Double Pendulum

6.7   Discrete Fourier Transform

6.7.1   Basic Use of the Fast Fourier Transform Algorithm

6.7.2   Frequency Spectra of Non-Sinusoidal Periodic Signals

6.7.3   Reconstructing a Noisy Signal

6.8   Writing and Reading Sound Files

6.8.1   Generating and Saving Signals

6.8.2   Reading and Displaying Signals

6.9   Signal Processing

6.9.1   Frequency Response of a Butterworth Lowpass

6.9.2   Frequency Response of a Crossover

6.9.3   Filtering Signals

6.10   Project Task: Simulation of a Rolling Bearing Damage

6.11   Project Task: Predator-Prey Model

6.11.1   Exponential Growth

6.11.2   Logistic Growth

6.11.3   Predator-Prey Relationship for Exponential Growth

6.11.4   Predator-Prey Relationship for Logistic Growth

6.12   Project Task: Simulation of an Epidemic

6.13   Tasks

7   3D Graphics and Animations Using VPython

7.1   The Coordinate System

7.2   Basic Shapes, Points, and Lines

7.2.1   Cylinder

7.2.2   Cuboid

7.2.3   Points

7.2.4   Lines

7.2.5   Sphere

7.2.6   Penetration

7.2.7   Composite Bodies

7.3   Bodies in Motion

7.3.1   Vertical Movement

7.3.2   Horizontal Movement

7.3.3   Movement in Space

7.3.4   Composite Motion

7.3.5   Rotational Motion

7.3.6   Random Motion

7.4   Animation of Oscillations

7.4.1   Simple Pendulum

7.4.2   Spring Pendulum

7.5   Event Processing

7.6   Project Task: Animation of a Coupled Spring Pendulum

7.7   Project Task: Animation of Two Coupled Simple Pendulums

7.8   Tasks

8   Computing with Complex Numbers

8.1   Mathematical Operations

8.2   Euler’s Formula

8.2.1   Symbolic Method

8.3   Calculating with Complex Resistors

8.4   Function Plots with Complex Magnitudes

8.4.1   Complex Frequency Response of a Series Resonant Circuit

8.4.2   Locus Curves

8.5   Project Task: Electric Power Transmission System

8.5.1   Task

8.5.2   Equivalent Circuit Diagram of a Three-Phase Power Line

8.6   Tasks

9   Statistical Computations

9.1   Generating, Saving, and Reading Measurement Values

9.1.1   Generating Measurement Values

9.1.2   Converting a Measurement Series into a Table

9.1.3   Writing Measurement Values to a File

9.1.4   Reading Measurement Values from a File

9.2   Frequency Distribution

9.2.1   Frequency Tables

9.2.2   Histograms

9.3   Location Parameters

9.3.1   Arithmetic Mean

9.3.2   Mode, Median, Harmonic Mean, and Geometric Mean

9.4   Dispersion Parameters

9.5   Normal Distribution

9.5.1   Graphical Representation of the Density Function

9.5.2   Probability Distribution

9.6   Skew

9.7   Regression Analysis

9.7.1   Computing the Regression Parameters

9.7.2   Representing the Scatter Plot and the Regression Line

9.8   Project Task: Simulation of a Quality Control Chart

9.9   Tasks

10   Boolean Algebra

10.1   Logical Operations

10.1.1   Conjunction

10.1.2   Disjunction

10.1.3   Negation

10.2   Laws of Boolean Algebra

10.2.1   Simple Postulates

10.2.2   De Morgan’s Laws

10.2.3   Distributive Law

10.3   Circuit Synthesis

10.3.1   Simplifying Logic Functions by Factoring Out

10.3.2   Simplification Using the Disjunctive Normal Form

10.3.3   Simplification Using the Conjunctive Normal Form

10.4   Project Task: Seven-Segment Coding

10.5   Tasks

11   Interactive Programming Using Tkinter

11.1   Interactions with Command Buttons, Textboxes, and Labels

11.1.1   Labels

11.1.2   Textboxes and Command Buttons

11.2   The Layout Manager of Tkinter

11.2.1   The pack Method

11.2.2   The grid Method

11.2.3   Summary

11.3   Selection with Radio Button

11.4   Slider

11.5   The Canvas Drawing Area

11.5.1   Representing Lines

11.5.2   Function Plots

11.5.3   Querying Mouse Coordinates

11.6   Project Task: Rotational Frequency Control of an Externally Excited DC Motor

11.7   Tasks

A   Appendix

A.1   Glossary: Basic Applied Computer Science Terminology

A.2   Derivatives of Elementary Functions

A.3   Antiderivative of Elementary Functions

A.4   Fourier Series of Important Electrotechnical Voltage Characteristics

A.5   Correspondence Table of Important Inverse Laplace Transforms

A.6   Bibliography

B   The Author

Index

Service Pages

Legal Notes

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

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.

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 highlighting, automatic indentation of the source code, and so on. The debugger helps programmers 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 Environment.” 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 (Section 1.1.4). This step may cause problems if you install a new Python version: The modules 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 environment.

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 development environment with a comparatively small range of functions. However, it is particularly 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 result of numerical calculations is then output in the Command Line window at the bottom 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, supports 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.

Figure 1.4The 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 containing slider controls can also be executed interactively only with this option.

Spyder is an immensely powerful development environment. However, one disadvantage 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:

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 version. 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 installation or update of the Python modules fails, I recommend using the Thonny development environment instead.

1.3    The Keywords of Python

Whenever you learn a new programming language, the first thing you must know are the keywords defined in that language. Keywords are the reserved words of a programming language. They have a specific meaning in the programming language definition and must therefore not be used as variable names in a program. Python has 35 keywords, which you can view by entering the following commands in the Python console:

>>> import keyword

>>> a=keyword.kwlist

>>> print(a)

You’ll receive the following output:

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

Similarly, the following statement will output the number of keywords:

>>> print(len(a))

35

You don’t need to memorize all the keywords at first. For better overview of Python’s keywords, a useful exercise is to first arrange them according to their functionalities. Table 1.1 provides an overview of the most important keywords arranged according to functional criteria.

ConditionalStatements

Loops

Classes, Modules, and Functions

ErrorHandling

if

for

class

try

else

in

def

except

elif

while

global

finally

not

break

lambda

raise

or

as

nonlocal

assert

and

continue

yield

with

is

import

True

return

False

from

None

Table 1.1     The Most Important Keywords in Python

With a few keywords like if, else, for, and while, along with the built-in Python function print(), you can already write simple Python programs.

1.4    Your Path through This Book

How should you read this book? Basically, you can read the individual chapters independently of each other. If you already know the basic structures of Python, then you can skip Chapter 2. If just starting to learn, you must read that chapter first as a prerequisite for understanding subsequent chapters.

Our approach to presentation and knowledge transfer is based on a uniform principle: One to three examples from electrical engineering, mechanical engineering, or physics are presented for each topic. After a brief description of the task, the complete source code is printed. Directly after the source code, the output (the results of the calculations) takes place. The source code is then discussed and analyzed.

Our analysis of source code also includes an analysis of the results (output). Are the results in line with expectations? Does the program solve the task set for it at all? Often, you won’t fully understand the source code of a program until you’ve taken a closer look at the output. After viewing the output, you can then analyze the source code again.

At the end of each chapter, one or more project assignments are provided, discussed, and fully solved to reinforce and expand on what was learned in that chapter.