matrix - How to represent fractions in python -


i trying implement method takes matrix matrix class i've defined , returns triagonal matrix using gaussian elimination. consider following matrix:

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

basically need add each row, multiple of previous row, until end matrix has 0 in places below main diagonal. following process, should have following matrix:

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

the problem fractions 1/3 come , wouldn't want lose precision using floats. there way represent fractions? have define special behaviour those? sake of doing myself don't want use external modules.

there class want: fractions.fraction:

>>> fractions import fraction >>> print(fraction(5, 6)) 5/6 

fractions behave regular numbers in 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 fraction gets converted float if other operand float. makes sense, since not expect float of undetermined precision converted fraction.


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -