Пример #1
0
print("Trying initial point %f..." % (x0))
x,err,res = iteration(f, g, x0, tol_err, tol_res, itmax)

x0 = 0.0
print("Trying initial point %f..." % (x0))
x,err,res = iteration(f, g, x0, tol_err, tol_res, itmax)

x0 = -0.1
print("Trying initial point %f..." % (x0))
x,err,res = iteration(f, g, x0, tol_err, tol_res, itmax)
# in the final run, the approximate solutions approaches minus infinity...

# now call the recursively programmed function
x0 = 1.0
print("Trying initial point %f with recursion..." % (x0))
x,err,res = recursion(f, g, x0, tol_err, tol_res, itmax)


# question 2 - Naming conflict with question 1. Comment Q1 and Uncomment code below to get answer.
#def f(x):
#    return math.exp(x-x**2)-x/2.0-1.0836
def fp(x):
    return (1.0-2.0*x)*math.exp(x-x**2)-0.5

# residual and error tolerance, number of iterations
tol_err = 1e-10
tol_res = 1e-10
itmax = 10

# initial point
x0 = 1.0
def match_sentence(sentence1, sentence2):
	#sentence1, sentence1_tag, sentence2_tag and sentence2 are arrays
	#print "sentence1:"
	#print sentence1
	#print "sentence2:"
	#print sentence2

	max_row = len(sentence1)
	max_col = len(sentence2)
	#print str(max_col) + " ======" + str(max_row)
	#create a two-dimensional array to record the Levenshtein distance
	memo = [[0 for col in range(max_col + 1)] for row in range(max_row + 1)]
	#initialize the two-dimensional array
	for i in range(max_row + 1):
		memo[i][0] = i
	for i in range(max_col + 1):
		memo[0][i] = i

	for j in range(1, max_col + 1):
		for k in range(1, max_row + 1):
			if cmp(sentence2[j - 1], sentence1[k - 1]) == 0:
				memo[k][j] = min(memo[k - 1][j] + 1, memo[k][j - 1] + 1)
				memo[k][j] = min(memo[k][j], memo[k - 1][j - 1])
			else:
				memo[k][j] = min(memo[k - 1][j] + 1, memo[k][j - 1] + 1)
				memo[k][j] = min(memo[k][j], memo[k - 1][j - 1] + 1)
	#print "matrix: " + str(memo[max_row][max_col])

	'''
	for i in range(len(memo)):
		for j in range(len(memo[0])):
			print str(memo[i][j]) + "   ",
		print
	'''

	row_coll = []
	col_coll = []
	row_index = len(memo) - 1
	col_index = len(memo[0]) - 1
	direc = []
	recursion(memo, row_coll, col_coll, row_index, col_index, direc)
	#print direc
	'''
	print "row_coll  " + str(row_coll)
	print "col_coll  " + str(col_coll)
	print direc
	'''
	'''
	for i in range(len(memo)):
		for j in range(len(memo[0])):
			print str(memo[i][j]) + "    ",
		print
	'''

	#former: sentence1; later: sentence2
	align = []
	#i: sentence1; j: sentence2
	for i in range(len(direc)):
		if (direc[i] == "transpose") and (sentence1[row_coll[i] - 1] == sentence2[col_coll[i] - 1]):
			continue
		elif (direc[i] == "transpose") and  (not (sentence1[row_coll[i] - 1] == sentence2[col_coll[i] - 1])):
			align.append(str(row_coll[i] - 1) + "," + str(col_coll[i] - 1))
		elif (direc[i] == "up"):
			align.append(str(row_coll[i] - 1) + "," + str(-1))
		else:
			align.append(str(-1) + "," + str(col_coll[i] - 1))
	#print align
	'''
	print "row_coll"
	print row_coll
	print "col_coll"
	print col_coll
	'''
	align_up = []
	align_down = []
	for i in range(len(align)):
		#print "align[i]= " + align[i]
		arr = align[i].split(",")
		align_up.append(int(arr[0]))
		align_down.append(int(arr[1]))
	#print align_up
	#print align_down



	#count the number of unalignments
	count = 0
	for i in range(len(align_up)):
		if align_up[i] == -1:
			if (i > 0) and (align_down[i - 1] + 1 == align_down[i]) and (align_up[i - 1] == -1):
				#print "align_up[i] == -1 && match && i + count: " + str(i) + str(count)
				continue
			else:
				#print "align_up[i] == -1 && not match && i + count: " + str(i) + str(count)
				count = count + 1
		elif align_down[i] == -1:
			if (i > 0) and (align_up[i - 1] + 1 == align_up[i]) and (align_down[i - 1] == -1):
				#print "align_down[i] == -1 && match && i + count: " + str(i) + str(count)
				continue
			else:
				#print "align_dwon[i] == -1 && not match && i + count: " + str(i) + str(count)
				count = count + 1
		else:
			#print "transpose && i + count: " + str(i) + str(count)
			count = count + 1
	#print "count:" + str(count) 



	#print "finish-------------"

	#analyze conditions of transposition
	return count, align
