3

So for example I have:

a = np.array(...)
a[idx / 3] = 5

idx / 3 will be a float, even though it will always have an integer value in that program. This will raise either a VisibleDeprecationWarning or is already no longer supported by newer Python versions.

Is there a built-in function that converts a float to an int and can raise an Exception if the input value is not an integer? Or what is the proper way to do it?

I'm aware that this might also lead to some questions about 'how close' to an integer, that's why I ask and do not just trust in floor/ceil.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Michael
  • 7,407
  • 8
  • 41
  • 84

1 Answers1

5

Be explicit:

assert (idx % 3) == 0, "idx must be divisible by 3"
a[idx // 3] = 5
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • This gives ``IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices`` on NumPy 1.12. You need to actually cast the result of `idx // 3` to an int – Eric May 22 '17 at 16:16
  • Ah, only if `idx` is a float – Eric May 22 '17 at 16:17
  • Be carefull, `"assert" statements are removed when the compilation is optimized`, see https://stackoverflow.com/questions/944592/best-practice-for-using-assert/1838411#1838411 – BorjaEst May 28 '23 at 16:59