Python ** 和 % 运算符与大数字的行为
当我将Python解释器a ** b % c与大a(20个数字)b(4个数字)c(20个数字)放入Python解释器时,我发现Python计算它非常快,几乎像pow(a,b,c)一样。我期望 Python 首先计算 a ** b 然后获取结果的模 (%) 的另一种行为,这样的计算将花费更多的时间。
幕后的魔力在哪里?
When I put in Python interpreter a ** b % c with large a (20 figures) b (4 figures) c (20 figures) I saw that Python calculates it pretty fast, almost like pow (a,b,c). I expect another behavior that Python first calculate a ** b then get the modulo (%) of result and such calculation will take significantly more time.
Where is the magic behind the scene?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您在 Python 解释器中输入类似以下内容:
然后会看到几秒钟的等待。然后尝试:
看到不等待,并想知道为什么会有差异,那么您在第一个实例中看到的延迟实际上是您的终端缓冲和等待的时间将您刚刚创建的巨大数字打印到屏幕上。
If you are typing into the Python interpreter something like:
Then seeing a couple of seconds wait. Then trying:
And seeing no wait, and wondering why there is a difference, then the delay that you see in the first instance is actually the time your terminal takes to buffer and print the huge number you just created to the screen.
对于现代计算机来说,20 位数字小得可笑。尝试 2000 个数字,您可能会发现差异。
另外,过去的问题是相关的: Python 如何实现构建的-in 函数 pow()?
20 figures is laughably small on a modern computer. Try 2000 figures and you might see a difference.
Also, this past question is related: How did Python implement the built-in function pow()?
除了 Python 支持任意精度整数并且实现良好之外,幕后并没有什么魔力。它确实计算了 a**b,然后是 %c。
There is no magic behind the scenes, other than Python supports arbitrary-precision integers, and is well-implemented. It really did calculate a**b, then %c.
今天的计算机速度快得惊人,非常复杂的计算似乎可以在短时间内完成。您需要多次重复此类计算才能看到延迟;我会从一百万开始。
Today's computers are amazingly fast, very complicated calculations can occur in what seems like no time at all. You need to repeat such calculations very many times to see the delay; I'd start with a million.