Web-Books
in the Austria-Forum
Austria-Forum
Web-Books
Informatik
Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Page - 73 -
  • User
  • Version
    • full version
    • text only version
  • Language
    • Deutsch - German
    • English

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 -

Image of the Page - 73 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition

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
back to the  book Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition"
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
Web-Books
Library
Privacy
Imprint
Austria-Forum
Austria-Forum
Web-Books
Programming for Computations – Python