Seite - 21 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python
Bild der Seite - 21 -
Text der Seite - 21 -
1.5 MoreBasicConcepts 21
plt.savefig(’some_plot.png’) # PNG format
plt.savefig(’some_plot.pdf’) # PDF format
plt.savefig(’some_plot.jpg’) # JPG format
plt.savefig(’some_plot.eps’) # Encanspulated PostScript format
For the readerwho is into linear algebra, itmaybeuseful toknowthat standard
matrix/vector operationsare straightforwardwith arrays, e.g.,matrix-vectormulti-
plication.What is needed though, is to create the right variable types (after having
importedanappropriatemodule). Forexample, assumeyouwould like tocalculate
thevectory (note thatboldface isused forvectorsandmatrices) asyDAx,where
A is a2 2matrix andx is a vector.Wemaydo this as illustratedby theprogram
matrix_vector_product.pyreading
from numpy import zeros, mat, transpose
x = zeros(2)
x = mat(x)
x = transpose(x)
x[0] = 3; x[1] = 2 # Pick some values
A = zeros((2,2))
A = mat(A)
A[0,0] = 1; A[0,1] = 0
A[1,0] = 0; A[1,1] = 1
# The following gives y = x since A = I, the identity matrix
y = A*x
print y
Here, x is first created as an array, just as we did above. Then the variable type
of x is changed to mat, i.e., matrix, by the line x = mat(x). This is followed
by a transpose of x from dimension 1 2 (the default dimension) to 2 1with
the statement x = transpose(x), before some test values are plugged in. The
matrixA isfirstcreatedasa twodimensionalarraywithA = zeros((2,2))before
conversionandfilling invalues takeplace. Finally, themultiplication is performed
as y = A*x. Note the number of parentheseswhen creating the two dimensional
arrayA.Running theprogramgives the followingoutputon thescreen:
[[3.]
[2.]]
1.5.8 ErrorMessagesandWarnings
Allprogrammersexperienceerrormessages,andusually toalargeextentduringthe
early learning process. Sometimes errormessages are understandable, sometimes
theyarenot. Anyway, it is important toget used to them. One idea is to startwith
aprogramthat initially isworking, and thendeliberately introduceerrors in it, one
byone. (Butrememberto takeacopyof theoriginalworkingcode!) Foreacherror,
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python
- Titel
- Programming for Computations – Python
- Untertitel
- A Gentle Introduction to Numerical Simulations with Python
- Autoren
- Svein Linge
- Hans Petter Langtangen
- Verlag
- Springer Open
- Datum
- 2016
- Sprache
- englisch
- Lizenz
- CC BY-NC 4.0
- ISBN
- 978-3-319-32428-9
- Abmessungen
- 17.8 x 25.4 cm
- Seiten
- 248
- Schlagwörter
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Kategorie
- Informatik