How likely is that?
Toss a coin ten times. Five heads is the likeliest outcome – but how likely, exactly? Statistics answers such questions with distributions: they say how often each outcome is to be expected. SciRuby's gem distribution knows the important ones; Claudio Bustos and Carlos Agarie wrote it.
For coin tosses it is the binomial distribution: n tries, each succeeding with the probability p. pdf(k, n, p) says how likely exactly k hits are:
install_gem "distribution"
require "distribution"
# toss a coin 10 times: how likely are exactly 5 heads?
Distribution::Binomial.pdf(5, 10, 0.5)0.246 – just under a quarter. Probabilities lie between 0 (never) and 1 (certain). And all the other outcomes?
(0..10).map { |heads| [heads, Distribution::Binomial.pdf(heads, 10, 0.5).round(3)] }.to_hFive is in the middle, and the further away, the rarer: 0 or 10 heads come up about once in a thousand times. All eleven numbers add up to 1 – some outcome always comes out.
cdf(k, n, p) adds up everything up to and including k: at most 3 heads. Whether that is right, the cell tries out for itself – ten tosses, 10,000 times, with Ruby's rand:
at_most_3 = Distribution::Binomial.cdf(3, 10, 0.5)
tried = 10_000.times.count { 10.times.count { rand < 0.5 } <= 3 }
[at_most_3.round(3), tried / 10_000.0]17.2 % worked out, and about as much tried out – a little different on every run, because rand throws anew each time.
Many measurements look different: heights, weights, measuring errors. They cluster around an average and get rarer to both sides – the normal distribution, also called the bell curve. Normal.rng builds a die for it: each call gives a random number, here a height around 170 cm, mostly no more than 8 cm off. With the seed 2024, every run brings the same 500 heights. In a Daru::Vector (lesson 75) they do their statistics at once:
install_gem "daru"
require "daru"
dice = Distribution::Normal.rng(170, 8, 2024) # mean 170 cm, spread 8 cm, seed 2024
heights = Daru::Vector.new(Array.new(500) { dice.call.round(1) })
[heights.mean.round(1), heights.sd.round(1), heights.min, heights.max]Mean 169.8, spread 8.5 – almost exactly what we ordered, but only almost: 500 random numbers are no perfect bell.
Let's look at them. SciRuby's charts are drawn by Rubyvis, by Claudio Bustos as well: a translation of Protovis, the JavaScript library from Stanford that D3 later followed. A chart is a Panel with marks in it – bar for bars, rule for lines with labels – and every mark gets data, and for every property a value or a block. Scale.linear turns centimetres into points. Rubyvis writes SVG, and show_image shows it:
install_gem "rubyvis"
require "rubyvis"
# how many in each step of 4 cm: 160 means 160 to 163.9
steps = heights.to_a.group_by { |cm| (cm / 4).floor * 4 }.transform_values(&:size).sort
x = Rubyvis::Scale.linear(140, 200).range(0, 400) # cm -> points to the right
y = Rubyvis::Scale.linear(0, 100).range(0, 200) # how many -> points up
chart = Rubyvis::Panel.new do
width 400
height 200
left 20
right 20
bottom 20
bar do
data steps
left { |step| x.scale(step[0]) }
width 25
bottom 0
height { |step| y.scale(step[1]) }
fill_style "#e8722a"
end
rule do
data x.ticks
left { |cm| x.scale(cm) }
bottom(-5)
height 5
label(anchor: "bottom").text { |cm| cm.to_s }
end
end
show_image chart, alt: "Bars: how many of the 500 are how tall"One bar for every 4 cm, and its height says how many are that tall: most in the middle, few at the edges. Over them belongs the bell we ordered. Normal.pdf says how densely the values lie at a point – for the standard bell around 0 with the spread 1. So each height is first converted into spreads above the mean: (cm - 170) / 8.0. Divided by 8, times 500 people and times 4 cm per bar, that becomes the count that would belong in a bar. chart.line puts the curve into the same picture:
chart.line do
data (140..200).to_a
left { |cm| x.scale(cm) }
bottom do |cm|
count = 500 * 4 * Distribution::Normal.pdf((cm - 170) / 8.0) / 8
y.scale(count)
end
stroke_style "#333"
line_width 2
end
show_image chart, alt: "The bars, and the bell curve over them"The bars follow the curve, now a little above, now below – that is what chance looks like.
How many people are taller than 185 cm? Normal.cdf(z) says which part of the bell lies to the left of z; what lies to the right is the rest up to 1. Next to it, we count among our 500:
z = (185 - 170) / 8.0 # 1.875 spreads above the mean
expected = 1 - Distribution::Normal.cdf(z)
counted = heights.to_a.count { |cm| cm > 185 } / 500.0
[expected.round(3), counted]3 % says the bell, 3.6 % it is in our sample – 18 out of 500.
The area under the curve to the right of 185 is exactly that probability. Areas under curves are what the integral works out, and SciRuby's gem integration does it with numbers: it cuts the area into narrow strips and adds them up. Instead of going to infinity, 250 cm is enough – there the bell is so flat that nothing more comes in:
install_gem "integration"
require "integration"
density = ->(cm) { Distribution::Normal.pdf((cm - 170) / 8.0) / 8 }
Integration.integrate(185, 250, &density)0.0304 – the same as with cdf, to four places.
One more question, and one more gem: which number lies closest to the 500 heights? "Closest" means here: the distances to all of them, each one squared, should add up to as little as possible. minimization looks for the point where a function is smallest. Richard Brent's method, Brent, needs only a range to search and the function as a lambda:
install_gem "minimization"
require "minimization"
distance = ->(m) { heights.to_a.sum { |cm| (cm - m)**2 } }
search = Minimization::Brent.new(150, 190, distance)
search.iterate
[search.x_minimum.round(2), heights.mean.round(2)]It found 169.79 – exactly the mean. That is no coincidence: the mean is the number for which the squared distances add up to the least. That is where the method for laying straight lines through measured points gets its name: the method of least squares.
gem install distribution integration minimization rubyvis. With Bundler, prime, bigdecimal, ostruct and rexml belong in the Gemfile too: these gems need them, and they are no longer among Ruby's default gems. If the gem gsl is installed, distribution computes with the GNU Scientific Library in C. chart.to_svg gives a chart's SVG as text – to save in a file, after chart.render has drawn it. distribution, minimization and Rubyvis come under the BSD licence, integration under the MIT licence.
chance.install_gem "distribution"
require "distribution"
throws = 20 # a six comes up with the probability 1/6
# chance = ... (at least 5 sixes)