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.
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>
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 before using 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.
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.
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).