예제 #1
0
    def area(self):
        from scitools.std import array, sqrt
        from numpy import dot, cross
        v1 = array(self.v1)
        v2 = array(self.v2)
        v3 = array(self.v3)
        v2 = v2 - v1
        v3 = v3 - v1
        v1 = v1 - v1  # now v1 is at the origin

        return abs(cross(v2, v3)) / 2.0
예제 #2
0
	def area(self):
		from scitools.std import array, sqrt
		from numpy import dot, cross
		v1 = array(self.v1)
		v2 = array(self.v2)
		v3 = array(self.v3)
		v2 = v2 - v1
		v3 = v3 - v1 
		v1 = v1 - v1 # now v1 is at the origin
	
		return abs(cross(v2,v3))/2.0
예제 #3
0
def _test():
    from scitools.std import sin, pi, array
    s = Integral(sin, 0)
    x = array([pi / 4, pi / 2, 3 * pi / 4, pi])
    a = s(x)
    print 'The integral of sin(x) for'
    for i in range(4):
        print '0 to %.2f' % x[i], 'is %.2f' % a[i]
예제 #4
0
def _test():
	from scitools.std import sin, pi, array
	s = Integral(sin, 0)
	x = array([pi/4, pi/2, 3*pi/4, pi])
	a = s(x)
	print 'The integral of sin(x) for'
	for i in range(4):
		print '0 to %.2f' % x[i], 'is %.2f' % a[i]
예제 #5
0
	def circumference(self):
		from scitools.std import array, sqrt
		from numpy import dot
		v1 = array(self.v1)
		v2 = array(self.v2)
		v3 = array(self.v3)
		v2 = v2 - v1
		v3 = v3 - v1 #now v1 is at the origin
		v1 = v1 - v1
	
		side1 = sqrt(dot(v2,v2))
		side2 = sqrt(dot(v3,v3))
		v1 = v1 - v2
		v3 = v3 - v2
		v2 = v2 - v2 #now v2 is at the origin
	
		side3 = sqrt(dot(v3, v3))
		return side1 + side2 + side3
예제 #6
0
    def circumference(self):
        from scitools.std import array, sqrt
        from numpy import dot
        v1 = array(self.v1)
        v2 = array(self.v2)
        v3 = array(self.v3)
        v2 = v2 - v1
        v3 = v3 - v1  #now v1 is at the origin
        v1 = v1 - v1

        side1 = sqrt(dot(v2, v2))
        side2 = sqrt(dot(v3, v3))
        v1 = v1 - v2
        v3 = v3 - v2
        v2 = v2 - v2  #now v2 is at the origin

        side3 = sqrt(dot(v3, v3))
        return side1 + side2 + side3
예제 #7
0
def trapezoidal_vectorized(f, a, x, n):
	h = (x-a)/float(n)
	I = 0.5*f(a)
	from scitools.std import array
	s = f(a + array(range(1,n))*h)
	I += sum(s)
	I += 0.5*f(x)
	I *= h
	return I
예제 #8
0
def trapezoidal_vectorized(f, a, x, n):
    h = (x - a) / float(n)
    I = 0.5 * f(a)
    from scitools.std import array
    s = f(a + array(range(1, n)) * h)
    I += sum(s)
    I += 0.5 * f(x)
    I *= h
    return I
예제 #9
0
def midpointsum_num(f,a,b,n):
    h = float(b - a) / n
    x = array([f(a-0.5*h + i * h) for i in range(1,n+1)])
    s = h * np.sum(x[i] for i in range(len(x)))
    return s

# %timeit results with f(x)=x^2, 0, 10, 100
# midpointint: 10000 loops, best of 3: 125 microseconds per loop
# midpointsum_py: 10000 loops, best of 3: 185 microseconds per loop
# midpointsum_num: 10000 loops, best of 3: 179 microseconds per loop
예제 #10
0
def trapezoidal(f, a, x, n):
	from scitools.std import array, iseq, linspace, zeros
	x = array(x)
	I = zeros(len(x))
	index = 0
	new_sum = 0
	old_sum = 0
	for i in x:
		new_sum = 0.5*f(a)
		h = (i-a)/float(n)
		new_sum += sum(f(a + array(range(1,n))*h))
		new_sum += 0.5*f(i)
		new_sum *= h
		new_sum += old_sum
		I[index] = new_sum
		index += 1
		a = i
		old_sum = new_sum	
	if len(I) == 1:
		return I[0]
	else:
		return I
