一、SciPy 简介
SciPy(Scientific Python)是基于 NumPy 的开源科学计算库,提供了数值积分、优化、信号处理、线性代数、统计分析等高级科学计算功能。它是构建 Python 科学计算生态系统的核心组件之一,常用于科研、工程、数据分析等领域。
二、安装 SciPy
2.1 使用 pip 安装(推荐)
pip install scipy
2.2 使用 Anaconda 安装(科学计算推荐)
conda install scipy
2.3 验证安装
import scipy
print(scipy.__version__)
三、SciPy 子模块简介
模块 | 作用说明 |
---|---|
scipy.integrate | 积分计算 |
scipy.optimize | 函数优化与最小值求解 |
scipy.stats | 概率分布与统计测试 |
scipy.linalg | 线性代数运算(比 NumPy 更丰富) |
scipy.fft | 傅里叶变换 |
scipy.signal | 信号处理 |
scipy.spatial | 空间数据结构与计算几何 |
scipy.cluster | 聚类算法 |
四、使用示例
4.1 数值积分
from scipy import integrate
result, _ = integrate.quad(lambda x: x**2, 0, 1)
print(result) # 输出 1/3 ≈ 0.333
4.2 函数最小值
from scipy import optimize
f = lambda x: x**2 + 10*np.sin(x)
res = optimize.minimize(f, x0=0)
print(res.x)
4.3 统计分析
from scipy import stats
data = [2, 4, 6, 8, 10]
print(stats.mean(data))
print(stats.variation(data)) # 变异系数
五、线性代数计算
from scipy import linalg
import numpy as npA = np.array([[1, 2], [3, 4]])
b = np.array([1, 2])
x = linalg.solve(A, b)
print(x)
六、信号处理
from scipy import signal
import numpy as np
import matplotlib.pyplot as pltx = np.linspace(0, 1, 500)
y = signal.sawtooth(2 * np.pi * 5 * x)plt.plot(x, y)
plt.title("Sawtooth 波形")
plt.show()
七、空间与距离计算
from scipy.spatial import distancea = [1, 2]
b = [4, 6]
print(distance.euclidean(a, b)) # 欧几里得距离
八、常见问题
Q1: 报错 ModuleNotFoundError: No module named 'scipy'
?
请确保正确安装了 scipy
:
pip install scipy
或者使用 conda 安装:
conda install scipy
Q2: 安装太慢?
可尝试使用清华镜像源:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple scipy
九、学习资源推荐
- SciPy 官方文档
- SciPy 教程(菜鸟教程)
- Python 科学计算手册
- 《Python 科学计算》 作者:Travis Oliphant
本文由“小奇Java面试”原创发布,转载请注明出处。
可以搜索【小奇JAVA面试】第一时间阅读,回复【资料】获取福利,回复【项目】获取项目源码,回复【简历模板】获取简历模板,回复【学习路线图】获取学习路线图。