001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.numbers.gamma;
018
019/**
020 * <a href="http://mathworld.wolfram.com/Erfc.html">Complementary error function</a>.
021 */
022public final class Erfc {
023    /** The threshold value for returning the extreme value. */
024    private static final double EXTREME_VALUE_BOUND = 40;
025
026    /** Private constructor. */
027    private Erfc() {
028        // intentionally empty.
029    }
030
031    /**
032     * <p>
033     * This implementation computes erfc(x) using the
034     * {@link RegularizedGamma.Q#value(double, double, double, int) regularized gamma function},
035     * following <a href="http://mathworld.wolfram.com/Erf.html">Erf</a>, equation (3).
036     * </p>
037     *
038     * <p>
039     * The value returned is always between 0 and 2 (inclusive).
040     * If {@code abs(x) > 40}, then {@code erf(x)} is indistinguishable from
041     * either 0 or 2 at {@code double} precision, so the appropriate extreme
042     * value is returned.
043     * </p>
044     *
045     * @param x Value.
046     * @return the complementary error function.
047     * @throws ArithmeticException if the algorithm fails to converge.
048     *
049     * @see RegularizedGamma.Q#value(double, double, double, int)
050     */
051    public static double value(double x) {
052        if (Math.abs(x) > EXTREME_VALUE_BOUND) {
053            return x > 0 ? 0 : 2;
054        }
055        final double ret = RegularizedGamma.Q.value(0.5, x * x, 1e-15, 10000);
056        return x < 0 ?
057            2 - ret :
058            ret;
059    }
060}
061