def matrix_invert(matrix):
    """    Функция считает обратную матрицу.

    Функция принимает в качестве аргумента матрицу в виде списка списков, вызовом функции
    matmin получает матрицу миноров. Затем транспонирует ее, одновременно считая каждый элемент,
    умноженный на обратный определитель."""
    degenerate = False
    try:
        if determinant(matrix) != 0:
            trans = []
            M = matmin(matrix)
            for j in range(len(M[0])):
                t = []
                for i in range(len(M)):
                    if (i + j) % 2 != 0:
                        t = t + [-M[i][j] / determinant(matrix)]
                    else:
                        t = t + [M[i][j] / determinant(matrix)]

                trans = trans + [t]
            return trans
        else:
            degenerate = True
    except:
        raise ValueError('Incorrect dimensions')
    else:
        if degenerate:
            raise ValueError('Matrix cannot be inverted as it is degenerate')
示例#2
0
def traditional_matrix_inverse(A):
    delta = determinant(A)
    shape = np.shape(A)
    adj = np.zeros_like(A)
    for i in range(shape[0]):
        for j in range(shape[1]):
            adj[i][j] = (-1.)**(i + j) * determinant(cofactor(A, i, j))
    adj = adj.T
    inv = np.power(delta, -1) * adj
    return inv
def matmin(matrix):
    """    Функция определяет матрицу миноров.

    Функция принимает в качестве аргумента квадратную матрицу. Для каждого элемента
    матрицы функция считает его миноры путем вызова функции minorize,
    тем самым вычеркивая строку и стобец, в котором стоит элемент, а затем от этой функции
    вызывается функция determinant, которая считает определитель полученного выражения.
    Таким образом, получается матрица миноров."""
    try:
        ma = []
        for i in range(len(matrix)):
            ma.append([])
            for j in range(len(matrix)):
                ma[i].append(0)

        if len(matrix) == 1:
            return matrix[0][0]

        for i in range(len(matrix[0])):
            for j in range(len(matrix[0])):
                ma[i][j] = determinant(minorize(matrix, i, j))

        return ma
    except:
        raise ValueError('Incorrect dimensions')
示例#4
0
def compute_birkhoff_coefficients_and_polynomials(
        degree_of_function, determinant_of_original_matrix, field_size,
        function_dict, matrix, person_ids, print_statements, vector_of_shares):
    for i, share in enumerate(vector_of_shares):
        # calculate birkhoff interpolation coefficient
        birkhoff_coefficient = (int(share) * (-1)**i * divide(
            (determinant(get_minor(matrix, i, 0), field_size)) % field_size,
            determinant_of_original_matrix, field_size)) % field_size
        # generate a function with the coefficient as scalar
        function_dict[person_ids[i]] = generate_function(
            degree_of_function, birkhoff_coefficient, field_size)
        if print_statements or debug:
            print("Birkhoff Coefficient a_{}_0:".format(i + 1),
                  birkhoff_coefficient, "=", share, "*(-1)**", i, "*",
                  (determinant(get_minor(matrix, i, 0), field_size)) %
                  field_size, '/', determinant_of_original_matrix)
示例#5
0
def matching(np_T, n, err):
    E = np_T
    if abs(determinant(deepcopy(np_T),n,err)) < err:
        print "NUMPY - ZERO DET"
        return []

    excl = set()
    C_T = augment(np_T, n)
    M = []

    while len(M) < n/2:
        N = inverse(deepcopy(C_T), n, excl, excl, err)
        first_row = None
        for row in xrange(0, n):
            if not row in excl:
                first_row = row
                break

        j_col = None
        for col in xrange(n,2*n):
            if not (col-n) in excl and abs(N[first_row][col]) > err and E[first_row][col-n]!= 0:
                j_col = col - n
                break

        e = (first_row, j_col)
        M.append(e)

        excl.add(first_row)
        excl.add(j_col)

    return M
示例#6
0
def invert(matrix, steps=False):
    if not square(matrix):
        print("Matrix is not square.")
    elif determinant(matrix) == 0:
        print("Determinant of matrix is 0. Not invertible.")
    else:
        new_matrix = matrix[:]
        matrix_columns = columns(new_matrix)
        augmented = append_identity(new_matrix)
        full_matrix = reducer_invert(augmented)
        returned_matrix = remove_original(full_matrix, matrix_columns)
        readable_matrix(returned_matrix)
        return returned_matrix
示例#7
0
 def test2(self):
     m = [ [1,3], [2,5] ]
     self.assertEqual(determinant(m), -1)
示例#8
0
 def test1(self):
     m = [ [1] ]
     self.assertEqual(determinant(m), 1)
示例#9
0
 def test3(self):
     m = [ [2,5,3], [1,-2,-1], [1,3,4] ]
     self.assertEqual(determinant(m), -20)
示例#10
0
文件: CAS.py 项目: mridulv/CAS
    def answer(self,event):
        f=open("data.txt",'w')
        t1=self.tc.GetValue()
        t2=self.tc2.GetValue()
        self.imp.Append(t1)
        f.write(t1+'\n')
        self.imp.Append(t2)
        f.write(t2+'\n')
        print self.k
        if self.k<=5 and self.k>=0:                                                          # matrices (part 1)
            text=self.tc.GetValue()
            print(text)
            a=self.conv(text)
            text2=self.tc2.GetValue()
            print(text2)
            b=self.conv(text2)
            if self.k==0:
              try:
                    ans=matrix(a)+matrix(b)
                    ans=str(ans)
                    self.text12.SetValue(ans)
              except:
                ans='Either of the matrix is not given in the correct format' 
                self.text12.SetValue(ans)
            if self.k==1:
              try:
                ans=matrix(a)-matrix(b)
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='Either of the matrix is not given in the correct format' 
                self.text12.SetValue(ans)
            if self.k==2:
              try:
                ans=dot(matrix(a),matrix(b))
                ans=str(ans)                                         
                self.text12.SetValue(ans)
              except:
                ans='Either of the matrix is not given in the correct format' 
                self.text12.SetValue(ans)
            if self.k==3:
              try:
               if determinant.determinant(a)!=0:   
                v=matrix(a).I
                ans=dot(v,matrix(b))
                ans=str(ans)
                self.text12.SetValue(ans)
               elif determinant.determinant(a)==0:
                ans='Given an invertible matrix'
                self.text12.SetValue(ans)  
              except:
                ans='Either of the matrix is not given in the correct format' 
                self.text12.SetValue(ans)  
            if self.k==4:
              try:  
               if determinant.determinant(a)!=0:
                ans=matrix(a).I
                ans=str(ans)
                self.text12.SetValue(ans)
               elif determinant.determinant(a)==0:
                ans='The matrix is not invertible'
                self.text12.SetValue(ans)
              except:
                ans='The matrix is not given inthe correct format'
                self.text12.SetValue(ans)  
            if self.k==5:
               try: 
                c=determinant.determinant(a)
                ans=str(c)
                self.text12.SetValue(ans)
               except:
                ans='The matrix given is not in the correct format'
                self.text12.SetValue(ans)
                
        if self.k>5 and self.k<=14 :
            self.text2.SetLabel('')
            text=self.tc.GetValue()                                                # matrices (part 2)
            print(text)
            a=self.conv(text)
            if self.k==6:
              try:
                a=matrix(a)
                m=rank(a)
                m=str(m)
                self.text12.SetValue(m)
              except:
                m='The given input is not in the correct format'
                self.text12.SetValue(m)
            if self.k==7:
              try:
                c=matrix(a)
                ans=gauss.test(c,len(a))
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not in the correct format'
                self.text12.SetValue(ans)
            if self.k==8:
              try:
                l,u,d=ludecomposition.test(a)
                ans='l is ',l,'u is',u,'and d is',d
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not in the correct format'
                self.text12.SetValue(ans)
            if self.k==9:
              try:
                ans=matrix(a).T
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not in the correct format'
                self.text12.SetValue(ans)  
            if self.k==10:
              try:
                a=matrix(a)
                ans1,ans2=qr_decomposition.test(text)
                ans='Q is ',ans1,'R is ',ans2,'in QR decomposition'
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
            if self.k==11:
              try:
                ans=qr_decomposition2.test(text)
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)  
            if self.k==12:
              try:
                ans=eigen.test(text)
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is incorrect'
                self.text12.SetValue(ans)

        if self.k>=16 and self.k<20:                                            # differential calculus
            text2=self.tc2.GetValue()
            text=self.tc.GetValue()
            if self.k==16:
              try:
                b=self.conv(text2)
                print b[0],b[1]
                ans=symbolic.differentiate(text,float(b[0]),int(b[1]))
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='please check the input that you have given'
                self.text12.SetValue(ans)
            if self.k==17:
              try:
                ans=symbolic.CallDiff(text,text2)
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
            if self.k==18:
              try:
                b=self.conv(text2)
                ans=symbolic.dirDeriv(text,b[0],b[1])
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
            if self.k==19:
              try:
                ans=symbolic.Laplacian(text)
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
                
        if self.k>=21 and self.k<=25:                                                    # polynomials
            text=self.tc.GetValue()
            text2=self.tc2.GetValue()
            Poly=Polynomial()
            if self.k==21:
              try:
                ans=Poly.addPolynomial(text,text2)
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
            if self.k==22:
              try:
                ans=Poly.subtractPolynomial(text,text2)
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
            if self.k==23:
              try:
                ans=Poly.MultiplyPolynomial(text,text2)
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
            if self.k==24:
              try:
                ans=Poly.dividePolynomial(text,text2)
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
            if self.k==25:
              try:
                self.tc2.SetValue('')
                ans=rootpoly(text)
                ans=str(ans)                                                           # karna hain
                self.text12.SetValue(ans)
              except:
                ans='he choice not selected'
                self.text12.SetValue(ans)
        if self.k>=27 and self.k<=30:                                                    # integral calculus
            text=self.tc.GetValue()
            text2=self.tc2.GetValue()                                               
            print(text2)

            if self.k==27:
              try:
                b=self.conv(text2)
                lower=[None]*len(b)
                upper=[None]*len(b)
                ans=symbolic.integrate(text,b[0],b[1])
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
            if self.k==28:
              try:
                b=self.conv3(text2)
                print 'mridul',b
                lower=[None]*len(b)
                upper=[None]*len(b)
                for i in range(len(b)):
                    lower[i]=b[i][0]
                    upper[i]=b[i][1]
                print 'mridul',lower,upper
                ans=symbolic.multiDimensionInteg(text,len(b),lower,upper)
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
            if self.k==29:
              try:
                b=self.conv(text2)
                lower=[None]*len(b)
                upper=[None]*len(b)
                if len(b)==6:
                    ans=diffeqn.solveDiffEqn4(text,b[:len(b)-2],b[len(b)-2],b[len(b)-1])                        # the first element b[len(b)-1] is the point where the f(x) has to be calculated  and the rest are the initial conditions
                if len(b)==5:
                    ans=diffeqn.solveDiffEqn3(text,b[:len(b)-2],b[len(b)-2],b[len(b)-1])
                if len(b)==4:
                    ans=diffeqn.solveDiffEqn2(text,b[:len(b)-2],b[len(b)-2],b[len(b)-1])                        # the first element b[0] is the point where the f(x) has to be calculated  and the rest are the initial conditions
                if len(b)==3:
                    ans=diffeqn.solveDiffEqn1(text,b[:len(b)-2],b[len(b)-2],b[len(b)-1])
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not in not in the standard format demanded by CAS'
                self.text12.SetValue(ans)
            if self.k==30:
              try:
                b=self.conv3(text2)
                lower=[None]*len(b)
                upper=[None]*len(b)
                print b
                ans=diffeqn.LaplaceEqn(text,b[0],b[2],b[1],b[3])                                        
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
        if self.k>=37 and self.k<=44:                                             # statistics the data points  
            text=self.tc.GetValue()
            print(text)
            b=self.conv(text)
            lower=[None]*len(b)
            middle=[None]*len(b)
            upper=[None]*len(b)
            if self.k==37:
              try:
                text2=self.tc2.GetValue()
                for i in range(len(b)):
                    lower[i]=b[i][0]
                    upper[i]=b[i][1]
                ans=regression.LeastSquare(int(text2),lower,upper)
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct format'
                self.text12.SetValue(ans)
            if self.k==38:
              try:
                for i in range(len(b)):
                    lower[i]=b[i][0]
                    middle[i]=b[i][1]
                    upper[i]=b[i][2]
                ans=regression.PlaneFit(lower,middle,upper)
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
            if self.k==39:
              try:
                for i in range(len(b)):
                    lower[i]=b[i][0]
                    upper[i]=b[i][1]
                ans=regression.ExponentialCurve(lower,upper)
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
            if self.k==40:
              try:
                for i in range(len(b)):
                    lower[i]=b[i][0]
                    upper[i]=b[i][1]
                ans=regression.LogarithmicCurve(lower,upper)
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
            if self.k==41:
              try:
                ans=regression.SplineInterpolation(b)
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
            if self.k==42:
              try:
                for i in range(len(b)):
                    lower[i]=b[i][0]
                    upper[i]=b[i][1]
                ans=regression.SpearsmanCoff(lower,upper)
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
            if self.k==43:
              try:
                for i in range(len(b)):
                    lower[i]=b[i][0]
                    upper[i]=b[i][1]
                ans=regression.Pearson(lower,upper)
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
            if self.k==44:
              try:
                ans=regression.tau(b)
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)  
        if self.k>=32 and self.k<=36:                                        # playing with Fourier
             text=self.tc.GetValue()
             print (text)
             if self.k==32:
              try:
                text2=self.tc2.GetValue()
                b=self.conv(text2)
                ans=SinCoeff(text,b[0],b[1],b[2])
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
             if self.k==33:
              try:
                text2=self.tc2.GetValue()
                b=self.conv(text2)
                ans=CosCoeff(text,b[0],b[1],b[2])
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
             if self.k==34:
              try:
                text2=self.tc2.GetValue()
                b=self.conv(text2)
                ans=FourierCoeff(text,b[0],b[1],b[2])
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
             if self.k==35:
              try:
                b=self.conv2(text)
                ans=discreteFourier(b,len(b))
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
             if self.k==36:
              try:
                b=self.conv2(text)
                ans=inverseVal(b,len(b))
                ans=str(ans)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
                
        if self.k>=46 and self.k<=47:                                        # optimization
             text=self.tc.GetValue()
             print (text)
             text2=self.tc2.GetValue()
             b=self.conv(text2)
             lower=[None]*len(b)
             upper=[None]*len(b)
             for i in range(len(b)):
                    lower[i]=b[i][0]
                    upper[i]=b[i][1]
             if self.k==46:
              try:
                m=symbolic.Max(text,len(b),lower,upper)
                ans=str(m)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
             if self.k==47:
              try:
                m=symbolic.Min(text,len(b),lower,upper)
                ans=str(m)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
                

        if self.k>=49:                                                      #evaluating expression
            text=self.tc.GetValue()
            print (text)
            text2=self.tc2.GetValue()
            b=self.conv(text2)
            if self.k==49:
              try:
                m=symbolic.roots_interval(text,b[0],b[1])
                ans=str(m)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
            if self.k==50:
              try:
                m=symbolic.EqnSolver(text,b[0],b[1])
                ans=str(m)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
            if self.k==51:
              try:
                m=extract.main(text,b)
                ans=str(m)
                self.text12.SetValue(ans)
              except:
                ans='The given input is not correct'
                self.text12.SetValue(ans)
        t3=self.text12.GetValue()
        self.imp.Append(t3)
        f.write(t3+'\n')
        f.close()
