首页 > 其他分享 >第二章习题

第二章习题

时间:2024-11-17 23:30:29浏览次数:1  
标签:plt print set import np ax 习题 第二章

学号后四位:3018

2.1:

点击查看代码
import math
import pylab as plt
import numpy as np
 
plt.rc('text', usetex=True)  # 调用字库
x = np.linspace(-10, 10, 100)
y1 = np.cosh(x)
y2 = np.sinh(x)
y3 = math.e**x/2
plt.plot(x, y1, label='$\\mathrm{cosh}(x)$')
plt.plot(x, y2, label='$\\mathrm{sinh}(x)$')
plt.plot(x, y3, label='$\\frac{1}{2} \cdot e^x$')
plt.legend()
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.show()
print("xuehao3018")

2.2:

点击查看代码
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad
 
def fun(t, x):
    return np.exp(-t) * (t ** (x - 1))
 
 
x = np.linspace(0, 10, 100)  # x 的范围
y = [quad(fun, 0, np.inf, args=i)[0] for i in x]  # 计算积分
 
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('$ y = \int_0^{\infty} e^{-t} \cdot t^{x-1} dt $')
plt.grid(True)
plt.show()
print("xuehao3018")

2.3:

点击查看代码
import numpy as np
import matplotlib.pyplot as plt
 
k_values = [1, 2, 3, 4, 5, 6]  # k的取值
x = np.linspace(-10, 10, 100)  # x的范围
 
for k in k_values:
    y = k * x ** 2 + 2 * k  # 计算y值
    label = f'k={k}'  # 设置标注
    plt.plot(x, y, label=label)  # 绘制曲线
 
plt.xlabel('x')  # 添加x轴标签
plt.ylabel('y')  # 添加y轴标签
plt.legend()  # 添加图例
plt.grid(True)  # 添加网格线
plt.show()  # 显示图形
print("xuehao43018")

2.4:

点击查看代码
import numpy as np
import matplotlib.pyplot as plt
 
plt.rc('font', family='SimHei')  # 用来正常显示中文标签
plt.rc('axes', unicode_minus=False) # 用来正常显示负号
k_values = [1, 2, 3, 4, 5, 6]  # k的取值
x = np.linspace(-10, 10, 100)  # x的范围
 
fig, axs = plt.subplots(2, 3, figsize=(10, 6))  # 创建2行3列的子窗口
 
for i, k in enumerate(k_values):
    y = k * x ** 2 + 2 * k  # 计算y值
    row = i // 3  # 计算子窗口所在的行数
    col = i % 3  # 计算子窗口所在的列数
    ax = axs[row, col]  # 获取当前子窗口
    label = f'k={k}'  # 设置标注
    ax.plot(x, y, label=label)  # 绘制曲线
    ax.set_xlabel('x')  # 添加x轴标签
    ax.set_ylabel('y')  # 添加y轴标签
    ax.set_title(f'图 {i+1}')  # 添加子窗口标题
    ax.legend()  # 添加图例
    ax.grid(True)  # 添加网格线
 
plt.tight_layout()  # 自动调整子窗口布局
plt.show()  # 显示图形
print("xuehao3018")

2.5(1):

点击查看代码
import numpy as np
import matplotlib.pyplot as plt
 
a = 2
b = np.sqrt(10)
c = np.sqrt(8)
 
phi = np.arange(0, 2*np.pi+0.1, 0.1)
theta = np.arange(-1, 1.1, 0.1)[:, np.newaxis]
 
x = a * np.cosh(theta) * np.cos(phi)
y = b * np.cosh(theta) * np.sin(phi)
z = c * np.sinh(theta)
 
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.plot_surface(x, y, z,  cmap='viridis')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_box_aspect([1, 1, 1])
ax.set_title('$\\frac{x^2}{4}+\\frac{y^2}{10}-\\frac{z^2}{8}=1$')
plt.show()
print("xuehao3018")

2.5(2):

点击查看代码
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
 
