Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different result of modulo and integer divison for float and Decimal

I am quite confused with the behaviour as shown below:

>>> (-7) % 3 
2
>>> Decimal('-7') % Decimal('3') 
Decimal('-1')
>>> 

>>> (-7) // 3
-3
>>> Decimal('-7') // Decimal('3') 
Decimal('-2')
>>>

Can someone please explain?

like image 739
Arindam Choudhury Avatar asked Apr 09 '15 15:04

Arindam Choudhury


1 Answers

Quoting the decimal documentation:

There are some small differences between arithmetic on Decimal objects and arithmetic on integers and floats. When the remainder operator % is applied to Decimal objects, the sign of the result is the sign of the dividend rather than the sign of the divisor:

>>> (-7) % 4
1
>>> Decimal(-7) % Decimal(4)
Decimal('-3')

The integer division operator // behaves analogously, returning the integer part of the true quotient (truncating towards zero) rather than its floor, so as to preserve the usual identity x == (x // y) * y + x % y:

>>> -7 // 4
-2
>>> Decimal(-7) // Decimal(4)
Decimal('-1')
like image 83
vaultah Avatar answered Sep 24 '22 06:09

vaultah