What I need to do is use integer arithmetic to convert fractions into floating point numbers. The number of decimal places needed is specified as a variable DECIMALS. Each fraction is contained in a tuple of integers, for example (1, 3). The first item is the numerator and the second is the denominator. The tuples are contained in a list called fractions.
This is my code so far:
fractions = [(1,7), (2,3), (22,7), (7001,7), (9,3), (611951,611953), (1,11), (1,7689585)]
DECIMALS = 10**40 # 40 decimal places
for fraction in fractions:
x = DECIMALS*fraction[0]/fraction[1]
print x
When i run the code this is what i get:
1428571428571428571428571428571428571428
6666666666666666666666666666666666666666
31428571428571428571428571428571428571428
10001428571428571428571428571428571428571428
30000000000000000000000000000000000000000
9999967317751526669531810449495304377950
909090909090909090909090909090909090909
1300460297922449651053990559958697
The problem is that I need to format this into the correct decimal format. What I tried was
print "0.%.40d" % (x)
But of course this will only help me with the first 2 decimals; the rest will be wrong. I thought about dividing it up so I can calculate the fractions indivdually to make them easier to format, but I have no idea how to do this. The catch is that all the fractions need to be processed by the same code. I also want it to be rounded properly but thats not a big deal right now.
If it strictly formatting, as implied by your question, you could, of course, do this with integers and strings alone:
Output:
The last digit will not correctly round and it will not handle edge cases (‘inf’, ‘NaN’, division by zero, etc) correctly.
Works in a pinch I suppose.
Why not use the batteries included though, like Decimal or Fraction?