#include <stdint.h>
#include <math.h>

/**
 * erf function
 * Algorithm taken from the Boost project, source:
 * http://www.boost.org/doc/libs/1_46_1/boost/math/special_functions/erf.hpp
 * Use, modification and distribution are subject to the
 * Boost Software License, Version 1.0 (see notice below).
 * Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:

The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.

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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
 */

float fft_erff(float z)
{
    float val;
    unsigned int neg = 0;

    /* handle the symmetry: erf(-x) = -erf(x) */
    if (z < 0) {
        neg = 1;
        z = -z;
    }

    /* branch based on range of z, and pick appropriate approximation */
    if (z == 0) {
        return 0;
    /* handle the nan case, but don't use isnan for max portability */
    } else if (z != z) {
        return z;
    } else if (z < 1e-10f) {
        return z * 1.125f + z * 0.0033791670955f;
    } else if (z < 0.84375f) {
        // Maximum Deviation Found:                     1.561e-17
        // Expected Error Term:                         1.561e-17
        // Maximum Relative Change in Control Points:   1.155e-04
        // Max Error found at float precision =        2.961182e-17
        static const float p[] = {
            0.0834305892146531832907,
            -0.338165134459360935041,
            -0.0509990735146777432841,
            -0.00772758345802133288487,
            -0.000322780120964605683831,
        };
        static const float q[] = {
            0.455004033050794024546,
            0.0875222600142252549554,
            0.00858571925074406212772,
            0.0003709,
        };
        float zz = z * z;
        float val = ((p[0]+zz*(p[1]+zz*(p[2]+zz*(p[3]+zz*p[4])))) / (1.0f+zz*(q[0]+zz*(q[1]+zz*(q[2]+zz*q[3])))));
        return z * (1.04494857788f + val);
    } else if (z < 3.75f) {
        // Max Error found at float precision =        6.599585e-18
        // Maximum Deviation Found:                     3.909e-18
        // Expected Error Term:                         3.909e-18
        // Maximum Relative Change in Control Points:   9.886e-05
        static const float p[] = {
            -0.0243500476207698441272,
            0.0386540375035707201728,
            0.04394818964209516296,
            0.0175679436311802092299,
            0.00323962406290842133584,
            0.000235839115596880717416,
        };
        static const float q[] = {
            1.53991494948552447182,
            0.982403709157920235114,
            0.325732924782444448493,
            0.0563921837420478160373,
            0.00410369723978904575884,
        };
        float x = z - 1.5f;
        val = 0.5067281723f + (p[0]+x*(p[1]+x*(p[2]+x*(p[3]+x*(p[4]+x*p[5]))))) / (1.0f+x*(q[0]+x*(q[1]+x*(q[2]+x*(q[3]+x*q[4])))));
        goto return_erfc;
    } else if (z < 4.5f) {
        float x = 1.0f/(2.0f*z*z);
        val = (float)M_1_PI * (1.0f + x*(-1.0f + x*(3.0f + 15.0f*x*(-1.0f + 7.0f*x*(1.0f - 9.0f*x)))));
        goto return_erfc;
    /* Just use the asymptotic expansion here, truncation at second-order is enough to saturate single-precision floats. */
    } else if (z < 5.92f) {
        float x = 1.0f/(2.0f*z*z);
        val = (float)M_1_PI * (1.0f - x);
        goto return_erfc;
    /* finally return saturated result */
    } else {
        return 1;
    }

return_erfc:
    val *= expf(-z * z) / z;
    return (neg ? (result - 1) : (1 - result));
}

#ifdef TEST

#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <sys/time.h>

typedef union _f32 {
    float f;
    uint32_t i;
} _f32;

static float rel_err_diff(float x1, float x2)
{
  if(x1 == 0.0f && x2 == 0.0f) {
    return 0.0f;
  } else if (x1 == 0.0f) {
    return fabsf(x2);
  } else if(x1 <= 1e38f && x2 <= 1e38f && (x1 + x2 != 0.0f)) {
    return fabsf((x1-x2)/(x1+x2));
  } else {
    return 1.0f;
  }
}

