Problem with float python (Uri 1098)

Asked

Viewed 659 times

2

I’m trying to solve this problem and when I execute the code, at a certain point it stops working correctly. I think it’s because of rounding, but when that part is removed, the code runs 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)

there is some function that is better working with decimals?

  • It seems to me to work well. What problem are you referring to?

2 answers

1


Your code seems to work well.

As for running to infinity I think it’s because of the logic in your while. To answer your question:

there is some function that is better working with decimals?

Yes there is the module decimal. A 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 at footnote)

0

This issue refers to the number challenge 1098, whose title is Sequence IJ 4 made available by Uri Online Judge.

See here the entirety of the statement.

To solve this issue we must develop an algorithm that is capable of reproduzir the example given in that question.

To solve this question correctly we implement the following algorithm...

i = 0
j = 1
acrescimo = (0.2)
n = 0
while i <= 2:
    for c in range(1, 4):
        if i > 2.19:
            print('I={:.0f} J={:.0f}'.format(2, j))
        if i == 1.0 or i == 0.0 or i > 1.8:
            print('I={:.0f} J={:.0f}'.format(i, j))
        elif i < 2:
            print('I={:.1f} J={:.1f}'.format(i, j))
        j = j + 1
    i = i + acrescimo
    j = 1 + i

See how the algorithm works on repl it..

This question has already been testada, submetida and properly aprovada on the website of URI, under programming language Python 3.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.