Python Forum
question about recursion
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
question about recursion
#1
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?
Reply
#2
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  GCF function w recursion and helper function(how do i fix this Recursion Error) hhydration 3 2,485 Oct-05-2020, 07:47 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020