CBuilderLab· about 40 min· in the browser
Lab: simulate dice and compare with the theory
Estimate a probability with simulation (Monte Carlo) and see that the frequency approaches the theory as the number of trials grows.
Theory
P(the sum of two dice = 7) = 6/36 ≈ 0.167. Simulate 20,000 rolls with a fixed random seed and count the share of sevens. Relative frequency → probability (the law of large numbers).
Sub-tasks
- kasta_tva(rng) — roll two — Return the sum of two dice rolls using
rng.randint(1, 6). - andel_sjuor(n, seed) — share of sevens — Simulate n rolls with
random.Random(seed)and return the share that came out as 7. - teoretisk_sannolikhet(summa) — theoretical probability — Return the exact probability of a given sum 2–12.
The starter code
runs in your browserimport random
def kasta_tva(rng):
# TODO: summan av två kast med rng.randint(1, 6)
...
def andel_sjuor(n, seed=0):
# TODO: rng = random.Random(seed); räkna hur många av n kast som blir 7
...
def teoretisk_sannolikhet(summa):
# TODO: antal gynnsamma par (a, b) med a + b == summa, delat med 36
...
You write the code; tests you cannot see decide whether it holds up. Create a free account to run the lab.
Try the diagnosticCreate a free accountExpected results
andel_sjuor(20000, 1) within ±0.01 of 0.1667; teoretisk_sannolikhet(7) = 6/36; teoretisk_sannolikhet(2) = 1/36.
Common mistakes
randint(1, 6)includes 6 (unlikerange).- A new random seed in every call makes the result irreproducible — create
Random(seed)once. - Counts sums 1–12 instead of 2–12.