本文整理汇总了Python中polynomial.Polynomial类的典型用法代码示例。如果您正苦于以下问题:Python Polynomial类的具体用法?Python Polynomial怎么用?Python Polynomial使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Polynomial类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_scale_1
def test_scale_1(self):
one = Polynomial([2,4,7,3])
scalar = 12
r = one.scale(12)
self.assertEqual(list(r.coefficients), [24, 48, 84, 36])
示例2: test_scale
def test_scale(self):
one = Polynomial(map(GF2int, [2,14,7,3]))
scalar = 12
r = one.scale(12)
self.assertEqual(list(r.coefficients), [24, 72, 36, 20])
示例3: test_mul_at
def test_mul_at(self):
one = Polynomial(map(GF2int, [2,4,7,3]))
two = Polynomial(map(GF2int, [5,2,4,2]))
k = 3
r1 = one * two
r2 = one.mul_at(two, k)
self.assertEqual(r1.get_coefficient(k), r2)
示例4: polynomialbasin
def polynomialbasin(coeffs, vw, auto=False, n=10, dots=True, mode=1, filename=None, save=True):
p = Polynomial(*coeffs)
rootlist = list(p.roots())
rootlist.sort(cmp=argcmp)
if auto:
vw.autocomplex(*rootlist)
if filename is None:
filename = "polynomialbasin {poly} {n} {dots} {time}".format(poly=p, n=n, dots=dots, time=str(int(time())))
return globals()["basin" + str(mode) * (mode in (2, 3))](p, rootlist, Color.colors(len(rootlist)), vw, p.deriv(), n,
dots, filename, save)
示例5: test_div_fast
def test_div_fast(self):
one = Polynomial(map(GF2int, [8,3,5,1]))
two = Polynomial(map(GF2int, [5,3,1,1,6,8]))
q, r = two._fastdivmod(one)
self.assertEqual(list(q.coefficients), [101, 152, 11])
self.assertEqual(list(r.coefficients), [183, 185, 3])
# Make sure they multiply back out okay
self.assertEqual(q*one + r, two)
示例6: test_div_fast_1
def test_div_fast_1(self):
# no remander
one = Polynomial([1,0,0,2,2,0,1,-2,-4])
two = Polynomial([1,0,-1])
q, r = one._fastdivmod(two)
self.assertEqual(q, one._fastfloordiv(two))
self.assertEqual(r, one._fastmod(two))
self.assertEqual(list(q.coefficients), [1,0,1,2,3,2,4])
self.assertEqual(list(r.coefficients), [0])
示例7: main
def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print 'single.py -i <inputfile> -o <outputfile>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'single.py -i <inputfile> -o <outputfile> '
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
try:
fi = open(inputfile,"r")
fl = open(outputfile,"a")
except IOError:
print 'main.py -i <inputfile> -o <outputfile>'
sys.exit(2)
l = []
for i in fi:
p = Polynomial(i)
l.append(p)
name = outputfile
name = name + ".xlsx"
name = "" + name
workbook = xlsxwriter.Workbook(name)
worksheet = workbook.add_worksheet("irredutiveis")
worksheet.write(0,0, "Polynomials")
worksheet.write(0,1, "m")
worksheet.write(0,2, "a")
worksheet.write(0,3, "b")
worksheet.write(0,4, "c")
worksheet.write(0,5, "d")
row = 1
colum = 0
for p in l:
colum = 0
worksheet.write(row,colum, str(p.coefs()))
colum = 1
j = sorted(p.coefs(), reverse=True)
for num in j:
worksheet.write(row,colum, num)
colum = colum+1
row = row + 1
workbook.close()
示例8: main
def main(argv):
inputfile = ''
outputfile = ''
debug = False
try:
opts, args = getopt.getopt(argv,"hi:o:d",["ifile=","ofile="])
except getopt.GetoptError:
print 'single.py -i <inputfile> -o <outputfile>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'single.py -i <inputfile> -o <outputfile> -d for debug'
sys.exit()
elif opt in ("-d", "--debug"):
debug = True
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
try:
fi = open(inputfile,"r")
fl = open(outputfile,"a")
except IOError:
print 'main.py -i <inputfile> -o <outputfile>'
sys.exit(2)
l = []
pols = []
files = [inputfile]
for fileName in files:
save = outputfile
f = open(fileName,'r')
#read, pols = recoverfile(save, f)
if True:
for line in f:
try:
pol = Polynomial(line)
pols.append(pol)
except Exception as e:
print line
sys.exit(2)
result = defaultdict(list)
print len(pols)
for pol in pols:
if len(pol.coefs()) > 1:
red = Reduction(debug)
count = red.reduction(pol.coefs())
result = str(pol.coefs()) + ":" + str(count)
print result
fl.write(result + "\n")
示例9: test_simple_operations
def test_simple_operations(self):
"""tests with some specific polynomials"""
p1 = Polynomial([2.,0,3.,0]) # 2 + 3x^2
self.assertEqual(str(p1), '2.0 + 3.0X^2')
self.assertEqual(repr(p1), 'Polynomial([2.0, 0.0, 3.0])')
p2 = Polynomial([3.,2.]) #3 + 2x
self.assertEqual(str(p2), '3.0 + 2.0X')
self.assertEqual(p1.degree(), 2)
self.assertEqual(p1[4], 0, "Index out of range should return zero")
self.assertEqual(p1[0], 2)
self.assertEqual(p1+p2, Polynomial([5,2,3]))
self.assertEqual(p1.differentiate(), Polynomial([0,6]))
self.assertEqual(p1(2), 14)
self.assertEqual(p1*p2, Polynomial([6., 4., 9., 6.]))
示例10: recover
def recover(shares, pword=""):
#Intial Stuff
intmod.set_base(59)
#Construct key, If no password is provided, default password of "" is used
seclen=len(shares[0])-1
if pword:
key=genpad(seclen,pword)
else:
key=[intmod(0) for c in xrange(seclen)]
#Catch errors Two keys for the same point
lsh=len(shares)
xs=[intmod(b58conv(shares[i][-1])) for i in xrange(lsh)]
todel=[]
for i in xrange(lsh-1):
for j in xrange(i+1,lsh):
if xs[i]==xs[j]:
if j not in todel:
todel.append(j)
d=0
todel=sorted(todel,reverse=True)
for i in todel:
del xs[i]
del shares[i]
d=d+1
lsh=lsh-d
#Construct the Lagrange Polynomials (These are the same for all elements)
l=[]
for i in xrange(lsh):
lt=Polynomial(x0=intmod(1))
for j in xrange(lsh):
if i != j:
if (xs[i]-xs[j])==intmod(0):
raise ValueError("Two of your keys are for identical points please remedy this")
lt=lt*(Polynomial(x1=intmod(1),x0=-xs[j]))
lt=lt//Polynomial(x0=(xs[i]-xs[j]))
l.append(lt)
#Reconstruct Secret (To best knowledge), Completes Lagrange integration for each character
#Evaluates at 0 and converts into a base 58 character
rect=[]
for i in xrange(seclen):
p=Polynomial(x0=intmod(0))
for j in xrange(lsh):
p=p+Polynomial(x0=(b58conv(shares[j][i])))*l[j]
rect.append(r58conv(p.evaluate(intmod(0))-key[i%64]))
return "".join(rect)
示例11: test_div_gffast
def test_div_gffast(self):
one = Polynomial(map(GF2int, [1,3,5,1])) # must be monic! (because the function is optimized for monic divisor polynomial)
two = Polynomial(map(GF2int, [5,3,1,1,6,8]))
q, r = two._gffastdivmod(one) # optimized for monic divisor polynomial
q2, r2 = two._fastdivmod(one)
self.assertEqual(q, q2)
self.assertEqual(r, r2)
self.assertEqual(list(q.coefficients), [5, 12, 4])
self.assertEqual(list(r.coefficients), [52, 30, 12])
# Make sure they multiply back out okay
self.assertEqual(q*one + r, two)
示例12: test_orientation_reprojection
def test_orientation_reprojection(self):
true_s = np.array([.1, .2, -.3])
true_r = utils.cayley(true_s)
true_k = 1. / (1. + np.dot(true_s, true_s))
true_vars = np.r_[true_s, true_k]
xs = np.random.rand(8, 3)
true_ys = np.dot(xs, true_r.T)
sym_vars = Polynomial.coordinates(4, ctype=float)
x, y, z, w = sym_vars
sym_s = sym_vars[:3]
sym_k = sym_vars[3]
sym_r = utils.cayley_mat(sym_s)
sym_rd = utils.cayley_denom(sym_s)
residuals = (np.dot(xs, sym_r.T) - true_ys * sym_rd).flatten()
cost = sum(r**2 for r in residuals)
gradients = cost.partial_derivatives()
constraint = sym_k * (1 + np.dot(sym_s, sym_s)) - 1
print 'Cost:', cost
print 'Constraint:', constraint
print 'At ground truth:'
print ' Cost = ', cost(*true_vars)
print ' Constraint = ', constraint(*true_vars)
print ' Gradients = ', [p(*true_vars) for p in gradients]
expansions = [solvers.all_monomials(sym_vars, 2) for _ in range(cost.num_vars)]
for a in expansions:
a.extend([z*z*w, x*x*w, y*y*w, z*z*w*w, z*w*w])
minima = optimize.minimize_globally(cost,
[constraint],
expansions=expansions,
diagnostic_solutions=[true_vars])
print 'Minima: ', minima
示例13: test_ntt_mul
def test_ntt_mul():
global w,wInv
print "test_ntt_mul"
powers2 = [pow(2,i) for i in range(1,19)]
for N in powers2:
print N
k = (P-1)/(2*N)
assert (P-1)%(2*N) == 0
wN = pow(7,k,P)
assert pow(wN,(2*N),P) == 1
w = []
for j in range(2*N):
w.append(pow(wN,j,P))
wInv = []
for j in range(2*N):
wInv.append(pow(w[j],P-2,P))
a = [randint(0,2**16) for _ in xrange(N)]+[0]*N
b = [randint(0,2**16) for _ in xrange(N)]+[0]*N
polynomial_a = Polynomial()
polynomial_a.coef = a
polynomial_b = Polynomial()
polynomial_b.coef = b
polynomial_c = polynomial_a*polynomial_b
my_ntt_a = CPU_NTT(a)
my_ntt_b = CPU_NTT(b)
my_ntt_c = [x[0]*x[1] % P for x in zip(my_ntt_a,my_ntt_b)]
ntt_intt_c = CPU_INTT(my_ntt_c)
# assert len(ntt_intt_c) == len(polynomial_c.coef)
for i,v in enumerate(polynomial_c.coef):
v2 = ntt_intt_c[i]/(2*N)
assert v == v2
print "We are good"
示例14: test_two_vars
def test_two_vars(self):
x, y = Polynomial.coordinates(2)
equations = [x**2 + y**2 - 1,
x-y]
expansion_monomials = [
[x, y],
[x, y, x*y, x*x, y*y]
]
result = solvers.solve_via_basis_selection(equations, expansion_monomials, x+y+1)
expected_solutions = [np.sqrt([.5, .5]), -np.sqrt([.5, .5])]
self.assert_solutions_found(result, expected_solutions)
示例15: test_estimate_pose_and_depths
def test_estimate_pose_and_depths(self):
np.random.seed(0)
num_landmarks = 5
# Generate ground truth
true_cayleys = np.array([.1, .2, -.3])
true_orientation = utils.cayley(true_cayleys)
true_position = np.array([2., 3., 10.])
# Generate observed quantities
true_landmarks = np.random.randn(num_landmarks, 3)
true_pfeatures = np.dot(true_landmarks - true_position, true_orientation.T)
true_depths = np.sqrt(np.sum(np.square(true_pfeatures), axis=1))
true_features = true_pfeatures / true_depths[:, None]
true_vars = np.hstack((true_orientation.flatten(), true_position, true_depths))
# Create symbolic quantities
sym_vars = Polynomial.coordinates(12 + num_landmarks, ctype=float)
sym_orientation = np.reshape(sym_vars[:9], (3, 3))
sym_position = np.array(sym_vars[9:12])
sym_depths = np.array(sym_vars[12:])
residuals = []
for i, (landmark, feature, sym_depth) in enumerate(zip(true_landmarks, true_features, sym_depths)):
residual = np.dot(sym_orientation, landmark - sym_position) - sym_depth * feature
residuals.extend(residual)
constraints = (np.dot(sym_orientation.T, sym_orientation) - np.eye(3)).flatten()
cost = sum(r**2 for r in residuals)
gradients = cost.partial_derivatives()
print 'Cost:', cost
print 'Constraints:'
for constraint in constraints:
print ' ', constraint
print 'At ground truth:'
print ' Cost = ', cost(*true_vars)
print ' Constraints = ', utils.evaluate_array(constraints, *true_vars)
print ' Gradients = ', [p(*true_vars) for p in gradients]
expansions = solvers.all_monomials(sym_vars, 2)
minima = optimize.minimize_globally(cost,
constraints,
expansions=expansions,
#diagnostic_solutions=[true_vars],
)
estimated_r = np.reshape(minima, (3, 3))
error = np.linalg.norm(estimated_r - true_orientation)
print 'Minima:\n', estimated_r
print 'Ground truth:\n', true_orientation
print 'Error:', error