Skip to content

Instantly share code, notes, and snippets.

@ryana ryana/sha.rb
Created Apr 7, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.