Skip to main content

2011 | Buch

A Primer on Scientific Programming with Python

insite
SUCHEN

Über dieses Buch

The book serves as a first introduction to computer programming of scientific applications, using the high-level Python language. The exposition is example- and problem-oriented, where the applications are taken from mathematics, numerical calculus, statistics, physics, biology, and finance. The book teaches "Matlab-style" and procedural programming as well as object-oriented programming. High school mathematics is a required background, and it is advantageous to study classical and numerical one-variable calculus in parallel with reading this book. Besides learning how to program computers, the reader will also learn how to solve mathematical problems, arising in various branches of science and engineering, with the aid of numerical methods and programming. By blending programming, mathematics and scientific applications, the book lays a solid foundation for practicing computational science.

Inhaltsverzeichnis

Frontmatter
1. Computing with Formulas
Abstract
Our first examples on computer programming involve programs that evaluate mathematical formulas. You will learn how to write and run a Python program, how to work with variables, how to compute with mathematical functions such as e x and sin x, and how to use Python for interactive calculations.
We assume that you are somewhat familiar with computers so that you know what files and folders are, how you move between folders, how you change file and folder names, and how you write text and save it in a file.
All the program examples associated with this chapter can be found as files in the folder src/formulas. We refer to the preface for how to download the folder tree src containing all the program files for this book.
Hans Petter Langtangen
2. Loops and Lists
Abstract
This chapter shows how repetitive tasks in a program can be automated by loops. We also introduce list objects for storing and processing collections of data with a specific order. Loops and lists, together with functions and if-tests from Chapter 3, lay the fundamental programming foundation for the rest of the book. The programs associated with the chapter are found in the folder src/looplist.
Hans Petter Langtangen
3. Functions and Branching
Abstract
This chapter introduces two fundamental and extremely useful concepts in programming: user-defined functions and branching of program flow, the latter often referred to as “if tests”. The programs associated with the chapter are found in src/funcif.
Hans Petter Langtangen
4. Input Data and Error Handling
Abstract
Recall our first program for evaluating the formula (1.2) on page 19 in Chapter 1:
C = 21
F = (9/5)*C + 32
print F
In this program, C is input data in the sense that C must be known before the program can perform the calculation of F. The results produced by the program, here F, constitute the output data.
Input data can be hardcoded in the program as we do above. That is, we explicitly set variables to specific values (C = 21). This programming style may be suitable for small programs. In general, however, it is considered good practice to let a user of the program provide input data when the program is running. There is then no need to modify the program itself when a new set of input data is to be explored.
This chapter starts with describing three different ways of reading data into a program: (i) letting the user answer questions in a dialog in the terminal window (Chapter 4.1), (ii) letting the user provide input on the command line (Chapter 4.2), and (iii) letting the user write input data in a graphical interface (Chapter 4.4). A fourth method is to read data from a file, but this topic is left for Chapter 6.
Even if your program works perfectly, wrong input data from the user may cause the program to produce wrong answers or even crash. Checking that the input data are correct is important, and Chapter 4.3 tells you how to do this with so-called exceptions.
The Python programming environment is organized as a big collection of modules. Organizing your own Python software in terms of modules is therefore a natural and wise thing to do. Chapter 4.5 tells you how easy it is to make your own modules.
All the program examples from the present chapter are available in files in the src/input folder.
Hans Petter Langtangen
5. Array Computing and Curve Plotting
Abstract
Lists are introduced in Chapter 2 to store “tabular data” in a convenient way. An array is an object that is very similar to a list, but less flexible and computationally much more efficient. When using the computer to perform mathematical calculations, we often end up with a huge amount of numbers and associated arithmetic operations. Storing numbers in lists may in such contexts lead to slow programs, while arrays can make the programs run much faster. This may not be very important for the mathematical problems in this book, since most of the programs usually finish execution within a few seconds. Nevertheless, in more advanced applications of mathematics, especially the applications met in industry and science, computer programs may run for weeks and months. Any clever idea that reduces the execution time to days or hours is therefore paramount.
This chapter gives a brief introduction to arrays – how they are created and what they can be used for. Array computing usually ends up with a lot of numbers. It may be very hard to understand what these numbers mean by just looking at them. Since the human is a visual animal, a good way to understand numbers is to visualize them. In this chapter we concentrate on visualizing curves that reflect functions of one variable, e.g., curves of the form y = f(x). A synonym for curve is graph, and the image of curves on the screen is often called a plot. We will use arrays to store the information about points along the curve. It is fair to say that array computing demands visualization and visualization demands arrays.
All program examples in this chapter can be found as files in the folder src/plot.
Hans Petter Langtangen
6. Files, Strings, and Dictionaries
Abstract
Files are used for permanent storage of information on a computer. From previous computer experience you are hopefully used to save information to files and open the files at a later time for inspection again. The present chapter tells you how Python programs can access information in files (Chapter 6.1) and also create new files (Chapter 6.5). The chapter builds on programming concepts introduced in Chapters 1–5.
Since files often contain structured information that one wants to map to objects in a running program, there is a need for flexible objects where various kinds of other objects can be stored. Dictionaries are very handy for this purpose and are described in Chapter 6.2.
Information in files often appear as pure text, so to interpret and extract data from files it is sometimes necessary to carry out sophisticated operations on the text. Python strings have many methods for performing such operations, and the most important functionality is described in Chapter 6.3.
The World Wide Web is full of information and scientific data that may be useful to access from a program. Chapter 6.4 tells you how to read web pages from a program and interpret the contents using string operations.
The folder src/files contains all the program example files referred to in the present chapter.
Hans Petter Langtangen
7. Introduction to Classes
Abstract
A class packs a set of data (variables) together with a set of functions operating on the data. The goal is to achieve more modular code by grouping data and functions into manageable (often small) units. Most of the mathematical computations in this book can easily be coded without using classes, but in many problems, classes enable either more elegant solutions or code that is easier to extend at a later stage. In the non-mathematical world, where there are no mathematical concepts and associated algorithms to help structure the problem solving, software development can be very challenging. Classes may then improve the understanding of the problem and contribute to simplify the modeling of data and actions in programs. As a consequence, almost all large software systems being developed in the world today are heavily based on classes.
Programming with classes is offered by most modern programming languages, also Python. In fact, Python employs classes to a very large extent, but one can – as we have seen in previous chapters – use the language for lots of purposes without knowing what a class is. However, one will frequently encounter the class concept when searching books or the World Wide Web for Python programming information. And more important, classes often provide better solutions to programming problems. This chapter therefore gives an introduction to the class concept with emphasis on applications to numerical computing. More advanced use of classes, including inheritance and object orientation, is the subject of Chapter 9.
The folder src/class contains all the program examples from the present chapter.
Hans Petter Langtangen
8. Random Numbers and Simple Games
Abstract
Random numbers have many applications in science and computer programming, especially when there are significant uncertainties in a phenomenon of interest. The purpose of this chapter is to look at some practical problems involving random numbers and learn how to program with such numbers. We shall make several games and also look into how random numbers can be used in physics. You need to be familiar with Chapters 1–5 in order to study the present chapter, but a few examples and exercises will require familiarity with the class concept from Chapter 7.
The key idea in computer simulations with random numbers is first to formulate an algorithmic description of the phenomenon we want to study. This description frequently maps directly onto a quite simple and short Python program, where we use random numbers to mimic the uncertain features of the phenomenon. The program needs to perform a large number of repeated calculations, and the final answers are “only” approximate, but the accuracy can usually be made good enough for practical purposes. Most programs related to the present chapter produce their results within a few seconds. In cases where the execution times become large, we can vectorize the code. Vectorized computations with random numbers is definitely the most demanding topic in this chapter, but is not mandatory for seeing the power of mathematical modeling via random numbers.
All files associated with the examples in this chapter are found in the folder src/random.
Hans Petter Langtangen
9. Object-Oriented Programming
Abstract
This chapter introduces the basic ideas of object-oriented programming. Different people put different meanings into the term objectoriented programming: Some use the term for programming with objects in general, while others use the term for programming with class hierarchies. The author applies the second meaning, which is the most widely accepted one in computer science. The first meaning is better named object-based programming. Since everything in Python is an object, we do object-based programming all the time, yet one usually reserves this term for the case when classes different from Python’s basic types (int, float, str, list, tuple, dict) are involved.
A necessary background for the present chapter is Chapter 7. For Chapters 9.2 and 9.3 one must know basic methods for numerical differentiation and integration, for example from Appendix B. During an initial readings of the chapter, it can be beneficial to skip the more advanced material in Chapters 9.2.3–9.2.6.
All the programs associated with this chapter are found in the src/oo folder.
Hans Petter Langtangen
Backmatter
Metadaten
Titel
A Primer on Scientific Programming with Python
verfasst von
Hans Petter Langtangen
Copyright-Jahr
2011
Verlag
Springer Berlin Heidelberg
Electronic ISBN
978-3-642-18366-9
Print ISBN
978-3-642-18365-2
DOI
https://doi.org/10.1007/978-3-642-18366-9