你的意思是这样的:
from fractions import Fraction
import decimal
decimal.getcontext().prec = 50
fractions = [(1,7), (2,3), (22,7), (7001,7), (9,3), (611951,611953), (1,11),(1,7689585)]
su=Fraction(0)
for i, t in enumerate(fractions,1):
f=Fraction(*t)
su+=Fraction(*t)
d=decimal.Decimal(f.numerator) / decimal.Decimal(f.denominator)
print '{} becomes {}'.format(t,f)
print '\tfloat of that is: {}'.format(float(f))
print '\tDecimal: {}'.format(d)
print '\t{} elements cum sum of the list: {}\n'.format(i,su)
印刷:
(1, 7) becomes 1/7
float of that is: 0.142857142857
Decimal: 0.14285714285714285714285714285714285714285714285714
1 elements cum sum of the list: 1/7
(2, 3) becomes 2/3
float of that is: 0.666666666667
Decimal: 0.66666666666666666666666666666666666666666666666667
2 elements cum sum of the list: 17/21
(22, 7) becomes 22/7
float of that is: 3.14285714286
Decimal: 3.1428571428571428571428571428571428571428571428571
3 elements cum sum of the list: 83/21
(7001, 7) becomes 7001/7
float of that is: 1000.14285714
Decimal: 1000.1428571428571428571428571428571428571428571429
4 elements cum sum of the list: 21086/21
(9, 3) becomes 3
float of that is: 3.0
Decimal: 3
5 elements cum sum of the list: 21149/21
(611951, 611953) becomes 611951/611953
float of that is: 0.999996731775
Decimal: 0.99999673177515266695318104494953043779505942449829
6 elements cum sum of the list: 12955044968/12851013
(1, 11) becomes 1/11
float of that is: 0.0909090909091
Decimal: 0.090909090909090909090909090909090909090909090909091
7 elements cum sum of the list: 142518345661/141361143
(1, 7689585) becomes 1/7689585
float of that is: 1.30046029792e-07
Decimal: 1.3004602979224496510539905599586973809379829990825E-7
8 elements cum sum of the list: 121767437017889092/120778724977295
分数模块允许您使用有理数(无需转换为浮点数)。一旦你把它们放到分数课上,你就可以用它们做算术(就像在小学里一样)
像这样:
>>> Fraction(1,3) + Fraction(3,4)
Fraction(13, 12)
>>> Fraction(1,3) + Fraction(1,6)
Fraction(1, 2)
>>> Fraction(1,2).numerator
1
>>> Fraction(1,2).denominator
2
Fraction 模块是默认 Python 发行版的一部分(自 2.6 起)。
要将其转换为浮点数,float(Fraction(17,18))
例如或在 Decimal 类变量中使用Fraction.numerator
andFraction().denominator
进行任意精度转换。
像这样:
>>> decimal.Decimal(su.numerator) / decimal.Decimal(su.denominator)
Decimal('1008.186144047968368606384293')
或者:
>>> float(su.numerator) / su.denominator
1008.1861440479684