[Tutor] in-built square root function

Timothy M. Brauch tbrauch@mindless.com
Wed Feb 19 17:16:00 2003


For reasons that have been argued endlessly, you have to try to remember to
hit "reply-all" when replying.  Don't worry, we all forget sometimes.

> fair enough... I'll have write math.sqrt, unless of course I do the "from
> math import *(which i'm guessing is all, everything)

Yes, that is correct.  I think, this is going from memory, you can also do
something like:
from math inport sqrt.  Let me check...

>>> from math import sqrt
>>> sqrt(9)
3.0
>>> math.sqrt(9)
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in ?
    math.sqrt(9)
NameError: name 'math' is not defined
>>>

Yes, so if you do not want to import everything, only part, you can use
"from [module] import [item]"  Then, if you really want to get fancy, you
can try...

>>> from math import sqrt as square_root
>>> square_root(9)
3.0
>>> sqrt(9)
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in ?
    sqrt(9)
NameError: name 'sqrt' is not defined
>>> math.sqrt(9)
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in ?
    math.sqrt(9)
NameError: name 'math' is not defined
>>>

But I have never come across a time when I thought something like this was
necessary.  I'm sure someone much wiser than me can explain better.
> I didn't know that so thanks for clearing it up for me, tim.
>
> However I'm now alittle puzzled to why I didn't have to do the same thing
> with the power operator, which worked fine without write the equevalent:
> "math.pow(x,y)"???

As for why pow works, there is this neat little function called dir.  It is
my friend.  You use it to find out what exists and where it exists.  Like
this...

>>> import math
>>> dir(math)
['__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos',
'cosh', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp',
'log', 'log10', 'modf', 'pi', 'pow', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
>>>

That tells you all the functions that work under the module math.  So, you
can use math.log().  If you are not sure what a command does, you can always
try "print [module].[function].__doc__"
Such as...

>>> print math.log.__doc__
log(x) -> the natural logarithm (base e) of x.

Or even...

>>> print math.__doc__
This module is always available.  It provides access to the
mathematical functions defined by the C standard.

Not everyone uses these __doc__ strings in their code, though, so don't rely
on it.

Back to dir, though.  Look at this...

Let's see what we have so far...

>>> dir()
['__builtins__', '__doc__', '__name__', 'math']

Hmm, so what functions are builtin?

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError',
'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError',
'Exception', 'False', 'FloatingPointError', 'IOError', 'ImportError',
'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented',
'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning',
'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError',
'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',
'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError',
'UnicodeError', 'UserWarning', 'ValueError', 'Warning', 'WindowsError',
'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__',
'abs', 'apply', 'bool', 'buffer', 'callable', 'chr', 'classmethod', 'cmp',
'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict',
'dir', 'divmod', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',
'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input',
'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license',
'list', 'locals', 'long', 'map', 'max', 'min', 'object', 'oct', 'open',
'ord', 'pow', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload',
'repr', 'round', 'setattr', 'slice', 'staticmethod', 'str', 'super',
'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']
>>>

Ah, so the pow function is always available and we do not need to import it.
But, there is no sqrt function builtin.  But, look at this...

>>> print pow.__doc__
pow(x, y[, z]) -> number

With two arguments, equivalent to x**y.  With three arguments,
equivalent to (x**y) % z, but may be more efficient (e.g. for longs).
>>> print math.pow.__doc__
pow(x,y)

Return x**y (x to the power of y).
>>>

So, math.pow() and pow() are two slightly different functions.

Remember, dir() and __doc__ should be your friends.

 - Tim