def plot(self,U,V,ctr):
     X1=arange(min(U)-2,max(U)+2,0.1)
     x=[1]
     for i in range(len(U)):
         x=P.polymul(x,[-1*U[i],1])
     plt.axis([-10,10,min(V)-1,max(V)+1])
     b=[0]
     for i in range(len(U)):
         a=P.polydiv(x,[-1*U[i],1])
         b=P.polyadd(P.polymul((P.polydiv(a[0],P.polyval(U[i],a[0])))[0],[V[i]]),b)
         Y=P.polyval(X1,P.polymul((P.polydiv(a[0],P.polyval(U[i],a[0])))[0],[V[i]]))
         plt.plot(X1,Y,'y')
     plt.plot(U,V,'ro')
     X1=arange(-5,5,0.1)
     Y=P.polyval(X1,b)
     plt.plot(X1,Y,'b',label='Required Polynomial')
     plt.plot((-8,8),(0,0),'k')
     
     plt.grid(b=True, which='both', color='0.65',linestyle='-')
     Y=list(Y)
     plt.plot((0,0),(-max(Y)-5,max(Y)+5),'k')
     plt.xlabel('x-axis')
     plt.ylabel('y-axis')
     plt.legend(loc=1)
     filename = "this_plot"+str(ctr)+".png"
     path = "C:\\Users\HP\Anaconda3\static"
     fullpath = os.path.join(path, filename)
     plt.savefig(fullpath)
示例#2
0
    def plot(self, U, V, ctr):
        X1 = arange(min(U) - 2, max(U) + 2, 0.1)
        x = [1]
        for i in range(len(U)):
            x = P.polymul(x, [-1 * U[i], 1])
        plt.axis([-10, 10, min(V) - 1, max(V) + 1])
        b = [0]
        for i in range(len(U)):
            a = P.polydiv(x, [-1 * U[i], 1])
            b = P.polyadd(
                P.polymul((P.polydiv(a[0], P.polyval(U[i], a[0])))[0], [V[i]]),
                b)
            Y = P.polyval(
                X1,
                P.polymul((P.polydiv(a[0], P.polyval(U[i], a[0])))[0], [V[i]]))
            plt.plot(X1, Y, 'y')
        plt.plot(U, V, 'ro')
        X1 = arange(-5, 5, 0.1)
        Y = P.polyval(X1, b)
        plt.plot(X1, Y, 'b', label='Required Polynomial')
        plt.plot((-8, 8), (0, 0), 'k')

        plt.grid(b=True, which='both', color='0.65', linestyle='-')
        Y = list(Y)
        plt.plot((0, 0), (-max(Y) - 5, max(Y) + 5), 'k')
        plt.xlabel('x-axis')
        plt.ylabel('y-axis')
        plt.legend(loc=1)
        filename = "this_plot" + str(ctr) + ".png"
        path = "C:\\Users\HP\Anaconda3\static"
        fullpath = os.path.join(path, filename)
        plt.savefig(fullpath)
示例#3
0
def extended_euclid_poly(a, b, p):
    """ Повертає d=НСД(x,y) і x, y такі, що ax + by = d """
    if np.all(b == 0):
        print ("b=0", a, b)
        return a, np.array([1]), np.array([0])
    d, x, y = extended_euclid_poly(b, P.polydiv(a, b)[1] % p, p)
    print (d, x, y)
    return d, y, (x - P.polymul(P.polydiv(a,b)[0], y)) % p
示例#4
0
def egcd(a, b, p):
    x,y, u,v = np.array([0]),np.array([1]), np.array([1]),np.array([0])
    while not np.all(a == 0):
        q, r = P.polydiv(b,a)[0]%p, P.polydiv(b, a)[1]%p
        print(q,r)
        m, n = (x-P.polymul(u, q))%p, (y-P.polymul(v,q))%p
        b,a, x,y, u,v = a,r, u,v, m,n
    gcd = b
    return gcd, x, y
示例#5
0
def PolyGCD(a: numpy.array, b: numpy.array):
    """Iterative Greatest Common Divisor  for polynomial"""

    # if len(a) < len(b):
    #     a, b = b, a
    x, xt, y, yt = (1, ), (0, ), (0, ), (1, )
    while any(num != 0.0 for num in b):
        q = polydiv(a, b)[0]
        a, b = b, polydiv(a, b)[1]
        x, xt = xt, polysub(x, polymul(xt, q))
        y, yt = yt, polysub(y, polymul(yt, q))
    return a, x, y
