So I have to make a code to check whether or not a number is a perfect cube, but for some reason for any cube greater than 27, it says it's root is x.99999999. (i.e. it returns 64**(1/3) as 3.9999 & 125**(1/3) as 4.9999).
n = int(input("What number would you like to check if it is a cube?"))
def is_cube(n):
guess = n**(1.0/3.0)
if (guess)%1 == 0:
print(True, "it's cubed root is", guess)
else:
print(False, "it's cubed root is", guess)
is_cube(n)
Just convert to an integer with round and check whether that integer cubed is the input (n).
def is_cube(n):
cube_root = n**(1./3.)
if round(cube_root) ** 3 == n:
print(True, "its cubed root is", round(cube_root))
else:
print(False, "its cubed root is", cube_root)
And some tests:
>>> is_cube(12)
False its cubed root is 2.2894284851066637
>>> is_cube(34)
False its cubed root is 3.239611801277483
>>> is_cube(27)
True its cubed root is 3
>>> is_cube(64)
True its cubed root is 4
Oh and btw, the possessive form of its doesn't require an apostrophe. It's not right in your code.
Simple method to check perfect square and cube:
1 - For cube:
if(int(x**(1./3.))**3 == int(x))
and 2 - For square:
if(int(x**0.5)**2 ==int(x))
Take square root or cube of number convert to an integer then take the square or cube if the numbers are equal then it is a perfect square or cube otherwise not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With