python学习笔记6--fraction

上一节学习了decimal模块,这节再学习下fraction模块。

fraction模块提供有关有理数的算术表达和计算,实际上就是分数的表达和计算。python中的一个分数可以由以下几种方式构造出来:

Fraction(numerator=0, denominator=1)  :第一个参数是分子,默认为0;第二个参数为分母,默认为1。比如Fraction(2)=2;Fraction()=0。

Fraction(other_fraction) :从其他分数构造。

Fraction(float) :从float构造,表达出的分数值与float在内存中的存储值对应,可能不够精确。

Fraction(decimal) :从Decimla数构造。

Fraction(string):从string构造。

使用如下:

from fractions import *
from decimal import *

#Construct a Fraction by numerator and denominator
print (Fraction(3))      #3
print (Fraction())       #0
print (Fraction(10,8))   #5/4

#construct by other fraction
print (Fraction(5/4))    #5/4

#construct by float
print (Fraction(2.5))    #5/2
print (Fraction(1.1))    #2476979795053773/2251799813685248

#construct by decimal
print (Fraction(Decimal('2.5')))  #5/2

#construct by string
print (Fraction('12/23'))         #12/23

另外,fraction和math中还有几个关于分数操作比较常见的函数

limit_denominator(max=1000000):可以截取想要得到的分母最大值;

floor(fraction):小于该分数的最大整数;

ceil(fraction):大于该分数的最小整数;

round(fraction):各版本略有不同,没具体分析,通常是最近的整数。

#test functions
print (Fraction('3.1415926').limit_denominator(1000))  #355/113
print (floor(Fraction(355,113)))   #2
print (ceil(Fraction(355,113)))    #3
print (round(Fraction(355,113)))   #3


  • 8
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值