-1

I have an issue with numpy linspace

import numpy as np

temp = np.linspace(1,2,11)

for t in temp:
    print(t)

This return :

1.0
1.1
1.2
1.3
1.4
1.5
1.6
1.7000000000000002
1.8
1.9
2.0

The 1.7 value looks definitely wrong.

It seems related to this issue https://github.com/numpy/numpy/issues/8909

Does anybody ever had such a problem with numpy.linspace ? is it a known issue ?

François

Francois
  • 182
  • 3
  • 15
  • Possible duplicate of [Why Are Floating Point Numbers Inaccurate?](https://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate) – Daniel F Aug 29 '18 at 12:12
  • 2
    Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – FlyingTeller Aug 29 '18 at 12:13

1 Answers1

3

This is nothing to do with numpy, consider:

>>> temp = np.linspace(1,2,11)
>>> temp
array([1. , 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. ])
>>> #                                     ^ look, numpy displays it fine
>>> for t in temp:
...     print(t)
... 
1.0
1.1
1.2
1.3
1.4
1.5
1.6
1.7000000000000002
1.8
1.9
2.0

The "issue" is with how computers represent floats in general. See: https://docs.python.org/3/tutorial/floatingpoint.html.

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
  • Thanks for the information. The document you provided explain very well the problem. Today I learned something :-) – Francois Aug 29 '18 at 12:46
  • @Francois Yeah it caught me out on a test concerning money before! You always want to store money as pence (I'm English) rather than pounds and pence: so `£3.45` should be `345` rather than `3.45` as there is no avoiding this. – Joe Iddon Aug 29 '18 at 12:48