Python程序中的日志功能
注意-如果将负数传递给方法,则将出现ValueError。
示例
让我们看一些例子。
# importing math module import math # logarithm with base 3 print(math.log(15, 7))
输出结果
如果运行上述程序,将得到以下结果。
1.3916625094004957
您可以在上述程序中指定所需的任何基值。让我们看看没有任何基本值的相同示例。默认基值为e。
示例
# importing math module import math # logarithm with base e(default) print(math.log(15))
输出结果
如果运行上面的代码,您将得到以下结果。
2.70805020110221
示例
让我们看看如果将负数传递给math.log()方法会发生什么。
# importing math module import math # logarithm with negative number 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 errormath.log2(数字)
如果要计算以2为底的值的对数,则可以使用math.log2()方法。与上述方法相似。让我们看一些例子。
示例
# importing math module import math # logarithm with base 2 print(math.log2(15))
输出结果
如果运行上面的代码,您将得到以下结果。
3.9068905956085187
与math.log方法类似,如果将负数传递给math.log2方法,则会收到错误消息。让我们通过示例来看一下。
示例
# importing math module import math # logarithm with base 2 & negative number 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 errormath.log10(数字)
我们可以使用math.log10方法找到以10 为底的对数。它类似于上面的math.log2方法。让我们看一些例子。
示例
# importing math module import math # logarithm with base 10 print(math.log10(15))
输出结果
如果执行上述程序,将得到以下输出。
1.1760912590556813
尝试将负数传递给math.log10方法。您将收到与上述方法类似的错误。
示例
# importing math module import math # logarithm with base 10 & negative number 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 errormath.log1p(数字)
方法math.log1p(x)将以e为底计算log(1+x)。通过将给定数字加1来计算给定数字的对数。让我们看一些例子。
示例
# importing math module import math # logarithm print(math.log1p(15)) # similar to math.log(16)
输出结果
如果执行上述程序,将得到以下结果。
2.772588722239781
尝试将负数传递给math.log1p方法。我相信您会收到一个错误,就像我们之前看到的那样。
# importing math module import math # logarithm print(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结论
我们已经从math模块中看到了总共四种对数方法。如果将负数传递给本教程中看到的任何对数方法,则会出现错误。您也可以将浮点数传递给方法。尝试使用浮点数执行本教程中看到的示例。
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短