Menu
CoddyTech

Expected Value

Part of the Statistics for ML section of Coddy's Machine Learning journey. Lesson 16 of 64.

A raffle: 70% of tickets win nothing, 25% win 5 dollars, 5% win 20. What is one worth?

Three bars for the raffle prizes 0, 5 and 20 dollars, with chances 0.7, 0.25 and 0.05. The bars stand on a beam like a seesaw, balanced on a triangle at 2.25, the expected value

Weight each prize by its chance and add: the expected value, the chart's balance point:

prizes = np.array([0, 5, 20])
chances = np.array([0.7, 0.25, 0.05])
print((prizes * chances).sum())

This prints 2.25, the long-run average, though no ticket pays it. rng.choice with p= draws tickets by those chances:

rng = np.random.default_rng(1)
tickets = rng.choice(prizes, size=10000, p=chances)
print(tickets.mean())

This prints 2.298. At 3 dollars, a buyer loses 0.75 a ticket. A model's average error on new data is an expected value too.

challenge icon

Challenge

Medium

A fairground wheel pays the tokens in prizes, each zone with its chance in chances. The starter spun it 4000 times into spins; the program reads a spin's price.

  1. Print the expected prize, then the simulated average, both to 2 decimals.
  2. Print whether a player gains or loses per spin in the long run, and how much.

For another wheel and a price of 1.5:

Expected prize: 1.1 tokens
Simulated average: 1.08 tokens
A player loses 0.4 tokens a spin

Try it yourself

import numpy as np

price = float(input())

# The prize of each zone of the wheel, in tokens, and its chance
prizes = np.array([0, 1, 4, 10])
chances = np.array([0.5, 0.3, 0.15, 0.05])

# Don't change the lines below: 4000 simulated spins
rng = np.random.default_rng(9)
spins = rng.choice(prizes, size=4000, p=chances)

# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Statistics for ML

Practice on your own: Online Python compiler