Question

I wrote two functions to calculate the nth root of a number. One uses a linear search and the other uses a bisection search. However, when I tried calling them there was a problem with both of them. It just said that the number I specified cannot be taken to that root. I am very confused and cannot tell what I have done wrong. Does anybody have an idea?

def rootBisect(root, num):
    low = 0.0
    high = num
    ans = (high + low)/2.0
    while ans ** root < abs(float(num)):
        if ans ** root < num:
            low = ans
        else:
            high = ans
        ans = (high + low)/2.0
    if ans ** root != abs(num):
        print '%d cannot be taken to %d root.' % (num, root)
    else:
        if num < 0:
            ans = -ans
        print '%d root of %d is %d.' % (root, num, ans)
    return ans

def rootLinear(root, num):
    ans = 0
    while ans ** root < abs(float(num)):
        ans += 0.1
    if ans ** root != abs(num):
        print '%d cannot be taken to %d root.' % (num, root)
    else:
        if num < 0:
            ans = -ans
        print '%d root of %d is %d.' % (root, num, ans)
    return ans

rootBisect(2, 16)

rootLinear(2, 16)
Was it helpful?

Solution

The problem is that you expect ans ** root == abs(num) to be true. That is not likely, as floating point arithmetics work with a limited precision. Take a look at that:

>>> import math
>>> math.sqrt(7)
2.6457513110645907
>>> math.sqrt(7)**2
7.000000000000001
>>> math.sqrt(7)**2 == 7
False

You should change your success condition. For example:

acceptable_error = 0.000001
if abs(ans ** root - abs(num)) <= acceptable_error):
    # success

Not that the if your linear search takes big steps, acceptable_error must be big too.

As to the binary search, you should have something like:

while abs(ans ** root - abs(num)) > acceptable_error):
    ...

OTHER TIPS

num1=input("Please enter a number to find the root: ")#accepting input and saving in num1
num2=input("Please enter another number as the root: ")#accepting input and saving in num2
x=float(num1)#converting string to float
n=float(num2)#converting string to float

least=1#the lower limit to find the average
most=x#the lower limit to find the average

approx=(least+most)/2#to find simple mean using search method taught in class

while abs(approx**n-x)>=0.0000000001:#for accuracy

    if approx**n>x:
        most=approx
    else:
        least=approx

    approx=(least+most)/2

print("The approximate root: ",approx)#output

I hope this is a clearer and simpler code for the same!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top