Expected Payout and Fair Reroll Fee in a Dice Game
Medium · Statistics & Math · Data Scientist · Online Assessment
Problem Statement
Consider a sequential game played with a six-sided die bearing faces 1 through 6. On every throw, you collect dollars equal to the number shown on the die. Whenever the die shows 4, 5, or 6, play continues with another throw; the very first time the die shows 1, 2, or 3, you still collect that throw's face value and the game ends immediately.
- Balanced die: Assuming all six faces are equally likely, derive the player's expected gross winnings from a full game, showing every algebraic step (either by conditioning on the stopping throw or by summing an infinite series, or via first-step conditioning).
- Weighted die: Generalize to an arbitrary six-sided die where a single throw lands in
{4, 5, 6}with probabilitypand has unconditional expected face valuemu. Express the expected gross winnings in terms ofpandmu. - Paid rerolls: Suppose the opening throw is free, whereas every subsequent throw (
2, 3, ...) deducts a constant feec. Derive the fair feecat which expected net profit is0.
Implement expected_payoff_and_break_even_cost(p: float, mu: float) -> List[Optional[float]] returning [expected_gross_winnings, fair_reroll_fee]:
- If p == 1.0, the game never terminates, so return [None, None].
- If p == 0.0, the game always halts on the free opening throw (expected_gross_winnings = mu) and no paid reroll ever occurs, so return [mu, None].
- If p lies outside [0.0, 1.0] or is NaN, raise ValueError.
Examples
Example 1
Input: p = 0.2, mu = 2.4
Output: [3.0, 12.0]
Walk-through: Each throw stops play with probability 1 - 0.2 = 0.8, so the expected throw count is 1 / 0.8 = 1.25 and expected gross winnings are 2.4 * 1.25 = 3.0. Because only 1.25 - 1 = 0.25 paid rerolls occur on average, offsetting 3.0 requires charging 3.0 / 0.25 = 12.0 (mu / p = 2.4 / 0.2) per reroll.
Example 2
Input: p = 0.6, mu = 4.2
Output: [10.5, 7.0]
Walk-through: Stopping probability is 1 - 0.6 = 0.4, giving expected gross winnings 4.2 / 0.4 = 10.5. Expected paid rerolls equal 0.6 / 0.4 = 1.5, so the fair reroll fee is 10.5 / 1.5 = 7.0 (4.2 / 0.6).
Example 3
Input: p = 0.0, mu = 2.5
Output: [2.5, None]
Walk-through: Since p = 0.0, every throw lands in {1, 2, 3} and halts immediately after the free opening throw, paying 2.5 on average. Because a second throw never happens, no per-reroll fee c can make expected net profit equal 0, so the second entry is None.
Constraints
0.0 <= p <= 1.0for valid probabilities; raiseValueErrorifp < 0.0,p > 1.0, orpisNaN.muis a finite floating-point number representing the single-throw mean.- Numeric entries in the returned two-element list are compared within
10^-6relative/absolute tolerance.
Step-by-step walkthrough
Understand the game mechanics and boundary cases
Let us map out one complete play of the die game:
+-------------------------------------------+ v | [ Throw die: earn face value X ] ---> X in {4, 5, 6}? -- Yes (prob p) --+ | (on throws 2+, No: X in {1, 2, 3} (prob 1 - p) deduct fee c!) v [ HALT ]Keep two rule details front and center: 1. Every throw pays its face value — including the terminating low throw (
1,2, or3)! 2. In the fee variant, only throws after the opening throw (throws2, 3, ...) incur feec; throw1is free.The function
expected_payoff_and_break_even_cost(p, mu)receives the continuation probabilityp = P(X in {4, 5, 6})and single-throw meanmu, and returns[expected_payout, break_even_cost](usingNonewhenever a quantity is undefined atp == 1.0orp == 0.0).Balanced die (Method 1): first-step conditioning
Start with a balanced six-sided die (
p = 1/2,mu = 3.5), and letEdenote the expected gross winnings.First confirm
Eis finite so algebraic rearrangement is valid: each throw pays at most6, and the throw countNis geometric with stopping probability1/2(E[N] = 2), giving0 <= E <= 6 * 2 = 12 < infinity.Now condition on the opening throw: - Faces
1, 2, 3(probability1/6each): collect1,2, or3and halt right away. - Faces4, 5, 6(probability1/6each): collect4,5, or6and continue into a brand-new, independent copy of the exact same game worthEin expectation!Averaging over all six faces:
E = (1/6)*1 + (1/6)*2 + (1/6)*3 + (1/6)*(4 + E) + (1/6)*(5 + E) + (1/6)*(6 + E) = (1 + 2 + 3 + 4 + 5 + 6) / 6 + (3 / 6) * E = 21 / 6 + 0.5 * E = 3.5 + 0.5 * ESubtracting
0.5 * Efrom both sides gives:0.5 * E = 3.5 => E = 3.5 / 0.5 = 7Balanced die (Method 2): stopping-time infinite series
We can also obtain
7by conditioning on the stopping throwN(the index of the first outcome in{1, 2, 3}).Stopping on throw
n(n >= 1) requiresn - 1consecutive high outcomes in{4, 5, 6}followed by one low outcome in{1, 2, 3}:P(N = n) = (1/2)^(n - 1) * (1/2) = (1/2)^nConditioned on
N = n, what do thenthrows sum to on average? - Each of the firstn - 1throws is uniform on{4, 5, 6}, averaging(4 + 5 + 6) / 3 = 5. - Then-th throw is uniform on{1, 2, 3}, averaging(1 + 2 + 3) / 3 = 2. - HenceE[total | N = n] = 5 * (n - 1) + 2 = 5n - 3.Weighting by
P(N = n)and summing acrossn = 1, 2, 3, ...:E[total] = sum_{n = 1}^{inf} (5n - 3) * (1/2)^n = 5 * sum_{n = 1}^{inf} n * (1/2)^n - 3 * sum_{n = 1}^{inf} (1/2)^nEvaluate the two standard series for
|r| < 1atr = 1/2: 1. Geometric series:S_0 = r + r^2 + r^3 + ... = r / (1 - r) = (1/2) / (1/2) = 1. 2. Arithmetico-geometric seriesS_1 = r + 2r^2 + 3r^3 + ...: subtractingr * S_1fromS_1yields(1 - r) * S_1 = r / (1 - r), soS_1 = r / (1 - r)^2 = (1/2) / (1/4) = 2.Substitute
S_1 = 2andS_0 = 1:E[total] = 5 * 2 - 3 * 1 = 10 - 3 = 7Generalize to a weighted die with parameters p and mu
Now let
P(X in {4, 5, 6}) = p(0 <= p < 1) andE[X] = mu.Write
mu_high = E[X | X in {4, 5, 6}]andmu_low = E[X | X in {1, 2, 3}]. By total expectation on a single throw, those conditional means combine tomu:mu = p * mu_high + (1 - p) * mu_lowConditioning on the opening throw gives: - With probability
p, we earnmu_highon average and restart an identical game worthE. - With probability1 - p, we earnmu_lowon average and halt.E = p * (mu_high + E) + (1 - p) * mu_low = [ p * mu_high + (1 - p) * mu_low ] + p * E = mu + p * ENotice that
mu_highandmu_lowrecombine directly intomu! Solving forE:(1 - p) * E = mu => E = mu / (1 - p)Series cross-check: throw
n(n >= 1) is reached if and only if the precedingn - 1throws were all high (probabilityp^(n - 1)), and whenever thrownis reached, its fresh outcome has meanmu. Summingmu * p^(n - 1)overn >= 1again givesmu / (1 - p).Derive the fair per-reroll fee c
When each throw after the first deducts
c, a game lastingNthrows chargesc * (N - 1).Since each throw halts with probability
1 - p, total throws satisfyE[N] = 1 / (1 - p). Subtracting the1free opening throw leaves the expected count of paid rerolls:E[N - 1] = 1 / (1 - p) - 1 = (1 - (1 - p)) / (1 - p) = p / (1 - p)Setting expected net profit to
0:expected_payout - c * E[N - 1] = 0 mu / (1 - p) - c * p / (1 - p) = 0Multiplying through by
1 - p > 0cancels the denominator cleanly:mu - c * p = 0 => c = mu / p (for 0 < p < 1)On the balanced die (
p = 0.5, mu = 3.5),c = 3.5 / 0.5 = 7.0: you collect7.0on average across1.0expected paid reroll, so charging7.0per reroll makes the game fair.Guard boundary probabilities cleanly in Python
Check three edge cases before dividing:
- Out-of-range or
NaNprobability: writeif not (0.0 <= p <= 1.0): raise ValueError(...). Usingnot (...)is critical because IEEE-754NaNevaluates<and>toFalse, sop < 0 or p > 1would fail to rejectfloat("nan"). p == 1.0: play never halts (1 - p == 0), so return[None, None].p == 0.0: play always halts on throw1(expected_payout = mu) with zero paid rerolls (E[N - 1] == 0), so return[expected_payout, None].
if not (0.0 <= p <= 1.0): raise ValueError("p must be a probability in [0, 1]") if p == 1.0: return [None, None] stop_prob = 1.0 - p expected_payout = mu / stop_prob if p == 0.0: return [expected_payout, None] break_even_cost = mu / p return [expected_payout, break_even_cost]- Out-of-range or
Trace Examples 1–3
Let us verify all three walkthrough examples from the statement:
Example | p | mu | stop_prob = 1 - p | E = mu / (1 - p) | c = mu / p --------+------+-----+-------------------+-------------------+------------ 1 | 0.20 | 2.4 | 0.80 | 2.4 / 0.80 = 3.0 | 2.4 / 0.20 = 12.0 2 | 0.60 | 4.2 | 0.40 | 4.2 / 0.40 = 10.5 | 4.2 / 0.60 = 7.0 3 | 0.00 | 2.5 | 1.00 | 2.5 / 1.00 = 2.5 | None (0 rerolls)Look at Example 1 (
p = 0.2, mu = 2.4): because paid rerolls happen only0.2 / 0.8 = 0.25times on average, each rare reroll must charge12.0to offset the3.0expected payout!Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def expected_payoff_and_break_even_cost(p: float, mu: float) -> List[Optional[float]]: """Return [expected_total_payout, break_even_reroll_cost] for a reroll dice game. Args: p: Probability in [0, 1] that a single roll lands in {4, 5, 6} (forcing another roll). mu: Expected face value of a single roll. """ # Phase 1: validate p. # Why 'not (0.0 <= p <= 1.0)' instead of 'p < 0 or p > 1': IEEE-754 NaN evaluates # every comparison to False, so 'not (0.0 <= p <= 1.0)' catches NaN as well. if not (0.0 <= p <= 1.0): raise ValueError("p must be a probability in [0, 1]") # Phase 2: handle p == 1 (game never terminates, so neither quantity is finite). if p == 1.0: return [None, None] # Phase 3: compute expected gross payout. # Each roll stops the game with probability (1 - p), so total roll count N ~ Geometric(1 - p) # has E[N] = 1 / (1 - p). Since each roll earns mu on average, E[payout] = mu / (1 - p). stop_prob = 1.0 - p expected_payout = mu / stop_prob # Phase 4: handle p == 0 (always stops on roll 1; zero paid rerolls ever occur, # so no per-reroll fee c can alter the net value). if p == 0.0: return [expected_payout, None] # Phase 5: compute break-even cost c charged on rolls 2, 3, ..., N. # Expected paid rerolls = E[N - 1] = p / (1 - p). # Setting expected_payout == c * (p / (1 - p)) cancels (1 - p) and gives c = mu / p. break_even_cost = mu / p # result: two-element list [expected_payout, break_even_cost], e.g. [7.0, 7.0]. return [expected_payout, break_even_cost]✅ Submit now — all tests should pass.
Intuition & how it works
Picture a carnival prize wheel where your opening spin is free, awards mu tickets on average, and with probability p lights up a "SPIN AGAIN" arrow that triggers the exact same process. Because independent throws obey the memoryless property (past outcomes do not alter future probabilities), hitting {4, 5, 6} places you at the start of a fresh copy of the game worth the same expected total E. That gives the one-line balance E = mu + p * E, solving directly to E = mu / (1 - p). Equivalently, Wald's identity (a theorem stating that summing independent identically distributed rewards up to a stopping time — a halt rule determined solely by outcomes observed so far without looking ahead — yields expected steps times single-step mean) gives the same result: since each throw halts with probability 1 - p, total throws N follow a geometric distribution (the trial count until the first halt event) with mean 1 / (1 - p), producing (1 / (1 - p)) * mu.
Why do brute-force attempts stumble? Listing every terminating path (2, 5 -> 1, 6 -> 4 -> 3, ...) branches without bound (3^(n - 1) * 3 sequences of length n). Even worse, candidates often write E[total | N = n] = n * mu, which is wrong: conditioning on halting at throw n forces throws 1 .. n - 1 into {4, 5, 6} (averaging 5 on a fair die, not 3.5) and throw n into {1, 2, 3} (averaging 2, not 3.5). Conditioning on just the first step — or summing indicator variables (0-or-1 variables marking whether throw n occurs) unconditionally — avoids that pitfall cleanly.
Let us walk through Example 2 (p = 0.6, mu = 4.2):
- Expected gross winnings E: throw 1 averages 4.2 and continues with probability 0.6, so E = 4.2 + 0.6 * E, giving 0.4 * E = 4.2, or E = 10.5.
- Expected paid rerolls: total throws average E[N] = 1 / (1 - 0.6) = 2.5. Subtracting the free opening throw leaves E[N - 1] = 1.5 paid rerolls.
- Fair reroll fee c: canceling 10.5 in gross winnings across 1.5 expected paid rerolls requires c = 10.5 / 1.5 = 7.0 (mu / p = 4.2 / 0.6 = 7.0).
Complexity
- Time: O(1). The code executes at most three comparisons, one subtraction, and two divisions regardless of how close
psits to1. - Space: O(1). Only scalar floats and the two-item output list
[expected_payout, break_even_cost]are allocated.
Edge cases
p = 0.0(never continues): play always halts on the free opening throw (expected_payout = mu), and because zero paid rerolls ever happen (E[N - 1] = 0), no per-reroll fee can zero out the player's advantage, returning[mu, None](Example 3).p = 1.0(never halts):1 - p = 0means play runs forever and winnings diverge, returning[None, None]cleanly instead of raisingZeroDivisionError.- Out-of-bounds or
NaNprobability: guarded vianot (0.0 <= p <= 1.0). Under IEEE-754NaN(the floating-point "Not a Number" value), comparisons likenan < 0andnan > 1both evaluate toFalse, whereas negating0.0 <= p <= 1.0catchesNaNproperly and raisesValueError. - Binary float rounding: expressions like
1.0 - 0.8evaluate to0.19999999999999996in IEEE-754 float, so callers and tests compare numeric results within relative/absolute tolerance rather than exact==.
Common mistakes
- Dropping the stopping throw's payout: counting only high throws
{4, 5, 6}yields5instead of7on a balanced die; the1,2, or3that ends play still pays its face value. - Dividing by
pinstead of1 - pforE[N]:pis the continuation probability while1 - pis the stopping probability. On a balanced die (p = 0.5), both equal0.5, masking the mistake until an asymmetric test like Example 1 (p = 0.2, mu = 2.4 -> E = 3.0, not12.0). - Charging
con throw 1 as well: charging allNthrows instead ofN - 1solvesmu / (1 - p) = c / (1 - p) => c = mu(2.4in Example 1 instead of12.0). - Getting stuck looking for
mu_highandmu_lowseparately: you do not need individual face weights becausep * mu_high + (1 - p) * mu_lowcollapses back intomu.
Alternative approaches
- Explicit stopping-time series: evaluate
E[total | N = n] = (n - 1) * mu_high + mu_lowagainstP(N = n) = p^(n - 1) * (1 - p)usingsum_{n>=1} (n - 1) p^(n - 1) (1 - p) = p / (1 - p)to obtain(p * mu_high + (1 - p) * mu_low) / (1 - p) = mu / (1 - p). Useful whenever an interviewer asks for a full series derivation. - Absorbing Markov chain equations: a Markov chain is a state system whose transition probabilities depend only on the current state; defining
ActiveandHaltedstates withV(Halted) = 0andV(Active) = mu + p * V(Active)solves this problem in one line and generalizes cleanly to multi-step stop rules (such as halting after two consecutive low throws).
Follow-up questions
- What is the payout variance for a fair six-sided die, and are p and mu sufficient to determine variance for an arbitrary weighted die? Write total payout recursively as
S = X + I_high * S', whereI_highequals1whenXlands in{4, 5, 6}andS'is an independent copy ofS. Squaring (S^2 = X^2 + 2 * X * I_high * S' + I_high * S'^2) and taking expectations givesE[S^2] = (E[X^2] + 2 * E[X * I_high] * E[S]) / (1 - p). On a balanced die (E[X^2] = 91/6,E[X * I_high] = 15/6 = 2.5,E[S] = 7,1 - p = 0.5), we getE[S^2] = (91/6 + 35) / 0.5 = 301/3andVar(S) = 301/3 - 49 = 154/3 ≈ 51.33— whereas for a weighted die,(p, mu)alone are not enough becauseVar(S)also depends onE[X^2]andE[X * I_high]. - Suppose the house replaces the per-reroll fee c with a single entry fee F paid before the first throw; what value of F makes the game fair? Since
Fis paid once up front on every play, expected net profit isE[payout] - F, so the break-even entry fee is simplyF = mu / (1 - p). On a balanced die (p = 0.5, mu = 3.5),F = 7andc = 7coincide only because expected paid rerollsp / (1 - p)equal1; in Example 1 (p = 0.2, mu = 2.4), the fair upfront fee is3.0whereas the fair per-reroll fee is12.0. - How can you quickly sanity-check your closed-form formulas with a simulation during an online assessment? Run a Monte Carlo simulation (approximating expectations by averaging many simulated random plays) across
N_sim = 50,000seeded games. WithVar(S) ≈ 51.33on a balanced die, the standard error (the typical sampling noise of an average, given bysqrt(Var(S) / N_sim)) is onlysqrt(51.33 / 50000) ≈ 0.032, instantly catching algebra slips like5.0(omitting the final throw) or3.5(charging throw 1).
Follow-up questions
- What is the payout variance for a fair six-sided die, and are p and mu sufficient to determine variance for an arbitrary weighted die?
- Suppose the house replaces the per-reroll fee c with a single entry fee F paid before the first throw; what value of F makes the game fair?
- How can you quickly sanity-check your closed-form formulas with a simulation during an online assessment?
Similar questions
- Binomial Tree Valuation for Equity Options and Bonds
- Handling an Inconclusive A/B Test Readout
- Ad Serving Economics, Mixture Variance, and Waiting Times
- Target Bankroll Probability with Biased Flips
- Statistical Inference and Sizing for Trip Cancellations
- Impact of Dataset Duplication on OLS and Large-Sample Inference