Russ wrote:
> I have a couple of questions for the number crunchers out there:


Sure, but the answers depend on the underlying Python implementation.
And if we're talking CPython, they also depend on the underlying C
implementation of libm (i.e., math.h).


> Does "pow(x,2)" simply square x, or does it first compute logarithms
> (as would be necessary if the exponent were not an integer)?


The former, using binary exponentiation (quite fast), assuming x is an
int or long.

If x is a float, Python coerces the 2 to 2.0, and CPython's float_pow()
function is called.  This function calls libm's pow(), which in turn
uses logarithms.


> Does "x**0.5" use the same algorithm as "sqrt(x)", or does it use some
> other (perhaps less efficient) algorithm based on logarithms?


The latter, and that algorithm is libm's pow().  Except for a few
special cases that Python handles, all floating point exponentation is
left to libm.  Checking to see if the exponent is 0.5 is not one of
those special cases.

If you're curious, download the Python source, open up
Objects/floatobject.c, and check out float_pow().  The binary
exponentation algorithms are in Objects/intobject:int_pow() and
Objects/longobject:long_pow().

The 0.5 special check (and any other special case optimizations) could,
in theory, be performed in the platform's libm.  I'm not familiar
enough with any libm implementations to comment on whether this is ever
done, or if it's even worth doing... though I suspect that the 0.5 case
is not.

Hope that helps,
--Ben

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to