def generate_all_g_in_poly1d_format(m): gs_in_poly1d_format = {} for i in range(0, g_field_size): key = "g" + str(i) list_for_poly1d = [1] j = 0 while j < i: # Padding necessary 0s to the list: list_for_poly1d.append(0) j += 1 poly1d_point = np.poly1d(list_for_poly1d) # Expressing the point in terms of the irreducible polynomial: quotient, remainder = np.polydiv(poly1d_point, P_x) remainder_coefficients = (abs(remainder.c)) % 2 gs_in_poly1d_format[key] = remainder_coefficients g_power_list[key] = i # E.g => g^0 = 0, g^3 = 3 etc. zeropoly1d = np.poly1d([0]) q, r = np.polydiv(zeropoly1d, P_x) r_coeffs = (abs(r.c)) % 2 gs_in_poly1d_format["0"] = r_coeffs return gs_in_poly1d_format
def polynomial_gcd(a, b): """Function to find gcd of two poly1d polynomials. Return gcd, s, t, u, v with a s + bt = gcd (Bezout s theorem) a = u gcd b = v gcd Hence s u + t v = 1 These are used in diagimalize procedure """ s = poly1d(0) old_s = poly1d(1) t = poly1d(1) old_t = poly1d(0) r = b old_r = a while not is_zero_polynomial(r): quotient, remainder = polydiv(old_r, r) (old_r, r) = (r, remainder) (old_s, s) = (s, old_s - quotient * s) (old_t, t) = (t, old_t - quotient * t) u, _ = polydiv(a, old_r) v, _ = polydiv(b, old_r) return old_r, old_s, old_t, u, v
def JSS_trans(D): """Calcul la décomposition en fraction continue""" D = list(D.flat) # TODO:ugly!! n = len(D) Ol = [] El = [] for i in range(0, n): if i % 2 == 0: Ol.append(D[i]) El.append(0.0) else: El.append(D[i]) Ol.append(0.0) O = np.poly1d(Ol) # Polynôme des monômes pair E = np.poly1d(El) # Polynôme des monômes impair r = [] j = len(D) while j > 1: if len(O) > len(E): LMo = [] Ro = [] for i in range(0, len(O) + 1): if i < len(O): Ro.append(O[i]) LMo.append(0.0) else: LMo.append(O[i]) LMo.reverse() LMo = np.poly1d(LMo) Ro.reverse() Ro = np.poly1d(Ro) (Q, R) = np.polydiv(LMo, E) r.append(Q[1]) O = Ro + R else: LMe = [] Re = [] for i in range(0, len(E) + 1): if i < len(E): Re.append(E[i]) LMe.append(0.0) else: LMe.append(E[i]) LMe.reverse() LMe = np.poly1d(LMe) Re.reverse() Re = np.poly1d(Re) (Q, R) = np.polydiv(LMe, O) r.append(Q[1]) E = Re + R j -= 1 r.reverse() # On trouve les alpha à partir des r en utilisant la formule alpha = [] for i in range(0, len(r) - 1): alpha.append(sqrt(1.0 / (r[i] * r[i + 1]))) alpha.append(1.0 / (r[-1])) # On retourne les alpha qui serviront à construire Phi_in et K_in return alpha
def traiter_situation_1(): sx = recuperer_valeur() sx = np.array(sx) gx = np.array([1.0, 1.0]) xd = np.array([1.0, 0.0]) rx = np.polydiv(np.polymul(sx, xd), gx)[1][0] print("CRC: R(x)= ", int(rx)) print("T(x)= " + str(np.concatenate((sx, np.array([int(i) for i in np.polydiv(np.polymul(sx, xd), gx)[0]])))))
def factorize(f): res = [] while len(f) > 1 or f[0] != 1: g = kroneker(f) res.append(g) x = np.polydiv(f, g) f = np.polydiv(f, g)[0] return res
def mullerMethod(a): r = [] if len(a) - 1 == 4: r.extend(quartic(a[0], a[1], a[2], a[3], a[4])) elif len(a) - 1 == 3: r.extend(cubic(a[0], a[1], a[2], a[3])) elif len(a) - 1 > 4: p0 = list(a) p1 = list(a) l = 0 while len(p1) - 1 > 4: r.append(complex(mullerRoot(p1))) if abs(r[l].imag) < accuracy: p1 = np.polydiv(np.array(p0), np.array([1, -r[l]]))[0].tolist() p0 = p1 l = l + 1 p1r = list(p1) p1r.reverse() while abs(evalPoly(len(p1r), p1r, r[l - 1], [0, 0])[0]) < accuracy: r.append(r[l - 1]) p1 = np.polydiv(np.array(p0), np.array([1, -r[l]]))[0].tolist() p0 = p1 l = l + 1 else: conjugate_r = r[l].conjugate() r.append(conjugate_r) p1 = np.polydiv( np.array(p0), np.array([1, -2 * r[l].real, r[l].real**2 + r[l].imag**2]))[0].tolist() p0 = p1 l = l + 2 p1r = list(p1) p1r.reverse() while abs(evalPoly(len(p1r), p1r, r[l - 1])[0]) < accuracy: r.append(r[l - 2]) r.append(r[l - 2]) p1 = np.polydiv( np.array(p0), np.array( [1, -2 * r[l].real, r[l].real**2 + r[l].imag**2]))[0].tolist() p0 = p1 l = l + 2 if len(p1) - 1 == 4: r.extend(quartic(p1[0], p1[1], p1[2], p1[3], p1[4])) elif len(p1) - 1 == 3: r.extend(cubic(p1[0], p1[1], p1[2], p1[3])) r_final = [] for i in r: r_final.append( complex(round(Newton(a, i).real, 8), round(Newton(a, i).imag, 8))) return r_final
def test_polydiv_type(self): # Make polydiv work for complex types msg = "Wrong type, should be complex" x = np.ones(3, dtype=complex) q, r = np.polydiv(x, x) assert_(q.dtype == complex, msg) msg = "Wrong type, should be float" x = np.ones(3, dtype=int) q, r = np.polydiv(x, x) assert_(q.dtype == float, msg)
def test_polydiv_type(self): """Make polydiv work for complex types""" msg = "Wrong type, should be complex" x = np.ones(3, dtype=np.complex) q, r = np.polydiv(x, x) assert_(q.dtype == np.complex, msg) msg = "Wrong type, should be float" x = np.ones(3, dtype=np.int) q, r = np.polydiv(x, x) assert_(q.dtype == np.float, msg)
def index(): # add threshold of division by the second polynomial x = np.array([1,-3,0,-4,0,1,-1]) y = np.array([1,1,1]) if request.method == "POST": print(f"Stepen na rezultata {len(x)-len(y)}") pedal, pedal2 = np.polydiv(x,y) pedalList = list(pedal) pedal2List = list(pedal2) a = list(map(int, range(len(pedalList)))) a = a[::-1] publicListA = [] publicListB = [] print("Rezultat:") for i in range(len(pedalList)): publicListA.append(int(pedalList[i])}x^{a[i]) print(f"{int(pedalList[i])}x^{a[i]}") b = list(map(int, range(len(pedal2List)))) b = b[::-1] print("Ostatuk") for i in range(len(pedal2List)): publicListA.append(int(pedal2List[i])}x^{b[i]) print(f"{int(pedal2List[i])}x^{b[i]}")
def Division(a, b, mod): a = hex2bin(a)[2:] b = hex2bin(b)[2:] x = [] y = [] for i in range(len(a)): x.append(int(a[i])) for i in range(len(b)): y.append(int(b[i])) del i list = np.polydiv(x, y) quotient = list[0] % 2 # Array to binary representation temp = quotient quotient = "0b" for i in range(len(temp)): quotient = quotient + (temp[i].astype(np.int64)).astype(np.str) del temp quotient = moduloreduction(bin2hex(quotient), mod) return quotient
def Muller_all_solver(f, left, middle, right, tol, max_iter=50): root_count = 0 result = [] rank = poly1d(f).order # print("# of solution should be :", rank) numerator = f while (root_count < rank): root1, itr = Muller_solver(numerator, left, middle, right, tol, 100) if isinstance(root1, complex): # print("root is complex") root1_conj = numpy.conjugate(root1) temp = (1, -1 * 2 * root1.real, +(root1 * root1_conj).real) result.append(root1) root_count = root_count + 1 # print(root_count, root1) result.append(root1_conj) root_count = root_count + 1 # print(root_count, root1_conj) else: # print("root is real") temp = (1, -1 * root1) result.append(root1) root_count = root_count + 1 # print(root_count, root1) denominator = numpy.poly1d(temp) q, r = numpy.polydiv(numerator, denominator) numerator = q # r value should be controlled in commerical case return (result)
def test_polydiv(self): b = np.poly1d([2, 6, 6, 1]) a = np.poly1d([-1j, (1+2j), -(2+1j), 1]) q, r = np.polydiv(b, a) assert_equal(q.coeffs.dtype, np.complex128) assert_equal(r.coeffs.dtype, np.complex128) assert_equal(q*a + r, b) c = [1, 2, 3] d = np.poly1d([1, 2, 3]) s, t = np.polydiv(c, d) assert isinstance(s, np.poly1d) assert isinstance(t, np.poly1d) u, v = np.polydiv(d, c) assert isinstance(u, np.poly1d) assert isinstance(v, np.poly1d)
def factorize(polynomial): n = len(polynomial) - 1 m = floor(n / 2) + 1 d = [divisors(func(x, polynomial)) for x in range(m)] p = list(product(*d)) print([func(x, polynomial) for x in range(m)]) for _ in map(print, d): pass print(p) print({ str(lagrange(list(range(m)), y)).split('\n')[1] for y in p if len(lagrange(list(range(m)), y).coefficients) > 1 and all(map(lambda x: x == int(x), lagrange(list(range(m)), y))) }) for y in p: f = lagrange(list(range(m)), y) if len(f.coefficients) > 1 and all( map(lambda x: x == int(x), f.coefficients)): g = polydiv(polynomial, f.coefficients) if not any(g[1]) and all(map(lambda x: x == int(x), g[0])): print(str(f)[2:]) print(g, '\n') return f, factorize([int(x) for x in g[0]]) return polynomial
def decode(input: str) -> str: codeword = string_to_list(input) shift = 0 while True: syndrome = compute_syndrome(codeword) syndrome_16 = compute_syndrome_16(syndrome) syndrome_17 = compute_syndrome_17(syndrome) if compute_weight(syndrome) <= 3: errors = syndrome break if compute_weight(syndrome_16) <= 2: errors = np.polyadd(x16, syndrome_16) break if compute_weight(syndrome_17) <= 2: errors = np.polyadd(x17, syndrome_17) break shift += 1 codeword = np.roll(codeword, 1) codeword = normalize(np.polyadd(codeword, errors)) codeword = np.roll(codeword, -shift) decoded_codeword = np.polydiv(codeword, G)[0] decoded_codeword = normalize(decoded_codeword[len(decoded_codeword) - k:]) return list_to_string(decoded_codeword, k)
def EEA(A, B): # R = Ri # RP = R(i+1) # RS = R(i+2) R = A U = np.poly1d([1]) V = np.poly1d([0]) RP = B UP = np.poly1d([0]) VP = np.poly1d([1]) while RP.order != 0: quotient, remainder = np.polydiv(R, RP) Q = np.remainder(quotient, 2) RS = np.poly1d(np.remainder(remainder, 2)) US = np.poly1d(U - poly_binary_mul(Q, UP)) VS = np.poly1d(V - poly_binary_mul(Q, VP)) R = RP RP = RS U = UP UP = US V = VP VP = VS return np.remainder(UP, 2), np.remainder(VP, 2)
def PolyGCD(a: numpy.array, b: numpy.array): a = numpy.trim_zeros(a) b = numpy.trim_zeros(b) if (len(a) < len(b) or (len(a) == 0) or (len(b) == 0)): return None, None, None p0 = a[0] p1 = b[0] a0, a1 = a / p0, b / p1 s0, s1 = 1 / p0, 0 t0, t1 = 0, 1 / p1 while (len(a1)): q, r = numpy.polydiv(a0, a1) if (len(numpy.trim_zeros(a0 - numpy.polymul(a1, q))) == 0): return a1, s1, t1 a0, a1 = a1, a0 - numpy.polymul(a1, q) a1 = numpy.trim_zeros(a1) lu = a1[0] a1 = a1 / lu tmp = numpy.trim_zeros(numpy.polymul(s1, q)) if (len(tmp) == 0): tmp = 0 s0, s1 = s1, (s0 - tmp) / lu tmpt = numpy.trim_zeros(numpy.polymul(t1, q)) if (len(tmpt) == 0): tmpt = 0 t0, t1 = t1, (t0 - tmpt) / lu return a1, s1, t1
def test_polydiv(self): b = np.poly1d([2, 6, 6, 1]) a = np.poly1d([-1j, (1 + 2j), -(2 + 1j), 1]) q, r = np.polydiv(b, a) assert_equal(q.coeffs.dtype, np.complex128) assert_equal(r.coeffs.dtype, np.complex128) assert_equal(q * a + r, b)
def test_polydiv(self): b = np.poly1d([2, 6, 6, 1]) a = np.poly1d([-1j, (1+2j), -(2+1j), 1]) q, r = np.polydiv(b, a) assert_equal(q.coeffs.dtype, np.complex128) assert_equal(r.coeffs.dtype, np.complex128) assert_equal(q*a + r, b)
def windowing(num, den, M=100): b = num a = den res = b #inicializaciòn h = np.array([]) for ii in range(0, M): u, res = np.polydiv(res, a) res = np.append(res, 0) h = np.append(h, u) #print(h) u, v = signal.freqz(b=h, worN=512 * 16) plt.figure(figsize=(10, 3)) ax1 = plt.subplot(1, 2, 1, ylabel='Magnitude', xlabel='Frequency [rad/sample]', xscale='log') ax1.grid(True) ax1.plot(u, np.abs(v), 'b') ax2 = plt.subplot(1, 2, 2, ylabel='Angle (radians)', xlabel='Frequency [rad/sample]', xscale='log') ax2.plot(u, np.unwrap(np.angle(v))) ax2.grid(True) return h
def horner(poly, coeff): tempDiv = np.polydiv(poly, [1, -coeff]) print(tempDiv) if tempDiv[0][0] != 0: horner(tempDiv[0], coeff) else: print("Result is: ", tempDiv[1][0], "\n")
def test_poly1d_math(self): # here we use some simple coeffs to make calculations easier p = np.poly1d([1.0, 2, 4]) q = np.poly1d([4.0, 2, 1]) assert_equal(p / q, (np.poly1d([0.25]), np.poly1d([1.5, 3.75]))) assert_equal(p.integ(), np.poly1d([1 / 3, 1.0, 4.0, 0.0])) assert_equal(p.integ(1), np.poly1d([1 / 3, 1.0, 4.0, 0.0])) p = np.poly1d([1.0, 2, 3]) q = np.poly1d([3.0, 2, 1]) assert_equal(p * q, np.poly1d([3.0, 8.0, 14.0, 8.0, 3.0])) assert_equal(p + q, np.poly1d([4.0, 4.0, 4.0])) assert_equal(p - q, np.poly1d([-2.0, 0.0, 2.0])) assert_equal( p**4, np.poly1d( [1.0, 8.0, 36.0, 104.0, 214.0, 312.0, 324.0, 216.0, 81.0])) assert_equal(p(q), np.poly1d([9.0, 12.0, 16.0, 8.0, 6.0])) assert_equal(q(p), np.poly1d([3.0, 12.0, 32.0, 40.0, 34.0])) assert_equal(p.deriv(), np.poly1d([2.0, 2.0])) assert_equal(p.deriv(2), np.poly1d([2.0])) assert_equal( np.polydiv(np.poly1d([1, 0, -1]), np.poly1d([1, 1])), (np.poly1d([1.0, -1.0]), np.poly1d([0.0])), )
def Muller(f, x_0, x_1, x_2, epsilon): x = np.array([x_0, x_1, x_2], dtype=complex) roots = [] while len(f.c) > 1: while (True): fx = f(x) if (0 in fx): # if any of the initial guesses are roots return root = x[np.where(fx == 0)][0] break coefficients = get_dd_coefficients(x, f(x)) a = coefficients[2] b = coefficients[1] + coefficients[2] * (x[2] - x[1]) c = f(x[2]) val1 = 2 * c / (b + cmath.sqrt(b**2 - 4 * a * c)) val2 = 2 * c / (b - cmath.sqrt(b**2 - 4 * a * c)) if abs(val1) >= abs(val2): x_3 = x[2] - val2 else: x_3 = x[2] - val1 x = np.append(x[1:], x_3) if abs(f(x[2])) < epsilon: digit_accuracy = math.floor(-math.log10(epsilon)) root = round(x[2], digit_accuracy) break roots.append(root) f, _ = np.polydiv(f.c, [1, -root]) f = np.poly1d(f) return roots
def am(f, n): if n == 1: for i in range(f): for j in range(f): x = (i + j) % f y = (i * j) % f g.append(x) h.append(y) else: for i in range(f): for j in range(f): x = bin(i).replace("0b", "") y = bin(j).replace("0b", "") z = int(x, 2) ^ int(y, 2) a = list(map(int, list(x))) b = list(map(int, list(y))) c = np.polymul(a, b) d = [1] * (n + 1) if n % 2 == 1: d[n - 1] = 0 q, r = np.polydiv(c, d) e = [int(abs(k)) % 2 for k in r] l = list(map(str, e)) m = "".join(l) o = int(m, 2) g.append(z) h.append(o) a = np.array(g).reshape(f, f) m = np.array(h).reshape(f, f) return a, m
def poly_pulverizer(a: np.ndarray, b: np.ndarray): """return (g, x, y) such that a*x + b*y = g = gcd(a, b)""" a = np.array(a) b = np.array(b) if a.size < b.size: a, b = b, a a = np.trim_zeros(a, trim="f") % 2 b = np.trim_zeros(b, trim="f") % 2 r = np.ndarray((1,)) x1, x2, y1, y2 = 1, 0, 0, 1 while np.trim_zeros(r).size != 0: q, r = np.polydiv(a, b) a = b b = r x2 = np.polysub(x1, np.polymul(q, x2)) y2 = np.polysub(y1, np.polymul(q, y2)) x1, y1 = x2, y2 a = np.trim_zeros(a % 2, trim="f") b = np.trim_zeros(b % 2, trim="f") return b, x2, y2
def __init__(self, poly, word_size, offset_words): self.word_size = word_size self.poly = numpy.array(poly, dtype=int) self.offset_words = offset_words # calculate the P matrix by polynomial division # each row is: e(i)*x^10 mod rds_poly # where e(i) is the i-th base vector in the canonical orthogonal base self.check_size = self.poly.size - 1 self.matP = numpy.empty([0, self.check_size], dtype=int) for i in range(word_size): (q, r) = numpy.polydiv(numpy.identity(self.word_size+self.check_size, dtype=int)[i], self.poly) #print q, r # r may be "left-trimmed" => add missing zeros if self.check_size - r.size > 0: #print r #print numpy.zeros(check_size - r.size) r = numpy.append(numpy.zeros(self.check_size - r.size, dtype=int), r) rr = numpy.mod(numpy.array([r], dtype=int), 2) self.matP = numpy.append(self.matP, rr, axis=0) self.matG = numpy.append(numpy.identity(self.word_size, dtype=int), self.matP, axis=1) self.matH = numpy.append(self.matP, numpy.identity(self.check_size, dtype=int), axis=0) #self.offset_words = numpy.array(offset_words, dtype=int) self.syndromes = {} for ow_name, ow in offset_words.items(): # actually it's useless to call syndrome here, because of the way # our H is constructed. Do the block-wise matrix multiplication # to be convinced of this. self.syndromes[ow_name] = self.syndrome(numpy.append(numpy.zeros(self.word_size, dtype=int), numpy.array(ow, dtype=int)))
def gcd_poly(poly1: np.poly1d, poly2: np.poly1d, p: int) -> np.poly1d: """Seek the gcd of two polynomials over Fp. Args: poly1 (np.poly1d): A polynomial. poly2 (np.poly1d): A polynomial. p (int): A prime number. Returns: np.poly1d: gcd(poly1, poly2) over Fp. """ def poly2monic(poly: np.poly1d)\ -> Tuple[np.poly1d, Tuple[np.poly1d, np.poly1d]]: highest_degree_coeff = poly.coeffs[0] if highest_degree_coeff == 1: return poly, (np.poly1d([1]), np.poly1d([1])) inv_hdc = inverse.inverse_el(highest_degree_coeff, p) coeffs = poly.coeffs * inv_hdc return np.poly1d(modulus.modulus_coeffs(coeffs, p)),\ (np.poly1d([highest_degree_coeff]), np.poly1d([inv_hdc])) if len(poly1.coeffs) < len(poly2.coeffs): poly1, poly2 = poly2, poly1 poly2_monic, hdc = poly2monic(poly2) _, r = np.polydiv(poly1 * hdc[1], poly2_monic) r = np.poly1d(modulus.modulus_coeffs(r.coeffs, p)) * hdc[0] r = modulus.modulus_poly_over_fp(r, p) if r.coeffs[0] == 0: return poly2 return gcd_poly(poly2, r, p)
def adjust(self, u): assert self.poly[0] == 1 u = np.array(u) % self.p div,mod = np.polydiv(u, self.poly) result = np.array(mod).astype(int) % self.p if len(result) == 0: result = np.array([0]) return result
def encode(input_message: str) -> str: """ :return: A * x^r + (A * x^r) mod G, where A is input codeword """ input = np.array(string_to_list(input_message)) extended = np.polymul(input, [1, 0, 0, 0]) result = np.polyadd(extended, np.polydiv(extended, G)[1]) return list_to_string(normalize(result), n)
def __truediv__(self, other): #return self.__div(other) if sc.isscalar(other): return poly1d(self.coeffs/other, variable='s') else: other = sc.poly1d(other, variable='s') tplAt = sc.polydiv(self, other) return (poly1d(tplAt[0]), poly1d(tplAt[1]))
def polynomial_euclidian(p, b, c): v = np.array([1.0, b, c]) (qq, rem) = np.polydiv(p, v) r = rem[0] if (rem.size == 1): s = 0 else: s = rem[1] return (qq, r, s)
def reduceMod_t(p): global phid global t p[:] = [x % t for x in p] # print(p) Q, R = np.polydiv(p, phid) R[:] = [x % t for x in R] return R
def scalar_div(M, b): q = zeros(M.shape) r = zeros(M.shape) for i in range(M.shape[0]): for j in range(M.shape[1]): qx, rx = polydiv(M[i, j], b) q[i, j] = qx r[i, j] = rx return q, r
def __rtruediv__(self, other): #return "XXX" #return self.__div__(a) if sc.isscalar(other): return sc.poly1d(other/self.coeffs, variable='s') else: other = sc.poly1d(other, variable='s') tplAt = sc.polydiv(other, self) return (poly1d(tplAt[0]), poly1d(tplAt[1]))
def reduceMod_t(p): # Put the given polynomial in the range [-0, t) global phid global t p = [x % t for x in p] # print(p) Q, R = np.polydiv(p, phid) R = [x % t for x in R] return R
def test_polynom_arithmetic_mod(self, poly1, poly2): try: poly_numpy_1 = np.array(list(reversed(poly1.coefficients))) poly_numpy_2 = np.array(list(reversed(poly2.coefficients))) remainder_self = poly1 % poly2 quotient, remainder_numpy = np.polydiv(poly_numpy_1, poly_numpy_2) assert remainder_self.coefficients == list( reversed(remainder_numpy)) except IndexError: assert True
def checkRemainder(): for x in range(len(potentialPrimitives)): Y = np.array(potentialPrimitives[x]) print(f"potential: {potentialPrimitives[x]}") for i in range(len(divisors)): X = np.array(divisors[i]) quotient, remainder = np.polydiv(X, Y) for j in range(len(remainder)): remainder[j] = (remainder[j] % 2) print(remainder)
def residue(b,a,tol=1e-3,rtype='avg'): """Compute partial-fraction expansion of b(s) / a(s). If M = len(b) and N = len(a) b(s) b[0] s**(M-1) + b[1] s**(M-2) + ... + b[M-1] H(s) = ------ = ---------------------------------------------- a(s) a[0] s**(N-1) + a[1] s**(N-2) + ... + a[N-1] r[0] r[1] r[-1] = -------- + -------- + ... + --------- + k(s) (s-p[0]) (s-p[1]) (s-p[-1]) If there are any repeated roots (closer than tol), then the partial fraction expansion has terms like r[i] r[i+1] r[i+n-1] -------- + ----------- + ... + ----------- (s-p[i]) (s-p[i])**2 (s-p[i])**n See also: invres, poly, polyval, unique_roots """ b,a = map(asarray,(b,a)) k,b = polydiv(b,a) p = roots(a) r = p*0.0 pout, mult = unique_roots(p,tol=tol,rtype=rtype) p = [] for n in range(len(pout)): p.extend([pout[n]]*mult[n]) p = asarray(p) # Compute the residue from the general formula indx = 0 for n in range(len(pout)): bn = b.copy() pn = [] for l in range(len(pout)): if l != n: pn.extend([pout[l]]*mult[l]) an = atleast_1d(poly(pn)) # bn(s) / an(s) is (s-po[n])**Nn * b(s) / a(s) where Nn is # multiplicity of pole at po[n] sig = mult[n] for m in range(sig,0,-1): if sig > m: # compute next derivative of bn(s) / an(s) term1 = polymul(polyder(bn,1),an) term2 = polymul(bn,polyder(an,1)) bn = polysub(term1,term2) an = polymul(an,an) r[indx+m-1] = polyval(bn,pout[n]) / polyval(an,pout[n]) \ / factorial(sig-m) indx += sig return r, p, k
def div_inc_pow(num, den, order): rnum = np.zeros(len(den)) for i in range(0,len(num)): rnum[i] = num[-i-1] rden = den[::-1] res = np.zeros(order) for i in range(0, order): quot, rem = np.polydiv(rnum, rden) res[i], rnum = quot, np.zeros(len(den)) for i in range(0,len(rem)): rnum[i] = rem[i] return res[::-1]
def Bairstow(P): k = 0 # compteur d'iteration; A = P.coeffs B = 1 C = -8 # B = A[1]/A[0]; # C = A[2]/A[0]; epsilon = 10 ** -10 V = np.zeros(2) while (abs(P(V[1])) > epsilon) & (abs(P(V[0])) > epsilon): U = np.array([B, C]) T = np.poly1d([1, B, C]) Div = np.polydiv(P, T) # 1ere div Reste = Div[1] Q = Div[0] R = Reste[0] S = Reste[1] Div = np.polydiv(Q, T) # 2nde div Reste = Div[1] G = Div[0] Rc = -Reste[0] Sc = -Reste[1] Rb = -B * Rc + Sc Sb = -C * Rc dv = 1.0 / (Sb * Rc - Sc * Rb) delb = (R * Sc - S * Rc) * dv delc = (-R * Sb + S * Rb) * dv diff = np.array([delb, delc]) B = B + diff[0] C = C + diff[1] T = np.poly1d([1, B, C]) V = T.roots k = k + 1 return V, k
def polygcd(a,b, eps=1e-6): '''return monic GCD of polynomials a and b''' pa = a pb = b M = lambda x: x/x[0] # find gcd of a and b while len(pb) > 1 or pb[0] != 0: # Danger Will Robinson! requires numerical equality q,r = np.polydiv(pa,pb) pa = pb pb = r return M(pa)
def Bairstow(P,epsilon): k = 0; # compteur d'iteration; A = P.coeffs; #B = 1; C = -2; B = A[1]/A[0]; C = A[2]/A[0]; V = np.zeros(2); while ((abs(P(V[1])) > epsilon) & (abs(P(V[0])) > epsilon)): U = np.array([B, C]); T = np.poly1d([1, B, C]); Div = np.polydiv(P,T) #1ere div Reste = Div[1]; Q = Div[0]; R = Reste[0]; S = Reste[1]; Div = np.polydiv(Q,T); #2nde div Reste = Div[1]; G = Div[0]; Rc = -Reste[0]; Sc = -Reste[1]; Rb = -B*Rc + Sc; Sb = -C*Rc; dv = 1.0/(Sb*Rc -Sc*Rb); delb = (R*Sc - S*Rc)*dv; delc = (-R*Sb + S*Rb)*dv; diff = np.array([delb, delc]) B = B + diff[0]; C = C + diff[1]; T = np.poly1d([1, B, C]); V = T.roots; k = k+ 1; return V,k;
def Bairstow2(P): # Ici la resolution se fait avec Newton_Raphson k = 0 B = 100 C = -110 epsilon = 10 ** -10 V = np.zeros(2) while abs(P(V[1])) > epsilon and abs(P(V[0])) > epsilon: U = np.array([B, C]) T = np.poly1d([1, B, C]) Div = np.polydiv(P, T) # 1ere div Reste = Div[1] Q = Div[0] R = Reste[0] S = Reste[1] Div = np.polydiv(Q, T) # 2nde div Reste = Div[1] G = Div[0] Rc = -Reste[0] Sc = -Reste[1] Rb = -B * Rc + Sc Sb = -C * Rc f = lambda x, y: np.array([R, S]) J = np.array([[Rb, Rc], [Sb, Sc]]) diff = Newton_Raphson(f, J, U, 100, 10 ** -3) B = B + diff[0] C = C + diff[1] T = np.poly1d([1, B, C]) V = T.roots k = k + 1 return V, k
def test_poly1d_math(self): # here we use some simple coeffs to make calculations easier p = np.poly1d([1., 2, 4]) q = np.poly1d([4., 2, 1]) assert_equal(p/q, (np.poly1d([0.25]), np.poly1d([1.5, 3.75]))) assert_equal(p.integ(), np.poly1d([1/3, 1., 4., 0.])) assert_equal(p.integ(1), np.poly1d([1/3, 1., 4., 0.])) p = np.poly1d([1., 2, 3]) q = np.poly1d([3., 2, 1]) assert_equal(p * q, np.poly1d([3., 8., 14., 8., 3.])) assert_equal(p + q, np.poly1d([4., 4., 4.])) assert_equal(p - q, np.poly1d([-2., 0., 2.])) assert_equal(p ** 4, np.poly1d([1., 8., 36., 104., 214., 312., 324., 216., 81.])) assert_equal(p(q), np.poly1d([9., 12., 16., 8., 6.])) assert_equal(q(p), np.poly1d([3., 12., 32., 40., 34.])) assert_equal(p.deriv(), np.poly1d([2., 2.])) assert_equal(p.deriv(2), np.poly1d([2.])) assert_equal(np.polydiv(np.poly1d([1, 0, -1]), np.poly1d([1, 1])), (np.poly1d([1., -1.]), np.poly1d([0.])))
def GetPolyEvalData(degrees, batch_size=128): """ Generate one batch of data """ assert type(degrees) is list if FLAGS.task == "root_eval": return GetSmallestRootData(degrees, batch_size) degree = np.random.choice(degrees) X = np.zeros((degree, batch_size, 2), dtype=np.float32) if FLAGS.task.endswith("eval"): Y = np.zeros((batch_size, 1), dtype=np.float32) else: Y = np.zeros((degree, batch_size, 1), dtype=np.float32) for i in xrange(batch_size): roots = np.random.uniform(low=-1, high=1, size=degree - 1) roots.sort() coefs_0_n = np.polynomial.polynomial.polyfromroots(roots) f = np.poly1d(roots, True) coefs_0_n = np.random.uniform(low=-1, high=1, size=degree) f = np.poly1d(coefs_0_n[::-1]) a = np.random.uniform(low=-1, high=1) if FLAGS.task == "poly_eval": Y[i, 0] = f(a) elif FLAGS.task == "poly_der_eval": Y[i, 0] = np.polyder(f)(a) elif FLAGS.task == "poly_div": Y[:, i, 0] = np.concatenate(np.polydiv(f, [1, -a])) elif FLAGS.task == "newton_eval": Y[i, 0] = a - f(a) / np.polyder(f)(a) else: raise ValueError("Task must be either poly_eval, poly_div, " + "poly_der_eval, root_eval, or newton_eval") X[:, i, 0] = coefs_0_n[::-1] X[:, i, 1] = a if FLAGS.task.endswith("eval"): return list(X), Y else: return list(X), list(Y)
def polyInverse(num,field,modValue = 2,printOption = False): a = num ansOld = np.poly1d(a) b = field ans = np.poly1d(b) first = np.poly1d(0) sec = np.poly1d(1) otherSol = np.poly1d(1) secotherSol = np.poly1d(0) while ansOld(0) != 0: array = np.polydiv(ans,ansOld)[0] array = modPolynomial(array) inv = compute(sec,first,array) first = sec sec = inv othInv = compute(secotherSol,otherSol,array) otherSol = secotherSol secotherSol = othInv newAns = compute(ansOld,ans,array) ans = ansOld ansOld = newAns list = (inv, othInv) if printOption: print 'the inverse of \n ',np.poly1d(field),' is \n',inv print 'and the other inverse is \n',othInv return list
def polylcm(a,b): '''return (Ka,Kb,c) such that c = LCM(a,b) = Ka*a = Kb*b''' gcd = polygcd(a,b) Ka,_ = np.polydiv(b,gcd) Kb,_ = np.polydiv(a,gcd) return (Ka,Kb,np.polymul(Ka,a))
matriz = [] matriz.append(eval(input("Informe os coeficientes do polinômio: "))) a = eval(input("Entre com o limite inferior: ")) b = eval(input("Entre com o limite superior: ")) size = len(matriz[0]) ordem = size -2 matriz.append(np.polyder(matriz[0])) i = 0 while ordem: matriz.append(np.polydiv(matriz[i], matriz[i+1])[1]*-1) i += 1 ordem -= 1 i = 0 mul = size - 1 resultadoA = [] resultadoB = [] while size: resultadoA.append(np.polyval(matriz[i], a)) resultadoB.append(np.polyval(matriz[i], b)) i += 1 size -= 1
def poly2lsf(a): """Prediction polynomial to line spectral frequencies. converts the prediction polynomial specified by A, into the corresponding line spectral frequencies, LSF. normalizes the prediction polynomial by A(1). .. doctest:: >>> a = [1.0000 , 0.6149 , 0.9899 , 0.0000 , 0.0031, -0.0082 >>> lsf = poly2lsf(a) >>> lsf = array([ 0.7842, 1.5605 , 1.8776 , 1.8984, 2.3593]) .. seealso:: lsf2poly, poly2rc, poly2qc, rc2is """ #Line spectral frequencies are not defined for complex polynomials. # Normalize the polynomial a = numpy.array(a) if a[0] != 1: a/=a[0] if max(numpy.abs(numpy.roots(a))) >= 1.0: print("hello world") # Form the sum and differnce filters p = len(a)-1 # The leading one in the polynomial is not used a1 = numpy.concatenate((a, numpy.array([0]))) a2 = a1[-1::-1] P1 = a1 - a2 # Difference filter Q1 = a1 + a2 # Sum Filter divisorOdd = [1,0,-1] divisorEven1 = [1,-1] divisorEven2 = [1,1] # If order is even, remove the known root at z = 1 for P1 and z = -1 for Q1 # If odd, remove both the roots from P1 if p%2: # Odd order P, r = scipy.signal.deconvolve(P1,divisorOdd) Q = Q1 else: # Even order P, r = numpy.polydiv(P1, divisorEven1) Q, r = numpy.polydiv(Q1, divisorEven2) rP = numpy.roots(P) rQ = numpy.roots(Q) aP = numpy.angle(rP[1::2]) aQ = numpy.angle(rQ[1::2]) lsf = sorted(numpy.concatenate((-aP,-aQ))) print("a",a) print("p",p) print("a1",a1) print("a2",a2) print("P1",P1) print("Q1",Q1) print("r",r) print("P",P) print("Q",Q) print("rP",rP) print("rQ",rQ) print("aP",aP) print("aQ",aQ) return lsf
def div(self, u1, u2): return self.adjust(np.polydiv(u1,u2))
def test_poly_div(self): # Ticket #553 u = np.poly1d([1, 2, 3]) v = np.poly1d([1, 2, 3, 4, 5]) q, r = np.polydiv(u, v) assert_equal(q*v + r, u)
def residue(b, a, tol=1e-3, rtype='avg'): """ Compute partial-fraction expansion of b(s) / a(s). If ``M = len(b)`` and ``N = len(a)``, then the partial-fraction expansion H(s) is defined as:: b(s) b[0] s**(M-1) + b[1] s**(M-2) + ... + b[M-1] H(s) = ------ = ---------------------------------------------- a(s) a[0] s**(N-1) + a[1] s**(N-2) + ... + a[N-1] r[0] r[1] r[-1] = -------- + -------- + ... + --------- + k(s) (s-p[0]) (s-p[1]) (s-p[-1]) If there are any repeated roots (closer together than `tol`), then H(s) has terms like:: r[i] r[i+1] r[i+n-1] -------- + ----------- + ... + ----------- (s-p[i]) (s-p[i])**2 (s-p[i])**n Returns ------- r : ndarray Residues. p : ndarray Poles. k : ndarray Coefficients of the direct polynomial term. See Also -------- invres, numpy.poly, unique_roots """ b, a = map(asarray, (b, a)) rscale = a[0] k, b = polydiv(b, a) p = roots(a) r = p * 0.0 pout, mult = unique_roots(p, tol=tol, rtype=rtype) p = [] for n in range(len(pout)): p.extend([pout[n]] * mult[n]) p = asarray(p) # Compute the residue from the general formula indx = 0 for n in range(len(pout)): bn = b.copy() pn = [] for l in range(len(pout)): if l != n: pn.extend([pout[l]] * mult[l]) an = atleast_1d(poly(pn)) # bn(s) / an(s) is (s-po[n])**Nn * b(s) / a(s) where Nn is # multiplicity of pole at po[n] sig = mult[n] for m in range(sig, 0, -1): if sig > m: # compute next derivative of bn(s) / an(s) term1 = polymul(polyder(bn, 1), an) term2 = polymul(bn, polyder(an, 1)) bn = polysub(term1, term2) an = polymul(an, an) r[indx + m - 1] = polyval(bn, pout[n]) / polyval(an, pout[n]) \ / factorial(sig - m) indx += sig return r / rscale, p, k
def residuez(b,a,tol=1e-3,rtype='avg'): """Compute partial-fraction expansion of b(z) / a(z). If M = len(b) and N = len(a) b(z) b[0] + b[1] z**(-1) + ... + b[M-1] z**(-M+1) H(z) = ------ = ---------------------------------------------- a(z) a[0] + a[1] z**(-1) + ... + a[N-1] z**(-N+1) r[0] r[-1] = --------------- + ... + ---------------- + k[0] + k[1]z**(-1) ... (1-p[0]z**(-1)) (1-p[-1]z**(-1)) If there are any repeated roots (closer than tol), then the partial fraction expansion has terms like r[i] r[i+1] r[i+n-1] -------------- + ------------------ + ... + ------------------ (1-p[i]z**(-1)) (1-p[i]z**(-1))**2 (1-p[i]z**(-1))**n See also: invresz, poly, polyval, unique_roots """ b,a = map(asarray,(b,a)) gain = a[0] brev, arev = b[::-1],a[::-1] krev,brev = polydiv(brev,arev) if krev == []: k = [] else: k = krev[::-1] b = brev[::-1] p = roots(a) r = p*0.0 pout, mult = unique_roots(p,tol=tol,rtype=rtype) p = [] for n in range(len(pout)): p.extend([pout[n]]*mult[n]) p = asarray(p) # Compute the residue from the general formula (for discrete-time) # the polynomial is in z**(-1) and the multiplication is by terms # like this (1-p[i] z**(-1))**mult[i]. After differentiation, # we must divide by (-p[i])**(m-k) as well as (m-k)! indx = 0 for n in range(len(pout)): bn = brev.copy() pn = [] for l in range(len(pout)): if l != n: pn.extend([pout[l]]*mult[l]) an = atleast_1d(poly(pn))[::-1] # bn(z) / an(z) is (1-po[n] z**(-1))**Nn * b(z) / a(z) where Nn is # multiplicity of pole at po[n] and b(z) and a(z) are polynomials. sig = mult[n] for m in range(sig,0,-1): if sig > m: # compute next derivative of bn(s) / an(s) term1 = polymul(polyder(bn,1),an) term2 = polymul(bn,polyder(an,1)) bn = polysub(term1,term2) an = polymul(an,an) r[indx+m-1] = polyval(bn,1.0/pout[n]) / polyval(an,1.0/pout[n]) \ / factorial(sig-m) / (-pout[n])**(sig-m) indx += sig return r/gain, p, k
def test_poly_div(self, level=rlevel): """Ticket #553""" u = np.poly1d([1, 2, 3]) v = np.poly1d([1, 2, 3, 4, 5]) q, r = np.polydiv(u, v) assert_equal(q*v + r, u)