Computing Probabilities

With the mathematical rules from probability theory one may compute the probability that a certain event happens, say the probability that you get one black ball when drawing three balls from a hat with four black balls, six white balls, and three green balls. Unfortunately, theoretical calculations of probabilities may soon become hard or impossible if the problem is slightly changed. There is a simple numerical way of computing probabilities that is generally applicable to problems with...

E Visualizing a Program with Lumpy

Lumpy is a nice tool for graphically displaying the relations between the variables in a program. Consider the following program inspired by Chapter 2.1.9 , where we extract a sublist and modify the original list The point is that the change in ll is reflected in 10, but not in 12, because sublists are created by taking a copy of the original list, while ll and l0 refer to the same object. Lumpy can visually display the variables and how they relate, and thereby making it obvious that l0 and 11...

Info Erd

where we have introduced the short form y 1 P t to save space. Equation C.18 can easily be solved for Si 1 Si 1 m Y -1 2mSi -mSi-1 Y tSi - t2 kSi m wi 1 - 2wi Wi-1 t2 mg C.19 One fundamental problem arises when we try to start the computations. We know S0 and want to apply C.19 for i 0 to calculate S1. However, C.19 involves Si-1, that is, S-1, which is an unknown value at a point of time before we compute the motion. The initial conditions come to rescue here. Since dS dt 0 at t 0 or i 0 , we...

Exercises Auw

Exercise 5.1. Determine the limit of a sequence. Given the sequence make a program that computes and prints out an for n 1,2, , N. Read N from the command line. Does an approach a finite limit when n to Name of program file sequence_limit1.py. o Exercise 5.2. Determine the limit of a sequence. Solve Exercise 5.1 when the sequence of interest is given by Name of program file sequence_limit2.py. o Exercise 5.3. Experience convergence problems. Given the sequence Dn f x h - f x , h 2-n 5.42 make a...

B A General Ordinary Differential Equation

Let us briefly consider a general ordinary3 differential equations on the form where f u is a given function and the initial state uo is given. Suppose we want to compute an approximate solution of B.25 for t ranging from t 0 to t T where T gt 0 is given. As above we start by introducing the time step where n 1 is a given integer, and we let u denote an approximation of the exact solution u tk . Also as above, we replace the derivative of u with a finite difference and obtain the scheme The...

Class Hierarchy for 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...

Info Fsl

File integrate_v1.py, line 26, in lt module gt I_exact pi asin pi - sqrt 1 - pi 2 - 1 ValueError math domain error It is easy to go directly to the ValueError now, but one should always examine the output from top to bottom. If there is strange output before Python reports an error, there may be an error indicated by our print statements which causes Python to abort the program. This is not the case in the present example, but it is a good habit to start at the top of the output anyway. We see...

Info Utj

Fig. 4.15 Plot of the dimensionless temperature T z, t in the ground for two different t values and b 2. Fig. 4.15 Plot of the dimensionless temperature T z, t in the ground for two different t values and b 2. Fill lists xlist and hlist with x and h x values for uniformly spaced x coordinates in -4,4 . You may adapt the example in Chapter 4.2.1. Name of program file fill_lists.py. o Exercise 4.2. Fill arrays loop version. The aim is to fill two arrays x and h with x and h x values, where h x is...

B Exponential Growth

The example above was really not much of a differential equation, because the solution was obtained by straightforward integration. Equations of the form arise in situations where we can explicitly specify the derivative of the unknown function u. Usually, the derivative is specified in terms of the solution itself. Consider, for instance, population growth under idealized conditions as modeled in Chapter 5.1.4. We introduce the symbol v for the number of individuals at time t v corresponds to...

Info Fbx

return - 1. 6 f x 2 h f x h - 0.5 f x - 1. 3 f x-h h Here is a short example of using one of these classes to numerically differentiate the sine function4 gt gt gt from Diff import gt gt gt from math import sin gt gt gt mycos Central4 sin gt gt gt compute sin' pi gt gt gt mycos pi -1.000000082740371 Instead of a plain Python function we may use an object with a __call__method, here exemplified through the function f t a,b,c

N

For example, the Taylor polynomial for ex equals S x with fk x xk k . The purpose of the exercise is to make a movie of how S x develops and hopefully improves as an approximation as we add terms in the sum. That is, the frames in the movie correspond to plots of S x M, M 1 , S x M, M 2 , , S x M, N . animate_series fk, M, N, xmin, xmax, ymin, ymax, n, exact for creating such animations. The argument fk holds a Python function implementing the term fk x in the sum, M and N are the summation...

