"""蓝色天空网 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()
本例需在 本地 Python 3.12 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地 Python 3.12
入口文件:projects/python-lab/python-math.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python-math.py,或下载右侧课程工程包。 - 确认本地已准备 本地 Python 3.12。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip