def smoothed_Heaviside(x, e=1E-2):
    cond = operator.and_(-e <= x, x <= e)
    r = np.zeros(len(x))
    r[x < -e] = 0.0
    r[cond] = 0.5 + x[cond] / (2 * e) + 1 / (2 * pi) * sin(pi * x[cond] / e)
    r[x > e] = 1.0
    return r
Exemple #2
0
def _test1():
	f = lambda x: x**5 - sin(x)
	x0 = 1
	x1 = 2
	N = 100
	epsilon = 1e-10
	x, info = Secant(f, x0, x1,epsilon,N, True)
	
	info = transpose(info)
	x_values = info[0]
	f_values = info[1]
	
	
	figure()
	plot(x_values,
		xlabel='Iteration Number',
		ylabel='x_i',
		title='Secant method for f = x**5 - sin(x), '\
			'Iteration number vs. x_i')
	
	figure()
	semilogy(f_values,
		xlabel='Iteration Number',
		ylabel='f(x_i)',
		axes=[0, len(f_values), -1e-1,1e-1],
		title='Secant method for f = x**5 - sin(x), '\
			'Iteration number vs. f(x_i)')
	
	raw_input('Press Enter to quit: ')
Exemple #3
0
def _test1():
    f = lambda x: x**5 - sin(x)
    x0 = 1
    x1 = 2
    N = 100
    epsilon = 1e-10
    x, info = Secant(f, x0, x1, epsilon, N, True)

    info = transpose(info)
    x_values = info[0]
    f_values = info[1]

    figure()
    plot(x_values,
     xlabel='Iteration Number',
     ylabel='x_i',
     title='Secant method for f = x**5 - sin(x), '\
      'Iteration number vs. x_i')

    figure()
    semilogy(f_values,
     xlabel='Iteration Number',
     ylabel='f(x_i)',
     axes=[0, len(f_values), -1e-1,1e-1],
     title='Secant method for f = x**5 - sin(x), '\
      'Iteration number vs. f(x_i)')

    raw_input('Press Enter to quit: ')
def smoothed_Heaviside(x, e=1E-2):
    cond = operator.and_(-e <= x, x <= e)
    r = np.zeros(len(x))
    r[x < -e] = 0.0
    r[cond] = 0.5 + x[cond] / (2 * e) + 1 / (2 * pi) * sin(pi * x[cond] / e)
    r[x > e] = 1.0
    return r
Exemple #5
0
def _test2():
	from scitools.std import sin
	f = lambda x: sin(x)
	x0 = 1
	x1 = 2
	x, info = Secant(f, x0, x1,1e-10,100, True)
	x_values = transpose(info)[0]
	f_values = transpose(info)[1]
	for i in range(len(x_values)):
		print '%10f %10f' % (x_values[i], f_values[i])
Exemple #6
0
def _test2():
    from scitools.std import sin
    f = lambda x: sin(x)
    x0 = 1
    x1 = 2
    x, info = Secant(f, x0, x1, 1e-10, 100, True)
    x_values = transpose(info)[0]
    f_values = transpose(info)[1]
    for i in range(len(x_values)):
        print '%10f %10f' % (x_values[i], f_values[i])
Exemple #7
0
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)
Exemple #8
0
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 pi_approx(N):
    '''
	Calculates the approximation to pi by computing
	the path length of a polygon with N points inscribed
	in the circle of radius 1
	'''
    from scitools.std import sin, pi
    x = [1. / 2 * cos(2. * pi * i / (N)) for i in range(N + 1)]
    y = [1. / 2 * sin(2. * pi * i / (N)) for i in range(N + 1)]
    approx = pathlength(x, y)
    return approx
def H(x,e):
	'''
	A smooth, continuous version of the Heaviside function
	evaluated at x.
	e is epsilon, of which we transition from 0 to 1 from
	-e <= x <= e
	'''
	from scitools.std import pi, sin
	# we must use there where() fn since x may be an array
	import operator
	condition = operator.and_(-e <= x, x <= e)
	i = where(x > e, 1, x)
	i = where(condition, 1./2 + x/(2.*e) + 1./(2*pi)*sin(pi*x/e), i)
	i = where(x < -e, 0, i)
	return i
def H(x, e):
    '''
	A smooth, continuous version of the Heaviside function
	evaluated at x.
	e is epsilon, of which we transition from 0 to 1 from
	-e <= x <= e
	'''
    from scitools.std import pi, sin
    # we must use there where() fn since x may be an array
    import operator
    condition = operator.and_(-e <= x, x <= e)
    i = where(x > e, 1, x)
    i = where(condition,
              1. / 2 + x / (2. * e) + 1. / (2 * pi) * sin(pi * x / e), i)
    i = where(x < -e, 0, i)
    return i
    return s


def test_p_L(xp, yp):
    n = len(xp) - 1
    eps = 10e-12
    count = 0  #count how many answers are not close enough
    for k in range(n + 1):
        if abs(p_L(xp[k], xp, yp) - yp[k]) > eps:
            count += 1
    if count == 0:
        print 'Success!  The Lagrange interpolation polynomial indeed passes',\
        'through all the points (xp,yp).'
    else:
        print 'Oh no!  There were %d points where the interpolation polynomial'\
        %(count), 'fails to pass through (xp,yp).'


