Question

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?

Was it helpful?

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

OTHER TIPS

Searching a little bit I found this function limit_denominator(...), that could help you:

F = fr.Fraction(str(ai - 1)).limit_denominator(100)

Output:

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

Read more in Fraction docs.

The fractions module is a great utility. Thanks for bringing it up here.

To control the denominator to more reasonable values, try adding limit_denominator() like this:

from fractions import Fraction
ai=2
bi=1
n=5
for i in range(n):
  ai=2+float(bi)/ai
  F=Fraction(str(ai-1)).limit_denominator(1000)
  print i, F

Output now looks like this:

%run "testFractions.py"
0 3/2
1 7/5
2 17/12
3 41/29
4 99/70
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top