예제 #11
0
def trapezoidal(f, a, x, n):
    from scitools.std import array, iseq, linspace, zeros
    x = array(x)
    I = zeros(len(x))
    index = 0
    new_sum = 0
    old_sum = 0
    for i in x:
        new_sum = 0.5 * f(a)
        h = (i - a) / float(n)
        new_sum += sum(f(a + array(range(1, n)) * h))
        new_sum += 0.5 * f(i)
        new_sum *= h
        new_sum += old_sum
        I[index] = new_sum
        index += 1
        a = i
        old_sum = new_sum
    if len(I) == 1:
        return I[0]
    else:
        return I
예제 #12
0
파일: oppgg.py 프로젝트: andrenos/Inf5620
def main(nx, dt):
    # Parameters
    T = 1.0
    rho = 1.0
    # Create mesh and define function space
    mesh = UnitIntervalMesh(nx)
    V = FunctionSpace(mesh, 'Lagrange', 1)

    # Define boundary conditions
    u0 = Expression('t * x[0]*x[0]*(0.5 - x[0]/3.)', t=0)
    # Initial condition
    u_1 = interpolate(u0, V)

    #Define variational problem
    u = TrialFunction(V)
    v = TestFunction(V)

    f = Expression('rho*x[0]*x[0]*(-2*x[0] + 3)/6. - \
		(-12*t*x[0] + 3*t*(-2*x[0] + 3))*(pow(x[0],4.)*\
		pow((-dt + t),2)*pow((-2*x[0] + 3),2.) + 36)/324.\
		- (-6*t*x[0]*x[0] + 6*t*x[0]*(-2*x[0] + 3))*\
		(36*pow(x[0],4.)*pow((-dt + t),2.)*(2*x[0] - 3)+\
		36*pow(x[0],3.)*pow((-dt + t),2.)*pow((-2*x[0] + 3),2.))/5832.',
                   rho=rho,
                   dt=dt,
                   t=0)
    a = u * v * dx + (dt / rho) * (1 - u_1**2) * inner(nabla_grad(u),
                                                       nabla_grad(v)) * dx
    L = u_1 * v * dx + (dt / rho) * f * v * dx

    u = Function(V)

    # Initial condition already stored in u_1, so start iteration at t=dt
    t = dt
    counter = 1
    E = []
    while t <= T:
        u0.t = t
        f.t = t
        solve(a == L, u)
        u_e = interpolate(u0, V)
        e = u_e.vector().array() - u.vector().array()
        E.append(numpy.sqrt(numpy.sum(e**2) / u.vector().array().size))
        if (counter % 10 == 0):
            print e

        u_1.assign(u)  # Copy solution to u_1 to prepare for next time-step
        t += dt
        counter += 1
    return array(E).max()
예제 #13
0
파일: oppgg.py 프로젝트: andrenos/Inf5620
def main(nx, dt):
	# Parameters
	T = 1.0
	rho = 1.0
	# Create mesh and define function space
	mesh = UnitIntervalMesh(nx)
	V = FunctionSpace(mesh, 'Lagrange', 1)
	
	# Define boundary conditions
	u0 = Expression('t * x[0]*x[0]*(0.5 - x[0]/3.)', t=0)
	# Initial condition
	u_1 = interpolate(u0, V)
	
	
	#Define variational problem
	u = TrialFunction(V)
	v = TestFunction(V)
	
	f = Expression('rho*x[0]*x[0]*(-2*x[0] + 3)/6. - \
		(-12*t*x[0] + 3*t*(-2*x[0] + 3))*(pow(x[0],4.)*\
		pow((-dt + t),2)*pow((-2*x[0] + 3),2.) + 36)/324.\
		- (-6*t*x[0]*x[0] + 6*t*x[0]*(-2*x[0] + 3))*\
		(36*pow(x[0],4.)*pow((-dt + t),2.)*(2*x[0] - 3)+\
		36*pow(x[0],3.)*pow((-dt + t),2.)*pow((-2*x[0] + 3),2.))/5832.',
		rho=rho, dt=dt, t=0)
	a = u*v*dx + (dt/rho)*(1-u_1**2)*inner(nabla_grad(u), nabla_grad(v))*dx		
	L = u_1*v*dx + (dt/rho)*f*v*dx 
	
	u = Function(V)
	
	# Initial condition already stored in u_1, so start iteration at t=dt
	t = dt
	counter = 1
	E=[]
	while t<=T:
		u0.t = t; f.t = t
		solve(a==L, u)
		u_e = interpolate(u0, V)
		e = u_e.vector().array() - u.vector().array()
		E.append(numpy.sqrt(numpy.sum(e**2)/u.vector().array().size))
		if(counter%10 == 0):
			print e
		
		u_1.assign(u) # Copy solution to u_1 to prepare for next time-step
		t += dt
		counter += 1
	return array(E).max()
예제 #14
0
        '''
		graphs the Lagrange polynomial over self.points	
		'''
        #from scitools.std import *
        from scitools.std import zeros, linspace, plot, array
        points = self.points
        xlist = linspace(points[0, 0], points[-1, 0], resolution)
        ylist = self.__call__(xlist)
        plot(xlist, ylist)


if __name__ == '__main__':
    from scitools.std import *
    x = linspace(0, pi, 5)
    y = sin(x)
    points = array(zip(x, y))
    l = Lagrange(points)
    l.verify()

    figure()
    hold('on')
    axis([-.1, pi + .1, -.1, 1.1])
    for i in [5, 10, 20, 55, 70, 100]:
        x = linspace(0, pi, i)
        y = sin(x)
        points = array(zip(x, y))
        l = Lagrange(points)
        l.graph()
        xlabel('x')
        ylabel('y')
        legend('n = %d' % i)
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')
예제 #16
0
 def __init__(self, coefficients):
     from scitools.std import array
     self.coeff = array(coefficients)
예제 #17
0
infile = open('lnoutput.txt', 'r')
eps = []  #intialize three empty lists
exa = []
enn = []
for line in infile:
    if line.find('epsilon:') == -1:  #if we can't find epsilon, skip this line
        continue
    else:  #otherwise, process the line
        words = line.split(',')
        epsilon = float(words[0].split(':')[1].strip())
        exact = float(words[1].split(':')[1].strip())
        n = float(words[2].split('=')[1].strip())
        eps.append(epsilon)
        exa.append(exact)
        enn.append(n)
eps = array(eps)  #convert lists to arrays
exa = array(exa)
enn = array(enn)
infile.close()

semilogy(enn,
         eps,
         '-b',
         enn,
         exa,
         '-r',
         xlabel='n',
         ylabel='Log of eps/error',
         legend=['epsilon', 'exact error'],
         title='Ln sum errors')
"""
Exercise 5.14: Plot data in a two-column file
Author: Weiyun Lu
"""

from scitools.std import plot, array, average

myfile = open('xydat.txt', 'r')
x = []
y = []

for line in myfile:
    w1 = float(line.split()[0])
    w2 = float(line.split()[1])
    x.append(w1)
    y.append(w2)

plot(x, y)
y = array(y)
avg = average(y)
maxi = max(y)
mini = min(y)
myfile.close()

print 'The mean is', avg, 'the min value is', mini, 'and the max value is', maxi, '.'
예제 #19
0
from scitools.std import array, plot

infile = open("../output/TEST3.txt", 'r')

n = []
t = [[],[],[]]
i = [[],[],[]]

