Page - 50 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 50 -
Text of the Page - 50 -
50 2 AFewMoreSteps
In [5]: x
Out[5]: array([ 0., 1., 2.])
Note the use of “dots” to get floating point numbers and that we call arraywith
bracketed12 numbers, i.e.,[0, 1, 2]and[0., 1., 2.].
2.3.2 IndexinganArrayfromtheEnd
Byuseofaminussign, theelementsofanarraymaybeindexedfromtheend,rather
fromthebeginning.That is,withourarrayxhere,wecouldgetholdof theverylast
element by writing x[-1], the second last element by writing x[-2], and so on.
Continuingtheprevious interactivesession,we maywrite
In [6]: x[-1]
Out[6]: 2.0
In [7]: x[-2]
Out[7]: 1.0
In [8]: x[-3]
Out[8]: 0.0
2.3.3 IndexOutofBounds
A typical error to make when working with arrays, is to accidentally use an illegal
index.With thearrayx inourongoingdialogue,wemay illustrate thisby
In [9]: x[3]
Traceback (most recent call last):
File "<ipython-input-18-ed224ad0520d>", line 1, in <module>
x[3]
IndexError: index 3 is out of bounds for axis 0 with size 3
Ourindex3is illegalandweget theerrormessageshown.Fromtheabove,it should
beclear that legalindicesare0,1and2.Alternatively,if indexingfromtheend, legal
indicesare−1,−2and−3.Note thatcounting is a bit “different” then, causing−3
tobea legal index(aswesaw above),while3 isnot.
2.3.4 CopyinganArray
Copyingarraysrequiressomecare,ascanbeseennext,whenwetry tomakeacopy
of thexarrayfromabove:
In [10]: y = x
In [11]: y
Out[11]: array([ 0., 1., 2.]) # ...as expected
12 The arguments toarrayare two examples of lists,which will be addressed in Sect.5.1.
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