Adem
Adem

Reputation: 5

Floating point comparison.

There is a better way to write this code:

for i in range(50, 56, 1):
        print(i / 10)
print("Half way done!")
for k in range(56, 61, 1):
     print(k / 10)
print("All the way done!")

Output:

5.0
5.1
5.2
5.3
5.4
5.5
Half way done!
5.6
5.7
5.8
5.9
6.0
All the way done!

I've been trying to compare floating point numbers and this is the best I have gotten so far, there are methods out there but I cant understand them as I'm not at that level yet, so if anyone could provide an alternative way of comparing floating point numbers, that would be much appreciated. Thanks!

Upvotes: 0

Views: 63

Answers (1)

TigerhawkT3
TigerhawkT3

Reputation: 49320

Instead of trying to compare i/10 to 5.5, simply compare the loop iterator (which is an integer) to the calculated halfway point (another integer):

start = 50
end = 61
half = (end-start)//2 + start
for i in range(50, 61):
    print(i/10)
    if i == half:
        print('Half way done!')

print("All the way done!")

Upvotes: 2

Related Questions