c - 如何用C编写函数 'extensible'?

标签 c math

我有以下函数,它应该可以与 for 循环一起正常工作,以分析一系列 double 结果是否已“稳定”。我写的内容总共分析了 3 个点,我想知道如何接受一个名为“minNumberOfSamples”的变量并让它比较这么多结果?

    bool MeasurementStabilized(double newResult, double percentageThreshold, double limitRange)
{
    static double meas1 = 1E100;
    static double meas2 = 1E100;

    if ((abs(newResult - meas2) / limitRange >= percentageThreshold) ||
        (abs(meas2 - meas1) / limitRange >= percentageThreshold))
        return TRUE;

    meas1 = meas2;
    meas2 = newResult;
    return FALSE;
}

最佳答案

我想在@John Coleman 的帮助下我现在已经很接近了。这似乎可以完成这项工作,但如果有人能想到的话,我们正在寻求一些改进:

static double* gArr;

void MeasurementStabilizedCleanup(void)
{
    free(gArr); 
}

static bool MeasurementStabilized(double newResult, double percentageThreshold, double limitRange, int minNumberOfSamples)
{
    static bool firstRun = TRUE;
    bool retVal = TRUE;
    int x;

    //init variables
    if (firstRun)
    {
        gArr = malloc((minNumberOfSamples + 1) * sizeof(double)); 
        for(x = 0; x <= minNumberOfSamples; x++)
        {
            gArr[x] = 1E100;
        }
        firstRun = FALSE;
    }

    //loop through each value comparing it to the latest result
    for(x = minNumberOfSamples - 1; x >= 0; x--)
    {
        gArr[x + 1] = gArr[x];  //4 -> 5 , 3 -> 4, ...
        if (fabs(newResult - gArr[x]) / limitRange >= percentageThreshold)
            retVal = FALSE;
    }
    gArr[0] = newResult;    //dont forget to update the latest sample   
    return retVal;  
}

void main(void)
{
    double doubles[] = {1, 2, 4, 4, 4, 4, 4};
    int x;

    for (x = 0; x <= 6; x++)
    {
        if(MeasurementStabilized(doubles[x], 0.01, 4, 4))
        {
            ;
        }
    }
    MeasurementStabilizedCleanup();
}

关于c - 如何用C编写函数 'extensible'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50545769/

相关文章:

c程序函数图参数

c - 如何修复 "A heap has been corrupted"运行时错误?

c++ - 迁移 C-->C++ 指向函数的指针会引发编译器错误

math - 这个 arg max 符号在朴素贝叶斯的 scikit-learn 文档中意味着什么?

javascript - 计算一直给出 NaN 结果

c - 为什么使用 char** 会导致 char* 工作时出现段错误?

c - 加入线程困惑

javascript - 用鼠标光标移动框

math - 计算几何、四面体符号体积

c++ - 稀疏约束线性最小二乘求解器