Pythonmath.log10() 函数是数学模块的一个库方法,用来获取数字的基数-2对数;它接受一个数字并返回给定数字的基数-10对数。
Python log10
Python log10() 是一个内置的数学 库函数 ,用于获得任何给定数字的以10为底的对数。要在Python中使用log10()函数,请导入 数学库以使用该函数。log10() 方法返回 x > 0 的以 10 为底的对数。
语法
math.log10(num)
log10()函数需要两个参数。
num-> 我们想找到其以10为底的对数。
返回值
Python log10() 函数返回基数为 10 的对数,特别是给定的数字。
但是如果有任何值作为参数被传递,这个函数会抛出一个ValueError异常。
编程实例
请看下面的代码。
# Importing math library
import math
# initializing values
# positive value
num = 10
print("Logarithm with base 10 of the value ", num, " is: ", math.log10(num))
# Negative number
num = -10
print("Logarithm with base 10 of the value ", num, " is: ", math.log10(num))
输出
Logarithm with base 10 of the value 10 is: 1.0
Traceback (most recent call last):
File "1log10.py", line 12, in <module>
print("Logarithm with base 10 of the value ",num," is: ",math.log10(num))
ValueError: math domain error
在这个程序中,我们初始化了数值,然后计算了以10为底的数字的对数。在下一行中,我们想计算一个负数的对数,但按照规则,程序抛出了ValueError异常。
程序2
请看下面的程序。
# app.py
# Importing math library
import math
# taking input from user values
# positive value
num = int(input("Enter a num to find log10(num): "))
print("Logarithm with base 10 of the value ", num, " is: ", math.log10(num))
输出
Enter a num to find log10(num): 15
Logarithm with base 10 of the value 15 is: 1.1760912590556813
在这个程序中,我们接受了用户的输入并计算了以10为底的对数。
使用列表和元组的 Python log10()
让我们将log10()函数应用于列表和元组,并看看输出结果。 请看下面的代码。
import math
Tup = (1, 2, 11, -4, 5) # Tuple Declaration
Lis = [-1, 2, -11.21, -4, 5] # List Declaration
print('The log10() value of Positive Number = %.2f' % math.log10(1))
print('The log10() value of Positive Decimal = %.2f' % math.log10(2.5))
print('The log10() value of Tuple Item = %.2f' % math.log10(Tup[2]))
print('The log10() value of List Item = %.2f' % math.log10(Lis[4]))
print('The log10() value of Multiple Number = %.2f' % math.log10(2 + 7 - 5))
print('The log10() value of String Number = ', math.log10('Locke and Key'))
输出
python3 app.py
The log10() value of Positive Number = 0.00
The log10() value of Positive Decimal = 0.40
The log10() value of Tuple Item = 1.04
The log10() value of List Item = 0.70
The log10() value of Multiple Number = 0.60
Traceback (most recent call last):
File "app.py", line 13, in <module>
print('The log10() value of String Number = ', math.log10('Locke and Key'))
TypeError: must be real number, not str
如果你传递一个字符串,它会给出TypeError。
结论
Python log10()函数计算以10为底数的给定数字的对数。首先,我们找到不同数据类型的基数10的对数值并显示输出。
另请参见
The postPython log10: How to Use log10() Function in Pythonappeared first onAppDividend.