Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incomplete beta function in raw C

A friend of mine needs an analogue of MatLAB's betainc function for some statistical calculations in programmable logic devices (PLD's) (I'm not a man of hardware and don't know any details on his project yet).

Therefore using precompiled libraries is not an option. She needs an implementation in raw C considering that each of the three parameters is variable.

Is there a good one somewhere on the Web?

Thank you so much in advance!

like image 242
wh1t3cat1k Avatar asked Jul 21 '26 01:07

wh1t3cat1k


1 Answers

I know I'm late to answering, but your currently accepted answer (using code from "Numerical Recipes") has a terrible license. Also, it doesn't help others that don't already own the book.

Here is raw C99 code for the incomplete beta function released under the Zlib license:

#include <math.h>

#define STOP 1.0e-8
#define TINY 1.0e-30

double incbeta(double a, double b, double x) {
    if (x < 0.0 || x > 1.0) return 1.0/0.0;

    /*The continued fraction converges nicely for x < (a+1)/(a+b+2)*/
    if (x > (a+1.0)/(a+b+2.0)) {
        return (1.0-incbeta(b,a,1.0-x)); /*Use the fact that beta is symmetrical.*/
    }

    /*Find the first part before the continued fraction.*/
    const double lbeta_ab = lgamma(a)+lgamma(b)-lgamma(a+b);
    const double front = exp(log(x)*a+log(1.0-x)*b-lbeta_ab) / a;

    /*Use Lentz's algorithm to evaluate the continued fraction.*/
    double f = 1.0, c = 1.0, d = 0.0;

    int i, m;
    for (i = 0; i <= 200; ++i) {
        m = i/2;

        double numerator;
        if (i == 0) {
            numerator = 1.0; /*First numerator is 1.0.*/
        } else if (i % 2 == 0) {
            numerator = (m*(b-m)*x)/((a+2.0*m-1.0)*(a+2.0*m)); /*Even term.*/
        } else {
            numerator = -((a+m)*(a+b+m)*x)/((a+2.0*m)*(a+2.0*m+1)); /*Odd term.*/
        }

        /*Do an iteration of Lentz's algorithm.*/
        d = 1.0 + numerator * d;
        if (fabs(d) < TINY) d = TINY;
        d = 1.0 / d;

        c = 1.0 + numerator / c;
        if (fabs(c) < TINY) c = TINY;

        const double cd = c*d;
        f *= cd;

        /*Check for stop.*/
        if (fabs(1.0-cd) < STOP) {
            return front * (f-1.0);
        }
    }

    return 1.0/0.0; /*Needed more loops, did not converge.*/
}

It is taken from this Github repo. There is also a very thorough write-up about how it works here.

Hope you find this helpful.

like image 169
icanhelp Avatar answered Jul 23 '26 16:07

icanhelp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!