summaryrefslogtreecommitdiff
path: root/algorithms/bootstrap.rb
blob: 0f84d5731890d45564cde88609067089bfebdb24 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/usr/bin/env ruby

aspirin_total = 11037
aspirin_heart = 104
aspirin_pop = ([0]*(aspirin_total-aspirin_heart) + [1.0]*aspirin_heart).shuffle

placebo_total = 11034
placebo_heart = 189
placebo_pop = ([0]*(placebo_total-placebo_heart) + [1.0]*placebo_heart).shuffle

def sample a, n
  sample = []
  n.times { 
    sample << a[rand(n)]
  }

  return sample
end

ratios = []
(0).upto(100000) {
  
  aspirin_sample = sample(aspirin_pop, aspirin_total)
  placebo_sample = sample(placebo_pop, placebo_total)
  
  r = aspirin_sample.inject(:+) / placebo_sample.inject(:+)
  ratios << r
}

ratios.sort!

mean = ratios.inject(:+)/ratios.size
var = 0
ratios.each { |r|
  var +=  (mean - r)**2
}
stddev = Math.sqrt(var/ratios.size)

puts "mean = %f"%mean
puts "stddev = %f"%stddev

_25th = ratios[0,0.25*ratios.size]
puts "25th = %f"%(_25th.inject(:+)/_25th.size)

_975th = ratios[0.975*ratios.size, ratios.size]
puts "975th = %f"%(_975th.inject(:+)/_975th.size)