示例#11
0
 def det(self):
     import determinant
     return determinant.determinant(self.matrix)
 def test_multi(self):
     a = [[1, 2], [4, 5]]
     b = determinant(a)
     self.assertEqual(b, -3)
 def test_rectangle(self):
     e = [[1, 2, 3], [4, 5, 6]]
     with self.assertRaises(Exception) as e:
         determinant(e)
 def test_3by3(self):
     c = [[1,2,3],[4,5,6],[7,8,9]]
     d = determinant(c)
     self.assertEqual(d, 0)
示例#15
0
from gauss_elim import gauss_elim
from gauss_jordan import gauss_jordan
from gauss_nonlin import gauss_nonlin
from gauss_seidel import gauss_seidel
from inv_lu import inv_lu
from lu_decomp import lu_decomp
from matinv import matinv
from mmult import mmult
from tpose import tpose

if __name__ == '__main__':
    #Problem 1 (Solution: x = 68/69 = 0.98550724637, y = 101/69 = 1.46376811594, z = 21/23 = 0.91304347826)
    print("Problem 1: Solve a system of equations!")
    prob_1_system = [[0, -3, 7], [1, 2, -1], [5, -2, 0]]
    prob_1_rhs = [2, 3, 2]
    deter = determinant(prob_1_system)
    print("a)\tThe determinant of this system is:" + str(deter))
    cramer_sol = []
    for i in range(len(prob_1_rhs)):
        numerator_matrix = []
        for j in range(len(prob_1_system)):
            numerator_matrix.append([])
            for k in range(len(prob_1_system[0])):
                if i == k:
                    numerator_matrix[j].append(prob_1_rhs[j])
                else:
                    numerator_matrix[j].append(prob_1_system[j][k])
        cramer_sol.append(determinant(numerator_matrix)/deter)
    print("b)\tSolved using Cramer's rule: "+str(cramer_sol))
    print("c)\tSolved using Gauss Elimination: "+str(gauss_elim(prob_1_system, prob_1_rhs, 1e-6)))
    print("d)\tSolved using Gauss Jordan: "+str(gauss_jordan(prob_1_system, prob_1_rhs, 1e-6)))