xref: /original-bsd/lib/libm/common_source/erf.c (revision d0e3910b)
1 /*	@(#)erf.c	4.2 (Berkeley) 8/21/85; 5.1 (ucb.elefunt) 11/30/87 */
2 
3 /*
4 	C program for floating point error function
5 
6 	erf(x) returns the error function of its argument
7 	erfc(x) returns 1.0-erf(x)
8 
9 	erf(x) is defined by
10 	${2 over sqrt(pi)} int from 0 to x e sup {-t sup 2} dt$
11 
12 	the entry for erfc is provided because of the
13 	extreme loss of relative accuracy if erf(x) is
14 	called for large x and the result subtracted
15 	from 1. (e.g. for x= 10, 12 places are lost).
16 
17 	There are no error returns.
18 
19 	Calls exp.
20 
21 	Coefficients for large x are #5667 from Hart & Cheney (18.72D).
22 */
23 
24 #define M 7
25 #define N 9
26 static double torp = 1.1283791670955125738961589031;
27 static double p1[] = {
28 	0.804373630960840172832162e5,
29 	0.740407142710151470082064e4,
30 	0.301782788536507577809226e4,
31 	0.380140318123903008244444e2,
32 	0.143383842191748205576712e2,
33 	-.288805137207594084924010e0,
34 	0.007547728033418631287834e0,
35 };
36 static double q1[]  = {
37 	0.804373630960840172826266e5,
38 	0.342165257924628539769006e5,
39 	0.637960017324428279487120e4,
40 	0.658070155459240506326937e3,
41 	0.380190713951939403753468e2,
42 	0.100000000000000000000000e1,
43 	0.0,
44 };
45 static double p2[]  = {
46 	0.18263348842295112592168999e4,
47 	0.28980293292167655611275846e4,
48 	0.2320439590251635247384768711e4,
49 	0.1143262070703886173606073338e4,
50 	0.3685196154710010637133875746e3,
51 	0.7708161730368428609781633646e2,
52 	0.9675807882987265400604202961e1,
53 	0.5641877825507397413087057563e0,
54 	0.0,
55 };
56 static double q2[]  = {
57 	0.18263348842295112595576438e4,
58 	0.495882756472114071495438422e4,
59 	0.60895424232724435504633068e4,
60 	0.4429612803883682726711528526e4,
61 	0.2094384367789539593790281779e4,
62 	0.6617361207107653469211984771e3,
63 	0.1371255960500622202878443578e3,
64 	0.1714980943627607849376131193e2,
65 	1.0,
66 };
67 
68 double
69 erf(arg) double arg;{
70 	double erfc();
71 	int sign;
72 	double argsq;
73 	double d, n;
74 	int i;
75 
76 	sign = 1;
77 	if(arg < 0.){
78 		arg = -arg;
79 		sign = -1;
80 	}
81 	if(arg < 0.5){
82 		argsq = arg*arg;
83 		for(n=0,d=0,i=M-1; i>=0; i--){
84 			n = n*argsq + p1[i];
85 			d = d*argsq + q1[i];
86 		}
87 		return(sign*torp*arg*n/d);
88 	}
89 	if(arg >= 10.)
90 		return(sign*1.);
91 	return(sign*(1. - erfc(arg)));
92 }
93 
94 double
95 erfc(arg) double arg;{
96 	double erf();
97 	double exp();
98 	double n, d;
99 	int i;
100 
101 	if(arg < 0.)
102 		return(2. - erfc(-arg));
103 /*
104 	if(arg < 0.5)
105 		return(1. - erf(arg));
106 */
107 	if(arg >= 10.)
108 		return(0.);
109 
110 	for(n=0,d=0,i=N-1; i>=0; i--){
111 		n = n*arg + p2[i];
112 		d = d*arg + q2[i];
113 	}
114 	return(exp(-arg*arg)*n/d);
115 }
116