Javascript 标准差javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7343890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Standard deviation javascript
提问by tc03
I am trying to get the standard deviation of a user input string. I have as follows, but it returns the wrong value for SD. The calculation should go as follows: Sum values/number values = mean Square (sum each value-mean) Sum squares/number values.
我正在尝试获取用户输入字符串的标准偏差。我有以下内容,但它返回了错误的 SD 值。计算应如下:求和值/数值=均方(求和每个值-均值)求和平方/数值。
Assistance appreciated (and explanation if possible):
感谢您的帮助(如果可能,请提供解释):
function sum() {
var val = document.getElementById('userInput').value;
var temp = val.split(" ");
var total = 0;
var v;
var mean = total / temp.length;
var total1 = 0;
var v1;
var temp23;
var square;
for (var i = 0; i < temp.length; i++) {
v = parseFloat(temp[i]);
total += v;
}
mean = total / temp.length;
for (var i = 0; i < temp.length; i++) {
v1 = parseFloat(Math.pow(temp[i] - mean), 2);
total1 += v1;
}
temp23 = total1 / temp.length;
square = Math.sqrt(temp23);
document.write(total + '<br />');
document.write(mean + '<br />');
document.write(square);
}
<html>
<head>
</head>
<body>
<form id="input">
<textarea id="userInput" rows=20 cols=20></textarea>
<input id="Run" type=Button value="run" onClick="sum()" />
</form>
</body>
</html>
采纳答案by nnnnnn
I think the (main) problem is on this line:
我认为(主要)问题在这一行:
v1 = parseFloat(Math.pow(temp[i]-mean),2);
Should be:
应该:
v1 = Math.pow(parseFloat(temp[i])-mean),2);
Your code is trying to use the string in temp[i]
as a number and subtract mean
from it, and then square it, and then parse the resulting value. Need to parseFloat beforeusing it in a calculation. Also you've got the ,2
outside the closing parenenthesis for the Math.pow
call so the squaring won't work either.
您的代码试图将字符串temp[i]
用作数字并mean
从中减去,然后将其平方,然后解析结果值。在计算中使用它之前需要解析Float 。此外,您还拥有呼叫,2
的结束括号外,Math.pow
因此平方也不起作用。
Would be helpful to use more meaningful variable names too, I mean, e.g., you have a variable called "square" that holds the result of a square-root operation.
使用更有意义的变量名称也会有帮助,我的意思是,例如,您有一个名为“square”的变量,它保存平方根运算的结果。
P.S. You need to add some error checking in case the user enters non-numeric data. Check that the result of parseFloat()
is not NaN
. I'd be inclined to do an initial loop through the array parsing and checking for valid numbers, storing the parsed numbers in a second array (or writing them back to the first array), and if any are invalid give the user an error message at that point and stop. Then in your actual calculations you don't have to worry about parsing as you go (or, in your case, parsing again in the second loop).
PS 您需要添加一些错误检查,以防用户输入非数字数据。检查的结果parseFloat()
不是NaN
。我倾向于通过数组解析和检查有效数字进行初始循环,将解析的数字存储在第二个数组中(或将它们写回第一个数组),如果有任何无效,则给用户一条错误消息在这一点上停止。然后在您的实际计算中,您不必担心解析(或者,在您的情况下,在第二个循环中再次解析)。
回答by Foxcode
Shorthand method for getting standard deviation from an array if you don't like lots of code:
如果您不喜欢大量代码,从数组中获取标准偏差的速记方法:
const n = array.length;
const mean = array.reduce((a,b) => a+b)/n;
const s = Math.sqrt(array.map(x => Math.pow(x-mean,2)).reduce((a,b) => a+b)/n);
回答by cssimsek
For anyone looking for a more generic solution, here's a standard deviation function added to the Array#. The function expects to be called on an array of numbers.
对于任何寻求更通用解决方案的人,这里有一个添加到 Array# 的标准偏差函数。该函数期望在数字数组上调用。
Array.prototype.stanDeviate = function(){
var i,j,total = 0, mean = 0, diffSqredArr = [];
for(i=0;i<this.length;i+=1){
total+=this[i];
}
mean = total/this.length;
for(j=0;j<this.length;j+=1){
diffSqredArr.push(Math.pow((this[j]-mean),2));
}
return (Math.sqrt(diffSqredArr.reduce(function(firstEl, nextEl){
return firstEl + nextEl;
})/this.length));
};
回答by Berk Kanburlar
function StandardDeviation(numbersArr) {
//--CALCULATE AVAREGE--
var total = 0;
for(var key in numbersArr)
total += numbersArr[key];
var meanVal = total / numbersArr.length;
//--CALCULATE AVAREGE--
//--CALCULATE STANDARD DEVIATION--
var SDprep = 0;
for(var key in numbersArr)
SDprep += Math.pow((parseFloat(numbersArr[key]) - meanVal),2);
var SDresult = Math.sqrt(SDprep/numbersArr.length);
//--CALCULATE STANDARD DEVIATION--
alert(SDresult);
}
var numbersArr = [10, 11, 12, 13, 14];
StandardDeviation(numbersArr);
回答by Ibraheem
Quick implementation of the standard deviation function:
标准差函数的快速实现:
const sd = numbers => {
const mean = numbers.reduce((acc, n) => acc + n) / numbers.length;
return Math.sqrt(
numbers.reduce((acc, n) => (n - mean) ** 2) / (numbers.length - 1)
);
};