gpt4 book ai didi

python - float 和小数的模数和整数除法的不同结果

转载 作者:太空狗 更新时间:2023-10-29 21:05:38 26 4
gpt4 key购买 nike

我对如下所示的行为感到很困惑:

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

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

有人可以解释一下吗?

最佳答案

引用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')

关于python - float 和小数的模数和整数除法的不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29543323/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com