Google Colab
import random
import matplotlib.pyplot as plt
def jugar():
resultado_dado: int = random.choice(range(1, 7))
if resultado_dado % 2 == 0:
return 10
return -5
def simulacion(n: int, pp: bool = True):
total: float = 0
for _ in range(1, n):
total += jugar()
if pp:
print(f"Después de jugar {n} veces, se termina con ${total}")
print(f"Promedio de ganancia/pérdida por juego {total / n}")
print()
return total / n
for j in [10**i for i in [1, 2, 3, 4, 5]]:
simulacion(j)
x = range(1, 100_000, 100)
y = [simulacion(j, False) for j in x]
plt.plot(x, y, label='Ganancia promedio')
plt.axhline(y=2.5, color='r', linestyle='--', label='Valor esperado (2.5)')
plt.xlabel('Veces que se repite el experimento')
plt.ylabel('Ganancia promedio')
plt.title('Convergencia al valor esperado')
plt.legend()
plt.grid(alpha=0.3)
plt.show()
