Search code examples
pythonfractions

The fractions are incomplete


I'm working with the fractions module of python.

I'm trying to get fractions that aproximates 2*.5. The problem is that when I use the Fraction command, it doesn't returns me what I want, because, for example, in i=2, the fractions that returns is 146666667/1000000000, but i want that it returns me 17/12 (The third aproximation of 2*.5). How i can solve it?

The code is this:

ai=2
bi=1
n=5
for i in range(n):
  ai=2+float(bi)/ai
  F=fr.Fraction(str(ai-1))
  print F

Can someone help me, please?


Solution

  • If you are going to work with fractions, don't do part of the calculation with floats. You can perform all the arithmetic with respect to fractions by making ai a Fraction:

    import fractions
    ai = fractions.Fraction(2)
    bi = 1
    n = 5
    for i in range(n):
        ai = 2 + bi / ai
        F = ai - 1
        print(F)
    

    yields

    3/2
    7/5
    17/12
    41/29
    99/70