Hey does anyone know if there is an error function in the math library of C++? I think there is so, but I just can't figure out how to use it.

6 Years
Discussion Span
Last Post by tesuji


The 2001 ANSI standard added the erfc function ( 1-erf(x) ), for float/double/long double.

Not 100% sure when that got built into most version of cmath and math.h. But by now almost every compiler should have it, and should have had it for nearly 8-9 years.
Certainly it is is gcc/g++.

Not the best example

#include <cmath>
#include <iostream>

   for(int i=0;i<50;i++)
       std::cout<<"x == "<<i*0.1<<" "<<-erfc(i*0.1)+1.0<<std::endl;

Please note : that erf has been added to a lot of cmath files, but I didn't know if that was in the standard

Edited by StuXYZ: n/a


This is how I'm using it. But...It says that identifier not found for "erfc".

#include <iostream>
#include <cmath>
#include <math.h>
#include <fstream>
#include <string>
using namespace std;

int main()

double value, x;

x =2;

value = erfc(x); 

return 0;



I didn't found any error function when I was searching the compilers (gcc, visual c, watcom). Therefore, I took an approximation from Abramowitz/Stegun and wrote my own erf(x). It's approximation error is about 10^(-7). which was almost always sufficient for my apps. erf(x) = 1-erfc(x).

double erf(double x)
/* erf(z) = 2/sqrt(pi) * Integral(0..x) exp( -t^2) dt
erf(0.01) = 0.0112834772 erf(3.7) = 0.9999998325
Abramowitz/Stegun: p299, |erf(z)-erf| <= 1.5*10^(-7) 
 double y = 1.0 / ( 1.0 + 0.3275911 * x);   
 return 1 - (((((
        + 1.061405429  * y
        - 1.453152027) * y
        + 1.421413741) * y
        - 0.284496736) * y 
        + 0.254829592) * y) 
        * exp (-x * x);      

Maybe this small function is also useful for you.


Edited by tesuji: n/a


"tesuji"'s little erf(x) function saved my time...I was thinking to write one for my own to use with MS Visual C++ 6.0 compiler. thanks tesuji.


Hi munur93,

I am glad that my little erf() saved your time.

Unfortunately, MS visual c++ and other poor compilers do not have any Gaussian erfxcz function implemented to date despite the C99 standard provides some error functions in math.h. (Then I cribbed from famous Irene Stegun's Handbook of Mathematical Functions, what sadly only contains an approximation of medium-range precision, possibly the old one from Goldstine.)

There are erf() and erfc() in gnu c and c++, header file is math.h, not cmath.h.

If you are interested in higher precision erf() (about 1e-14), you can send me a message. I have calculated some erf() with higher precision using rational functions in L1-approximation.

-- tesu

Edited by tesuji: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.