示例#6
0
def plot(points):

    s, X, F = points[:], [], []
    while (s != ''):
        i = s.index('(')
        j = s.index(',', i)
        X.append(float(s[i + 1:j]))
        k = s.index(')', j)
        F.append(float(s[j + 1:k]))
        s = s[k + 2:]

    fig = plt.figure()
    plt.clf()
    sub = fig.add_subplot(111)
    X1 = np.arange(min(X) - 2, max(X) + 2, 0.1)
    num_plots = len(X)
    colormap = plt.cm.gist_ncar
    plt.gca().set_color_cycle(
        [colormap(i) for i in np.linspace(0.2, 0.9, num_plots)])
    x = [1.0]
    for i in range(len(X)):
        x = P.polymul(x, [-1 * X[i], 1])
    b = [0.0]
    for i in range(len(X)):
        a = P.polydiv(x, [-1 * X[i], 1])
        b = P.polyadd(
            P.polymul((P.polydiv(a[0], P.polyval(X[i], a[0])))[0], [F[i]]), b)
        Y = P.polyval(
            X1, P.polymul((P.polydiv(a[0], P.polyval(X[i], a[0])))[0], [F[i]]))
        sub.plot(X1, Y)

    Y = P.polyval(X1, b)
    Y1 = P.polyval(np.arange(min(X), max(X) + 0.1, 0.1), b)
    interpol_obj = sub.plot(X1, Y, 'k', linewidth=2)
    sub.plot(X, F, 'ro', markersize=8)

    plt.grid(True)
    fig.legend(interpol_obj, ['Interpolating Polynomial'],
               fancybox=True,
               shadow=True,
               loc='upper left')
    plt.axis([min(X) - 3, max(X) + 3, min(Y1) - 2, max(Y1) + 2])
    plt.xlabel('x axis')
    plt.ylabel('y axis')
    plt.title('Interpolate')
    canvas = FigureCanvas(fig)
    output = StringIO.StringIO()
    canvas.print_png(output)
    response = make_response(output.getvalue())
    response.mimetype = 'image/png'
    return response
示例#7
0
def polynomials_mult(x, y, mod, poly_mod):
    return np.int64(
        np.round(
            poly.polydiv(
                poly.polymul(x, y) % mod,
                poly_mod
            )[1] % mod))
示例#8
0
def decode(in_file, in_file2, out_file):
    a = open(in_file, 'r')
    base = int(a.readline())
    n = int(a.readline())
    poly = list(map(int, a.readline().split()))
    a.close()

    maxp = 0
    for i, v in enumerate(poly):
        if (v == 1):
            maxp = i

    a = open(in_file2, 'r')
    data_len = int(a.readline())
    data = list(map(int, a.readline().split()))
    a.close()

    decoded = []
    data_idx = 0
    while data_idx < data_len:
        cur_data = data[data_idx:data_idx + n]
        dec = list(
            map(
                lambda x: int(x % base),
                p.polydiv(list(map(lambda x: x % base, cur_data)),
                          list(map(lambda x: x % base, poly)))[0]))
        decoded += dec + (n - maxp - len(dec)) * [0]
        #print(dec+(n-maxp-len(dec))*[0])
        data_idx += n

    a = open(out_file, 'w')
    a.write(str(len(decoded)) + '\n' + ' '.join(map(str, decoded)) + '\n')
    print(decoded)
示例#9
0
def divpoly(f, g, m):
    fx = []
    gx = []
    for i in range(len(f)):
        fx.append(Fraction(int(f[i]), 1))
    for i in range(len(g)):
        gx.append(Fraction(int(g[i]), 1))
    div = poly.polydiv(fx, gx)
    div0 = div[0]  # f // g
    div1 = div[1]  # f % g
    for i in range(len(div0)):
        fract = str(div0[i]).split('/')
        if len(fract) == 2:
            a = int(fract[0])
            b = int(fract[1])
            div0[i] = a * int(invert(b, m))
        div0[i] = int(div0[i] % m)
    for i in range(len(div1)):
        fract = str(div1[i]).split('/')
        if len(fract) == 2:
            a = int(fract[0])
            b = int(fract[1])
            div1[i] = a * int(invert(b, m))
        div1[i] = int(div1[i] % m)
    return (div0, div1)
