python中Fraction()方法的用法介绍

本文介绍了一种将分数字符串转换为浮点型小数的方法,通过使用Fraction类实现有理数运算,再将结果转换为浮点数。具体实现涉及字符串处理、有理数运算及类型转换。

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

小编是想将字符串的分数,转换为浮点型的小数才接触到这个方法的。

源码如下:

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.

    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)

    """

这个类实现有理数。

在构造函数的双参数形式中,分数(8,6)将得到一个有理数,等于4/3。两种观点都必须是理性的。分子默认为0,分母默认为0

默认为1,所以Fraction(3)= 3,Fraction()= 0。

分数也可以由:

-数字字符串浮动构造函数(例如,'-2.3'或'1e10')

-“123/456”格式的字符串

-浮点和十进制实例

-其他Rational实例(包括整数)

具体实现将分数字符串转换为浮点型小数的实例代码如下:

import fractions

a = "3/4"

b = float(sum(fractions.Fraction(x) for x in a.split()))

print(type(b))
print(b)

打印结果为:

<class 'float'>
0.75
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值