@完全沒用到函數庫,可以用來選修課教學生,可幫學生了解公式:
print("請輸入X值,以空格隔開:")
x = [int(a) for a in input().split()]
print("請輸入Y值,以空格隔開:")
y = [int(b) for b in input().split()]
def Sum(x): #陣列各項數字和
s=0
for i in range(len(x)):
s+=x[i]
return s
def Average(x):#陣列平均
return Sum(x)/len(x)
def Variance(x):#陣列變異數
var=0
for i in range(len(x)):#
var+=((x[i]-Average(x))**2)/len(x)
return var
def Std(x):#陣列標準差
return Variance(x)**0.5
def Cov(x,y):#二陣列的共變異數
s=0
for i in range(len(x)):
s+=(x[i]-Average(x))*(y[i]-Average(y))
return s/len(x)
def Corr(x,y):#二陣列的相關係數
return Cov(x,y)/Std(x)/Std(y)
def Slope(x,y):#迴歸直線的斜率
return Corr(x,y)*Std(y)/Std(x)
#迴歸直線方程式
print("y=",Slope(x,y),"x",Average(y)-Slope(x,y)*Average(x))
沒有留言:
張貼留言