Skip to content

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

x = np.roots([1, -2, 1]) # x^2 - 2x + 1 = 0
print(x) # [ 2. -2.]

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

import numpy as np
a = np.array([1, 2, 3, 4, 5])
print(a) # [1 2 3 4 5]
a = np.arange(1, 10, 2)
print(a) # [1 3 5 7 9]
a = np.random.randint(1, 10, 5)
print(a) # [3 4 5 6 7]

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

x = np.arange(1, 6)
y = np.random.randint(1, 10, 5)

plt.bar(x, y, color='skyblue')
plt.show()

Plotting a pie chart

x = np.random.randint(1, 10, 5)
plt.pie(x, labels=x)
plt.show()

Plotting a scatter plot (np normal distribution)

x = np.random.normal(0, 100000, 250)
y = np.arange(250)

plt.scatter(x, y)
plt.show()

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

x = np.random.normal(0, 100000, 250)
plt.hist(x, bins=10)
plt.show()

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

from scipy.optimize import minimize

def f(x):
    return x**2

sol = minimize(f, 0)
print(sol.x) # [0.]

Summary

Numpy methods

  • np.linalg.solve(A, b): Solve a linear equation
  • np.roots([1, -2, 1]): Find roots of a polynomial
  • np.linalg.inv(A): Find the inverse of a matrix
  • np.linalg.det(A): Find the determinant of a matrix
  • np.fft.fft(x): Compute the one-dimensional discrete Fourier Transform
  • np.random.randint(1, 10, 5): Generate a random array
  • np.arange(1, 10, 2): Generate an array with a range
  • np.random.normal(0, 100000, 250): Generate an array with a normal distribution

Matplotlib methods

  • plt.plot(x, y, 'o--r'): Plot a line graph
  • plt.bar(x, y, color='skyblue'): Plot a bar graph
  • plt.pie(x, labels=x): Plot a pie chart
  • plt.scatter(x, y): Plot a scatter plot
  • plt.subplot(2, 1, 1): Create subplots
  • plt.hist(x, bins=10): Plot a histogram

Scipy methods

  • root(f, 0): Find the root of a function
  • minimize(f, 0): Minimize a function