SciPy 教程


SciPy 教程

简介

SciPy 是一个基于 Python 的科学计算库,它包含了很多有用的科学计算工具,例如:数值积分、优化算法、线性代数运算、统计分析、随机模拟、信号处理等等。SciPy 是一个免费的开源软件,可以在 Windows、Mac OS X 和 Linux 下运行。

安装

SciPy 依赖于 NumPy 库和 Matplotlib 库,所以需要先安装 NumPy 和 Matplotlib:

pip3 install numpy matplotlib

然后安装 SciPy:

pip3 install scipy

数学函数

SciPy 提供了很多数学函数,下面介绍一些常用的数学函数。

积分函数

SciPy 提供了许多数值积分函数,例如:单变量定积分、双变量定积分、多重定积分、自适应积分等等。

import scipy.integrate as spi

# 单变量定积分
a, b = 0, 1
res, err = spi.quad(lambda x: x**2, a, b)
print(f"The result is {res}, the error is {err}")

# 双变量定积分
res, err = spi.nquad(lambda x, y: x**2 + y**2, [(0, 1), (0, 1)])
print(f"The result is {res}, the error is {err}")

# 多重定积分
res, err = spi.dblquad(lambda x, y: x**2 + y**2, 0, 1, lambda x: 0, lambda x: 1)
print(f"The result is {res}, the error is {err}")

# 自适应积分
res, err = spi.fixed_quad(lambda x: x**2, a, b, n=5)
print(f"The result is {res}, the error is {err}")

最优化函数

SciPy 提供了许多最优化函数,例如:线性规划、非线性规划、无约束优化、全局优化等等。

import scipy.optimize as spo

# 线性规划
c = [-1, 2, 3]
A = [[1, 1, 1], [2, 3, 1], [2, 1, 2]]
b = [4, 7, 6]
res = spo.linprog(c, A_eq=A, b_eq=b)
print(res)

# 非线性规划
def rosen(x):
    return sum((1 - x[:3])**2) + 100 * sum((x[1:] - x[:-1]**2)**2)

res = spo.minimize(rosen, x0=[-1.2, 1.0, 1.0, 1.0, 1.0], method='SLSQP')
print(res)

# 无约束优化
res = spo.minimize(lambda x: x**2, x0=1.0, method='BFGS')
print(res)

# 全局优化
def f(x):
    return x**2 * np.sin(x) * np.exp(-x)

res = spo.differential_evolution(f, [(0, 10)])
print(res)

线性代数函数

SciPy 提供了许多线性代数函数,例如:矩阵求解、特征值计算、奇异值计算等等。

import scipy.linalg as spla

# 矩阵求解
A = np.array([[1, 2], [3, 4]])
b = np.array([5, 6])
x = spla.solve(A, b)
print(x)

# 特征值计算
A = np.array([[1, 2], [3, 4]])
w, v = spla.eig(A)
print(w)
print(v)

# 奇异值计算
A = np.array([[1, 2], [3, 4]])
u, s, vh = spla.svd(A)
print(u)
print(s)
print(vh)

统计函数

SciPy 提供了许多统计函数,例如:概率分布函数、假设检验、回归分析等等。

import scipy.stats as sps

# 概率分布函数
norm = sps.norm(loc=0, scale=1)
print(norm.pdf(0.5), norm.cdf(0.5), norm.rvs(10))

# 假设检验
s, p = sps.wilcoxon([1, 2, 3, 4], [2, 3, 4, 5])
print(s, p)

# 回归分析
x = np.array([1, 2, 3, 4, 5])
y = np.array([2.3, 4.5, 5.2, 6.1, 7.4])
slope, intercept, r, p, std_err = sps.linregress(x, y)
print(slope, intercept, r, p, std_err)

小结

SciPy 是一个非常有用的科学计算库,它提供了许多数学函数、最优化函数、线性代数函数、统计函数等等。本文介绍了一些常用的数学函数,读者可以根据自己的需要去了解更多的函数。