Вопрос

I have a problem with calculating the standard deviation in php. But it's generating the wrong result.

e.g. I am getting as result for (4+4+4+4+4+4) = 1.40 instead of 0.

Please help.

function std_dev ($attr, $test1,$test2,$test3,$test4,$test5,$test6) {
    //$items = array($test1->$attr,$test2->$attr,$test3->$attr,$test4->$attr,$test5->$attr,$test6->$attr);
    $items[] = array();

    if (isset($test1) && $test1->$attr != 9 && $test1->$attr != 0) {
        $items[] = $test1->$attr;
    }
    if (isset($test2) && $test2->$attr != 9  && $test2->$attr != 0) {
        $items[] = $test2->$attr;
    }
    if (isset($test3) && $test3->$attr != 9 && $test3->$attr != 0) {
        $items[] = $test3->$attr;
    }
    if (isset($test4) && $test4->$attr != 9 && $test4->$attr != 0) {
        $items[] = $test4->$attr;
    }
    if (isset($test5) && $test5->$attr != 9 && $test5->$attr != 0) {
        $items[] = $test5->$attr;
    }
    if (isset($test6) && $test6->$attr != 9 && $test6->$attr != 0) {
        $items[] = $test6->$attr;
    }

    $sample_square[] = array();
    $item_count = count($items);
    for ($current = 1; $item_count > $current; ++$current) $sample_square[$current] = pow($items[$current], 2);

    $standard_deviation = sqrt(array_sum($sample_square) / $item_count - pow((array_sum($items) / $item_count), 2));

    return round($standard_deviation,2);

}
Это было полезно?

Решение

$items = array();

$sample_square = array();

no [] when you define those variables as arrays.

for ($current = 0; $item_count > $current; ++$current)

start from 0 not 1 if you want to iterate over all the elements (otherwise you'll miss item at index 0)


Wondering what this is for...

if (isset($test1) && $test1->$attr != 9 && $test1->$attr != 0) {
    $items[] = $test1->$attr;
}

and how you pass input values to the function. This may also cause wrong result...

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top