Python中的数学函数?
从python中执行简单到复杂的数学运算(例如三角运算,对数运算等),我们可能需要使用该math()模块。
pythonmath模块用于访问数学函数。所有math()函数方法都用于整数或实型对象,但不用于复数。
要使用此功能,我们需要将其导入代码中
import math
常数
我们在Python中使用这些常量进行计算-
数字和数字表示
Python提供了不同的函数,用于表示不同形式的数字,例如-
让我们编写一个程序来演示上述数学函数的用法-
#Import math library
import math
#Floor and Ceiling
print('The Floor and Ceiling value of 9.45 are:
' + str(math.ceil(9.45)) + ', ' + str(math.floor(9.45)))
#Copysign
x = 94
y = -27
print('The value of x after copying the sign from y is: ' + str(math.copysign(x, y)))
#Absolute
print('Absolute value of -94 and 54 are: ' + str(math.fabs(-94)) + ', ' + str(math.fabs(54)))
#Fsum & gcd
my_list = [12, 9.25, 89, 3.02, -75.23, -7.2, 6.3]
print('Sum of the elements of the list: ' + str(math.fsum(my_list)))
print('The GCD of 24 and 56 : ' + str(math.gcd(24, 48)))
#isnan
x = float('nan')
if math.isnan(x):
print('It is not a number')
x = float('inf')
#isinf
y = 54
if math.isinf(x):
print('It is Infinity')
#x is not a finite number
print(math.isfinite(x))
#y is a finite number
print(math.isfinite(y))结果
The Floor and Ceiling value of 9.45 are: 10, 9 The value of x after copying the sign from y is: -94.0 Absolute value of -94 and 54 are: 94.0, 54.0 Sum of the elements of the list: 37.13999999999999 The GCD of 24 and 56 : 24 It is not a number It is Infinity False True
幂和对数函数
这些函数用于计算python中与幂和对数有关的不同任务。
示例程序演示上述功能的使用
import math
print("The value of 2^5: " + str(math.pow(2, 5)))
print("Square root of 625: " + str(math.sqrt(625)))
print("The value of 5^e: " + str(math.exp(5)))
print("The value of log(625), base 5: " + str(math.log(625, 5)))
print("The value of log(1024), base 10: " + str(math.log10(1024)))
print("The value of log(1024), base 2: " + str(math.log2(1024)))结果
The value of 2^5: 32.0 Square root of 625: 25.0 The value of 5^e: 148.4131591025766 The value of log(625), base 5: 4.0 The value of log(1024), base 10: 3.010299956639812 The value of log(1024), base 2: 10.0
三角和角转换函数
这些函数用于计算不同的三角运算-
演示上述功能用法的示例程序
import math
print("The value of sin(45 degree): " + str(math.sin(math.radians(45))))
print('The value of cos(pi): ' + str(math.cos(math.pi)))
print("The value of tan(45 degree): " + str(math.tan(math.pi/2)))
print("the angle of sin(0.95504050560):" + str(math.degrees(math.sin(0.95504050560))))结果
The value of sin(45 degree): 0.7071067811865475 The value of cos(pi): -1.0 The value of tan(45 degree): 1.633123935319537e+16 the angle of sin(0.95504050560):46.77267256206895