Class: RandomBell

Inherits:
Object
  • Object
show all
Defined in:
lib/random_bell.rb,
lib/random_bell/version.rb

Constant Summary collapse

VERSION =
"0.1.0"

Instance Method Summary collapse

Constructor Details

#initialize(mu: 0.5, sigma: 0.2, range: 0.0..1.0, method: :box_muller) ⇒ RandomBell

Returns a new instance of RandomBell.



4
5
6
7
8
9
# File 'lib/random_bell.rb', line 4

def initialize(mu: 0.5, sigma: 0.2, range: 0.0..1.0, method: :box_muller)
  @mu     = mu
  @sigma  = sigma
  @range  = range
  @method = method
end

Instance Method Details

#normalObject



15
16
17
# File 'lib/random_bell.rb', line 15

def normal
  @mu + standard * @sigma
end

#randObject



19
20
21
22
23
24
# File 'lib/random_bell.rb', line 19

def rand
  loop do
    num = normal
    return num if @range.include?(num)
  end
end

#standardObject



11
12
13
# File 'lib/random_bell.rb', line 11

def standard
  send(@method)
end

#to_histogram(rows: 20, size: 10 ** 4) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/random_bell.rb', line 26

def to_histogram(rows: 20, size: 10 ** 4)
  histogram = ""

  numbers = (1..size).to_a.map{ rand }

  klasses, klass_width = [], (@range.max - @range.min).to_f / rows
  (0..rows).each_cons(2) do |min, max|
    klasses << Range.new(klass_width * min, klass_width * max)
  end

  divider = (klasses.map{|klass| numbers.select{|num| klass.include?(num) }.size }.max / 50.0).ceil
  klasses.each do |klass|
    n = numbers.select{|num| klass.include?(num) }.size / divider
    histogram << sprintf("%+3.3f", klass.max) << ": " << "*" * n << "\n"
  end

  histogram
end