Module: ChrisMath
- Includes:
- Math
- Defined in:
- lib/chris_lib/chris_math.rb
Instance Method Summary collapse
- #bi_gaussian_rand ⇒ Object
- #combinatorial(n, k) ⇒ Object
- #combinatorial_distribution(n, r, p) ⇒ Object
- #factorial(n) ⇒ Object
- #gaussian_array(n = 1) ⇒ Object
- #gaussian_rand(mean, std) ⇒ Object
- #std(values) ⇒ Object
Instance Method Details
#bi_gaussian_rand ⇒ Object
184 185 186 187 188 189 190 |
# File 'lib/chris_lib/chris_math.rb', line 184 def bi_gaussian_rand u1 = rand() u2 = rand() z0 = sqrt(-2*log(u1))*cos(2*PI*u2) z1 = sqrt(-2*log(u1))*sin(2*PI*u2) [z0,z1] end |
#combinatorial(n, k) ⇒ Object
228 229 230 231 |
# File 'lib/chris_lib/chris_math.rb', line 228 def combinatorial(n, k) #from rosetta code (0...k).inject(1) do |m,i| (m * (n - i)) / (i + 1) end end |
#combinatorial_distribution(n, r, p) ⇒ Object
209 210 211 212 213 214 215 216 217 218 219 220 221 |
# File 'lib/chris_lib/chris_math.rb', line 209 def combinatorial_distribution(n,r,p) # probability that r out n or greater hits with the # probability of one hit is p. if r <= n && r >= 0 sum = 0 (r..n).each do |k| sum += combinatorial(n,k)*(p)**(k)*(1-p)**(n - k) end sum else raise 'Error, #{r} must be >= 0 and <= #{n}' end end |
#factorial(n) ⇒ Object
223 224 225 226 |
# File 'lib/chris_lib/chris_math.rb', line 223 def factorial(n) #from rosetta code (1..n).inject {|prod, i| prod * i} end |
#gaussian_array(n = 1) ⇒ Object
176 177 178 179 180 181 182 |
# File 'lib/chris_lib/chris_math.rb', line 176 def gaussian_array(n = 1) (1..n).map do u1 = rand() u2 = rand() sqrt(-2*log(u1))*cos(2*PI*u2) end end |
#gaussian_rand(mean, std) ⇒ Object
192 193 194 195 196 197 |
# File 'lib/chris_lib/chris_math.rb', line 192 def gaussian_rand(mean,std) u1 = rand() u2 = rand() z0 = sqrt(-2*log(u1))*cos(2*PI*u2) z0*std + mean end |
#std(values) ⇒ Object
200 201 202 203 204 205 206 |
# File 'lib/chris_lib/chris_math.rb', line 200 def std(values) n = values.length raise 'n = #{n} but must be greater than 1' if n < 2 m = mean(values) sum = values.inject { |s,v| s + (v**2 - m**2)} sqrt(sum.to_f/(n - 1)) end |