def test_add(self): p0 = Polynomial([1, 2.5, -3]) p1 = 4 p2 = Polynomial([]) p3 = Polynomial([-1, -2.5, 3]) p4 = Polynomial([1, 2, 3, 4]) p5 = Polynomial([1, 2]) res = p0 + p1 self.assertEqual(res.coeffs, [1, 2.5, 1]) self.assertEqual(res.degree, 2) res = p1 + p0 self.assertEqual(res.coeffs, [1, 2.5, 1]) self.assertEqual(res.degree, 2) res = p0 + p2 self.assertEqual(res.coeffs, [1, 2.5, -3]) self.assertEqual(res.degree, 2) res = p0 + p3 self.assertEqual(res.coeffs, [0]) self.assertEqual(res.degree, 0) res = p0 + p4 self.assertEqual(res.coeffs, [1, 3, 5.5, 1]) self.assertEqual(res.degree, 3) res = p0 + p5 self.assertEqual(res.coeffs, [1, 3.5, -1]) self.assertEqual(res.degree, 2) p0 += p5 self.assertEqual(p0.coeffs, [1, 3.5, -1]) self.assertEqual(p0.degree, 2)
def _selectPP(self, x0, idxStart=0): '''return (first) polynomial piece containing x0 in its definition range >>> pp1 = PolyPiece(Polynomial([0,1]), [-1,1]) >>> pp2 = PolyPiece(Polynomial([0,2]), [ 1,2]) >>> fpp = PolyPieceFunc([pp1, pp2]) >>> fpp._isConsistent() True >>> fpp._selectPP(-2) (<Polynomial '0'>, 0) >>> fpp._selectPP(-1) (<Polynomial 'x'>, 0) >>> fpp._selectPP(1) (<Polynomial 'x'>, 0) >>> fpp._selectPP(2) (<Polynomial '2x'>, 1) ''' if idxStart >= len(self.polyPieces): return Polynomial(), idxStart if x0 < self.polyPieces[idxStart].interval[0]: return Polynomial(), idxStart for i, pp in enumerate(self.polyPieces[idxStart:]): intv, pi = pp.interval, pp.poly if intv[0] > x0: return Polynomial(), idxStart + i if x0 <= intv[1]: return pi, idxStart + i return Polynomial(), idxStart + len(self.polyPieces)
def test_eq_float(self): p = Polynomial([1.5, 4, 6.7]) s = Polynomial([0, 0, 0, 0, 0, 1, 4.8]) self.assertEqual(p, Polynomial([1.5, 4, 6.7])) self.assertTrue(p == Polynomial([1.5, 4, 6.7])) self.assertTrue(p != s) self.assertFalse(p == s)
def test_Str(self): pol1 = Polynomial([3, 2, 1]) self.assertEqual(str(pol1), "3x^2+2x+1") pol2 = Polynomial([-3, -2, -1]) self.assertEqual(str(pol2), "-3x^2-2x-1") pol3 = Polynomial([0]) self.assertEqual(str(pol3), "0") pol4 = Polynomial([0, 0, 0]) self.assertEqual(str(pol4), "0") pol5 = Polynomial([-9, 0, 8]) self.assertEqual(str(pol5), "-9x^2+8") pol6 = Polynomial([3.3, 2.2, 1.1]) self.assertEqual(str(pol6), "3.3x^2+2.2x+1.1") pol7 = Polynomial([-3.3, -2.3, -1.3]) self.assertEqual(str(pol7), "-3.3x^2-2.3x-1.3") pol8 = Polynomial([0.0]) self.assertEqual(str(pol8), "0") pol9 = Polynomial([0.0, 0.0, 0.0]) self.assertEqual(str(pol9), "0") pol10 = Polynomial([-9.9, 0.0, 8.9]) self.assertEqual(str(pol10), "-9.9x^2+8.9")
def get_prod_funs(e, field_value=257): k = len(e) temp_poly = Polynomial([1]) for i in range(k): temp_poly = temp_poly.multiply( Polynomial([1, (field_value - e[i]) % field_value])) return temp_poly
def test_constructor_correct(self): p1 = Polynomial([6, 3, 2, 1]) self.assertEqual(p1.coeffs, [6, 3, 2, 1]) self.assertEqual(p1.degree, 3) p2 = Polynomial([0]) self.assertEqual(p2.coeffs, [0]) self.assertEqual(p2.degree, 0)
def test_integral_expressions_against_real_hamiltonian(self): extractor = IntegralExtractor(self.hill.alg) extractor.set_complex_normal_hamiltonian(self.hill.k_dc) extractor.find_lost_simple_integrals_and_non_simple_integral() extractor.list_the_simple_integrals() extractor.express_simple_part_as_polynomial_over_all_integrals() extractor.express_both_parts_as_polynomial_over_all_integrals() extractor.express_all_integrals_in_normal_form_coords() k_dc_in_ints = extractor._total_in_integrals ints_in_coords = extractor._integrals_in_coords r_ints_in_coords = [ one_int.substitute(self.hill.sub_r_into_c) for one_int in ints_in_coords ] res = Polynomial(6) for po, co in k_dc_in_ints.powers_and_coefficients(): tmp = Polynomial.One(6) for i, po_i in enumerate(po): if po_i > 0: tmp *= (r_ints_in_coords[i]**po_i) res += co * tmp eval_at_ints = res diff = eval_at_ints - self.hill.k_dr self.assert_(diff.l_infinity_norm() < 1.0e-15, diff) eval_at_ints = k_dc_in_ints.substitute(r_ints_in_coords) diff = eval_at_ints - self.hill.k_dr self.assert_(diff.l_infinity_norm() < 1.0e-15, diff)
def single_term(points, i): theTerm = Polynomial([1.]) print("here",theTerm) xi, yi = points[i] for j, p in enumerate(points): if j==i: continue print("p:",p) xj = p[0] theTerm = theTerm* Polynomial( [-xj / (xi - xj) , 1.0/ (xi -xj)] ) print("j",xj) print("i",xi) print(Polynomial( [-xj / (xi - xj) , 1.0/ (xi -xj)] )) print("term ",theTerm) print("yi",Polynomial([yi])) return theTerm * Polynomial([yi])
def import_key(key_file): with open(key_file, 'r') as input_file: keys = input_file.read().replace("\n", "").replace( PUBLIC_BEGIN_BLOCK, "").replace(PUBLIC_END_BLOCK, "").replace(PRIVATE_BEGIN_BLOCK, "").replace(PRIVATE_END_BLOCK, "") keys = base64.b64decode(keys).decode() parameters_list = keys.split("\n") """ Dump parameters """ params = parameters_list[0][ 35:] # len('Parameters (N, p, q, df, dg, dr) = ') = 35 params = ast.literal_eval(params) params = Parameters(params[0], params[1], params[2], params[3], params[4], params[5]) """ Dump polynomial h (public key) """ h = parameters_list[1][30:] # len('Coefficient of polynomial h = ') = 30 h = Polynomial(ast.literal_eval(h), params.get_N()) """ Dump polynomial f, g (private key) """ f = g = None if len(parameters_list) == 4: f = parameters_list[2][30:] f = Polynomial(ast.literal_eval(f), params.get_N()) g = parameters_list[3][30:] g = Polynomial(ast.literal_eval(g), params.get_N()) if f and g: return NTRUKey(params, h, f, g) else: return NTRUKey(params, h)
def test_sub(self): p0 = Polynomial([1, 2.5, -3]) p1 = 4 p2 = Polynomial([]) p3 = Polynomial([1, 2.5, -3]) p4 = Polynomial([1, 2, 3, 4]) p5 = Polynomial([1, 2]) res = p0 - p1 self.assertEqual(res.coeffs, [1, 2.5, -7]) self.assertEqual(res.degree, 2) res = p1 - p0 self.assertEqual(res.coeffs, [-1, -2.5, 7]) self.assertEqual(res.degree, 2) res = p0 - p2 self.assertEqual(res.coeffs, [1, 2.5, -3]) self.assertEqual(res.degree, 2) res = p0 - p3 self.assertEqual(res.coeffs, [0]) self.assertEqual(res.degree, 0) res = p0 - p4 self.assertEqual(res.coeffs, [-1, -1, -0.5, -7]) self.assertEqual(res.degree, 3) res = p0 - p5 self.assertEqual(res.coeffs, [1, 1.5, -5]) self.assertEqual(res.degree, 2) p0 -= p5 self.assertEqual(p0.coeffs, [1, 1.5, -5]) self.assertEqual(p0.degree, 2)
def test_mul(self): p0 = Polynomial([1, 2.5, -3]) p1 = 4 p2 = Polynomial([]) p3 = Polynomial([1, 2.5, -3]) p4 = Polynomial([1, 2]) res = p0 * p1 self.assertEqual(res.coeffs, [4, 10, -12]) self.assertEqual(res.degree, 2) res = p1 * p0 self.assertEqual(res.coeffs, [4, 10, -12]) self.assertEqual(res.degree, 2) res = p0 * p2 self.assertEqual(res.coeffs, [0]) self.assertEqual(res.degree, 0) res = p0 * p3 self.assertEqual(res.coeffs, [1, 5, 0.25, -15, 9]) self.assertEqual(res.degree, 4) res = p0 * p4 self.assertEqual(res.coeffs, [1, 4.5, 2.0, -6]) self.assertEqual(res.degree, 3) p0 *= 2 self.assertEqual(p0.coeffs, [2, 5, -6]) self.assertEqual(p0.degree, 2)
def test_initWithError(self): with self.assertRaises(TypeError) as context: p0 = Polynomial('a') self.assertEqual( str(context.exception), "('Wrong or unsupported type of argument(must be const(int, float) or Polynomial): ', 'a')" ) with self.assertRaises(TypeError) as context: p0 = Polynomial([1, 'a']) self.assertEqual( str(context.exception), "('Wrong or unsupported type of argument(must be const(int, float) or Polynomial): ', 'a')" ) with self.assertRaises(TypeError) as context: p0 = Polynomial([1, (2, 3)]) self.assertEqual( str(context.exception), "('Wrong or unsupported type of argument(must be const(int, float) or Polynomial): ', (2, 3))" ) with self.assertRaises(TypeError) as context: p0 = Polynomial([1, 2, [3, 4]]) self.assertEqual( str(context.exception), "('Wrong or unsupported type of argument(must be const(int, float) or Polynomial): ', [3, 4])" ) with self.assertRaises(TypeError) as context: p = "2x+1" p0 = Polynomial(p) self.assertEqual( str(context.exception), "('Wrong or unsupported type of argument(must be const(int, float) or Polynomial): ', '2x+1')" )
def __init__(self, poly, interval=None): if interval is None: if isinstance(poly, PolyPiece): self.poly = poly.poly self.interval = poly.interval else: try: poly, interval = poly PolyPiece(poly, interval) # check if arguments are valid self.poly = poly if isinstance( poly, Polynomial) else Polynomial(poly) self.interval = interval except Exception: raise TypeError( "PolyPiece cannot be constructed from '%s'" % [poly]) elif len(interval) == 2 and all( [isinstance(n, numbers.Real) for n in interval]): if interval[1] < interval[0]: raise ValueError( "cannot create PolyPiece: invalid interval '%s'" % interval) self.poly = poly if isinstance(poly, Polynomial) else Polynomial(poly) self.interval = interval else: raise TypeError( "cannot create PolyPiece, this is not an interval of reals: '%s'" % interval)
def test_mult(self): p = Polynomial([0., 0, 0., -1, 0, 4.5, 0, -6, 9.9]) s = Polynomial([0, 0, 0, 0, 0, 1, 4]) self.assertListEqual((p * s).coeffs, (s * p).coeffs) p = Polynomial([1, -1, 1]) s = Polynomial([-1, 1]) self.assertEqual((p * s).coeffs, [-1, 2, -2, 1])
def __init__(self, array): self._matrix = array if not Matrix.isColumnMatrix(self): for row in self._matrix: if len(row) != len(self[0]): raise Exception("Declaration error: \n Rows must have same number of items") try: # case matrix (n, p) for i in range(len(self._matrix)): for j in range(len(self[i])): if not isinstance(self[i][j], Polynomial): self[i][j] = Polynomial([self[i][j]]) self.__nbRows = len(self._matrix) self.__nbColumns = len(self[0]) except TypeError: # case column matrix for element in self._matrix: if not isinstance(element, Polynomial): element = Polynomial([element]) self.__nbRows = len(self._matrix) self.__nbColumns = 1 return
def setUp(self): """Set up an example from Hill's equations.""" x_2 = Powers((2, 0, 0, 0, 0, 0)) px2 = Powers((0, 2, 0, 0, 0, 0)) y_2 = Powers((0, 0, 2, 0, 0, 0)) py2 = Powers((0, 0, 0, 2, 0, 0)) z_2 = Powers((0, 0, 0, 0, 2, 0)) pz2 = Powers((0, 0, 0, 0, 0, 2)) xpy = Powers((1, 0, 0, 1, 0, 0)) ypx = Powers((0, 1, 1, 0, 0, 0)) terms = { px2: 0.5, py2: 0.5, pz2: 0.5, xpy: -1.0, ypx: 1.0, x_2: -4.0, y_2: 2.0, z_2: 2.0 } assert len(terms) == 8 self.h_2 = Polynomial(6, terms=terms) self.lie = LieAlgebra(3) self.diag = Diagonalizer(self.lie) self.eq_type = 'scc' e = [] e.append(+sqrt(2.0 * sqrt(7.0) + 1.0)) e.append(-e[-1]) e.append(complex(0.0, +sqrt(2.0 * sqrt(7.0) - 1.0))) e.append(-e[-1]) e.append(complex(0.0, +2.0)) e.append(-e[-1]) self.eig_vals = e
def test_TypeError(self): self.assertRaises(TypeError, Polynomial, []) self.assertRaises(TypeError, Polynomial, ['x', 'y']) self.assertRaises(TypeError, Polynomial, ['x', 42]) self.assertRaises(TypeError, Polynomial.__add__, Polynomial([4, 2]), "x") self.assertRaises(TypeError, Polynomial.__mul__, Polynomial([4, 2]), "x") self.assertRaises(TypeError, Polynomial.__eq__, Polynomial([4, 2]), "x")
def test_terms(self): s = Taylor.Cosine(1, 0) self.assert_(not s[1]) self.assert_(not s[3]) self.assert_(not s[5]) self.assert_(s[0] == Polynomial(1, terms={Powers((0,)): +1.0})) self.assert_(s[2] == Polynomial(1, terms={Powers((2,)): -1.0/2.0}), s[2]) self.assert_(s[4] == Polynomial(1, terms={Powers((4,)): +1.0/24.0}), s[4])
def test_terms_cached(self): s = Taylor.Cached(Taylor.Sine(2, 1)) self.assert_(not s[0]) self.assert_(not s[2]) self.assert_(not s[4]) self.assert_(s[1] == Polynomial(2, terms={Powers((0, 1)): +1.0})) self.assert_(s[3] == Polynomial(2, terms={Powers((0, 3)): -1.0/6.0}), s[3]) self.assert_(s[5] == Polynomial(2, terms={Powers((0, 5)): +1.0/120.0}), s[5])
def test_terms(self): s = Taylor.Sine(1, 0) self.assert_(not s[0]) self.assert_(not s[2]) self.assert_(not s[4]) self.assert_(s[1] == Polynomial(1, terms={Powers((1,)): +1.0})) self.assert_(s[3] == Polynomial(1, terms={Powers((3,)): -1.0/6.0}), s[3]) self.assert_(s[5] == Polynomial(1, terms={Powers((5,)): +1.0/120.0}), s[5])
def divide_polynomial_by_basis(self, poly_to_divide): division_ans = [Polynomial()] * len(self.basis) residual = Polynomial() while not poly_to_divide.is_empty(): poly_to_divide, division_ans, residual = \ self.__divide_lead_term_by_basis(poly_to_divide, division_ans, residual) return division_ans, residual
def get_expected_base_Ex0(): ''' Produce the basis x**2, 2xy, 2y**2 - x ''' exp_p2 = Polynomial([Mon(1, (2, 0))]) exp_p3 = Polynomial([Mon(2, (1, 1))]) exp_p4 = Polynomial([Mon(2, (0, 2)), Mon(-1, (1, 0))]) return [exp_p2, exp_p3, exp_p4]
def get_S_polynomial(poly0, poly1): gamma_ex = np.maximum(poly0.get_multidegree(), poly1.get_multidegree()) poly_gamma = Polynomial([Monomial(1, gamma_ex)]) a0 = poly_gamma.divide_by_leading_term(poly0) a1 = poly_gamma.divide_by_leading_term(poly1) S_poly = (a0 * poly0) - (a1 * poly1) return S_poly
def test_terms_embed(self): s = Taylor.Cosine(2, 1) self.assert_(not s[1]) self.assert_(not s[3]) self.assert_(not s[5]) self.assert_(s[0] == Polynomial(2, terms={Powers((0, 0)): +1.0})) self.assert_(s[2] == Polynomial(2, terms={Powers((0, 2)): -1.0/2.0}), s[2]) self.assert_(s[4] == Polynomial(2, terms={Powers((0, 4)): +1.0/24.0}), s[4])
def __init__(self, string): self.string = string; split = string.rstrip().split("="); if (len(split) != 2): raise Exception("the equation must have one left hand side and one right hand side"); else: self.lhs = Polynomial(split[0]); self.rhs = Polynomial(split[1]);
def _convPolys(tIntervals, f, g, xIdPoly): zName = max(f.varName, g.varName, xIdPoly.varName) + '0' fz = Polynomial(f.coeffs, varName=zName) # "computes" f(z) x_z = Polynomial([xIdPoly, -1], varName=zName) # computes the polynomial x-z F = (fz * g(x_z)).intIndef(zName) convPolys = [F(upper) - F(lower) for lower, upper in tIntervals] return convPolys
def solve(seq): """Return the Polynomial that can be used to compute the given sequence""" coefficients = calculateCoefficients(seq) p = Polynomial() for i in xrange(0, len(coefficients)): p = p.plus(Polynomial(coefficients[i]).times(factorialPower(i))) p.removeTrailingZeroes() return p
def test_constructor_bad(self): with self.assertRaises(Exception) as context: p1 = Polynomial([4, 's', 9, 8]) self.assertEqual(str(context.exception), "Coeffs list values(int or float)") with self.assertRaises(Exception) as context: p2 = Polynomial(['a']) self.assertEqual(str(context.exception), "Coeffs list values(int or float)")
def test_string_float(self): p1 = Polynomial([0.0]) self.assertEqual(str(p1), "0") p1 = Polynomial([0.0, 0.0, 0.0]) self.assertEqual(str(p1), "0") p1 = Polynomial([3.3, -2.2, 1.5]) self.assertEqual(str(p1), "3.3x2-2.2x+1.5") p1 = Polynomial([-4.1, 3.3, -2.2, 1.5]) self.assertEqual(str(p1), "-4.1x3+3.3x2-2.2x+1.5")
def get_expected_reduced_base(): ''' Produce the basis x**2, xy, y**2 - x/2 ''' exp_p0 = Polynomial([Mon(1, (2, 0))]) exp_p1 = Polynomial([Mon(1, (1, 1))]) exp_p2 = Polynomial([Mon(1, (0, 2)), Mon(-0.5, (1, 0))]) expected_base = IdealBasis([exp_p0, exp_p1, exp_p2]) return expected_base
def test_str_float(self): p = Polynomial([0.0]) self.assertEqual(str(p), "0") p = Polynomial([0.0, 0.0, 0.0]) self.assertEqual(str(p), "0") p = Polynomial([-1.2, 4.5, -6.8]) self.assertEqual(str(p), "-1.2x2+4.5x-6.8") p = Polynomial([-1.2, 0.0, -6.8]) self.assertEqual(str(p), "-1.2x2-6.8")
def __init__(self, numerator, denominator=[1.]): if hasattr(numerator, 'is_polynomial'): self.numerator = numerator else: self.numerator = Polynomial(numerator) if hasattr(denominator, 'is_polynomial'): self.denominator = denominator else: self.denominator = Polynomial(denominator) self._normalize()
def changeP(self): temp = self._P.get() if Polynomial.isValid(temp): self.P = Polynomial(temp) % self.R self._P.delete(0, END) self._P.insert(0, self.P) self._output.insert(END, "P(z) = " + str(self.P) + "\n") else: self._P.delete(0, END) self._P.insert(0, self.P) self._output.insert(END, "There was an error with your input. Please try again.\n")
def order(self): # O(q^2) algorithm, where q = 2^r polys = [] for i in range(self.getModulus().degree()): Polynomial.generatePolys(polys) count = 1 # point at infinity for i in range(len(polys)): for j in range(len(polys)): leftside = (polys[j] * polys[j] + polys[i] * polys[j]) % self.getModulus() # y^2 + xy rightside = (polys[i] * polys[i] * polys[i] + self.getA() * polys[i] * polys[i] + self.getB())\ % self.getModulus() # x^3 + ax^2 + b if leftside == rightside: count += 1 return count
def interpolateLagrange(points): runningSum = Polynomial([0.0]) for j in range(len(points)): runningProduct = Polynomial([1]) for k in range(len(points)): if k != j: scale = points[j][0] - points[k][0] runningProduct *= Polynomial([-points[k][0]/scale, 1/scale]) runningSum += runningProduct.scale(points[j][1]) return runningSum
def changeModulus(self): temp = self._irred.get() if Polynomial.isValid(temp): self.modulus = Polynomial(temp) self.r = self.modulus.degree() self.curveString.set("E : F_(2^" + str(self.r) + ") : y^2 + xy = x^3 + ") self._irred.delete(0, END) self._irred.insert(0, self.modulus) E = BinaryEllipticCurve(self.a, self.b, self.modulus) self._output.insert(END, "The irreducible polynomial is now set to " + str(self.modulus) + ".\n") else: self._irred.delete(0, END) self._irred.insert(0, self.modulus) self._output.insert(END, "There was an error with your input. Please try again.\n")
def listRandomECs(m, irred, n): if (m & (m-1)) != 0: # only powers of 2 don't have this property return "" + str(m) + " is not a power of 2." count = 0 rval = "" deg = int(math.log(m, 2)) while count < n: a = Polynomial.random(deg-1) b = Polynomial.random(deg-1) E = BinaryEllipticCurve(a, b, irred) if E.isEC(): rval += str(E) + "\n" count += 1 rval += str(count) + " curves were generated.\n" return rval
def setUp(self): """Set up an example from Hill's equations.""" x_2 = Powers((2, 0, 0, 0, 0, 0)) px2 = Powers((0, 2, 0, 0, 0, 0)) y_2 = Powers((0, 0, 2, 0, 0, 0)) py2 = Powers((0, 0, 0, 2, 0, 0)) z_2 = Powers((0, 0, 0, 0, 2, 0)) pz2 = Powers((0, 0, 0, 0, 0, 2)) xpy = Powers((1, 0, 0, 1, 0, 0)) ypx = Powers((0, 1, 1, 0, 0, 0)) terms = {px2: 0.5, py2: 0.5, pz2: 0.5, xpy: -1.0, ypx: 1.0, x_2: -4.0, y_2: 2.0, z_2: 2.0} assert len(terms) == 8 self.h_2 = Polynomial(6, terms=terms) self.lie = LieAlgebra(3) self.diag = Diagonalizer(self.lie) self.eq_type = 'scc' e = [] e.append(+sqrt(2.0*sqrt(7.0)+1.0)) e.append(-e[-1]) e.append(complex(0.0, +sqrt(2.0*sqrt(7.0)-1.0))) e.append(-e[-1]) e.append(complex(0.0, +2.0)) e.append(-e[-1]) self.eig_vals = e
def changeQ(self): tempx = self._Qx.get() tempy = self._Qy.get() if Polynomial.isValid(tempx) and Polynomial.isValid(tempy): self.Qx = Polynomial(tempx) % self.modulus self.Qy = Polynomial(tempy) % self.modulus self._Qx.delete(0, END) self._Qy.delete(0, END) self._Qx.insert(0, self.Qx) self._Qy.insert(0, self.Qy) self._output.insert(END, "Q = " + str(PolynomialPoint(self.Qx, self.Qy, 1)) + "\n") else: self._Qx.delete(0, END) self._Qy.delete(0, END) self._Qx.insert(0, self.Qx) self._Qy.insert(0, self.Qy) self._output.insert(END, "There was an error with your input. Please try again.\n")
def read_ascii_polynomial(istream, is_xxpp_format, order=None): """ Read a polynomial from an input stream in ASCII format. @param istream: an iterable of input lines (e.g. file-like), @param is_xxpp_format: a boolean to specify whether the input file is in the old (Mathematica) format where all configuration coordinates come first, following by all the momenta, rather than the new even-odd format. @param order: reorder the degrees of freedom on the fly @return: polynomial. Note: this needs to be refactored; the xxpp logic belongs in a lie algebra of one sort or another. """ line = istream.next() n_vars = int(line) assert n_vars >= 0 line = istream.next() n_monomials = int(line) assert n_monomials >= 0 p = Polynomial(n_vars) for i in xrange(n_monomials): line = istream.next() elts = line.split(' ') elts = elts[:n_vars]+[' '.join(elts[n_vars:])] assert len(elts) == n_vars+1 powers_list = [int(e) for e in elts[:-1]] if is_xxpp_format: powers_list = xxpp_to_xpxp(powers_list) if order != None: powers_list = reorder_dof(powers_list, order) powers = tuple(powers_list) coeff = complex(elts[-1]) m = coeff*Polynomial.Monomial(powers) assert not p.has_term(Powers(powers)) p += m return p
def _normalize(self): self.numerator = self._truncate(self.numerator) self.denominator = self._truncate(self.denominator) n = 0 while 1: if self.numerator.coeff[n] != 0: break if self.denominator.coeff[n] != 0: break n = n + 1 if n == len(self.numerator.coeff): break if n > 0: self.numerator = Polynomial(self.numerator.coeff[n:]) self.denominator = Polynomial(self.denominator.coeff[n:]) factor = self.denominator.coeff[-1] if factor != 1.: self.numerator = self.numerator/factor self.denominator = self.denominator/factor
def __init__(self, numerator, denominator=[1.]): """ @param numerator: polynomial in one variable, or a list of polynomial coefficients @type numerator: L{Scientific.Functions.Polynomial.Polynomial} or C{list} of numbers @param denominator: polynomial in one variable, or a list of polynomial coefficients @type denominator: L{Scientific.Functions.Polynomial.Polynomial} or C{list} of numbers """ if hasattr(numerator, 'is_polynomial'): self.numerator = numerator else: self.numerator = Polynomial(numerator) if hasattr(denominator, 'is_polynomial'): self.denominator = denominator else: self.denominator = Polynomial(denominator) self._normalize()
def listRandomPoints(self, n): count = 0 s = "" a = self.getA() b = self.getB() modulus = self.getModulus() deg = modulus.degree() while count < n: foundPoint = False while not foundPoint: x = Polynomial.random(deg-1) y = Polynomial.random(deg-1) leftside = (y*y + x*y) % modulus rightside = (x*x*x + a*x*x + b) % modulus if leftside == rightside: foundPoint = True s += str(PolynomialPoint(x, y, Polynomial("1"))) + "\n" count += 1 s += str(count) + " points were generated.\n" return s
def changeR(self): temp = self._R.get() if Polynomial.isValid(temp): self.R = Polynomial(temp) self._R.delete(0, END) self._R.insert(0, self.R) self._output.insert(END, "R(z) = " + str(self.R) + "\n") else: self._R.delete(0, END) self._R.insert(0, self.R) self._output.insert(END, "There was an error with your input. Please try again.\n")
def changeB(self): temp = self._b.get() if Polynomial.isValid(temp): self.b = Polynomial(temp) % self.modulus self._b.delete(0, END) self._b.insert(0, self.b) E = BinaryEllipticCurve(self.a, self.b, self.modulus) self._output.insert(END, str(E) + "\n") else: self._b.delete(0, END) self._b.insert(0, self.b) self._output.insert(END, "There was an error with your input. Please try again.\n")
parser.add_argument('test_values', nargs='+', help='The number series to process.', metavar='N') results = parser.parse_args() test_values = [] for string_num in vars(results)['test_values']: test_values.append(int(string_num)) num_nums = len(test_values) result_vector = vector(test_values) working_matrix = Matrix((num_nums, num_nums)) for col in range(0, num_nums): for row in range(0, num_nums): working_matrix.set((row, col), math.pow(col + 1, row)) result = Polynomial(solve(working_matrix, result_vector)) # output! print("\033c") formatter = ANSIEscapeCodes() # display the original series. print(formatter.decorate(formatter.COLORS['white'], "Input vector")) print(formatter.decorate(formatter.COLORS['red'], str(test_values))) # display the polynomial equation that this series satisfies print() print(formatter.decorate(formatter.COLORS['white'], "Polynomial equation satisfying the number series"))
def factorialPower(n): p = Polynomial(1) for i in xrange(1, n + 1): p = p.times(Polynomial(1 - i, 1)) p.removeTrailingZeroes() return p
def __init__(self, master, name): Tab.__init__(self, master, name) self.a = 43827423 self.b = 8372842 self.p = 7447344552397 self.P = Polynomial("z^29 + z^18 + z^3 + 1") self.Q = Polynomial("z^17 + z^13 + z^11 + z^7") self.k = 473423 self.R = Polynomial("z^32 + z^26 + z^23 + z^22 + z^16 + z^12 + z^11 + z^10 + z^8 + z^7 + z^5 + z^4 + z^2 + z + 1") # default is crc-32 poly outputFrame = Frame(self) Button(outputFrame, text="Clear Output", bg="blue", fg="white", command=(lambda: self.clear()), borderwidth=1).pack(side=BOTTOM, pady=3) self._output = Text(outputFrame, height=15, width=65) self._output.insert(END, "You are responsible for making sure the irreducible polynomial you use is actually irreducible. " "The default, z^32 + z^26 + z^23 + z^22 + z^16 + z^12 + z^11 + z^10 + z^8 + z^7 + z^5 + z^4 + z^2 + z + 1," " is irreducible.\n\n") self._output.pack(side=LEFT) scrollbar = Scrollbar(outputFrame) scrollbar.pack(side=RIGHT, fill=Y) scrollbar.config(command=self._output.yview) modularInput = Frame(self) modularButtons = Frame(self) polyInput = Frame(self) irredFrame = Frame(self) polyOut1 = Frame(self) polyOut2 = Frame(self) Label(modularInput, text="a = ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=1, pady=3) self._a = Entry(modularInput, width=10) self._a.insert(0, self.a) self._a.bind("<Return>", (lambda event: self.changeA())) self._a.grid(row=1, column=2, pady=3) Label(modularInput, text=" b = ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=3, pady=3) self._b = Entry(modularInput, width=10) self._b.insert(0, self.b) self._b.bind("<Return>", (lambda event: self.changeB())) self._b.grid(row=1, column=4, pady=3) Label(modularInput, text=" p = ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=5, pady=3) self._p = Entry(modularInput, width=20) self._p.insert(0, self.p) self._p.bind("<Return>", (lambda event: self.changePrime())) self._p.grid(row=1, column=6, pady=3) Button(modularInput, text="Generate Random Prime", bg="blue", fg="white", command=(lambda: self.generatePrime())).grid(row=1, column=7, padx=5, pady=3) Button(modularButtons, text="a^b (mod p)", bg="blue", fg="white", command=(lambda: self.modExp())).grid(row=1, column=1, padx=5, pady=3) Button(modularButtons, text="1/a (mod p)", bg="blue", fg="white", command=(lambda: self.inverse())).grid(row=1, column=2, padx=5, pady=3) Button(modularButtons, text="sqrt(a) (mod p)", bg="blue", fg="white", command=(lambda: self.sqrt())).grid(row=1, column=3, padx=5, pady=3) Label(polyInput, text="P(z) = ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=1, pady=3) self._P = Entry(polyInput, width=25) self._P.insert(0, self.P) self._P.bind("<Return>", (lambda event: self.changeP())) self._P.grid(row=1, column=2, pady=3) Label(polyInput, text=" Q(z) = ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=3, pady=3) self._Q = Entry(polyInput, width=25) self._Q.insert(0, self.Q) self._Q.bind("<Return>", (lambda event: self.changeQ())) self._Q.grid(row=1, column=4, pady=3) Label(irredFrame, text="R(z) = ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=1, pady=3) self._R = Entry(irredFrame, width=25) self._R.insert(0, self.R) self._R.bind("<Return>", (lambda event: self.changeR())) self._R.grid(row=1, column=2, pady=3) Label(irredFrame, text=" k = ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=3, pady=3) self._k = Entry(irredFrame, width=10) self._k.insert(0, self.k) self._k.bind("<Return>", (lambda event: self.changeK())) self._k.grid(row=1, column=4, pady=3) Button(polyOut1, text="P(z) + Q(z) (mod R(z))", bg="blue", fg="white", command=(lambda: self.polyAdd())).grid(row=1, column=1, padx=5, pady=3) Button(polyOut1, text="P(z) * Q(z) (mod R(z))", bg="blue", fg="white", command=(lambda: self.polyMult())).grid(row=1, column=2, padx=5, pady=3) Button(polyOut2, text="P(z)^k (mod R(z))", bg="blue", fg="white", command=(lambda: self.polyModExp())).grid(row=1, column=1, padx=5, pady=3) Button(polyOut2, text="1/P(z) (mod R(z))", bg="blue", fg="white", command=(lambda: self.polyInverse())).grid(row=1, column=2, padx=5, pady=3) Button(polyOut2, text="sqrt(P(z)) (mod R(z))", bg="blue", fg="white", command=(lambda: self.polySqrt())).grid(row=1, column=3, padx=5, pady=3) modularInput.pack(side=TOP) modularButtons.pack(side=TOP) polyInput.pack(side=TOP) irredFrame.pack(side=TOP) polyOut1.pack(side=TOP) polyOut2.pack(side=TOP) outputFrame.pack(side=BOTTOM)
class MiscTab(Tab): def __init__(self, master, name): Tab.__init__(self, master, name) self.a = 43827423 self.b = 8372842 self.p = 7447344552397 self.P = Polynomial("z^29 + z^18 + z^3 + 1") self.Q = Polynomial("z^17 + z^13 + z^11 + z^7") self.k = 473423 self.R = Polynomial("z^32 + z^26 + z^23 + z^22 + z^16 + z^12 + z^11 + z^10 + z^8 + z^7 + z^5 + z^4 + z^2 + z + 1") # default is crc-32 poly outputFrame = Frame(self) Button(outputFrame, text="Clear Output", bg="blue", fg="white", command=(lambda: self.clear()), borderwidth=1).pack(side=BOTTOM, pady=3) self._output = Text(outputFrame, height=15, width=65) self._output.insert(END, "You are responsible for making sure the irreducible polynomial you use is actually irreducible. " "The default, z^32 + z^26 + z^23 + z^22 + z^16 + z^12 + z^11 + z^10 + z^8 + z^7 + z^5 + z^4 + z^2 + z + 1," " is irreducible.\n\n") self._output.pack(side=LEFT) scrollbar = Scrollbar(outputFrame) scrollbar.pack(side=RIGHT, fill=Y) scrollbar.config(command=self._output.yview) modularInput = Frame(self) modularButtons = Frame(self) polyInput = Frame(self) irredFrame = Frame(self) polyOut1 = Frame(self) polyOut2 = Frame(self) Label(modularInput, text="a = ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=1, pady=3) self._a = Entry(modularInput, width=10) self._a.insert(0, self.a) self._a.bind("<Return>", (lambda event: self.changeA())) self._a.grid(row=1, column=2, pady=3) Label(modularInput, text=" b = ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=3, pady=3) self._b = Entry(modularInput, width=10) self._b.insert(0, self.b) self._b.bind("<Return>", (lambda event: self.changeB())) self._b.grid(row=1, column=4, pady=3) Label(modularInput, text=" p = ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=5, pady=3) self._p = Entry(modularInput, width=20) self._p.insert(0, self.p) self._p.bind("<Return>", (lambda event: self.changePrime())) self._p.grid(row=1, column=6, pady=3) Button(modularInput, text="Generate Random Prime", bg="blue", fg="white", command=(lambda: self.generatePrime())).grid(row=1, column=7, padx=5, pady=3) Button(modularButtons, text="a^b (mod p)", bg="blue", fg="white", command=(lambda: self.modExp())).grid(row=1, column=1, padx=5, pady=3) Button(modularButtons, text="1/a (mod p)", bg="blue", fg="white", command=(lambda: self.inverse())).grid(row=1, column=2, padx=5, pady=3) Button(modularButtons, text="sqrt(a) (mod p)", bg="blue", fg="white", command=(lambda: self.sqrt())).grid(row=1, column=3, padx=5, pady=3) Label(polyInput, text="P(z) = ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=1, pady=3) self._P = Entry(polyInput, width=25) self._P.insert(0, self.P) self._P.bind("<Return>", (lambda event: self.changeP())) self._P.grid(row=1, column=2, pady=3) Label(polyInput, text=" Q(z) = ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=3, pady=3) self._Q = Entry(polyInput, width=25) self._Q.insert(0, self.Q) self._Q.bind("<Return>", (lambda event: self.changeQ())) self._Q.grid(row=1, column=4, pady=3) Label(irredFrame, text="R(z) = ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=1, pady=3) self._R = Entry(irredFrame, width=25) self._R.insert(0, self.R) self._R.bind("<Return>", (lambda event: self.changeR())) self._R.grid(row=1, column=2, pady=3) Label(irredFrame, text=" k = ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=3, pady=3) self._k = Entry(irredFrame, width=10) self._k.insert(0, self.k) self._k.bind("<Return>", (lambda event: self.changeK())) self._k.grid(row=1, column=4, pady=3) Button(polyOut1, text="P(z) + Q(z) (mod R(z))", bg="blue", fg="white", command=(lambda: self.polyAdd())).grid(row=1, column=1, padx=5, pady=3) Button(polyOut1, text="P(z) * Q(z) (mod R(z))", bg="blue", fg="white", command=(lambda: self.polyMult())).grid(row=1, column=2, padx=5, pady=3) Button(polyOut2, text="P(z)^k (mod R(z))", bg="blue", fg="white", command=(lambda: self.polyModExp())).grid(row=1, column=1, padx=5, pady=3) Button(polyOut2, text="1/P(z) (mod R(z))", bg="blue", fg="white", command=(lambda: self.polyInverse())).grid(row=1, column=2, padx=5, pady=3) Button(polyOut2, text="sqrt(P(z)) (mod R(z))", bg="blue", fg="white", command=(lambda: self.polySqrt())).grid(row=1, column=3, padx=5, pady=3) modularInput.pack(side=TOP) modularButtons.pack(side=TOP) polyInput.pack(side=TOP) irredFrame.pack(side=TOP) polyOut1.pack(side=TOP) polyOut2.pack(side=TOP) outputFrame.pack(side=BOTTOM) def changeA(self): try: self.a = int(self._a.get()) % self.p self._a.delete(0, END) self._a.insert(0, self.a) self._output.insert(END, "a = " + str(self.a) + "\n") except ValueError: self._a.delete(0, END) self._a.insert(0, self.a) self._output.insert(END, "There was an error with your input. Please try again.\n") def changeB(self): try: self.b = int(self._b.get()) % self.p self._b.delete(0, END) self._b.insert(0, self.b) self._output.insert(END, "b = " + str(self.b) + "\n") except ValueError: self._b.delete(0, END) self._b.insert(0, self.b) self._output.insert(END, "There was an error with your input. Please try again.\n") def changePrime(self): try: temp = int(self._p.get()) if ECMath.isPrime(temp): self.p = temp self._p.delete(0, END) self._p.insert(0, self.p) self._output.insert(END, "p = " + str(self.p) + "\n") else: self._output.insert(END, str(temp) + " is not prime. Please try again.\n") self._p.delete(0, END) self._p.insert(0, self.p) except ValueError: self._p.delete(0, END) self._p.insert(0, self.p) self._output.insert(END, "There was an error with your input. Please try again.\n") def generatePrime(self): digits = randint(1, 40) self.p = ECMath.randomPrime(digits) self._p.delete(0, END) self._p.insert(0, self.p) self._output.insert(END, "p = " + str(self.p) + "\n") def modExp(self): temp = pow(self.a, self.b, self.p) self._output.insert(END, str(self.a) + "^" + str(self.b) + " (mod " + str(self.p) + ") = " + str(temp) + "\n") def inverse(self): temp = ECMath.inverse(self.a, self.p) if temp != -1: self._output.insert(END, "1/" + str(self.a) + " (mod " + str(self.p) + ") = " + str(temp) + "\n") else: self._output.insert(END, "1/" + str(self.a) + " (mod " + str(self.p) + ") = undefined\n") def sqrt(self): if self.a % self.p == 0: self._output.insert(END, "sqrt(" + str(self.a) + ") (mod " + str(self.p) + ") = 0\n") elif ECMath.jacobi(self.a, self.p) == 1: temp = ECMath.sqrt(self.a, self.p) self._output.insert(END, "sqrt(" + str(self.a) + ") (mod " + str(self.p) + ") = " + str(temp) + "\n") else: self._output.insert(END, str(self.a) + " is not a square (mod " + str(self.p) + ")\n") def changeP(self): temp = self._P.get() if Polynomial.isValid(temp): self.P = Polynomial(temp) % self.R self._P.delete(0, END) self._P.insert(0, self.P) self._output.insert(END, "P(z) = " + str(self.P) + "\n") else: self._P.delete(0, END) self._P.insert(0, self.P) self._output.insert(END, "There was an error with your input. Please try again.\n") def changeQ(self): temp = self._Q.get() if Polynomial.isValid(temp): self.Q = Polynomial(temp) % self.R self._Q.delete(0, END) self._Q.insert(0, self.Q) self._output.insert(END, "Q(z) = " + str(self.Q) + "\n") else: self._Q.delete(0, END) self._Q.insert(0, self.Q) self._output.insert(END, "There was an error with your input. Please try again.\n") def changeR(self): temp = self._R.get() if Polynomial.isValid(temp): self.R = Polynomial(temp) self._R.delete(0, END) self._R.insert(0, self.R) self._output.insert(END, "R(z) = " + str(self.R) + "\n") else: self._R.delete(0, END) self._R.insert(0, self.R) self._output.insert(END, "There was an error with your input. Please try again.\n") def changeK(self): try: self.k = int(self._k.get()) self._k.delete(0, END) self._k.insert(0, self.k) self._output.insert(END, "k = " + str(self.k) + "\n") except ValueError: self._k.delete(0, END) self._k.insert(0, self.k) self._output.insert(END, "There was an error with your input. Please try again.\n") def polyAdd(self): temp = (self.P + self.Q) % self.R self._output.insert(END, "P(z) + Q(z) = (" + str(temp) + ") (mod R(z))\n") def polyMult(self): temp = (self.P * self.Q) % self.R self._output.insert(END, "P(z) * Q(z) = (" + str(temp) + ") (mod R(z))\n") def polyModExp(self): temp = self.P.modExp(self.k, self.R) self._output.insert(END, "P(z)^" + str(self.k) + " = (" + str(temp) + ") (mod R(z))\n") def polyInverse(self): temp = self.P.inverse(self.R) if temp is None: self._output.insert(END, "1/(P(z)) = undefined (mod R(z))\n") else: self._output.insert(END, "1/(P(z)) = (" + str(temp) + ") (mod R(z))\n") def polySqrt(self): temp = self.P.sqrt(self.R) self._output.insert(END, "sqrt(P(z)) = (" + str(temp) + ") (mod R(z))\n") def clear(self): self._output.delete(1.0, END) self._output.insert(END, "You are responsible for making sure the irreducible polynomial you use is actually irreducible. " "The default, z^32 + z^26 + z^23 + z^22 + z^16 + z^12 + z^11 + z^10 + z^8 + z^7 + z^5 + z^4 + z^2 + z + 1," " is irreducible.\n\n")
class RationalFunction: """Rational Function Instances of this class represent rational functions in a single variable. They can be evaluated like functions. Rational functions support addition, subtraction, multiplication, and division. """ def __init__(self, numerator, denominator=[1.]): """ @param numerator: polynomial in one variable, or a list of polynomial coefficients @type numerator: L{Scientific.Functions.Polynomial.Polynomial} or C{list} of numbers @param denominator: polynomial in one variable, or a list of polynomial coefficients @type denominator: L{Scientific.Functions.Polynomial.Polynomial} or C{list} of numbers """ if hasattr(numerator, 'is_polynomial'): self.numerator = numerator else: self.numerator = Polynomial(numerator) if hasattr(denominator, 'is_polynomial'): self.denominator = denominator else: self.denominator = Polynomial(denominator) self._normalize() is_rational_function = 1 def __call__(self, value): return self.numerator(value)/self.denominator(value) def __repr__(self): return "RationalFunction(%s,%s)" % (repr(list(self.numerator.coeff)), repr(list(self.denominator.coeff))) def _normalize(self): self.numerator = self._truncate(self.numerator) self.denominator = self._truncate(self.denominator) n = 0 while 1: if self.numerator.coeff[n] != 0: break if self.denominator.coeff[n] != 0: break n = n + 1 if n == len(self.numerator.coeff): break if n > 0: self.numerator = Polynomial(self.numerator.coeff[n:]) self.denominator = Polynomial(self.denominator.coeff[n:]) factor = self.denominator.coeff[-1] if factor != 1.: self.numerator = self.numerator/factor self.denominator = self.denominator/factor def _truncate(self, poly): if poly.coeff[-1] != 0.: return poly coeff = poly.coeff while len(coeff) > 1 and coeff[-1] == 0.: coeff = coeff[:-1] return Polynomial(coeff) def __coerce__(self, other): if hasattr(other, 'is_rational_function'): return (self, other) elif hasattr(other, 'is_polynomial'): return (self, RationalFunction(other, [1.])) else: return (self, RationalFunction([other], [1.])) def __mul__(self, other): return RationalFunction(self.numerator*other.numerator, self.denominator*other.denominator) __rmul__ = __mul__ def __div__(self, other): return RationalFunction(self.numerator*other.denominator, self.denominator*other.numerator) def __rdiv__(self, other): return RationalFunction(other.numerator*self.denominator, other.denominator*self.numerator) def __add__(self, other): return RationalFunction(self.numerator*other.denominator+ self.denominator*other.numerator, self.denominator*other.denominator) __radd__ = __add__ def __sub__(self, other): return RationalFunction(self.numerator*other.denominator- self.denominator*other.numerator, self.denominator*other.denominator) def __rsub__(self, other): return RationalFunction(other.numerator*self.denominator- other.denominator*self.numerator, self.denominator*other.denominator) def divide(self, shift=0): """ @param shift: the power of the independent variable by which the numerator is multiplied prior to division @type shift: C{int} (non-negative) @return: a polynomial and a rational function such that the sum of the two is equal to the original rational function. The returned rational function's numerator is of lower order than its denominator. @rtype: (L{Scientific.Functions.Polynomial.Polynomial}, L{RationalFunction}) """ num = Numeric.array(self.numerator.coeff, copy=1) if shift > 0: num = Numeric.concatenate((shift*[0.], num)) den = self.denominator.coeff den_order = len(den) coeff = [] while len(num) >= den_order: q = num[-1]/den[-1] coeff.append(q) num[-den_order:] = num[-den_order:]-q*den num = num[:-1] if not coeff: coeff = [0] coeff.reverse() if len(num) == 0: num = [0] return Polynomial(coeff), RationalFunction(num, den) def zeros(self): """ Find the X{zeros} (X{roots}) of the numerator by diagonalization of the associated Frobenius matrix. @returns: an array containing the zeros @rtype: C{Numeric.array} """ return self.numerator.zeros() def poles(self): """ Find the X{poles} (zeros of the denominator) by diagonalization of the associated Frobenius matrix. @returns: an array containing the poles @rtype: C{Numeric.array} """ return self.denominator.zeros()
class RationalFunction: """Rational Function Instances of this class represent rational functions in a single variable. They can be evaluated like functions. Constructor: RationalFunction(|numerator|, |denominator|) Arguments: |numerator|, |denominator| -- polynomials or sequences of numbers that represent the polynomial coefficients Rational functions support addition, subtraction, multiplication, and division. """ def __init__(self, numerator, denominator=[1.]): if hasattr(numerator, 'is_polynomial'): self.numerator = numerator else: self.numerator = Polynomial(numerator) if hasattr(denominator, 'is_polynomial'): self.denominator = denominator else: self.denominator = Polynomial(denominator) self._normalize() is_rational_function = 1 def __call__(self, value): return self.numerator(value)/self.denominator(value) def __repr__(self): return "RationalFunction(%s,%s)" % (repr(list(self.numerator.coeff)), repr(list(self.denominator.coeff))) def _normalize(self): self.numerator = self._truncate(self.numerator) self.denominator = self._truncate(self.denominator) n = 0 while 1: if self.numerator.coeff[n] != 0: break if self.denominator.coeff[n] != 0: break n = n + 1 if n == len(self.numerator.coeff): break if n > 0: self.numerator = Polynomial(self.numerator.coeff[n:]) self.denominator = Polynomial(self.denominator.coeff[n:]) factor = self.denominator.coeff[-1] if factor != 1.: self.numerator = self.numerator/factor self.denominator = self.denominator/factor def _truncate(self, poly): if poly.coeff[-1] != 0.: return poly coeff = poly.coeff while len(coeff) > 1 and coeff[-1] == 0.: coeff = coeff[:-1] return Polynomial(coeff) def __coerce__(self, other): if hasattr(other, 'is_rational_function'): return (self, other) elif hasattr(other, 'is_polynomial'): return (self, RationalFunction(other, [1.])) else: return (self, RationalFunction([other], [1.])) def __mul__(self, other): return RationalFunction(self.numerator*other.numerator, self.denominator*other.denominator) __rmul__ = __mul__ def __div__(self, other): return RationalFunction(self.numerator*other.denominator, self.denominator*other.numerator) def __rdiv__(self, other): return RationalFunction(other.numerator*self.denominator, other.denominator*self.numerator) def __add__(self, other): return RationalFunction(self.numerator*other.denominator+ self.denominator*other.numerator, self.denominator*other.denominator) __radd__ = __add__ def __sub__(self, other): return RationalFunction(self.numerator*other.denominator- self.denominator*other.numerator, self.denominator*other.denominator) def __rsub__(self, other): return RationalFunction(other.numerator*self.denominator- other.denominator*self.numerator, self.denominator*other.denominator) def divide(self, shift=0): """Returns a polynomial and a rational function such that the sum of the two is equal to the original rational function. The returned rational function's numerator is of lower order than its denominator. The argument |shift| (default: 0) specifies a positive integer power of the independent variable by which the numerator is multiplied prior to division. """ num = Numeric.array(self.numerator.coeff, copy=1) if shift > 0: num = Numeric.concatenate((shift*[0.], num)) den = self.denominator.coeff den_order = len(den) coeff = [] while len(num) >= den_order: q = num[-1]/den[-1] coeff.append(q) num[-den_order:] = num[-den_order:]-q*den num = num[:-1] if not coeff: coeff = [0] coeff.reverse() if len(num) == 0: num = [0] return Polynomial(coeff), RationalFunction(num, den) def zeros(self): "Returns an array containing the zeros." return self.numerator.zeros() def poles(self): "Returns an array containing the poles." return self.denominator.zeros()
def __init__(self, master, name): Tab.__init__(self, master, name) self.a = Polynomial("z^8 + z") # initially E : y^2 + xy = x^3 + (z^8 + z)x^2 + (z + 1) self.b = Polynomial("z + 1") self.r = 9 # field is initially GF(2^9) self.modulus = Polynomial("z^9 + z^8 + 1") # initial irred poly self.Gx = Polynomial("z^8 + z^6 + z^2 + 1") # initially G = (z^8 + z^6 + z^2 + 1, z^7 + z^5 + z^4 + z + 1) self.Gy = Polynomial("z^7 + z^5 + z^4 + z + 1") self.Px = Polynomial("z^8 + z^5 + z^3 + z") # initially P = (z^8 + z^5 + z^3 + z, z^8 + z^4 + z + 1) self.Py = Polynomial("z^8 + z^4 + z + 1") self.Qx = Polynomial("z^6 + z^4 + z^3 + z") # initially Q = (z^6 + z^4 + z^3 + z, z^5 + 1) self.Qy = Polynomial("z^5 + 1") self.k = 179 self.n = 5 # initially n = 5 random curves self.m = 10 # initially m = 10 random points outputFrame = Frame(self) Button(outputFrame, text="Clear Output", bg="blue", fg="white", command=(lambda: self.clear()), borderwidth=1).pack(side=BOTTOM, pady=3) self._output = Text(outputFrame, height=15, width=70) self._output.insert(END, "You are responsible for making sure the irreducible polynomial you use is actually irreducible. " "The default, z^9 + z^8 + 1, is irreducible.\n\n") self._output.pack(side=LEFT) scrollbar = Scrollbar(outputFrame) scrollbar.pack(side=RIGHT, fill=Y) scrollbar.config(command=self._output.yview) ecInfo = Frame(self) polyFrame = Frame(self) ptsInfo1 = Frame(self) ptsInfo2 = Frame(self) arithmeticFrame = Frame(self) orderFrame = Frame(self) listFrame = Frame(self) ptsFrame = Frame(self) self.curveString = StringVar() self.curveString.set("E : F_(2^" + str(self.r) + ") : y^2 + xy = x^3 + ") curveLabel = Label(ecInfo, textvariable=self.curveString, bg="orange", fg="black", borderwidth=1).grid(row=1, column=1) self._a = Entry(ecInfo, width=25) self._a.insert(0, self.a) self._a.bind("<Return>", (lambda event: self.changeA())) self._a.grid(row=1, column=2) Label(ecInfo, text="x^2 + ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=3) self._b = Entry(ecInfo, width=25) self._b.insert(0, self.b) self._b.bind("<Return>", (lambda event: self.changeB())) self._b.grid(row=1, column=4) Label(polyFrame, text="Irreducible Polynomial: ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=1, pady=3) self._irred = Entry(polyFrame, width=51) self._irred.insert(0, self.modulus) self._irred.bind("<Return>", (lambda event: self.changeModulus())) self._irred.grid(row=1, column=2, pady=3) Label(ptsInfo1, text="Generator G = (", bg="orange", fg="black", borderwidth=1).grid(row=1, column=1, pady=3) self._Gx = Entry(ptsInfo1, width=15) self._Gx.insert(0, self.Gx) self._Gx.bind("<Return>", (lambda event: self.changeG())) self._Gx.grid(row=1, column=2, pady=3) Label(ptsInfo1, text=", ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=3, pady=3) self._Gy = Entry(ptsInfo1, width=15) self._Gy.insert(0, self.Gy) self._Gy.bind("<Return>", (lambda event: self.changeG())) self._Gy.grid(row=1, column=4, pady=3) Label(ptsInfo1, text="), k = ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=5, pady=3) self._k = Entry(ptsInfo1, width=5) self._k.insert(0, self.k) self._k.bind("<Return>", (lambda event: self.changeK())) self._k.grid(row=1, column=6, pady=3) Label(ptsInfo2, text="P = ", bg="blue", fg="white", borderwidth=1).grid(row=1, column=1, pady=3) self._Px = Entry(ptsInfo2, width=15) self._Px.insert(0, self.Px) self._Px.bind("<Return>", (lambda event: self.changeP())) self._Px.grid(row=1, column=2, pady=3) Label(ptsInfo2, text=", ", bg="blue", fg="white", borderwidth=1).grid(row=1, column=3, pady=3) self._Py = Entry(ptsInfo2, width=15) self._Py.insert(0, self.Py) self._Py.bind("<Return>", (lambda event: self.changeP())) self._Py.grid(row=1, column=4, pady=3) Label(ptsInfo2, text="), Q = ", bg="blue", fg="white", borderwidth=1).grid(row=1, column=5, pady=3) self._Qx = Entry(ptsInfo2, width=15) self._Qx.insert(0, self.Qx) self._Qx.bind("<Return>", (lambda event: self.changeQ())) self._Qx.grid(row=1, column=6, pady=3) Label(ptsInfo2, text=", ", bg="blue", fg="white", borderwidth=1).grid(row=1, column=7, pady=3) self._Qy = Entry(ptsInfo2, width=15) self._Qy.insert(0, self.Qy) self._Qy.bind("<Return>", (lambda event: self.changeQ())) self._Qy.grid(row=1, column=8) Label(ptsInfo2, text=")", bg="blue", fg="white", borderwidth=1).grid(row=1, column=9, pady=3) Button(arithmeticFrame, text="P + Q", bg="blue", fg="white", command=(lambda: self.add())).grid(row=1, column=1, padx=5, pady=3) Button(arithmeticFrame, text="kP", bg="blue", fg="white", command=(lambda: self.mult())).grid(row=1, column=2, padx=5, pady=3) Button(arithmeticFrame, text="log_G(P)", bg="blue", fg="white", command=(lambda: self.log())).grid(row=1, column=3, padx=5, pady=3) Button(orderFrame, text="Order(E)", bg="blue", fg="white", command=(lambda: self.order())).grid(row=1, column=1, padx=5, pady=3) Button(orderFrame, text="Order(G)", bg="blue", fg="white", command=(lambda: self.pointOrder())).grid(row=1, column=2, padx=5, pady=3) Label(listFrame, text="Generate ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=1, pady=3) self._n = Entry(listFrame, width=3) self._n.insert(0, self.n) self._n.bind("<Return>", (lambda event: self.changeN())) self._n.grid(row=1, column=2, pady=3) Button(listFrame, text="Random ECs", bg="orange", fg="black", command=(lambda: self.randomECs())).grid(row=1, column=3, padx=5, pady=3) Label(ptsFrame, text="List ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=1, pady=3) self._m = Entry(ptsFrame, width=3) self._m.insert(0, self.m) self._m.bind("<Return>", (lambda event: self.changeM())) self._m.grid(row=1, column=2, pady=3) Button(ptsFrame, text="Random points on E", bg="orange", fg="black", command=(lambda: self.randomPoints())).grid(row=1, column=3, padx=5, pady=3) ecInfo.pack(side=TOP) polyFrame.pack(side=TOP) ptsInfo1.pack(side=TOP) ptsInfo2.pack(side=TOP) arithmeticFrame.pack(side=TOP) orderFrame.pack(side=TOP) listFrame.pack(side=TOP) ptsFrame.pack(side=TOP) outputFrame.pack(side=BOTTOM)
class BinaryTab(Tab): def __init__(self, master, name): Tab.__init__(self, master, name) self.a = Polynomial("z^8 + z") # initially E : y^2 + xy = x^3 + (z^8 + z)x^2 + (z + 1) self.b = Polynomial("z + 1") self.r = 9 # field is initially GF(2^9) self.modulus = Polynomial("z^9 + z^8 + 1") # initial irred poly self.Gx = Polynomial("z^8 + z^6 + z^2 + 1") # initially G = (z^8 + z^6 + z^2 + 1, z^7 + z^5 + z^4 + z + 1) self.Gy = Polynomial("z^7 + z^5 + z^4 + z + 1") self.Px = Polynomial("z^8 + z^5 + z^3 + z") # initially P = (z^8 + z^5 + z^3 + z, z^8 + z^4 + z + 1) self.Py = Polynomial("z^8 + z^4 + z + 1") self.Qx = Polynomial("z^6 + z^4 + z^3 + z") # initially Q = (z^6 + z^4 + z^3 + z, z^5 + 1) self.Qy = Polynomial("z^5 + 1") self.k = 179 self.n = 5 # initially n = 5 random curves self.m = 10 # initially m = 10 random points outputFrame = Frame(self) Button(outputFrame, text="Clear Output", bg="blue", fg="white", command=(lambda: self.clear()), borderwidth=1).pack(side=BOTTOM, pady=3) self._output = Text(outputFrame, height=15, width=70) self._output.insert(END, "You are responsible for making sure the irreducible polynomial you use is actually irreducible. " "The default, z^9 + z^8 + 1, is irreducible.\n\n") self._output.pack(side=LEFT) scrollbar = Scrollbar(outputFrame) scrollbar.pack(side=RIGHT, fill=Y) scrollbar.config(command=self._output.yview) ecInfo = Frame(self) polyFrame = Frame(self) ptsInfo1 = Frame(self) ptsInfo2 = Frame(self) arithmeticFrame = Frame(self) orderFrame = Frame(self) listFrame = Frame(self) ptsFrame = Frame(self) self.curveString = StringVar() self.curveString.set("E : F_(2^" + str(self.r) + ") : y^2 + xy = x^3 + ") curveLabel = Label(ecInfo, textvariable=self.curveString, bg="orange", fg="black", borderwidth=1).grid(row=1, column=1) self._a = Entry(ecInfo, width=25) self._a.insert(0, self.a) self._a.bind("<Return>", (lambda event: self.changeA())) self._a.grid(row=1, column=2) Label(ecInfo, text="x^2 + ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=3) self._b = Entry(ecInfo, width=25) self._b.insert(0, self.b) self._b.bind("<Return>", (lambda event: self.changeB())) self._b.grid(row=1, column=4) Label(polyFrame, text="Irreducible Polynomial: ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=1, pady=3) self._irred = Entry(polyFrame, width=51) self._irred.insert(0, self.modulus) self._irred.bind("<Return>", (lambda event: self.changeModulus())) self._irred.grid(row=1, column=2, pady=3) Label(ptsInfo1, text="Generator G = (", bg="orange", fg="black", borderwidth=1).grid(row=1, column=1, pady=3) self._Gx = Entry(ptsInfo1, width=15) self._Gx.insert(0, self.Gx) self._Gx.bind("<Return>", (lambda event: self.changeG())) self._Gx.grid(row=1, column=2, pady=3) Label(ptsInfo1, text=", ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=3, pady=3) self._Gy = Entry(ptsInfo1, width=15) self._Gy.insert(0, self.Gy) self._Gy.bind("<Return>", (lambda event: self.changeG())) self._Gy.grid(row=1, column=4, pady=3) Label(ptsInfo1, text="), k = ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=5, pady=3) self._k = Entry(ptsInfo1, width=5) self._k.insert(0, self.k) self._k.bind("<Return>", (lambda event: self.changeK())) self._k.grid(row=1, column=6, pady=3) Label(ptsInfo2, text="P = ", bg="blue", fg="white", borderwidth=1).grid(row=1, column=1, pady=3) self._Px = Entry(ptsInfo2, width=15) self._Px.insert(0, self.Px) self._Px.bind("<Return>", (lambda event: self.changeP())) self._Px.grid(row=1, column=2, pady=3) Label(ptsInfo2, text=", ", bg="blue", fg="white", borderwidth=1).grid(row=1, column=3, pady=3) self._Py = Entry(ptsInfo2, width=15) self._Py.insert(0, self.Py) self._Py.bind("<Return>", (lambda event: self.changeP())) self._Py.grid(row=1, column=4, pady=3) Label(ptsInfo2, text="), Q = ", bg="blue", fg="white", borderwidth=1).grid(row=1, column=5, pady=3) self._Qx = Entry(ptsInfo2, width=15) self._Qx.insert(0, self.Qx) self._Qx.bind("<Return>", (lambda event: self.changeQ())) self._Qx.grid(row=1, column=6, pady=3) Label(ptsInfo2, text=", ", bg="blue", fg="white", borderwidth=1).grid(row=1, column=7, pady=3) self._Qy = Entry(ptsInfo2, width=15) self._Qy.insert(0, self.Qy) self._Qy.bind("<Return>", (lambda event: self.changeQ())) self._Qy.grid(row=1, column=8) Label(ptsInfo2, text=")", bg="blue", fg="white", borderwidth=1).grid(row=1, column=9, pady=3) Button(arithmeticFrame, text="P + Q", bg="blue", fg="white", command=(lambda: self.add())).grid(row=1, column=1, padx=5, pady=3) Button(arithmeticFrame, text="kP", bg="blue", fg="white", command=(lambda: self.mult())).grid(row=1, column=2, padx=5, pady=3) Button(arithmeticFrame, text="log_G(P)", bg="blue", fg="white", command=(lambda: self.log())).grid(row=1, column=3, padx=5, pady=3) Button(orderFrame, text="Order(E)", bg="blue", fg="white", command=(lambda: self.order())).grid(row=1, column=1, padx=5, pady=3) Button(orderFrame, text="Order(G)", bg="blue", fg="white", command=(lambda: self.pointOrder())).grid(row=1, column=2, padx=5, pady=3) Label(listFrame, text="Generate ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=1, pady=3) self._n = Entry(listFrame, width=3) self._n.insert(0, self.n) self._n.bind("<Return>", (lambda event: self.changeN())) self._n.grid(row=1, column=2, pady=3) Button(listFrame, text="Random ECs", bg="orange", fg="black", command=(lambda: self.randomECs())).grid(row=1, column=3, padx=5, pady=3) Label(ptsFrame, text="List ", bg="orange", fg="black", borderwidth=1).grid(row=1, column=1, pady=3) self._m = Entry(ptsFrame, width=3) self._m.insert(0, self.m) self._m.bind("<Return>", (lambda event: self.changeM())) self._m.grid(row=1, column=2, pady=3) Button(ptsFrame, text="Random points on E", bg="orange", fg="black", command=(lambda: self.randomPoints())).grid(row=1, column=3, padx=5, pady=3) ecInfo.pack(side=TOP) polyFrame.pack(side=TOP) ptsInfo1.pack(side=TOP) ptsInfo2.pack(side=TOP) arithmeticFrame.pack(side=TOP) orderFrame.pack(side=TOP) listFrame.pack(side=TOP) ptsFrame.pack(side=TOP) outputFrame.pack(side=BOTTOM) def changeA(self): temp = self._a.get() if Polynomial.isValid(temp): self.a = Polynomial(temp) % self.modulus self._a.delete(0, END) self._a.insert(0, self.a) E = BinaryEllipticCurve(self.a, self.b, self.modulus) self._output.insert(END, str(E) + "\n") else: self._a.delete(0, END) self._a.insert(0, self.a) self._output.insert(END, "There was an error with your input. Please try again.\n") def changeB(self): temp = self._b.get() if Polynomial.isValid(temp): self.b = Polynomial(temp) % self.modulus self._b.delete(0, END) self._b.insert(0, self.b) E = BinaryEllipticCurve(self.a, self.b, self.modulus) self._output.insert(END, str(E) + "\n") else: self._b.delete(0, END) self._b.insert(0, self.b) self._output.insert(END, "There was an error with your input. Please try again.\n") def changeModulus(self): temp = self._irred.get() if Polynomial.isValid(temp): self.modulus = Polynomial(temp) self.r = self.modulus.degree() self.curveString.set("E : F_(2^" + str(self.r) + ") : y^2 + xy = x^3 + ") self._irred.delete(0, END) self._irred.insert(0, self.modulus) E = BinaryEllipticCurve(self.a, self.b, self.modulus) self._output.insert(END, "The irreducible polynomial is now set to " + str(self.modulus) + ".\n") else: self._irred.delete(0, END) self._irred.insert(0, self.modulus) self._output.insert(END, "There was an error with your input. Please try again.\n") def changeG(self): tempx = self._Gx.get() tempy = self._Gy.get() if Polynomial.isValid(tempx) and Polynomial.isValid(tempy): self.Gx = Polynomial(tempx) % self.modulus self.Gy = Polynomial(tempy) % self.modulus self._Gx.delete(0, END) self._Gy.delete(0, END) self._Gx.insert(0, self.Gx) self._Gy.insert(0, self.Gy) self._output.insert(END, "G = " + str(PolynomialPoint(self.Gx, self.Gy, 1)) + "\n") else: self._Gx.delete(0, END) self._Gy.delete(0, END) self._Gx.insert(0, self.Gx) self._Gy.insert(0, self.Gy) self._output.insert(END, "There was an error with your input. Please try again.\n") def changeP(self): tempx = self._Px.get() tempy = self._Py.get() if Polynomial.isValid(tempx) and Polynomial.isValid(tempy): self.Px = Polynomial(tempx) % self.modulus self.Py = Polynomial(tempy) % self.modulus self._Px.delete(0, END) self._Py.delete(0, END) self._Px.insert(0, self.Px) self._Py.insert(0, self.Py) self._output.insert(END, "P = " + str(PolynomialPoint(self.Px, self.Py, 1)) + "\n") else: self._Px.delete(0, END) self._Py.delete(0, END) self._Px.insert(0, self.Px) self._Py.insert(0, self.Py) self._output.insert(END, "There was an error with your input. Please try again.\n") def changeQ(self): tempx = self._Qx.get() tempy = self._Qy.get() if Polynomial.isValid(tempx) and Polynomial.isValid(tempy): self.Qx = Polynomial(tempx) % self.modulus self.Qy = Polynomial(tempy) % self.modulus self._Qx.delete(0, END) self._Qy.delete(0, END) self._Qx.insert(0, self.Qx) self._Qy.insert(0, self.Qy) self._output.insert(END, "Q = " + str(PolynomialPoint(self.Qx, self.Qy, 1)) + "\n") else: self._Qx.delete(0, END) self._Qy.delete(0, END) self._Qx.insert(0, self.Qx) self._Qy.insert(0, self.Qy) self._output.insert(END, "There was an error with your input. Please try again.\n") def changeK(self): try: self.k = int(self._k.get()) self._k.delete(0, END) self._k.insert(0, self.k) self._output.insert(END, "k = " + str(self.k) + "\n") except ValueError: self._k.delete(0, END) self._k.insert(0, self.k) self._output.insert(END, "There was an error with your input. Please try again.\n") def changeN(self): try: self.n = int(self._n.get()) self._n.delete(0, END) self._n.insert(0, self.n) self._output.insert(END, "Random curve selection will now generate " + str(self.n) + " curve") if self.n != 1: self._output.insert(END, "s") self._output.insert(END, ".\n") except ValueError: self._n.delete(0, END) self._n.insert(0, self.n) self._output.insert(END, "There was an error with your input. Please try again.\n") def changeM(self): try: self.m = int(self._m.get()) self._m.delete(0, END) self._m.insert(0, self.m) self._output.insert(END, "Random point selection will now generate " + str(self.m) + " point") if self.m != 1: self._output.insert(END, "s") self._output.insert(END, ".\n") except ValueError: self._m.delete(0, END) self._m.insert(0, self.m) self._output.insert(END, "There was an error with your input. Please try again.\n") def add(self): P = PolynomialPoint(self.Px, self.Py, Polynomial("1")) Q = PolynomialPoint(self.Qx, self.Qy, Polynomial("1")) R = P.add(Q, self.a, self.b, self.modulus) self._output.insert(END, str(P) + " + " + str(Q) + " = " + str(R) + "\n") def mult(self): P = PolynomialPoint(self.Px, self.Py, Polynomial("1")) R = P.mult(self.k, self.a, self.b, self.modulus) self._output.insert(END, str(self.k) + str(P) + " = " + str(R) + "\n") def log(self): E = BinaryEllipticCurve(self.a, self.b, self.modulus) P = PolynomialPoint(self.Px, self.Py, Polynomial("1")) G = PolynomialPoint(self.Gx, self.Gy, Polynomial("1")) R = E.log(P, G) self._output.insert(END, "log_G" + str(P) + " = " + str(R) + "\n") def order(self): ord = BinaryEllipticCurve(self.a, self.b, self.modulus).order() self._output.insert(END, "|E| = " + str(ord) + "\n") def pointOrder(self): ord = BinaryEllipticCurve(self.a, self.b, self.modulus).pointOrder(PolynomialPoint(self.Gx, self.Gy, Polynomial("1"))) self._output.insert(END, "|G| = " + str(ord) + "\n") def randomECs(self): s = BinaryEllipticCurve.listRandomECs((1<<self.modulus.degree()), self.modulus, self.n) self._output.insert(END, s + "\n") def randomPoints(self): s = BinaryEllipticCurve.listRandomPoints(BinaryEllipticCurve(self.a, self.b, self.modulus), self.m) self._output.insert(END, s + "\n") def clear(self): self._output.delete(1.0, END) self._output.insert(END, "You are responsible for making sure the irreducible polynomial you use is actually irreducible. " "The default, z^9 + z^8 + 1, is irreducible.\n\n")
def polynomialPrint(pol): polArray = strtoPolynomialArray(pol) polynomial = Polynomial(polArray) return polynomial.tostr() + "\n"
def polynomialFunctions(PolExpr): newpoli = 0 for c in PolExpr: if c == '[': newpoli = 1 elif c == ']': newpoli = 0 if c == '+' and newpoli == 0: operation = PolExpr.split('+', 1) pol1 = strtoPolynomialArray(operation[0]) pol2 = strtoPolynomialArray(operation[1]) polynomial1 = Polynomial(pol1) polynomial2 = Polynomial(pol2) print (polynomial1.tostr()) print (polynomial2.tostr()) print ("+__________________") return (polynomial1.addition(polynomial2).tostr() + "\n") elif c == '-' and newpoli == 0: operation = PolExpr.split('-', 1) pol1 = strtoPolynomialArray(operation[0]) pol2 = strtoPolynomialArray(operation[1]) polynomial1 = Polynomial(pol1) polynomial2 = Polynomial(pol2) print (polynomial1.tostr()) print (polynomial2.tostr()) print ("-__________________") return (polynomial1.substraction(polynomial2).tostr() + "\n") elif c == '*' and newpoli == 0: operation = PolExpr.split('*', 1) pol1 = strtoPolynomialArray(operation[0]) pol2 = strtoPolynomialArray(operation[1]) polynomial1 = Polynomial(pol1) polynomial2 = Polynomial(pol2) print (polynomial1.tostr()) print (polynomial2.tostr()) print ("*__________________") return (polynomial1.multiplication(polynomial2).tostr() + "\n") elif c == '/' and newpoli == 0: operation = PolExpr.split('/', 1) pol1 = strtoPolynomialArray(operation[0]) pol2 = strtoPolynomialArray(operation[1]) polynomial1 = Polynomial(pol1) polynomial2 = Polynomial(pol2) print (polynomial1.tostr()) print (polynomial2.tostr()) print ("/__________________") if polynomial1.degree() < polynomial2.degree(): return "Numerator must have a higher or equal degree compare with the denominator to be able divide both" if polynomial2.degree() == 0: return "Division by 0 error" result = [] result = polynomial1.division(polynomial2) if len(result) == 3: return result[0].tostr() + " + " + result[2].tostr() + "/" + "(" + result[1].tostr() + ")" + "\n" return (result[0].tostr() + "\n") elif c == '#' and newpoli == 0: operation = PolExpr.split('#', 1) pol1 = strtoPolynomialArray(operation[0]) polynomial1 = Polynomial(pol1) print (polynomial1.tostr()) print ("#__________________") return (polynomial1.differentiate().tostr() + "\n") elif c == '@' and newpoli == 0: operation = PolExpr.split('@', 1) pol1 = strtoPolynomialArray(operation[0]) evalnum = (operation[1].replace("(", "")).replace(")", "") polynomial1 = Polynomial(pol1) print (polynomial1.tostr()) print ("@__________________") return (str(polynomial1.eval(int(evalnum)))+ "\n")
from Polynomial import Polynomial # = TheClass() coefficients = [10, 3, 3, 4] coefficients1 = [1, 5, 2] coefficients2 = [1, 5] c = Polynomial(coefficients) d = Polynomial(coefficients1) e = Polynomial(coefficients2) print(c.tostr()) print(d.tostr()) print("_________________") print("Eval: " + str(c.eval(2))) print("Sum :" + str(c.addition(d).tostr())) print("Sub: " + c.substraction(d).tostr()) print("Mult: " + c.multiplication(d).tostr()) #print("Div: " + c.division(d).tostr()) print("Deri: " + e.differentiate().tostr())
class CanonicalChange(unittest.TestCase): def setUp(self): """Set up an example from Hill's equations.""" x_2 = Powers((2, 0, 0, 0, 0, 0)) px2 = Powers((0, 2, 0, 0, 0, 0)) y_2 = Powers((0, 0, 2, 0, 0, 0)) py2 = Powers((0, 0, 0, 2, 0, 0)) z_2 = Powers((0, 0, 0, 0, 2, 0)) pz2 = Powers((0, 0, 0, 0, 0, 2)) xpy = Powers((1, 0, 0, 1, 0, 0)) ypx = Powers((0, 1, 1, 0, 0, 0)) terms = {px2: 0.5, py2: 0.5, pz2: 0.5, xpy: -1.0, ypx: 1.0, x_2: -4.0, y_2: 2.0, z_2: 2.0} assert len(terms) == 8 self.h_2 = Polynomial(6, terms=terms) self.lie = LieAlgebra(3) self.diag = Diagonalizer(self.lie) self.eq_type = 'scc' e = [] e.append(+sqrt(2.0*sqrt(7.0)+1.0)) e.append(-e[-1]) e.append(complex(0.0, +sqrt(2.0*sqrt(7.0)-1.0))) e.append(-e[-1]) e.append(complex(0.0, +2.0)) e.append(-e[-1]) self.eig_vals = e def test_basic_matrix(self): """This test is rather monolithic, but at least it implements a concrete example that we can compare with our earlier computations. It also tests the mutual-inverse character of the equi-to-diag and diag-to-equi transformations.""" tolerance = 5.0e-15 eig = self.diag.compute_eigen_system(self.h_2, tolerance) self.diag.compute_diagonal_change() eq_type = eig.get_equilibrium_type() self.assertEquals(eq_type, self.eq_type) eigs = [pair.val for pair in eig.get_raw_eigen_value_vector_pairs()] for actual, expected in zip(eigs, self.eig_vals): self.assert_(abs(actual-expected) < tolerance, (actual, expected)) mat = self.diag.get_matrix_diag_to_equi() assert self.diag.matrix_is_symplectic(mat) sub_diag_into_equi = self.diag.matrix_as_vector_of_row_polynomials(mat) mat_inv = LinearAlgebra.inverse(MLab.array(mat)) sub_equi_into_diag = self.diag.matrix_as_vector_of_row_polynomials(mat_inv) h_diag_2 = self.h_2.substitute(sub_diag_into_equi) h_2_inv = h_diag_2.substitute(sub_equi_into_diag) self.assert_(h_2_inv) #non-zero self.assert_(not h_2_inv.is_constant()) self.assert_(self.lie.is_isograde(h_2_inv, 2)) self.assert_((self.h_2-h_2_inv).l1_norm() < 1.0e-14) comp = Complexifier(self.diag.get_lie_algebra(), eq_type) sub_complex_into_real = comp.calc_sub_complex_into_real() h_comp_2 = h_diag_2.substitute(sub_complex_into_real) h_comp_2 = h_comp_2.with_small_coeffs_removed(tolerance) self.assert_(self.lie.is_diagonal_polynomial(h_comp_2))