Python math module

2019-04-18 15:46发布

Whenever I try to use any of the built-in functions of Python's exponentiation and logarithms module, I get an error like this:

NameError: name 'sqrt' is not defined

I have tried using math.sqrt(4),sqrt(4) and sqrt(4.0), but none of them work. The exception is pow, which works as it's supposed to. This is really strange and I'm not sure what's wrong.

6条回答
ら.Afraid
2楼-- · 2019-04-18 15:59

In

from math import sqrt

Using sqrt(4) works perfectly well. You need to only use math.sqrt(4) when you just use "import math".

查看更多
萌系小妹纸
3楼-- · 2019-04-18 16:02

You can also import as

from math import *

Then you can use any mathematical function without prefixing math. e.g.

sqrt(4)
查看更多
时光不老,我们不散
4楼-- · 2019-04-18 16:09

pow is built into the language(not part of the math library). The problem is that you haven't imported math.

Try this:

import math
math.sqrt(4)
查看更多
Summer. ? 凉城
5楼-- · 2019-04-18 16:14
import math #imports math module

import math as m
print(m.sqrt(25))

from math import sqrt #imports a method from math module
print(sqrt(25))

from math import sqrt as s
print(s(25))

from math import *
print(sqrt(25))
查看更多
你好瞎i
6楼-- · 2019-04-18 16:17

You need to say math.sqrt when you use it. Or, do from math import sqrt.

Hmm, I just read your question more thoroughly.... How are you importing math? I just tried import math and then math.sqrt which worked perfectly. Are you doing something like import math as m? If so, then you have to prefix the function with m (or whatever name you used after as).

pow is working because there are two versions: an always available version in __builtin__, and another version in math.

查看更多
爷的心禁止访问
7楼-- · 2019-04-18 16:23

add:

import math

at beginning. and then use:

math.sqrt(num)  # or any other function you seem neccessary
查看更多
登录 后发表回答