Python 程序中的对数函数
在本教程中,我们将学习 math 模块中的对数函数。我们有四种对数函数变体。Python 在 math 模块中提供了所有这些函数。让我们一一了解它们。
math.log(number, [Base])
math.log(number, [Base]) 方法用于计算任何 Base 的对数。如果我们没有指定任何底数值,那么它将以 e 作为默认底数。
注意 −如果将负数传递给该方法,则会出现 ValueError。
示例
让我们看一些例子。
# 导入数学模块 import math # 以 3 为底的对数 print(math.log(15, 7))
输出
如果运行上述程序,您将得到以下结果。
1.3916625094004957
您可以在上述程序中指定任何所需的底数。让我们看一个没有任何底数的相同示例。默认底数为 e。
示例
# 导入数学模块 import math # 底数为 e 的对数(默认) print(math.log(15))
输出
如果您运行上述代码,您将获得以下结果。
2.70805020110221
示例
让我们看看如果将负数传递给 math.log() 方法会发生什么。
# 导入数学模块 import math # 带负数的对数 print(math.log(-15))
输出
如果你运行上述程序,你将得到以下结果。
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-6-b686fcb806c6> in <module> 3 4 # logarithm with base e(default) ----> 5 print(math.log(-15)) ValueError: math domain error
math.log2(number)
如果要计算以 2 为底的对数,则可以使用 math.log2() 方法。它与上述方法类似。让我们看一些示例。
示例
# 导入 math 模块 import math # 以 2 为底的对数 print(math.log2(15))
输出
如果您运行上述代码,您将获得以下结果。
3.9068905956085187
与 math.log 方法类似,如果我们将负数传递给 math.log2 方法,我们将收到错误。我们通过例子来看一下。
示例
# 导入数学模块 import math # 底数为 2 且为负数的对数 print(math.log2(-15))
输出
如果你通过执行程序来查看输出,那么你会发现我们现在得到的错误和之前得到的错误是一样的。
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-3-8019b45e571f> in <module> 3 4 # logarithm with base 2 & negative number ----> 5 print(math.log2(-15)) ValueError: math domain error
math.log10(number)
我们可以使用 math.log10 方法找到以 10 为底的对数。它与上面的 math.log2 方法类似。让我们看一些例子。
示例
# 导入数学模块 import math # 以 10 为底的对数 print(math.log10(15))
输出
如果执行上述程序,您将获得以下输出。
1.1760912590556813
尝试将负数传递给 math.log10 方法。您将收到与上述方法类似的错误。
示例
# 导入数学模块 import math # 以 10 为底的对数 &负数 print(math.log10(-15))
输出
如果您看到输出,您将收到以下错误。
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-52ac56b802ca> in <module> 3 4 # logarithm with base 10 & negative number ----> 5 print(math.log10(-15)) ValueError: math domain error
math.log1p(number)
方法 math.log1p(x) 将计算以 e 为底的 log(1 + x)。它通过将 1 加到给定数字上来计算该数字的对数。让我们看一些例子。
示例
# 导入数学模块 import math # 对数 print(math.log1p(15)) # 类似于 math.log(16)
输出
如果执行上述程序,您将得到以下结果。
2.772588722239781
尝试将负数传递给 math.log1p 方法。我确信你会得到一个错误,就像我们之前看到的那样。
示例
# 导入数学模块 import math # 对数 打印(math.log1p(-15))
# 导入数学模块导入数学# 对数打印(math.log1p(-15))
输出
由于我们传递给该方法的负数,我们将得到以下错误。
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-15-26016884cb23> in <module> 3 4 # logarithm ----> 5 print(math.log1p(-15)) ValueError: math domain error
结论
我们在数学模块中一共看到了四种对数方法。如果我们将负数传递给本教程中看到的任何对数方法,我们都会得到一个错误。你也可以将浮点数传递给这些方法。尝试用浮点数执行本教程中看到的示例。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

