求一超球体的圓心與半徑


#!/usr/bin/ruby -Ku
require 'ai4r'
require 'csv'

def EuclideanDistance(x,y)
  sum = 0
  for i in (0..x.size-1)
    #printf("x[%d]=%f,y[%d]=%f\n",i,x[i],i,y[i])
    ->(px,py){ sum += (px-py)**2.0}.(x[i],y[i])
  end
return Math.sqrt(sum)
end

csv_file = "tfidf-ckip-a.csv"
f=File.new("#{csv_file}")
data = Array.new
while (line = f.gets)
  data << line.split(',').collect  do |s| s.to_f end
end

#data = [[1,1,1], [3,3,3],[9,9,9]]
ai4r_data = Ai4r::Data::DataSet.new(:data_items=> data)
kmeans = Ai4r::Clusterers::KMeans.new
#abuild(dataset,clusters)
res=kmeans.build(ai4r_data,1)
#puts res.inspect
center = res.centroids[0] #此球体圓心
r = 0 #此球体半徑


 r = 0 #此球体半徑
tmp = 0
printf("計算中...\n")
for i  in (0..data.size-1)
  tmp = EuclideanDistance(center,data[i])
  r = tmp if(tmp > r)
end

printf("球体,%s\n",csv_file)
printf("球体半徑為,%f\n",r)
printf("球体圓心為,%s\n",center.join(','))



創作者介紹
創作者 igogo 的頭像
igogo

牛大叔.生活隨筆

igogo 發表在 痞客邦 留言(0) 人氣()