How to get an integer result for a cube?

I am creating a problem that requires me to find the root of the cube of certain numbers, some of them have integer roots of the number, but many of them do not.

I have numbers like 125 that should return the cubic root of 5, but instead Python returns 4.99999 Example:

>>> 125 ** (1.0/3.0)
4.999999999999999

This is my code:

processing = True
n = 12000
while processing:


    if (n ** (1.0/3.0)).is_integer() == True:
        print((n ** (1.0/3.0)), "is the cube root of ", n)
        processing = False
    else:
        n -= 1
+3
source share
6 answers

The standard way to check for floating point equality is to check the quality within a certain tolerance:

def floateq(a, b, tolerance=0.00000001):
    return abs(a-b) < tolerance

Now you can check whether the rounded, converted to integer version of the cube root is equal to the cube root itself within a certain tolerance:

def has_integer_cube_root(n):
    floatroot = (n ** (1.0 / 3.0))
    introot = int(round(floatroot))
    return floateq(floatroot, introot)

Using:

>>> has_integer_cube_root(125)
True
>>> has_integer_cube_root(126)
False

However, this is pretty inaccurate for your use case:

>>> has_integer_cube_root(40000**3)
True
>>> has_integer_cube_root(40000**3 + 1)
True

, - .

EDIT: , , :

def has_integer_cube_root(n):
    floatroot = (n ** (1.0 / 3.0))
    introot = int(round(floatroot))
    return introot*introot*introot == n

>>> has_integer_cube_root(40000**3)
True
>>> has_integer_cube_root(40000**3 + 1)
False    
+6

- cubit (int(... + 0.1)), , . ( , n int)

cand = int(n ** (1.0/3.0) + 0.1)
if cand**3 == n:
    print(cand, "is the cube root of ", n)
    processing = False
else:
    n -= 1
+1

125 ** (1.0/3.0) , . , . , , max, :

max = 12000
cube_root = int(max ** (1.0/3.0))  # Take cube root and round to nearest integer
cubed = cube_root ** 3             # Find cube of this number
print str(cube_root) + " is the cube root of " + str(cubed)  # Output result

, , max, , 4.9999999999999. 4, (5) "4 - 64". . :

cube_root = int(max ** (1.0/3.0) + 0.5)

"round down" int() "round to ".

+1

, . , gmpy2:

>>> import gmpy2
>>> root, exact = gmpy2.iroot(125, 3)
>>> print(root)
5
>>> print(exact)
True
+1

It is pretty simple. Move floating point to string and string to float. Like this

float (str (pow (125, (1./3))))

0
source

It is easier to avoid a problem! For instance:

mx = 12000                   # maximum for cubes
crmx = int(mx**(1/3)) + 1    # largest test integer

result = max([n for n in range(crmx) if n**3 < mx])

# result = 22

Floating-point arithmetic is always approximate. For instance:

.9999999999999999999.is_integer () gives True

.9999999999999999.is_integer () gives False

(The distance of your translator may vary.)

0
source

All Articles