Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created December 27, 2017 05:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/4cc4608bc21c4ed74c73b04ba85239c7 to your computer and use it in GitHub Desktop.
Save JoshCheek/4cc4608bc21c4ed74c73b04ba85239c7 to your computer and use it in GitHub Desktop.
Settlers of Catan dice test
# http://www.itl.nist.gov/div898/handbook/eda/section3/eda3674.htm
def chi_sqr(rolls)
counts = rolls.group_by(&:itself).map { |k, v| [k, v.length] }.sort.to_h
expected = rolls.length / 6.0
chis = 1.upto(6).map do |n|
counts[n]
counts[n] - expected
(counts[n] - expected)**2
((counts[n] - expected)**2) / expected
end
chis.reduce(0, :+)
end
# Probability less than the critical value
# ν 0.90 0.95 0.975 0.99 0.999
# 5 9.236 11.070 12.833 15.086 20.515
#
# If the chi squared value is less than the number here, then we are that
# percentage confident that it is not biased. If it is over that value,
# then we are that percentage confident that it is biased.
#
# I chose 180 rolls b/c 5*36 = 180, 5 b/c that's what was suggested here:
# https://rpg.stackexchange.com/questions/70802/how-can-i-test-whether-a-die-is-fair
# and 36 b/c that's how many possibilities 2 dice can have.
red_rolls, yel_rolls = DATA.readlines.map { |l| l.split.map &:to_i }.transpose
chi_sqr red_rolls # => 5.666666666666668
chi_sqr yel_rolls # => 2.6666666666666665
# 99% confident that the bad die is biased.
good_die = [*1..6]
bad_die = [*1..6, 6]
chi_sqr 180.times.map { good_die.sample } # => 4.333333333333333
chi_sqr 180.times.map { bad_die.sample } # => 15.666666666666668
__END__
6 6
4 1
6 6
1 6
3 4
3 6
1 4
4 1
4 4
5 2
5 6
2 5
4 6
1 6
1 1
6 1
6 2
6 3
1 5
6 1
4 2
6 3
4 4
3 4
6 3
4 5
5 2
3 4
2 4
1 1
3 1
5 6
3 2
5 5
3 4
5 1
3 4
3 4
4 2
6 2
3 1
1 5
3 6
2 1
6 4
4 4
1 2
5 3
5 3
3 2
5 6
4 1
2 6
4 3
5 6
1 1
4 5
4 3
4 3
1 4
4 2
4 3
6 2
1 1
2 3
4 6
4 2
1 1
5 3
2 6
6 5
6 6
4 5
3 6
2 5
5 4
4 2
2 3
4 1
1 4
2 5
4 2
3 5
6 6
1 6
1 1
1 5
2 3
3 4
5 5
5 4
6 1
5 3
1 3
6 2
4 6
3 6
1 1
1 4
1 1
4 2
2 3
6 6
4 2
3 2
5 5
5 6
3 2
5 2
2 6
4 1
5 6
5 3
4 5
1 5
3 2
5 4
6 6
4 3
6 2
4 4
2 5
5 4
4 4
5 5
4 2
3 2
5 5
1 5
2 3
3 2
2 3
3 3
5 3
4 2
6 4
3 3
5 2
6 2
3 3
2 4
6 3
4 4
5 2
6 3
4 4
1 6
4 2
2 4
1 3
3 4
2 4
1 6
3 1
5 5
5 5
3 2
5 5
1 4
2 6
6 4
3 5
2 1
1 1
5 4
1 3
6 4
3 2
6 5
6 3
4 2
4 3
2 1
1 6
5 5
6 4
3 5
4 6
4 3
1 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment