Erf.java

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * This is not the original file distributed by the Apache Software Foundation
 * It has been modified by the Hipparchus project
 */
package org.hipparchus.special;

import org.hipparchus.CalculusFieldElement;
import org.hipparchus.Field;
import org.hipparchus.util.FastMath;

/**
 * This is a utility class that provides computation methods related to the
 * error functions.
 *
 */
public class Erf {

    /**
     * The number {@code X_CRIT} is used by {@link #erf(double, double)} internally.
     * This number solves {@code erf(x)=0.5} within 1ulp.
     * More precisely, the current implementations of
     * {@link #erf(double)} and {@link #erfc(double)} satisfy:<br>
     * {@code erf(X_CRIT) < 0.5},<br>
     * {@code erf(Math.nextUp(X_CRIT) > 0.5},<br>
     * {@code erfc(X_CRIT) = 0.5}, and<br>
     * {@code erfc(Math.nextUp(X_CRIT) < 0.5}
     */
    private static final double X_CRIT = 0.4769362762044697;

    /**
     * Default constructor.  Prohibit instantiation.
     */
    private Erf() {}

    /**
     * Returns the error function.
     *
     * \[
     * \mathrm{erf}(x) = \frac{2}{\sqrt{\pi}} \int_{t=0}^x e^{-t^2}dt
     * \]
     *
     * <p>This implementation computes erf(x) using the
     * {@link Gamma#regularizedGammaP(double, double, double, int) regularized gamma function},
     * following <a href="http://mathworld.wolfram.com/Erf.html"> Erf</a>, equation (3)</p>
     *
     * <p>The value returned is always between -1 and 1 (inclusive).
     * If {@code abs(x) > 40}, then {@code erf(x)} is indistinguishable from
     * either 1 or -1 as a double, so the appropriate extreme value is returned.
     * </p>
     *
     * @param x the value.
     * @return the error function erf(x)
     * @throws org.hipparchus.exception.MathIllegalStateException
     * if the algorithm fails to converge.
     * @see Gamma#regularizedGammaP(double, double, double, int)
     */
    public static double erf(double x) {
        if (FastMath.abs(x) > 40) {
            return x > 0 ? 1 : -1;
        }
        final double ret = Gamma.regularizedGammaP(0.5, x * x, 1.0e-15, 10000);
        return x < 0 ? -ret : ret;
    }

    /**
     * Returns the error function.
     *
     * \[
     * \mathrm{erf}(x) = \frac{2}{\sqrt{\pi}} \int_{t=0}^x e^{-t^2}dt
     * \]
     *
     * <p>This implementation computes erf(x) using the
     * {@link Gamma#regularizedGammaP(double, double, double, int) regularized gamma function},
     * following <a href="http://mathworld.wolfram.com/Erf.html"> Erf</a>, equation (3)</p>
     *
     * <p>The value returned is always between -1 and 1 (inclusive).
     * If {@code abs(x) > 40}, then {@code erf(x)} is indistinguishable from
     * either 1 or -1 as a double, so the appropriate extreme value is returned.
     * </p>
     *
     * @param <T> type of the field elements
     * @param x the value.
     * @return the error function erf(x)
     * @throws org.hipparchus.exception.MathIllegalStateException
     * if the algorithm fails to converge.
     * @see Gamma#regularizedGammaP(double, double, double, int)
     */
    public static <T extends CalculusFieldElement<T>> T erf(T x) {
        final Field<T> field = x.getField();
        final T one = field.getOne();

        if (FastMath.abs(x.getReal()) > 40) {
            return x.getReal() > 0 ? one : one.negate();
        }
        final T ret = Gamma.regularizedGammaP(one.newInstance(0.5), x.square(), 1.0e-15, 10000);
        return x.getReal() < 0 ? ret.negate() : ret;
    }


    /**
     * Returns the complementary error function.
     *
     * \[
     * \mathrm{erfc}(x) =  \frac{2}{\sqrt{\pi}} \int_{t=x}^\infty e^{-t^2}dt = 1 - \mathrm{erf}
     *
     * <p>This implementation computes erfc(x) using the
     * {@link Gamma#regularizedGammaQ(double, double, double, int) regularized gamma function},
     * following <a href="http://mathworld.wolfram.com/Erf.html"> Erf</a>, equation (3).</p>
     *
     * <p>The value returned is always between 0 and 2 (inclusive).
     * If {@code abs(x) > 40}, then {@code erf(x)} is indistinguishable from
     * either 0 or 2 as a double, so the appropriate extreme value is returned.
     * </p>
     *
     * @param x the value
     * @return the complementary error function erfc(x)
     * @throws org.hipparchus.exception.MathIllegalStateException
     * if the algorithm fails to converge.
     * @see Gamma#regularizedGammaQ(double, double, double, int)
     */
    public static double erfc(double x) {
        if (FastMath.abs(x) > 40) {
            return x > 0 ? 0 : 2;
        }
        final double ret = Gamma.regularizedGammaQ(0.5, x * x, 1.0e-15, 10000);
        return x < 0 ? 2 - ret : ret;
    }

    /**
     * Returns the complementary error function.
     *
     * \[
     * erfc(x) = \frac{2}{\sqrt{\pi}} \int_x^\infty e^{-t^2}dt = 1 - erf(x)
     * \]
     *
     * <p>This implementation computes erfc(x) using the
     * {@link Gamma#regularizedGammaQ(double, double, double, int) regularized gamma function}, following <a
     * href="http://mathworld.wolfram.com/Erf.html"> Erf</a>, equation (3).</p>
     *
     * <p>The value returned is always between 0 and 2 (inclusive).
     * If {@code abs(x) > 40}, then {@code erf(x)} is indistinguishable from either 0 or 2 as a double, so the
     * appropriate extreme value is returned. <b>This implies that the current implementation does not allow the use of
     * {@link org.hipparchus.dfp.Dfp Dfp} with extended precision.</b>
     * </p>
     *
     * @param x the value
     * @param <T> type of the field elements
     *
     * @return the complementary error function erfc(x)
     *
     * @throws org.hipparchus.exception.MathIllegalStateException if the algorithm fails to converge.
     * @see Gamma#regularizedGammaQ(double, double, double, int)
     */
    public static <T extends CalculusFieldElement<T>> T erfc(T x) {
        final Field<T> field = x.getField();
        final T        zero  = field.getZero();
        final T        one   = field.getOne();

        if (FastMath.abs(x.getReal()) > 40) {
            return x.getReal() > 0 ? zero : one.newInstance(2.);
        }
        final T ret = Gamma.regularizedGammaQ(one.newInstance(0.5), x.square(), 1.0e-15, 10000);
        return x.getReal() < 0 ? ret.negate().add(2.) : ret;
    }

    /**
     * Returns the difference between erf(x1) and erf(x2).
     * <p>
     * The implementation uses either erf(double) or erfc(double)
     * depending on which provides the most precise result.
     *
     * @param x1 the first value
     * @param x2 the second value
     * @return erf(x2) - erf(x1)
     */
    public static double erf(double x1, double x2) {
        if(x1 > x2) {
            return -erf(x2, x1);
        }

        return
        x1 < -X_CRIT ?
            x2 < 0.0 ?
                erfc(-x2) - erfc(-x1) :
                erf(x2) - erf(x1) :
            x2 > X_CRIT && x1 > 0.0 ?
                erfc(x1) - erfc(x2) :
                erf(x2) - erf(x1);
    }

