Python Forum
Square and Cube roots. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Square and Cube roots. (/thread-9508.html)



Square and Cube roots. - jarrod0987 - Apr-13-2018

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


RE: Square and Cube roots. - nilamo - Apr-13-2018

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.


RE: Square and Cube roots. - casevh - Apr-13-2018

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.