Oscillator V1.py

Design the class such that the above session can be carried out. Hint Use classes from the Diff and Integrator hierarchies Chapters 9.2 and 9.3 for numerical differentiation and integration with, e.g., Central2 and Trapezoidal as default methods for differentiation and integration, respectively . The method set_differentiation_method takes a subclass name in the Diff hierarchy as argument, and makes an attribute df that holds a subclass instance for computing derivatives. With...

vtk vifci J ardr w vifci tk fc

for k 1,2, Idots, n 1, while v0 0. Use this formula to fill an array v with velocity values. Now only t is given on the command line, and the a0, , an-1 values must be read from file as in Exercise 6.5. Name of program file acc2vel.py. O Exercise 6.7. Find velocity from GPS coordinates. Imagine that a GPS device measures your position at every s seconds. The positions are stored as x,y coordinates in a file src files pos. dat with the an x and y number on each line, except for the first line...

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

O

Exercise 4.29. Explain why array computations fail. The following loop computes the array y from x gt gt gt x linspace 0, 1, 3 gt gt gt y zeros len x gt gt gt for i in range len x y i x i 4 gt gt gt for xi, yi in zip x, y yi xi 5 leaves y unchanged. Why Explain in detail what happens in each pass of this loop and write down the contents of xi, yi, x, and y as the loop

Info Gjm

2. Coding of the formula in Python C 5.0 9 F - 32 3. Establish a test case from the c2f.py program in Chapter 1.3.3 we know that C 21 corresponds to F 69.8. We can therefore, in our new program, set F 69.8 and check that C 21. The output from a run can be appended as a triple quoted string at the end of the program. 28 Alternatively, the output lines can be inserted as comments, but using a multi-line string requires less typing. Technically, a string object is created, but not assigned to any...

Monte Carlo Integration

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

iiTs T

Suppose now you take a hot pizza out of the oven. The temperature of the pizza is 200 C at t 0 and 180 C after 20 seconds, in a room with temperature 20 C. Find an estimate of h from the formula above. Solve 9.48 to find the evolution of the temperature of the pizza. Use class ForwardEuler or RungeKutta4, and supply a terminate function to the solve method so that the simulation stops when T is sufficiently close to the final room temperature Ts. Plot the solution. Name of program file...

Info Ecd

The reason why we do not get exactly 1.0 as answer in the first case, is because 1 49 is not correctly represented in the computer. Also 1 51 has an inexact representation, but the error does not propagate to the final answer. To summarize, errors21 in floating-point numbers may propagate through mathematical calculations and result in answers that are only approximations to the exact underlying mathematical values. The errors in the answers are commonly known as round-off errors. As soon as...

Info Jmx

Pretty Print. To print a list a, print a can be used, but the pprint and scitools. pprint2 modules and their pprint function give a nicer layout of the output for long and nested lists. The scitools.pprint2 module has the possibility to better control the output of floating-point numbers. If Tests. The if-elif-else tests are used to branch the flow of statements. That is, different sets of statements are executed depending on whether a set of conditions is true or not. value -1 elif x gt 0 and...

B A Model for the Spread of a Disease

Mathematical models are used intensively to analyze the spread of infectious diseases5. In the simplest case, we may consider a population, that is supposed to be constant, consisting of two groups the susceptibles S who can catch the disease, and the infectives I who have the disease and are able to transmit it. A system of differential equations modelling the evolution of S and I is given by Here r and a are given constants reflecting the characteristics of the epidemic. The initial...

Polynomial Dict1.py

Exercise 7.2. 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...

B A Simple Pendulum

Simple Pendulum Equation

So far we have considered scalar ordinary differential equations, i.e., equations with one single function u t as unknown. Now we shall deal 4 Leonhard Paul Euler, 17o7-1783. A pioneering Swiss mathematician and physicist who spent most of his life in Russia and Germany. Euler is one of the greatest scientists of all time, and made important contributions to calculus, mechanics, optics, and astronomy. He also introduced much of the modern terminology and notation in mathematics. Explicit Euler...

Info Fnu

In a program we want to access these density data. A dictionary with the name of the substance as key and the corresponding density as value seems well suited for storing the data. Solution. We can read the densities.dat file line by line, split each line into words, use a float conversion of the last word as density value, and the remaining one or two words as key in the dictionary. words line.split density float words -1 substance words 0 ' ' words 1 else densities substance density...

