function standard_deviation_population ($a)
{
//variable and initializations
$the_standard_deviation = 0.0;
$the_variance = 0.0;
$the_mean = 0.0;
$the_array_sum = array_sum($a); //sum the elements
$number_elements = count($a); //count the number of elements
//calculate the mean
$the_mean = $the_array_sum / $number_elements;
//calculate the variance
for ($i = 0; $i < $number_elements; $i++)
{
//sum the array
$the_variance = $the_variance + ($a[$i] - $the_mean) * ($a[$i] - $the_mean);
}
$the_variance = $the_variance / $number_elements;
//calculate the standard deviation
$the_standard_deviation = pow( $the_variance, 0.5);
//return the variance
return $the_standard_deviation;
}
$query_question = mysqli_query($con,"SELECT * FROM question order by s_id");
$QuestionDimArray = array();
while ($data_question = mysqli_fetch_array($query_question))
{
$QuestionDimArray []= $data_question['q_id'];
}
$a = array($QuestionDimArray());
$standard_deviation = standard_deviation_population ($a);
echo "standard_deviation =" .$standard_deviation;
如何将数据库值存储到
中$variable = array([database values here]);
例如,定义值(1,2,3)
$a = array(1,2,3); $standard_deviation = standard_deviation_population ($a); echo "standard_deviation =" .$standard_deviation;
返回, standard_deviation = 0.81649658092773
答案 0 :(得分:0)
以这种方式计算标准偏差并不是一个好主意。数据库系统具有标准偏差的内置函数。您可以在一个查询中获取它,例如:SELECT STDDEV_POP(q_id) FROM question
。
在您的代码中,$QuestionDimArray
已经是一个数组。你可以$standard_deviation = standard_deviation_population ($QuestionDimArray);
答案 1 :(得分:0)
您的问题不明确,但如果我理解得您想将所有数据库结果放入$ variable?
$query_question = mysqli_query($con,"SELECT * FROM question order by s_id");
$QuestionDimArray = array();
while ($data_question = mysqli_fetch_array($query_question)) {
$QuestionDimArray []= $data_question['q_id'];
/* if you want the full data line from your query use. It depends your implementation.
You will have an 2d array
[['col1' => 'val_line_1_1', 'col2'=> 'val_line_1_2',...],...,['col1' => 'val_line_n_1', 'col2'=> 'val_line_n_2',...]]
$QuestionDimArray []= $data_question;
*/
}
// $a = array($QuestionDimArray()); unless you want copy the array this line is useless. Event worst its wrong
$standard_deviation = standard_deviation_population ($questionDimArray);
echo "standard_deviation =" .$standard_deviation;