Skip to content

Instantly share code, notes, and snippets.

@ceptreee
Last active August 19, 2018 18:55
Show Gist options
  • Save ceptreee/415d8a68710863c4947ce1df42dedb8a to your computer and use it in GitHub Desktop.
Save ceptreee/415d8a68710863c4947ce1df42dedb8a to your computer and use it in GitHub Desktop.
# x
X = 5.0
xlm = [-X,X]
dx = 0.1
x = xlm[1]:dx:xlm[2]
x_n = length(x)
# t
T = 50.0
tlm = [0,T]
dt = 0.1
t = tlm[1]:dt:tlm[2]
t_n = length(t)
# パラメータ
D = 0.05
α = D * dt / dx^2
# 初期条件
f(x) = exp(-x^2)
# 初期化
u = zeros(x_n, t_n)
# 境界条件
u[1, :] = 0.0
u[end,:] = 0.0
# 初期条件
u[:,1] = f.(x)
for j = 1:t_n-1
for i = 2:x_n-1
u[i,j+1] = (1.0 - 2.0 * α) * u[i,j] + α * ( u[i+1,j] + u[i-1,j] )
end
end
# plot
#----------------------------------------------
using PyPlot
using PyCall
@pyimport matplotlib.animation as anim
# figure
fig = figure(figsize=(4, 4))
# line
line = plot([],[])[1]
# setting
xlim(xlm)
ylim([-1,1])
grid()
xlabel("x")
ylabel("u")
tight_layout()
grid("on",linestyle="--")
# update
function update(i)
line[:set_data](x, u[:,i+1])
# title
title(@sprintf("%4.2f",t[i+1]))
end
# animation
myanim = anim.FuncAnimation(fig, update, frames=t_n, interval=10)
# save
myanim[:save]("Diffusion_1d_v0.6.gif", writer="imagemagick")
# x
X = 5.0
xlm = [-X,X]
dx = 0.1
x = xlm[1]:dx:xlm[2]
Nx = length(x)
# t
T = 50.0
tlm = [0,T]
dt = 0.1
t = tlm[1]:dt:tlm[2]
Nt = length(t)
# パラメータ
D = 0.05
α = D * dt / dx^2
# 初期条件
f(x) = exp(-x^2)
# 初期化
u = zeros(Nx, Nt)
# 境界条件
u[1, :] .= 0.0
u[end,:] .= 0.0
# 初期条件
u[:,1] = f.(x)
for j = 1:Nt-1
for i = 2:Nx-1
u[i,j+1] = (1.0 - 2.0 * α) * u[i,j] + α * ( u[i+1,j] + u[i-1,j] )
end
end
# plot
#----------------------------------------------
using PyPlot
using PyCall
@pyimport matplotlib.animation as anim
# @spritnf
using Printf
# figure
fig = figure(figsize=(4, 4))
# line
line = plot([],[])[1]
# setting
xlim(xlm)
ylim([0,1])
grid()
xlabel("x")
ylabel("u")
title(@sprintf("%4.1f",t[1]))
tight_layout()
grid("on",linestyle="--")
# update
function update(i)
line[:set_data](x, u[:,i+1])
# title
title(@sprintf("%4.1f",t[i+1]))
end
# animation
myanim = anim.FuncAnimation(fig, update, frames=Nt, interval=10)
# save
myanim[:save]("Diffusion_1d_v1.gif", writer="imagemagick")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment