4

Below code displays from 12.01 till 16.01. But shouldn't it display only till 16.00?

import numpy as np

for i in np.arange(12.01, (16.01), 0.01):
    print(float('{num:0.2f}'.format(num=i)))
jpp
  • 159,742
  • 34
  • 281
  • 339
Jp Mohan
  • 160
  • 2
  • 7
  • print the whole range at once. – Mazdak Mar 20 '18 at 09:19
  • 2
    Using floating point in this way is not reliable. – llllllllll Mar 20 '18 at 09:20
  • Try adding `0.01` to `12.01` 400 times. It'll give you something slightly smaller than 16.01 (namely 16.009999999999916 on my machine) due to floating point arithmetic. Also maybe have a look at: [this question](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). – jotasi Mar 20 '18 at 09:26
  • You can also try: `16.02-0.01 == 16.009999999999998` – jpp Mar 20 '18 at 09:27
  • Use `decimal` [module](https://docs.python.org/3.6/library/decimal.html) if you need decimals... – jpp Mar 20 '18 at 09:29

1 Answers1

4

From the numpy.arange documentation:

When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use linspace for these cases.

So linspace might be more appropriate for your case

If you want 400 evenly spaced numbers from 12.01 to 16:

np.linspace(12.01, 16, num=400)
H. Gourlé
  • 884
  • 7
  • 15
  • 1
    That documentation is simplifying :) The results are not "not consistent" – they *are* – but the implicitly applied accuracy of such floating point numbers is beyond normal human ken. – Jongware Mar 20 '18 at 09:28