2

There is a post about broken rounding . However it is not a rounding problem here because it does round in the normal case as you see but it doesn't round when inserting into an array.

I have following code:

print(round(limits[1],1))
limit = [round(limits[0],1), round(limits[1],1)]
print(limit)

Output:

25860.4
[14766.4, 25860.400000000001]

I do not understand why second element of an array is not rounded, although I do round it before while I pack it into the array.

Code:

import numpy as np
def intrvl_comparison(data):
    m = np.mean(data)
    sd = np.std(data)
    up_l = (m + sd)
    low_l = (m - sd)
    limits = [low_l, up_l]
    limit = [round(x,1) for x in limits]
    print(round(limits[0],1))
    limit = [round(limits[0],1), round(limits[1],1)]
    print(limit)

intrvl_comparison([2.66666,4.4444444,6066,9999])
Community
  • 1
  • 1
Alina
  • 2,191
  • 3
  • 33
  • 68
  • What python version are you using? This seems to be an issue with pre-2.7 versions. – gonczor Apr 19 '17 at 09:41
  • I have Python 3.6.0 – Alina Apr 19 '17 at 09:42
  • I'll try to reproduce this on my machine. Could you please provide a minimal code I could run? – gonczor Apr 19 '17 at 09:44
  • @gonczor I included a code into the question – Alina Apr 19 '17 at 09:49
  • Added 3.x tag, as I can reproduce this in Python 3 at repl.it, but not on my machine in 2.7 – SiHa Apr 19 '17 at 09:54
  • Thanks, I've tried playing around with it and if I call limit[0] == - 230.4 it returns True meaning it could have more to do with representation than with actual value. You could check out Decimal library, or use formatting for printouts if it doesn;t affect the logic of your code. Sorry, I don't know this issue. – gonczor Apr 19 '17 at 10:04
  • For what it's worth, there are two effects here. First is the fact that `repr` is used when printing elements of a collection, as opposed to the `str` that's used when printing an element directly. That's covered in the linked so-called duplicate. But that's not enough to explain what's being seen here, since in Python >= 3.2, the `repr` and `str` of a Python `float` are identical. The other piece of information that you need is that you're looking at NumPy `float64` objects, which use a different `repr` algorithm from Python floats. ... – Mark Dickinson Apr 19 '17 at 17:37
  • ... So you're seeing the difference between `str` and `repr` for NumPy `float64` objects. But the underlying message of the linked answers holds: the values aren't changing; it's merely that they're being displayed differently in the two cases. – Mark Dickinson Apr 19 '17 at 17:38

0 Answers0