4

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]
Saed
  • 357
  • 1
  • 7
  • 12
  • 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 https://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate – tnknepp Aug 01 '19 at 10:30
  • Possible duplicate of [Why are floating point numbers inaccurate?](https://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate) – tnknepp Aug 01 '19 at 10:33
  • Thats odd, its printing out fine for me. – Axois Aug 01 '19 at 10:36
  • @tnknepp Thanks for that comment. That's the part I was curious about. – Saed Aug 01 '19 at 11:25

2 Answers2

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]
bharatk
  • 4,202
  • 5
  • 16
  • 30
  • 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 Aug 01 '19 at 11:22
  • @Saed [see this](https://stackoverflow.com/questions/12502122/python-numpy-floating-point-text-precision) Python/numpy floating-point text precision behaviour. – bharatk Aug 01 '19 at 11:46
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 ;)

  • Thanks for the answer. I had to mark the above one as the answer, as it that was the first response (just like yours) :) – Saed Aug 01 '19 at 11:24