How to simulate C style integer division?
Steven D'Aprano
steve at pearwood.info
Thu Jan 21 22:48:38 EST 2016
On Fri, 22 Jan 2016 12:59 pm, Grobu wrote:
> On 21/01/16 09:39, Shiyao Ma wrote:
>> Hi,
>>
>> I wanna simulate C style integer division in Python3.
>>
>> So far what I've got is:
>> # a, b = 3, 4
>>
>> import math
>> result = float(a) / b
>> if result > 0:
>> result = math.floor(result)
>> else:
>> result = math.ceil(result)
>>
>>
>> I found it's too laborious. Any quick way?
>>
>
> math.trunc( float(a) / b )
That fails for sufficiently big numbers:
py> a = 3**1000 * 2
py> b = 3**1000
py> float(a)/b # Exact answer should be 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: long int too large to convert to float
Note that Python gets the integer division correct:
py> a//b
2L
And even gets true division correct:
py> from __future__ import division
py> a/b
2.0
so it's just the intermediate conversion to float that fails.
--
Steven
More information about the Python-list
mailing list