Пример #3
0
"""
Assignment 1
Question 1 test script for both iteration.py and recursion.py
Author: Hassan Tariq, 100657119
"""

from iteration import iteration
from recursion import recursion
import math
pi = math.pi

# Define both function
def f(x):
    return math.sin(pi*x) - x*x

# Define derivative of function
def g(x):
    return 1/(2*math.pi) * math.sin(math.pi*x) - 1/(2*math.pi) * x**2 + x

#Initialize variables
x0 = 1
tolx = tolf = 1e-6
kmax = 50
print("\n\tIterative solution for question 1")
iteration(f, g, x0, kmax, tolx, tolf)

# Initialize extra recursion counter variable
i = 0
print("\n\n\tRecursive solution for question 1")
recursion(f, g, x0, tolx, tolf, kmax, i)
Пример #4
0
def compute_single_defect(xd, yd, x, y, phi, phi_nematic, cid, sim, cell_list, \
                          possible_defect_pts, pt_colors, \
                          rn, nn, total_rec_num, dcut, fig_cnt):
    """ compute the defect strength of a single point given with (xd, yd)"""

    ### allocate array to divide the full circle into orthants

    nseg = 10
    DEFECT_BOOL = False

    ### calculate and average the order parameter matrix per orthant

    qxx, qxy, qyy, xcm, ycm = calculate_order_param_matrix(
        xd, yd, nseg, x, y, phi_nematic, sim, cell_list)

    ### calculate the nematic directors per orthant

    directors, corrected_directors = calculate_nematic_directors(
        qxx, qxy, qyy, nseg)

    ### determine the defect strength

    dmax = calculate_defect_strength(corrected_directors)
    cc = 'colors'

    ### check for -1/2 defects

    if (dmax > -dcut - 0.5 and dmax < dcut - 0.5):
        DEFECT_BOOL = True
        cc = 'r'
        possible_defect_pts.append([xd, yd, dmax])
        pt_colors.append(cc)

    ### check +1/2 defects

    elif (dmax > 0.5 - dcut and dmax < dcut + 0.5):
        DEFECT_BOOL = True
        cc = 'g'
        possible_defect_pts.append([xd, yd, dmax])
        pt_colors.append(cc)

    ### if the point is not a defect

    else:
        return

    ### search around friends of friends total_rec_num times max

    if DEFECT_BOOL:
        #print "Commencing recursion loop"
        friend_list = recursion.find_friends(dmax, xd, yd, cell_list.rcut, rn,
                                             nn)
        recursion.recursion(possible_defect_pts, friend_list, dmax, cc, rn, nn, x, y, \
      phi_nematic, nseg, \
      cid, sim, cell_list, \
      possible_defect_pts, \
      pt_colors, fig_cnt, total_rec_num, 0)

    ### plot the defects

#    if len(pt_colors) % 50 == 0:
#        savepath = '/usr/users/iff_th2/duman/Desktop/figcontainer/fig_' + str(fig_cnt) + '.png'
#        plot_defects.plot_defect(x, y, phi, phi_nematic, cid, xd, yd, directors, corrected_directors, \
#                        dmax, sim, cell_list, possible_defect_pts, pt_colors, xcm, ycm, savepath)

    return
Пример #5
0
n = 1
i = 0
while n <= 99:
    L.insert(i, n)
    i += 1
    n += 2
print(L[-2:])
print([L[0], L[1], L[2]])  # 取出前三个元素笨方法
r = []
j = 3
for x in range(j):
    r.append(L[x])  # for取出前三个元素方法
print(r)

print('*******************')
print(recursion(5))
print(recursion(100))

print('*******************')

print(power(5))
print(power(5, 4))

print('*******************')

print(calc(1, 2, 3, 4, 5, 6, 7, 8))

print('*******************')

print('product(5) =', product(5))
print('product(5, 6) =', product(5, 6))
Пример #6
0
from maps import MapPractice
from recursion import recursion

self = recursion()

# Code for calculating the power
print recursion.pow(self, 2, 4)

# Code for writing the fibonacci sequence n times
#print recursion.fibonacci(self, 1)
#print recursion.fibonacci(self, 3)
#print recursion.fibonacci(self, 5)
#print recursion.fibonacci(self, 7)

# Code for writing numbers in order
#recursion.writeNums(self, 1)
#print "\n"
#recursion.writeNums(self, 2)
#print "\n"
#recursion.writeNums(self, 5)
#print "\n"
#recursion.writeNums(self, 12)
#print "\n"


# Maps test code

#self = MapPractice()

# Code for containsThree
#first = ["to", "be", "or", "not", "to", "be", "hamlet"]