用python实现蒙特卡洛预测足球比赛的代码
时间: 2024-10-16 13:06:19 浏览: 68
蒙特卡洛方法在预测足球比赛结果时通常用于模拟大量随机比赛,以得到基于概率的结果。这需要一些基本假设,比如进球的可能性、平局概率等。以下是一个简单的Python代码示例,使用了random库来模拟:
```python
import random
# 假设参数
HOME_GOAL_PROBABILITY = 0.5
AWAY_GOAL_PROBABILITY = 0.45
DRAW_PROBABILITY = 0.05
NUM_SIMULATIONS = 10000
def simulate_game(home_team, away_team):
home_goals = random.choices([0, 1, 2, 3], [1 - HOME_GOAL_PROBABILITY, HOME_GOAL_PROBABILITY * (1 - DRAW_PROBABILITY), HOME_GOAL_PROBABILITY * DRAW_PROBABILITY, HOME_GOAL_PROBABILITY ** 2])
away_goals = random.choices([0, 1, 2, 3], [1 - AWAY_GOAL_PROBABILITY, AWAY_GOAL_PROBABILITY * (1 - DRAW_PROBABILITY), AWAY_GOAL_PROBABILITY * DRAW_PROBABILITY, AWAY_GOAL_PROBABILITY ** 2])
if max(home_goals) > max(away_goals):
return "Home team wins"
elif max(away_goals) > max(home_goals):
return "Away team wins"
else:
return "Draw"
# 模拟并计算结果
results = {result: 0 for result in ["Home team wins", "Away team wins", "Draw"]}
for _ in range(NUM_SIMULATIONS):
results[simulate_game("Home Team", "Away Team")] += 1
# 输出预测结果的百分比
for result, percentage in results.items():
print(f"{result}: {percentage / NUM_SIMULATIONS * 100:.2f}%")
阅读全文