This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Float // Integer doesn't give best result.
Type: Stage: resolved
Components: ctypes Versions: Python 3.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: def, mark.dickinson, serhiy.storchaka, steven.daprano, tim.peters
Priority: normal Keywords:

Created on 2019-11-27 12:00 by def, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg357566 - (view) Author: Douglas Feather (def) Date: 2019-11-27 12:00
40.9//2 give 20.0 as a result.  I would have expected one of: 20.45 or 20.  If it is going to give an FP answer then it should do the division as FP and get the right answer.  If it is going to do an integer division then it should give the division as an integer.
msg357567 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2019-11-27 12:26
To get 20.45 use the true division operator /.

If float // int would return int, 1e300 // 2 would return a 300-digit integer. It takee more memory and its creation is slower than 5e299. In addition it does not make sense to provide such precision.
msg357569 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2019-11-27 12:50
Although it often gets called "integer division", that's not actually what // does, it is actually *floor* division, as documented here:

https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex

So the behaviour as given is correct: it returns the floor of the quotient. Arguments are coerced to a common type in the normal fashion, so float//int performs the floor  division in floating point, which may not give the same result as integer floor division due to floating point rounding:

py> 10**17 // 7
14285714285714285
py> 1e17 // 7
1.4285714285714284e+16

If you don't want floating point rounding, don't use floats.

If you want "true division", use / not the floor division operator.

This isn't a bug, it is working as designed.

Even if the behaviour you are asking for was possible, practical and desirable, it would break backwards compatibility. There's no way to do a "floor division that returns an int" for all float arguments, since there are no int NANs.

py> float('inf')//7
nan
History
Date User Action Args
2022-04-11 14:59:23adminsetgithub: 83110
2019-11-27 12:50:33steven.dapranosetstatus: open -> closed

nosy: + steven.daprano
messages: + msg357569

resolution: not a bug
stage: resolved
2019-11-27 12:26:09serhiy.storchakasetnosy: + mark.dickinson, serhiy.storchaka, tim.peters
messages: + msg357567
2019-11-27 12:00:58defcreate