Python数学模块

问题描述 投票:20回答:7

每当我尝试使用Python的exponentiation和logarithms模块的任何内置函数时,我都会收到如下错误:

NameError: name 'sqrt' is not defined

我尝试过使用math.sqrt(4)sqrt(4)sqrt(4.0),但它们都没有用。唯一的例外是pow,它按照预期的方式工作。这真的很奇怪,我不确定是什么问题。

python math module import logarithm
7个回答
51
投票

pow内置于语言中(不属于数学库)。问题是你没有输入数学。

试试这个:

import math
math.sqrt(4)

14
投票

您也可以导入为

from math import *

然后你可以使用任何数学函数而不用数学前缀。例如

sqrt(4)

5
投票

加:

import math

开始时。然后使用:

math.sqrt(num)  # or any other function you seem neccessary

2
投票

当你使用它时,你需要说math.sqrt。或者,做from math import sqrt

嗯,我只是更彻底地阅读你的问题....你如何进口math?我只是尝试了import math然后math.sqrt完美的工作。你在做像import math as m这样的事吗?如果是这样,那么你必须在函数前加上m(或者你在as之后使用的任何名称)。

pow正在工作,因为有两个版本:__builtin__中的始终可用版本,以及math中的另一个版本。


1
投票
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))

0
投票

来自math import sqrt

使用sqrt(4)非常有效。当你只使用“import math”时,你只需要使用math.sqrt(4)。


0
投票

导入数学为m a = int(输入(“输入否”))print(m.sqrt(a))

来自math import sqrt print(sqrt(25))

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

来自math import * print(sqrt(25))

一切都有效。

© www.soinside.com 2019 - 2024. All rights reserved.