Python Forum

Full Version: question about recursion
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I was making an old exam but I am currently stuck on one question. I need to implement a class for real numbers. The class has one attribute, r, which is a float. In the class I need to approximate sqrt(n) in the following way:

x0 = n
xi = 0.5(xi-1 + n / xi-1) for i = 1,2,3,...

The approximation of sqrt(n) has to be x10.

After reading the question I thought about recursion.
My attempt:

class Real(object):
    def __init__(self, r = 0):
        self.r = r

    def __str__(self):
        return "%18.15f" % (self.r,)
    def mul(self, y):
        return self.r * y.r

    def sqrt(self):
        i = 10
        if i == 0:
            return n
        else:
            return 0.5 * (self.sqrt(i - 1) + n / self.sqrt(i - 1))
Problem is that the only argument of sqrt function is self (and I am not allowed to create more arguments), so I obtain the following error:
Error:
TypeError: sqrt() takes 1 positional argument but 2 were given
How should I solve this problem. Is recursion after all the wrong way to solve this? Am I implementing recursion in the wrong way?
Solved it myself.

Here is the solution:

class Real(object):
    def __init__(self, r = 0):
        self.r = r

    def __str__(self):
        return "%18.15f" % (self.r,)

    def sqrt(self):
        if self.r == 0:
            return 0
        else:
            x = self.r
            for i in range(1, 11):
                x = 0.5 * (x + self.r / x)
            return x