static __attribute__((always_inline)) inline void disable_denormals(void)
{
    unsigned int a = 0x9f80;
    __asm__ __volatile__ ("ldmxcsr %0" : "+m" (a));
}

int main(void) {
    _f32 f, g1, g2;
    unsigned int i, nerrs = 0;
    float diff, maxdiff = 0.0f;

    disable_denormals();
    setvbuf(stdout, NULL, _IONBF, 0);

    nerrs = 0;
    maxdiff = 0.0f;
    f.i = 0x3f800000;
    printf("start: %.7f\n", f.f-1.0f);
    for (i = 0; i < (1 << 23U); i++) {
        f.i = 0x3f800000|i;
        f.f -= 1.0f;
        g1.f = erff(f.f);
        g2.f = fft_erff(f.f);
        if ((diff = rel_err_diff(g1.f, g2.f)) >=  0x1.0p-24f) {
            nerrs++;
            if (diff > fabsf(maxdiff)) maxdiff = diff;
            if (!(i & 0xff))
                printf("Error: erff(%.7g): %.7g != fft_erff(%.7g): %.7g (diff: %.7e / 0x%08x)\n", f.f, g1.f, f.f, g2.f, diff, (g1.i ^ g2.i));
        }
    }
    printf("end: %.7f\n", f.f);
    f.i = 0x3f800000;
    printf("start: %.7f\n", f.f);
    for (i = 0; i < (1 << 23U); i++) {
        f.i = 0x3f800000|i;
        g1.f = erff(f.f);
        g2.f = fft_erff(f.f);
        if ((diff = rel_err_diff(g1.f, g2.f)) >=  0x1.0p-24f) {
            nerrs++;
            if (diff > fabsf(maxdiff)) maxdiff = diff;
            if (!(i & 0xff))
                printf("Error: erff(%.7g): %.7g != fft_erff(%.7g): %.7g (diff: %.7e / 0x%08x)\n", f.f, g1.f, f.f, g2.f, diff, (g1.i ^ g2.i));
        }
    }
    printf("end: %.7f\n", f.f);
    f.i = 0x40000000;
    printf("start: %.7f\n", f.f);
    for (i = 0; i < (1 << 23U); i++) {
        f.i = 0x40000000|i;
        g1.f = erff(f.f);
        g2.f = fft_erff(f.f);
        if ((diff = rel_err_diff(g1.f, g2.f)) >=  0x1.0p-24f) {
            nerrs++;
            if (diff > fabsf(maxdiff)) maxdiff = diff;
            if (!(i & 0xff))
                printf("Error: erff(%.7g): %.7g != fft_erff(%.7g): %.7g (diff: %.7e / 0x%08x)\n", f.f, g1.f, f.f, g2.f, diff, (g1.i ^ g2.i));
        }
    }
    printf("end: %.7f\n", f.f);
    f.i = 0x40800000;
    printf("start: %.7f\n", f.f);
    for (i = 0; i < (1 << 23U); i++) {
        f.i = 0x40800000|i;
        g1.f = erff(f.f);
        g2.f = fft_erff(f.f);
        if ((diff = rel_err_diff(g1.f, g2.f)) >=  0x1.0p-24f) {
            nerrs++;
            if (diff > fabsf(maxdiff)) maxdiff = diff;
            if (!(i & 0xff))
                printf("Error: erff(%.7g): %.7g != fft_erff(%.7g): %.7g (diff: %.7e / 0x%08x)\n", f.f, g1.f, f.f, g2.f, diff, (g1.i ^ g2.i));
        }
    }
    printf("end: %.7f\n", f.f);
    printf("Total errors, erff: %u, largest error: %.7e\n", nerrs, maxdiff); nerrs = 0;

    return 0;
}
#endif
