0

I wrote the following code:

for value in values:
    p = round(stats[value] / stats.sum(),2)
    e = round(-p * math.log(p,2),2)
    print (e)
    plist.append((value,p,e))

the "print(e)" displays the values 0.46 and 0.53. That's what's expected. When I print the list, I obtain the following:

[('Y', 0.57999999999999996, 0.46000000000000002), 
 ('N', 0.41999999999999998, 0.53000000000000003)]

the value of 'e' that was rounded properly, is now appended to the list as 0.46000000000000002 and 0.53000000000000003.

Why is that and how can I get the rounded values on 2 decimals in my tuple ?

Mike Müller
  • 82,630
  • 20
  • 166
  • 161
JCF
  • 307
  • 2
  • 17
  • You are looking at different representations. `print()` uses `str()`, and in a container `repr()` is used. They are the *exact same values*. – Martijn Pieters Dec 25 '17 at 20:08
  • 1
    Don't use containers as user-presentation-ready formats. Format your output yourself if you must have the 'friendly' values. – Martijn Pieters Dec 25 '17 at 20:09
  • The 'yes' should represent 5/12, and the 'no', 7/12. I try to obtain proportions that add up exactly to 1. I suppose then that the recommended approach is then to round decimal by setting precision using getcontext().prec = 3 ? – JCF Dec 25 '17 at 22:04
  • If you are trying to store fractions, perhaps you want to store [`fractions.Fraction()` objects](https://docs.python.org/3/library/fractions.html) instead? – Martijn Pieters Dec 25 '17 at 22:57
  • I suspect that you're using NumPy's `round` function, or that the values you're rounding are NumPy floats rather than regular Python floats. For regular Python floats, in Python >= 3.2, the `str` and `repr` are identical, and you shouldn't see any difference when printing the value standalone versus printing a container containing it. – Mark Dickinson Dec 26 '17 at 16:06
  • Possible duplicate of [Python (strangely) rounding values](https://stackoverflow.com/questions/16105833/python-strangely-rounding-values) – Mark Dickinson Dec 26 '17 at 16:22

0 Answers0