Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Matrix:
- def __init__(self, a, b, c, d):
- self.a = a
- self.b = b
- self.c = c
- self.d = d
- self.det = a * d - b * c
- def isInvert(self):
- return self.det != 0
- def printMatrix(self):
- print("| {} {} |\n| {} {} |".format(self.a, self.b, self.c, self.d))
- def inverse(self):
- if not self.isInvert():
- return None
- new_a = float(self.d) / self.det
- new_b = -float(self.b) / self.det
- new_c = -float(self.c) / self.det
- new_d = float(self.a) / self.det
- return Matrix(new_a, new_b, new_c, new_d)
- @staticmethod
- def __quadratic_solver(a, b, c):
- import math
- d = pow(b, 2) - 4 * a * c
- if d < 0:
- return []
- elif not d:
- return [(- b + math.sqrt(d)) / (2 * a)]
- return [(-b + math.sqrt(d)) / (2 * a), (-b - math.sqrt(d)) / (2 * a)]
- def eigenvalue(self):
- return self.__quadratic_solver(1, -(self.a + self.d), self.det)
- # Make matrix printable so that we can call print(matrix) instead of matrix.printMatrix()
- def __str__(self):
- return "| {} {} |\n| {} {} |".format(self.a, self.b, self.c, self.d)
- # Allows us to add to matrices with the "+" operator
- def __add__(self, other):
- return Matrix(self.a + other.a, self.b + other.b, self.c + other.c, self.d + other.d)
- # Allows us to subtract to matrices with the "-" operator
- def __sub__(self, other):
- return Matrix(self.a - other.a, self.b - other.b, self.c - other.c, self.d - other.d)
- # The matrix can now have a negativ sign. This is the same as multiplying with -1
- def __neg__(self):
- return -1 * self
- # Allows us to multiply a matrix with a constant or another matrix with the "*" operator
- def __mul__(self, other):
- if isinstance(other, int) or isinstance(other, float):
- return Matrix(other * self.a, other * self.b, other * self.c, other * self.d)
- new_a = self.a * other.a + self.b * other.c
- new_b = self.a * other.b + self.b * other.d
- new_c = self.c * other.a + self.d * other.c
- new_d = self.c * other.b + self.d * other.d
- return Matrix(new_a, new_b, new_c, new_d)
- # Without this "constant * matrix" would throw an exception, while "matrix * constant" would not
- __rmul__ = __mul__
- class Matrix:
- def __init__(self, a, b, c, d):
- self.a = float(a)
- self.b = float(b)
- self.c = float(c)
- self.d = float(d)
- self.determinant = (a * d) - (b * c)
- def isInvert(self):
- return self.determinant != 0
- def printMatrix(self):
- print(str.format("| {} {} |", self.a, self.b))
- print(str.format("| {} {} |", self.c, self.d))
- def inverse(self):
- if not self.isInvert():
- return None
- return Matrix(self.d / self.determinant,
- -self.b / self.determinant,
- -self.c / self.determinant,
- self.a / self.determinant)
- #!/usr/bin/python3
- # Design a class called Matrix() that accepts four parameters to create a 2x2
- # matrix. This class should have five member variables: the four numerical
- # entries and also its determinant.
- class Matrix(object):
- def __init__(self, values):
- self.a = float(values[0])
- self.b = float(values[1])
- self.c = float(values[2])
- self.d = float(values[3])
- # This won't change if you change one of the values after creation.
- self.determinant = (self.a * self.d - self.b * self.c)
- def is_invertable(self):
- return self.determinant != 0
- def print_matrix(self):
- print("| {0} {1} |\n| {2} {3} |".format(self.a, self.b, self.c, self.d))
- def inverse(self):
- if self.is_invertable():
- inverted = []
- def invert(x):
- return x / self.determinant
- inverted = [invert(x) for x in [self.d, -self.b, -self.c, self.a]]
- return Matrix(inverted)
- else:
- return None
- if __name__ == "__main__":
- example = Matrix([1.0, 2.0, 3.0, 4.0])
- print(example.determinant)
- print(example.is_invertable())
- inverted = example.inverse()
- inverted.print_matrix()
- example.print_matrix()
- class Matrix:
- def __init__(self, *args, **kwargs):
- if not all(map(lambda n: isinstance(n, float), args)):
- raise TypeError("All arguments must be of type float")
- elif len(args) != 4:
- raise NotImplementedError("Support for 2x2 matrix only")
- self.a, self.b, self.c, self.d = args
- self.determinant = self.a * self.d - self.b * self.c
- def __str__(self):
- max_length = max(len(str(v)) for k, v in self.__dict__.items() if k != 'determinant')
- return "| {a:>{max_length}} {b:>{max_length}} |\n| {c:>{max_length}} {d:>{max_length}} |".format(max_length=max_length, **self.__dict__)
- def is_invert(self):
- return bool(self.determinant)
- def inverse(self):
- if self.is_invert():
- return Matrix(self.d / self.determinant,
- self.b * -1 / self.determinant,
- self.c * -1 / self.determinant,
- self.a / self.determinant)
- else:
- return "Can't invert an uninvertible matrix."
- matrix = Matrix(1.0, 2.0, 3.0, 4.0)
- print("determinant:", matrix.determinant)
- print("matrix is invertible:", matrix.is_invert())
- print("matrix")
- print(matrix)
- print("inverse matrix")
- print(matrix.inverse())
- # over all documentation is a bit incomplete since I'm pretty bad with the
- # matrix topic.
- class Matrix:
- """
- Create simple 2x2 matrixs with each instance.
- attributes:
- a (float) point a of the matrix.
- b (float) point b of the matrix.
- c (float) point c of the matrix.
- d (float) point d of the matrix.
- determinant determinant of the matrix.
- """
- def __init__(self, a, b, c, d):
- """
- called when creating new instance of the Matrix class. Accepts int and
- float input. All input is converted to float.
- args:
- a (int/float) point a of the matrix.
- b (int/float) point b of the matrix.
- c (int/float) point c of the matrix.
- d (int/float) point d of the matrix.
- rasies:
- TypeError All inputs need to be ints or floats.
- """
- self.a = float(a)
- self.b = float(b)
- self.c = float(c)
- self.d = float(d)
- self.determinant = (a * d) - (b * c)
- def print_matrix(self):
- """
- Prints out representation of the the matrix.
- """
- print("| {} {} |\n| {} {} |".format(self.a, self.b, self.c, self.d))
- def is_invert(self):
- """
- Returns if the matrix is invertible.
- return:
- bool True if matrix is invertible and False otherwise.
- """
- return self.determinant != 0
- def inverse(self):
- """
- Creates a inverted matrix.
- return:
- Matrix Returns new instance of the Matrix class if invertible.
- None Returns None if not invertible.
- """
- if self.is_invert:
- a = self.d / self.determinant
- b = self.b / self.determinant * -1
- c = self.c / self.determinant * -1
- d = self.a / self.determinant
- return Matrix(a, b, c, d)
- else:
- return None
- if __name__ == '__main__':
- new_matrix = Matrix(1, 2, 3, 4)
- new_matrix.print_matrix()
- print(new_matrix.determinant)
- print(new_matrix.is_invert())
- matrix2 = new_matrix.inverse()
- matrix2.print_matrix()
- print(new_matrix == matrix2)
- import numbers
- """Matrix class
- By: TheFueley (Renegade_Pythons)
- """
- class Matrix:
- """creates Matrix object
- Args: a, b, c, d
- Raises: ValueError if a,b,c, or d are not numbers
- """
- def __init__(self, a, b, c, d):
- if not isinstance(a, numbers.Real):
- raise ValueError("Not a digit '{}'".format(a))
- elif not isinstance(b, numbers.Real):
- raise ValueError("Not a digit '{}'".format(b))
- elif not isinstance(c, numbers.Real):
- raise ValueError("Not a digit '{}'".format(c))
- elif not isinstance(d, numbers.Real):
- raise ValueError("Not a digit '{}'".format(d))
- else:
- self._a = a
- self._b = b
- self._c = c
- self._d = d
- self.deter = self._findDeter()
- def isInvert(self):
- """Checks if matrix is invertible
- Returns: True if invertible, false otherwise
- """
- if self._findDeter() == 0:
- return False
- else:
- return True
- def printMatrix(self):
- """Prints values of matrix
- """
- print("| " + str(self._a) + " " + str(self._b) + " |")
- print("| " + str(self._c) + " " + str(self._d) + " |")
- def inverse(self):
- """inverts the matrix
- Returns: a new matrix, inverted from one that was supplied
- """
- if self.isInvert():
- a = self._a / self.deter
- b = self._b / self.deter * -1
- c = self._c / self.deter * -1
- d = self._d / self.deter
- return Matrix(d, b, c, a)
- else:
- return None
- def _findDeter(self):
- """find's the determinant of the matrix
- Returns: determinant
- """
- return (self._a * self._d) - (self._b * self._c)
- class Matrix():
- def __init__(self, a, b, c, d):
- self.a = a
- self.b = b
- self.c = c
- self.d = d
- Matrix.determinant = (a*d) - (b*c)
- def isInvert(self):
- return Matrix.determinant != 0
- def printMatrix(self):
- print('| %F %F |' % (self.a, self.b))
- print('| %F %F |' % (self.c, self.d))
- def inverse(self):
- if Matrix.isInvert(self) is True:
- return Matrix((self.d / Matrix.determinant),
- (-self.b / Matrix.determinant),
- (-self.c / Matrix.determinant),
- (self.a / Matrix.determinant))
- elif Matrix.isInvert(self) is False:
- print("Wrong, not invertible.")
- # elcrawfodor
- class Matrix():
- """
- creates a 2 x 2 matrix with entries
- a b
- c d
- """
- def __init__(self, a, b, c, d):
- self.a = float(a)
- self.b = float(b)
- self.c = float(c)
- self.d = float(d)
- self.determinant = float(a*d) - float(b*c)
- def isInvert(self):
- """
- checks to see if matrix is invertible
- :return: Boolean
- """
- return self.determinant != 0
- def printMatrix(self):
- """
- prints out the matrix with format
- | a b |
- | c d |
- """
- print("| {} {} |".format(self.a, self.b))
- print("| {} {} |".format(self.c, self.d))
- def inverse(self):
- """
- if invertible, returns the inverse matrix; else returns None
- """
- if self.isInvert():
- a_invert = self.d / self.determinant
- b_invert = (self.b * -1) / self.determinant
- c_invert = (self.c * -1) / self.determinant
- d_invert = self.a / self.determinant
- return Matrix(a_invert, b_invert, c_invert, d_invert)
- else:
- return None
- def eigenvalue(self):
- """
- if real e-values exist, returns them as a tuple with two floats; else returns a tuple with 2 ComplexNum objects;
- the formulas came from plugging parts of the characteristic equation of 2x2 matrix into the quadratic formula
- """
- import math
- d = (self.a ** 2) - (2*self.a*self.d) + (4*self.b*self.c) + (self.d ** 2)
- if d < 0:
- # returns complex roots as tuple of ComplexNum objects
- d= math.sqrt(-1 * d)
- eigen1 = ComplexNum((self.a + self.d) / 2,
- d / 2)
- eigen2 = ComplexNum((self.a + self.d) / 2,
- d / -2)
- return eigen1, eigen2
- else:
- # returns real roots as tuple of floats
- d = math.sqrt(d)
- eigen1 = 0.5*((self.a + self.d) + d)
- eigen2 = 0.5*((self.a + self.d) - d)
- return eigen1, eigen2
- def __add__(self, other):
- return Matrix(self.a + other.a,
- self.b + other.b,
- self.c + other.c,
- self.d + other.d)
- def __sub__(self, other):
- return Matrix(self.a - other.a,
- self.b - other.b,
- self.c - other.c,
- self.d - other.d)
- def __mul__(self, other):
- return Matrix(self.a * other.a + self.b * other.c,
- self.a * other.b + self.b * other.d,
- self.c * other.a + self.d * other.c,
- self.c * other.b + self.d * other.d)
- def __str__(self):
- """
- prints out the matrix with format
- | a b |
- | c d |
- """
- return "| {} {} |\n| {} {} |".format(self.a, self.b, self.c, self.d)
- class ComplexNum():
- """
- creates a complex number of the form a + bi, where i represents sqrt(-1)
- """
- def __init__(self, a, b):
- self.a = float(a)
- self.b = float(b)
- def __add__(self, other):
- return ComplexNum(self.a + other.a,
- self.b + other.b)
- def __sub__(self, other):
- return ComplexNum(self.a - other.a,
- self.b - other.b)
- def __mul__(self, other):
- return ComplexNum(self.a * other.a - self.b * other.b,
- self.a * other.b + self.b * other.a)
- def __str__(self):
- return "{} + {}i".format(self.a, self.b)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement