[Tutor] Use of sqrt() from math module

زياد بن عبدالعزيز البات زياد بن عبدالعزيز البات
Sat Dec 1 16:04:15 CET 2007


Matt Smith wrote:
> Hi,
Hi...

> 
> I need to find the square root of a number in a program I am writing. I have 
> imported the 'math' module so I thought I could just call sqrt(x) but I get an 
> error message. Extact from my code and error message below.
> 
> 
> import sys, pygame, math
You import the module "math", not what's _inside_ it!  (This is 
important!  Both ways are okay, but in your case this is important!)

> 
> ...
> 
>      if ypos >= 384 and velocity > 0:
>          impactvel = sqrt(velocity ** 2 + (2 * gravity * (ypos - 384 * 160)))
> 
> ...
Where did you get this thing called "sqrt"?  You didn't define a 
function called "sqrt", did you?

What you need is the "sqrt" function (or method) that lives _inside_ the 
"math" module, and you *must* tell that to Python, otherwise it won't 
find it!

To fix your problem, either:
  - Use: "from math import sqrt".  But this will import the "sqrt"
    function only.  If all you need from the "math" module is this
    function/method then this is fine.  (Though, this is generally not
    good practice, since you'll pollute you name space.  The other
    solution is better.)

  - Or in the line that triggers the error, use: "math.sqrt(..." instead.
    By using "math." you tell Python where to find this thing that's
    called "sqrt", which is what you want.

> 
> 
> Traceback (most recent call last):
>    File "<stdin>", line 32, in <module>
> ValueError: math domain error
I see you sent a new message with the actual error which is:

    Traceback (most recent call last):
      File "<stdin>", line 32, in <module>
    ValueError: math domain error

which confirm what I wrote above.


Hope this helps.
Ziyad.


More information about the Tutor mailing list