6个回答

qq_42745109 666

var variance = function(numbers) {

var mean = 0;

var sum = 0;

for(var i=0;i<numbers.length;i++){

sum += numbers[i];

}

mean = sum / numbers.length;

sum = 0;

for(var i=0;i<numbers.length;i++){

sum += Math.pow(numbers[i] - mean , 2);

}

return sum / numbers.length;

};

<!DOCTYPE html>

demo function log(msg) { console.log(msg); } /** * 可视化的打印出矩阵的数据 <em>/ function printMatrixData(data) { console.log(data); if(!data) { return; } var numberSize = 5; for(var i=0, len=data.length; i&lt;len; i++) { var row = data[i]; var rowLog = &quot;(&quot;; for(var j=0, jLen=row.length; j&lt;jLen; j++) { rowLog += row[j]; // 补齐空格 rowLog += indent(numberSize - (row[j]+&quot;&quot;).length); } rowLog+=&quot;)&quot;; console.log(rowLog); } } /</em>* * 拼接指定长度的空格 <em>/ function indent(length) { var empty = &quot;&quot;; for(var i=0; i&lt;length; i++) { empty += &quot; &quot;; } return empty; } /</em>* * 矩阵原型 */ function Matrix(data) { // 这里必须传一个二维数组，最好严格检验一下 if(typeof data !== &quot;object&quot; || typeof data.length === &quot;undefined&quot; || !data) { throw new Error(&quot;data&#39;s type is error&quot;); } this.data = data; this.cols = data.length; } var M = { findByLocation: function(data, xIndex, yIndex) { if(data &amp;&amp; data[xIndex]) { return data[xIndex][yIndex]; } }, // 矩阵乘积 multiply: function(m, n) { if(!m instanceof Matrix &amp;&amp; !n instanceof Matrix) { throw new Error(&quot;data&#39;s type is error&quot;); } var mData = m.data; var nData = n.data; if(mData.length == 0 || nData.length == 0) { return 0; } if(mData[0].length != nData.length) { throw new Error(&quot;the two martrix data is not allowed to dot&quot;); } var result = []; for(var i=0, len=mData.length; i<len; i++) { var mRow = mData[i]; result[i] = []; for(var j=0, jLen=mRow.length; j<jLen; j++) { var resultRowCol = 0; // 如果n矩阵没有足够的列数相乘，转入m矩阵下一行 if(typeof this.findByLocation(nData, 0, j) === "undefined") { break; } for(var k=0, kLen=jLen; k<kLen; k++) { resultRowCol += mRow[k]*this.findByLocation(nData, k, j); } result[i][j] = resultRowCol; } } return result; } }; var m = new Matrix([[2, -1], [-2, 1], [-1, 2]]); var n = new Matrix([[4, -3], [3, 5]]); var result = M.multiply(m, n); printMatrixData(result); var m2 = new Matrix([[2, 3, 1], [5, 2, 4], [-3, 2, 0]]); var n2 = new Matrix([[11], [5], [8]]); var result2 = M.multiply(m2, n2); printMatrixData(result2);
``````
``````

var sum=0
arr.foreach((value,index)=>{sum+=arr[index]})
var mean=sum/arr.length()

var mean = 0;

var sum = 0;

for(var i=0;i<numbers.length;i++){

sum += numbers[i];

``````var mean = 0;

var sum = 0;

for(var i=0;i<numbers.length;i++){

sum += numbers[i];
``````