Problem with float python (uri 1098)

1

I'm trying to solve this problem and when I run the code, at some point it stops working correctly . I think it's because of rounding, but when that part is removed, the code executes to infinity.

i = 0
j = 1

while(i != 2.2):
    print('I=%s J=%s' % (i, j))
    j = j + 1
    if(j == (i + 4)):
        i = round(i + 0.2, 1)
        j = round(j - 2.8, 1)

Is there a function that works best with decimals?

    
asked by anonymous 21.08.2016 / 00:42

1 answer

1

Your code seems to work fine.

As for running to infinity I believe it is because of logic in your while . To answer your question:

  

Is there a function that works best with decimals?

Yes, there is the decimal module. One possible solution:

from decimal import Decimal

i = 0
j = 1
while(i <= 2):
    print('I={} J={}'.format(i, j))
    j = j + 1
    if(j == (i + 4)):
        i += Decimal('0.2')
        j -= Decimal('2.8')

Reference: Python Cookbook, 3rd edition pags: 102/103 (84/85 in the footer)

    
21.08.2016 / 03:27