Skip to content

Instantly share code, notes, and snippets.

@satyr
Created December 14, 2009 05:16
Show Gist options
  • Save satyr/255805 to your computer and use it in GitHub Desktop.
Save satyr/255805 to your computer and use it in GitHub Desktop.
Shapley-Shubik/Banzhaf power indices
# coding: utf-8
require 'mathn'
class PICalc
def initialize name, parties
@name = name
@parties = parties
@total = parties.values.inject :+
@perms = parties.to_a.permutation.to_a
end
def ss pass_rate
thresh = @total * pass_rate
dic = Hash[@parties.map{|k,| [k, 0] }]
@perms.each do |pe|
sum = 0
key = pe.each{|k, v| break k if (sum += v) > thresh }
dic[key] += 1
end
show :'Shapley-Shubik', pass_rate, dic, @perms.size
end
def b pass_rate
thresh = @total * pass_rate
dic = Hash[@parties.map{|k,| [k, 0] }]
ptotal = @parties.size ** 2
(1...ptotal).each do |vec|
sum = 0
@parties.each_with_index{|(_, v), i| sum += v * vec[i] }
@parties.each_with_index do |(k, v), i|
next if vec[i] == 0 and not (sum...sum+v) === thresh
next if vec[i] == 1 and not (sum-v...sum) === thresh
dic[k] += 1
end
end
show :Banzhaf, pass_rate, dic, ptotal
end
def show type, rate, dic, total
puts "#{type} Power Indices of #@name\n(over #{rate} seats needed)"
puts dic.sort_by{|_, v| -v }.map!{|k, v| "#{k}\t#{v / total}" }
puts
self
end
end
{ #http://www.shugiin.go.jp/itdb_annai.nsf/html/statics/syu/kaiha_m.htm
衆議院: {
民主: 311,
自民: 119,
公明: 21,
共産: 9,
社民: 7,
他: 13,
},
#http://www.sangiin.go.jp/japanese/joho1/kousei/giin/173/giinsu.htm
参議院: {
民主: 120,
自民: 85,
公明: 21,
共産: 7,
社民: 5,
他: 4,
},
}.each{|_| PICalc.new(*_).ss(1/2).ss(2/3).b(1/2).b(2/3) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment