Statistics and simulation
Mean, median, mode, standard deviation, a histogram, prime numbers and an estimate of pi from random points — small formulas written as small functions, and checked against .NET.
What you will learn#
- the common statistics and how to compute them,
- writing each formula as a function,
- cross-checking with LINQ,
- the sieve of Eratosthenes,
- a Monte Carlo simulation with a seeded
Random.
The program#
# numbers - statistics, primes and a simulation (Monte Carlo estimate of pi)
load "dotnet.ring"
using {
"System"
"System.Linq"
}
func main
aData = [4,8,15,16,23,42,8,15,8,4]
# 1. The usual summaries of a set of numbers
? "Data : " + joinList(aData)
? "Count, sum : " + len(aData) + ", " + sumOf(aData)
? "Mean (average) : " + mean(aData)
? "Median (middle): " + median(aData)
? "Mode (common) : " + mode(aData)
? "Smallest, largest: " + min(aData) + ", " + max(aData)
? "Standard deviation: " + stdDev(aData)
# 2. .NET gives the same answer with LINQ: a check of our own code
? nl + "LINQ average : " + dnQuery(aData).Average("") + " (same as the mean)"
# 3. A histogram: how often each value occurs, as bars of #
? nl + "Histogram:"
aValues = []
aSortedValues = sort(aData)
for nValue in aSortedValues
if find(aValues,nValue) = 0
aValues + nValue
ok
next
for nValue in aValues
? " " + right(" " + nValue,2) + " " + copies("#",count(aData,nValue))
next
# 4. Primes: the sieve of Eratosthenes
aPrimes = primesUpTo(100)
? nl + "Primes up to 100: " + len(aPrimes) + " of them, the last is " + aPrimes[len(aPrimes)]
# 5. Greatest common divisor and least common multiple
? nl + "gcd(84, 36) = " + gcd(84,36) + ", lcm(4, 6) = " + lcm(4,6)
# 6. A simulation: throw random points into a square. The share that falls inside the quarter circle is pi / 4
oRandom = new Random(2024) # a fixed seed: the same numbers in every run
nInside = 0
nThrows = 20000
for nThrow = 1 to nThrows
nX = oRandom.NextDouble()
nY = oRandom.NextDouble()
if nX * nX + nY * nY <= 1
nInside++
ok
next
? nl + "Estimate of pi from " + nThrows + " random points: " + (4 * nInside / nThrows)
? "Math.PI : " + new Math().PI
# ---------------------------------------------------------------- the formulas (small functions, each testable)
func sumOf aList
nSum = 0
for nValue in aList
nSum += nValue
next
return nSum
func mean aList
return sumOf(aList) / len(aList)
func median aList
aSorted = sort(aList)
nMiddle = len(aSorted) / 2
if len(aSorted) % 2 = 1
return aSorted[ceil(nMiddle)]
ok
return (aSorted[nMiddle] + aSorted[nMiddle + 1]) / 2
func mode aList
nBest = aList[1]
nBestCount = 0
for nValue in aList
nTimes = count(aList,nValue)
if nTimes > nBestCount
nBest = nValue
nBestCount = nTimes
ok
next
return nBest
func stdDev aList
nMean = mean(aList)
nSquares = 0
for nValue in aList
nSquares += (nValue - nMean) * (nValue - nMean)
next
return sqrt(nSquares / len(aList))
func count aList, nValue
nTimes = 0
for nItem in aList
if nItem = nValue
nTimes++
ok
next
return nTimes
func primesUpTo nLimit
aIsPrime = list(nLimit)
for nIndex = 1 to nLimit
aIsPrime[nIndex] = True
next
aIsPrime[1] = False
for nNumber = 2 to floor(sqrt(nLimit))
if aIsPrime[nNumber]
for nMultiple = nNumber * nNumber to nLimit step nNumber
aIsPrime[nMultiple] = False
next
ok
next
aPrimes = []
for nIndex = 1 to nLimit
if aIsPrime[nIndex]
aPrimes + nIndex
ok
next
return aPrimes
func gcd nA, nB
while nB != 0
nTemp = nB
nB = nA % nB
nA = nTemp
end
return nA
func lcm nA, nB
return nA * nB / gcd(nA,nB)
func copies cText, nTimes
cResult = ""
for nIndex = 1 to nTimes
cResult += cText
next
return cResult
func joinList aList
cText = ""
for xItem in aList
if cText != ""
cText += ", "
ok
cText += xItem
next
return cTextData : 4, 8, 15, 16, 23, 42, 8, 15, 8, 4
Count, sum : 10, 143
Mean (average) : 14.30
Median (middle): 11.50
Mode (common) : 8
Smallest, largest: 4, 42
Standard deviation: 10.85
LINQ average : 14.30 (same as the mean)
Histogram:
4 ##
8 ###
15 ##
16 #
23 #
42 #
Primes up to 100: 25 of them, the last is 97
gcd(84, 36) = 12, lcm(4, 6) = 12
Estimate of pi from 20000 random points: 3.16
Math.PI : 3.14The statistics#
| Name | Meaning | Function |
|---|---|---|
| Mean | the average: sum ÷ count | mean |
| Median | the middle value of the sorted list (the average of the two middle ones when the count is even) | median |
| Mode | the value that occurs most often | mode |
| Standard deviation | how far values are from the mean, typically: the square root of the average squared distance | stdDev |
For the data 4 8 15 16 23 42 8 15 8 4 (sorted: 4 4 8 8 8 15 15 16 23 42):
- the mean is
14.3; - the median: there are ten values, so the middle is the pair at positions 5 and 6, which are
8and15:(8 + 15) / 2 = 11.5; - the mode is
8(it occurs three times); - the standard deviation is about
10.85: the values are spread out.
The mean is pulled up by the single large value 42; the median is not. That is why reports often use the median for incomes and house prices.
How it works#
One function per formula#
Each statistic is a small function with one job that takes a list and returns a number. You can test each alone (see the tutorial Testing your programs), reuse them, and the main program reads like a description of the results. The program also asks LINQ for the average (dnQuery(aData).Average("")) and gets the same 14.3: when two independent ways agree, you can trust the code.
The histogram#
A histogram counts how often each value occurs and shows it as a bar of # characters. The program collects the distinct values (find prevents duplicates), sorts them, and for each prints the value and a bar as long as the count.
The sieve of Eratosthenes#
To find all primes up to 100: write down every number from 2; take the first unmarked number (2), mark all its multiples (4, 6, 8...) as not prime; take the next unmarked number (3), mark its multiples; continue up to √100. What stays unmarked is prime. The code keeps a list of 100 flags and marks multiples with for nMultiple = nNumber * nNumber to nLimit step nNumber. There are 25 primes up to 100, the last is 97.
gcd and lcm#
Euclid's algorithm: the greatest common divisor of two numbers is the same as that of the smaller one and the remainder of their division. Repeat until the remainder is 0. The least common multiple follows: a × b ÷ gcd.
A simulation#
Throw random points into the unit square. The quarter circle of radius 1 has an area of π/4 and the square has an area of 1, so the share of points that fall inside the circle (x² + y² ≤ 1) is about π/4. With 20000 points the estimate is close to 3.14. new Random(2024) uses a seed: the same seed gives the same random numbers every time, which makes a simulation repeatable (leave the seed out for different numbers every run). More points give a better estimate, slowly: ten times more points give about three times more accuracy.
Ring prints a number with two decimals (3.16); the value itself is more precise. decimals(6) at the start of a program shows more.
What you learned#
- mean, median, mode, standard deviation,
- histograms from counts,
- the sieve, gcd, lcm,
- simulation with a seeded
Random, - verify a result with a second method.
Exercises#
- Compute the 90th percentile of a list.
- Simulate 1000 throws of two dice and print the histogram of the sums.
- Find all perfect numbers below 10000 (a number that equals the sum of its divisors).
- Estimate the probability that two random people in a group of 23 share a birthday (the birthday paradox) with 10000 simulated groups.