Exponentials in python x.**y vs math.pow(x, y)

后端 未结 5 2028
臣服心动
臣服心动 2020-11-27 03:32

Which one is more efficient using math.pow or the ** operator? When should I use one over the other?

So far I know that x**y can return an int

5条回答
  •  [愿得一人]
    2020-11-27 04:01

    Just for the protocol: The ** operator calls the built-in pow function which accepts an optional third argument (modulus) if the first two arguments are integer types.

    So, if you intend to calculate remainders from powers, use the built-in function. The math.pow may give you false results:

    import math
    
    base = 13
    exp = 100
    mod = 2
    print math.pow(base, exp) % mod
    print pow(base, exp, mod)
    

    When I ran this, I got 0.0 in the first case which obviously cannot be true, because 13 is odd (and therefore all of it's integral powers). The math.pow version uses limited accuracy which causes an error.

    For sake of fairness, we must say, math.pow can be much faster:

    import timeit
    print timeit.timeit("math.pow(2, 100)",setup='import math')
    print timeit.timeit("pow(2, 100)")
    

    Here is what I'm getting as output:

    0.240936803195
    1.4775809183
    

    Some online examples

    • http://ideone.com/qaDWRd (wrong remainder with math.pow)
    • http://ideone.com/g7J9Un (lower performance with pow on int values)
    • http://ideone.com/KnEtXj (slightly lower performance with pow on float values)

提交回复
热议问题