Basic Constructions [chapter]

Svein Linge, Hans Petter Langtangen
2016 Programming for Computations - Python  
Very often in life, and in computer programs, the next action depends on the outcome of a question starting with "if". This gives the possibility to branch into different types of action depending on some criterion. Let us as usual focus on a specific example, which is the core of so-called random walk algorithms used in a wide range of branches in science and engineering, including materials manufacturing and brain research. The action is to move randomly to the north (N), east (E), south (S),
more » ... or west (W) with the same probability. How can we implement such an action in life and in a computer program? We need to randomly draw one out of four numbers to select the direction in which to move. A deck of cards can be used in practice for this purpose. Let the four suits correspond to the four directions: clubs to N, diamonds to E, hearts to S, and spades to W, for instance. We draw a card, perform the corresponding move, and repeat the process a large number of times. The resulting path is a typical realization of the path of a diffusing molecule. In a computer program, we need to draw a random number, and depending on the number, update the coordinates of the point to be moved. There are many ways to draw random numbers and translate them into (e.g.) four random directions, but the technical details usually depend on the programming language. Our technique here is universal: we draw a random number in the interval OE0; 1/ and let OE0; 0:25/ correspond to N, OE0:25; 0:5/ to E, OE0:5; 0:75/ to S, and OE0:75; 1/ to W. Let x and y 29
doi:10.1007/978-3-319-32428-9_2 fatcat:thbvfvld65bp7cgktxgvwr5oai