Search code examples
pythonmatrixfractions

How to represent fractions in python


I am trying to implement a method that takes a matrix from the matrix class i've defined and returns a triagonal matrix using gaussian elimination. Consider the following matrix:

m1 = [[2, -3, -4],
      [-1, 4, 5],
      [1, -3, -4]]

Basically i need to add to each row, a multiple of another previous row, until i end up with a matrix which has 0 in all places below the main diagonal. Following this process, i should have the following matrix:

m2 = [[2, -3, -4],
      [0, 5/2, 3],
      [0, 0, -1/5]]

The problem is that fractions like 1/3 will often come up and i wouldn't want to lose precision by using floats. So is there any way to represent fractions? Will i have to define special behaviour for those? For the sake of doing it by myself i don't want to use any external modules.


Solution

  • There is a class that does exactly what you want: fractions.Fraction:

    >>> from fractions import Fraction
    >>> print(Fraction(5, 6))
    5/6
    

    Fractions behave like regular numbers in most situations:

    >>> print(Fraction(5, 6) + 6)
    41/6
    >>> print(Fraction(5, 6) + Fraction(1, 2))
    4/3
    >>> print(Fraction(5, 6) + 17.445)
    18.278333333333332
    

    The last example shows that the fraction gets converted to a float if the other operand is a float. This makes sense, since you would not expect a float of undetermined precision to be converted to a Fraction.