A SIMPLE PROGRAM TO CALCULATE GEOMETRIC MEAN OF A GIVEN SEQUENCE IN RUBY LANGUAGE

Posted on June 24, 2011

0


In this program the practical definition of a geometric mean is used.

The definition is : The average of the logarithmic values of a data set, converted back to a base 10 number.

I have found that base 10 is not required.

I have used base 2 and as far as I know, anything can be used.

The program has comments and since it’s a fairly simple program , its self explanatory

#This is the program to calculate geometric mean of a sequence.

#The sequence will be passed as an array as argument to the function

class Geometric

#this is the method to return the geometric mean of the sequence

def mean_calculate(x)

tmp=0

y=Array.new       #This array will be used to store logarithms of the numbers of the sequence

#this loop is used to find logs of numbers in sequence and sum them up in a variable called tmp

for i in 0..x.length-1

y[i]=Math.log(x[i])

tmp=tmp+y[i]

end

#end of i for loop

#this is to find average of the sum of logs taken.

avg_log=tmp/x.length

#This is to convert logs back to original form

gm=Math.exp(avg_log)

#Finally display the result !!

puts “Geometric mean is : “+gm.to_s

end

#end of mean_calculate method

end

#end of class

x=Array.[](6,50,9,1200)

Geometric.new.mean_calculate(x)

In this code, I have used a very simple sequence.

You may test it with a larger sequence.

Advertisements
Posted in: Ruby