I am trying to find the largest cube root that is a whole number, that is less than 12,000.
processing = True
n = 12000
while processing:
n -= 1
if n ** (1/3) == #checks to see if this has decimals or not
I am not sure how to check if it is a whole number or not though! I could convert it to a string then use indexing to check the end values and see whether they are zero or not, that seems rather cumbersome though. Is there a simpler way?
Wouldn't it be easier to test the cube roots? Start with 20 (20**3 = 8000) and go up to 30 (30**3 = 27000). Then you have to test fewer than 10 integers.
The above answers work for many cases but they miss some. Consider the following:
Using this as a benchmark, some of the other suggestions don't get the behavior we might want:
Instead try:
now we get:
isclose
comes with Python 3.5+, and for other Python's you can use this mostly equivalent definition (as mentioned in the corresponding PEP)Try using:
It will give lot more precision than any other methods.
All the answers are good but a sure fire method would be
The function returns True if it's a whole number else False....I know I'm a bit late but here's one of the interesting methods which I made...
Edit: as stated by the comment below, a cheaper equivalent test would be:
We can use the modulo (%) operator. This tells us how many remainders we have when we divide x by y - expresses as
x % y
. Every whole number must divide by 1, so if there is a remainder, it must not be a whole number.This function will return a boolean,
True
orFalse
, depending on whethern
is a whole number.You can use the
round
function to compute the value.Yes in python as many have pointed when we compute the value of a cube root, it will give you an output with a little bit of error. To check if the value is a whole number you can use the following function:
But remember that
int(n)
is equivalent tomath.floor
and because of this if you find theint(41063625**(1.0/3.0))
you will get 344 instead of 345.So please be careful when using
int
withe cube roots.