[Tutor] How do I do square roots and exponents?

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 27 Mar 2002 17:26:50 -0800 (PST)


> While toying around in Python, I decided to make a program that
> calculates the hypotenuse. I ran into a problem when I realized that I
> had no idea what the command was for square roots and exponents. Does
> anyone know?

Hi James,

Python has an exponentiation operator using the double stars "**", so you
can do something like this:

###
>>> 2 ** (0.5)
1.4142135623730951
>>> 2 ** 8
256
###


If you'd rather like to use functions to do this, you may also find the
functions in the 'math' module very useful:

    http://www.python.org/doc/lib/module-math.html

###
>>> math.sqrt(2)
1.4142135623730951
>>> math.pow(2, 8)
256.0
###

(Notice that math.pow is defined to return a floating point value.)



Finally, if you know about complex numbers, then you'll definitely want to
look at the cmath module:

    http://www.python.org/doc/lib/module-cmath.html

since it properly supports things like taking the square root of negative
numbers:

###
>>> (-1) ** (0.5)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: negative number cannot be raised to a fractional power
>>> import cmath
>>> cmath.sqrt(-1)
1j
###



Good luck!