Skip to content

Instantly share code, notes, and snippets.

@Ikariusrb
Last active August 7, 2020 04:24
Show Gist options
  • Save Ikariusrb/f5d6025b31b9d66c63f9c93a53535f34 to your computer and use it in GitHub Desktop.
Save Ikariusrb/f5d6025b31b9d66c63f9c93a53535f34 to your computer and use it in GitHub Desktop.
Ruby RNG that returns a normal distribution between two integers
# MIT License
# Copyright (c) 2020 Ross Becker
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
class GaussianRandom
attr_reader :min, :max, :mean, :deviation, :results
def initialize(min, max, deviation: 3.5)
@min, @max = min, max
@mean = min + ((max - min) / 2.0)
@deviation = (max - min) / 2.0 / deviation
@results = []
end
def call
r = nil
until (min..max).cover? r
results.push(*box_muller(mean, deviation)) if results.empty?
r = results.shift
end
return r
end
private
def box_muller(mean, deviation)
s = nil
until (0.0..1.0).cover? s
v1 = 2.0 * Kernel.rand - 1.0;
v2 = 2.0 * Kernel.rand - 1.0;
s = v1 * v1 + v2 * v2;
end
s = Math.sqrt((-2.0 * Math.log(s)) / s);
return (mean+(v1*s)*deviation).round, (mean+(v2*s)*deviation).round
end
end
# USE:
# rng = GaussianRandom.new( MIN_VAL, MAX_VAL), rng.call
# You can change the distribution by passing an optional distribution parameter, lower numbers will spread the curve.
#
rn_gauss = GaussianRandom.new(3,8)
dist = Array.new(10000) { rn_gauss.call }.each_with_object(Hash.new(0)) { |val,h| h[val] += 1 }.sort
puts "Dist: #{dist}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment