Guest User

Untitled

a guest
Nov 22nd, 2024
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.97 KB | Source Code | 0 0
  1. import numpy as np
  2. import random
  3. import matplotlib.pyplot as plt
  4. from scipy.optimize import fsolve
  5.  
  6. # Function to compute the slope-zero point from the first code (for bet percentage calculation)
  7. def compute_slope_zero_f(b, a, p, q):
  8. # Derivative of r with respect to f (using the chain rule)
  9. def derivative(f, b, a, p, q):
  10. term1 = p * (1 + f * b) ** (p - 1) * b
  11. term2 = q * (1 - f * a) ** (q - 1) * (-a)
  12. return term1 * (1 - f * a) ** q + (1 + f * b) ** p * term2
  13.  
  14. # Use fsolve to find the value of f where the derivative is zero
  15. slope_zero_f = fsolve(derivative, 0.5, args=(b, a, p, q))[0] # Initial guess: 0.5
  16. return round(slope_zero_f, 5)
  17.  
  18. # Function to simulate a coin toss game
  19. def simulate_game(num_people, num_rounds, win_probability, lose_probability, win_percentage, lose_percentage, bet_percentage, starting_money):
  20. # Initialize everyone's starting money
  21. money = [starting_money] * num_people # List to track each person's money
  22.  
  23. # Create a matrix to track each person's money after each round
  24. money_over_time = np.zeros((num_people, num_rounds))
  25.  
  26. # Simulate each round of the game for each person
  27. for round_num in range(num_rounds):
  28. for i in range(num_people):
  29. # Calculate how much money to bet for this round
  30. bet = money[i] * bet_percentage
  31.  
  32. # Simulate the coin toss result (True = win, False = lose)
  33. toss_result = random.random() < win_probability # Toss result based on win probability
  34.  
  35. # Update money based on the result
  36. if toss_result:
  37. money[i] += bet * win_percentage # Win
  38. else:
  39. money[i] -= bet * lose_percentage # Lose
  40.  
  41. # Store the money of this person after the current round
  42. money_over_time[i, round_num] = money[i]
  43.  
  44. # Return the matrix of money over time
  45. return money_over_time
  46.  
  47. # Function to run the simulation and plot money over rounds
  48. def run_simulation():
  49. # Get inputs from the user for the first set of code (game parameters)
  50. win_probability = float(input("Enter the chance of winning (between 0 and 1): ")) # Chance of winning
  51. win_percentage = float(input("Enter the percentage gained on a win (as a decimal): ")) # Percentage gained on win
  52. lose_percentage = float(input("Enter the percentage lost on a loss (as a decimal): ")) # Percentage lost on loss
  53. loss_probability = 1 - win_probability # Probability of losing is 1 - probability of winning
  54.  
  55. # Get inputs from the user for the second set of code (simulation parameters)
  56. num_people = int(input("Enter the number of players: ")) # Number of people
  57. num_rounds = int(input("Enter the number of rounds: ")) # Number of rounds each player plays
  58. starting_money = float(input("Enter the starting amount of money for each player: ")) # Starting amount for each player
  59.  
  60. # Calculate the bet percentage from the first set (using the slope-zero point)
  61. b = win_percentage # Gain from win
  62. a = lose_percentage # Loss from loss
  63. p = win_probability # Probability of winning
  64. q = loss_probability # Probability of losing
  65. bet_percentage = compute_slope_zero_f(b, a, p, q) # Bet percentage from the first set's slope-zero point
  66.  
  67. print(f"Calculated bet percentage (fraction of current money to bet): {bet_percentage:.5f}")
  68.  
  69. # Simulate the game
  70. money_over_time = simulate_game(num_people, num_rounds, win_probability, loss_probability, win_percentage, lose_percentage, bet_percentage, starting_money)
  71.  
  72. # --- Plot 1: Return Rate and Slope Zero Point ---
  73. f_values = np.linspace(0, 10000, 1000000)
  74. r_values = np.round((1 + f_values * b) ** p * (1 - f_values * a) ** q, 5)
  75.  
  76. # Create the first plot for return rate r(f)
  77. plt.figure(figsize=(12, 8))
  78. plt.plot(f_values, r_values, label=r'$r = ((1 + f \cdot b)^p) \cdot ((1 - f \cdot a)^q)$', color='blue')
  79.  
  80. # Add the line where the slope is zero
  81. plt.axvline(x=bet_percentage, color='green', linestyle='--', label=f'Slope = 0 at f = {bet_percentage:.5f}')
  82.  
  83. # Set the x-axis limits (from 0 to 1 as required)
  84. plt.xlim(0, bet_percentage + (bet_percentage / 10))
  85.  
  86. # Dynamically set the y-axis limits based on the range of r_values
  87. plt.ylim(1, max(r_values) + (max(r_values) / 100))
  88.  
  89. plt.title('Return Rate r vs Fraction of Bet f')
  90. plt.xlabel('Fraction of Bet (f)')
  91. plt.ylabel('Return Rate (r)')
  92. plt.grid(True)
  93. plt.legend()
  94. plt.show()
  95.  
  96. # --- Plot 2: Money Over Time ---
  97. # Plot money over time for each player
  98. plt.figure(figsize=(12, 8))
  99.  
  100. # Plot the money of the first few players (let's limit it to the first 100 players for clarity)
  101. num_to_plot = 100 # Number of players to plot for clarity
  102. for i in range(min(num_to_plot, num_people)):
  103. plt.plot(money_over_time[i, :], alpha=0.5) # alpha for transparency to avoid overlap
  104.  
  105. # Calculate and plot the average money across all players at each round
  106. average_money = np.mean(money_over_time, axis=0)
  107. plt.plot(average_money, label='Average Money', color='red', linewidth=2)
  108.  
  109. # Calculate the average money at the end of the simulation
  110. average_money_final = np.mean(money_over_time[:, -1]) # Average money after all rounds
  111.  
  112. # Set the Y-axis to 1.5 times the average final money
  113. plt.ylim(0, 1.5 * average_money_final) # Dynamically adjust Y-axis based on average final money
  114.  
  115. # Plot a horizontal line at the starting money level
  116. plt.axhline(starting_money, color='green', linestyle='--', label=f'Starting Money: ${starting_money}')
  117.  
  118. plt.title('Money Over Time for Players')
  119. plt.xlabel('Rounds')
  120. plt.ylabel('Money ($)')
  121. plt.grid(True)
  122. plt.legend(loc='upper right', bbox_to_anchor=(1.1, 1.05), title="Average/Player/Starting Amount")
  123. plt.show()
  124.  
  125. # Calculate and print some statistics
  126. players_above_avg = np.sum(money_over_time[:, -1] > average_money_final) # Players with more money than average
  127. players_below_avg = np.sum(money_over_time[:, -1] < average_money_final) # Players with less money than average
  128.  
  129. # Calculate players above or below the starting amount (dynamic value)
  130. players_above_start = np.sum(money_over_time[:, -1] > starting_money) # Players with more than starting money at the end
  131. players_below_start = np.sum(money_over_time[:, -1] < starting_money) # Players with less than starting money at the end
  132.  
  133. print("\nSimulation results:")
  134. print(f"Average money per player: ${average_money_final:.2f}")
  135. print(f"Number of players above the average: {players_above_avg}")
  136. print(f"Number of players below the average: {players_below_avg}")
  137. print(f"Number of players above the starting amount of ${starting_money}: {players_above_start}")
  138. print(f"Number of players below the starting amount of ${starting_money}: {players_below_start}")
  139.  
  140. return money_over_time
  141.  
  142. # Run the simulation
  143. final_money = run_simulation()
Add Comment
Please, Sign In to add comment