The formula used is :

**Regression Equation(y) = a + bx **

** Slope(b) = (NΣXY – (ΣX)(ΣY)) / (NΣX ^{2} – (ΣX)^{2})**

**Intercept(a) = (ΣY – b(ΣX)) / N**

#this is a simple program to perform linear regression on 2 sequences x and y

#the 2 sequences will be accepted as arguments in the function

#v is the value of x for which we want to find value of y

class Linear_regression

def linear_calculate(x,y,v)

#the linear regression equation is

#y=a+bx

#b is slope and a is intercept

#number of samples

n=x.length

#calculation of summation of x,y,x2,y2and xy

x_sum=0

y_sum=0

x2_sum=0

y2_sum=0

xy_sum=0

for i in 0..x.length-1

x_sum=x_sum+x[i]

y_sum=y_sum+y[i]

xy_sum=xy_sum+x[i]*y[i]

x2_sum=x2_sum+x[i]**2

y2_sum=y2_sum+y[i]**2

end

#end of i for loop

#calculate slope b

b1=(n*xy_sum-(x_sum*y_sum))

b2=((n*x2_sum)-(x_sum**2))

b=b1/b2

#calculate intercept a

a=(y_sum-(b*x_sum))/n

#the regression equation is :

puts “the regression equation is :”

puts “y = “+a.to_s+”+”+b.to_s+”x”

r=a+b*v

#the answer for x=v

puts “The final answer is “

puts r.to_s

end

#end of method linear_calculate

end

#end of class linear_regression

x=Array.[](60,61,62,63,65)

y=Array.[](3.1,3.6,3.8,4,4.1)

Linear_regression.new.linear_calculate(x,y,64)

*Ruby*

Posted on June 25, 20110