Epsilon
Epsilon

Reputation: 151

Calculating square root of 2

Why does the following code does not terminate?

# approximating sqrt(2)

def approx (error,left, right):
    c = (left+right)/2
    f = c**2 - 2

    if abs(f)<error :
        return c

    if f < 0:
        left = c
    else:
        right = c

    return approx(error,left,right)

print approx(0.1,0,2)

Upvotes: 0

Views: 210

Answers (1)

Kevin
Kevin

Reputation: 76254

You might be losing precision on this line:

c = (left+right)/2

if left and right are both integers, then c will also be an integer. This leads to unexpected behavior, for instance 1/2 evaluating to 0.

You can force the result to be a float by dividing by a float:

c = (left+right)/2.0

Or you can switch to Python 3.X and it will use ordinary sensible division automatically.

Upvotes: 3

Related Questions