你的意思是這樣的:
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模塊可讓您與有理數工作(無轉換爲浮動)。一旦你把它們放入一個Fraction類,你可以做算術與他們(就像在小學)
像這樣:
>>> 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
的分數模塊是默認的Python發行版的一部分(自2.6) 。
要將其轉換爲浮點數,請執行float(Fraction(17,18))
例如或在Decimal類變量中使用Fraction.numerator
和Fraction().denominator
進行任意精度轉換。
像這樣:
>>> decimal.Decimal(su.numerator)/decimal.Decimal(su.denominator)
Decimal('1008.186144047968368606384293')
或:
>>> float(su.numerator)/su.denominator
1008.1861440479684
很難確定問題在這裏。可能http://docs.python.org/library/decimal.html做你想做的事情? – msw
你到底想要做什麼? –
好了,現在編輯它,希望你們這一次能理解這個問題。 – 321