← 中文资源

简体中文版本

math.isqrt 精确整数平方根

math.sqrt 先把参数转成 float,超过 2**53 就丢精度;math.isqrt 对任意大整数保持精确,先取整再平方验证也是判别完全平方数的正确做法。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

n          = 10000000000000000200000000000000001
int(sqrt)  = 100000000000000000
math.isqrt = 100000000000000001
float loses the +1: True
10000000000000000 -> True
10000000000000001 -> False
0 -> True
2 -> False

实现说明

底层就是函数 is_perfect_square。 在这里做循环的是 for candidate in [10**16, 10**16 + 1, 0, 2]。

使用要点

  • 跑完文件,输出里会留下标记——math.isqrt =、float loses the +1:。
  • 调用方只需要 is_perfect_square——其余都是内部实现。

常见问题

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。 全部导入都来自标准库:math。 文件在加载时定义 is_perfect_square。

主要签名是 def is_perfect_square(value: int) -> bool

核心语句

def is_perfect_square(value: int) -> bool:
    if value < 0:
        return False
    root = math.isqrt(value)
    return root * root == value

代码示例

import math

# float 平方根在 2**53 之后开始丢精度;isqrt 始终精确
n = (10**17 + 1) ** 2
float_root = int(math.sqrt(n))
exact_root = math.isqrt(n)
print("n          =", n)
print("int(sqrt)  =", float_root)
print("math.isqrt =", exact_root)
print("float loses the +1:", float_root != exact_root)


# 判别完全平方数:先取整再平方验证,避免浮点比较
def is_perfect_square(value: int) -> bool:
    if value < 0:
        return False
    root = math.isqrt(value)
    return root * root == value


for candidate in [10**16, 10**16 + 1, 0, 2]:
    print(candidate, "->", is_perfect_square(candidate))