math.isqrt Keeps Integer Square Roots Exact

math.sqrt converts to float first and loses precision past 2**53, while math.isqrt stays exact on arbitrarily large integers and detects perfect squares.

PythonData Integrity

Code

pythonsnippet
22 lines
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))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

Inside the snippet

math.isqrt Keeps Integer Square Roots Exact is built around the function is_perfect_square.

The file repeats itself only inside for candidate in [10**16, 10**16 + 1, 0, 2].

Using it

Entry signature: def is_perfect_square(value: int) -> bool

The demo output is labeled (math.isqrt =, float loses the +1:), so every printed line maps back to its originating operation.

Import is_perfect_square from the file and call it — the rest of the code is implementation detail.

Key statements

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

Interactive Tools for This Topic

FAQ

Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. Every import resolves inside the standard library — `math`. The file defines `is_perfect_square` at load time.