# 创建一个三维坐标系
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
 
# 生成x,y的网格
x = np.linspace(-50, 50, 1000)
y = np.linspace(-50, 50, 1000)
X, Y = np.meshgrid(x, y)
 
# 计算z的值
Z = (X**2)/4+(Y**2)/6
 
# 绘制二次曲面
ax.plot_surface(X, Y, Z, cmap='viridis')
 
# 添加坐标轴标签
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
 
# 添加标题
ax.set_title('$(\\frac{x^2}{4}+\\frac{y^2}{6})=z$')
 
# 设置z轴的范围
ax.set_zlim(0, 1000)
 
# 显示图形
plt.show()
print("xuehao3018")

2.6:

点击查看代码
import pandas as pd
import numpy as np
 
# 生成x、y和z数据
x = np.arange(0, 101, 1)
y = np.arange(0, 101, 1)
z = np.random.randint(0, 1001, size=(101, 101))
 
# 创建DataFrame对象
df = pd.DataFrame(data=z, index=x, columns=y)
 
# 写入Excel文件
df.to_excel('data.xlsx')

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import RectBivariateSpline
 
 
df = pd.read_excel('data.xlsx', header=None)
 
x = df.iloc[1:, 0].values
y = df.iloc[0, 1:].values
z = df.iloc[1:, 1:].values
 
# 绘制等高线图
plt.contour(x, y, z)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Contour Plot')
plt.colorbar()  # 添加颜色条
# 在已知点处添加标注
point1 = (30, 0)
point2 = (43, 30)
plt.annotate('(30,0)', point1, textcoords="offset points", xytext=(0,10), ha='center')
plt.annotate('(43,30)', point2, textcoords="offset points", xytext=(0,10), ha='center')
# 创建插值函数
interp_func = RectBivariateSpline(x, y, z)
 
# 定义积分区间
x_min, x_max = min(x), max(x)
y_min, y_max = min(y), max(y)
 
# 计算积分区间的网格点数
grid_size = 100  # 可根据需要调整
 
# 生成网格点
x_grid = np.linspace(x_min, x_max, grid_size)
y_grid = np.linspace(y_min, y_max, grid_size)
 
# 计算网格点上的插值值
z_grid = interp_func(x_grid, y_grid)
 
# 计算曲面面积
area = np.trapz(np.trapz(z_grid, x_grid), y_grid)
 
print('区域面积:', area)
 
plt.show()
print("xuehao3018")

点击查看代码
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
 
df = pd.read_excel('data2.xlsx', header=None)
 
x = df.iloc[1:, 0].values
y = df.iloc[0, 1:].values
z = df.iloc[1:, 1:].values
 
# 创建网格
X, Y = np.meshgrid(y, x)
 
# 创建画布和3D坐标轴
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
 
# 绘制三维网格图
ax.plot_surface(X, Y, z)
 
# 设置坐标轴标签
ax.set_xlabel('Y')
ax.set_ylabel('X')
ax.set_zlabel('Z')
 
# 显示三维网格图
plt.show()
print("xuehao3018")

2.7:

点击查看代码
import numpy as np
 
# 定义系数矩阵 A 和常数向量 b
A = np.array([[4, 2, -1], [3, -1, 2], [11, 3, 0]])
b = np.array([2, 10, 8])
 
# 解线性方程组 Ax = b
x = np.linalg.solve(A, b)
 
# 判断解的情况
if np.linalg.matrix_rank(A) == np.linalg.matrix_rank(np.column_stack((A, b))):
    if np.linalg.matrix_rank(A) == A.shape[1]:
        print("线性方程组有唯一解")
        x_unique = np.linalg.solve(A, b)
        print("唯一解 x =", x_unique)
    else:
        print("线性方程组有无穷多解")
        x_least_squares = np.linalg.lstsq(A, b, rcond=None)[0]
        print("最小二乘解 x =", x_least_squares)
