【发布时间】:2017-04-02 19:28:47
【问题描述】:
我正在研究 Mark Newman 的《计算物理学》一书中标题为 Euler's Method 的示例 8.1。我将示例重写为使用 Numpy 数组的方法,但是当我绘制它时,我在同一个图中得到了两个图,不知道如何更正它。还有更好的方法将我的 2 个 1D 数组转换为 1 个 2D 数组以用于在 Matplotlib 中绘图,谢谢。
纽曼的例子:
from math import sin
from numpy import arange
from pylab import plot,xlabel,ylabel,show
def f(x,t):
return -x**3 + sin(t)
a = 0.0 # Start of the interval
b = 10.0 # End of the interval
N = 1000 # Number of steps
h = (b-a)/N # Size of a single step
x = 0.0 # Initial condition
tpoints = arange(a,b,h)
xpoints = []
for t in tpoints:
xpoints.append(x)
x += h*f(x,t)
plot(tpoints,xpoints)
xlabel("t")
ylabel("x(t)")
show()
我的修改:
from pylab import plot,show,xlabel,ylabel
from numpy import linspace,exp,sin,zeros,vstack,column_stack
def f(x,t):
return (-x**(3) + sin(t))
def Euler(f,x0,a,b):
N=1000
h = (b-a)/N
t = linspace(a,b,N)
x = zeros(N,float)
y = x0
for i in range(N):
x[i] = y
y += h*f(x[i],t[i])
return column_stack((t,x)) #vstack((t,x)).T
plot(Euler(f,0.0,0.0,10.0))
xlabel("t")
ylabel("x(t)")
show()
【问题讨论】:
-
我想您的第一个问题是您需要以某种方式清除绘图空间。我不太了解 Pyplot,但在 Matplotlib 中有一个
plt.clf() -
@Henry 刚刚尝试过,虽然它有帮助,但由于某种原因,主线性图仍然显示出来,它似乎需要一个数据集并从中绘制两张图。
-
对不起,兄弟。没有使用 pyplot 的经验!
-
@Henry 很好的清理确实帮助我解决了另一个问题
-
@Henry
pyplot是plt如果你是importedmatplotlib.pyplot as plt。pylab也只是pyplot的不同命名空间。
标签: python arrays numpy matplotlib