杰瑞科技汇

Python simple bettor如何实现最优策略?

Of course! Here is a simple "Python Bettor" simulation. This program models a gambler who places a series of even-money bets (like on red/black in roulette) and tracks their bankroll over time.

Python simple bettor如何实现最优策略?-图1
(图片来源网络,侵删)

This is a great way to visualize concepts like the Gambler's Ruin and the Law of Large Numbers.

The Core Idea

We'll simulate a gambler who:

  1. Starts with an initial amount of money (a "bankroll").
  2. Bets a fixed amount on each round.
  3. Wins with a certain probability (e.g., 47.37% for a single zero roulette wheel).
  4. Repeats for a set number of bets.
  5. We'll run this simulation many times to see the long-term outcomes.

The Python Code

This code is broken down into a function for the simulation and a main block to run it and display the results.

import random
import matplotlib.pyplot as plt
def simple_bettor(initial_funds, initial_wager, wager_count, win_probability):
    """
    Simulates a simple bettor's bankroll over a series of bets.
    Args:
        initial_funds (float): The starting amount of money.
        initial_wager (float): The amount of money bet on each turn.
        wager_count (int): The total number of bets to place.
        win_probability (float): The probability of winning a single bet (between 0 and 1).
    Returns:
        list: A list representing the bettor's bankroll after each bet.
    """
    funds = initial_funds
    wager = initial_wager
    fund_history = [funds] # Start history with the initial funds
    # Loop for the total number of bets
    for i in range(wager_count):
        # Generate a random number to determine the outcome of the bet
        if random.random() < win_probability:
            # Win: add the wager to the funds
            funds += wager
        else:
            # Lose: subtract the wager from the funds
            funds -= wager
        # Record the new bankroll after this bet
        fund_history.append(funds)
        # Optional: Stop the simulation if the bettor is broke
        if funds <= 0:
            # print(f"Broke after {i+1} bets!")
            break
    return fund_history
# --- Main part of the script ---
if __name__ == "__main__":
    # --- Simulation Parameters ---
    STARTING_FUNDS = 1000
    WAGER_AMOUNT = 100
    NUMBER_OF_BETS = 500
    # Probability of winning a single bet (e.g., European Roulette on Red/Black)
    # 18/37 = ~0.4865
    WIN_PROBABILITY = 18 / 37
    # --- Run a Single Simulation and Plot It ---
    print("Running a single simulation...")
    history = simple_bettor(STARTING_FUNDS, WAGER_AMOUNT, NUMBER_OF_BETS, WIN_PROBABILITY)
    plt.figure(figsize=(12, 6))
    plt.plot(history)
    plt.title(f"Single Bettor Simulation\n(Starting Funds: ${STARTING_Funds}, Wager: ${WAGER_AMOUNT}, Win Prob: {WIN_PROBABILITY:.4f})")
    plt.xlabel("Number of Bets")
    plt.ylabel("Bankroll ($)")
    plt.grid(True)
    plt.axhline(y=0, color='r', linestyle='--') # Show the "broke" line
    plt.show()
    # --- Run Many Simulations to See the Overall Trend ---
    print("\nRunning 100 simulations to show long-term trend...")
    num_simulations = 100
    plt.figure(figsize=(12, 6))
    for _ in range(num_simulations):
        history = simple_bettor(STARTING_FUNDS, WAGER_AMOUNT, NUMBER_OF_BETS, WIN_PROBABILITY)
        plt.plot(history, alpha=0.5) # Use alpha for transparency
    plt.title(f"{num_simulations} Bettor Simulations\n(Showing the high probability of losing over time)")
    plt.xlabel("Number of Bets")
    plt.ylabel("Bankroll ($)")
    plt.grid(True)
    plt.axhline(y=0, color='r', linestyle='--', label='Broke')
    plt.axhline(y=STARTING_FUNDS, color='g', linestyle='--', label='Starting Funds')
    plt.legend()
    plt.show()

How to Run the Code

  1. Install necessary libraries: If you don't have matplotlib installed, open your terminal or command prompt and run:

    Python simple bettor如何实现最优策略?-图2
    (图片来源网络,侵删)
    pip install matplotlib
  2. Save the code: Save the code above into a file named bettor.py.

  3. Execute the script: Run the file from your terminal:

    python bettor.py

Understanding the Output

You will see two plots:

  1. Single Simulation Plot: This graph shows one possible journey of a gambler. You'll see the bankroll go up and down randomly. In many cases, it will trend downwards and cross the red "broke" line before all 500 bets are complete. This is the Gambler's Ruin in action. Even if the bettor has a slight chance of winning, the risk of ruin is high with repeated betting.

    Python simple bettor如何实现最优策略?-图3
    (图片来源网络,侵删)
  2. Multiple Simulations Plot: This is the more powerful visualization. It shows 100 different simulation runs on the same graph. Notice how almost all the lines trend downwards and eventually cross the "broke" line. Very few, if any, will end up significantly higher than they started. This clearly demonstrates that even with a nearly 50/50 chance of winning, the "house edge" (the casino's built-in advantage) makes long-term success for the bettor nearly impossible. This is the Law of Large Numbers at work.

Key Concepts Illustrated

  • Gambler's Ruin: A mathematical principle that states a gambler with a finite bankroll playing a game with a negative expected value will eventually go broke with a probability of 1.
  • Law of Large Numbers: As the number of trials (bets) increases, the average of the results will get closer to the expected value. In this case, the expected value of each bet is negative, so the average outcome is a loss.
  • House Edge: The casino's built-in advantage. In our example, the probability of winning is 18/37, but the payout is 1:1. The true odds should be 18/19 for a fair game. The difference is the house edge, which guarantees the casino's profit over time.

How to Experiment (Modify the Code)

You can change the parameters at the top of the if __name__ == "__main__": block to see how different strategies affect the outcome:

  • Change the Win Probability: Try win_probability = 0.5. This is a fair game. You'll see that the outcomes are much more varied, with many bettors going broke and many others doing well. Now try win_probability = 0.51. The bettor now has a slight edge. You'll notice a lot more green lines at the end!
  • Change the Wager Amount: Try WAGER_AMOUNT = 10. With smaller bets, the bankroll fluctuates less, and it takes longer to go broke. Try WAGER_AMOUNT = 500. With larger bets, the outcome is decided much more quickly.
  • Change the Starting Funds: A larger starting fund makes it harder to go broke in the short term, but the long-term trend remains the same if the house edge exists.
分享:
扫描分享到社交APP
上一篇
下一篇