[Tutor] hypotenuse
John Fouhy
john at fouhy.net
Fri Mar 14 02:45:40 CET 2008
On 14/03/2008, Scott Kerr <uwskerr at gmail.com> wrote:
> Hello,
>
> I am also new to python and programming. Since two have already posted that
> you need to import math modules to do square roots, I am curious.
>
> Why can you not use something like:
>
> >>>hypotenuse = hyp_squared**1/2
>
> or
>
> >>>hypotenuse = hyp_squared**.5
Hmm, good question :-)
I suppose there is no strong reason. The best I can offer is that for
many people, the concept of a square root is more accessible through
the name "sqrt", whereas fractional exponentiation requires a brief
brain pause while they remember what it means.
Hence Luke and I, who are familiar with the math module, more easily
think "math.sqrt" than "x**0.5". And the same benefit might apply to
a hypothetical reader of the code.
Interestingly, using x**0.5 seems faster too:
Morpork:~ repton$ python -m timeit -s "x = 2" "y = x**0.5"
1000000 loops, best of 3: 0.298 usec per loop
Morpork:~ repton$ python -m timeit -s "import math" -s "x = 2" "y =
math.sqrt(x)"
1000000 loops, best of 3: 0.487 usec per loop
Morpork:~ repton$ python -m timeit -s "import math" -s "m = math.sqrt"
-s "x = 2" "y = m(x)"
1000000 loops, best of 3: 0.371 usec per loop
though the advantage vanishes if you need a function:
Morpork:~ repton$ python -m timeit -s "m = lambda x: x**0.5" -s "x =
2" "y = m(x)"
1000000 loops, best of 3: 0.526 usec per loop
(if you've never seen the timeit module before, it's a good way to
benchmark short snippets of code. The -s option is used for
non-benchmarked startup code. So, for example, ' python -m timeit -s
"import math" -s "x = 2" "y = math.sqrt(x)"' means "import math, set x
to 2, then run y=math.sqrt(x) many many times to estimate its
performance". From the interpreter, type 'import timeit;
help(timeit)' for more information)
--
John.
More information about the Tutor
mailing list