Search code examples
pythonpython-2.7loopswhile-loopfractions

How to increase the value of a fraction in a loop with Python


Im was trying to do a loop, increasing the numerator by 1 each iteration, but I got this error:

ZeroDivisionError: Fraction(1, 0)

My code is something like this:

from fractions import Fraction
x = Fraction(0,48)
z = x.numerator
limit = (48,48)    
while x == limit:
    print("cycle " + str(z))
    x += Fraction(1,0)
print("loop finished!")

Solution

  • it looks like you increment x from zero to one, in steps of 1/48

    try this

    from fractions import Fraction
    m_denominator = 48
    x = Fraction(0,m_denominator)
    z = 0
    limit = Fraction(m_denominator,m_denominator)    #notice limit is now a Fraction object
    while x <= limit: #notice, i changed this
        print("cycle " + str(z))
        z = z+1
        x += Fraction(1,m_denominator)
    print("loop finished!")