fun regularizedGammaP()

in plot-base/src/commonMain/kotlin/org/jetbrains/letsPlot/core/plot/base/stat/math3/Gamma.kt [140:182]


    fun regularizedGammaP(
        a: Double,
        x: Double,
        epsilon: Double = DEFAULT_EPSILON,
        maxIterations: Int = Int.MAX_VALUE
    ): Double {
        val ret: Double

        if (a.isNaN() || x.isNaN() || a <= 0.0 || x < 0.0) {
            ret = Double.NaN
        } else if (x == 0.0) {
            ret = 0.0
        } else if (x >= a + 1) {
            // use regularizedGammaQ because it should converge faster in this
            // case.
            ret = 1.0 - regularizedGammaQ(a, x, epsilon, maxIterations)
        } else {
            // calculate series
            var n = 0.0 // current element index
            var an = 1.0 / a // n-th element in the series
            var sum = an // partial sum
            while (abs(an / sum) > epsilon &&
                n < maxIterations &&
                sum < Double.POSITIVE_INFINITY
            ) {
                // compute next element in the series
                n = n + 1.0
                an = an * (x / (a + n))

                // update partial sum
                sum = sum + an
            }
            if (n >= maxIterations) {
                error("MaxCountExceeded - maxIterations: $maxIterations")
            } else if (sum.isInfinite()) {
                ret = 1.0
            } else {
                ret = exp(-x + a * ln(x) - logGamma(a)) * sum
            }
        }

        return ret
    }