python科学计算和数据科学应用pdf(Python 科学计算入门笔记)python基础 / python科学计算基础...

wufei123 发布于 2024-07-02 阅读(7)

在 Python 语言下,实现科学计算主要依赖于 NumPy、SciPy、Matplotlib 等库本文将主要记录下 python 基础循环语句,以及上述三个库的在科学计算的应用1 基础语法1.1 for 循环:

# 遍历列表modes = ["TA", "LA", "ZA"]for mode in modes:    print(mode)# 遍历数字范围for i in range(5):    print(i)

1.2 while 循环:# 使用 while 循环计数count = 0while count < 5:    print(count)    count += 11.3 循环控制语句:# 使用 break 结束循环

for i in range(10):if i == 5:break    print(i)# 使用 continue 跳过当前循环的剩余代码,继续下一次循环for i in range(10):if i % 

2 == 0:continue    print(i)# pass 用作占位符,不做任何操作for i in range(5):pass# 什么都不做2 NumPy 库NumPy 用于处理大型多维数组和矩阵,以及执行数学运算。

2.1 数组创建和基本操作import numpy as np# 创建数组arr1 = np.array([1, 2, 3, 4, 5])arr2 = np.array([[1, 2, 3], [4, 

5, 6]])# 形状和维度shape = arr2.shapedimension = arr2.ndim# 数组运算mean_value = np.mean(arr1)sum_by_column = np.sum(arr2, axis=

0)2.2 数组索引和切片# 索引element = arr1[2]# 切片subset = arr1[1:4]2.3 数组形状改变# 改变数组形状reshaped_arr = arr1.reshape(

1, 5)2.4 数学运算# 数学运算sqrt_arr = np.sqrt(arr1)sin_arr = np.sin(arr1)2.5 数组合并和分割# 数组合并arr3 = np.array([6, 

7, 8, 9, 10])concatenated_arr = np.concatenate((arr1, arr3))# 数组分割split_arr = np.split(concatenated_arr, [

2, 5])2.6 矩阵乘法# 创建两个矩阵matrix1 = np.array([[1, 2], [3, 4]])matrix2 = np.array([[5, 6], [7, 8]])# 矩阵乘法product_matrix = np.dot(matrix1, matrix2)

2.7 布尔运算# 布尔运算bool_arr = arr1 > 3filtered_arr = arr1[bool_arr]2.8 随机数生成# 生成随机整数数组random_integers = np.random.randint(low=

1, high=10, size=(3, 3))# 生成随机浮点数数组random_floats = np.random.rand(2, 2)3 SciPy 库SciPy 是建立在 NumPy 基础上的库,提供了更高级的科学计算功能。

它包括了优化、信号处理、统计学、线性代数等多个模块3.1 科学计算功能import scipy# 计算阶乘factorial_result = scipy.special.factorial(5)# 计算组合数

combinations_result = scipy.special.comb(5, 2)3.2 线性代数from scipy.linalg import inv, det, eig# 矩阵求逆matrix_inverse = inv(matrix)

# 矩阵行列式matrix_determinant = det(matrix)# 矩阵特征值和特征向量eigenvalues, eigenvectors = eig(matrix)3.3 优化算法from

 scipy.optimize import minimize# 最小化函数result = minimize(lambda x: (x[0] - 1)**2 + (x[1] - 2.5)**2, [0

, 0], method=BFGS)3.4 插值from scipy.interpolate import interp1d# 创建插值函数x = np.array([1, 2, 3, 4, 5])y = np.array([

2, 0, 1, 4, 3])interp_function = interp1d(x, y, kind=linear)# 计算插值结果interp_result = interp_function(2.5

)3.5 信号处理from scipy.signal import find_peaks# 生成示例信号signal = np.array([1, 3, 7, 1, 2, 0, 5, 6, 1])# 寻找峰值

peaks, _ = find_peaks(signal)3.6 统计from scipy.stats import norm# 创建正态分布对象normal_dist = norm(loc=0, scale=

1)# 计算概率密度函数值pdf_value = normal_dist.pdf(0.5)4 Matplotlib 库Matplotlib是一个用于绘制图表和可视化数据的库4.1 折线图import matplotlib.pyplot 

as pltimport numpy as np# 生成数据x = np.linspace(0, 10, 100)y = np.sin(x)# 绘制折线图plt.plot(x, y, label=Sin Function

, color=blue, linestyle=--, linewidth=2, marker=o, markersize=5)# 添加标签和标题plt.xlabel(X-axis, fontsize=

12)plt.ylabel(Y-axis, fontsize=12)plt.title(Sine Function Plot, fontsize=14)# 显示图例plt.legend()# 添加网格plt.grid(

True, linestyle=--, alpha=0.5)# 修改坐标轴范围plt.xlim(0, 10)plt.ylim(-1.5, 1.5)# 显示图表plt.show()

4.2 散点图# 生成随机数据x_rand = np.random.rand(50)y_rand = np.random.rand(50)# 绘制散点图plt.scatter(x_rand, y_rand, color=

green, marker=s, s=50, alpha=0.8, label=Random Points)# 添加标签和标题plt.xlabel(X-axis, fontsize=12)plt.ylabel(

Y-axis, fontsize=12)plt.title(Scatter Plot, fontsize=14)# 显示图例plt.legend()# 添加颜色条plt.colorbar()# 显示图表

plt.show()

4.3 条形图categories = [Category A, Category B, Category C]values = [4, 7, 2]plt.bar(categories, values, color=[

red, green, blue], edgecolor=black, width=0.5, alpha=0.7)plt.xlabel(Categories, fontsize=12)plt.ylabel(

Values, fontsize=12)plt.title(Bar Chart, fontsize=14)plt.show()

4.4 饼图labels = [Label A, Label B, Label C]sizes = [3, 6, 2]plt.pie(sizes, labels=labels, autopct=%1.1f%%

, startangle=90, colors=[red, green, blue])plt.title(Pie Chart, fontsize=14)plt.show()

4.5 绘制子图x = np.linspace(0, 2 * np.pi, 100)y1 = np.sin(x)y2 = np.cos(x)plt.subplot(2, 1, 1)plt.plot(x, y1)

plt.title(Sin Function)plt.subplot(2, 1, 2)plt.plot(x, y2)plt.title(Cos Function)plt.show()

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

河南中青旅行社综合资讯 奇遇综合资讯 盛世蓟州综合资讯 综合资讯 游戏百科综合资讯 新闻36043