Python math.log10()方法

Python编程语言提供了一个库,math ,它包含各种数学运算的实现,如三角函数和对数函数。

对数指的是指数化的反函数。简单地说,一个数字的对数a ,就是另一个数字(x )的指数或数字(b ),为了使这个数字a ,应该提高到这个数字的基数。

Logarithm

在这篇文章中,我们将讨论math 模块中的一个方法,即log10() ,它可以计算一个以10 为底的数字的对数。

语法

math.log10(x)

参数

类型 说明
x 浮点数 一个非负的整数和非零的值。

返回

log10() 方法返回一个数字的对数,以10 为底。它等同于math.log(x, 10) ,在某些情况下,比它更精确。

例1:一个数字的以10为底的对数

import math
print(math.log10(0.000001))
print(math.log10(1))
print(math.log10(0.341))
print(math.log10(99999))
print(math.log10(2352.579))

输出:

-6.0
0.0
-0.4672456210075022
4.999995657033466
3.3715442160261846

上面的Python代码计算了0.000001,1,0.341,99999, 和2352.579 的基10对数值。请注意,这些值都是非负数和非零值。

对于范围为(0, 1) 的输入,基10对数会返回负数结果。反之,范围[1, ∞) ,则会得到正的结果。

例2:如果输入的不是一个数字

import math
print(math.log10("this is a string"))

输出:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(math.log10("this is a string"))
TypeError: must be real number, not str

上面的 Python 代码需要一个字符串作为输入。由于log10() 方法期望的是一个数字值,如整数或浮点数,所以它引发了一个TypeError 异常。

例3:如果输入值小于或等于0

import math
print(math.log10(0))

输出:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(math.log10(0))
ValueError: math domain error

上面的Python代码把0 作为输入,由于0 已经超出了log10() 方法的范畴,所以它引发了一个ValueError 异常。

import math
print(math.log10(-99.09))

输出:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(math.log10(-99.09))
ValueError: math domain error

上面的Python代码把小于0-99.09 作为输入,这样的值对log10() 方法来说是无效的,因为它们在它的领域之外。

因此,它引发了一个ValueError 异常。

例四:如果输入是无穷大

import math
print(math.log10(math.inf))

输出:

inf

无限大的对数到基数10 是无限大。

例 5: 如果输入是NaN

import math
print(math.log10(math.nan))

输出:

nan