Numpy Vorlesungs-Notebook
Vorlesungs-Notebook¶
In [1]:
import numpy as np
Die Einträge zweier Listen addieren (ohne Numpy)¶
In [2]:
x = [1, 2, 3]
y = [4, 5, 6]
result = []
for i, j in zip(x, y):
result.append(i + j)
print(result)
-> ein bisschen umständlich
Mit Numpy:¶
In [3]:
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
result = x + y
print(result)
In [4]:
print(x - y)
print(x * y)
print(x ** y)
In [5]:
type(x)
Out[5]:
In [6]:
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
In [7]:
print(matrix)
In [8]:
matrix + matrix
Out[8]:
In [9]:
matrix + np.array([1, 2, 3])
Out[9]:
In [10]:
matrix + np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
Out[10]:
In [11]:
arr = np.array([1, 2, 3], dtype=np.int64)
In [12]:
division = matrix / arr
print(division, division.dtype)
ganzzahl_division = matrix // arr
print(ganzzahl_division, ganzzahl_division.dtype)
In [13]:
mit_nullen_gefüllt = np.zeros((4, 3, 3), dtype=np.int32)
print(mit_nullen_gefüllt)
In [14]:
# range von Zahlen
range_arr = np.arange(0, 100)
print(range_arr)
In [15]:
# Berechne den Sinus im Interval von 0 bis 2 Pi
x = np.linspace(0, 2 * np.pi, 50)
y = np.sin(x)
In [16]:
print(y.max())
print(y.min())
print(y.mean())
print(y.std())
In [17]:
def welche_dimension_hat_mein_array(arr):
shape = arr.shape
dimension = len(shape)
return dimension
In [18]:
arr = np.zeros((15, 1, 2, 3, 5, 1,7, 8))
In [19]:
print("Dimension des Arrays:", welche_dimension_hat_mein_array(arr))
In [20]:
arr = np.array(list("abcdefghiklmnopqrstuvwxyz"))
arr2d = arr[:20].reshape((4, 5))
In [21]:
x = "abcdefghiklmnopqrstuvwxyz"
In [22]:
x[3:5]
Out[22]:
In [23]:
arr2d[-2, -3:]
Out[23]:
In [24]:
arr2d
Out[24]:
In [25]:
matrix * np.array([1, 2, 3])
Out[25]:
In [26]:
masses = np.array([1, 2, 3])
In [27]:
masses.sum()
Out[27]:
In [28]:
position_atom1 = [0, 0, 0]
position_atom2 = [2.5, 4, 1.3]
position_atom3 = [8, -3, 7.5]
masses = np.array([0.5, 1.3, 2.7])
atoms = np.array([position_atom1,
position_atom2,
position_atom3]
)
gewichtete_koordinaten = atoms * masses.reshape((3, 1)) / masses.sum()
In [29]:
gewichtete_koordinaten.sum(axis=0)
Out[29]:
In [30]:
# noch ein sum Beispiel
print(matrix)
print(matrix.sum(axis=0, keepdims=True))
In [31]:
print(matrix)
print(matrix.sum(axis=1, keepdims=True))
Monte Carlo¶
In [32]:
x_0 = 0.5
y_0 = 0.3
x_0**2 + y_0**2 <= 1
Out[32]:
In [33]:
gesamt_anzahl_punkte = 10_000
x = np.random.random(gesamt_anzahl_punkte)
y = np.random.random(gesamt_anzahl_punkte)
punkte_drinnen = x**2 + y**2 <= 1
print(punkte_drinnen.dtype)
In [34]:
import matplotlib.pyplot as plt
plt.figure().set_size_inches((5, 5))
plt.scatter(x[punkte_drinnen], y[punkte_drinnen], s=2)
plt.scatter(x[~punkte_drinnen], y[~punkte_drinnen], s=2)
plt.show()
In [ ]: