Python 中 % 的结果是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4432208/
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
What is the result of % in Python?
提问by orange
What does the %in a calculation? I can't seem to work out what it does.
什么是%在计算?我似乎无法弄清楚它的作用。
Does it work out a percent of the calculation for example: 4 % 2is apparently equal to 0. How?
它是否计算出计算的百分比,例如:4 % 2显然等于 0。如何?
采纳答案by meder omuraliev
The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].
%(模)运算符产生第一个参数除以第二个参数的余数。数字参数首先转换为通用类型。零右参数引发 ZeroDivisionError 异常。参数可以是浮点数,例如,3.14%0.7 等于 0.34(因为 3.14 等于 4*0.7 + 0.34。)结果的绝对值严格小于第二个操作数 [2] 的绝对值。
Taken from http://docs.python.org/reference/expressions.html
取自http://docs.python.org/reference/expressions.html
Example 1:6%2evaluates to 0because there's no remainder if 6 is divided by 2 ( 3 times ).
示例 1:6%2评估为,0因为如果 6 除以 2(3 次),则没有余数。
Example 2: 7%2evaluates to 1because there's a remainder of 1when 7 is divided by 2 ( 3 times ).
示例 2:7%2评估为1因为1当 7 除以 2 ( 3 次 ) 时有余数。
So to summarise that, it returns the remainder of a division operation, or 0if there is no remainder. So 6%2means find the remainder of 6 divided by 2.
总而言之,它返回除法运算的余数,或者0如果没有余数。所以6%2意味着找到 6 除以 2 的余数。
回答by Paulo Scardine
An expression like x % yevaluates to the remainder of x ÷ y- well, technically it is "modulus" instead of "reminder" so results may be different if you are comparing with other languages where %is the remainder operator. There are some subtle differences(if you are interested in the practical consequences see also "Why Python's Integer Division Floors" bellow).
像这样的表达式x % y计算为余数x ÷ y- 好吧,从技术上讲,它是“模数”而不是“提醒”,因此如果您将%余数运算符与其他语言进行比较,结果可能会有所不同。有一些细微的差异(如果您对实际结果感兴趣,另请参阅下面的“为什么 Python 的整数除法层”)。
Precedence is the same as operators /(division) and *(multiplication).
优先级与运算符/(除法)和*(乘法)相同。
>>> 9 / 2
4
>>> 9 % 2
1
- 9 divided by 2 is equal to 4.
- 4 times 2 is 8
- 9 minus 8 is 1 - the remainder.
- 9 除以 2 等于 4。
- 4 乘以 2 是 8
- 9 减 8 是 1 - 余数。
Python gotcha: depending on the Python version you are using, %is also the (deprecated) string interpolation operator, so watch out if you are coming from a language with automatic type casting (like PHP or JS) where an expression like '12' % 2 + 3is legal: in Python it will result in TypeError: not all arguments converted during string formattingwhich probably will be pretty confusing for you.
Python 问题:根据您使用的 Python 版本,%也是(不推荐使用的)字符串插值运算符,因此请注意您是否来自具有自动类型转换的语言(如 PHP 或 JS),其中表达式 like'12' % 2 + 3是合法的: Python 它会导致TypeError: not all arguments converted during string formatting你可能会非常困惑。
[update for Python 3]
[Python 3 更新]
User n00p comments:
用户 n00p 评论:
9/2 is 4.5 in python. You have to do integer division like so: 9//2 if you want python to tell you how many whole objects is left after division(4).
9/2 在 python 中是 4.5。你必须像这样进行整数除法:9//2 如果你想让 python 告诉你除法后剩下多少整个对象(4)。
To be precise, integer division used to be the default in Python 2 (mind you, this answer is older than my boy who is already in school and at the time 2.x were mainstream):
准确地说,整数除法曾经是 Python 2 中的默认值(请注意,这个答案比我已经上学并且当时 2.x 是主流的男孩还要大):
$ python2.7
Python 2.7.10 (default, Oct 6 2017, 22:29:07)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 9 / 2
4
>>> 9 // 2
4
>>> 9 % 2
1
In modern Python 9 / 2results 4.5indeed:
在现代 Python9 / 2结果中4.5确实:
$ python3.6
Python 3.6.1 (default, Apr 27 2017, 00:15:59)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 9 / 2
4.5
>>> 9 // 2
4
>>> 9 % 2
1
[update]
[更新]
User dahiya_boy asked in the comment session:
用户 dahiya_boy 在评论区提问:
Q.Can you please explain why
-11 % 5 = 4- dahiya_boy
问:你能解释一下原因
-11 % 5 = 4吗 - dahiya_boy
This is weird, right? If you try this in JavaScript:
这很奇怪,对吧?如果您在 JavaScript 中尝试此操作:
> -11 % 5
-1
This is because in JavaScript %is the "remainder" operator while in Python it is the "modulus" (clock math) operator.
这是因为在 JavaScript 中%是“余数”运算符,而在 Python 中它是“模数”(时钟数学)运算符。
You can get the explanation directly from GvR:
Edit - dahiya_boy
编辑 - dahiya_boy
In Java and iOS -11 % 5 = -1whereas in python and ruby -11 % 5 = 4.
在 Java 和 iOS 中,-11 % 5 = -1而在 python 和 ruby 中-11 % 5 = 4。
Well half of the reason is explained by the Paulo Scardine, and rest of the explanation is below here
Paulo Scardine解释了一半的原因,其余的解释在下面
In Java and iOS, %gives the remainder that means if you divide 11 % 5gives Quotient = 2 and remainder = 1and -11 % 5gives Quotient = -2 and remainder = -1.
在Java和iOS,%使剩余这意味着,如果你把11%的5给出了Quotient = 2 and remainder = 1和-11%5给出Quotient = -2 and remainder = -1。
Sample code in swift iOS.
Swift iOS 中的示例代码。
But when we talk about in python its gives clock modulus. And its work with below formula
但是当我们在 python 中谈论它时,它给出了时钟模数。它的工作与以下公式
mod(a,n) = a - {n * Floor(a/n)}
mod(a,n) = a - {n * Floor(a/n)}
Thats means,
也就是说,
mod(11,5) = 11 - {5 * Floor(11/5)} => 11 - {5 * 2}
mod(11,5) = 11 - {5 * Floor(11/5)} => 11 - {5 * 2}
So, mod(11,5) = 1
所以, mod(11,5) = 1
And
和
mod(-11,5) = -11 - 5 * Floor(11/5) => -11 - {5 * (-3)}
mod(-11,5) = -11 - 5 * Floor(11/5) => -11 - {5 * (-3)}
So, mod(-11,5) = 4
所以, mod(-11,5) = 4
Sample code in python 3.0.
python 3.0中的示例代码。
Why Python's Integer Division Floors
I was asked (again) today to explain why integer division in Python returns the floor of the result instead of truncating towards zero like C.
For positive numbers, there's no surprise:
为什么 Python 的整数除法层
我今天(再次)被要求解释为什么 Python 中的整数除法返回结果的下限,而不是像 C 那样向零截断。
对于正数,也就不足为奇了:
>>> 5//2
2
But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity):
但如果其中一个操作数为负,则结果为底,即从零舍入(向负无穷大):
>>> -5//2
-3
>>> 5//-2
-3
This disturbs some people, but there is a good mathematical reason. The integer division operation (//) and its sibling, the modulo operation (%), go together and satisfy a nice mathematical relationship (all variables are integers):
这让一些人感到不安,但有一个很好的数学原因。整数除法运算 (//) 和它的兄弟,模运算 (%),一起满足一个很好的数学关系(所有变量都是整数):
a/b = q with remainder r
such that
以至于
b*q + r = a and 0 <= r < b
(assuming a and b are >= 0).
If you want the relationship to extend for negative a (keeping b positive), you have two choices: if you truncate q towards zero, r will become negative, so that the invariant changes to 0 <= abs(r) < otherwise, you can floor q towards negative infinity, and the invariant remains 0 <= r < b. [update: fixed this para]
In mathematical number theory, mathematicians always prefer the latter choice (see e.g. Wikipedia). For Python, I made the same choice because there are some interesting applications of the modulo operation where the sign of a is uninteresting. Consider taking a POSIX timestamp (seconds since the start of 1970) and turning it into the time of day. Since there are 24*3600 = 86400 seconds in a day, this calculation is simply t % 86400. But if we were to express times before 1970 using negative numbers, the "truncate towards zero" rule would give a meaningless result! Using the floor rule it all works out fine.
Other applications I've thought of are computations of pixel positions in computer graphics. I'm sure there are more.
For negative b, by the way, everything just flips, and the invariant becomes:
(假设 a 和 b >= 0)。
如果您希望关系扩展为负 a(保持 b 为正),您有两种选择:如果将 q 截断为零,r 将变为负数,因此不变量变为 0 <= abs(r) < 否则,您可以将 q 推向负无穷大,并且不变量保持 0 <= r < b。[更新:修正此段]
在数学数论中,数学家总是喜欢后一种选择(参见例如维基百科)。对于 Python,我做出了同样的选择,因为模运算有一些有趣的应用,其中 a 的符号并不有趣。考虑采用 POSIX 时间戳(自 1970 年初以来的秒数)并将其转换为一天中的时间。由于一天有 24*3600 = 86400 秒,所以这个计算只是 t % 86400。但是如果我们用负数表示 1970 年之前的时间,“向零截断”规则将给出一个毫无意义的结果!使用地板规则,一切都很好。
我想到的其他应用是计算计算机图形中的像素位置。我确定还有更多。
顺便说一下,对于负数 b,一切都只是翻转,不变量变成:
0 >= r > b.
So why doesn't C do it this way? Probably the hardware didn't do this at the time C was designed. And the hardware probably didn't do it this way because in the oldest hardware, negative numbers were represented as "sign + magnitude" rather than the two's complement representation used these days (at least for integers). My first computer was a Control Data mainframe and it used one's complement for integers as well as floats. A pattern of 60 ones meant negative zero!
Tim Peters, who knows where all Python's floating point skeletons are buried, has expressed some worry about my desire to extend these rules to floating point modulo. He's probably right; the truncate-towards-negative-infinity rule can cause precision loss for x%1.0 when x is a very small negative number. But that's not enough for me to break integer modulo, and // is tightly coupled to that.
PS. Note that I am using // instead of / -- this is Python 3 syntax, and also allowed in Python 2 to emphasize that you know you are invoking integer division. The / operator in Python 2 is ambiguous, since it returns a different result for two integer operands than for an int and a float or two floats. But that's a totally separate story; see PEP 238.
Posted by Guido van Rossum at 9:49 AM
那么为什么 C 不这样做呢?可能在设计 C 时硬件没有这样做。硬件可能没有这样做,因为在最古老的硬件中,负数表示为“符号+幅度”,而不是当今使用的二进制补码表示(至少对于整数)。我的第一台计算机是 Control Data 大型机,它使用整数和浮点数的补码。60 的模式意味着负零!
Tim Peters 知道所有 Python 的浮点骨架都埋在哪里,他对我希望将这些规则扩展到浮点模数表示了一些担忧。他可能是对的;当 x 是一个非常小的负数时,truncate-towards-negative-infinity 规则会导致 x%1.0 的精度损失。但这对我来说打破整数模是不够的,而且 // 与它紧密耦合。
附注。请注意,我使用 // 而不是 / -- 这是 Python 3 语法,并且在 Python 2 中也允许强调您知道您正在调用整数除法。Python 2 中的 / 运算符是不明确的,因为它为两个整数操作数返回的结果与一个 int 和一个浮点数或两个浮点数的结果不同。但这是一个完全不同的故事;见 PEP 238。
由 Guido van Rossum 于上午 9:49 发布
回答by wkl
Modulus operator, it is used for remainder division on integers, typically, but in Python can be used for floating point numbers.
模运算符,通常用于整数的余数除法,但在 Python 中可用于浮点数。
http://docs.python.org/reference/expressions.html
http://docs.python.org/reference/expressions.html
The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].
%(模)运算符产生第一个参数除以第二个参数的余数。数字参数首先转换为通用类型。零右参数引发 ZeroDivisionError 异常。参数可以是浮点数,例如,3.14%0.7 等于 0.34(因为 3.14 等于 4*0.7 + 0.34。)结果的绝对值严格小于第二个操作数 [2] 的绝对值。
回答by sorpigal
回答by Andrew Jaffe
It is, as in many C-like languages, the remainder or modulo operation. See the documentation for numeric types — int, float, long, complex.
与许多类似 C 的语言一样,它是余数或模运算。请参阅数字类型的文档 — int、float、long、complex。
回答by user225312
The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type.
%(模)运算符产生第一个参数除以第二个参数的余数。数字参数首先转换为通用类型。
3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 = 7
3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 = 7
This is based on operator precedence.
这是基于运算符的优先级。
回答by khachik
回答by Marc Hughes
It's a modulo operation http://en.wikipedia.org/wiki/Modulo_operation
这是一个模运算 http://en.wikipedia.org/wiki/Modulo_operation
http://docs.python.org/reference/expressions.html
http://docs.python.org/reference/expressions.html
So with order of operations, that works out to
因此,按照操作顺序,可以达到
(3+2+1-5) + (4%2) - (1/4) + 6
(3+2+1-5) + (4%2) - (1/4) + 6
(1) + (0) - (0) + 6
(1) + (0) - (0) + 6
7
7
The 1/4=0 because we're doing integer math here.
1/4=0 因为我们在这里做整数数学。
回答by Halil
Python - Basic Operators
http://www.tutorialspoint.com/python/python_basic_operators.htm
Python - 基本运算符
http://www.tutorialspoint.com/python/python_basic_operators.htm
Modulus - Divides left hand operand by right hand operand and returns remainder
模数 - 将左手操作数除以右手操作数并返回余数
a = 10 and b = 20
a = 10 和 b = 20
b % a = 0
b % a = 0


