0

I need to check to see if a shape is a cube (or could be). I have the total volume and length of one side. I begin by checking to see if the volume and side are both greater than 0, and then if the cubed root of the volume is equal to the side.
The problem I have is that the cubed root of 125 returns as 4.999999999 using the following code. Rounding the number would make it inaccurate in other cases (4.6 would also become 5). I'm new to Python, as far as I can tell there's no built in cube root like Javascripts Math.cbrt().

def is_cube(volume, side):
if volume <= 0 or side <= 0:
    return False
elif volume ** (1/3) != side:
    return False
else:
    return True

I feel like I'm missing something very obvious. I know division in Python 3 will always give me a floating number, but 125 is a perfect cube.

  • Your solution (with corrected indentation) works with 125, 5 as parameters. It returns True. That is what you want, right? – mrCarnivore Nov 22 '17 at 11:35
  • Yes, I was just confused by the 4.999999 instead of 5. Still getting the hang of python... and stackoverflow. –  Nov 22 '17 at 11:48

2 Answers2

3
def is_cube(volume):    
    return int(round(volume ** (1/3.))) ** 3 == volume
mcsim
  • 1,647
  • 2
  • 16
  • 35
0
def cube_volume(volume,side):
    if side>= 0 and volume>= 0:
        if side**3 == volume:
            return True
        else:
            return False

Try this!