示例#10
0
def poly_mul_mod(op1, op2, coeff_mod, poly_mod):
    """Multiply two polynomials and modulo every coefficient with coeff_mod.

    Args:
        op1 (list): First Polynomail (Multiplicand).
        op2 (list): Second Polynomail (Multiplier).

    Returns:
        A list with polynomial coefficients.
    """

    # For non same size polynomials we have to shift the polynomials because numpy consider right
    # side as lower order of polynomial and we consider right side as heigher order.
    if len(op1) != poly_mod:
        op1 += [0] * (poly_mod - len(op1))
    if len(op2) != poly_mod:
        op2 += [0] * (poly_mod - len(op2))

    poly_len = poly_mod
    poly_mod = np.array([1] + [0] * (poly_len - 1) + [1])
    result = (
        poly.polydiv(
            poly.polymul(np.array(op1, dtype="object"), np.array(op2, dtype="object")) % coeff_mod,
            poly_mod,
        )[1]
        % coeff_mod
    ).tolist()

    if len(result) != poly_len:
        result += [0] * (poly_len - len(result))

    return [round(x) for x in result]
示例#11
0
    def Lagrange(L,M):                                                               
        polylist=[]
        n=len(L)                                                           
        w=(-1*L[0],1)                                                      
        for i in range(1,n):
            w=P.polymul(w,(-1*L[i],1))                                    
        result=array([0.0 for i in range(len(w)-1)])                    
        derivative=P.polyder(w)                                             
        for i in range(n):
            polylist.append((P.polydiv(w,(-1*L[i],1))[0]*M[i])/P.polyval(L[i],derivative))
            result+=polylist[-1]   

        polynomial=""                                                  
        for i in range(len(result)-1,0,-1):                                 
            if(result[i]!=0):
                if(result[i]>0 and i!=(len(result)-1)):
                    polynomial+=" + "+str(result[i])+"x^"+str(i)+" "
                elif(result[i]>0 and i==(len(result)-1)):
                    polynomial+=str(result[i])+"x^"+str(i)+" "
                else:
                    polynomial+=" - "+str(-1*result[i])+"x^"+str(i)+" "
        if(result[0]!=0):
            polynomial+=" + "+str(result[0]) if result[0]>0 else " - "+str(-1*result[0])
        plot(L,M,polylist,result)
        return (polynomial)
示例#12
0
 def __div__(self, other):
     if isinstance(other, Polynomial):
         result = polynomial.polydiv(self._poly, other._poly)[0]
     else:
         result = self._poly[other:]
     result = self._normalizePoly(result, len(self._poly))
     return Polynomial(poly=result)
示例#13
0
def plot(points):

    s,X,F=points[:],[],[]
    while(s!=''):
        i=s.index('(')
        j=s.index(',',i)
        X.append(float(s[i+1:j]))
        k=s.index(')',j)
        F.append(float(s[j+1:k]))
        s=s[k+2:]

    fig=plt.figure()
    plt.clf()
    sub=fig.add_subplot(111)
    X1=np.arange(min(X)-2,max(X)+2,0.1)
    num_plots=len(X)
    colormap = plt.cm.gist_ncar
    plt.gca().set_color_cycle([colormap(i) for i in np.linspace(0.2, 0.9, num_plots)])
    x=[1.0]
    for i in range(len(X)):
        x=P.polymul(x,[-1*X[i],1])
    b=[0.0]
    for i in range(len(X)):
        a=P.polydiv(x,[-1*X[i],1])
        b=P.polyadd(P.polymul((P.polydiv(a[0],P.polyval(X[i],a[0])))[0],[F[i]]),b)
        Y=P.polyval(X1,P.polymul((P.polydiv(a[0],P.polyval(X[i],a[0])))[0],[F[i]]))
        sub.plot(X1,Y)

    Y=P.polyval(X1,b)
    Y1=P.polyval(np.arange(min(X)-0.1,max(X)+0.1,0.1),b)
    interpol_obj=sub.plot(X1,Y,'k',linewidth=2)
    sub.plot(X,F,'ro',markersize=8)

    plt.grid(True)
    fig.legend(interpol_obj,['Interpolating Polynomial'],fancybox=True,shadow=True,loc='upper left')
    plt.axis([min(X)-3,max(X)+3,min(Y1)-2,max(Y1)+2])
    plt.xlabel('x axis')
    plt.ylabel('y axis')
    plt.title('Interpolate')
    #plt.show()

    canvas = FigureCanvas(fig)
    output = StringIO.StringIO()
    canvas.print_png(output)
    response = make_response(output.getvalue())
    response.mimetype = 'image/png'
    return response
