python linear equation components

Solutions on MaxInterview for python linear equation components by the best coders in the world

showing results for - "python linear equation components"
Ilona
01 Sep 2017
1def liner(x,y):
2    """ 'y(x) = ax + b' --> get a & b by providing arrays x & y"""
3    sum_xy = sum([i*j for i,j in zip(x,y)])
4    sum_x2 = sum([pow(i,2)for i in x ])
5    a = ( len(y)*sum_xy - sum(x)*sum(y) ) / ( len(y)*sum_x2 - pow(sum(x),2))  
6    b = ( sum(y)*sum_x2 - sum(x)*sum_xy)  / ( len(y)*sum_x2 - pow(sum(x),2)) 
7    return a,b
8xx = [0,2,6,11,12,13,17,21,24,26,31,36,37]
9yy = [0,4,7,11,16,26,27,31,39,47,49,57,58]
10a,b = liner(xx,yy)
11print("a:",a," b:",b)  # a: 1.631407787762088 b: -1.000941377834831
12
13# Or use numpy
14import numpy as np
15np.polyfit(xx, yy, 1)   # [ 1.63140779 -1.00094138]