4

Visual Studio 2005 的cmath似乎没有 erf(x)。我正在使用 NIST Statistical Test Suite for Random and Pseudorandom Number Generators。在 cephes.c 的方法 double cephes_normal(double x) 中,它使用了 C99 数学函数 erf(x),我认为 Visual Studio 2005 不支持该函数。

我该如何克服这个问题?我在这里看到了一个 C++ 解决方案:http: //social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/9f5f4bf4-c0ae-4620-8039-4dc36e98d718/

有人使用了 boost C++ 数学库。但我认为我不能将 c++ 标头包含到 C 源文件中。

4

3 回答 3

5

一些谷歌搜索发现了这个C++ 实现(在此处重新发布):

erf代码:

#include <cmath>

double erf(double x)
{
    // constants
    double a1 =  0.254829592;
    double a2 = -0.284496736;
    double a3 =  1.421413741;
    double a4 = -1.453152027;
    double a5 =  1.061405429;
    double p  =  0.3275911;

    // Save the sign of x
    int sign = 1;
    if (x < 0)
        sign = -1;
    x = fabs(x);

    // A&S formula 7.1.26
    double t = 1.0/(1.0 + p*x);
    double y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);

    return sign*y;
}

测试功能

void testErf()
{
    // Select a few input values
    double x[] = 
    {
        -3, 
        -1, 
        0.0, 
        0.5, 
        2.1 
    };

    // Output computed by Mathematica
    // y = Erf[x]
    double y[] = 
    { 
        -0.999977909503, 
        -0.842700792950, 
        0.0, 
        0.520499877813, 
        0.997020533344 
    };

    int numTests = sizeof(x)/sizeof(double);

    double maxError = 0.0;
    for (int i = 0; i < numTests; ++i)
    {
        double error = fabs(y[i] - erf(x[i]));
        if (error > maxError)
            maxError = error;
    }

    std::cout << "Maximum error: " << maxError << "\n";
}   
于 2011-06-08T15:15:18.877 回答
0

Numerical Recipes包含错误函数的实现(我的版本中的第 6 章)。

John D. Cook 的博客中有一个Python 实现,翻译起来看起来很简单。

于 2011-06-08T15:09:48.033 回答
0

好吧,要么自己编写,看看 boost 实现,C-ify 并使用它,或者不要在这个项目中使用 Visual Studio 2005,而是使用GCC (MinGW)之类的东西。

于 2011-06-08T15:10:17.533 回答