🧮 NumPy:Python 科学计算基石
NumPy(Numerical Python)是用于科学计算的基础库,提供高性能的多维数组对象(ndarray),并支持大量的数学、逻辑、随机、矩阵运算等功能 ([numpy.org][1])。
优势:
- 数组存储连续内存,访问速度相比 Python 列表快数十倍 。
- 采用 C/C++ 编写关键计算核心,性能优异 。
🔢 1. 创建 ndarray 数组
导入 numpy 作为 np
数组 = np.array([1, 2, 3, 4])
打印(数组, 数组.shape)
📏 2. 创建等差/线性空间数组
均匀 = np.arange(0, 10, 2) # [0 2 4 6 8]
线性 = np.linspace(0, 1, 5) # [0. 0.25 0.5 0.75 1. ]
➕ 3. 向量化操作 —— 快速数学计算
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
打印(a + b, a * b, a ** 2)
📐 4. 通用函数(ufuncs)
支持各种数学函数,自动对数组逐元素执行。
x = np.linspace(-np.pi, np.pi, 5)
打印(np.sin(x), np.cos(x))
🧱 5. 多维数组与矩阵运算
m = np.array([[1,2],[3,4]])
打印(m.transpose(), np.linalg.inv(m))