In python, why does np.arange(-1.6,-0.49,0.01) generate a list where the last element is -0.49 while np.arange(0,0.49,0.01) generates a list where the last element is 0.48?
Asked
Active
Viewed 111 times
0
-
1Short answer: [floating point math](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). It's the same reason that `0.1 + 0.2 != 0.3` – Cory Kramer Jan 15 '20 at 19:04
-
2Floating-point precision. Some value that isn't actually `-0.49` is *displayed* as `-0.49`, but it's probably something like `-0.490000001`. – chepner Jan 15 '20 at 19:04
-
1Use `np.linspace`. – user2357112 Jan 15 '20 at 19:05
-
1`arange` does have a cautionary note about using floating step values. – hpaulj Jan 15 '20 at 20:55
1 Answers
3
Floating point arithmetic doesn't use base 10, so things that look perfectly simple often don't work that way in practice. The exception to this is integers as floating point, because for reasonable numbers the errors are all to the right of the decimal point. You can restructure your range to use integers and you'll get consistent results.
np.arange(-160, -49) * 0.01

Mark Ransom
- 299,747
- 42
- 398
- 622