def gen_poly(n, q):
    global hlpr
    l = 0  #Gamma Distribution Location (Mean "center" of dist.)
    poly = np.floor(np.random.normal(l, size=(n)))
    while (len(poly) != n):
        poly = np.floor(np.random.normal(l, size=(n)))
        poly = np.floor(p.polydiv(poly, hlpr)[1] % q)
    return poly
示例#15
0
 def __gen_poly_dynamic(self, n, q):
     l = 0  #Gamma Distribution Location (Mean "center" of dist.)
     o = 3.467
     poly = np.floor(np.random.normal(l, size=(n)))
     while (len(poly) != n or poly[0] == 0):
         poly = (np.random.normal(l, o, size=(n))).astype(int)
         poly = (p.polydiv(poly, self.hlpr)[1]).astype(int)
     return poly
示例#16
0
    def DEC(self, g, t):

        # Return k = (gt (mod q) (mod 2) )/g (mod 2)
        k = p.polymul(g, t)
        print "Mult g*t=", k, len(k)
        k = self.polymod(k)
        print k
        print "gt/g", p.polydiv((k), g)
        k = (p.polydiv((k) % 2, g)[0] % 2).astype(int)

        print "---DEC:"
        print "(IN)  g: ", g, len(g)
        print "(IN)  t: ", t, len(t)
        print "(OUT) k: ", k, len(k)
        print "\n"

        return k
def sturms_sequence(p: Polynomial):
    """
    Returns Sturm's sequence of a given polynomial.
    """
    # setting up the Sturm's sequence.
    sturms_seq = []
    sturms_seq.append(p)
    sturms_seq.append(p.deriv())

    # filling the Sturm's sequence list.
    f = -Polynomial(poly.polydiv(sturms_seq[-2].coef, sturms_seq[-1].coef)[1])
    while f.degree() != 0 or f.coef[0] != 0:
        sturms_seq.append(f.copy())
        f = -Polynomial(
            poly.polydiv(sturms_seq[-2].coef, sturms_seq[-1].coef)[1])

    return sturms_seq
示例#18
0
def polymul_wm(x, y, poly_mod):
    """Multiply two polynomials
    Args:
        x, y: two polynomials to be multiplied.
        poly_mod: polynomial modulus.
    Returns:
        A polynomial in Z[X]/(poly_mod).
    """
    return poly.polydiv(poly.polymul(x, y), poly_mod)[1]
示例#19
0
def polyadd_wm(x, y, poly_mod):
    """Add two polynomials
        Args:
            x, y: two polynomials to be added.
            poly_mod: polynomial modulus.
        Returns:
            A polynomial in Z[X]/(poly_mod).
        """
    return poly.polydiv(poly.polyadd(x, y), poly_mod)[1]
示例#20
0
def polynomials_sum(x, y, mod, poly_mod):
    return np.int64(
        np.round(
            poly.polydiv(
                poly.polyadd(x, y) % mod,
                poly_mod
            )[1] % mod
        )
    )
示例#21
0
def gcd(x, y, p):
    x = np.array(x)
    y = np.array(y)
    if np.all(x == 0) or np.all(y == 0):
        return np.array([-1.])
    while not np.all(y == 0):
        (x, y) = (y % p, P.polydiv(x, y)[1] % p)
        #print(x,y)
    #print(polyNorm(x))
    return polyNorm(x)
示例#22
0
def PolyGCD_rec(a: numpy.array, b: numpy.array):
    """Recursive Greatest Common Divisor  for polynomial"""

    if all(num == 0.0 for num in a):
        return b, 0, 1
    t = polydiv(b, a)
    d, x1, y1 = PolyGCD_rec(t[1], a)
    x = polysub(y1, polymul(t[0], x1))
    y = x1
    return d, x, y
