python - 我如何在 Python 中使用 Pyplot 函数?
问题描述
程序完成后,我无法显示我的结果。我期待看到速度与位置图,但由于某种原因,它没有出现。我的代码有问题吗。
import numpy
from matplotlib import pyplot
import time,sys
#specifying parameters
nx=41 # number of space steps
nt=25 #number of time steps
dt=0.025 #width between time intervals
dx=2/(nx-1) #width between space intervals
c=1 # the speed of the initial wave
#boundary conditions
u = numpy.ones(nx)
u[int(0.5/dx):int(1/(dx+1))] = 2
un = numpy.ones(nx)
#initializing the velocity function
for i in range(nt):
un= u.copy()
for i in range(1,nx):
u[i]= un[i] -c*(dt/dx)*(u[i]-u[i-1])
pyplot.xlabel('Position')
pyplot.ylabel('Velocity')
pyplot.plot(numpy.linspace(0,2,nx),u)
解决方案
这里发生了一些事情
你不需要写出你正在导入的包的全名。您可以只使用别名来调用这些包并稍后将它们与这些别名一起使用。例如,这个。
import numpy as np
您的 dx 值初始化将为您提供 0,因为您将 2 除以 40,这将为您提供零。您可以通过将该表达式中的一个值设置为浮点数来初始化 dx 的值,所以就像这样。
dx=float(2)/(nx-1) #width between space intervals
正如评论中建议的评论中的 Meowcolm Law 一样,添加 pyplot.show() 以显示图形。这就是您的代码的编辑版本所喜欢的
import numpy as np
import matplotlib.pyplot as plt
import time,sys
#specifying parameters
nx=41 # number of space steps
nt=25 #number of time steps
dt=0.025 #width between time intervals
dx=float(2)/(nx-1) #width between space intervals
c=1 # the speed of the initial wave
#boundary conditions
u = np.ones(nx)
u[int(0.5/dx):int(1/(dx+1))] = 2
un = np.ones(nx)
#initializing the velocity function
for i in range(nt):
un= u.copy()
for i in range(1,nx):
u[i]= un[i] -c*(dt/dx)*(u[i]-u[i-1])
plt.xlabel('Position')
plt.ylabel('Velocity')
plt.plot(np.linspace(0,2,nx),u)
plt.show()
推荐阅读
- postgresql - 需要一种从 Postgres 数据库触发器启动 Mirth 进程的方法
- reactjs - React Native - [TypeError: undefined is not an object (evalating '_components.UsernameContext.Provider')]
- node.js - 我想用 node.js 将文件上传到我的服务器,但我不想要 html
- html - css 中的媒体查询被忽略
- css - 使用 SVG 蒙版重新定位和重新缩放图像
- image-processing - 基于 RGB 对图像进行聚类,并根据其中心对每个聚类进行着色
- python - 如何通过采用应用于另一列的重复值来替换一列的值
- kubernetes - 使用 Isito Operator 设置 Ingress Gateway NodePort
- python - 如何将带有空字符的字符串从 C++ DLL 返回到 Python?
- laravel - 当我使用 url 在远程服务器上配置 apache2 时出现问题