Accuracy of math.sqrt(), was Re: Serious error in int() function?

Peter Otten __peter__ at web.de
Thu Apr 14 03:46:53 EDT 2016


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

Well, you "annoy" me ;)

Would you please always take the time to come up with a subject line that 
matches your question. You should also start a new thread.

> 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 ?

Even if you get an integer it may not be the one you are expecting:

>>> sqrt((10**22)**2) == 10**22
True
>>> sqrt((10**23)**2) == 10**23
False
>>> sqrt((10**23)**2).is_integer()
True
>>> int(sqrt((10**23)**2))
99999999999999991611392





More information about the Python-list mailing list