Exemple #1
0
def gauss_jordan(eqs, varNames, api = False, ACCURACY = 4):
    ''' Gauss Jordan Method '''
    if len(eqs) != len(eqs[0])-1 or len(varNames) != len(eqs):
        raise Exception("Insufficient number of variables of equations.")
    var_count = len(varNames)
    M = SquareMatrix([row[:-1] for row in eqs])
    B = Matrix([[row[-1]] for row in eqs])

    # convert to lower triangular matrix
    for i in range(M.m-1):
        if M[i][i] == 0:
            found = False
            for j in range(i+1, M.m):
                if M[j][i] != 0:
                    M[j], M[i] = M[i], M[j]
                    B[j], B[i] = B[i], B[j]
                    found = True
                    break
            if not found:
                raise Exception("Cannot find a unique solution.")
        for j in range(i+1, M.m):
            factor = M[j][i]/M[i][i]
            M[j] = M[j] - (M[i]*factor)
            B[j] = B[j] - (B[i]*factor)

    # convert to diagonal matrix
    for i in range(M.m-1, -1, -1):
        if M[i][i] == 0:
            raise Exception("Cannot find a unique solution.")
        for j in range(i-1, -1, -1):
            factor = M[j][i]/M[i][i]
            M[j] = M[j] - (M[i]*factor)
            B[j] = B[j] - (B[i]*factor)
    
    result = [M.toList(), [p[0] for p in B.toList()]]
    value = [0 for _ in range(M.n)]   # solutions

    # substitue values back in the equations
    for i in range(M.m):
        value[i] = B[i][0]/M[i][i]

    for i in range(var_count):
        result.append((varNames[i], round(value[i], ACCURACY)))

    if api:
        return result
    else:
        print("Diagonal Matrix")
        mat = result[0]
        for row, c in zip(mat, result[1]):
            for elem in row:
                print("{0:.{1}f}".format(elem, ACCURACY), end = ' ')
            print("| {0:.{1}f}".format(c, ACCURACY))
        print("")
        print("Solution:")
        for name, val in result[2:]:
            print("{0} = {1:.{2}f}".format(name, val, ACCURACY))
Exemple #2
0
def matrix_inversion(eqs, varNames, api = False, ACCURACY = 4):
    ''' Matrix Inversion Method '''
    if len(eqs) != len(eqs[0])-1 or len(varNames) != len(eqs):
        raise Exception("Insufficient number of variables of equations.")
    var_count = len(varNames)
    delta_matrix = SquareMatrix([row[:-1] for row in eqs])
    delta = det(delta_matrix)

    if delta == 0:
        raise Exception("Δ = 0, Matrix Inversion failed!")

    const_matrix = Matrix([[row[-1]] for row in eqs])
    adjoint = adj(delta_matrix)
    res = (adjoint*const_matrix)*(1/delta)  # actual solving step
    adjointArray = adjoint.toList()
    resArray = [q[0] for q in res]
    result = [delta, adjointArray]
    for i in range(var_count):
        result.append((varNames[i], round(resArray[i], ACCURACY)))

    if api:
        return result
    else:
        print("Determinant = {0:.{1}f}".format(delta, ACCURACY))
        print("Adjoint = " + str(adjointArray))
        for name, value in result[2:]:
            print("{0} = {1:.{2}f}".format(name, value, ACCURACY))
Exemple #3
0
def cramer(eqs, varNames, api = False, ACCURACY = 4):
    ''' Cramer's Rule '''
    if len(eqs) != len(eqs[0])-1 or len(varNames) != len(eqs):
        raise Exception("Insufficient number of variables of equations.")
    var_count = len(varNames)
    delta_matrix = SquareMatrix([row[:-1] for row in eqs])
    delta = det(delta_matrix)

    if delta == 0:
        raise Exception("Δ = 0, Cramer's method failed!")

    result = []
    for i in range(var_count):
        local_matrix = SquareMatrix([row[:i] + [row[-1]] + row[i+1:-1] for row in eqs])
        result.append((varNames[i], round(det(local_matrix)/delta, ACCURACY)))

    if api:
        return result
    else:
        for name, value in result:
            print("{0} = {1:.{2}f}".format(name, value, ACCURACY))
def ssin(x):
    for i in range(100):
        x = sin(x)
    return x


def trivial_function(x):
    return log(exp(x))


def strange_function(x):
    return sin(x + cos(x + sin(x)))


MATRIX_SIZE = 3
A = SquareMatrix([[random() for j in range(MATRIX_SIZE)]
                  for i in range(MATRIX_SIZE)])