def graph(f, n, xmin, xmax, resolution=1001):
    Xp = linspace(xmin, xmax, n)
    Yp = f(Xp)
    Xr = linspace(xmin, xmax, resolution)  #array of values to plot
    Yr = array([p_L(x, Xp, Yp) for x in Xr])  #get interpolation points
    plot(Xr, Yr, '-r', Xp, Yp, 'bo', title='Lagrange Interpolation')


if __name__ == '__main__':
    XP = linspace(0, pi, 5)
    YP = sin(XP)
    test_p_L(XP, YP)
    graph(sin, 5, 0, pi)
Exemple #13
0
def points(N):
    x = [0.5 * cos(2 * pi * i / N) for i in range(N + 1)]
    y = [0.5 * sin(2 * pi * i / N) for i in range(N + 1)]
    return x, y
Exemple #14
0
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)
Exemple #15
0
"""
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')
Exemple #16
0
	def value(self, x):
		from scitools.std import exp, sin
		a = self.a
		w = self.w
		return exp(-a*x)*sin(w*x)
Exemple #17
0
def _g(x):
    return exp(-0.1 * x**2) * sin(pi / 2 * x)
Exemple #18
0
def _g(x):
    return exp(-0.1*x**2)*sin(pi/2*x)
Exemple #19
0
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)
Exemple #20
0
# 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 points(N):
    x = [0.5 * cos(2 * pi * i / N) for i in range(N + 1)]
    y = [0.5 * sin(2 * pi * i / N) for i in range(N + 1)]
    return x, y
Exemple #22
0
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
Exemple #23
0
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
Exemple #24
0
# 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')
Exemple #25
0
    s = 0  #initialize sum
    n = len(xp) - 1
    for k in range(n + 1):
        s += yp[k] * L_k(x, k, xp, yp)
    return s


def test_p_L(xp, yp):
    n = len(xp) - 1
    eps = 10e-12
    count = 0  #count how many answers are not close enough
    for k in range(n + 1):
        if abs(p_L(xp[k], xp, yp) - yp[k]) > eps:
            count += 1
    if count == 0:
        print 'Success!  The Lagrange interpolation polynomial indeed passes',\
        'through all the points (xp,yp).'
    else:
        print 'Oh no!  There were %d points where the interpolation polynomial'\
        %(count), 'fails to pass through (xp,yp).'


if __name__ == '__main__':
    Xp = linspace(0, pi, 5)
    Yp = sin(Xp)
    test_p_L(Xp, Yp)
    x = Xp[2] - Xp[1] / 2.0
    y = sin(x)
    y_inter = p_L(x, Xp, Yp)
    print 'Take the point between Xp[1] and Xp[2].  Evaluating the sin function',\
    'directly yields %.6f, whilst the interpolated value is %.6f.' %(y, y_inter)
Exemple #26
0
"""
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
Exemple #27
0
for name in glob.glob('pix/planet*.png'):
    os.remove(name)

n = 100  #we want 100 frames
a = 1  #set parameters for the orbit
b = 1
w = 1
delta_t = (2 * pi) / (w * n)
counter = 0
X = []
Y = []

for k in range(n + 1):
    tk = k * delta_t  #each time through we need to add a new k value
    x = a * cos(w * tk)
    y = b * sin(w * tk)
    X.append(x)
    Y.append(y)
    XP = array(X)
    YP = array(Y)
    XF = array([x])
    YF = array([y])
    velo = w * sqrt(a**2 * sin(w * tk)**2 + b**2 * cos(w * tk)**2)
    plot(XP,
         YP,
         '-r',
         XF,
         YF,
         'bo',
         axis=[-1.2, 1.2, -1.2, 1.2],
         title='Planetary orbit',
	Calculates the approximation to pi by computing
	the path length of a polygon with N points inscribed
	in the circle of radius 1
	'''
    from scitools.std import sin, pi
    x = [1. / 2 * cos(2. * pi * i / (N)) for i in range(N + 1)]
    y = [1. / 2 * sin(2. * pi * i / (N)) for i in range(N + 1)]
    approx = pathlength(x, y)
    return approx


N = array(range(3, 31))
count = 0
C = 1000  # points with which we draw the circle
xcircle = [1. / 2 * cos(2. * pi * i / C) for i in range(C + 1)]
ycircle = [1. / 2 * sin(2. * pi * i / C) for i in range(C + 1)]
xmin = -.55
xmax = .55
ymin = xmin
ymax = .65
for n in N:
    x = [1. / 2 * cos(2. * pi * i / n) for i in range(n + 1)]
    y = [1. / 2 * sin(2. * pi * i / n) for i in range(n + 1)]
    plot(x,
         y,
         '-o-',
         xcircle,
         ycircle,
         axis=[xmin, xmax, ymin, ymax],
         xlabel='x',
         ylabel='y',