for line in infile:
    if line.startswith("n="):
        n.append(int(line.split("=")[1]))
    else:
        tmp = line.split(":")
        j = int(tmp[0])
        t[j].append(float(tmp[2]))
        i[j].append(int(tmp[3]))
        

t0 = array(t[0])/array(i[0])
t1 = array(t[1])/array(i[1])
t2 = array(t[2])/array(i[2])

T = array([t0, t1, t2])
styles = ["k--","k:","k-."]
methods = ["QR", "HessenbergQR", "shiftedQR"]

for i in range(1, len(T)):
    plot(n, T[i,:], styles[i], hold="on",legend=methods[i], title="Comparison of runtime pr. iteration. n = matrix dim.", ylabel="n", xlabel="runtime/iteration [s]")
    
raw_input()
예제 #20
0
def midpointsum_py(f,a,b,n):
    h = float(b - a) / n
    x = array([f(a-0.5*h + i * h) for i in range(1,n+1)])
    s = h * sum(x[i] for i in range(len(x)))
    return s
예제 #21
0
 def __init__(self, coefficients):
     from scitools.std import array
     self.coeff = array(coefficients)
예제 #22
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
예제 #23
0
		graphs the Lagrange polynomial over self.points	
		'''
		#from scitools.std import *
		from scitools.std import zeros, linspace, plot, array
		points = self.points
		xlist = linspace(points[0,0], points[-1,0], resolution)
		ylist = self.__call__(xlist)
		plot(xlist, ylist)

	

if __name__ == '__main__':
	from scitools.std import *
	x = linspace(0, pi, 5)
	y = sin(x)
	points = array(zip(x,y))
	l = Lagrange(points)
	l.verify()
	
	figure()
	hold('on')
	axis([-.1, pi+.1, -.1, 1.1])
	for i in [5,10,20,55,70, 100]:
		x = linspace(0, pi, i)
		y = sin(x)
		points = array(zip(x,y))
		l = Lagrange(points)	
		l.graph()
		xlabel('x')
		ylabel('y')
		legend('n = %d' % i)
예제 #24
0
    elif 30 <= i <= 39:
        hat[i] = 'purple'

from scitools.std import array, append
import copy
N = 10**4
successes = 0
total = 0
for i in range(N):
    temp = copy.deepcopy(hat)
    selection = []
    for j in range(10):
        pick = random.choice(temp)
        temp.remove(pick)
        selection = append(selection, pick)
    n_blue = sum(array(selection) == 'blue')
    n_purple = sum(array(selection) == 'purple')
    if n_blue == 2 and n_purple == 2:
        successes += 1
    total += 1

print 'Our probability of picking two blue balls and two'
print 'purple balls from ten picks without repalcement is'
print '%.6f' % (float(successes) / total)
'''
python 4balls_from10.py
Our probability of picking two blue balls and two
purple balls from ten picks without repalcement is
0.090600
'''
예제 #25
0
	elif 30 <= i <= 39:
		hat[i] = 'purple'

from scitools.std import array, append
import copy
N = 10**4
successes = 0
total = 0
for i in range(N):
	temp = copy.deepcopy(hat)
	selection = []
	for j in range(10):
		pick = random.choice(temp)
		temp.remove(pick)
		selection = append(selection, pick)
	n_blue = sum(array(selection) == 'blue')
	n_purple = sum(array(selection) == 'purple')
	if n_blue == 2 and n_purple == 2:
		successes += 1
	total += 1

print 'Our probability of picking two blue balls and two'
print 'purple balls from ten picks without repalcement is'
print '%.6f' % (float(successes) / total)

'''
python 4balls_from10.py
Our probability of picking two blue balls and two
purple balls from ten picks without repalcement is
0.090600
'''
예제 #26
0
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',
         legend=(['Instaneous velocity=%6f' % velo, 'present location']),
         savefig='pix/planet%4d.png' % counter)
    counter += 1
예제 #27
0
    def __call__(self, x):
        """Evaluate the polynomial."""
        from scitools.std import array
	x_values = array([x**i for i in range(len(self.coeff))])
	s = sum(self.coeff * x_values)
        return s