Page - 73 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 73 -
Text of the Page - 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, Volume Second Edition
- Title
- Programming for Computations β Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Volume
- Second Edition
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2020
- Language
- English
- License
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 356
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik