7

Can someone explain me what's happening here?

Why is there more decimal points for 0.3 and 0.7 values. I just want 1 decimal point values.

threshold_range = np.arange(0.1,1,0.1)
threshold_range.tolist()
[Output]: [0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6, 0.7000000000000001, 0.8, 0.9]
4
  • 1
    This is correct behavior. This occurs because python, like most programming languages, cannot EXACTLY represent some decimals due to floating point limitations. See also stackoverflow.com/questions/21895756/… Commented Aug 1, 2019 at 10:30
  • Possible duplicate of Why are floating point numbers inaccurate? Commented Aug 1, 2019 at 10:33
  • Thats odd, its printing out fine for me. Commented Aug 1, 2019 at 10:36
  • @tnknepp Thanks for that comment. That's the part I was curious about. Commented Aug 1, 2019 at 11:25

2 Answers 2

5

Use np.round

Ex.

import numpy as np

threshold_range = np.arange(0.1,1,0.1)
print(threshold_range.tolist())
print(np.round(threshold_range, 2).tolist())

O/P:

[0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6, 0.7000000000000001, 0.8, 0.9]
[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for that. But I curious as to why it was acting up. Since you gave a solution to fix it first, I will mark it as the answer. As for the why, @tnknepp answered it in the comments.
@Saed see this Python/numpy floating-point text precision behaviour.
3

Solution: You can simply use round function:

threshold_range = np.arange(0.1,1,0.1).round(1)
threshold_range.tolist() # [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]

Reason of error: I think it has to do with floating point precision ;)

1 Comment

Thanks for the answer. I had to mark the above one as the answer, as it that was the first response (just like yours) :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.