Ruby/Development/Math extensions
Материал из Wiki.crossplatform.ru
Содержание |
Add function to Math module
module Math def Math.logb(num, base) log(num) / log(base) end end
Get hmean value
def hmean(x) sum=0 x.each {|v| sum += (1.0/v)} x.size/sum end data = [1.1,2.3,3.3,1.2,4.5,2.1,6.6 ] puts hm = hmean(data) # 2.101997946
Get mean value
def mean(x) sum=0 x.each {|v| sum += v} sum/x.size end data = [1.1,2.3,3.3,1.2,4.5,2.1,6.6 ] puts am = mean(data) # 3.014285714
Get sigma value
def mean(x) sum=0 x.each {|v| sum += v} sum/x.size end def variance(x) m = mean(x) sum =0.0 x.each {|v| sum += (v-m)**2 } sum/x.size end def sigma(x) Math.sqrt(variance(x)) end data = [2,3,2,2,3,4,5,5,4,3,4,1,2 ] puts sigma(data) # 1.20894105
Get the median value
def median(x) sorted = x.sort mid = x.size/2 sorted[mid] end data =[7,7,7,4,4,5,4,5,7,2,2,3,3,7,3,4 ] puts median(data) # 4
Get the mode value
def mode(x) sorted = x.sort a = Array.new b = Array.new sorted.each do |x| if a.index(x)==nil a << x # Add to list of values b << 1 # Add to list of frequencies else b[a.index(x)] += 1 # Increment existing counter end end maxval = b.max # Find highest count where = b.index(maxval) # Find index of highest count a[where] # Find corresponding data value end data =[7,7,7,4,4,5,4,5,7,2,2,3,3,7,3,4 ] puts mode(data) # 7
Get variance value
def mean(x) sum=0 x.each {|v| sum += v} sum/x.size end def variance(x) m = mean(x) sum =0.0 x.each {|v| sum += (v-m)**2 } sum/x.size end data = [2,3,2,2,3,4,5,5,4,3,4,1,2 ] puts variance(data) # 1.461538462
Return the gmean value
def gmean(x) prod=1.0 x.each {|v| prod *= v} prod**(1.0/x.size) end data = [1.1,2.3,3.3,1.2,4.5,2.1,6.6 ] gm = gmean(data) # 2.508411474
Your own math function
module Math RAD2DEG = 360.0/(2.0*PI) # Radians to degrees RAD2GRAD = 400.0/(2.0*PI) # Radians to grads end def sin_d(theta) Math.sin(theta/Math::RAD2DEG) end def sin_g(theta) Math.sin(theta/Math::RAD2GRAD) end def atan2_d(y,x) Math.atan2(y,x)/Math::RAD2DEG end def atan2_g(y,x) Math.atan2(y,x)/Math::RAD2GRAD end def arcsin(x) Math.atan2(x,Math.sqrt(1.0-x*x)) end def arccos(x) Math.atan2(Math.sqrt(1.0-x*x),x) end def arctan(x) Math.atan2(x,1.0) end def sinh(x) (Math.exp(x)-Math.exp(-x))/2.0 end def cosh(x) (Math.exp(x)+Math.exp(-x))/2.0 end def tanh(x) sinh(x)/cosh(x) end def asinh(x) Math.log(x + Math.sqrt(1.0+x**2)) end def acosh(x) 2.0 *Math.log(Math.sqrt((x+1.0)/2.0)+Math.sqrt((x-1)/2.0)) end def atanh(x) (Math.log(1.0+x) - Math.log(1.0-x))/2.0 end