Print Cube Root of A Number in Python

Confronting with numbers is the first thing each one of us has learned in school. However, as we step up high more and more difficult questions based on the same fundamentals seem to appear in our way. It’s the same with programming, using the same fundamentals to find solutions for multiple complex problems. Now the cool thing is, you can be creative in your way eventually coming up with a unique solution. And if you’re able to do this, then you’ve clearly understood how to use programming for others and your good. But keeping that aside, we’ve talked about numbers before. So what if we find the cube root of numbers, seems too easy right!. Well, So let’s quickly find out how to Print the Cube Root of A Number in Python.

With the help of this program, you will be able to find the root square of integers. Practising these types of questions also helps to get an upper edge in Competitive Programming.

 

What’s The Approach?

 

  • Therefore we’ll initialize start=0 & end=n, and we’ll find the middle value in this list by executing (start + end)/2
  • We’ll set an error point e, below which if the calculation goes will be set as the cube root of n. So the condition is (n – mid*mid*mid) < e
  • However, if (mid*mid*mid)>n we’ll set end=mid. And if (mid*mid*mid)<n we’ll set start=mid

Also Read: Implement Linear Search using Python

 

Python Program To Print Cube Root of A Number

 

Input:

n = 8

 

Output:

 

The cubic root of 8.000000 is 2.000000


Source Code

# Python program to find cubic root

# Returns the absolute value of
# n-mid*mid*mid
def diff(n, mid) :
    if (n > (mid * mid * mid)) :
        return (n - (mid * mid * mid))
    else :
        return ((mid * mid * mid) - n)
        
# Returns cube root of a no n
def cubicRoot(n) :
    
    # Set start and end for binary
    # search
    start = 0
    end = n
    
    # Set precision
    e = 0.0000001
    while (True) :
        
        mid = (start + end) / 2
        error = diff(n, mid)

        # If error is less than e
        # then mid is our answer
        # so return mid
        if (error  n) :
            end = mid
            
        # If mid*mid*mid is less
        # than n set start = mid
        else :
            start = mid
            
# Driver code
n = 8
print("Cubic root of", n, "is",
    round(cubicRoot(n),6))

 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published.