PYTHON Fraction 分数处理

本文介绍了Python中的Fraction类,用于处理有理数。Fraction类允许从字符串、浮点数、Decimal实例等创建分数,并自动进行约分。示例中展示了如何创建和使用Fraction,以及关于gcd函数的弃用提示,建议使用math.gcd()替代。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)

    &#

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值