Differentiation Becomes Finite Differences

Probably, the following formulas are well known to you But why is differentiation so important The reason is quite simple The derivative is a mathematical expression of change. And change is, of course, essential in modeling various phenomena. If we know the state of a system, and we know the laws of change, then we can, in principle, compute the future of that system. Appendix B treats this topic in detail. Chapter 5 also computes the future of systems, based...

Ve rr Si Page

Fig. 6.4 Example of what a very simple HTML file looks like in a web browser. < body bgcolor orange> < h1> A Very Simple HTML Page< h1> < -- headline --> Web pages are written in a language called < a Ordinary text is written as ordinary text, but when we need links, headlines, lists, < ul> < li> < em> emphasized words< em> , or < li> < b> boldface text< b> , < ul> we need to embed the text inside HTML tags. We can also insert GIF or PNG images,...

About the Problem Motion and Forces in Physics C The Physical Problem

We shall study a simple device which models oscillating systems. A box with mass m and height b is attached to a spring of length L as shown in Figure C.1. The end of the spring is attached to a plate which Fig. C.1 An oscillating system with a box attached to a spring. Fig. C.1 An oscillating system with a box attached to a spring. we can move up and down with a displacement w(t), where t denotes time. There are two ways the box can be set in motion we can either stretch or compress the string...

Cf

2.1.6 Alternative Implementations with Lists and Loops We have already solved the problem of printing out a nice-looking conversion table for Celsius and Fahrenheit degrees. Nevertheless, there are usually many alternative ways to write a program that solves a specific problem. The next paragraphs explore some other possible Python constructs and programs to store numbers in lists and print out tables. The various code snippets are collected in the program file c2f_table_lists.py. While Loop...

How to Debug

Most programmers will claim that writing code consumes a small portion of the time it takes to develop a program - the major portion of the work concerns testing the program and finding errors1. Newcomers to programming often panic when their program runs for the first time and aborts with a seemingly cryptic error message. How do you approach the art of debugging This appendix summarizes some important working habits in this respect. Some of the tips are useful for problem solving in general,...

D pg

Make a program for computing d in (3.7) when the initial car velocity v0 and the friction coefficient p are given on the command line. Run the program for two cases v0 120 and v0 50 km h, both with p 0.3 (p is dimensionless). (Remember to convert the velocity from km h to m s before inserting the value in the formula ) Name of program file stopping_length.py. o Exercise 3.22. Check if mathematical rules hold on a computer. Because of round-off errors, it could happen that a mathematical rule...

Variable Number of Function Arguments

Arguments to Python functions are of four types 1. positional arguments, where each argument has a name, 2. keyword arguments, where each argument has a name and a default value, 3. a variable number of positional arguments, where each argument has no name, but just a location in a list, 4. a variable number of keyword arguments, where each argument is a (name, default value) pair in a dictionary. The corresponding general function definition can be sketched as def f(pos1, pos2, key1 val1, key2...

Example Class for Complex Numbers

Imagine that Python did not already have complex numbers. We could then make a class for such numbers and support the standard mathematical operations. This exercise turns out to be a very good pedagogical example of programming with classes and special methods. The class must contain two attributes the real and imaginary part of the complex number. In addition, we would like to add, subtract, multiply, and divide complex numbers. We would also like to write out a complex number in some...

F ut u U

The latter type involves n equations with n unknown functions u(i)(t), i 0, , n 1 In addition, we need n initial conditions for a system with n equations and unknowns u(i)(0) u i), i 0, ,n 1. (9.19) It is common to collect the functions u( ),u(1), ,u(n-1) in a vector and the initial conditions also in a vector In that case, (9.18) and (9.19) can be written as (9.17). We may take important advantage of this fact in an implementation If the vectors are represented...

Info

Note the difference between just writing filestr and writing print filestr. The former dumps the string with newlines as backslash n characters, while the latter is a pretty print where the string is written out without quotes and with the newline characters as visible line shifts2. Having the numbers inside a string instead of inside a file does not look like a major step forward. However, string objects have many useful functions for extracting information. A very useful feature is split...

Making Modules

Sometimes you want to reuse a function from an old program in a new program. The simplest way to do this is to copy and paste the old source code into the new program. However, this is not good programming practice, because you then over time end up with multiple identical versions of the same function. When you want to improve the function or correct a bug, you need to remember to do the same update in all files with a copy of the function, and in real life most programmers fail to do so. You...

More Examples on Classes

The use of classes to solve problems from mathematical and physical sciences may not be so obvious. On the other hand, in many administrative programs for managing interactions between objects in the real world the objects themselves are natural candidates for being modeled by classes. Below we give some examples on what classes can be used to model. The concept of a bank account in a program is a good candidate for a class. The account has some data, typically the name of the account holder,...

Preface

The aim of this book is to teach computer programming using examples from mathematics and the natural sciences. We have chosen to use the Python programming language because it combines remarkable power with very clean, simple, and compact syntax. Python is easy to learn and very well suited for an introduction to computer programming. Python is also quite similar to Matlab and a good language for doing mathematical computing. It is easy to combine Python with compiled languages, like Fortran,...

Simple Function Classes

Classes can be used for many things in scientific computations, but one of the most frequent programming tasks is to represent mathematical functions which have a set of parameters in addition to one or more independent variables. Chapter 7.1.1 explains why such mathematical functions pose difficulties for programmers, and Chapter 7.1.2 shows how the class idea meets these difficulties. Chapters 7.1.3 presents another example where a class represents a mathematical function. More advanced...

Simple Games

This section presents the implementation of some simple games based on drawing random numbers. The games can be played by two humans, but here we consider a human versus the computer. The Game. The computer determines a secret number, and the player shall guess the number. For each guess, the computer tells if the number is too high or too low. The Implementation. We let the computer draw a random integer in an interval known to the player, let us say 1,100 . In a while loop the program prompts...

Static Methods and Attributes

Up to now, each instance has its own copy of attributes. Sometimes it can be natural to have attributes that are shared among all instances. For example, we may have an attribute that counts how many instances 8 This may sound scary and highly illegal to C, C++, Java, and C programmers, but it is natural and legal in many other languages - and sometimes even useful. that have been made so far. We can exemplify how to do this in a little class for points (x, y, z) in space def __init__(self, x,...

List of Exercises

Exercise 1.1 Compute Exercise 1.2 Write a Hello, World Exercise 1.3 Convert from meters to British length units 43 Exercise 1.4 Compute the mass of various substances 43 Exercise 1.5 Compute the growth of money in a bank 43 Exercise 1.6 Find error s in a Exercise 1.7 Type in program text Exercise 1.8 Type in programs and debug them 44 Exercise 1.9 Evaluate a Gaussian Exercise 1.10 Compute the air resistance on a football 45 Exercise 1.11 Define objects in IPython Exercise 1.12 How to cook the...

Exercises

Make a program that simulates flipping a coin N times. Print out tail or head for each flip and let the program count the number of heads. Hint Use r random.random and define head as r lt 0.5 or draw an integer among 1, 2 with r random.randint 1,2 and define head when r is 1. Name of program file flip_coin.py. o Exercise 8.2. Compute a probability. What is the probability of getting a number between 0.5 and 0.6 when drawing uniformly distributed random numbers from the interval 0,1 To answer...

Class Hierarchy for Geometric Shapes

Oop Geometric Shapes

Our next examples concern drawing geometric shapes. We know from Chapter 4 how to draw curves y f x , but the point now is to construct some convenient software tools for drawing squares, circles, arcs, springs, wheels, and other shapes. With these tools we can create figures describing physical systems, for instance. Classes are very suitable for implementing the software because each shape is naturally associ ated with a class, and the various classes are related to each other through a...

Example Solution of Differential Equations

An ordinary differential equation ODE , where the unknown is a function u t , can be written in the generic form In addition, an initial condition, u 0 u0, must be associated with this ODE to make the solution of 7.3 unique. The function f reflects an expression with u and or t. Some important examples of ODEs and their corresponding forms of f are given below. 1. Exponential growth of money or populations where a is a given constant expressing the growth rate of u. 2. Logistic growth of a...

Random Walk in Two Space Dimensions

A random walk in two dimensions performs a step either to the north, south, west, or east, each one with probability 1 4. To demonstrate this process, we introduce x and y coordinates of np particles and draw random numbers among 1, 2, 3, or 4 to determine the move. The positions of the particles can easily be visualized as small circles in an xy coordinate system. The algorithm described above is conveniently expressed directly as a complete working program def random_walk_2D np, ns, plot_step...

Monte Carlo Integration

Montecarlo Integration Error

One of the earliest applications of random numbers was numerical computation of integrals, that is, a non-random deterministic problem. Here we shall address two related methods for computing fa f x dx. 8.5.1 Standard Monte Carlo Integration Let be uniformly distributed random numbers between a is an approximation to the integral fb f x dx. This method is usually referred to as Monte Carlo integration. It is easy to interpret 8.7 . A well-known result from calculus is that the integral of a...

Random Walk in One Space Dimension

In this section we shall simulate a collection of particles that move around in a random fashion. This type of simulations are fundamental in physics, biology, chemistry as well as other sciences and can be used to describe many phenomena. Some application areas include molecular motion, heat conduction, quantum mechanics, polymer chains, population genetics, brain research, hazard games, and pricing of financial instruments. Imagine that we have some particles that perform random moves, either...

Polynomial Dict1.py

Make a very simple class. Make a class Simple with one attribute i, one method double, which replaces the value of i by i i, and a constructor that initializes the attribute. Try out the following code for testing the class s2 Simple 'Hello' s2.double s2.double print s2.i s2.i 100 print s2.i Before you run this code, convince yourself what the output of the print statements will be. Name of program file Simple.py. o Exercise 7.3. Extend the class from Ch. 7.2.1. Add an attribute...