计算功率转速(在python) [英] Speed of calculating powers (in python)

查看:244
本文介绍了计算功率转速(在python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇,为什么它是如此之快的繁殖,而不是采取在python权力(虽然从我读过这很可能是在许多其他语言也如此)。例如它的速度更快做

I'm curious as to why it's so much faster to multiply than to take powers in python (though from what I've read this may well be true in many other languages too). For example it's much faster to do

x*x

x**2

我想**操作是更通用,也可以处理分数的权力。但如果这就是为什么它这么慢得多,为什么没有进行检查的int指数,然后只是做乘法?

I suppose the ** operator is more general and can also deal with fractional powers. But if that's why it's so much slower, why doesn't it perform a check for an int exponent and then just do the multiplication?

编辑:下面是一些例子code我想...

Here's some example code I tried...

def pow1(r, n):
  for i in range(r):
    p = i**n

def pow2(r, n):
  for i in range(r):
    p = 1
    for j in range(n):
      p *= i

现在,POW2仅仅是一个简单的例子,并且显然不是优化!
但即便如此我发现,使用N = 2和R = 1,000,000,然后POW1需要设置在2500ms〜和POW2需要〜1700ms。
 我承认,对于n值很大,那么POW1没有什么比POW2快得多。但是,这不是太奇怪了。

Now, pow2 is just a quick example and is clearly not optimised!
But even so I find that using n = 2 and r = 1,000,000, then pow1 takes ~ 2500ms and pow2 takes ~ 1700ms.
I admit that for large values of n, then pow1 does get much quicker than pow2. But that's not too surprising.

推荐答案

基本上天真的乘法是O(n)具有非常低的常数因子。取功率为O(log n)的具有较高常数因子(有特殊情况需要被测试...分数指数,负指数等)。编辑:只是要清楚,这是O(n),其中n是指数

Basically naive multiplication is O(n) with a very low constant factor. Taking the power is O(log n) with a higher constant factor (There are special cases that need to be tested... fractional exponents, negative exponents, etc) . just to be clear, that's O(n) where n is the exponent.

当然,天真的做法会更快对于小的n,你只有真正实现指数运算的一小部分,以便您的常数因子可以忽略不计。

Of course the naive approach will be faster for small n, you're only really implementing a small subset of exponential math so your constant factor is negligible.

这篇关于计算功率转速(在python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