我的标准偏差函数给出了错误的答案

问题描述 投票:0回答:1

我目前正在尝试用 C 编写一个程序,该程序可以计算一组数字的平均值及其标准差。 代码是在 code composer studio v12 中编写的,并在 msp430g2553 上调试。 我已经将问题缩小到“float gem = avg(input, sizeof input / sizeof input[0]);”函数的一部分。

替换有问题的部分 'float gem = avg(input, sizeof input / sizeof input[0]);'函数的实际平均值 (float gem = 6.625;) 修复了函数,之后它将按预期工作。

有问题的代码/功能:

#include <msp430.h> 
#include <math.h> //library used for the sqrt and powf functions.

float avg(float input[], int n) // function used to calculate the average of an array of n length.
{
    int i = 0;
    float sum = 0;
    for (i = 0; i < n; i++)
    {
        sum = input[i] + sum;
    }
    return sum / n;
}

float std_dev(float input[], int n) // function used to calculate standard deviation 
{
    int i = 0;
    float sum = 0;
    float gem = avg(input, sizeof input / sizeof input[0]);
    for (i = 0; i < n; i++)
    {
        sum = sum + powf((input[i] -gem ), 2);
    }
    return sqrt(sum / 4);

}
/**
 * main.c
 */
int main(void)
{
    WDTCTL = WDTPW | WDTHOLD;   // stop watchdog timer
    float cijfers[] = { 3.2, 5.7, 8.5, 9.1 };

    float som;
    som = avg(cijfers, sizeof cijfers / sizeof cijfers[0]);

    float deviatie;
    deviatie = std_dev(cijfers, sizeof cijfers / sizeof cijfers[0]);

    return 0;
}
c function math msp430
1个回答
1
投票
float std_dev(float input[], int n) // function used to calculate standard deviation 
{
    const float gem = avg( input, n ); // Pass parameter N, since we already have it.
    float sum = 0;

    for (int i = 0; i < n; i++)        // Declare i to be loop-local
    {
        sum += (input[i] - gem) * (input[i] - gem); // Re-wrote for simplicity.
    }
    return sqrt(sum/n);                // Change the /4 to a /n
}

您已经将数组的大小作为参数

n
。只需在调用函数
avg
时使用它,这既是为了简单起见,也是因为 sizeof“技巧”在这种情况下不起作用。

调用

powf
不是“错误的”,但当您只是尝试进行基本平方时,这是不必要的。它更容易自己做价值的乘法。

我不知道你为什么最后做了一个

/ 4
。据我所知,标准偏差只是方差的平方根。

© www.soinside.com 2019 - 2024. All rights reserved.