-1

Here is a python while loop code I am using:

i = 0.0
while i < 9.0:
    y = 13.0 - i
    if (y -i) == 6.0:
        print '[+] Solution found!'
        print 'x = ', i
        print 'y = ', y
        print 'z =', 8.0 - i
    i += 0.1

The problem is that 'if' block never gets executed even when condition is satisfied. On the other hand, if I put increment of 0.5 i.e. i += 0.5 then the code works as it should. Any idea what is causing the issue?

Ismael Padilla
  • 5,246
  • 4
  • 23
  • 35
dek0der
  • 3
  • 2

3 Answers3

0

Try this Code :

i = 0.0
while i < 9.0:
    y = 13.0 - i
    if round((y -i),1) == 6.0:
        print('[+] Solution found!')
        print('x = ', round(i,1))
        print('y = ', round(y,1))
        print('z =', round(8.0 - i,1))
    i += 0.1
Saragada Ramesh
  • 191
  • 2
  • 5
0

This is an issue of floating point precision. It's a really old problem. A way to get around this is to use Decimal and limit the precision to 2 digits after the comma. A possible way would like this (switched to python3 to test on my machine):

from decimal import *
getcontext().prec = 2
i = Decimal(0.0)
while i < Decimal(9.0):
    y = Decimal(13.0) - i
    if (y -i) == 6.0:
        print('[+] Solution found!')
        print('x = ', i)
        print('y = ', y)
        print('z =', Decimal(8.0) - i)
    i += Decimal(0.1)
Ralvi Isufaj
  • 442
  • 2
  • 9
0

It is caused by floating point precision. As MisterMiyagi commented, check Is floating point math broken ?. I would suggest using integers here.

Sileo
  • 307
  • 2
  • 18