Advertisement
Guest User

gamble simulator

a guest
Dec 4th, 2023
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 KB | None | 0 0
  1. import numpy as np
  2.  
  3.  
  4. class Gamble:
  5.     def __init__(self, value: float | list[tuple[float, "Gamble"]]):
  6.         self.value = value
  7.  
  8.     def sample(self) -> float:
  9.         if isinstance(self.value, float):
  10.             return self.value
  11.         probs = [v[0] for v in self.value]
  12.         idx = np.random.choice(len(probs), p=probs)
  13.         return self.value[idx][1].sample()
  14.  
  15.     def samples(self, n: int) -> np.ndarray:
  16.         return np.array([self.sample() for _ in range(n)])
  17.  
  18.     def __or__(self, other: "Gamble") -> "Gamble":
  19.         return Gamble([(0.5, self), (0.5, other)])
  20.  
  21.     def __mul__(self, other: float) -> "Gamble":
  22.         if isinstance(other, float):
  23.             return Gamble(self.value * other)
  24.         return Gamble([(v[0] * other, v[1]) for v in self.value])
  25.  
  26.  
  27. const = Gamble(1.0)
  28. sure = const * 1.0
  29. risky = (const * 1e-100) | (const * 1e20)
  30. sure_or_sure = sure | sure
  31. risky_or_sure = risky | sure
  32.  
  33.  
  34. def U(g: Gamble, k: int, n: int = 10**4) -> float:
  35.     outcomes = 1
  36.     for _ in range(k):
  37.         outcomes += g.samples(n=n)
  38.     outcomes /= k
  39.     return np.log(outcomes).mean()
  40.  
  41.  
  42. K = 2
  43.  
  44. print(U(sure, k=K))
  45. print(U(risky, k=K))
  46.  
  47. print(U(sure_or_sure, k=K))
  48. print(U(risky_or_sure, k=K))
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement