使用Python的math模块执行常见数学函数
发布时间:2023-06-22 19:11:01
Python是一种高级编程语言,广泛应用于数据科学、人工智能、Web开发等领域。在Python中,math模块提供了各种常见的数学函数,在数据分析、科学计算等领域非常有用。
本文将介绍Python中math模块的常见函数,包括三角函数、指数函数、对数函数、复数函数、常数以及其他常用函数。
## 三角函数
math模块提供了三角函数sin、cos、tan、asin、acos和atan,这些函数的参数和结果都是弧度制。
例如:
import math x = math.sin(math.pi / 2) print(x) # 输出 1.0
## 指数函数和对数函数
math模块提供了指数函数exp和对数函数log、log10和log2。
例如:
import math x = math.exp(2) print(x) # 输出 7.3890560989306495 y = math.log(4) print(y) # 输出 1.3862943611198906 z = math.log10(100) print(z) # 输出 2.0 w = math.log2(16) print(w) # 输出 4.0
## 复数函数
math模块提供了复数函数,包括复数的实部、虚部、模和相位。
例如:
import math x = complex(1, 2) print(math.real(x)) # 输出 1.0 print(math.imag(x)) # 输出 2.0 print(math.sqrt(x.real ** 2 + x.imag ** 2)) # 输出 2.23606797749979 print(math.atan2(x.imag, x.real)) # 输出 1.1071487177940904
## 常数
math模块还提供了一些常用的常数。
例如:
import math print(math.pi) # 输出 3.141592653589793 print(math.e) # 输出 2.718281828459045 print(math.inf) # 输出 inf print(math.nan) # 输出 nan
## 其他常用函数
除了上述函数,math模块还提供了其他常用函数。
例如:
import math x = math.ceil(1.5) print(x) # 输出 2 y = math.floor(1.5) print(y) # 输出 1 z = math.factorial(5) print(z) # 输出 120 w = math.gcd(10, 25) print(w) # 输出 5 v = math.pow(2, 3) print(v) # 输出 8.0 u = math.sqrt(25) print(u) # 输出 5.0
总结:
本文介绍了Python中math模块的常见函数,包括三角函数、指数函数、对数函数、复数函数、常数以及其他常用函数。这些函数在数据分析、科学计算等领域非常有用。
