Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find cube root using Python? [duplicate]

Here is how, this is the best way, I have found:

x = int(raw_input("Enter an integer: ")) for ans in range(0, abs(x) + 1):     if ans ** 3 == abs(x):         break if ans ** 3 != abs(x):     print x, 'is not a perfect cube!' else:     if x < 0:         ans = -ans     print 'Cube root of ' + str(x) + ' is ' + str(ans) 

Is there a better way, preferably one that avoids having to iterate over candidate values?

like image 949
Luke D Avatar asked Jan 18 '15 20:01

Luke D


People also ask

What is the correct expression for calculating the cube root of 27 in Python?

Python Get Cube Root Using the Exponent Symbol ** For example, the cube root of integer -27 should be -3 but Python returns 1.5000000000000004+2.598076211353316j .

Is there any cube function in Python?

The pow() function finds the cube of a number by giving the values of i and number. ex: pow(i,3).

What would you use to find a number's square root in Python?

sqrt() function is an inbuilt function in Python programming language that returns the square root of any number. Syntax: math. sqrt(x) Parameter: x is any number such that x>=0 Returns: It returns the square root of the number passed in the parameter.


1 Answers

You could use x ** (1. / 3) to compute the (floating-point) cube root of x.

The slight subtlety here is that this works differently for negative numbers in Python 2 and 3. The following code, however, handles that:

def is_perfect_cube(x):     x = abs(x)     return int(round(x ** (1. / 3))) ** 3 == x  print(is_perfect_cube(63)) print(is_perfect_cube(64)) print(is_perfect_cube(65)) print(is_perfect_cube(-63)) print(is_perfect_cube(-64)) print(is_perfect_cube(-65)) print(is_perfect_cube(2146689000)) # no other currently posted solution                                    # handles this correctly 

This takes the cube root of x, rounds it to the nearest integer, raises to the third power, and finally checks whether the result equals x.

The reason to take the absolute value is to make the code work correctly for negative numbers across Python versions (Python 2 and 3 treat raising negative numbers to fractional powers differently).

like image 184
NPE Avatar answered Oct 11 '22 07:10

NPE