Skip to content

Python for HfT

Lineare Gleichungssysteme Lösen

import numpy as np
a = np.array([[1,2], [3,2]])
b = np.array([19, 29])
# 1*x0 + 2*x1 = 19
# 3*x0 + 2*x1 = 29
x = np.linalg.solve(a, b)
np.dot(a, x)
np.allclose(np.dot(a,x),b)

Mit komplexen Zahlen rechnen

1 + 2j
complex(1, 2)
z = 1 + 2j
abs(z)
z.real
z.imag
z**3
import cmath
cmath.sin(z)
cmath.exp(z)
cmath.rect(1, cmath.pi/3)

Mehrdimensionale Matrizen

import numpy as np

m = np.arange(12)
m = m.reshape(2,3,2)
m[1]
m[1][2]
m[1][2][0]
m[:,2,:]

def f(i,j,k):
    return (i + 3*j + 5*k)

np.fromfunction(f, (2,2,2))

Daten in 2D darstellen

import matplotlib.pyplot as plt

t = np.linspace(0, 2*np.pi, 500)
plt.plot(t, np.sin(t))
plt.show()

Daten in 3D darstellen

from mpl_toolkits.mplot3d import Axes3D # Needed for 3d plots

ax = plt.axes(projection='3d')
z = np.linspace(0, 1, 100)
x = z * np.sin(20 * z)
y = z * np.cos(20 * z)
ax.scatter(x, y, z, c = x+y)
plt.show()

Animationen (movies)

Tools → Preferences → Ipython Console → Graphics → Graphics Backend → Backend: “automatic”

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()

x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))

def animate(i):
    line.set_ydata(np.sin(x + 2*i*np.pi/100.0) *np.cos(2*i*np.pi/200))  # update the data
    return line,

def init():
    line.set_ydata(np.ma.array(x, mask=True))
    return line,

ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init,
              interval=25, blit=True)
plt.show()

Fourier Transformation

import numpy as np
import matplotlib.pyplot as plt

N = 1000
T = 0.01
x = np.linspace(0.0, N*T, N)
y = np.where(abs(x)<=0.5, 1, 0) # Rectangular function
yf = np.fft.fft(y)
xf = np.linspace(0.0, 1.0/(2.0*T), N//2)

fig, ax = plt.subplots()
ax.plot(xf, 2.0/N * yf[:N//2])
plt.show()

Ab- und Aufleiten, Nullstellen

from sympy import *
init_printing() # for pretty printing
x,a  = symbols('x a')
f = sin(sqrt((exp(x)+a)/2))
diff(f,x)
integrate(1/(1+x**2),x)
solve(f,x)
f.subs(x,log(-a))

Multi-plots

import numpy as np
import matplotlib.pyplot as plt

N = 5
x = np.linspace(0, 2 * np.pi, 400)
fig, subplots = plt.subplots(N, N, sharex='col', sharey='row')
for (i, j), subplot in np.ndenumerate(subplots):
    subplot.plot(x, i * np.cos(x**2) + j * np.sin(x))

fig.suptitle("i * cos(x**2) + j * sin(x)")
plt.show()