1import struct
2
3def isqrt(number):
4 threehalfs = 1.5
5 x2 = number * 0.5
6 y = number
7
8 packed_y = struct.pack('f', y)
9 i = struct.unpack('i', packed_y)[0] # treat float's bytes as int
10 i = 0x5f3759df - (i >> 1) # arithmetic with magic number
11 packed_i = struct.pack('i', i)
12 y = struct.unpack('f', packed_i)[0] # treat int's bytes as float
13
14 y = y * (threehalfs - (x2 * y * y)) # Newton's method
15 return y