Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Sum, mean, variance, tests.

  • Loading branch information...
commit 3c80a8153ab6319ebc81c2dd6b73e5fb6f3133c3 1 parent f9eef50
@tmcw authored
View
5 Makefile
@@ -1,4 +1,7 @@
docs:
docco src/*.js
-.PHONY: docs
+test:
+ mocha
+
+.PHONY: docs test
View
11 README.md
@@ -1,13 +1,4 @@
-[![Build Status](https://secure.travis-ci.org/tmcw/simple-statistics.png?branch=gh-pages)](http://travis-ci.org/tmcw/simple-statistics)
+[![Build Status](https://secure.travis-ci.org/tmcw/simple-statistics.png?branch=master)](http://travis-ci.org/tmcw/simple-statistics)
A project to learn about and make simple reference implementations
of statistics algorithms.
-
-Implementations are going to be **literate, general, and straightforward.**
-
-* [Naive Bayes](http://en.wikipedia.org/wiki/Naive_Bayes_classifier)
-* [Linear Regression](http://en.wikipedia.org/wiki/Simple_linear_regression)
-
-## See Also
-
-* [gauss](https://github.com/stackd/gauss)
View
30 src/simple_statistics.js
@@ -205,4 +205,34 @@
// Return the completed model.
return bayes_model;
};
+
+ // The sum is simply the result of adding all numbers
+ // together, starting from zero.
+ ss.sum = function(x) {
+ var sum = 0;
+ for (var i = 0; i < x.length; i++) {
+ sum += x[i];
+ }
+ return sum;
+ };
+
+ // The mean is the sum over the number of values
+ ss.mean = function(x) {
+ return ss.sum(x) / x.length;
+ }
+
+ // The variance is the sum of squared deviations from the mean
+ ss.variance = function(x) {
+ var mean = ss.mean(x),
+ deviations = [];
+
+ // Make a list of squared deviations from the mean.
+ for (var i = 0; i < x.length; i++) {
+ deviations.push(Math.pow(x[i] - mean, 2));
+ }
+
+ // Find the mean value of that list
+ return ss.mean(deviations);
+ };
+
})(this);
View
6 test/mean.test.js
@@ -0,0 +1,6 @@
+var assert = require('assert');
+var ss = require('../');
+
+it('can get the mean of two numbers', function() {
+ assert.equal(ss.mean([1, 2]), 1.5);
+});
View
6 test/sum.test.js
@@ -0,0 +1,6 @@
+var assert = require('assert');
+var ss = require('../');
+
+it('can get the sum of two numbers', function() {
+ assert.equal(ss.sum([1, 2]), 3);
+});
View
10 test/variance.test.js
@@ -0,0 +1,10 @@
+var assert = require('assert');
+var ss = require('../');
+
+function rnd(x) {
+ return Math.round(x * 1000) / 1000;
+}
+
+it('can get the variance of a six-sided die', function() {
+ assert.equal(rnd(ss.variance([1, 2, 3, 4, 5, 6])), 2.917);
+});
Please sign in to comment.
Something went wrong with that request. Please try again.