0

I have this code which is basically flipping a coin and when it hits heads (1) it flips again until the probability of it keep flipping heads is lower than 0.1% or when it hits tails it start again.

import numpy


def checkAgain(probability):
    if(probability >= 0.1):
        runCode()

def flipCoin(successes):
    rand = numpy.random.randint(2)
    if (rand == 1):
        # true
        successes += 1
        flipCoin(successes)
    else:
        probability = 50
        for i in range(successes):
            probability /= 2
        print(str(successes) + " " + str(probability) + "%")
        checkAgain(probability)

def runCode():
    successes = 0
    flipCoin(successes)

runCode()

But the code only works sometimes. Most of the time I get this error: maximum recursion depth exceeded in comparison I read online that this prevents "a stack overflow" but I have no idea how I can make the code run untill the probability is lower than 0.1

Sven
  • 49
  • 6
  • Why are you using recursion in your code when you don't need to? – quamrana Jul 30 '21 at 10:30
  • It's not a good idea to use recursivity in python if you can do the same algorithm with a simple while or for loop – Julien Sorin Jul 30 '21 at 10:31
  • when you are calling runcode again you are setting sucess 0 again , – sahasrara62 Jul 30 '21 at 11:03
  • Does this answer your question? [Python: maximum recursion depth exceeded while calling a Python object](https://stackoverflow.com/questions/6809402/python-maximum-recursion-depth-exceeded-while-calling-a-python-object) – Tomerikoo Aug 02 '21 at 09:51

3 Answers3

0

I think there is a conceptual problem in this question. (I can be wrong about that).

Each flip is independent from the previous flip and the next, so what i would do instead is calculate a geometric distribution (probability of getting head until you get a tail) and then take the CDF at the 99% watch this.

Probably this is why you get:

maximum recursion depth exceeded in comparison

If you would like to continue doing so i think using a while loop can be a solution as others pointed out.

ale_C
  • 51
  • 6
0

Notice that when you get "tails" and start a new "experiment", the previous calls never return, they simply accumulate, possibly until the maximum recursion depth is reached.

The program terminates when it samples at least 9 consecutive "heads" (from probability < 0.1), and the expected number of trials until this condition is met is at least 2 ** (9 + 1) - 2 = 1022 (example calculation on MathSE).

The problem is that this number may be above the default stack depth (most likely ~1000; see sys.getrecursionlimit()), which is why you're getting the error.

Like others have suggested, you can simply use an iterative approach:

import numpy

successes = 0

while True:
    rand = numpy.random.randint(2)
    
    if rand == 1:
        successes += 1
    else:
        probability = 50
        for i in range(successes):
            probability /= 2
        print(str(successes) + " " + str(probability) + "%")
        
        if probability >= 0.1:
            successes = 0
        else:
            break

and can even further simplify the else condition, since probability >= 0.1 can only happen when successes < 9:

import numpy

successes = 0

while True:
    rand = numpy.random.randint(2)
    
    if rand == 1:
        successes += 1
    else:        
        probability = 50 / (2 ** successes)
        print(str(successes) + " " + str(probability) + "%")
        
        if successes < 9:
            assert probability >= 0.1
            successes = 0
        else:
            break
Alexandru Dinu
  • 1,159
  • 13
  • 24
-1

In short, more recursions --> more memory usage. Read more about the error and a simple case here. You can do the same with loops easily as mentioned by Julien Sorin.