matmul_start.py
import random
import time
#Set a random seed
random.seed(42)
# Define the range for random numbers
min_value = 1 # Minimum value
max_value = 100 # Maximum value
# Generate the two lists of 10_000_000 random numbers each
list1 = [random.randint(min_value, max_value) for _ in range(10000000)]
list2 = [random.randint(min_value, max_value) for _ in range(10000000)]
start_time = time.perf_counter()
# Continue here:
time.perf_counter()
zip()
um zwei Listen gleichzeitig zu durchlaufenmatmul_solution_native.py
# Start the timer
start_time = time.perf_counter()
result = 0
for first_number, second_number in zip(list1, list2):
multiplication_result= first_number * second_number
result = result + multiplication_result
print("--- %s seconds ---" % (time.perf_counter() - start_time))
print(result)
numpy
→ normalerweise mit Alias np
numpy
Arraysnp.matmul()
bzw. @
für die Matrixmultiplikationmatmul_solution_numpy.py
# Paket für numerische Aufgaben im Python
import numpy as np
# Umwandlung der Listen in numpy arrays
# vgl. Konstruktor
array1 = np.array(list1, dtype=np.int64)
array2 = np.array(list2, dtype=np.int64)
# %%
start_time = time.perf_counter()
# Aufruf der Funktion für Matrixmultiplikation des Pakets numpy
result = np.matmul(array1, array2)
print("--- %s seconds ---" % (time.perf_counter() - start_time))
print(result)
numpy
-O3
optimierenmatmul_solution_c.c
int main(){
int amt = 10000000;
int* list1 = malloc(sizeof(int) * amt);
int* list2 = malloc(sizeof(int) * amt);
if(list1 == NULL) { printf("Not enough memory!"); return -1; }
if(list2 == NULL) { printf("Not enough memory!"); return -1; }
for(int i = 0; i < amt; i++){
list1[i] = (rand() % 100) + 1;
list2[i] = (rand() % 100) + 1;
}
//Start matrix multiplication
long result = 0;
clock_t begin = clock();
for(int i = 0; i < amt; i++){
result += list1[i] * list2[i];
}
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("Execution time: %f\n Result is %ld\n", time_spent, result);
free(list1); free(list2);
return 0;
}
numpy
Praktisches Arbeiten mit numpy
in Python
numpy.ndarray
)dtype
) sammelt → unterscheidet sich dadurch von Listen# Zweidimensionales Array
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
# Form des Arrays
a.shape
#> (3,4)
# Typ der Zahlen im Array
a.dtype
#> dtype('int32')
# Zugriff auf erste Zeile
print(a[0])
#> array([1 2 3 4])
# Zugriff auf zweites Element der ersten Zeile
print(a[0][1])
#> 2
list
-Objekten erstellt werdennumpy
enthaltennp.zeros(2)
#> array([0., 0.])
np.arange(4)
#> array([0, 1, 2, 3]
np.linspace(0, 10, num=5)
#> array([ 0., 2.5, 5., 7.5, 10.])
np.eye(3)
#>array([[1., 0., 0.],
#> [0., 1., 0.],
#> [0., 0., 1.]])
np.logspace(1, 3, num=5)
#> array([10., 31.6227766, 100., 316.22776602, 1000.])
np.empty([2, 2]) # uninitialisierte Werte --> wie in C(++)
#> array([[ -9.74499359e+001, 6.69583040e-309],
#> [ 2.13182611e-314, 3.06959433e-309]])
a = np.array([[1 , 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
c = a[(a > 2) & (a < 11)]
print(c)
#> [ 3 4 5 6 7 8 9 10]
numpy.ndarray
-Klasse verfügbarnumpy
-Paketsdata = np.array([1, 2, -3, 10, 15, -20])
data.max()
#> 15.0
data.min()
#> -20.0
data.sum()
#> 5.0
data.mean()
#> 0.8333333333333334
np.argmax(data)
#> 4
np.resize(data, (2, 3))
#>array([[ 1, 2, -3],
#> [ 10, 15, -20]])
numpy
Arrays implementiert
scalar * matrix
matrix + matrix
np.square(...)
numpy
ermöglicht Operationen auf Arrays unterschiedlicher Forma = np.array([1, 2, 3])
b = 2
print(a * b)
#> array([2, 4, 6])
f(x)
wird der Skalar b
"ausgedehnt" auf die Größe von a
def f(a):
b = 1
return a + b
arr = np.array([1, 2, 3, 4, 5])
print(f(arr))
numpy
lösen
numpy
berechnet werdennumpy_example_filters_inclass_start.ipynb
numpy_example_filters.ipynb
matplotlib
umsetzbarmatplotlib
Plots sind aus "Bausteinen" (siehe rechts) aufgebautscatter.py
import numpy as np
import matplotlib.pyplot as plt
# generate data to be plotted
x = np.arange(0, 10, 0.1)
y = np.random.rand(100)
# create figure and axis
# to plot on
fig, ax = plt.subplots()
ax.plot(
x, #data to plot
y, #data to plot
marker='o', #opt. marker style
linestyle='None' #opt. linestyle
)
plt.show() #actually show it
matplotlib
bietet viele Möglichkeiten zur Anpassung der Plotsax.plot(
x, y,
color='g',
marker='o',
markersize=12,
markevery=25,
markerfacecolor='b',
markeredgecolor='r',
linestyle='--',
linewidth=2,
label="Datenpunkte"
)
color
: Gibt Farbe anmarker
& markersize
: Geben Form & Größe der Marker anmarkevery
: Gibt an, wie oft ein Marker gezeichnet wirdmarkerfacecolor
& markeredgecolor
: Farbe des Markerslinestyle
& linewidth
: Geben Stil & Breite der Linie anlabel
: Legendeneintrag für dieses Elementstyling.py
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0.1, 10*np.pi, 1e3)
y = np.sin(x)
#create figure and axis
fig, ax = plt.subplots()
ax.plot(
x, y,
color='g',
marker='o',
markersize=12,
markevery=25,
markerfacecolor='b',
markeredgecolor='r',
linestyle='--',
linewidth=2,
label="Datenpunkte"
)
plt.tight_layout()
plt.show()
#plt.savefig("plot.svg")
color = b
: blaucolor = g
: grüncolor = k
: schwarzcolor = "mediumseagreen"
: color = "0.75"
color = "#eeefff"
color = [0.1, 0.3, 0.9]
color = [28, 69, 113]
→ sind mit 8-Bit Farbtiefe kodiertcolor = [28/255, 69/255, 113/255]
color = [0.11, 0.27, 0.44]
*.bmp
, *.png
, *.jpg
, *.gif
, *.tiff
, etc.*.pdf
, *.svg
, *.eps
, etc.# Beispiel für das Speichern als Vektorgrafik
plt.savefig("test.pdf")
"tidy data"
Prinzipienmatplotlib
weiter zu vertiefen kann das hier verlinkte Notebook bearbeitet werden.numpy
sondern implementieren Sie die Berechnung selbst → dies ist durch aufstellen & lösen eines linearen Gleichungssystems möglich