示例#23
0
def berlekampTest(prime, poly):
    m = len(poly) - 1
    u = [0, 1]
    for i in range(0, m // 2):
        u = P.polydiv(P.polypow(u, prime), poly)[1] % prime
        d = gcd(P.polysub(u, [0, 1]) % prime, poly, prime)
        #print(P.polysub(u, [0, 1]) % prime, poly, d)
        if not np.array_equal(np.array([1.]), d):
            return False
    return True
示例#24
0
def mul(a, b, prime, exp, min0):
    a.reverse()
    b.reverse()
    min0.reverse()
    ans = []
    mul0 = poly.polymul(a, b)
    ans = poly.polydiv(mul0, min0)[1]
    ans = list(map(int, ans))
    ans.reverse()
    return ans
示例#25
0
def poly_mul_mod(op1, op2, modulus):
    """return multiplication of two polynomials with all coefficients of
    polynomial %q(coefficient modulus) and result polynomial % t(polynomial modulus)"""
    poly_mod = np.array([1] + [0] * (len(op1) - 1) + [1])
    result = (poly.polydiv(
        poly.polymul(np.array(op1, dtype="object"),
                     np.array(op2, dtype="object")) % modulus,
        poly_mod,
    )[1] % modulus).tolist()
    return [round(x) for x in result]
示例#26
0
    def test_polydiv(self) :
        # check zero division
        assert_raises(ZeroDivisionError, poly.polydiv, [1], [0])

        # check scalar division
        quo, rem = poly.polydiv([2],[2])
        assert_equal((quo, rem), (1, 0))
        quo, rem = poly.polydiv([2,2],[2])
        assert_equal((quo, rem), ((1,1), 0))

        # check rest.
        for i in range(5) :
            for j in range(5) :
                msg = "At i=%d, j=%d" % (i,j)
                ci = [0]*i + [1,2]
                cj = [0]*j + [1,2]
                tgt = poly.polyadd(ci, cj)
                quo, rem = poly.polydiv(tgt, ci)
                res = poly.polyadd(poly.polymul(quo, ci), rem)
                assert_equal(res, tgt, err_msg=msg)
示例#27
0
    def test_polydiv(self):
        # check zero division
        assert_raises(ZeroDivisionError, poly.polydiv, [1], [0])

        # check scalar division
        quo, rem = poly.polydiv([2], [2])
        assert_equal((quo, rem), (1, 0))
        quo, rem = poly.polydiv([2, 2], [2])
        assert_equal((quo, rem), ((1, 1), 0))

        # check rest.
        for i in range(5):
            for j in range(5):
                msg = "At i=%d, j=%d" % (i, j)
                ci = [0] * i + [1, 2]
                cj = [0] * j + [1, 2]
                tgt = poly.polyadd(ci, cj)
                quo, rem = poly.polydiv(tgt, ci)
                res = poly.polyadd(poly.polymul(quo, ci), rem)
                assert_equal(res, tgt, err_msg=msg)
def polymul(x, y, modulus, poly_mod):
    """Add two polynoms
    Args:
        x, y: two polynoms to be added.
        modulus: coefficient modulus.
        poly_mod: polynomial modulus.
    Returns:
        A polynomial in Z_modulus[X]/(poly_mod).
    """
    return np.int64(
        np.round(
            poly.polydiv(poly.polymul(x, y) % modulus, poly_mod)[1] % modulus))
示例#29
0
    def Keygen(self, l):
        #TODO: l has to come into play properly to provide strong security
        #For now I'm letting the polynomials be small, uniformly distributed centered at 0

        f = np.asarray(
            [-7, 1, 6,
             3])  #self.__gen_poly(self.n,self.q)          # f <-$- Df
        g = np.asarray(
            [-2, -1, -1,
             -2])  #self.__gen_poly(self.n,self.q)          # g <-$- Df
        # We gotta check that f,g are invertible

        h = (p.polydiv(f, g)[0]).astype(int)  # h = f/g (mod q)

        print "---Keygen:"
        print "(..)  f: ", f, len(f)
        print "(OUT) g: ", g, len(g)
        print "(OUT) h: ", p.polydiv(f, g), h, len(h)
        print "\n"

        return (g, h)  # Return (Kd, Ke) = (g,h)
示例#30
0
def channel_modeling(SNRdB: np.ndarray, n_exp: int, messages: np.ndarray,
                     codewords_bits: np.ndarray, codewords: np.ndarray,
                     g_x: np.ndarray):

    Pe_bit, Ped, Ped_theor = np.zeros(SNRdB.size), np.zeros(
        SNRdB.size), np.zeros(SNRdB.size)

    r = g_x.size - 1
    n = codewords_bits.shape[1]

    SNR = 10**(SNRdB / 10)
    for i in range(SNR.size):
        starttime = timeit.default_timer()

        sigma = np.sqrt(1 / (2 * SNR[i]))
        nTests = nErr = nErrBits = 0

        while nTests < n_exp:
            message_index = np.random.randint(0, messages.shape[0])
            c_x = codewords_bits[message_index]  # CRC
            c = codewords[message_index]  # BPSK
            c_AWGN = c + (sigma * np.random.randn(n))  # Channel AWGN
            c_x_AWGN = (c_AWGN > 0).astype('int32')  # unBPSK
            s = np.mod(poly.polydiv(c_x_AWGN, g_x), 2)[1].max() == 1  # unCRC

            # Counting errors
            v = (c_x.astype('int32') ^ c_x_AWGN).sum()
            nErrBits = nErrBits + v
            if not s and (v > 0):
                nErr = nErr + 1
            nTests = nTests + 1

        Ped[i] = nErr / nTests
        Pe_bit[i] = nErrBits / (nTests * n)
        print('[{}/{}]\tSNRdB = {}\tВремя выполнения : {:.1f}с'.format(
            i + 1, SNR.size, SNRdB[i],
            timeit.default_timer() - starttime))

    Pe_bit_theor = norm.sf(np.sqrt(2 * SNR))
    Ped_theor_up = np.ones(SNR.size) * (1 / 2**r)

    w = np.sum(codewords_bits[1:], axis=1)
    d = int(np.min(w))

    for i in range(SNR.size):
        Pe_theoretical = 0
        for j in range(d, n + 1):
            Pe_theoretical = Pe_theoretical + np.sum(w == j) * (
                Pe_bit_theor[i]**j) * ((1 - Pe_bit_theor[i])**(n - j))
        Ped_theor[i] = Pe_theoretical

    return Pe_bit, Ped, Ped_theor, Ped_theor_up, Pe_bit_theor
示例#31
0
def add_poly(x, y, mod_coeff, mod_poly):
    """
    Takes:
        x, y: the two polynoms to be multiplied.
        mod_coeff: coefficient modulus.
        mod_poly: polynomial modulus.
    Returns:
        A polynomial in Z_modulus[X]/(poly_mod).
        
    Adds the two polynoms x and y.
    """
    return np.int64(
        np.round(poly.polydiv(poly.polyadd(x, y) % mod_coeff, mod_poly)[1] % mod_coeff)
    )
        def Lagrange(self,A,B):

            from numpy import array
            from numpy.polynomial import polynomial as P
            n=len(A)
            w=(-1*A[0],1)
            for i in range(1,n):
                w=P.polymul(w,(-1*A[i],1))
            result=array([0.0 for i in range(len(w)-1)])
            derivative=P.polyder(w)
            for i in range(n):
                result+=(P.polydiv(w,(-1*A[i],1))[0]*B[i])/P.polyval(A[i],derivative)
            s=self.plot(list(result),A,B)
            return s
示例#33
0
def mul_poly(x, y, mod_coeff, mod_poly):
    """
    Takes:
        x, y: the two polynoms to be added.
        mod_coeff: coefficient modulus.
        mod_poly: polynomial modulus.
    Returns:
        A polynomial in Z_modulus[X]/(poly_mod).
        
    Multiplies the two polynoms x and y.
    """
    # It is important to explicitly typecast the sum returned as 64-bit
    return np.int64(
        np.round(poly.polydiv(poly.polymul(x, y) % mod_coeff, mod_poly)[1] % mod_coeff)
    )
示例#34
0
    def Lagrange(self, L, M):  # Lagrange function takes two lists as argument

        # L contains the list of x values
        # M contains the list of f(x) values
        # e.g.-
        #L=[1,2,3] , M=[0,-1,0]
        # i.e., f(1)=0, f(2)=-1, f(3)=0

        self.x_values = L
        self.fx_values = M
        self.polylist = []
        n = len(self.x_values)  # n=length of L, i.e., the number of points
        w = (-1 * self.x_values[0], 1)  # initialising polynomial w
        for i in range(1, n):
            w = P.polymul(w, (-1 * self.x_values[i], 1))  # calculating w
        self.result = array([0.0 for i in range(len(w) - 1)
                             ])  # initialising result array
        derivative = P.polyder(w)  # derivative of w
        for i in range(n):
            self.polylist.append(
                (P.polydiv(w,
                           (-1 * self.x_values[i], 1))[0] * self.fx_values[i])
                /
                P.polyval(self.x_values[i], derivative))  # calculating result
            self.result += self.polylist[-1]
        self.result = list(self.result)  # list of co-efficients
        self.polynomial = ""  # string to store final polynomial
        for i in range(len(self.result) - 1, 0, -1):  # building up the string
            if (self.result[i] != 0):
                if (self.result[i] > 0 and i != (len(self.result) - 1)):
                    self.polynomial += " + " + str(
                        self.result[i]) + "x^" + str(i) + " "
                elif (self.result[i] > 0 and i == (len(self.result) - 1)):
                    self.polynomial += str(
                        self.result[i]) + "x^" + str(i) + " "
                else:
                    self.polynomial += " - " + str(
                        -1 * self.result[i]) + "x^" + str(i) + " "
        if (self.result[0] != 0):
            self.polynomial += " + " + str(
                self.result[0]) if self.result[0] > 0 else " - " + str(
                    -1 * self.result[0])
        self.plot()
        return (self.polynomial)  # return result
示例#35
0
def parity(in_file, out_file):
	a=open(in_file,'r')
	base=int(a.readline())
	n=int(a.readline())
	dividend=[base-1]+[0]*(n-1)+[1]
	divisor=list(map(int, a.readline().split()))
	a.close()

	result=p.polydiv(dividend,divisor)
	q=list(map(lambda x: int(x%base),result[0]))+(n-len(result[0]))*[0]
	r=list(map(lambda x: int(x%base),result[1]))

	a=open(out_file,'w')
	if(sum(r)>0):
		a.write('NO\n')
	else:
		a.write('YES\n')
		a.write(' '.join(map(str,q))+'\n')
	a.close()
示例#36
0
def poly_mul_mod(op1, op2, modulus):
    """return multiplication of two polynomials with all coefficients of
    polynomial %q(coefficient modulus) and result polynomial % t(polynomial modulus)"""

    # For non same size polynomails we have to shift the polynomials because numpy consider right
    # side as lower order of polynomial and we consider right side as heigher order.
    if len(op1) != len(op2):
        if len(op1) > len(op2):
            op2 = op2 + [0] * (len(op1) - len(op2))
        else:
            op1 = op1 + [0] * (len(op2) - len(op1))

    poly_mod = np.array([1] + [0] * (len(op1) - 1) + [1])
    result = (poly.polydiv(
        poly.polymul(np.array(op1, dtype="object"),
                     np.array(op2, dtype="object")) % modulus,
        poly_mod,
    )[1] % modulus).tolist()
    return [round(x) for x in result]
示例#37
0
def test_returned_min_polynom(matrix, poly):
    arr_coef = poly.coef  #arr of the coef of the matrix

    #checks if the leading coef is 1
    if (arr_coef[sizeof(arr_coef) - 1] != 1):
        return false

    #if the poly does not become 0 with the matrix as x than it isnt the minimal poly
    if (mat_pol_solve(arr_coef, matrix) != 0):
        return false

    arr_mat_eigenvals = la.eig(matrix)
    arr_poly_roots = np.polyroots(poly)

    #checks if all the eigenvalues are roots of the poly and the poly has no other roots
    j = 0
    for i in len(arr_poly_roots):
        if (j >= len(arr_mat_eigenvals)):
            return false  #means that there are more roots than eigenvals
        while (j + 1 < len(arr_mat_eigenvals) and arr_mat_eigenvals[j]
               == arr_mat_eigenvals[j + 1]):  #skips the same eigenvals
            j += 1
        if (arr_mat_eigenvals[j] != arr_poly_roots[i]
            ):  # means that there is a diff between eigenvals and roots
            return false
        j += 1
    if (j < len(arr_mat_eigenvals) -
            1):  #means there are eigenvals that are not roots
        return false

    #checks if the poly is minimal
    for i in len(arr_mat_eigenvals):
        while (i + 1 < len(arr_mat_eigenvals) and arr_mat_eigenvals[i]
               == arr_mat_eigenvals[i + 1]):  #skips the same eigenvals
            i += 1
        if (mat_pol_solve(np.polydiv(arr_coef, (-arr_mat_eigenvals[i], 1)),
                          matrix) == 0):
            return false

    return true
    def _roots0(self):
        """
        Complex roots of pseudo-poly using `np.polynomial.polyroots` method,
        which finds the eigenvalues of the companion matrix of the root-finding
        poly.

        First finds common roots between `p` and `q` polynomials, then divides
        these roots from the `root_finding_poly`.

        Returns
        -------
        roots : list (of floats)
            (Complex) roots of the `root_finding_poly`
        p : tuple of floats
            Coefficients of the root finding polynomial
        dp : tuple of floats
            Coefficients of the derivative of the root finding polynomial
        """
        p  = self.root_finding_poly()
        dp = remove_zeros(pol.polyder(p))

        roots_p = pol.polyroots(self.p)
        roots_q = pol.polyroots(self.q)

        roots = []
        for root in roots_p:
            if any([ abs(rq - root) < 1E-5 for rq in roots_q ]):
                roots.append(root)

        pr    = remove_zeros(pol.polyfromroots(roots))
        p2, _ = pol.polydiv(p, pol.polymul(pr, pr))
        p2    = remove_zeros(p2)

        new_roots = list(pol.polyroots(p2))

        roots.extend(new_roots)

        return roots, p, dp
    def Lagrange(self,U,V):                                                
       
        
       
        n=len(U)                                                           
        w=(-1*U[0],1)                                                      
        for i in range(1,n):
            w=P.polymul(w,(-1*U[i],1))                                    
        result=array([0.0 for i in range(len(w)-1)])                    
        derivative=P.polyder(w)                                             
        for i in range(n):
            result+=(P.polydiv(w,(-1*U[i],1))[0]*V[i])/P.polyval(U[i],derivative)


        temp=list(result);
        cofficient=temp
        l=len(cofficient);
        temp=[];
        for i in range(l-1):
            temp.append(str(cofficient[l-(i+1)])+'x^'+str(l-(i+1))+str('+'))
        temp.append(str(cofficient[0])+'x^'+str(0));
        str1=''.join(temp)
        return(str1)   
示例#40
0
    def Lagrange(self, U, V):

        n = len(U)
        w = (-1 * U[0], 1)
        for i in range(1, n):
            w = P.polymul(w, (-1 * U[i], 1))
        result = array([0.0 for i in range(len(w) - 1)])
        derivative = P.polyder(w)
        for i in range(n):
            result += (P.polydiv(w, (-1 * U[i], 1))[0] * V[i]) / P.polyval(
                U[i], derivative)

        temp = list(result)
        cofficient = temp
        l = len(cofficient)
        temp = []
        for i in range(l - 1):
            temp.append(
                str(cofficient[l - (i + 1)]) + 'x^' + str(l - (i + 1)) +
                str('+'))
        temp.append(str(cofficient[0]) + 'x^' + str(0))
        str1 = ''.join(temp)
        return (str1)
示例#41
0
 def __mod__(self, other):
     result = polynomial.polydiv(self._poly, other._poly)[1]
     result = self._normalizePoly(result, len(self._poly))
     return Polynomial(poly=result)
示例#42
0
	# TESTING MULTIPLICATION FUNCTION	
	a=P.polymul(c1,c2).tolist()
	b=q.multPoly(c1,c2)
	if(a!=b):
		print "Failed on Case:"
		print "a * b"
		print "a",a
		print "b",b
		break
	
	# TESINGING DIVISION FUNCTION
	if q.trim(c2)==[0]:
		continue
	try:
		[a1,a2]=P.polydiv(c1,c2)
		a1=q.trim(a1.tolist())
		a2=q.trim(a2.tolist())
		[b1,b2]=q.divPoly(c1,c2)
		b1=map(float,b1)
		b2=map(float,b2)
		a1=map(lambda x: round(x,5),a1)
		a2=map(lambda x: round(x,5),a2)
		b1=map(lambda x: round(x,5),b1)
		b2=map(lambda x: round(x,5),b2)
	except:
		print "BREAKING ON EXCEPTION"
		print "Failed on Case:"
		print "C1",c1
		print "C2",c2
		print "a / b"
示例#43
0
文件: __init__.py 项目: 1950/sawbuck
def polydiv(c1, c2):
    from numpy.polynomial.polynomial import polydiv
    return polydiv(c1, c2)