简体   繁体   English

如何在python中表示分数

[英]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. 基本上,我需要向每一行添加另一行的倍数,直到我最终得到一个矩阵,该矩阵在主对角线以下的所有位置都具有0。 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. 问题在于,像1/3这样的分数经常会出现,我不想使用浮点数来失去精度。 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. 为了自己完成此操作,我不想使用任何外部模块。

There is a class that does exactly what you want: fractions.Fraction : 有一个类可以完全满足您的需求: 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 . 最后一个例子示出了分数被转换到一个float如果另一个操作数是一个float This makes sense, since you would not expect a float of undetermined precision to be converted to a Fraction . 这是有道理的,因为您不希望将精度不确定的浮点数转换为Fraction

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM