JSFiddle - React, Tailwind, and code Playground
by jonahe
JavaScript
(function() {
var ss = {};
if (typeof module !== 'undefined') {
// Assign the `ss` object to exports, so that you can require
// it in [node.js](http://nodejs.org/)
exports = module.exports = ss;
} else {
// Otherwise, in a browser, we assign `ss` to the window object,
// so you can simply refer to it as `ss`.
this.ss = ss;
}
// # [Linear Regression](http://en.wikipedia.org/wiki/Linear_regression)
//
// [Simple linear regression](http://en.wikipedia.org/wiki/Simple_linear_regression)
// is a simple way to find a fitted line
// between a set of coordinates.
ss.linear_regression = function() {
var linreg = {},
data = [];
// Assign data to the model. Data is assumed to be an array.
linreg.data = function(x) {
if (!arguments.length) return data;
data = x.slice();
return linreg;
};
// ## Fitting The Regression Line
//
// This is called after `.data()` and returns the
// equation `y = f(x)` which gives the position
// of the regression line at each point in `x`.
linreg.line = function() {
//if there's only one point, arbitrarily choose a slope of 0
//and a y-intercept of whatever the y of the initial point is
if (data.length == 1) {
m = 0;
b = data[0][1];
} else {
// Initialize our sums and scope the `m` and `b`
// variables that define the line.
var sum_x = 0, sum_y = 0,
sum_xx = 0, sum_xy = 0,
m, b;
// Gather the sum of all x values, the sum of all
// y values, and the sum of x^2 and (x*y) for each
// value.
//
// In math notation, these would be SS_x, SS_y, SS_xx, and SS_xy
for (var i = 0;...