Python之math模块

1. python的math模块介绍

Python的math模块是一个标准库,提供了一些数学函数和常量,涵盖了数学中的许多常见问题。

2. 数学常量

math模块提供了以下数学常量:

  • math.e:自然常数e,约等于2.718
  • math.pi:圆周率π,约等于3.1416
  • math.tau:τ=2π,6.2831
import math

print(math.e)   # 2.718281828459045
print(math.pi)  # 3.141592653589793
print(math.tau) # 6.283185307179586

3. 数学函数

以下是math模块提供的一些数学函数:

  • abs(x):返回参数x的绝对值。
  • ceil(x):返回不小于参数x的最小整数。
  • floor(x):返回不大于参数x的最大整数。
  • sqrt(x):返回参数x的平方根。
  • pow(x, y):返回x的y次方。
  • exp(x):返回e的x次方。
import math

x = -10.2
y = 2.5

print(math.abs(x))    # 10.2
print(math.ceil(x))   # -10
print(math.floor(x))  # -11
print(math.sqrt(y))   # 1.5811388300841898
print(math.pow(y, 3)) # 15.625
print(math.exp(y))    # 12.182493960703473

4.三角函数

以下是math模块提供的一些三角函数:

  • sin(x):返回参数x的正弦值,x为弧度。
  • cos(x):返回参数x的余弦值,x为弧度。
  • tan(x):返回参数x的正切值,x为弧度。
  • asin(x):返回参数x的反正弦值,返回值为弧度。
  • acos(x):返回参数x的反余弦值,返回值为弧度。
  • atan(x):返回参数x的反正切值,返回值为弧度。
import math

x = math.pi / 4.0

print(math.sin(x))  # 0.7071067811865475
print(math.cos(x))  # 0.7071067811865476
print(math.tan(x))  # 0.9999999999999999
print(math.asin(x)) # 0.9033391107665127
print(math.acos(x)) # 0.6674572160283838
print(math.atan(x)) # 0.6657737500283538

5. 对数函数

以下是math模块提供的一些对数函数:

  • log(x[, base]):返回参数x的自然对数,如果指定了base,则返回以base为底的对数。
  • log10(x):返回参数x的以10为底的对数。
  • log2(x):返回参数x的以2为底的对数。
import math

x = 1000.0

print(math.log(x))      # 6.907755278982137
print(math.log(x, 10))  # 3.0
print(math.log(x, 2))   # 9.965784284662087

6.其他函数

以下是math模块提供的一些其他函数: -

  • degrees(x):弧度转角度
  • radians(x):角度转弧度
import math

x = math.pi / 2.0

print(math.degrees(x))  # 90.0
print(math.radians(90)) # 1.5707963267948966
posted @ 2023-03-19 22:46  我不知道取什么名字好  阅读(82)  评论(0编辑  收藏  举报