#A = SquareMatrix([[1, 1], [1, 0.35]])
def matrix_function(t):
    return log((A * t).exp().det())


def test(f, start=1, stop=None, N=101, tol=0.001, plot=False):
    if stop is None:
        stop = start
        start = 0
    x_range = np.linspace(start, stop, N)
    ders = [D(f)(x) for x in x_range]
    approx_ders = [approx_der(f, x) for x in x_range]
    if not np.allclose(ders, approx_ders, atol=tol) or plot:
Exemple #5
0
from permutation import Permutation

print("Задание 1.")
p1 = Permutation([4, 5, 6, 2, 3, 7, 0, 1])
p2 = Permutation([4, 1, 3, 7, 6, 5, 0, 2])
p3 = Permutation([5, 4, 0, 2, 3, 7, 6, 1])
all_permutations = Permutation.get_permutations(8, list(range(8)))
right = (p1.get_inverse_permutation() * (p2**13))**187
for permutation in all_permutations:
    p = Permutation(permutation)
    if (p * p3 * p).permutation == right.permutation:
        print("Результат:")
        print("(0 1 2 3 4 5 6 7)")
        print("(", " ".join(str(i) for i in p.permutation), ")", sep="")
print("Задание 2.")
a = SquareMatrix([[2, -2, 2, -3], [1, -3, 2, -1], [1, 1, -3, 3],
                  [-2, -3, 3, 2]])
b = SquareMatrix([[-9, 3, 9, -4], [-6, -2, 4, 9], [-9, 6, 10, -3],
                  [6, -10, 9, 6]])
c = SquareMatrix([[2, 2, 3, 1], [2, 1, 1, -2], [2, 1, -1, -1], [-1, 2, -1, 2]])
d = SquareMatrix([[-1, -1, -1, -1], [-1, -2, -2, -2], [-1, -2, -3, -1],
                  [1, 2, 3, 2]])
left = (SquareMatrix.get_e(4).multiply_on_number(
    a.compute_det() * c.compute_det()) -
        (b * c.get_adjugate_matrix() * d * c.get_adjugate_matrix()))
left = left * c * d.get_adjugate_matrix() * a
print("Определителитель матрицы, на которую домножаем = ",
      (c * d.get_adjugate_matrix() * a).compute_det())
print(left.multiply_on_number(1 / 851))
print("Задание 3.")
print("Характеристичексий многочлен:")
a = SquareMatrix(
Exemple #6
0
p1 = Permutation([4, 5, 6, 2, 3, 7, 0, 1])
p2 = Permutation([4, 1, 3, 7, 6, 5, 0, 2])
p3 = Permutation([5, 4, 0, 2, 3, 7, 6, 1])
all_permutations = Permutation.get_permutations(8, list(range(8)))
right = (p1.get_inverse_permutation() * (p2**13))**187
for permutation in all_permutations:
    p = Permutation(permutation)
    if (p * p3 * p).permutation == right.permutation:
        print("Результат:")
        print("(0 1 2 3 4 5 6 7)")
        print("(", " ".join(str(i) for i in p.permutation), ")", sep="")
print("Задание 2.")
print("Характеристичексий многочлен:")
a = SquareMatrix([
    [-3, -4, -1, 4],
    [1, -4, -3, 3],
    [-5, -2, 2, 2],
    [0, 0, 2, -2],
])
for i, a_i in enumerate(a.get_characteristic_polynomial()[:4]):
    print("(" + str(a_i) + ")x^" + str(4 - i) + " + ", end="")
print("(" + str(a.get_characteristic_polynomial()[4]) + ")")
x = SquareMatrix((a**2 + a.multiply_on_number(3) +
                  SquareMatrix.get_e(4).multiply_on_number(2)).matrix)**2
print("Определитель посчитаю на листочке из значений характеристического")
print("Задание 5")
A = Matrix([[3, -3], [1, -1], [-1, 1], [4, -4], [-3, 3]])
B = Matrix([[-2, -1, 3, 2, 1], [3, 1, -2, -1, 2]])
res = SquareMatrix((A * B).matrix)
for i, a_i in enumerate(res.get_characteristic_polynomial()[:5]):
    print("(" + str(a_i) + ")x^" + str(5 - i) + " + ", end="")
print("(" + str(res.get_characteristic_polynomial()[5]) + ")")
Exemple #7
0
 def _transition_power(self, n):
     if n == 1:
         return self.transition_matrix
     return SquareMatrix(
         Matrix.Compose([self.transition_matrix for _ in range(n)]).matrix)