Python math.log()方法
Python编程语言提供了一个库,math
,它包含各种数学运算的实现,如三角函数和对数函数。
对数指的是指数化的反函数。简单地说,一个数字的对数a
,就是另一个数字(x
)的指数或数字(b
),为了使这个数字a
,应该提高到这个数字的基数。
在这篇文章中,我们将讨论一个方法,log()
,该方法在math
模块中可用,用于计算一个数字的对数。
语法
math.log(x, base)
参数
类型 | 说明 | |
---|---|---|
x |
浮点数 | 一个非负的整数和非零的值。 |
base |
浮点数 | 一个在(0, 1) 和(1, ∞) 范围内的对数基值。 |
返回
log()
方法对不同的参数集返回不同的结果。如果它得到一个参数,例如x
,它返回x
的自然对数或以数学常数为底的对数e
。
如果它得到两个参数,例如x
和base
,它返回x
的对数,以base
或log(x) / log(base)
为底。
logₘn = logₓn / logₓm
where m and n are real numbers greater than zero and x is in the ranges (0, 1) and (1, ∞).
例1:数字的自然对数(一个参数)
import math
print(math.log(0.000001))
print(math.log(1))
print(math.log(0.341))
print(math.log(99999))
print(math.log(2352.579))
输出:
-13.815510557964274
0.0
-1.07587280169862
11.512915464920228
7.7632674521921885
上面的 Python 代码计算了0.000001
,1
,0.341
,99999
, 和2352.579
的自然对数值。请注意,这些值都是非负值和非零值。
对于(0, 1)
范围内的输入,自然对数返回负的结果。反之,范围[1, ∞)
,则会产生正的结果。
例 2: 一个数字的自然对数 (两个参数)
import math
print(math.log(0.000001, math.e))
print(math.log(1, 0.1234))
print(math.log(0.341, 5324))
print(math.log(99999, 0.00001))
print(math.log(2352.579, 1.000001))
输出:
-13.815510557964274
-0.0
-0.1253933900998167
-0.9999991314066932
7763271.334463926
例3:如果输入不是一个数字
import math
print(math.log("this is a string"))
输出:
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(math.log("this is a string"))
TypeError: must be real number, not str
上面的Python代码将一个字符串作为输入。因为log()
方法期望的是一个数值,所以它引发了一个TypeError
。
例四:如果输入小于或等于0
import math
print(math.log(0))
输出:
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(math.log(0))
ValueError: math domain error
上面的Python代码将0
作为输入,由于0
已经超出了log()
方法的范畴,所以它引发了一个ValueError
。
import math
print(math.log(-54.2))
输出:
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(math.log(-54.2))
ValueError: math domain error
上面的Python代码将一个小于0
的值作为输入,而这样的值对于log()
方法来说是无效的输入。因此,它引发了一个ValueError
。
例 5: 如果输入是无穷大
import math
print(math.log(math.inf))
输出:
inf
例 6: 如果输入是NaN
import math
print(math.log(math.nan))
输出:
nan
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。