Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python 3 long ints and multiplication

Tags:

python

I'm trying to execute next code int((226553150 * 1023473145) / 5) and python3 gives me an answer 46374212988031352. But ruby and swift give me an answer 46374212988031350.

What do I miss?

like image 916
Arsen Avatar asked Feb 22 '16 17:02

Arsen


2 Answers

You are missing that Python's division (from Python 3 on) is by default a float division, so you have reduced precision in that. Force the integer division by using // instead of / and you will get the same result.

like image 123
filmor Avatar answered Sep 27 '22 19:09

filmor


a / b is a floating-point division in Python 3. In order to perform integer division you should use // operator:

In [3]: (226553150 * 1023473145) // 5
Out[3]: 46374212988031350

Floating point division precision limited to the mantissa size:

In [19]: (226553150 * 1023473145) / 5
Out[19]: 4.637421298803135e+16

As you can see, Python correctly represents all digits but the last. You could also made some interesting tricks with it:

In [20]: int((226553150 * 1023473145) / 5)
Out[20]: 46374212988031352

In [21]: int((226553150 * 1023473145) / 5 - 1)
Out[21]: 46374212988031352

In [22]: int((226553150 * 1023473145) / 5 + 1)
Out[22]: 46374212988031352

In [23]: int((226553150 * 1023473145) / 5 - 2)
Out[23]: 46374212988031352

In [24]: int((226553150 * 1023473145) / 5 - 3)
Out[24]: 46374212988031352

In [25]: int((226553150 * 1023473145) / 5 - 4)
Out[25]: 46374212988031344

In [26]: int((226553150 * 1023473145) / 5 + 4)
Out[26]: 46374212988031360

In [27]: int((226553150 * 1023473145) / 5 + 3)
Out[27]: 46374212988031352
like image 42
awesoon Avatar answered Sep 27 '22 21:09

awesoon