dustin
dustin

Reputation: 4416

Python: recursive method returns different results when it is a class method

I have a recursive function that works as expected when it is a standalone function

def drip2(n, 
          i: float = 0.0, 
          j: float = 0.0) -> float:
    return ((1 + i * (1 + j) ** (n - 1) / 4) ** 4 * drip2(n - 1) 
        if n > 1 else (1 + i / 4) ** 4)

drip2(0, 0.0067, 0.2) = drip2(1, 0.0067, 0.2) -> 1.0067168525555594
drip2(2, 0.0067, 0.2) -> 1.0080642730987266

However, when I wrap it in a class, the results differ.

class TestDrip:
    def __init__(self, 
                 i: float = 0.0, 
                 j: float = 0.0) -> None:
        self.i = i
        self.j = j

    def drip(self,
             n) -> float:
        return ((1 + self.i * (1 + self.j) ** (n - 1) / 4) ** 4 * self.drip(n - 1) 
            if n > 1 else (1 + self.i / 4) ** 4)

TestDrip(0.0067, 0.2).drip(1) = TestDrip(0.0067, 0.2).drip(1) -> 1.0067168525555594
TestDrip(0.0067, 0.2).drip(2) -> 1.014835292187658

Once the integer n is greater than or equal to 2, the result deviate. I am on Python 3.7.7.

enter image description here

Upvotes: 0

Views: 47

Answers (1)

Tristan Nemoz
Tristan Nemoz

Reputation: 2048

In the definition of drip2, the recursive call you are doing is:

drip2(n - 1)

which is equivalent to:

drip2(n - 1, 0, 0)

while in the method drip, the recursive call is:

self.drip(n - 1)

Since self refers to the same instance, self.i and self.j will stay at the same value throughout all recursive calls, while they are set to 0 starting from the first recursive call in your function definition.

Upvotes: 2

Related Questions