Numpy, Matplotlib, and Scipy
Solving equations with numpy
Solving a linear equation
import numpy as np
A = np.array([[1, 2], [3, 4]])
b = np.array([1, 2])
x = np.linalg.solve(A, b)
print(x) # [-3. 2.5]
Finding roots of a polynomial
Finding the inverse and determinant of a matrix
A = np.array([[1, 2], [3, 4]])
A_inv = np.linalg.inv(A)
A_det = np.linalg.det(A)
print(A_inv) # [[-2. 1. ]
# [ 1.5 -0.5]]
print(A_det) # -2.0000000000000004
FFT
import numpy as np
x = np.array([1, 2, 3, 4])
y = np.fft.fft(x)
print(y) # [10.+0.j -2.+2.j -2.+0.j -2.-2.j]
Creating lists using np
Matplotlib
Plotting a line graph
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 10, 0.1)
y = np.sin(x)
plt.plot(x, y, 'o--r') # o: circle, --: dashed line, r: red
plt.show()
Plotting a bar graph
Plotting a pie chart
Plotting a scatter plot (np normal distribution)
Subplots
x = np.arange(1, 10, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)
plt.subplot(2, 1, 1) # 2 rows, 1 column, 1st plot
plt.plot(x, y1, 'o--r')
plt.subplot(2, 1, 2) # 2 rows, 1 column, 2nd plot
plt.plot(x, y2, 'o--b')
plt.show()
Plot a histogram
Scipy
Find roots of a polynomial
import numpy as np
from scipy.optimize import root
def f(x):
return x**2 - 4
sol = root(f, 0)
print(sol.x) # [2.]
Minimize a function
Summary
Numpy methods
np.linalg.solve(A, b)
: Solve a linear equationnp.roots([1, -2, 1])
: Find roots of a polynomialnp.linalg.inv(A)
: Find the inverse of a matrixnp.linalg.det(A)
: Find the determinant of a matrixnp.fft.fft(x)
: Compute the one-dimensional discrete Fourier Transformnp.random.randint(1, 10, 5)
: Generate a random arraynp.arange(1, 10, 2)
: Generate an array with a rangenp.random.normal(0, 100000, 250)
: Generate an array with a normal distribution
Matplotlib methods
plt.plot(x, y, 'o--r')
: Plot a line graphplt.bar(x, y, color='skyblue')
: Plot a bar graphplt.pie(x, labels=x)
: Plot a pie chartplt.scatter(x, y)
: Plot a scatter plotplt.subplot(2, 1, 1)
: Create subplotsplt.hist(x, bins=10)
: Plot a histogram
Scipy methods
root(f, 0)
: Find the root of a functionminimize(f, 0)
: Minimize a function