    /**
     * Returns the difference between erf(x1) and erf(x2).
     * <p>
     * The implementation uses either erf(double) or erfc(double)
     * depending on which provides the most precise result.
     *
     * @param x1 the first value
     * @param x2 the second value
     * @param <T> type of the field elements
     *
     * @return erf(x2) - erf(x1)
     */
    public static <T extends CalculusFieldElement<T>> T erf(T x1, T x2) {

        if (x1.getReal() > x2.getReal()) {
            return erf(x2, x1).negate();
        }

        return
                x1.getReal() < -X_CRIT ?
                        x2.getReal() < 0.0 ?
                                erfc(x2.negate()).subtract(erfc(x1.negate())) :
                                erf(x2).subtract(erf(x1)) :
                        x2.getReal() > X_CRIT && x1.getReal() > 0.0 ?
                                erfc(x1).subtract(erfc(x2)) :
                                erf(x2).subtract(erf(x1));
    }

    /**
     * Returns the inverse erf.
     * <p>
     * This implementation is described in the paper:
     * <a href="http://people.maths.ox.ac.uk/gilesm/files/gems_erfinv.pdf">Approximating
     * the erfinv function</a> by Mike Giles, Oxford-Man Institute of Quantitative Finance,
     * which was published in GPU Computing Gems, volume 2, 2010.
     * The source code is available <a href="http://gpucomputing.net/?q=node/1828">here</a>.
     * </p>
     * @param x the value
     * @return t such that x = erf(t)
     */
    public static double erfInv(final double x) {

        // beware that the logarithm argument must be
        // computed as (1.0 - x) * (1.0 + x),
        // it must NOT be simplified as 1.0 - x * x as this
        // would induce rounding errors near the boundaries +/-1
        double w = - FastMath.log((1.0 - x) * (1.0 + x));
        double p;

        if (w < 6.25) {
            w -= 3.125;
            p =  -3.6444120640178196996e-21;
            p =   -1.685059138182016589e-19 + p * w;
            p =   1.2858480715256400167e-18 + p * w;
            p =    1.115787767802518096e-17 + p * w;
            p =   -1.333171662854620906e-16 + p * w;
            p =   2.0972767875968561637e-17 + p * w;
            p =   6.6376381343583238325e-15 + p * w;
            p =  -4.0545662729752068639e-14 + p * w;
            p =  -8.1519341976054721522e-14 + p * w;
            p =   2.6335093153082322977e-12 + p * w;
            p =  -1.2975133253453532498e-11 + p * w;
            p =  -5.4154120542946279317e-11 + p * w;
            p =    1.051212273321532285e-09 + p * w;
            p =  -4.1126339803469836976e-09 + p * w;
            p =  -2.9070369957882005086e-08 + p * w;
            p =   4.2347877827932403518e-07 + p * w;
            p =  -1.3654692000834678645e-06 + p * w;
            p =  -1.3882523362786468719e-05 + p * w;
            p =    0.0001867342080340571352 + p * w;
            p =  -0.00074070253416626697512 + p * w;
            p =   -0.0060336708714301490533 + p * w;
            p =      0.24015818242558961693 + p * w;
            p =       1.6536545626831027356 + p * w;
        } else if (w < 16.0) {
            w = FastMath.sqrt(w) - 3.25;
            p =   2.2137376921775787049e-09;
            p =   9.0756561938885390979e-08 + p * w;
            p =  -2.7517406297064545428e-07 + p * w;
            p =   1.8239629214389227755e-08 + p * w;
            p =   1.5027403968909827627e-06 + p * w;
            p =   -4.013867526981545969e-06 + p * w;
            p =   2.9234449089955446044e-06 + p * w;
            p =   1.2475304481671778723e-05 + p * w;
            p =  -4.7318229009055733981e-05 + p * w;
            p =   6.8284851459573175448e-05 + p * w;
            p =   2.4031110387097893999e-05 + p * w;
            p =   -0.0003550375203628474796 + p * w;
            p =   0.00095328937973738049703 + p * w;
            p =   -0.0016882755560235047313 + p * w;
            p =    0.0024914420961078508066 + p * w;
            p =   -0.0037512085075692412107 + p * w;
            p =     0.005370914553590063617 + p * w;
            p =       1.0052589676941592334 + p * w;
            p =       3.0838856104922207635 + p * w;
        } else if (!Double.isInfinite(w)) {
            w = FastMath.sqrt(w) - 5.0;
            p =  -2.7109920616438573243e-11;
            p =  -2.5556418169965252055e-10 + p * w;
            p =   1.5076572693500548083e-09 + p * w;
            p =  -3.7894654401267369937e-09 + p * w;
            p =   7.6157012080783393804e-09 + p * w;
            p =  -1.4960026627149240478e-08 + p * w;
            p =   2.9147953450901080826e-08 + p * w;
            p =  -6.7711997758452339498e-08 + p * w;
            p =   2.2900482228026654717e-07 + p * w;
            p =  -9.9298272942317002539e-07 + p * w;
            p =   4.5260625972231537039e-06 + p * w;
            p =  -1.9681778105531670567e-05 + p * w;
            p =   7.5995277030017761139e-05 + p * w;
            p =  -0.00021503011930044477347 + p * w;
            p =  -0.00013871931833623122026 + p * w;
            p =       1.0103004648645343977 + p * w;
            p =       4.8499064014085844221 + p * w;
        } else {
            // this branch does not appears in the original code, it
            // was added because the previous branch does not handle
            // x = +/-1 correctly. In this case, w is positive infinity
            // and as the first coefficient (-2.71e-11) is negative.
            // Once the first multiplication is done, p becomes negative
            // infinity and remains so throughout the polynomial evaluation.
            // So the branch above incorrectly returns negative infinity
            // instead of the correct positive infinity.
            p = Double.POSITIVE_INFINITY;
        }

        return p * x;

    }

    /**
     * Returns the inverse erf.
     * <p>
     * This implementation is described in the paper:
     * <a href="http://people.maths.ox.ac.uk/gilesm/files/gems_erfinv.pdf">Approximating
     * the erfinv function</a> by Mike Giles, Oxford-Man Institute of Quantitative Finance,
     * which was published in GPU Computing Gems, volume 2, 2010.
     * The source code is available <a href="http://gpucomputing.net/?q=node/1828">here</a>.
     * </p>
     * @param <T> type of the filed elements
     * @param x the value
     * @return t such that x = erf(t)
     */
    public static <T extends CalculusFieldElement<T>> T erfInv(final T x) {
        final T one = x.getField().getOne();

        // beware that the logarithm argument must be
        // computed as (1.0 - x) * (1.0 + x),
        // it must NOT be simplified as 1.0 - x * x as this
        // would induce rounding errors near the boundaries +/-1
        T w = one.subtract(x).multiply(one.add(x)).log().negate();
        T p;

        if (w.getReal() < 6.25) {
            w = w.subtract(3.125);
            p = one.newInstance(-3.6444120640178196996e-21);
            p = p.multiply(w).add(-1.685059138182016589e-19);
            p = p.multiply(w).add(1.2858480715256400167e-18);
            p = p.multiply(w).add(1.115787767802518096e-17);
            p = p.multiply(w).add(-1.333171662854620906e-16);
            p = p.multiply(w).add(2.0972767875968561637e-17);
            p = p.multiply(w).add(6.6376381343583238325e-15);
            p = p.multiply(w).add(-4.0545662729752068639e-14);
            p = p.multiply(w).add(-8.1519341976054721522e-14);
            p = p.multiply(w).add(2.6335093153082322977e-12);
            p = p.multiply(w).add(-1.2975133253453532498e-11);
            p = p.multiply(w).add(-5.4154120542946279317e-11);
            p = p.multiply(w).add(1.051212273321532285e-09);
            p = p.multiply(w).add(-4.1126339803469836976e-09);
            p = p.multiply(w).add(-2.9070369957882005086e-08);
            p = p.multiply(w).add(4.2347877827932403518e-07);
            p = p.multiply(w).add(-1.3654692000834678645e-06);
            p = p.multiply(w).add(-1.3882523362786468719e-05);
            p = p.multiply(w).add(0.0001867342080340571352);
            p = p.multiply(w).add(-0.00074070253416626697512);
            p = p.multiply(w).add(-0.0060336708714301490533);
            p = p.multiply(w).add(0.24015818242558961693);
            p = p.multiply(w).add(1.6536545626831027356);
        }
        else if (w.getReal() < 16.0) {
            w = w.sqrt().subtract(3.25);
            p = one.newInstance(2.2137376921775787049e-09);
            p = p.multiply(w).add(9.0756561938885390979e-08);
            p = p.multiply(w).add(-2.7517406297064545428e-07);
            p = p.multiply(w).add(1.8239629214389227755e-08);
            p = p.multiply(w).add(1.5027403968909827627e-06);
            p = p.multiply(w).add(-4.013867526981545969e-06);
            p = p.multiply(w).add(2.9234449089955446044e-06);
            p = p.multiply(w).add(1.2475304481671778723e-05);
            p = p.multiply(w).add(-4.7318229009055733981e-05);
            p = p.multiply(w).add(6.8284851459573175448e-05);
            p = p.multiply(w).add(2.4031110387097893999e-05);
            p = p.multiply(w).add(-0.0003550375203628474796);
            p = p.multiply(w).add(0.00095328937973738049703);
            p = p.multiply(w).add(-0.0016882755560235047313);
            p = p.multiply(w).add(0.0024914420961078508066);
            p = p.multiply(w).add(-0.0037512085075692412107);
            p = p.multiply(w).add(0.005370914553590063617);
            p = p.multiply(w).add(1.0052589676941592334);
            p = p.multiply(w).add(3.0838856104922207635);
        }
        else if (!w.isInfinite()) {
            w = w.sqrt().subtract(5.0);
            p = one.newInstance(-2.7109920616438573243e-11);
            p = p.multiply(w).add(-2.5556418169965252055e-10);
            p = p.multiply(w).add(1.5076572693500548083e-09);
            p = p.multiply(w).add(-3.7894654401267369937e-09);
            p = p.multiply(w).add(7.6157012080783393804e-09);
            p = p.multiply(w).add(-1.4960026627149240478e-08);
            p = p.multiply(w).add(2.9147953450901080826e-08);
            p = p.multiply(w).add(-6.7711997758452339498e-08);
            p = p.multiply(w).add(2.2900482228026654717e-07);
            p = p.multiply(w).add(-9.9298272942317002539e-07);
            p = p.multiply(w).add(4.5260625972231537039e-06);
            p = p.multiply(w).add(-1.9681778105531670567e-05);
            p = p.multiply(w).add(7.5995277030017761139e-05);
            p = p.multiply(w).add(-0.00021503011930044477347);
            p = p.multiply(w).add(-0.00013871931833623122026);
            p = p.multiply(w).add(1.0103004648645343977);
            p = p.multiply(w).add(4.8499064014085844221);
        }
        else {
            // this branch does not appear in the original code, it
            // was added because the previous branch does not handle
            // x = +/-1 correctly. In this case, w is positive infinity
            // and as the first coefficient (-2.71e-11) is negative.
            // Once the first multiplication is done, p becomes negative
            // infinity and remains so throughout the polynomial evaluation.
            // So the branch above incorrectly returns negative infinity
            // instead of the correct positive infinity.
            p = one.multiply(Double.POSITIVE_INFINITY);
        }

        return p.multiply(x);

    }

    /**
     * Returns the inverse erfc.
     * @param x the value
     * @return t such that x = erfc(t)
     */
    public static double erfcInv(final double x) {
        return erfInv(1 - x);
    }

    /**
     * Returns the inverse erfc.
     * @param x the value
     * @param <T> type of the field elements
     * @return t such that x = erfc(t)
     */
    public static <T extends CalculusFieldElement<T>> T erfcInv(final T x) {
        return erfInv(x.negate().add(1));
    }

}