Python math:实数函数、组合与浮点精度
按返回类型和输入范围选择数学函数,并用独立算例验证角度、距离、组合和浮点边界。
学完这一章,你能够
- 按返回类型和输入范围选择数学函数,并用独立算例验证角度、距离、组合和浮点边界。
根据输入与返回类型选择函数
import math 后可以用 math.sqrt、math.sin 或 math.log。dir(math) 可查看当前解释器实际提供的名字,名称清单会随版本变化。基本四则运算可直接写表达式,开根、三角函数和稳定求和适合使用对应的标准库函数。
许多实数运算返回 float。ceil、floor、trunc、isqrt、factorial、comb 等对普通数值输入返回整数,isclose、isfinite、isinf、isnan 返回布尔值,frexp 和 modf 返回元组。prod 和 sumprod 的结果类型取决于输入。负数的平方根在实数域会报错,需要复数结果时可用 cmath.sqrt。
从几何角度理解计算
sin、cos 和 tan 接收弧度。可用 radians 将角度转为弧度,再用 degrees 转回。atan2(y, x) 利用 x 和 y 的符号判断象限。pi 是圆周长与直径之比,tau 是 2π,也就是圆周长与半径之比。
hypot 测量向量长度,dist 测量两点的距离,输入点须等维。取非负整数平方根的下取整时用 isqrt。精确整数幂可用 **。math.pow 转成浮点后再计算,适用于能接受浮点结果的实数运算。
区分取整、余数与浮点误差
ceil 向正无穷取整,floor 向负无穷取整,trunc 向零截断。对 -3.4 三者分别得到 -3、-4、-3。整数和浮点都可用 %,浮点还可用 fmod 或 remainder,它们选择商或余数符号的规则各有不同。
x 很小时,直接算 exp(x)-1 或 log(1+x) 会丢失信息,可改用 expm1 和 log1p。fsum 可减少连加误差。检查近似值用 isclose 并给出符合量纲的容差,接近零时特别注意 abs_tol。用 isnan 判断 NaN,用 isinf、isfinite 区分无穷和有限值。
frexp 和 ldexp 连接尾数、二进制指数和原值。modf 返回有符号的浮点小数部分与整数部分。nextafter 沿目标方向前进可表示的浮点步长,ulp 表示所在尺度的最小有效单位。它们能说明相邻浮点值的间隔会随数值尺度变化。
用整数函数处理计数和版本兼容
comb 计算无序选择,perm 计算有序选择,factorial 计算全排列个数。gcd 和 lcm 处理整除关系。prod 计算连乘,sumprod 在两个可迭代对象等长时逐项相乘再求和。不要用浮点阶乘结果代替精确整数计数。
comb、perm、isqrt、dist 和 prod 自 Python 3.8 提供。lcm、nextafter 和 ulp 自 3.9 提供,cbrt 和 exp2 自 3.11 提供。sumprod 和 nextafter 的 steps 参数需要 3.12。现代 factorial 要求整数,早期版本曾接受数值上等于整数的浮点数。
下载本站源码和核对模块到同一目录,运行 python python-math.py。实验使用 Python 3.12,分别核对整数精确值、浮点容差、定义域错误及非有限数。程序也会输出实际运行版本与数值。
所需环境:本地 Python 3.12
当前源码 SHA256:e8fb85d9651d8224cbd3d25c15585a4b6a28919d39971a8afe50df65e236a401
所需环境:本地 Python 3.12
当前源码 SHA256:4b803aca5654715f4eabe59fc1b3ada5a00337edbe21e80d5009c5195b2c8b4a
常量与非有限值
| 名称或调用 | 作用与条件 |
|---|---|
| math.e | 自然对数的底,浮点近似值。 |
| math.inf | 正无穷浮点值。用 isinf 或 isfinite 判断。 |
| math.nan | 非数浮点值。用 isnan 判断,不能用 == 测是否为 NaN。 |
| math.pi | 圆周长与直径之比的浮点近似值。 |
| math.tau | 圆周长与半径之比,等于 2π 的浮点近似值。 |
三角、双曲与角度单位
| 名称或调用 | 作用与条件 |
|---|---|
| math.acos(x) | 实数输入 -1 到 1,返回 0 到 π 的反余弦弧度。 |
| math.acosh(x) | 实数输入至少为 1,返回反双曲余弦。 |
| math.asin(x) | 实数输入 -1 到 1,返回 -π/2 到 π/2 的反正弦弧度。 |
| math.asinh(x) | 返回实数的反双曲正弦。 |
| math.atan(x) | 返回反正切弧度,有限实数输入的结果在 -π/2 与 π/2 之间。 |
| math.atan2(y, x) | 返回坐标 (x, y) 的方向角,利用两个参数的符号确定象限。 |
| math.atanh(x) | 有限实数结果要求 -1 < x < 1。 |
| math.cos(x) | 返回弧度角 x 的余弦。 |
| math.cosh(x) | 返回 x 的双曲余弦。 |
| math.degrees(x) | 弧度转换为角度。 |
| math.radians(x) | 角度转换为弧度。 |
| math.sin(x) | 返回弧度角 x 的正弦。 |
| math.sinh(x) | 返回 x 的双曲正弦。 |
| math.tan(x) | 返回弧度角 x 的正切。接近 π/2 时对输入误差敏感。 |
| math.tanh(x) | 返回 x 的双曲正切。 |
根、指数与对数
| 名称或调用 | 作用与条件 |
|---|---|
| math.exp(x) | 计算自然指数 e 的 x 次幂。 |
| math.expm1(x) | 计算 e 的 x 次幂减 1。x 接近零时可减少相消误差。 |
| math.log(x[, base]) | 省略底数时取自然对数;给定底数时计算换底,底数为正且不等于 1。 |
| math.log10(x) | 正数的常用对数,底数为 10。 |
| math.log1p(x) | 计算 ln(1+x),适合接近零的 x;实数域 x > -1。 |
| math.log2(x) | 正数的二进制对数,底数为 2。 |
| math.pow(x, y) | 先把参数转为浮点再求幂。精确整数幂使用 ** 或内置 pow。 |
| math.sqrt(x) | 返回非负实数的浮点平方根,负实数需改用 cmath.sqrt。 |
| math.cbrt(x) | 实数立方根,负值也有实数结果。 |
| math.exp2(x) | 计算 2 的 x 次幂并返回浮点值。 |
取整、余数与浮点边界
| 名称或调用 | 作用与条件 |
|---|---|
| math.ceil(x) | 取不小于 x 的最小整数。 |
| math.copysign(x, y) | 取 x 的大小和 y 的符号,包括支持负零的平台。 |
| math.fabs(x) | 返回浮点绝对值。整数需要保留精度时可用内置 abs。 |
| math.floor(x) | 取不大于 x 的最大整数。 |
| math.fmod(x, y) | 浮点余数与被除数同号或为零。有限非零除数下结果大小小于除数绝对值。 |
| math.frexp(x) | 返回浮点尾数和整数指数 (m, e),非零有限 x 满足 x = m × 2**e。 |
| math.fsum(iterable) | 用更稳定的浮点求和方式得到浮点结果。 |
| math.isclose(a, b, *, rel_tol=1e-9, abs_tol=0.0) | 按相对和绝对容差判断是否接近,靠近 0 时常要给 abs_tol。 |
| math.isfinite(x) | 有限数返回 True,无穷和 NaN 返回 False。 |
| math.isinf(x) | 正负无穷返回 True。 |
| math.isnan(x) | 仅 NaN 返回 True。 |
| math.ldexp(x, i) | 计算 x × 2**i,可还原 frexp 返回的有限值。 |
| math.remainder(x, y) | 商取最接近整数后计算余数,恰好居中时选偶数。 |
| math.trunc(x) | 丢弃小数部分,向零取整。 |
| math.modf(x) | 分离小数部分与整数部分,两个结果都是带原符号的浮点数。 |
| math.nextafter(x, y, steps=1) | 从 x 沿 y 方向移动若干个可表示的浮点步长,steps 为 0 时保留 x。 |
| math.ulp(x) | 返回 x 的最小有效浮点单位。0 的结果是最小正次正规浮点数。 |
组合、整数与距离
| 名称或调用 | 作用与条件 |
|---|---|
| math.comb(n, k) | 从 n 个不同元素无序选 k 个。非负整数参数,k 大于 n 时为 0。 |
| math.dist(p, q) | 等维坐标序列或可迭代对象的欧氏距离,返回浮点数。 |
| math.factorial(n) | 计算非负整数阶乘。负数引发 ValueError,现代版本不接受浮点数。 |
| math.gcd(*integers) | 返回整数的非负最大公约数。无参数为 0。 |
| math.hypot(*coordinates) | 返回向量的欧氏长度,支持多个坐标。 |
| math.isqrt(n) | 非负整数平方根的下取整,直接保持整数精度。 |
| math.perm(n, k=None) | 从 n 个不同元素有序选 k 个。k 省略时取 n,k 大于 n 时为 0。 |
| math.prod(iterable, *, start=1) | 连乘可迭代对象中的值。输入为空时返回 start。 |
| math.lcm(*integers) | 返回整数的非负最小公倍数,任一参数为 0 时为 0。无参数为 1。 |
| math.sumprod(p, q) | 两个等长可迭代对象逐项相乘再相加。长度不符时引发 ValueError。 |
统计与特殊函数
| 名称或调用 | 作用与条件 |
|---|---|
| math.erf(x) | 误差函数,可用来表示正态分布的累计概率。 |
| math.erfc(x) | 互补误差函数。尾部概率很小时可避免直接从 1 减去 erf 的消减误差。 |
| math.gamma(x) | 计算 Gamma 函数。正整数 n 的值等于 (n-1)!。 |
| math.lgamma(x) | 计算 ln(abs(Gamma(x)))。负的非整数也可能有有效实数结果。 |
本章自编源码与运行范围
"""蓝色天空网 mbsky.com · math 实数与浮点边界实验。"""
import cmath
import math
from pathlib import Path
import platform
import sys
sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks
def near(check, name, actual, expected, *, rel=2e-14, absolute=0.0):
tolerance = max(absolute, abs(expected) * rel)
error = abs(actual - expected)
if type(actual) is not float or not error <= tolerance:
raise AssertionError((name, actual, expected, tolerance))
check.records.append(dict(name=name, actual=actual, expected=expected,
absolute_error=error, tolerance=tolerance, passed=True))
def constants(check):
check.eq("imported math exposes documented names",
all(name in dir(math) for name in ("sqrt", "pi", "comb", "sumprod", "nextafter")), True)
check.eq("basic arithmetic operators", (5+2, 5-2, 5*2, 5/2), (7, 3, 10, 2.5))
near(check, "e", math.e, 2.718281828459045)
check.eq("inf", (type(math.inf).__name__, math.isinf(math.inf), math.inf > 0), ("float", True, True))
check.eq("nan", (type(math.nan).__name__, math.isnan(math.nan), math.nan == math.nan), ("float", True, False))
near(check, "pi", math.pi, 3.141592653589793)
check.eq("tau", math.tau, 2 * math.pi)
def angles(check):
near(check, "acos", math.acos(-0.5), 2 * math.pi / 3)
near(check, "asin", math.asin(-0.5), -math.pi / 6)
near(check, "atan", math.atan(1), math.pi / 4)
near(check, "atan2", math.atan2(1, -1), 3 * math.pi / 4)
near(check, "sin", math.sin(math.pi / 6), 0.5)
near(check, "cos", math.cos(math.pi / 3), 0.5)
near(check, "tan", math.tan(-math.pi / 4), -1.0)
near(check, "degrees", math.degrees(math.pi / 6), 30.0)
near(check, "radians", math.radians(120), 2 * math.pi / 3)
near(check, "sinh", math.sinh(math.log(2)), 0.75)
near(check, "cosh", math.cosh(math.log(2)), 1.25)
near(check, "tanh", math.tanh(math.log(2)), 0.6)
near(check, "asinh", math.asinh(-0.75), -math.log(2))
near(check, "acosh", math.acosh(1.25), math.log(2))
near(check, "atanh", math.atanh(0.6), math.log(2))
check.raises("acos rejects value outside its real domain", ValueError, lambda: math.acos(1.5))
check.raises("asin rejects value outside its real domain", ValueError, lambda: math.asin(-1.5))
check.raises("acosh rejects values below one", ValueError, lambda: math.acosh(0.5))
check.raises("atanh excludes the endpoints", ValueError, lambda: math.atanh(1.0))
def powers(check):
check.eq("sqrt", math.sqrt(49), 7.0)
check.raises("sqrt rejects negative real input", ValueError, lambda: math.sqrt(-9))
check.eq("complex square root uses cmath", cmath.sqrt(-9), 3j)
near(check, "cbrt", math.cbrt(-27), -3.0)
check.eq("pow", (math.pow(3, 4), 3**4), (81.0, 81))
check.eq("exp2", math.exp2(-3), 0.125)
near(check, "exp", math.exp(2), 7.38905609893065)
check.raises("exp overflow is explicit", OverflowError, lambda: math.exp(1000))
tiny = 1e-16
near(check, "expm1", math.expm1(tiny), tiny)
check.eq("naive exp minus one loses small input", math.exp(tiny)-1, 0.0)
near(check, "log", math.log(8, 2), 3.0)
near(check, "natural logarithm default base", math.log(math.e), 1.0)
check.raises("log rejects zero", ValueError, lambda: math.log(0))
check.eq("log10", math.log10(1000), 3.0)
check.eq("log2", math.log2(2**20), 20.0)
near(check, "log1p", math.log1p(tiny), tiny)
check.eq("naive one plus small input rounds to one", math.log(1+tiny), 0.0)
check.raises("log1p excludes minus one", ValueError, lambda: math.log1p(-1))
def integers_geometry(check):
check.eq("factorial", (math.factorial(0), math.factorial(6)), (1, 720))
check.raises("factorial rejects a negative integer", ValueError, lambda: math.factorial(-1))
check.raises("factorial rejects integral float in modern Python", TypeError, lambda: math.factorial(6.0))
check.eq("comb", (math.comb(6, 2), math.comb(6, 0), math.comb(2, 6)), (15, 1, 0))
check.eq("perm", (math.perm(6, 2), math.perm(6), math.perm(2, 6)), (30, 720, 0))
check.raises("comb rejects negative count", ValueError, lambda: math.comb(6, -1))
check.raises("perm rejects a floating count", TypeError, lambda: math.perm(6, 2.0))
check.eq("gcd", (math.gcd(0, -18, 24), math.gcd()), (6, 0))
check.eq("lcm", (math.lcm(-6, 4, 10), math.lcm(0, 4), math.lcm()), (60, 0, 1))
n = 10**50 + 3
root = math.isqrt(n*n + n)
check.eq("isqrt", (root, root*root <= n*n+n < (root+1)**2), (n, True))
check.raises("isqrt rejects negative input", ValueError, lambda: math.isqrt(-1))
check.eq("prod", (math.prod([2, 3, 4], start=2), math.prod([], start=5)), (48, 5))
check.eq("sumprod", math.sumprod(iter([2, 3, 4]), iter([7, 2, 3])), 32)
check.eq("sumprod preserves exact integer calculation", math.sumprod([10**40, 2], [3, 4]), 3*10**40+8)
check.raises("sumprod rejects unequal lengths", ValueError, lambda: math.sumprod([2], [1, 3]))
check.eq("dist", math.dist(iter([1, 2, 3]), iter([4, 6, 3])), 5.0)
check.raises("dist rejects mismatched dimensions", ValueError, lambda: math.dist([1], [2, 3]))
check.eq("hypot", (math.hypot(2, 3, 6), math.hypot()), (7.0, 0.0))
def floats(check):
check.eq("ceil", (math.ceil(-3.4), math.ceil(3.4)), (-3, 4))
check.eq("floor", (math.floor(-3.4), math.floor(3.4)), (-4, 3))
check.eq("trunc", (math.trunc(-3.4), math.trunc(3.4)), (-3, 3))
check.eq("fabs", math.fabs(-7), 7.0)
check.eq("copysign", math.copysign(7, -0.0), -7.0)
check.eq("fmod", (math.fmod(-7.0, 2.0), -7.0 % 2.0), (-1.0, 1.0))
check.eq("remainder", (math.remainder(7, 2), math.remainder(5, 2)), (-1.0, 1.0))
check.raises("remainder rejects zero divisor", ValueError, lambda: math.remainder(2, 0))
check.eq("frexp", (math.frexp(18), math.frexp(0)), ((0.5625, 5), (0.0, 0)))
check.eq("ldexp", math.ldexp(*math.frexp(18)), 18.0)
check.eq("modf", math.modf(-3.25), (-0.25, -3.0))
check.eq("fsum", math.fsum([1e16, 1, -1e16]), 1.0)
check.eq("isclose", (math.isclose(1.0, 1.00001, rel_tol=1e-4),
math.isclose(0.0, 1e-12), math.isclose(0.0, 1e-12, abs_tol=1e-11),
math.isclose(math.nan, math.nan), math.isclose(math.inf, math.inf)),
(True, False, True, False, True))
check.eq("isfinite", tuple(math.isfinite(x) for x in (0.0, math.inf, math.nan)), (True, False, False))
check.eq("isinf", tuple(math.isinf(x) for x in (-math.inf, math.inf, math.nan)), (True, True, False))
check.eq("isnan", tuple(math.isnan(x) for x in (math.nan, math.inf, 0.0)), (True, False, False))
check.eq("nextafter", (math.nextafter(1, 2).hex(), math.nextafter(1, 2, steps=2).hex(),
math.nextafter(1, 2, steps=0)),
("0x1.0000000000001p+0", "0x1.0000000000002p+0", 1.0))
check.raises("nextafter rejects negative steps", ValueError, lambda: math.nextafter(1, 2, steps=-1))
check.eq("ulp", (math.ulp(1.0), math.ulp(-1.0), math.ulp(0.0), math.ulp(math.inf)),
(2**-52, 2**-52, float.fromhex("0x0.0000000000001p-1022"), math.inf))
check.eq("ulp preserves NaN classification", math.isnan(math.ulp(math.nan)), True)
def special_functions(check):
near(check, "erf", math.erf(1), 0.8427007929497149)
near(check, "erfc", math.erfc(1), 0.15729920705028513)
check.eq("erfc retains a positive tail when subtracting loses it",
(math.erfc(8) > 0, 1 - math.erf(8)), (True, 0.0))
near(check, "gamma", math.gamma(6), 120.0)
near(check, "gamma negative half", math.gamma(-0.5), -3.544907701811032)
near(check, "lgamma", math.lgamma(-0.5), 1.2655121234846454)
check.raises("gamma rejects a pole", ValueError, lambda: math.gamma(-1))
def main():
check = Checks()
constants(check)
angles(check)
powers(check)
integers_geometry(check)
floats(check)
special_functions(check)
check.finish("python-math", python=platform.python_version(), platform=platform.platform(),
float_mantissa_bits=sys.float_info.mant_dig, float_radix=sys.float_info.radix,
scope="CPython 3.12 with independently expected exact results and numeric tolerances")
if __name__ == "__main__":
main()
所需环境:CPython 3.12 with independently expected exact results and numeric tolerances
当前源码 SHA256:e8fb85d9651d8224cbd3d25c15585a4b6a28919d39971a8afe50df65e236a401
当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。
常见错误与边界
- 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。
练习与解答
使用本站实例修改一个条件,先写下预期,再实际运行。
展开参考解答
比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。