else:
    print("线性方程组无解")
    x_least_squares = np.linalg.lstsq(A, b, rcond=None)[0]
    print("最小二乘解 x =", x_least_squares)
    x_min_norm = np.linalg.pinv(A).dot(b)
    print("最小范数解 x =", x_min_norm)
print("xuehao3018")

标签:plt,print,set,import,np,ax,习题,第二章
From: https://www.cnblogs.com/wdew/p/18509320

相关文章

  • python基础练习题----练手
    python—练手题—40题#01-helloworldprint('helloworld!')#如果3大于0,则打印'ok'和'yes'if3>0:print('ok')print('yes')x=3y=4print(x+y)#02-printprint('helloworld!')print(�......
  • HDLBIts习题(7):状态机
    (1)较难习题1:134题(fsm_ps2data)    有个积攒数据的过程。(1)较难习题2:135题(fsm_serial)        读清题意,有一个检验选择是否发送的进程。(3)较难习题3:137题(fsm_serialdp)    加入了奇偶校验位检测机制(4)较难习题4:138题(fsm_hdlc)   ......
  • HDLBIts习题(2):位操作,For循环(generate与integer)
    (1)冷门习题1:VerilogLanguage-MoreVerilogFeatures-Reductionoperators    一个矢量的位操作,多比特矢量操作会变得方便。(2)冷门习题2:VerilogLanguage-MoreVerilogFeatures-Combinationfor-loop:Vectorreversal2     Verilog中的for循环(3......
  • 习题7.7
    1.代码实现点击查看代码importnumpyasnpfromscipy.optimizeimportcurve_fit,least_squaresfromscipy.linalgimportlstsqimportmatplotlib.pyplotaspltdefg(x,a,b):return(10*a)/(10*b+(a-10*b)*np.exp(-a*np.sin(x)))#给定参数a......
  • 习题7.4
    1.代码实现点击查看代码importnumpyasnpfromscipy.interpolateimportgriddataimportmatplotlib.pyplotasplt#定义函数deff(x,y):return(x**2-2*x)*np.exp(-x**2-y**2-x*y)#生成随机点np.random.seed(0)x_random=np.random.uni......
  • 习题7.3
    1.代码实现点击查看代码importnumpyasnpfromscipy.interpolateimportinterp1d,CubicSplineimportmatplotlib.pyplotasplt#给定数据T=np.array([700,720,740,760,780])V=np.array([0.0997,0.1218,0.1406,0.1551,0.1664])#要插值的温度点T_interp......
  • 数学建模习题8.5
    `importnumpyasnpimportmatplotlib.pyplotaspltfromscipy.integrateimportsolve_ivp定义微分方程模型defmodel(t,y):f,df_dm,d2f_dm2,T,dT_dm=yd3f_dm3=-3*f*d2f_dm2+2*(df_dm)**2-Td2T_dm2=-2*f*dT_dmreturn[df_dm,d2f_dm2,d3f_dm......
  • 习题7.10(3)
    1.代码实现点击查看代码importnumpyasnpimportpylabaspltfromscipy.optimizeimportcurve_fit#原始数据点x0=np.array([-2,-1.7,-1.4,-1.1,-0.8,-0.5,-0.2,0.1,0.4,0.7,1,1.3,1.6,1.9,2.2,2.5,2.8,3.1,3.4,3.7,4,4.3,4.6,4.9])y0=np.......
  • 习题8.5
    1.代码实现点击查看代码importnumpyasnpfromscipy.integrateimportodeintimportmatplotlib.pyplotasplt#定义微分方程组defsystem(state,eta):f,df,d2f,T,dT=stated3f=-3*d2f+2*df**2-Td2T=-2.1*df*dTreturn[df,......
  • 习题8.4
    1.代码实现点击查看代码importnumpyasnpfromscipy.integrateimportodeintimportmatplotlib.pyplotasplt#定义微分方程组defsystem(state,t):x,y=statedxdt=-x**3-ydydt=x-y**3return[dxdt,dydt]#初始条件x0=1y......