def T(z, t): ''' Formula for temperature oscillations in the ground. A1 is the amplitude of annual variations, in deg C A2 is the amplitude of the day/night variations in deg C w1 = 2*pi*P1 w2 = 2*pi*P2 a1 = sqrt(w1/(2.*k)) a2 = sqrt(w2/(2.*k)) k is the heat conduction coefficient T0 is the initial temperature z is the depth in the ground (m) t is the time in seconds A1, A2, w1, w2, a1, a2, k, T0 are global variables ''' from scitools.std import exp, sin return T0 + A1*exp(-a1*z)*sin(w1*t-a1*z) \ + A2*exp(-a2*z)*sin(w2*t-a2*z)
def T(z,t): ''' Formula for temperature oscillations in the ground. A1 is the amplitude of annual variations, in deg C A2 is the amplitude of the day/night variations in deg C w1 = 2*pi*P1 w2 = 2*pi*P2 a1 = sqrt(w1/(2.*k)) a2 = sqrt(w2/(2.*k)) k is the heat conduction coefficient T0 is the initial temperature z is the depth in the ground (m) t is the time in seconds A1, A2, w1, w2, a1, a2, k, T0 are global variables ''' from scitools.std import exp, sin return T0 + A1*exp(-a1*z)*sin(w1*t-a1*z) \ + A2*exp(-a2*z)*sin(w2*t-a2*z)
def value(self, x): from scitools.std import exp, sin a = self.a w = self.w return exp(-a*x)*sin(w*x)
t[0] = 0 dt = T/float(n) for k in range(n): t[k+1] = t[k] + dt u[k+1] = u[k] + dt*f(u[k], t[k]) return u, t # Problem: u'=u def f(u, t): return u u, t = ForwardEuler(f, U0=1, T=4, n=20) # Compare numerical solution and exact solution in a plot from scitools.std import plot, exp u_exact = exp(t) plot(t, u, 'r-', t, u_exact, 'b-', xlabel='t', ylabel='u', legend=('numerical', 'exact'), title="Solution of the ODE u'=u, u(0)=1", savefig='tmp.pdf') # More exact verification def test_ForwardEuler_against_hand_calculations(): """Verify ForwardEuler against hand calc. for 3 time steps.""" u, t = ForwardEuler(f, U0=1, T=0.2, n=2) exact = np.array([1, 1.1, 1.21]) # hand calculations error = np.abs(exact - u).max() success = error < 1E-14 assert success, '|exact - u| = %g != 0' % error def test_ForwardEuler_against_linear_solution():
def _dg(x): return -2*0.1*x*exp(-0.1*x**2)*sin(pi/2*x) + \ pi/2*exp(-0.1*x**2)*cos(pi/2*x)
t[0] = 0 dt = T/float(n) for k in range(n): t[k+1] = t[k] + dt u[k+1] = u[k] + dt*f(u[k], t[k]) return u, t # Problem: u'=u def f(u, t): return u u, t = ForwardEuler(f, U0=1, T=3, n=30) # Compare numerical solution and exact solution in a plot from scitools.std import plot, exp u_exact = exp(t) plot(t, u, 'r-', t, u_exact, 'b-', xlabel='t', ylabel='u', legend=('numerical', 'exact'), title="Solution of the ODE u'=u, u(0)=1") # Verify by hand calculations u, t = ForwardEuler(f, U0=1, T=0.2, n=2) print u, [1, 1,1, 1.21] # Verify by exact numerical solution def f1(u, t): return 0.2 + (u - u_solution_f1(t))**4 def u_solution_f1(t): return 0.2*t + 3
# Make a figure of a curve and "dart throws" for illustrating # Monte Carlo integration in 2D for area computations. import numpy as np xr = np.random.uniform(0, 2, 500) yr = np.random.uniform(0, 2.4, 500) x = np.linspace(0, 2, 51) from scitools.std import exp, sin, pi, plot y = 2 + x**2*exp(-0.5*x)*sin(pi*x) plot(x, y, 'r', xr, yr, 'o', hardcopy='tmp.eps')
""" Exercise 5.31: Animate a wave packet Author: Weiyun Lu """ from scitools.std import exp, sin, pi, linspace, plot, movie import time import glob import os f = lambda x, t: exp(-(x - 3 * t)**2) * sin(3 * pi * (x - t)) fps = float(1 / 6) xp = linspace(-6, 6, 1001) tp = linspace(-1, 1, 61) counter = 0 for name in glob.glob('pix/plot_wave*.png'): os.remove(name) for t in tp: yp = f(xp, t) plot(xp, yp, '-b', axis=[xp[0], xp[-1], -1.5, 1.5], legend='t=%4.2f' % t,\ title='Evolution of wave over time', savefig='pix/plot_wave%04d.png' \ % counter) counter += 1 time.sleep(fps) #movie('pix/plot_wave*.png')
""" Exercise 5.3: Fill arrays; vectorized (plot) Author: Weiyun Lu """ from scitools.std import sqrt, pi, exp, linspace, plot h = lambda x : (1/(sqrt(2*pi))) * exp(-0.5*x**2) xlist = linspace(-4,4,41) hlist = h(xlist) pairs = zip(xlist,hlist) plot(xlist, hlist, axis=[xlist[0], xlist[-1], 0, 0.5], xlabel='x', \ ylabel='h(x)', title='Standard Gaussian')
import numpy # Problem: u'=u def f(u, t): return u u0 = 1 T = 3 dt = 0.1 u, t = ForwardEuler(f, dt, u0, T) # compare numerical solution and exact solution in a plot: from scitools.std import plot, exp u_exact = exp(t) plot(t, u, 'r-', t, u_exact, 'b-', xlabel='t', ylabel='u', legend=('numerical', 'exact'), title="Solution of the ODE u'=u, u(0)=1") # Accuracy check for decreasing dt: for dt in 0.5, 0.05, 0.005: u, t = ForwardEuler(f, dt, u0, T) print 'dt=%.5f, u(%g)=%.6f, error=%g' % \
""" Exercise 5.6: Simulate by hand a vectorized expression Author: Weiyun Lu """ from scitools.std import array, sin, cos, exp, zeros x = array([0, 2]) t = array([1, 1.5]) y = zeros((2, 2)) f = lambda x, t: cos(sin(x)) + exp(1.0 / t) for i in range(2): for j in range(2): y[i][j] = f(x[i], t[j]) print y
def test_manufactured(): A=1 B=0 mx=1 my=1 b=1 c=1.1 #define some variables Lx = 2. Ly = 2. T = 1 C = 0.3 dt= 0.1 #help varabeles kx = pi*mx/Lx ky = pi*my/Ly w=1 #Exact solution ue = lambda x,y,t: A*cos(x*kx)*cos(y*ky)*cos(t*w)*exp(-c*t) I = lambda x,y: A*cos(x*kx)*cos(y*ky) V = lambda x,y: -c*A*cos(x*kx)*cos(y*ky) q = lambda x,y: x**2+y**2 f = lambda x,y,t:A*(-b*(c*cos(t*w) + w*sin(t*w))*cos(kx*x)*cos(ky*y) + c**2*cos(kx*x)*cos(ky*y)*cos(t*w) + 2*c*w*sin(t*w)*cos(kx*x)*cos(ky*y) + kx**2*(x**2 + y**2)*cos(kx*x)*cos(ky*y)*cos(t*w) + 2*kx*x*sin(kx*x)*cos(ky*y)*cos(t*w) + ky**2*(x**2 + y**2)*cos(kx*x)*cos(ky*y)*cos(t*w) + 2*ky*y*sin(ky*y)*cos(kx*x)*cos(t*w) - w**2*cos(kx*x)*cos(ky*y)*cos(t*w))*exp(-c*t) #factor dt decreeses per step step=0.5 #number of steps I want to do val=5 #array to store errors E=zeros(val) for i in range(val): v='vector' #solve eqation u,x,y,t,e=solver(I,V,f,q,b,Lx,Ly,dt*step**(i),T,C,8,mode=v,ue=ue) E[i]=e #find convergence rate between diffrent dt values r =zeros(val-1) r = log(E[1:]/E[:-1])/log(step) print print "Convergence rates for manufactured solution:" for i in range(val): if i==0: print "dt: ",dt," Error: ",E[i] else: print "dt: ",dt*step**(i)," Error: ",E[i], "rate of con.: ", r[i-1] #requiere "close" to 2 in convergence rate for last r. assert abs(r[-1]-2)<0.5
def test_manufactured(): A = 1 B = 0 mx = 1 my = 1 b = 1 c = 1.1 #define some variables Lx = 2. Ly = 2. T = 1 C = 0.3 dt = 0.1 #help varabeles kx = pi * mx / Lx ky = pi * my / Ly w = 1 #Exact solution ue = lambda x, y, t: A * cos(x * kx) * cos(y * ky) * cos(t * w) * exp(-c * t) I = lambda x, y: A * cos(x * kx) * cos(y * ky) V = lambda x, y: -c * A * cos(x * kx) * cos(y * ky) q = lambda x, y: x**2 + y**2 f = lambda x, y, t: A * ( -b * (c * cos(t * w) + w * sin(t * w)) * cos(kx * x) * cos(ky * y) + c **2 * cos(kx * x) * cos(ky * y) * cos(t * w) + 2 * c * w * sin( t * w) * cos(kx * x) * cos(ky * y) + kx**2 * (x**2 + y**2) * cos(kx * x) * cos(ky * y) * cos(t * w) + 2 * kx * x * sin(kx * x) * cos(ky * y) * cos(t * w) + ky**2 * (x**2 + y**2) * cos(kx * x) * cos(ky * y) * cos(t * w) + 2 * ky * y * sin(ky * y) * cos(kx * x) * cos(t * w) - w**2 * cos(kx * x) * cos( ky * y) * cos(t * w)) * exp(-c * t) #factor dt decreeses per step step = 0.5 #number of steps I want to do val = 5 #array to store errors E = zeros(val) for i in range(val): v = 'vector' #solve eqation u, x, y, t, e = solver(I, V, f, q, b, Lx, Ly, dt * step**(i), T, C, 8, mode=v, ue=ue) E[i] = e #find convergence rate between diffrent dt values r = zeros(val - 1) r = log(E[1:] / E[:-1]) / log(step) print print "Convergence rates for manufactured solution:" for i in range(val): if i == 0: print "dt: ", dt, " Error: ", E[i] else: print "dt: ", dt * step**( i), " Error: ", E[i], "rate of con.: ", r[i - 1] #requiere "close" to 2 in convergence rate for last r. assert abs(r[-1] - 2) < 0.5
# from __future__ import unicode_literals
def _g(x): return exp(-0.1 * x**2) * sin(pi / 2 * x)
from matplotlib.pyplot import * from scitools.std import zeros, exp n = 15 x = 3 #linspace(0,n,1000) z = zeros(n) for j in range(n): z[j] = (2 * j + 1) * exp((-j * (j + 1)) / (x)) plot(range(n), z) show()
def f(x,m,s): return (1.0/(sqrt(2*pi)*s))*exp(-0.5*((x-m)/s)**2)
def T(z, t): # T0, A, k, and omega are global variables return T0 + A1 * exp(-a1 * z) * cos(omega1 * t - a1 * z) + \ A2 * exp(-a2 * z) * cos(omega2 * t - a2 * z)
# Make a figure of a curve and "dart throws" for illustrating # Monte Carlo integration in 2D for area computations. import numpy as np xr = np.random.uniform(0, 2, 500) yr = np.random.uniform(0, 2.4, 500) x = np.linspace(0, 2, 51) from scitools.std import exp, sin, pi, plot y = 2 + x**2 * exp(-0.5 * x) * sin(pi * x) plot(x, y, 'r', xr, yr, 'o', hardcopy='tmp.eps')
def f(x, m, s): return (1.0/(sqrt(2*pi)*s))*exp(-0.5*((x-m)/s)**2)
def _g(x): return exp(-0.1*x**2)*sin(pi/2*x)
def value(self, x): from scitools.std import exp, sin a = self.a w = self.w return exp(-a * x) * sin(w * x) def __call__(self, x): return self.value(x) def __str__(self): return 'exp(-a*x)*sin(w*x)' def _test(): from math import pi f = F(a=1.0, w=0.1) print f(pi) f.a = 2 print f(pi) print f if __name__ == '__main__': _test() ''' python F2.py 0.013353835137 0.00057707154012 exp(-a*x)*sin(w*x) '''