NumPy Essentials for Scientific Computing
Introduction to NumPy
NumPy is the fundamental package for scientific computing in Python. It provides support for large, multi-dimensional arrays and matrices, along with a vast collection of high-level mathematical functions to operate on these arrays.
Basic Array Operations
import numpy as np
# Creating arrays
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.zeros((3, 3))
arr3 = np.ones((2, 2))
# Array operations
result = arr1 * 2 # Element-wise multiplication
print(result) # [2 4 6 8 10]
Array Manipulation
NumPy provides various methods to manipulate arrays, including reshaping, concatenating, and splitting arrays.
Reshaping Arrays
# Create a 1D array
arr = np.array([1, 2, 3, 4, 5, 6])
# Reshape to 2x3 matrix
matrix = arr.reshape(2, 3)
print(matrix)
# [[1 2 3]
# [4 5 6]]
Linear Algebra Operations
NumPy provides comprehensive tools for linear algebra operations, which are essential for physics computations.
Matrix Operations
# Create matrices
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
# Matrix multiplication
C = np.dot(A, B)
print(C)
# Eigenvalues and eigenvectors
eigenvals, eigenvecs = np.linalg.eig(A)
print("Eigenvalues:", eigenvals)
Physics Example: Simple Harmonic Motion
Let's use NumPy to simulate and visualize simple harmonic motion.
SHM Simulation
import numpy as np
import matplotlib.pyplot as plt
# Parameters
A = 1.0 # Amplitude
omega = 2.0 # Angular frequency
phi = 0.0 # Phase
# Time points
t = np.linspace(0, 10, 1000)
# Position
x = A * np.cos(omega * t + phi)
# Plot
plt.plot(t, x)
plt.xlabel('Time')
plt.ylabel('Position')
plt.title('Simple Harmonic Motion')
plt.grid(True)
plt.show()
Practice Exercises
Exercise 1: Array Operations
Create a 3x3 matrix of random numbers and calculate its:
- Determinant
- Inverse
- Transpose
Exercise 2: Physics Application
Use NumPy to simulate the motion of a damped harmonic oscillator and plot its position vs. time.