【python 内置模块】math

2024-01-20 00:00:00

目录:

基本常量与特殊值

math 模块内置了常用的数学常量,方便直接调用。

  • 圆周率 π:math.pi,约为 3.141592653589793;
  • 自然常数 e:math.e,约为 2.718281828459045;
  • 无穷大:math.inf 表示正无穷,-math.inf 表示负无穷;
  • 非数字 (NaN):math.nan 用于表示非法的数值结果;
import math

print(f"π: {math.pi}")
print(f"e: {math.e}")
print(f"正无穷: {math.inf}")
print(f"检查是否为无穷大: {math.isinf(math.inf)}")
print(f"检查是否为 NaN: {math.isnan(math.nan)}")    # math.inf / math.inf = math.nan

求整

这些函数用于处理数值的舍入和表示。

  • 向上取整:math.ceil(x) 返回大于或等于 x 的最小整数。例如,math.ceil(4.2) 返回 5;
  • 向下取整:math.floor(x) 返回小于或等于 x 的最大整数。例如,math.floor(4.8) 返回 4;
  • 截断取整:math.trunc(x) 返回 x 的整数部分(向零取整);
  • math.modf(x) 返回 (小数部分, 整数部分),两者均为浮点数。
import math

print(math.ceil(3.14))   # 输出: 4
print(math.floor(3.99))  # 输出: 3
print(math.trunc(-2.7))  # 输出: -2
print(math.modf(3.1415)) # 输出: (0.1415, 3.0)

求和

math.fsum(iterable) 返回可迭代对象中值的精确浮点求和,能有效减少累加误差。

import math

print(math.fsum([0.1]*10)) # 更精确地输出 1.0

求幂

  • math.pow(x, y) 返回 x 的 y 次幂(浮点数结果);
  • math.exp(x) 返回 e 的 x 次幂;
import math

print(math.pow(2, 3))      # 输出: 8.0
print(math.exp(2))         # 输出: 约 7.389

求平方根

  • math.sqrt(x) 返回 x 的平方根,要求 x ≥ 0;
  • math.isqrt(n) 返回非负整数 n 平方根的向下取整值;
import math

print(math.sqrt(16))       # 输出: 4.0
print(math.isqrt(17))      # 输出: 4

求对数

  • math.log(x) 返回 x 的自然对数(以 e 为底)。
  • math.log(x, base) 返回以 base 为底的对数。
  • math.log10(x) 返回以 10 为底的对数,更高效。
  • math.log2(x) 返回以 2 为底的对数,精度更高。
  • math.log1p(x) 返回 ln(1+x),对于接近 0 的 x 能保持高精度
import math

print(math.log(10))        # 输出: 约 2.302585
print(math.log(100, 10))   # 输出: 2.0

求绝对值

Python 内置函数 abs() 可以直接求绝对值。

math.fabs(x) 返回浮点数的绝对值。与内置 abs() 的区别在于,fabs 始终返回浮点数,且不支持复数。

import math

print(abs(-7.5))                # 输出: 7.5
print(math.fabs(-7.5))          # 输出: 7.5

print(abs(-7))                 # 输出: 7
print(math.fabs(-7))           # 输出: 7.0

求阶乘

import math

print(math.factorial(1))    # 1
print(math.factorial(2))    # 2
print(math.factorial(3))    # 6
print(math.factorial(4))    # 24
print(math.factorial(5))    # 120
print(math.factorial(6))    # 720
print(math.factorial(7))    # 5040
print(math.factorial(8))    # 40320
print(math.factorial(9))    # 362880
print(math.factorial(10))   # 3628800

返回首页

本文总阅读量  次
皖ICP备17026209号-3
总访问量: 
总访客量: