[英]ValueError: x and y must have same first dimension, but have shapes (6,) and (8,)
[英]ValueError: x and y must have the same first dimension
我正在尝试使用NumPy在Python中实现有限差分近似来求解热方程u_t = k * u_{xx}
。
这是我正在运行的代码的副本:
## This program is to implement a Finite Difference method approximation
## to solve the Heat Equation, u_t = k * u_xx,
## in 1D w/out sources & on a finite interval 0 < x < L. The PDE
## is subject to B.C: u(0,t) = u(L,t) = 0,
## and the I.C: u(x,0) = f(x).
import numpy as np
import matplotlib.pyplot as plt
# parameters
L = 1 # legnth of the rod
T = 10 # terminal time
N = 10
M = 100
s = 0.25
# uniform mesh
x_init = 0
x_end = L
dx = float(x_end - x_init) / N
x = np.arange(x_init, x_end, dx)
x[0] = x_init
# time discretization
t_init = 0
t_end = T
dt = float(t_end - t_init) / M
t = np.arange(t_init, t_end, dt)
t[0] = t_init
# Boundary Conditions
for m in xrange(0, M):
t[m] = m * dt
# Initial Conditions
for j in xrange(0, N):
x[j] = j * dx
# definition of solution u(x,t) to u_t = k * u_xx
u = np.zeros((N, M+1)) # array to store values of the solution
# Finite Difference Scheme:
u[:,0] = x**2 #initial condition
for m in xrange(0, M):
for j in xrange(1, N-1):
if j == 1:
u[j-1,m] = 0 # Boundary condition
elif j == N-1:
u[j+1,m] = 0
else:
u[j,m+1] = u[j,m] + s * ( u[j+1,m] -
2 * u[j,m] + u[j-1,m] )
print u, #t, x
plt.plot(u, t)
#plt.show()
我认为我的代码工作正常,并且正在产生输出。 我想绘制解决方案u
与t
(我的时间向量)的输出。 如果可以绘制该图,则可以检查我的数值近似值是否与Heat Equation的预期现象相符。 但是,我得到一个错误,即“ x和y必须具有相同的第一维”。 我该如何解决这个问题?
另外一个问题:我是最好企图让与动画matplotlib.animation
而不是使用matplotlib.plyplot
???
非常感谢您提供的所有帮助! 非常感谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.