3

I'm a beginner in python and have written a code to check if a number is a cube of a whole number. The code seems to be working fine for some values, however for some (even whole cubes) it prints the cube root as (x-0.000000004, x being cube root). Example it will give 3.9999999996 as the cube root of 64 but will print 2,5 for 8,125 . Any thoughts?

n=int(input("Please enter the number: "))
print (n)
x=n**(1/3)
print (x)
if x==int(x):
    print ('%s is a whole cube'%(n))
else:
    print ('%s is not a whole cube'%(n))

Ignore the intermediate print statements, they're just for line-by-line debugging.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
novice2020
  • 115
  • 1
  • 2
  • 7
  • 4
    Highly recommended read [Python rounding error with float numbers](http://stackoverflow.com/questions/5997027/python-rounding-error-with-float-numbers) – Bhargav Rao May 05 '15 at 18:20
  • This is one of the most asked questions. Please read some topics about floating point precision. For example the one Bhargav Rao mentioned. – tamasgal May 05 '15 at 18:22
  • Sorry for the repetition guys. will check out the python docs, thanks. – novice2020 May 05 '15 at 18:28

1 Answers1

5

You are checking for the wrong condition, comparing floats value for equality can easily give you nightmares. Check what the python docs have to say on this.

Instead, round the root, convert it to an int, and then compare the cube of this integer with the original number:

n = int(input("Please enter the number: "))
print (n)
x = n**(1/3)
x = int(round(x))
if x**3 == n:
    print ('%s is a whole cube'%(n))
else:
    print ('%s is not a whole cube'%(n))

As pointed by @StevenRumbalski in comments, in Python3, x = int(round(x)) could be written as round(x) since round returns int.

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
  • 1
    In Python 3 `round` returns an integer when called with one argument, so if OP is using Python 3 he can skip the cast to `int`. – Steven Rumbalski May 05 '15 at 18:27
  • You can skip the `round()`, too. `int(3.7)` is `3`. So the condition `if int(n**(1.0/3))**3 == n` could be used. I think this works in both Python 2 and 3. – ypercubeᵀᴹ Feb 09 '18 at 07:58