Because of floating point imprecision, you may not end up with exactly 0.65
.
To solve this, use <
rather than !=
(a):
intensity = 0.50
while intensity < 0.65:
print(intensity)
intensity = intensity + 0.05
The output of that (showing what I mean by imprecision as well) is:
0.5
0.55
0.6000000000000001
If you kept going, you'd see:
0.6500000000000001
0.7000000000000002
0.7500000000000002
0.8000000000000003
which is why it's never equal to 0.65
.
(a) You may be wondering what the situation would be if the next value was 0.6499...9
rather than 0.650..1
, and you would probably be right to be concerned.
While using <
will fix the latter case, you'll almost certainly get one iteration too many for the former case.
You can fix that by a number of possible different strategies, some of which are:
- round the number to the correct number of decimals before comparing, such as
round(intensity, 2)
.
- compare it with a "close enough" check, such as the absolute difference being less that
10-4
(for example) - something like if abs(intensity - 0.65) < 0.0001
.
- use integral values exclusively and scale the value as needed (e.g., initialising
intensity
to 50
, adding 5
, comparing to 65
, and printing round(intensity / 100, 2)
.
The Python documentation has an interesting article that you can read to further understand these limitations.
intensity
is0.6000000000000001
and the loop never closes. Rounding would fix this. However, I don't know why it isn't printing the value, so I have upvoted your question. – Dg