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: Calculating wrong modulus manually
Type: behavior Stage:
Components: Versions: Python 3.5
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: sfaisalawan, steven.daprano, xiang.zhang
Priority: normal Keywords:

Created on 2016-09-08 14:21 by sfaisalawan, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (3)
msg275015 - (view) Author: Faisal Saleem (sfaisalawan) Date: 2016-09-08 14:21
Hi,

when I calculate (11**19)%23 it gives me 15 but when I try to do the same operation manually it give a totally different result which is 1395.

>>> 11**19
61159090448414546291
>>> (11**19)%23
15
>>> a=11**19
>>> a
61159090448414546291
>>> b=23
>>> c=int(a/b)
>>> c
2659090889061501952
>>> d=b*c
>>> d
61159090448414544896
>>> e=a-d
>>> e
1395
msg275019 - (view) Author: Xiang Zhang (xiang.zhang) * (Python committer) Date: 2016-09-08 14:33
You should use a//b instead of int(a/b).

>>> 11**19 - 11**19//23*23
15
>>> 11**19 - int(11**19/23)*23
1395
msg275057 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2016-09-08 16:14
That is because of floating point rounding.

When you calculate a/23, the result is the approximate float 2.659090889061502e+18 instead of the exact integer result 2659090889061502012. Converting to an int gives you a result which is too small:

py> a = 11**19
py> a - (a//23)*23  # calculate modulus with no rounding error
15
py> a - int(a/23)*23  # introduces rounding error
1395
py> a/23
2.659090889061502e+18
py> int(a/23)
2659090889061501952
py> int(a/23) - a//23
-60


By the way, are you aware of the third argument to pow()?

py> pow(11, 19, 23)
15
History
Date User Action Args
2022-04-11 14:58:36adminsetgithub: 72208
2016-09-08 16:14:46steven.dapranosetstatus: open -> closed

nosy: + steven.daprano
messages: + msg275057

resolution: not a bug
2016-09-08 14:33:44xiang.zhangsetnosy: + xiang.zhang
messages: + msg275019
2016-09-08 14:21:07sfaisalawancreate