[英]Python: Writing a program to simulate 1D wave motion along a string
我正在研究一個程序,該程序模擬沿一維弦的波浪運動,最終模擬不同的波包。 我在“Python Scripting for Computational Science”一書中找到了一個程序,它聲稱可以描述波動,但我不確定如何實現它(這本書在谷歌圖書上,不會向我展示之前/之后的文字代碼)。
例如,我知道“f”是 x 和 t 的 function,“I”是 x 的 function,但實際上需要什么函數才能產生波?
I=
f=
c=
L=
n=
dt=
tstop=
x = linespace(0,L,n+1) #grid points in x dir
dx = L/float(n)
if dt <= 0: dt = dx/float(c) #max step time
C2 = (c*dt/dx)**2 #help variable in the scheme
dt2 = dt*dt
up = zeros(n+1) #NumPy solution array
u = up.copy() #solution at t-dt
um = up.copy() #solution at t-2*dt
t = 0.0
for i in iseq(0,n):
u[i] +0.5*C2*(u[i-1] - 2*u[i] +u[i+1]) + \
dt2*f(x[i], t)
um[0] = 0; um[n] = 0
while t<= tstop:
t_old = t; t+=dt
#update all inner points:
for i in iseq(start=1, stop= n-1):
up[i] = -um[i] +2*u[i] + \
C2*(u[i-1] - 2*u[i] + u[i+1]) + \
dt2*f(x[i], t_old)
#insert boundary conditions
up[0] = 0; up[n] = 0
#updata data structures for next step
um = u.copy(); u = up.copy()
下面的代碼應該工作:
from math import sin, pi
from numpy import zeros, linspace
from scitools.numpyutils import iseq
def I(x):
return sin(2*x*pi/L)
def f(x,t):
return 0
def solver0(I, f, c, L, n, dt, tstop):
# f is a function of x and t, I is a function of x
x = linspace(0, L, n+1) # grid points in x dir
dx = L/float(n)
if dt <= 0: dt = dx/float(c) # max time step
C2 = (c*dt/dx)**2 # help variable in the scheme
dt2 = dt*dt
up = zeros(n+1) # NumPy solution array
u = up.copy() # solution at t-dt
um = up.copy() # solution at t-2*dt
t = 0.0
for i in iseq(0,n):
u[i] = I(x[i])
for i in iseq(1,n-1):
um[i] = u[i] + 0.5*C2*(u[i-1] - 2*u[i] + u[i+1]) + \
dt2*f(x[i], t)
um[0] = 0; um[n] = 0
while t <= tstop:
t_old = t; t += dt
# update all inner points:
for i in iseq(start=1, stop=n-1):
up[i] = - um[i] + 2*u[i] + \
C2*(u[i-1] - 2*u[i] + u[i+1]) + \
dt2*f(x[i], t_old)
# insert boundary conditions:
up[0] = 0; up[n] = 0
# update data structures for next step
um = u.copy(); u = up.copy()
return u
if __name__ == '__main__':
# When choosing the parameters you should also check that the units are correct
c = 5100
L = 1
n = 10
dt = 0.1
tstop = 1
a = solver0(I, f, c, L, n, dt, tstop)
它返回一個數組,其中包含波在時間 tstop 和我們解決方案網格中所有點的值。
在將其應用於實際情況之前,您應該閱讀波動方程和有限元方法以了解代碼的作用。 它可以用來求波動方程的數值解:
Utt + beta*Ut = c^2*Uxx + f(x,t)
這是物理學中最重要的微分方程之一。 此 PDE 或波的解由 function 給出,它是空間和時間u(x,t)
的 function。
為了形象化波的概念,考慮兩個維度,空間和時間。 如果你固定時間,例如 t1,你將得到 x 的 function:
U(x) = U(x,t=t1)
然而,在空間的特定點 x1,波是 function 的時間:
U(t) = U(x=x1, t)
這應該有助於您了解波的傳播方式。 為了找到解決方案,您需要施加一些初始條件和邊界條件,以將所有可能的波限制為您感興趣的波。對於這種特殊情況:
I = I(xi)
是我們將施加的使擾動/波運行的初始力。f = f(x,t)
解釋了產生波的任何外力。c
為波速; 它是一個常數(假設介質是均勻的)。L
是我們要求解 PDE 的域的長度; 也是一個常數。n
是空間中的網格點數。dt
是一個時間步長。tstop
是停止時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.