-
Notifications
You must be signed in to change notification settings - Fork 1
/
Faddeeva.cpp
2516 lines (2395 loc) · 123 KB
/
Faddeeva.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; -*-
/* Copyright (c) 2012 Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* (Note that this file can be compiled with either C++, in which
case it uses C++ std::complex<double>, or C, in which case it
uses C99 double complex.) */
/* Available at: http://ab-initio.mit.edu/Faddeeva
Computes various error functions (erf, erfc, erfi, erfcx),
including the Dawson integral, in the complex plane, based
on algorithms for the computation of the Faddeeva function
w(z) = exp(-z^2) * erfc(-i*z).
Given w(z), the error functions are mostly straightforward
to compute, except for certain regions where we have to
switch to Taylor expansions to avoid cancellation errors
[e.g. near the origin for erf(z)].
To compute the Faddeeva function, we use a combination of two
algorithms:
For sufficiently large |z|, we use a continued-fraction expansion
for w(z) similar to those described in:
Walter Gautschi, "Efficient computation of the complex error
function," SIAM J. Numer. Anal. 7(1), pp. 187-198 (1970)
G. P. M. Poppe and C. M. J. Wijers, "More efficient computation
of the complex error function," ACM Trans. Math. Soft. 16(1),
pp. 38-46 (1990).
Unlike those papers, however, we switch to a completely different
algorithm for smaller |z|:
Mofreh R. Zaghloul and Ahmed N. Ali, "Algorithm 916: Computing the
Faddeyeva and Voigt Functions," ACM Trans. Math. Soft. 38(2), 15
(2011).
(I initially used this algorithm for all z, but it turned out to be
significantly slower than the continued-fraction expansion for
larger |z|. On the other hand, it is competitive for smaller |z|,
and is significantly more accurate than the Poppe & Wijers code
in some regions, e.g. in the vicinity of z=1+1i.)
Note that this is an INDEPENDENT RE-IMPLEMENTATION of these algorithms,
based on the description in the papers ONLY. In particular, I did
not refer to the authors' Fortran or Matlab implementations, respectively,
(which are under restrictive ACM copyright terms and therefore unusable
in free/open-source software).
Steven G. Johnson, Massachusetts Institute of Technology
http://math.mit.edu/~stevenj
October 2012.
-- Note that Algorithm 916 assumes that the erfc(x) function,
or rather the scaled function erfcx(x) = exp(x*x)*erfc(x),
is supplied for REAL arguments x. I originally used an
erfcx routine derived from DERFC in SLATEC, but I have
since replaced it with a much faster routine written by
me which uses a combination of continued-fraction expansions
and a lookup table of Chebyshev polynomials. For speed,
I implemented a similar algorithm for Im[w(x)] of real x,
since this comes up frequently in the other error functions.
A small test program is included the end, which checks
the w(z) etc. results against several known values. To compile
the test function, compile with -DTEST_FADDEEVA (that is,
#define TEST_FADDEEVA).
If HAVE_CONFIG_H is #defined (e.g. by compiling with -DHAVE_CONFIG_H),
then we #include "config.h", which is assumed to be a GNU autoconf-style
header defining HAVE_* macros to indicate the presence of features. In
particular, if HAVE_ISNAN and HAVE_ISINF are #defined, we use those
functions in math.h instead of defining our own, and if HAVE_ERF and/or
HAVE_ERFC are defined we use those functions from <cmath> for erf and
erfc of real arguments, respectively, instead of defining our own.
REVISION HISTORY:
4 October 2012: Initial public release (SGJ)
5 October 2012: Revised (SGJ) to fix spelling error,
start summation for large x at round(x/a) (> 1)
rather than ceil(x/a) as in the original
paper, which should slightly improve performance
(and, apparently, slightly improves accuracy)
19 October 2012: Revised (SGJ) to fix bugs for large x, large -y,
and 15<x<26. Performance improvements. Prototype
now supplies default value for relerr.
24 October 2012: Switch to continued-fraction expansion for
sufficiently large z, for performance reasons.
Also, avoid spurious overflow for |z| > 1e154.
Set relerr argument to min(relerr,0.1).
27 October 2012: Enhance accuracy in Re[w(z)] taken by itself,
by switching to Alg. 916 in a region near
the real-z axis where continued fractions
have poor relative accuracy in Re[w(z)]. Thanks
to M. Zaghloul for the tip.
29 October 2012: Replace SLATEC-derived erfcx routine with
completely rewritten code by me, using a very
different algorithm which is much faster.
30 October 2012: Implemented special-case code for real z
(where real part is exp(-x^2) and imag part is
Dawson integral), using algorithm similar to erfx.
Export ImFaddeeva_w function to make Dawson's
integral directly accessible.
3 November 2012: Provide implementations of erf, erfc, erfcx,
and Dawson functions in Faddeeva:: namespace,
in addition to Faddeeva::w. Provide header
file Faddeeva.hh.
4 November 2012: Slightly faster erf for real arguments.
Updated MATLAB and Octave plugins.
27 November 2012: Support compilation with either C++ or
plain C (using C99 complex numbers).
For real x, use standard-library erf(x)
and erfc(x) if available (for C99 or C++11).
#include "config.h" if HAVE_CONFIG_H is #defined.
15 December 2012: Portability fixes (copysign, Inf/NaN creation),
use CMPLX/__builtin_complex if available in C,
slight accuracy improvements to erf and dawson
functions near the origin. Use gnulib functions
if GNULIB_NAMESPACE is defined.
18 December 2012: Slight tweaks (remove recomputation of x*x in Dawson)
*/
/////////////////////////////////////////////////////////////////////////
/* If this file is compiled as a part of a larger project,
support using an autoconf-style config.h header file
(with various "HAVE_*" #defines to indicate features)
if HAVE_CONFIG_H is #defined (in GNU autotools style). */
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
/////////////////////////////////////////////////////////////////////////
// macros to allow us to use either C++ or C (with C99 features)
#ifdef __cplusplus
# include "Faddeeva.hh"
# include <cfloat>
# include <cmath>
# include <limits>
using namespace std;
// use std::numeric_limits, since 1./0. and 0./0. fail with some compilers (MS)
# define Inf numeric_limits<double>::infinity()
# define NaN numeric_limits<double>::quiet_NaN()
typedef complex<double> cmplx;
// Use C-like complex syntax, since the C syntax is more restrictive
# define cexp(z) exp(z)
# define creal(z) real(z)
# define cimag(z) imag(z)
# define cpolar(r,t) polar(r,t)
# define C(a,b) cmplx(a,b)
# define FADDEEVA(name) Faddeeva::name
# define FADDEEVA_RE(name) Faddeeva::name
// isnan/isinf were introduced in C++11
# if (__cplusplus < 201103L) && (!defined(HAVE_ISNAN) || !defined(HAVE_ISINF))
static inline bool my_isnan(double x) { return x != x; }
# define isnan my_isnan
static inline bool my_isinf(double x) { return 1/x == 0.; }
# define isinf my_isinf
# elif (__cplusplus >= 201103L)
// g++ gets confused between the C and C++ isnan/isinf functions
# define isnan std::isnan
# define isinf std::isinf
# endif
// copysign was introduced in C++11 (and is also in POSIX and C99)
# if defined(_WIN32) || defined(__WIN32__)
# define copysign _copysign // of course MS had to be different
# elif defined(GNULIB_NAMESPACE) // we are using using gnulib <cmath>
# define copysign GNULIB_NAMESPACE::copysign
# elif (__cplusplus < 201103L) && !defined(HAVE_COPYSIGN) && !defined(__linux__) && !(defined(__APPLE__) && defined(__MACH__)) && !defined(_AIX)
static inline double my_copysign(double x, double y) { return y<0 ? -x : x; }
# define copysign my_copysign
# endif
// If we are using the gnulib <cmath> (e.g. in the GNU Octave sources),
// gnulib generates a link warning if we use ::floor instead of gnulib::floor.
// This warning is completely innocuous because the only difference between
// gnulib::floor and the system ::floor (and only on ancient OSF systems)
// has to do with floor(-0), which doesn't occur in the usage below, but
// the Octave developers prefer that we silence the warning.
# ifdef GNULIB_NAMESPACE
# define floor GNULIB_NAMESPACE::floor
# endif
#else // !__cplusplus, i.e. pure C (requires C99 features)
# include "Faddeeva.h"
# define _GNU_SOURCE // enable GNU libc NAN extension if possible
# include <float.h>
# include <math.h>
typedef double complex cmplx;
# define FADDEEVA(name) Faddeeva_ ## name
# define FADDEEVA_RE(name) Faddeeva_ ## name ## _re
/* Constructing complex numbers like 0+i*NaN is problematic in C99
without the C11 CMPLX macro, because 0.+I*NAN may give NaN+i*NAN if
I is a complex (rather than imaginary) constant. For some reason,
however, it works fine in (pre-4.7) gcc if I define Inf and NaN as
1/0 and 0/0 (and only if I compile with optimization -O1 or more),
but not if I use the INFINITY or NAN macros. */
/* __builtin_complex was introduced in gcc 4.7, but the C11 CMPLX macro
may not be defined unless we are using a recent (2012) version of
glibc and compile with -std=c11... note that icc lies about being
gcc and probably doesn't have this builtin(?), so exclude icc explicitly */
# if !defined(CMPLX) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)) && !(defined(__ICC) || defined(__INTEL_COMPILER))
# define CMPLX(a,b) __builtin_complex((double) (a), (double) (b))
# endif
# ifdef CMPLX // C11
# define C(a,b) CMPLX(a,b)
# define Inf INFINITY // C99 infinity
# ifdef NAN // GNU libc extension
# define NaN NAN
# else
# define NaN (0./0.) // NaN
# endif
# else
# define C(a,b) ((a) + I*(b))
# define Inf (1./0.)
# define NaN (0./0.)
# endif
static inline cmplx cpolar(double r, double t)
{
if (r == 0.0 && !isnan(t))
return 0.0;
else
return C(r * cos(t), r * sin(t));
}
#endif // !__cplusplus, i.e. pure C (requires C99 features)
/////////////////////////////////////////////////////////////////////////
// Auxiliary routines to compute other special functions based on w(z)
// compute erfcx(z) = exp(z^2) erfz(z)
cmplx FADDEEVA(erfcx)(cmplx z, double relerr)
{
return FADDEEVA(w)(C(-cimag(z), creal(z)), relerr);
}
// compute the error function erf(x)
double FADDEEVA_RE(erf)(double x)
{
#if !defined(__cplusplus)
return erf(x); // C99 supplies erf in math.h
#elif (__cplusplus >= 201103L) || defined(HAVE_ERF)
return ::erf(x); // C++11 supplies std::erf in cmath
#else
double mx2 = -x*x;
if (mx2 < -750) // underflow
return (x >= 0 ? 1.0 : -1.0);
if (x >= 0) {
if (x < 8e-2) goto taylor;
return 1.0 - exp(mx2) * FADDEEVA_RE(erfcx)(x);
}
else { // x < 0
if (x > -8e-2) goto taylor;
return exp(mx2) * FADDEEVA_RE(erfcx)(-x) - 1.0;
}
// Use Taylor series for small |x|, to avoid cancellation inaccuracy
// erf(x) = 2/sqrt(pi) * x * (1 - x^2/3 + x^4/10 - x^6/42 + x^8/216 + ...)
taylor:
return x * (1.1283791670955125739
+ mx2 * (0.37612638903183752464
+ mx2 * (0.11283791670955125739
+ mx2 * (0.026866170645131251760
+ mx2 * 0.0052239776254421878422))));
#endif
}
// compute the error function erf(z)
cmplx FADDEEVA(erf)(cmplx z, double relerr)
{
double x = creal(z), y = cimag(z);
if (y == 0)
return C(FADDEEVA_RE(erf)(x),
y); // preserve sign of 0
if (x == 0) // handle separately for speed & handling of y = Inf or NaN
return C(x, // preserve sign of 0
/* handle y -> Inf limit manually, since
exp(y^2) -> Inf but Im[w(y)] -> 0, so
IEEE will give us a NaN when it should be Inf */
y*y > 720 ? (y > 0 ? Inf : -Inf)
: exp(y*y) * FADDEEVA(w_im)(y));
double mRe_z2 = (y - x) * (x + y); // Re(-z^2), being careful of overflow
double mIm_z2 = -2*x*y; // Im(-z^2)
if (mRe_z2 < -750) // underflow
return (x >= 0 ? 1.0 : -1.0);
/* Handle positive and negative x via different formulas,
using the mirror symmetries of w, to avoid overflow/underflow
problems from multiplying exponentially large and small quantities. */
if (x >= 0) {
if (x < 8e-2) {
if (fabs(y) < 1e-2)
goto taylor;
else if (fabs(mIm_z2) < 5e-3 && x < 5e-3)
goto taylor_erfi;
}
/* don't use complex exp function, since that will produce spurious NaN
values when multiplying w in an overflow situation. */
return 1.0 - exp(mRe_z2) *
(C(cos(mIm_z2), sin(mIm_z2))
* FADDEEVA(w)(C(-y,x), relerr));
}
else { // x < 0
if (x > -8e-2) { // duplicate from above to avoid fabs(x) call
if (fabs(y) < 1e-2)
goto taylor;
else if (fabs(mIm_z2) < 5e-3 && x > -5e-3)
goto taylor_erfi;
}
else if (isnan(x))
return C(NaN, y == 0 ? 0 : NaN);
/* don't use complex exp function, since that will produce spurious NaN
values when multiplying w in an overflow situation. */
return exp(mRe_z2) *
(C(cos(mIm_z2), sin(mIm_z2))
* FADDEEVA(w)(C(y,-x), relerr)) - 1.0;
}
// Use Taylor series for small |z|, to avoid cancellation inaccuracy
// erf(z) = 2/sqrt(pi) * z * (1 - z^2/3 + z^4/10 - z^6/42 + z^8/216 + ...)
taylor:
{
cmplx mz2 = C(mRe_z2, mIm_z2); // -z^2
return z * (1.1283791670955125739
+ mz2 * (0.37612638903183752464
+ mz2 * (0.11283791670955125739
+ mz2 * (0.026866170645131251760
+ mz2 * 0.0052239776254421878422))));
}
/* for small |x| and small |xy|,
use Taylor series to avoid cancellation inaccuracy:
erf(x+iy) = erf(iy)
+ 2*exp(y^2)/sqrt(pi) *
[ x * (1 - x^2 * (1+2y^2)/3 + x^4 * (3+12y^2+4y^4)/30 + ...
- i * x^2 * y * (1 - x^2 * (3+2y^2)/6 + ...) ]
where:
erf(iy) = exp(y^2) * Im[w(y)]
*/
taylor_erfi:
{
double x2 = x*x, y2 = y*y;
double expy2 = exp(y2);
return C
(expy2 * x * (1.1283791670955125739
- x2 * (0.37612638903183752464
+ 0.75225277806367504925*y2)
+ x2*x2 * (0.11283791670955125739
+ y2 * (0.45135166683820502956
+ 0.15045055561273500986*y2))),
expy2 * (FADDEEVA(w_im)(y)
- x2*y * (1.1283791670955125739
- x2 * (0.56418958354775628695
+ 0.37612638903183752464*y2))));
}
}
// erfi(z) = -i erf(iz)
cmplx FADDEEVA(erfi)(cmplx z, double relerr)
{
cmplx e = FADDEEVA(erf)(C(-cimag(z),creal(z)), relerr);
return C(cimag(e), -creal(e));
}
// erfi(x) = -i erf(ix)
double FADDEEVA_RE(erfi)(double x)
{
return x*x > 720 ? (x > 0 ? Inf : -Inf)
: exp(x*x) * FADDEEVA(w_im)(x);
}
// erfc(x) = 1 - erf(x)
double FADDEEVA_RE(erfc)(double x)
{
#if !defined(__cplusplus)
return erfc(x); // C99 supplies erfc in math.h
#elif (__cplusplus >= 201103L) || defined(HAVE_ERFC)
return ::erfc(x); // C++11 supplies std::erfc in cmath
#else
if (x*x > 750) // underflow
return (x >= 0 ? 0.0 : 2.0);
return x >= 0 ? exp(-x*x) * FADDEEVA_RE(erfcx)(x)
: 2. - exp(-x*x) * FADDEEVA_RE(erfcx)(-x);
#endif
}
// erfc(z) = 1 - erf(z)
cmplx FADDEEVA(erfc)(cmplx z, double relerr)
{
double x = creal(z), y = cimag(z);
if (x == 0.)
return C(1,
/* handle y -> Inf limit manually, since
exp(y^2) -> Inf but Im[w(y)] -> 0, so
IEEE will give us a NaN when it should be Inf */
y*y > 720 ? (y > 0 ? -Inf : Inf)
: -exp(y*y) * FADDEEVA(w_im)(y));
if (y == 0.) {
if (x*x > 750) // underflow
return C(x >= 0 ? 0.0 : 2.0,
-y); // preserve sign of 0
return C(x >= 0 ? exp(-x*x) * FADDEEVA_RE(erfcx)(x)
: 2. - exp(-x*x) * FADDEEVA_RE(erfcx)(-x),
-y); // preserve sign of zero
}
double mRe_z2 = (y - x) * (x + y); // Re(-z^2), being careful of overflow
double mIm_z2 = -2*x*y; // Im(-z^2)
if (mRe_z2 < -750) // underflow
return (x >= 0 ? 0.0 : 2.0);
if (x >= 0)
return cexp(C(mRe_z2, mIm_z2))
* FADDEEVA(w)(C(-y,x), relerr);
else
return 2.0 - cexp(C(mRe_z2, mIm_z2))
* FADDEEVA(w)(C(y,-x), relerr);
}
// compute Dawson(x) = sqrt(pi)/2 * exp(-x^2) * erfi(x)
double FADDEEVA_RE(Dawson)(double x)
{
const double spi2 = 0.8862269254527580136490837416705725913990; // sqrt(pi)/2
return spi2 * FADDEEVA(w_im)(x);
}
// compute Dawson(z) = sqrt(pi)/2 * exp(-z^2) * erfi(z)
cmplx FADDEEVA(Dawson)(cmplx z, double relerr)
{
const double spi2 = 0.8862269254527580136490837416705725913990; // sqrt(pi)/2
double x = creal(z), y = cimag(z);
// handle axes separately for speed & proper handling of x or y = Inf or NaN
if (y == 0)
return C(spi2 * FADDEEVA(w_im)(x),
-y); // preserve sign of 0
if (x == 0) {
double y2 = y*y;
if (y2 < 2.5e-5) { // Taylor expansion
return C(x, // preserve sign of 0
y * (1.
+ y2 * (0.6666666666666666666666666666666666666667
+ y2 * 0.26666666666666666666666666666666666667)));
}
return C(x, // preserve sign of 0
spi2 * (y >= 0
? exp(y2) - FADDEEVA_RE(erfcx)(y)
: FADDEEVA_RE(erfcx)(-y) - exp(y2)));
}
double mRe_z2 = (y - x) * (x + y); // Re(-z^2), being careful of overflow
double mIm_z2 = -2*x*y; // Im(-z^2)
cmplx mz2 = C(mRe_z2, mIm_z2); // -z^2
/* Handle positive and negative x via different formulas,
using the mirror symmetries of w, to avoid overflow/underflow
problems from multiplying exponentially large and small quantities. */
if (y >= 0) {
if (y < 5e-3) {
if (fabs(x) < 5e-3)
goto taylor;
else if (fabs(mIm_z2) < 5e-3)
goto taylor_realaxis;
}
cmplx res = cexp(mz2) - FADDEEVA(w)(z, relerr);
return spi2 * C(-cimag(res), creal(res));
}
else { // y < 0
if (y > -5e-3) { // duplicate from above to avoid fabs(x) call
if (fabs(x) < 5e-3)
goto taylor;
else if (fabs(mIm_z2) < 5e-3)
goto taylor_realaxis;
}
else if (isnan(y))
return C(x == 0 ? 0 : NaN, NaN);
cmplx res = FADDEEVA(w)(-z, relerr) - cexp(mz2);
return spi2 * C(-cimag(res), creal(res));
}
// Use Taylor series for small |z|, to avoid cancellation inaccuracy
// dawson(z) = z - 2/3 z^3 + 4/15 z^5 + ...
taylor:
return z * (1.
+ mz2 * (0.6666666666666666666666666666666666666667
+ mz2 * 0.2666666666666666666666666666666666666667));
/* for small |y| and small |xy|,
use Taylor series to avoid cancellation inaccuracy:
dawson(x + iy)
= D + y^2 (D + x - 2Dx^2)
+ y^4 (D/2 + 5x/6 - 2Dx^2 - x^3/3 + 2Dx^4/3)
+ iy [ (1-2Dx) + 2/3 y^2 (1 - 3Dx - x^2 + 2Dx^3)
+ y^4/15 (4 - 15Dx - 9x^2 + 20Dx^3 + 2x^4 - 4Dx^5) ] + ...
where D = dawson(x)
However, for large |x|, 2Dx -> 1 which gives cancellation problems in
this series (many of the leading terms cancel). So, for large |x|,
we need to substitute a continued-fraction expansion for D.
dawson(x) = 0.5 / (x-0.5/(x-1/(x-1.5/(x-2/(x-2.5/(x...))))))
The 6 terms shown here seems to be the minimum needed to be
accurate as soon as the simpler Taylor expansion above starts
breaking down. Using this 6-term expansion, factoring out the
denominator, and simplifying with Maple, we obtain:
Re dawson(x + iy) * (-15 + 90x^2 - 60x^4 + 8x^6) / x
= 33 - 28x^2 + 4x^4 + y^2 (18 - 4x^2) + 4 y^4
Im dawson(x + iy) * (-15 + 90x^2 - 60x^4 + 8x^6) / y
= -15 + 24x^2 - 4x^4 + 2/3 y^2 (6x^2 - 15) - 4 y^4
Finally, for |x| > 5e7, we can use a simpler 1-term continued-fraction
expansion for the real part, and a 2-term expansion for the imaginary
part. (This avoids overflow problems for huge |x|.) This yields:
Re dawson(x + iy) = [1 + y^2 (1 + y^2/2 - (xy)^2/3)] / (2x)
Im dawson(x + iy) = y [ -1 - 2/3 y^2 + y^4/15 (2x^2 - 4) ] / (2x^2 - 1)
*/
taylor_realaxis:
{
double x2 = x*x;
if (x2 > 1600) { // |x| > 40
double y2 = y*y;
if (x2 > 25e14) {// |x| > 5e7
double xy2 = (x*y)*(x*y);
return C((0.5 + y2 * (0.5 + 0.25*y2
- 0.16666666666666666667*xy2)) / x,
y * (-1 + y2 * (-0.66666666666666666667
+ 0.13333333333333333333*xy2
- 0.26666666666666666667*y2))
/ (2*x2 - 1));
}
return (1. / (-15 + x2*(90 + x2*(-60 + 8*x2)))) *
C(x * (33 + x2 * (-28 + 4*x2)
+ y2 * (18 - 4*x2 + 4*y2)),
y * (-15 + x2 * (24 - 4*x2)
+ y2 * (4*x2 - 10 - 4*y2)));
}
else {
double D = spi2 * FADDEEVA(w_im)(x);
double y2 = y*y;
return C
(D + y2 * (D + x - 2*D*x2)
+ y2*y2 * (D * (0.5 - x2 * (2 - 0.66666666666666666667*x2))
+ x * (0.83333333333333333333
- 0.33333333333333333333 * x2)),
y * (1 - 2*D*x
+ y2 * 0.66666666666666666667 * (1 - x2 - D*x * (3 - 2*x2))
+ y2*y2 * (0.26666666666666666667 -
x2 * (0.6 - 0.13333333333333333333 * x2)
- D*x * (1 - x2 * (1.3333333333333333333
- 0.26666666666666666667 * x2)))));
}
}
}
/////////////////////////////////////////////////////////////////////////
// return sinc(x) = sin(x)/x, given both x and sin(x)
// [since we only use this in cases where sin(x) has already been computed]
static inline double sinc(double x, double sinx) {
return fabs(x) < 1e-4 ? 1 - (0.1666666666666666666667)*x*x : sinx / x;
}
// sinh(x) via Taylor series, accurate to machine precision for |x| < 1e-2
static inline double sinh_taylor(double x) {
return x * (1 + (x*x) * (0.1666666666666666666667
+ 0.00833333333333333333333 * (x*x)));
}
static inline double sqr(double x) { return x*x; }
// precomputed table of expa2n2[n-1] = exp(-a2*n*n)
// for double-precision a2 = 0.26865... in FADDEEVA(w), below.
static const double expa2n2[] = {
7.64405281671221563e-01,
3.41424527166548425e-01,
8.91072646929412548e-02,
1.35887299055460086e-02,
1.21085455253437481e-03,
6.30452613933449404e-05,
1.91805156577114683e-06,
3.40969447714832381e-08,
3.54175089099469393e-10,
2.14965079583260682e-12,
7.62368911833724354e-15,
1.57982797110681093e-17,
1.91294189103582677e-20,
1.35344656764205340e-23,
5.59535712428588720e-27,
1.35164257972401769e-30,
1.90784582843501167e-34,
1.57351920291442930e-38,
7.58312432328032845e-43,
2.13536275438697082e-47,
3.51352063787195769e-52,
3.37800830266396920e-57,
1.89769439468301000e-62,
6.22929926072668851e-68,
1.19481172006938722e-73,
1.33908181133005953e-79,
8.76924303483223939e-86,
3.35555576166254986e-92,
7.50264110688173024e-99,
9.80192200745410268e-106,
7.48265412822268959e-113,
3.33770122566809425e-120,
8.69934598159861140e-128,
1.32486951484088852e-135,
1.17898144201315253e-143,
6.13039120236180012e-152,
1.86258785950822098e-160,
3.30668408201432783e-169,
3.43017280887946235e-178,
2.07915397775808219e-187,
7.36384545323984966e-197,
1.52394760394085741e-206,
1.84281935046532100e-216,
1.30209553802992923e-226,
5.37588903521080531e-237,
1.29689584599763145e-247,
1.82813078022866562e-258,
1.50576355348684241e-269,
7.24692320799294194e-281,
2.03797051314726829e-292,
3.34880215927873807e-304,
0.0 // underflow (also prevents reads past array end, below)
};
/////////////////////////////////////////////////////////////////////////
cmplx FADDEEVA(w)(cmplx z, double relerr)
{
if (creal(z) == 0.0)
return C(FADDEEVA_RE(erfcx)(cimag(z)),
creal(z)); // give correct sign of 0 in cimag(w)
else if (cimag(z) == 0)
return C(exp(-sqr(creal(z))),
FADDEEVA(w_im)(creal(z)));
double a, a2, c;
if (relerr <= DBL_EPSILON) {
relerr = DBL_EPSILON;
a = 0.518321480430085929872; // pi / sqrt(-log(eps*0.5))
c = 0.329973702884629072537; // (2/pi) * a;
a2 = 0.268657157075235951582; // a^2
}
else {
const double pi = 3.14159265358979323846264338327950288419716939937510582;
if (relerr > 0.1) relerr = 0.1; // not sensible to compute < 1 digit
a = pi / sqrt(-log(relerr*0.5));
c = (2/pi)*a;
a2 = a*a;
}
const double x = fabs(creal(z));
const double y = cimag(z), ya = fabs(y);
cmplx ret = 0.; // return value
double sum1 = 0, sum2 = 0, sum3 = 0, sum4 = 0, sum5 = 0;
#define USE_CONTINUED_FRACTION 1 // 1 to use continued fraction for large |z|
#if USE_CONTINUED_FRACTION
if (ya > 7 || (x > 6 // continued fraction is faster
/* As pointed out by M. Zaghloul, the continued
fraction seems to give a large relative error in
Re w(z) for |x| ~ 6 and small |y|, so use
algorithm 816 in this region: */
&& (ya > 0.1 || (x > 8 && ya > 1e-10) || x > 28))) {
/* Poppe & Wijers suggest using a number of terms
nu = 3 + 1442 / (26*rho + 77)
where rho = sqrt((x/x0)^2 + (y/y0)^2) where x0=6.3, y0=4.4.
(They only use this expansion for rho >= 1, but rho a little less
than 1 seems okay too.)
Instead, I did my own fit to a slightly different function
that avoids the hypotenuse calculation, using NLopt to minimize
the sum of the squares of the errors in nu with the constraint
that the estimated nu be >= minimum nu to attain machine precision.
I also separate the regions where nu == 2 and nu == 1. */
const double ispi = 0.56418958354775628694807945156; // 1 / sqrt(pi)
double xs = y < 0 ? -creal(z) : creal(z); // compute for -z if y < 0
if (x + ya > 4000) { // nu <= 2
if (x + ya > 1e7) { // nu == 1, w(z) = i/sqrt(pi) / z
// scale to avoid overflow
if (x > ya) {
double yax = ya / xs;
double denom = ispi / (xs + yax*ya);
ret = C(denom*yax, denom);
}
else if (isinf(ya))
return ((isnan(x) || y < 0)
? C(NaN,NaN) : C(0,0));
else {
double xya = xs / ya;
double denom = ispi / (xya*xs + ya);
ret = C(denom, denom*xya);
}
}
else { // nu == 2, w(z) = i/sqrt(pi) * z / (z*z - 0.5)
double dr = xs*xs - ya*ya - 0.5, di = 2*xs*ya;
double denom = ispi / (dr*dr + di*di);
ret = C(denom * (xs*di-ya*dr), denom * (xs*dr+ya*di));
}
}
else { // compute nu(z) estimate and do general continued fraction
const double c0=3.9, c1=11.398, c2=0.08254, c3=0.1421, c4=0.2023; // fit
double nu = floor(c0 + c1 / (c2*x + c3*ya + c4));
double wr = xs, wi = ya;
for (nu = 0.5 * (nu - 1); nu > 0.4; nu -= 0.5) {
// w <- z - nu/w:
double denom = nu / (wr*wr + wi*wi);
wr = xs - wr * denom;
wi = ya + wi * denom;
}
{ // w(z) = i/sqrt(pi) / w:
double denom = ispi / (wr*wr + wi*wi);
ret = C(denom*wi, denom*wr);
}
}
if (y < 0) {
// use w(z) = 2.0*exp(-z*z) - w(-z),
// but be careful of overflow in exp(-z*z)
// = exp(-(xs*xs-ya*ya) -2*i*xs*ya)
return 2.0*cexp(C((ya-xs)*(xs+ya), 2*xs*y)) - ret;
}
else
return ret;
}
#else // !USE_CONTINUED_FRACTION
if (x + ya > 1e7) { // w(z) = i/sqrt(pi) / z, to machine precision
const double ispi = 0.56418958354775628694807945156; // 1 / sqrt(pi)
double xs = y < 0 ? -creal(z) : creal(z); // compute for -z if y < 0
// scale to avoid overflow
if (x > ya) {
double yax = ya / xs;
double denom = ispi / (xs + yax*ya);
ret = C(denom*yax, denom);
}
else {
double xya = xs / ya;
double denom = ispi / (xya*xs + ya);
ret = C(denom, denom*xya);
}
if (y < 0) {
// use w(z) = 2.0*exp(-z*z) - w(-z),
// but be careful of overflow in exp(-z*z)
// = exp(-(xs*xs-ya*ya) -2*i*xs*ya)
return 2.0*cexp(C((ya-xs)*(xs+ya), 2*xs*y)) - ret;
}
else
return ret;
}
#endif // !USE_CONTINUED_FRACTION
/* Note: The test that seems to be suggested in the paper is x <
sqrt(-log(DBL_MIN)), about 26.6, since otherwise exp(-x^2)
underflows to zero and sum1,sum2,sum4 are zero. However, long
before this occurs, the sum1,sum2,sum4 contributions are
negligible in double precision; I find that this happens for x >
about 6, for all y. On the other hand, I find that the case
where we compute all of the sums is faster (at least with the
precomputed expa2n2 table) until about x=10. Furthermore, if we
try to compute all of the sums for x > 20, I find that we
sometimes run into numerical problems because underflow/overflow
problems start to appear in the various coefficients of the sums,
below. Therefore, we use x < 10 here. */
else if (x < 10) {
double prod2ax = 1, prodm2ax = 1;
double expx2;
if (isnan(y))
return C(y,y);
/* Somewhat ugly copy-and-paste duplication here, but I see significant
speedups from using the special-case code with the precomputed
exponential, and the x < 5e-4 special case is needed for accuracy. */
if (relerr == DBL_EPSILON) { // use precomputed exp(-a2*(n*n)) table
if (x < 5e-4) { // compute sum4 and sum5 together as sum5-sum4
const double x2 = x*x;
expx2 = 1 - x2 * (1 - 0.5*x2); // exp(-x*x) via Taylor
// compute exp(2*a*x) and exp(-2*a*x) via Taylor, to double precision
const double ax2 = 1.036642960860171859744*x; // 2*a*x
const double exp2ax =
1 + ax2 * (1 + ax2 * (0.5 + 0.166666666666666666667*ax2));
const double expm2ax =
1 - ax2 * (1 - ax2 * (0.5 - 0.166666666666666666667*ax2));
for (int n = 1; 1; ++n) {
const double coef = expa2n2[n-1] * expx2 / (a2*(n*n) + y*y);
prod2ax *= exp2ax;
prodm2ax *= expm2ax;
sum1 += coef;
sum2 += coef * prodm2ax;
sum3 += coef * prod2ax;
// really = sum5 - sum4
sum5 += coef * (2*a) * n * sinh_taylor((2*a)*n*x);
// test convergence via sum3
if (coef * prod2ax < relerr * sum3) break;
}
}
else { // x > 5e-4, compute sum4 and sum5 separately
expx2 = exp(-x*x);
const double exp2ax = exp((2*a)*x), expm2ax = 1 / exp2ax;
for (int n = 1; 1; ++n) {
const double coef = expa2n2[n-1] * expx2 / (a2*(n*n) + y*y);
prod2ax *= exp2ax;
prodm2ax *= expm2ax;
sum1 += coef;
sum2 += coef * prodm2ax;
sum4 += (coef * prodm2ax) * (a*n);
sum3 += coef * prod2ax;
sum5 += (coef * prod2ax) * (a*n);
// test convergence via sum5, since this sum has the slowest decay
if ((coef * prod2ax) * (a*n) < relerr * sum5) break;
}
}
}
else { // relerr != DBL_EPSILON, compute exp(-a2*(n*n)) on the fly
const double exp2ax = exp((2*a)*x), expm2ax = 1 / exp2ax;
if (x < 5e-4) { // compute sum4 and sum5 together as sum5-sum4
const double x2 = x*x;
expx2 = 1 - x2 * (1 - 0.5*x2); // exp(-x*x) via Taylor
for (int n = 1; 1; ++n) {
const double coef = exp(-a2*(n*n)) * expx2 / (a2*(n*n) + y*y);
prod2ax *= exp2ax;
prodm2ax *= expm2ax;
sum1 += coef;
sum2 += coef * prodm2ax;
sum3 += coef * prod2ax;
// really = sum5 - sum4
sum5 += coef * (2*a) * n * sinh_taylor((2*a)*n*x);
// test convergence via sum3
if (coef * prod2ax < relerr * sum3) break;
}
}
else { // x > 5e-4, compute sum4 and sum5 separately
expx2 = exp(-x*x);
for (int n = 1; 1; ++n) {
const double coef = exp(-a2*(n*n)) * expx2 / (a2*(n*n) + y*y);
prod2ax *= exp2ax;
prodm2ax *= expm2ax;
sum1 += coef;
sum2 += coef * prodm2ax;
sum4 += (coef * prodm2ax) * (a*n);
sum3 += coef * prod2ax;
sum5 += (coef * prod2ax) * (a*n);
// test convergence via sum5, since this sum has the slowest decay
if ((coef * prod2ax) * (a*n) < relerr * sum5) break;
}
}
}
const double expx2erfcxy = // avoid spurious overflow for large negative y
y > -6 // for y < -6, erfcx(y) = 2*exp(y*y) to double precision
? expx2*FADDEEVA_RE(erfcx)(y) : 2*exp(y*y-x*x);
if (y > 5) { // imaginary terms cancel
const double sinxy = sin(x*y);
ret = (expx2erfcxy - c*y*sum1) * cos(2*x*y)
+ (c*x*expx2) * sinxy * sinc(x*y, sinxy);
}
else {
double xs = creal(z);
const double sinxy = sin(xs*y);
const double sin2xy = sin(2*xs*y), cos2xy = cos(2*xs*y);
const double coef1 = expx2erfcxy - c*y*sum1;
const double coef2 = c*xs*expx2;
ret = C(coef1 * cos2xy + coef2 * sinxy * sinc(xs*y, sinxy),
coef2 * sinc(2*xs*y, sin2xy) - coef1 * sin2xy);
}
}
else { // x large: only sum3 & sum5 contribute (see above note)
if (isnan(x))
return C(x,x);
if (isnan(y))
return C(y,y);
#if USE_CONTINUED_FRACTION
ret = exp(-x*x); // |y| < 1e-10, so we only need exp(-x*x) term
#else
if (y < 0) {
/* erfcx(y) ~ 2*exp(y*y) + (< 1) if y < 0, so
erfcx(y)*exp(-x*x) ~ 2*exp(y*y-x*x) term may not be negligible
if y*y - x*x > -36 or so. So, compute this term just in case.
We also need the -exp(-x*x) term to compute Re[w] accurately
in the case where y is very small. */
ret = cpolar(2*exp(y*y-x*x) - exp(-x*x), -2*creal(z)*y);
}
else
ret = exp(-x*x); // not negligible in real part if y very small
#endif
// (round instead of ceil as in original paper; note that x/a > 1 here)
double n0 = floor(x/a + 0.5); // sum in both directions, starting at n0
double dx = a*n0 - x;
sum3 = exp(-dx*dx) / (a2*(n0*n0) + y*y);
sum5 = a*n0 * sum3;
double exp1 = exp(4*a*dx), exp1dn = 1;
int dn;
for (dn = 1; n0 - dn > 0; ++dn) { // loop over n0-dn and n0+dn terms
double np = n0 + dn, nm = n0 - dn;
double tp = exp(-sqr(a*dn+dx));
double tm = tp * (exp1dn *= exp1); // trick to get tm from tp
tp /= (a2*(np*np) + y*y);
tm /= (a2*(nm*nm) + y*y);
sum3 += tp + tm;
sum5 += a * (np * tp + nm * tm);
if (a * (np * tp + nm * tm) < relerr * sum5) goto finish;
}
while (1) { // loop over n0+dn terms only (since n0-dn <= 0)
double np = n0 + dn++;
double tp = exp(-sqr(a*dn+dx)) / (a2*(np*np) + y*y);
sum3 += tp;
sum5 += a * np * tp;
if (a * np * tp < relerr * sum5) goto finish;
}
}
finish:
return ret + C((0.5*c)*y*(sum2+sum3),
(0.5*c)*copysign(sum5-sum4, creal(z)));
}
/////////////////////////////////////////////////////////////////////////
/* erfcx(x) = exp(x^2) erfc(x) function, for real x, written by
Steven G. Johnson, October 2012.
This function combines a few different ideas.
First, for x > 50, it uses a continued-fraction expansion (same as
for the Faddeeva function, but with algebraic simplifications for z=i*x).
Second, for 0 <= x <= 50, it uses Chebyshev polynomial approximations,
but with two twists:
a) It maps x to y = 4 / (4+x) in [0,1]. This simple transformation,
inspired by a similar transformation in the octave-forge/specfun
erfcx by Soren Hauberg, results in much faster Chebyshev convergence
than other simple transformations I have examined.
b) Instead of using a single Chebyshev polynomial for the entire
[0,1] y interval, we break the interval up into 100 equal
subintervals, with a switch/lookup table, and use much lower
degree Chebyshev polynomials in each subinterval. This greatly
improves performance in my tests.
For x < 0, we use the relationship erfcx(-x) = 2 exp(x^2) - erfc(x),
with the usual checks for overflow etcetera.
Performance-wise, it seems to be substantially faster than either