-1

How do I output the probability density of a gamma distribution at a specific value x? (also the cdf, if possible!) Thanks!

rnt88
  • 11
  • Are you trying to hardcode the implementation of the gamma distribution or use a library add-on? I guarantee the boost library already has this implemented and optimized for you if you're willing to put in the work to figure out how to use it. https://www.boost.org/doc/libs/1_46_1/libs/math/doc/sf_and_dist/html/math_toolkit/dist/dist_ref/dists/gamma_dist.html – CodeoftheWarrior Mar 28 '19 at 18:42
  • Did you try anything? – Valentino Mar 28 '19 at 19:24
  • 1
    @CodeoftheWarrior Since C++ 11 the standard headers already have these functions. https://en.cppreference.com/w/cpp/numeric/math/tgamma – Max Langhof Mar 28 '19 at 20:50
  • @MaxLanghof Thank you for that. That is the gamma function not the gamma distribution, but it pointed me in the right direction. OP, look in the header file for the pdf of the gamma distribution. http://www.cplusplus.com/reference/random/gamma_distribution/ *Correction* this generates a value based on the distribution not the actual probability. – CodeoftheWarrior Mar 28 '19 at 21:21

1 Answers1

0
double gammapdf(double value, double alpha, double beta) {
return (std::pow(beta, alpha)*std::pow(value, (alpha-1))*std::pow(M_E, (-1*beta*value)))/tgamma(alpha);}

This implements the gamma distribution pdf calculation as listed on wikipedia. Did a little digging. The cdf is a bit more difficult and I'm not sure how to solve that one.

CodeoftheWarrior
  • 311
  • 2
  • 12
  • Thanks very much for this! That's great! I have implemented it and it seems to work ok. I can also numerically integrate it for the cdf which is a good workaround... However, your suggestion of using a boost library also sounds good. I'm inexperienced at this - do I simply add a #include at the top pointing at the boost library (which I should download as a file)? Thank you!! – rnt88 Mar 29 '19 at 10:47
  • https://www.boost.org/doc/libs/1_62_0/more/getting_started/windows.html Unfortunately, no. Boost is an add-on library and you are going to need to find some way to compile the libraries and then link those libraries to the project that needs them. It will require some leg-work, but it's good experience. – CodeoftheWarrior Mar 29 '19 at 15:37
  • I would be curious if this calculation is also ok from a numerical perspective. There are many algorithms (e.g. gauss elimination) where a straightforward replication of the mathematical operations can introduce massive floating point errors. But I have no idea if that is relevant in this particular case. – Max Langhof Mar 29 '19 at 22:17