Serious error in int() function?

blindanagram at nowhere.net blindanagram at nowhere.net
Thu Apr 14 03:59:11 EDT 2016


On 14/04/2016 07:52, ast wrote:
> 
> <martin.spichty at gmail.com> a écrit dans le message de
> news:52f7516c-8601-4252-ab16-bc30c59c8306 at googlegroups.com...
>> Hi,
>>
>> there may be a serious error in python's int() function:
>>
>> print int(float(2.8/0.1))
>>
>> yields
>>
>> 27
>>
>> instead of 28!!
>>
>> I am using Python Python 2.7.6, GCC 4.8.2 on Linux Ubuntu.
>>
>> Is that known?
>> Best,
>> Martin
> 
> 
> I have a similar question, so I post my message here.
> Hope this will not annoy the OP
> 
> 
> Is it sure that the square root of a square number is always
> an integer ?
> 
> I would not like to get a result as 345.99999999
> 
> from math import sqrt
> 
>>>> sqrt(16)
> 4.0
>>>> sqrt(16).is_integer()
> True
> 
>>>> for n in range(1000000):
> ...         if not sqrt(n**2).is_integer():
> ...             print(sqrt(n**2))
> 
> it seems to work ... but does it work for all integers ?

Assuming that IEEE 754 floating point arithmetic is being used, the
sqrt() function will return an exact integer square root for square
integers provided that the square root is exactly representable.

This means that the result will be correct provided it has 53 or less
bits - just short of 16 decimal digits (i.e for square numbers with less
than 32 digits).

With an integer square root function (isqrt), this program:

for exp in count(20):
  v = 2 ** exp - 1
  if isqrt(v) != sqrt(v):
    print(exp, isqrt(v), sqrt(v))
    break

terminates with:

  54 18014398509481983 1.8014398509481982e+16

showing a first error for a 54 bit square root




More information about the Python-list mailing list