开发者

Error function, erf(x), not found in math.h for visual studio 2005

It seems that cmath for visual studio 2005 does not have erf(x). I am using NIST Statistica开发者_如何学编程l Test Suite for Random and Pseudorandom Number Generators. In cephes.c's method, double cephes_normal(double x), it uses a C99 math function erf(x) which I don't believe is supported by visual studio 2005.

How can I overcome this problem? I saw a C++ solution here: http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/9f5f4bf4-c0ae-4620-8039-4dc36e98d718/

Someone used the boost C++ math library. But I don't think I can include a c++ header into a C source file.


Some Googling found this C++ implementation (reposted here):

erf code:

#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;
}

Test function

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";
}   


Numerical Recipes contains an implementation of the error function (Chapter 6 in my edition).

There's a Python implementation in John D. Cook's blog, which looks trivial to translate.


Well, either write it yourself, take a look at the boost implementation, C-ify it, and use that, or don't use Visual Studio 2005 for this project, but something like GCC (MinGW) instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