A Py

after n years. Make a program for computing how much money 1000 euros have grown to after three years with 5 interest rate. Name of program file interest_rate.py. o Exercise 1.6. Find error s in a program. Suppose somebody has written a simple one-line program for computing sin 1 x 1 print 'sin g g' x, sin x Type in this program and try to run it. What is the problem o Type the following program in your editor and execute it. If your program does not work, check that you have copied the code...

Read 2columns.py

Exercise 6.1. Read a two-column data file. The file src files xy.dat contains two columns of numbers, corresponding to x and y coordinates on a curve. The start of the file looks as this -1.0000 -0.0000 -0.9933 -0.0087 Make a program that reads the first column into a list x and the second column into a list y. Then convert the lists to arrays, and plot the curve. Print out the maximum and minimum y coordinates. Hint Read the file line by line, split each line into words, convert to float, and...

B Exercises

Exercise B.1. Solve a nonhomogeneous linear ODE. Solve the ODE problem using the Forward Euler method. Choose t 0.25. Plot the numerical solution together with the exact solution u t 1 2e2t. Name of program file Exercise B.2. Solve a nonlinear ODE. Solve the ODE problem using the Forward Euler method. The exact solution reads u t e for q 1 and u t t 1 - q 1 1 1-q for q gt 1 and t 1 - q 1 gt 0. Read q, t, and T from the command line, solve the ODE, and plot the numerical and exact solution. Run...

Info Pua

Fig. 8.6 Particle positions circles , histogram piecewise constant curve , and vertical lines indicating the mean value and the standard deviation from the mean after a one-dimensional random walk of 2000 particles for 30 steps. positions zeros np for step in range ns mean_pos, stdev_pos mean positions , std positions print mean_pos, stdev_pos nbins int 3 sqrt ns no of intervals in histogram pos, freq compute_histogram positions, nbins, plot positions, zeros np , 'ko3', pos, freq, 'r', axis min...

ax bx c

-b Vb2 - 4ac -b - Vb2 - 4ac . . Why does the following program not work correctly a 2 b 1 c 2 from math import sqrt q sqrt b b - 4 a c x1 -b q 2 a x2 -b - q 2 a print x1, x2 Hint Compute all terms in 1.20 with the aid of a calculator, and compare with the corresponding intermediate results computed in the program you need to add some print statements to see the result of q, -b q, and 2 a . O

Exercises 1

Exercise 2.1. Make a Fahrenheit-Celsius conversion table. Modify the c2f_table_while.py program so that it prints out a table with Fahrenheit degrees 0,10, 20, , 100 in the first column and the corresponding Celsius degrees in the second column. Name of program file c2f_table_while.py. O Write a program that generates all odd numbers from 1 to n. Set n in the beginning of the program and use a while loop to compute the numbers. Make sure that if n is an even number, the largest generated odd...

dashdot line

During programming, you can find all these details in the documentation of the plot function. Just type help plot in an interactive Python shell or invoke pydoc with scitools.easyviz.plot. This tutorial is available through pydoc scitools.easyviz. We remark that in the Gnuplot program all the different line types are drawn as solid lines on the screen. The hardcopy chooses automatically different line types solid, dashed, etc. and not in accordance with the line type specification. Lots of...

Info Afr

The animation is created by varying s in a loop and for each s issue a plot command. A moving curve is then visible on the screen. One can also make a movie file that can be played as any other computer movie using a standard movie player. To this end, each plot is saved to a file, and all the files are combined together using some suitable tool, which is reached through the movie function in Easyviz. All necessary steps will be apparent in the complete program below, but before diving into the...

Info Vse

Fig. 8.6 Particle positions circles , histogram piecewise constant curve , and vertical lines indicating the mean value and the standard deviation from the mean after a one-dimensional random walk of 2000 particles for 30 steps. The values are now either 1 or 2, but we want 1 or 1. A simple scaling and translation of the numbers transform the 1 and 2 values to 1 and 1 values Then we can create a two-dimensional array out of moves such that moves i,j is the i-th step of particle number j It does...

Info Adk

5. Look up information. Our test function f x sin-1 x must be evaluated in the program. How can we do this We know that many common mathematical functions are offered by the math module. It is therefore natural to check if this module has an inverse sine function. The best place to look for Python modules is the Python Library Reference see Chapter 2.4.3 . We go to the index of this manual, find the math entry, and click on it. Alternatively, you can write pydoc math on the command line....