Am 14.04.16 um 08:52 schrieb ast:
Is it sure that the square root of a square number is always
an integer ?

Mathematically, yes.

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 ?


No. sqrt uses floating point arithmetic, which in Python uses IEEE 64 bit floating point math (the C double type). This has 53 bits of mantissa, that means if your square is larger than 2^53, and does not contain only powers of two in addition, the square root will be off.

But the good news is that there are integer square root algorithms. Since Python supports arbitrary large integers, you can use one of those.

An isqrt implementation wa discussed here recently:

https://groups.google.com/forum/#!topic/comp.lang.python/70D5yVj7mIY

        Christian
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to