0
Python: arange() function troubleshooting
Hi, guys, have some strange thing while solving the Python test. The goal was to get "10" in the following task if a mean of proposed imputs is between 70 and 80. The proposed inputs were 64 and 87, therefore, mean is 75.5. Surprisingly, only step=0.5 in arange(70,80,0.5) works, while 0.1 doesn't. Why?? I printed simultaneously this arange(70,80,0.1), and 75.5 was among them. How it works? # from statistics import mean from numpy import arange score=(int(input()),int(input())) if mean(score) in arange(70, 80, 0.5): print("10")
2 Réponses
+ 2
The problem is that 0.1 has no precise representation as a binary floating point number, it is rounded. "arange" produces a list of numbers and "in" compares the left side to the values in that list using equality (==). Due to rounding 75.5 is not precisely part of that list. If you print the values however they are rounded. Floats should be compared by checking if the difference is below a threshold. I don't think you can do that using "in".
A better solution for this challenge would be to use inequality operators (>, <, >=, <=)
+ 1
output this and notice the output
print([x for x in arange(70, 80, 0.1)])
print([x for x in arange(70, 80, 0.5)])
try:
if mean(score) in [round(x, 1) for x in arange(70, 80, 0.1)]:
print("10")