Skip to content

Instantly share code, notes, and snippets.

@ryana
Created April 7, 2015 18:33
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 ryana/af156d4a087791e1807a to your computer and use it in GitHub Desktop.
Save ryana/af156d4a087791e1807a to your computer and use it in GitHub Desktop.
Testing to see if the to_i(16)/modulo of SHA256 has a uniform distribution
h = {}
1_000_000.times do |i|
puts i if (i % 1_000 == 0)
str = (0...16).map { (65 + rand(26)).chr }.join
digest = (Digest::SHA256.new << str).to_s
num = digest.to_i(16) % 100
h[num] ||= 0
h[num] += 1
end
h.values.inject(0) {|s,n| s + n } / h.values.size.to_f #=> 10000.0
module Enumerable
def sum
return self.inject(0){|accum, i| accum + i }
end
def mean
return self.sum / self.length.to_f
end
def sample_variance
m = self.mean
sum = self.inject(0){|accum, i| accum + (i - m) ** 2 }
return sum / (self.length - 1).to_f
end
def standard_deviation
return Math.sqrt(self.sample_variance)
end
end
h.values.standard_deviation #=> 96.69550249117175
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment