Class: Rubythinking::Distributions::Normal

Inherits:
Object
  • Object
show all
Defined in:
lib/rubythinking/distributions/normal.rb

Class Method Summary collapse

Class Method Details

.density(x, mean = 0, std = 1) ⇒ Object

Probability density function



19
20
21
22
23
# File 'lib/rubythinking/distributions/normal.rb', line 19

def self.density(x, mean = 0, std = 1)
  coefficient = 1.0 / (std * Math.sqrt(2 * Math::PI))
  exponent = -0.5 * ((x - mean) / std) ** 2
  coefficient * Math.exp(exponent)
end

.random(mean = 0, std = 1) ⇒ Object

Generate a single normal random variable using Box-Muller transform



5
6
7
8
9
10
11
# File 'lib/rubythinking/distributions/normal.rb', line 5

def self.random(mean = 0, std = 1)
  # Box-Muller transformation
  u1 = rand
  u2 = rand
  z0 = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math::PI * u2)
  mean + std * z0
end

.samples(n, mean = 0, std = 1) ⇒ Object

Generate multiple normal random variables



14
15
16
# File 'lib/rubythinking/distributions/normal.rb', line 14

def self.samples(n, mean = 0, std = 1)
  Array.new(n) { random(mean, std) }
end