Exactness of integer square root in Python -


i understand why happening. needed implement integer square root in python (isqrt(64) = 8 = isqrt(80)). convinced naive approach:

def isqrt(n):     return int(math.sqrt(n)) 

was bound fail when n passed square number, assuming python converts floats, performs square root calculation on floats. instance, calling isqrt(13*13) expected after converting floats , calculating sqrt, 12.999999843, after casting integer give 12.

but performed large loops testing values, big , small, , correct result. seem there no need implement special square root integers, after all!

not understanding bothers me, as when supposed work failing. why happening?

there question regarding integer square root in python: integer square root in python

in isqrt() defined there, +0.5 added n, guess included precisely fight issue mentioned expecting, cannot find in specific case.

edit: forgot specify, using python 2.7

using python 2.7 on machine c type long 64 bit integer , c type double implemented 64 bit ieee floating point number yields

>>> import math >>> x = (2<<53) + 1 >>> int(math.sqrt(x*x)) == x false 

i cheated , chose number 64 bit ieee floating point can't represent (but python's integer type can), (2<<53) + 1. python 2.7 computes x*x python 2.7 long integer. (note: distinct c long; python 2.7 can represent 2<<600 integer, c cannot.)

speaking of 2<<600,

>>> import math >>> x = 2<<600 >>> int(math.sqrt(x*x)) == x traceback (most recent call last):   file "<stdin>", line 1, in <module> overflowerror: long int large convert float 

Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -