0

I was creating a list of numbers by first generating an array and then converting it. However, I noticed that 0.3 comes out differently in the list. What causes this? I don't see a similar issue for the other lists I created e.g., list(np.arange(1,7))

display(np.arange(0.1, 0.4, 0.1)) # output: array([0.1, 0.2, 0.3, 0.4])
display(np.arange(0.1, 0.35, 0.1)) # array([0.1, 0.2, 0.3])
display(np.arange(0.1, 0.3, 0.1)) # array([0.1, 0.2])

display(list(np.arange(0.1, 0.4, 0.1))) # output: [0.1, 0.2, 0.30000000000000004, 0.4]
display(list(np.arange(0.1, 0.35, 0.1))) # [0.1, 0.2, 0.30000000000000004]
display(list(np.arange(0.1, 0.3, 0.1))) # [0.1, 0.2]
Marsha T
  • 13
  • 3
  • 3
    What is `display`? – Michael Butscher Aug 27 '23 at 13:52
  • 1
    @Michael I'm guessing `IPython.display.display` – wjandrea Aug 27 '23 at 14:23
  • Possible duplicate: [numpy arange unexpected results](/q/10011302/4518341). (I'm not a NumPy expert myself but this seems to answer the question.) – wjandrea Aug 27 '23 at 14:38
  • 2
    If you `np.set_printoptions(precision=17)`, the NumPy output changes too. – wjandrea Aug 27 '23 at 14:39
  • 1
    @QuangHoang Which of those answers explains this? If you re-close as duplicate of the same other question as the first close, I'd rather expect an explanation... – Kelly Bundy Aug 27 '23 at 15:02
  • 2
    @QuangHoang If this would be an issue with binary storing of floats (probably it is related to presentation instead) then why are floats in a list more broken than in a numpy array? – Michael Butscher Aug 27 '23 at 15:10
  • @MichaelButscher, it's a combination of how `arange` calculates the values (with a float step), and how `numpy` displays arrays. The numpy display rounds to a common length; list displays each element separately. But `arange` has a note about floating point artifacts. Lists aren't 'more broken'. – hpaulj Aug 27 '23 at 15:55
  • wjandrea has it in the comment above: it's `np.set_printoptions` which defaults to rounding the printout to 8 decimal places. So because of this, numpy hides smaller errors in array values when printing. – Dave Rove Aug 27 '23 at 18:19
  • @MichaelButscher storing binary data as float wouldn't be a problem as small integers are within float's resolution. I marked it as duplicated of floating point precision because it is important to understand that the **data** are the same in both list and numpy array, just the **displays** of the data are different; and that the actual data is not precisely `0.3`. – Quang Hoang Aug 28 '23 at 04:30
  • Thanks all! Confirmed using the following code (which gave no AssertionError): `array_t = np.arange(0.1, 0.4, 0.1)` `list_t = list(np.arange(0.1, 0.4, 0.1))` `assert list_t[2] == array_t[2]` – Marsha T Aug 29 '23 at 06:35

0 Answers0