Python Forum

Full Version: Square and Cube roots.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
What is an easy way to get the square or cube root of a number and not get the part after the decimal? I just want the whole number or maybe the whole number and a remainder. No decimals. Is that possible?
Thanks
Use int() to ignore the non-integer values:
>>> x = 9.4392
>>> x
9.4392
>>> int(x)
9
>>> y = 3.8743
>>> y
3.8743
>>> int(y)
3
To get a root, use a fraction as an exponent. The square root of 9 is 3. 3 squared is 9. 3**2 is 9. 9**(1/2) is 3.
The cube root of 27 is 3. 3 cubed is 27. 3**3 is 27. 27**(1/3) is 3.
If you are willing to install an external library, or are working with large integer numbers, you should look at gmpy2

>>> import gmpy2
>>> gmpy2.iroot_rem(128,3)
(mpz(5), mpz(3))
iroot_rem(x,N) returns the integer part of the N-th of x and the remainder.