Python 数学
Python 拥有一组内置的数学函数,包括一个广泛的数学模块,允许你对数字执行数学任务。
内置数学函数
min()
和 max()
函数可用于查找可迭代对象中的最低或最高值:
实例
x = min(5, 10, 25) y = max(5, 10, 25) print(x) print(y)
abs()
函数返回指定数字的绝对(正)值:
实例
x = abs(-7.25) print(x)
pow(x, y)
函数返回 x 的 y 次幂(xy)的值。
实例
返回 4 的 3 次幂(等同于 4 * 4 * 4):
x = pow(4, 3) print(x)
数学模块
Python 还有一个内置模块叫做 math
,它扩展了数学函数的列表。
要使用它,你必须导入 math
模块:
import math
当你导入了 math
模块后,就可以开始使用该模块的方法和常量了。
例如,math.sqrt()
方法返回一个数字的平方根:
实例
import math x = math.sqrt(64) print(x)
math.ceil()
方法将一个数字向上舍入到最近的整数,而 math.floor()
方法将一个数字向下舍入到最近的整数,并返回结果:
实例
import math x = math.ceil(1.4) y = math.floor(1.4) print(x) # 返回 2 print(y) # 返回 1
math.pi
常量返回 PI 的值(3.14...):
实例
import math x = math.pi print(x)
完整的数学模块参考
在我们的数学模块参考手册中,您将找到属于数学模块的所有方法和常量的完整参考。