在 Python 中,在整数除法中向零舍入的好方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19919387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Python, what is a good way to round towards zero in integer division?
提问by blacktrance
1/2
gives
给
0
as it should. However,
正如它应该。然而,
-1/2
gives
给
-1
, but I want it to round towards 0 (i.e. I want -1/2 to be 0), regardless of whether it's positive or negative. What is the best way to do that?
,但我希望它向 0 舍入(即我希望 -1/2 为 0),无论它是正数还是负数。最好的方法是什么?
采纳答案by Tim
Do floating point division then convert to an int. No extra modules needed.
做浮点除法然后转换为int。不需要额外的模块。
>>> int(float(-1)/2)
0
>>> int(float(-3)/2)
-1
>>> int(float(1)/2)
0
>>> int(float(3)/2)
1
回答by Conor Patrick
Try this. Only works for numbers greater than -1
尝试这个。仅适用于大于 -1 的数字
import math
x = .5
y = -.5
print math.floor(math.fabs(x))
>> 0
print math.floor(math.fabs(y))
>> 0
回答by dawg
Python's default division of integers is return the floor (towards negative infinity) with no ability to change that. You can readthe BDFL's reason why.
Python 的默认整数除法是返回下限(向负无穷大),无法改变它。您可以阅读BDFL 的原因。
To do 'round up' division, you would use:
要进行“四舍五入”除法,您可以使用:
>>> a=1
>>> b=2
>>> (a+(-a%b))//b
1
>>> a,b=-1,2
>>> (a+(-a%b))//b
0
To do truncation towards zero, and maintain integer division, you use (a+(-a%b))//b
if either a or b are negative and the default division if both are positive.
要向零截断并保持整数除法,请使用(a+(-a%b))//b
a 或 b 是否为负,如果两者均为正则使用默认除法。
This will do integer division and always round towards zero:
这将进行整数除法并始终向零舍入:
>>> a=1
>>> b=2
>>> a//b if a*b>0 else (a+(-a%b))//b
0
>>> a=-1
>>> b=2
>>> a//b if a*b>0 else (a+(-a%b))//b
0
>>> a,b=-3,2
>>> a//b if a*b>0 else (a+(-a%b))//b
-1
>>> a,b=3,2
>>> a//b if a*b>0 else (a+(-a%b))//b
1
footnote
脚注
Interestingly enough, C99 declares that round towards zerois the default:
有趣的是,C99 声明向零舍入是默认值:
#include <stdio.h>
int main(int argc, const char * argv[])
{
int a=-3;
int b=2;
printf("a=%d, b=%d, a/b=%d\n",a,b,a/b);
a=3;
printf("a=%d, b=%d, a/b=%d\n",a,b,a/b);
return 0;
}
Prints:
印刷:
a=-3, b=2, a/b=-1
a=3, b=2, a/b=1
回答by Tim Peters
Correct code to do this is, in my opinion, too obscure to write as a 1-liner. So I'd put it in a function, like:
在我看来,执行此操作的正确代码太晦涩,无法编写为 1-liner。所以我把它放在一个函数中,比如:
def int0div(a, b):
q = a // b
if q < 0 and b*q != a:
q += 1
return q
Good features: it works for any size of int, doesn't make any adjustment to the raw (a//b
) result unless necessary, only does one division (%
also does a division under the covers), and doesn't create any integers larger than the inputs. Those may or may not matter in your application; they become more important (for speed) if you use "big" integers.
好的特性:它适用于任何大小的 int,a//b
除非必要,否则不对原始 ( ) 结果进行任何调整,只进行一次除法(%
也在封面下进行除法),并且不会创建任何大于输入。这些在您的应用程序中可能重要也可能无关紧要;如果您使用“大”整数,它们会变得更加重要(对于速度)。
回答by Tim Peters
Throwing my hat in with a few alternate ideas:
提出一些替代想法:
Multiple the sign of the number [abs(x)/x] by the abs(x)/2
将数字 [abs(x)/x] 的符号乘以 abs(x)/2
(abs(x)/x)*(abs(x)/2)
Perform the addition, but if the number is less than zero add one to shift it closer to 0.
执行加法,但如果数字小于零,则加一使其更接近于 0。
x/2 + int(x<0)
回答by Mark Dickinson
For what it's worth, my own favourite solution is this one. Integer arithmetic only, a single division, and everything else linear time:
对于它的价值,我自己最喜欢的解决方案是这个。仅整数算术,单除法,以及其他所有线性时间:
def integer_divide_towards_zero(a, b):
return -(-a // b) if a < 0 else a // b
That assumes that b
is positive, but in most of the applications I've seen that's true. If you need to deal with negative b
too, then the function becomes marginally more complicated:
假设这b
是肯定的,但在我见过的大多数应用程序中都是如此。如果你也需要处理负数b
,那么函数会稍微复杂一些:
def integer_divide_towards_zero(a, b):
return -(-a // b) if (a < 0) ^ (b < 0) else a // b
Some sample outputs:
一些示例输出:
>>> integer_divide_towards_zero(11, 3)
3
>>> integer_divide_towards_zero(-11, 3)
-3
>>> integer_divide_towards_zero(6, 3)
2
>>> integer_divide_towards_zero(-6, 3)
-2
>>> integer_divide_towards_zero(11, -3)
-3
>>> integer_divide_towards_zero(-11, -3)
3
回答by jjisnow
You can also use the Decimalmodule as part of the standard python libraries.
您还可以使用Decimal模块作为标准 Python 库的一部分。
Specifically, " 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:"
具体来说,“整数除法运算符 // 的行为类似,返回真商的整数部分(向零截断)而不是其底数,以保留通常的恒等式 x == (x // y) * y + x %y:"
>>> -7 // 4
-2
>>> Decimal(-7) // Decimal(4)
Decimal('-1')
Also, have a look at Rounding Modesas they've got quite a few ways to view/round your information - Ceiling, down, floor, half-down, half-even, half-up, up and 05up rounding.
另外,看看舍入模式,因为他们有很多方法可以查看/舍入您的信息 - 天花板、向下、地板、半向下、半偶数、半向上、向上和 05 向上舍入。
Decimal was written as a solution to the traditional problem of binary mathematics in a world expecting decimals solutions
十进制是为了解决期望小数解决方案的世界中二进制数学的传统问题而编写的
回答by jjisnow
why reinvent the wheel, when there's a perfectly good math.trunc() function?
当有一个非常好的 math.trunc() 函数时,为什么要重新发明轮子?
import math
print(math.trunc(-3.5))
>>-3
print(math.trunc(3.5))
>>3