module TLib::Math

Public Instance Methods

exp(ave=0.5) click to toggle source

指数分布に従った乱数を返す

# File lib/t_lib/math.rb, line 60
def exp(ave=0.5)
  x = rand() ;
  y = rand() ;
  while ((1.0/ave)*Math.exp(-(x/ave)) < y )
    x = rand() ;
    y = rand() ;
  end
  return x ;
end
gauusian(x, mu, sigma) click to toggle source

gauusian distribution

@todo

# File lib/t_lib/math.rb, line 11
def gauusian(x, mu, sigma)
  f1 = 1.0/(Math.sqrt(2.0*Math::PI)*Math.sqrt(sigma))
  f2 = Math.exp(-(((x-mu)**2)/((2.0*sigma))))
  return f1 * f2
end
gauusian_array(x, mu, sigma) click to toggle source

gauusian distribution

@todo

# File lib/t_lib/math.rb, line 21
def gauusian_array(x, mu, sigma)
  if x[0].size <= 1
    x = x[0]
    mu = mu[0]
    sigma = sigma[0][0]
    return gauusian(x, mu, sigma)
  else
    return gauusian_over_2dim(x, mu, sigma)
  end
end
gauusian_over_2dim(x, mu, conv) click to toggle source

gauusian distribution over 2 dim version

# File lib/t_lib/math.rb, line 36
def gauusian_over_2dim(x, mu, conv)
  x = Matrix[x]
  mu = Matrix[mu]
  conv = Matrix[*conv]
  f1 = 1.0/(((2.0 * Math::PI)**(@dim/2.0)) * ( conv.det**(0.5) ))
  f2 = Math.exp((-1.0/2.0)*((x-mu) * conv.inverse * (x-mu).transpose)[0, 0])

  return (f1 * f2)
end
normal_rand(mu = 0,sigma = 1.0) click to toggle source

ボックス―ミューラー法をよる正規分布乱数発生

@param mu flout 平均 @param sigma flout 標準偏差 @return ボックスミューラー法に従う正規分布に従う乱数を生成

# File lib/t_lib/math.rb, line 52
def normal_rand(mu = 0,sigma = 1.0)
  a, b = rand(), rand() ;
  return (Math.sqrt(-2*Math.log(rand()))*Math.sin(2*Math::PI*rand()) * sigma) + mu
end
poisson_rand(mu=0.0) click to toggle source

ポアソン分布に従う乱数を発生する

# File lib/t_lib/math.rb, line 75
def poisson_rand(mu=0.0)
  lambda = Math.exp(-mu)
  k = 0
  p = 1.0
  while p >= lambda
    p *= rand()
    k += 1
  end
  return k - 1
end
scale(x) click to toggle source
# File lib/t_lib/math.rb, line 85
def scale(x)
  sum_each_vec = []
  ave_list = []
  std_list = []
  x.each{|vec| 
    vec.each_with_index{|data, i|
      sum_each_vec[i] = (sum_each_vec[i] == nil) ? data : sum_each_vec[i]+data
    }
  }
  x[0].size.times{|i|
    ave_list.push(sum_each_vec[i]/x.size)
  }

  sum_each_vec = []
  x.each{|vec| 
    vec.each_with_index{|data, i|
      sum_each_vec[i] = (sum_each_vec[i] == nil) ? (ave_list[i]-data)**2 : (sum_each_vec[i]+(ave_list[i]-data)**2)
    }
  }
  x[0].size.times{|i|
    std_list.push(Math.sqrt(sum_each_vec[i]/x.size))
  }

  scaled_x = []
  x.each_with_index{|vec, i| 
    scaled_x[i] ||= []
    vec.each_with_index{|data, j|
      scaled_x[i][j] ||= (data-ave_list[j])/std_list[j]
    }
  }
  return scaled_x
end