-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
213 lines (163 loc) · 6.75 KB
/
main.py
File metadata and controls
213 lines (163 loc) · 6.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import math
import random
class EloRatingSystem:
def __init__(self, k_factor=32):
"""
Args:
k_factor (int): How much ratings change per match
32 = Beginners/high volatility
16 = Experienced players
8 = Masters/low volatility
"""
self.k_factor = k_factor
def expected_score(self, rating_a, rating_b):
"""
Calculate expected probability that player A beats player B
Formula: E_A = 1 / (1 + 10^((R_B - R_A) / 400))
Args:
rating_a (float): Player A's current rating
rating_b (float): Player B's current rating
Returns:
float: Expected probability (0 to 1) that A beats B
"""
exponent = (rating_b - rating_a) / 400
expected_a = 1 / (1 + math.pow(10, exponent))
return expected_a
def update_ratings(self, rating_a, rating_b, score_a):
"""
Update both players' ratings after a match
Formula: R_new = R_old + K * (S - E)
Args:
rating_a (float): Player A's rating before match
rating_b (float): Player B's rating before match
score_a (float): Player A's actual score (1=win, 0=loss, 0.5=draw)
Returns:
tuple: (new_rating_a, new_rating_b)
"""
# Calculate expected scores
expected_a = self.expected_score(rating_a, rating_b)
expected_b = 1 - expected_a # Since probabilities sum to 1
# Actual scores (they sum to 1)
score_b = 1 - score_a
# Update ratings using Elo formula
new_rating_a = rating_a + self.k_factor * (score_a - expected_a)
new_rating_b = rating_b + self.k_factor * (score_b - expected_b)
return new_rating_a, new_rating_b
def rating_difference_to_probability(self, rating_diff):
"""
Convert rating difference to win probability
Args:
rating_diff (float): Rating A - Rating B
Returns:
float: Probability that A beats B
"""
return 1 / (1 + math.pow(10, -rating_diff / 400))
# Example usage with cars from your question
def main():
print("🏎️ ELO RATING SYSTEM DEMO - Car Rankings")
print("=" * 50)
# Initialize system
elo = EloRatingSystem(k_factor=32)
# Our cars with starting ratings
cars = {
"Audi R8": 1500,
"Porsche 911": 1500,
"VW Golf": 1500,
"Old Volvo (1990)": 1500
}
print("Starting ratings (all equal):")
for car, rating in cars.items():
print(f" {car}: {rating}")
print("\n" + "=" * 50)
print("SIMULATION: Let's simulate some realistic comparisons...")
print("=" * 50)
# Simulate realistic outcomes
comparisons = [
("Audi R8", "Old Volvo (1990)", 1), # Audi wins
("Porsche 911", "VW Golf", 1), # Porsche wins
("Audi R8", "Porsche 911", 0), # Close match, Porsche wins
("VW Golf", "Old Volvo (1990)", 1), # VW wins
("Audi R8", "VW Golf", 1), # Audi wins
("Porsche 911", "Old Volvo (1990)", 1), # Porsche wins
("Audi R8", "Porsche 911", 1), # Audi wins this time
("VW Golf", "Old Volvo (1990)", 1), # VW wins again
]
for i, (car_a, car_b, winner) in enumerate(comparisons, 1):
rating_a = cars[car_a]
rating_b = cars[car_b]
# Calculate expected probability
expected_a = elo.expected_score(rating_a, rating_b)
# Determine actual scores
score_a = 1 if winner == 1 else 0
# Update ratings
new_rating_a, new_rating_b = elo.update_ratings(rating_a, rating_b, score_a)
# Show the math
print(f"\nComparison {i}: {car_a} vs {car_b}")
print(f" Before: {car_a}={rating_a:.0f}, {car_b}={rating_b:.0f}")
print(f" Expected: {car_a} has {expected_a:.1%} chance to win")
print(f" Actual: {car_a if winner == 1 else car_b} wins")
print(f" After: {car_a}={new_rating_a:.0f} ({new_rating_a - rating_a:+.0f}), "
f"{car_b}={new_rating_b:.0f} ({new_rating_b - rating_b:+.0f})")
# Update our dictionary
cars[car_a] = new_rating_a
cars[car_b] = new_rating_b
print("\n" + "=" * 50)
print("FINAL RANKINGS:")
print("=" * 50)
# Sort by rating
sorted_cars = sorted(cars.items(), key=lambda x: x[1], reverse=True)
for rank, (car, rating) in enumerate(sorted_cars, 1):
print(f"{rank}. {car}: {rating:.0f}")
print("\n" + "=" * 50)
print("PROBABILITY ANALYSIS:")
print("=" * 50)
# Show win probabilities between top cars
top_car = sorted_cars[0][0]
top_rating = sorted_cars[0][1]
for car, rating in sorted_cars[1:]:
prob = elo.expected_score(top_rating, rating)
print(f"{top_car} vs {car}: {prob:.1%} chance {top_car} wins")
def demonstrate_math():
"""Show step-by-step mathematical calculations"""
print("\n" + "=" * 60)
print("MATHEMATICAL BREAKDOWN:")
print("=" * 60)
elo = EloRatingSystem(k_factor=32)
# Example: Audi R8 (1600) vs VW Golf (1400)
rating_audi = 1600
rating_vw = 1400
print(f"Example: Audi R8 ({rating_audi}) vs VW Golf ({rating_vw})")
print(f"Audi wins the comparison")
print()
# Step 1: Expected scores
print("Step 1: Calculate Expected Scores")
print("Formula: E_A = 1 / (1 + 10^((R_B - R_A) / 400))")
exponent = (rating_vw - rating_audi) / 400
expected_audi = 1 / (1 + math.pow(10, exponent))
expected_vw = 1 - expected_audi
print(f"E_Audi = 1 / (1 + 10^(({rating_vw} - {rating_audi}) / 400))")
print(f"E_Audi = 1 / (1 + 10^({exponent:.3f}))")
print(f"E_Audi = 1 / (1 + {math.pow(10, exponent):.3f})")
print(f"E_Audi = {expected_audi:.3f} ({expected_audi:.1%})")
print(f"E_VW = {expected_vw:.3f} ({expected_vw:.1%})")
print()
# Step 2: Update ratings
print("Step 2: Update Ratings")
print("Formula: R_new = R_old + K × (S - E)")
print("Where K=32, S_Audi=1 (win), S_VW=0 (loss)")
k = 32
score_audi = 1 # Audi won
score_vw = 0 # VW lost
change_audi = k * (score_audi - expected_audi)
change_vw = k * (score_vw - expected_vw)
new_rating_audi = rating_audi + change_audi
new_rating_vw = rating_vw + change_vw
print(
f"Audi: {rating_audi} + {k} × ({score_audi} - {expected_audi:.3f}) = {rating_audi} + {change_audi:.1f} = {new_rating_audi:.0f}")
print(
f"VW: {rating_vw} + {k} × ({score_vw} - {expected_vw:.3f}) = {rating_vw} + {change_vw:.1f} = {new_rating_vw:.0f}")
print(f"\nResult: Audi gains {change_audi:.1f} points, VW loses {-change_vw:.1f} points")
print("Notice: Audi gained fewer points because it was favored to win!")
if __name__ == "__main__":
main()
demonstrate_math()