Lektion 7

In [12]:
import numpy as np
import numpy.linalg as LA   #numpy linalg modul importieren
# oder mit
#from numpy import linalg as LA

Lösung linearer Gleichungssysteme

Zuerst muss das "Lineare Algebra"-Modul von numpy importiert werden

In [14]:
A = np.array([[1, 2, 3], [0, 3, 7], [1, 1, 1]])
b = np.array([14, 28, 6])

# löse LGS Ax=b nach x
x = LA.solve(A, b)
x
Out[14]:
array([2., 0., 4.])

Man kann auch die Inverse von A berechnen und "x" so berechnen (wird NICHT empfohlen)

In [20]:
Ainv = LA.inv(A)
x2 = Ainv@b
np.allclose(x, x2)
Out[20]:
True

Wie man sieht, sind die Ergebnisse (fast) gleich.

Operationen auf Arrays/Matrizen

In [21]:
A = np.array([[10, -7, 0], \
              [-3, 2, 6], \
              [5, -100, 5]])
A
Out[21]:
array([[  10,   -7,    0],
       [  -3,    2,    6],
       [   5, -100,    5]])
In [22]:
# erste Zeile von A
A[0]
Out[22]:
array([10, -7,  0])

Zeilentausch:

$A[[i, j]] = A[[j, i]]$ vertauscht Zeile i mit Zeile j

In [23]:
A[[1, 2]] = A[[2, 1]]
A
Out[23]:
array([[  10,   -7,    0],
       [   5, -100,    5],
       [  -3,    2,    6]])

x = y ist eine Kurzschreibweise für x = x y. Das gibt es auch für +, -, /

In [24]:
i = 3
i *= 2
i
Out[24]:
6
In [25]:
# Addiere das k-Fache der 2. Zeile zur 3. Zeile
k = 2
A[2] += k*A[1]
A
Out[25]:
array([[  10,   -7,    0],
       [   5, -100,    5],
       [   7, -198,   16]])
In [26]:
# Achtung
A[2] += 1.2*A[1]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-26-4262fe4e9d6d> in <module>
      1 # Achtung
----> 2 A[2] += 1.2*A[1]

TypeError: Cannot cast ufunc add output from dtype('float64') to dtype('int64') with casting rule 'same_kind'
In [27]:
# Fehlerbehebung

A = A.astype(float)
A[2] += 1.2*A[1]
A
Out[27]:
array([[  10.,   -7.,    0.],
       [   5., -100.,    5.],
       [  13., -318.,   22.]])
In [28]:
# oder von Anfang an als float
A = np.array([[10, -7, 0], \
              [-3, 2, 6], \
              [5, -100, 5]], dtype='float')
A
Out[28]:
array([[  10.,   -7.,    0.],
       [  -3.,    2.,    6.],
       [   5., -100.,    5.]])