PYTHON Fraction 分数处理

1. 导入Fraction

from fractions import Fraction

fractions 位于python/python36/fractions.py下面,学会查看源码,并且通熟一遍。

2. Fractions 定义

class Fraction(numbers.Rational):
    """This class implements rational numbers.  实现有理数
    In the two-argument form of the constructor, Fraction(8, 6) will    
    produce a rational number equivalent to 4/3(自动约分). Both arguments must
    be Rational. The numerator defaults to 0 and the denominator
    defaults to 1 so that Fraction(3) == 3 and Fraction() == 0.  (分子默认是0,而分母默认是1)
    Fractions can also be constructed from:
      - numeric strings similar to those accepted by the
        float constructor (for example, '-2.3' or '1e10')
      - strings of the form '123/456'
      - float and Decimal instances
      - other Rational instances (including integers)

    """

具体实例运行一下,就可以看出这个函数的功能,


具体使用可以直接查看lib下面的源码,功能太多。

fractions.py里面还有一个gcd函数,这个函数在Python3.5之后就废弃了,官方建议使用math.gcd()

In [55]: gcd(2,1)
C:\Users\79432\AppData\Local\Programs\Python\Python36\Scripts\ipython:1: DeprecationWarning: fractions.gcd() is deprecated. Use math.gcd() instead.
Out[55]: 1

猜你喜欢

转载自blog.csdn.net/suzimuyu99/article/details/79872800
今日推荐