Ad

Finding the real cube root of a number in Python

There is a unique real cube root of every real number.

For example, 5 is a real cube root of 125 because we can write 125 as the product of 3 positive 5's.

In Python, however, when it comes to finding a real cube root of a negative number n, simply raising n to the power of 1/3 results in a complex number.

For example, either pow(-125, (1/3)) or (-125) ** (1/3) evaluates to (2.5+4.330127018922192j) instead of -5.

In this kata, you are going to come up with a function that correctly calculates a real cube root of an input number, which can be zero, a positive real number or a negative one.

There is a unique real cube root of every real number.

For example, 5 is a real cube root of 125 because we can write 125 as the product of 3 positive 5's.

In Python, however, when it comes to finding a real cube root of a negative number n, simply raising n to the power of 1/3 results in a complex number.

For example, either pow(-125, (1/3)) or (-125) ** (1/3) evaluates to (2.5+4.330127018922192j) instead of -5.

In this kata, you are going to come up with a function that correctly calculates a real cube root of an input number, which can be zero, a positive real number or a negative one.

def real_cube_root(n):
    if n >= 0: return n ** (1/3)
    else: return -abs(n ** (1/3))