[Tutor] raising number to a power

Stefan Behnel stefan_ml at behnel.de
Thu Feb 25 19:55:47 CET 2010


Monte Milanuk, 25.02.2010 18:27:
> So... pow(4,4) is equivalent to 4**4, which works on anything - integers,
> floats, etc.

Correct, e.g.

  >>> class Test(object):
  ...   def __pow__(self, other, modulo=None):
  ...       print("POW!")
  ...       return 'tutu'
  ...
  >>> pow(Test(), 4)
  POW!
  'tutu'
  >>> Test() ** 4
  POW!
  'tutu'

But:

  >>> pow(Test(), 4, 5)
  POW!
  'tutu'

The pow() function has a 3-argument form that efficiently calculates the
modulo. There is no operator for that, and, IMHO, that's the raison d'être
for the pow() function in the first place.


> but math.pow(4,4) only works on floats... and in this case it
> converts or interprets (4,4) as (4.0,4.0), hence returning a float: 256.0.
> Is that about right?

Yes. Read the docs:

"""
10.2. math — Mathematical functions

This module is always available. It provides access to the mathematical
functions defined by the C standard.
[...]
The following functions are provided by this module. Except when explicitly
noted otherwise, all return values are floats.
"""

http://docs.python.org/library/math.html

So these are purely numeric and therefore actually pretty fast functions,
which is /their/ raison d'être.

$ python3.1 -m timeit -s 'from math import pow as mpow'  'pow(2,2)'
1000000 loops, best of 3: 0.562 usec per loop
$ python3.1 -m timeit -s 'from math import pow as mpow'  'mpow(2,2)'
10000000 loops, best of 3: 0.18 usec per loop

However:

$ python3.1 -m timeit -s 'from math import pow as mpow'  '2**2'
10000000 loops, best of 3: 0.0247 usec per loop

Stefan



More information about the Tutor mailing list