Created
January 27, 2020 07:34
-
-
Save cedrickvstheworld/311f1d5d555963d1821952e9acf9e259 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* y = a + bx | |
* | |
* | |
* a = ʏ̅ - bx̅ | |
* | |
* b = Σxy - nx̅ʏ̅ / Σx^2 - nx̅^2 | |
* | |
* */ | |
export interface IFeeds {x: number, y:number} | |
class Forecast { | |
private n: number | |
private sxy: number | |
private sx2: number | |
private sy: number | |
private sy2: number | |
private x_bar: number | |
private y_bar: number | |
private a: number | |
private b: number | |
constructor(feeds: Array<IFeeds>) { | |
const {x_list, y_list, sy, sxy, sx2, sy2} = feeds.reduce((acc, data) => { | |
acc.x_list.push(data.x) | |
acc.y_list.push(data.y) | |
acc.sy += data.y | |
acc.sxy += data.x * data.y | |
acc.sx2 += Math.pow(data.x, 2) | |
acc.sy2 += Math.pow(data.y, 2) | |
return acc | |
}, { | |
x_list: [], | |
y_list: [], | |
sxy: 0, | |
sy: 0, | |
sx2: 0, | |
sy2: 0 | |
}) | |
this.sxy = sxy | |
this.sx2 = sx2 | |
this.sy = sy | |
this.sy2 = sy2 | |
this.n = feeds.length | |
this.x_bar = this.mean(x_list) | |
this.y_bar = this.mean(y_list) | |
this.b = this.get_b() | |
this.a = this.get_a() | |
} | |
mean(n: Array<number>) { | |
return (n.reduce((acc, cur) => { | |
return acc += cur | |
}, 0)) / this.n | |
} | |
get_b() { | |
return (this.sxy - (this.n * this.x_bar * this.y_bar))/(this.sx2 - (this.n * Math.pow(this.x_bar, 2))) | |
} | |
get_a() { | |
return this.y_bar - (this.b * this.x_bar) | |
} | |
// returns the value independent varialbe | |
predict(x: number) { | |
return this.a + (this.b * x) | |
} | |
get_standard_error_of_estimation() { | |
return Math.sqrt((this.sy2 - (this.a * this.sy) - (this.b * this.sxy))/ this.n - 2) | |
} | |
} | |
const feeds: Array<IFeeds> = [ | |
{ | |
x: 1, | |
y: 220 | |
}, | |
{ | |
x: 2, | |
y: 245 | |
}, | |
{ | |
x: 3, | |
y: 263 | |
}, | |
{ | |
x: 4, | |
y: 234 | |
}, | |
{ | |
x: 5, | |
y: 255 | |
}, | |
{ | |
x: 6, | |
y: 352 | |
}, | |
{ | |
x: 5, | |
y: 403 | |
}, | |
{ | |
x: 6, | |
y: 353 | |
}, | |
{ | |
x: 7, | |
y: 375 | |
}, | |
{ | |
x: 8, | |
y: 552 | |
}, | |
{ | |
x: 9, | |
y: 302 | |
}, | |
{ | |
x: 10, | |
y: 193 | |
} | |
] | |
let test = new Forecast(feeds) | |
console.log(test.predict(11)) | |
console.log(test.get_standard_error_of_estimation()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment