Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 19113

Optimize binomial distribution for large numbers without using modules

$
0
0

I made this code to simulate the odds of getting tails "m" times when you toss a coin "n" times:

def factorial(n):    if n<0:        return "Indefinido"    if n==0 or n==1:        return 1    else:        valor=1        for i in range(2,n+1):            valor*=i        return valordef binomial(n,m):    if m>n:        return "Indefinido"    probabilidade=factorial(n)/(factorial(m)*factorial(n-m))*(1/2)**n    return probabilidade

However this code doesn't work for (n,m) pairs such as (10000, 5000) or (100000, 50000) because these integers are too large for a float.Is it possible to make it work for values that large without importing any modules?

I tried to optimize the code by adding a dictionary that stores some values:

memo = {}def factorial(n):    if n < 0:        return "Indefinido"    if n == 0 or n == 1:        return 1    if n in memo:        return memo[n]    else:        resultado = n * factorial(n - 1)        memo[n] = resultado        return resultadodef binomial(n, m):    if m > n:        return "Indefinido"    probabilidade = factorial(n) / (factorial(m) * factorial(n - m)) * (1 / 2) ** n    return probabilidade

but I got the following message:

"Windows fatal exception: stack overflow"


Viewing all articles
Browse latest Browse all 19113

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>