Seite - 73 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
Bild der Seite - 73 -
Text der Seite - 73 -
3.3 Branching(if,elifandelse) 73
d = 1 # step length (e.g., in meter)
x = np.zeros(N+1) # x coordinates
y = np.zeros(N+1) # y coordinates
x[0] = 0; y[0] = 0 # set initial position
for i in range(0, N, 1):
r = random.random() # random number in [0,1)
if 0 <= r < 0.25: # move north
y[i+1] = y[i] + d
x[i+1] = x[i]
elif 0.25 <= r < 0.5: # move east
x[i+1] = x[i] + d
y[i+1] = y[i]
elif 0.5 <= r < 0.75: # move south
y[i+1] = y[i] - d
x[i+1] = x[i]
else: # move west
x[i+1] = x[i] - d
y[i+1] = y[i]
# plot path (mark start and stop with blue o and *, respectively)
plt.plot(x, y, ’r--’, x[0], y[0], ’bo’, x[-1], y[-1], ’b*’)
plt.xlabel(’x’); plt.ylabel(’y’)
plt.show()
Here, the initial position is explicitly set, even if x[0] and y[0] are known to
be zero already. We do this, since the initial position is important, and by setting it
explicitly, it is clearlynotaccidentalwhat thestartingposition is.Note that if a step
is taken in thex-direction, they-coordinate is unchanged,andviceversa.
Executing the program produces the plot seen in Fig.3.2, where the initial and
final positions are marked in blue with a circle and a star, respectively. Remember
that pseudo-randomnumbersare involvedhere, meaning that two consecutive runs
will generallyproducetotallydifferentpaths.
Fig. 3.2 Onerealizationofarandomwalk(N-E-S-W)witha1000steps. Initialandfinalpositions
are marked inblue witha circle and a star, respectively
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
- Titel
- Programming for Computations – Python
- Untertitel
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Band
- Second Edition
- Autoren
- Svein Linge
- Hans Petter Langtangen
- Verlag
- Springer Open
- Datum
- 2020
- Sprache
- englisch
- Lizenz
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Abmessungen
- 17.8 x 25.4 cm
- Seiten
- 356
- Schlagwörter
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Kategorie
- Informatik